From bf6e0eaf27d878b22605fd6301cb2901876bafb4 Mon Sep 17 00:00:00 2001 From: David Machaj <46852402+dmachaj@users.noreply.github.com.> Date: Mon, 9 Dec 2024 11:34:45 -0800 Subject: [PATCH 1/9] Squash infrastructure changes before reformatting from scratch again --- .clang-format | 163 +++++++++++++++++++++++++++++++++++++++ .github/workflows/ci.yml | 45 +++++++++++ README.md | 16 ++++ build_test_all.cmd | 26 +++++++ find_clang_format.cmd | 14 ++++ strings/base_extern.h | 4 + 6 files changed, 268 insertions(+) create mode 100644 .clang-format create mode 100644 find_clang_format.cmd diff --git a/.clang-format b/.clang-format new file mode 100644 index 000000000..a9fe09c96 --- /dev/null +++ b/.clang-format @@ -0,0 +1,163 @@ +--- +Language: Cpp +BasedOnStyle: Microsoft + +AccessModifierOffset: -4 +AlignAfterOpenBracket: AlwaysBreak +AlignConsecutiveAssignments: false +AlignEscapedNewlines: DontAlign +AlignOperands: true +AlignTrailingComments: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowShortBlocksOnASingleLine: false +AllowShortLambdasOnASingleLine: Inline +AlwaysBreakBeforeMultilineStrings: true +AlwaysBreakTemplateDeclarations: MultiLine +BinPackArguments: false +BinPackParameters: false +BraceWrapping: + AfterCaseLabel: true + AfterUnion: true + BeforeLambdaBody: true + SplitEmptyFunction: false + SplitEmptyRecord: false + SplitEmptyNamespace: false +BreakBeforeBinaryOperators: None +BreakBeforeTernaryOperators: true +BreakConstructorInitializers: AfterColon +BreakStringLiterals: false +CommentPragmas: '^ IWYU pragma:' +CompactNamespaces: true +ConstructorInitializerAllOnOneLineOrOnePerLine: true +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: false +DerivePointerAlignment: false +DisableFormat: false +FixNamespaceComments: true +ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ] +IncludeBlocks: Regroup +IndentCaseLabels: false +IncludeCategories: + - Regex: '^"(stdafx.h|pch.h|precomp.h)"$' + Priority: -1 +IndentWrappedFunctionNames: false +KeepEmptyLinesAtTheStartOfBlocks: true +MacroBlockBegin: '^BEGIN_COM_MAP$|^BEGIN_CONNECTION_POINT_MAP$|^BEGIN_HELPER_NODEMAP$|^BEGIN_MODULE$|^BEGIN_MSG_MAP$|^BEGIN_OBJECT_MAP$|^BEGIN_TEST_CLASS$|^BEGIN_TEST_METHOD$|^BEGIN_TEST_METHOD_PROPERTIES$' +MacroBlockEnd: '^END_COM_MAP$|^END_CONNECTION_POINT_MAP$|^END_HELPER_NODEMAP$|^END_MODULE$|^END_MSG_MAP$|^END_OBJECT_MAP$|^END_TEST_CLASS$|^END_TEST_METHOD$|^END_TEST_METHOD_PROPERTIES$' +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: All +ObjCBlockIndentWidth: 2 +ObjCSpaceAfterProperty: false +ObjCSpaceBeforeProtocolList: true +PackConstructorInitializers: NextLineOnly +PenaltyBreakBeforeFirstCallParameter: 19 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakString: 2000 +PenaltyExcessCharacter: 2 +PointerAlignment: Left +SortIncludes: false +SpaceAfterCStyleCast: false +SpaceBeforeAssignmentOperators: true +SpaceBeforeParens: ControlStatements +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 1 +SpacesInAngles: Never +SpacesInContainerLiterals: true +SpacesInCStyleCastParentheses: false +SpacesInParentheses: false +SpacesInSquareBrackets: false +Standard: Latest + +AttributeMacros: [ + CALLBACK, +] + +StatementMacros: [ + _Acquires_exclusive_lock_, + _Acquires_lock_, + _Acquires_nonreentrant_lock_, + _Acquires_shared_lock_, + _Analysis_assume_smart_lock_acquired_, + _Analysis_assume_smart_lock_released_, + _Create_lock_level_, + _Detaches_lock_, + _Function_class_, + _Global_cancel_spin_lock_, + _Global_critical_region_, + _Global_interlock_, + _Global_priority_region_, + _Has_lock_kind_, + _Has_lock_level_, + _IRQL_always_function_max_, + _IRQL_always_function_min_, + _IRQL_raises_, + _IRQL_requires_, + _IRQL_requires_max_, + _IRQL_requires_min_, + _IRQL_requires_same_, + _IRQL_restores_, + _IRQL_restores_global_, + _IRQL_saves_, + _IRQL_saves_global_, + _Lock_level_order_, + _Moves_lock_, + _Must_inspect_result_, + _No_competing_thread_, + _Post_same_lock_, + _Post_writable_byte_size_, + _Pre_satisfies_, + _Releases_exclusive_lock_, + _Releases_lock_, + _Releases_nonreentrant_lock_, + _Releases_shared_lock_, + _Replaces_lock_, + _Requires_exclusive_lock_held_, + _Requires_lock_held_, + _Requires_lock_not_held_, + _Requires_no_locks_held_, + _Requires_shared_lock_held_, + _Ret_maybenull_, + _Ret_range_, + _Struct_size_bytes_, + _Success_, + _Swaps_locks_, + _Use_decl_annotations_, + _When_, + + DECLARE_ORDINAL_MAP, + DECLARE_PROCNAME_MAP, + DEFINE_ORDINAL_ENTRIES, + DEFINE_ORDINAL_ENTRIES_ALTNAME, + DEFINE_ORDINAL_ENTRIES_APISET, + DEFINE_ORDINAL_MAP, + DEFINE_PROCNAME_ENTRIES, + DEFINE_PROCNAME_ENTRIES_ALTNAME, + DEFINE_PROCNAME_ENTRIES_APISET, + DEFINE_PROCNAME_MAP, + DLOENTRY, + DLOENTRY_APISET, + DLPENTRY, + DLPENTRY_APISET, + + RpcEndExcept, + + ActivatableClass, + ActivatableClassWithFactory, + ActivatableClassWithFactoryEx, + ActivatableStaticOnlyFactory, + ActivatableStaticOnlyFactoryEx, + CoCreatableClass, + CoCreatableClassWithFactory, + CoCreatableClassWithFactoryEx, + + TEST_CASE, + SECTION, +] + +TypenameMacros: [ + IFACEMETHOD, + STDMETHOD, + STDAPI_, +] diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7f99be8fb..d6117c61f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -7,6 +7,51 @@ on: - master jobs: + check-formatting: + name: 'Check Formatting of Changes' + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + with: + # Force a non-shallow checkout, so that clang-format can access source history to compare against + # See https://github.com/actions/checkout for more details. + fetch-depth: 0 + + - name: Find vcvars64.bat + run: | + $vcvars64 = & "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere" -latest -find VC\Auxiliary\Build\vcvars64.bat + if (!$vcvars64) { exit 1 } + Write-Host "Using vcvars64: ${vcvars64}" + Add-Content $env:GITHUB_ENV "vcvars64=$vcvars64" + + - name: Check Formatting + shell: cmd + run: | + call "%vcvars64%" + + call .\find_clang_format.cmd + if %ERRORLEVEL% neq 0 ( + exit /b %ERRORLEVEL% + ) + + git clang-format origin/master --binary "%CLANG_FORMAT%" --style file -- cppwinrt/*.h cppwinrt/*.cpp fast_fwd/*.h fast_fwd/*.cpp natvis/*.h natvis/*.cpp prebuild/*.h prebuild/*.cpp scratch/*.h scratch/*.cpp strings/*.h strings/*.cpp test/*.h test/*.cpp vsix/*.h vsix/*.cpp + + if %ERRORLEVEL% neq 0 ( + echo ::error::This branch contains changes that have not been formatted with 'clang-format', + echo NOTE: To resolve this issue, you can run 'clang-format' in the following ways: + echo * Run build_test_all.cmd which will run 'clang-format' on _all_ source files. This script is + echo simpler to run, however there's a chance it may touch additional files you never changed due to you having + echo a mis-matched version of 'clang-format'. This may require you to manually revert changes made by + echo 'clang-format' to the locations where you made no code changes. + echo. + echo For more information, please see https://github.com/microsoft/cppwinrt?tab=readme-ov-file#formatting + echo. + echo NOTE: As an additional note, given that different versions of 'clang-format' may have different behaviors, this + echo may be a false positive. If you believe that to be the case ^(e.g. none of the above resulted in modifications + echo to the code you have changed^), please note this in your PR. + exit /b 1 + ) + test-msvc-cppwinrt-build: name: '${{ matrix.compiler }}: Build (${{ matrix.arch }}, ${{ matrix.config }})' strategy: diff --git a/README.md b/README.md index 1749fea0c..f1ad34cd6 100644 --- a/README.md +++ b/README.md @@ -34,3 +34,19 @@ a dev command prompt at the root of the repo _after_ following the above build i * Run `build_prior_projection.cmd` in the dev command prompt as well * Run `prepare_versionless_diffs.cmd` which removes version stamps on both current and prior projection * Use a directory-level differencing tool to compare `_build\$(arch)\$(flavor)\winrt` and `_reference\$(arch)\$(flavor)\winrt` + +## Formatting + +This project has adopted `clang-format` as the tool for formatting our code. +Please note that the `.clang-format` at the root of the repo is a copy from the internal Windows repo with few additions. +In general, please do not modify it. +If you find that a macro is causing bad formatting of code, you can add that macro to one of the corresponding arrays in the `.clang-format` file (e.g. `AttributeMacros`, etc.), format the code, and submit a PR. + +> _NOTE: Different versions of `clang-format` may format the same code differently. +In an attempt to maintain consistency between changes, we've standardized on using the version of `clang-format` that ships with the latest version of Visual Studio. +If you have LLVM installed and added to your `PATH`, the version of `clang-format` that gets picked up by default may not be the one we expect. + +Before submitting a PR to the cppwinrt repo we ask that you first run `clang-format` on your changes. +There is a CI check in place that will fail the build for your PR if you have not run `clang-format`. +`clang-format` will run automatically as part of `build_test_all.cmd`, so if you use that script this +should happen automatically. diff --git a/build_test_all.cmd b/build_test_all.cmd index 4372acfd5..85f7570ab 100644 --- a/build_test_all.cmd +++ b/build_test_all.cmd @@ -1,4 +1,6 @@ @echo off +setlocal +setlocal EnableDelayedExpansion set target_platform=%1 set target_configuration=%2 @@ -9,6 +11,28 @@ if "%target_platform%"=="" set target_platform=x64 if "%target_configuration%"=="" set target_configuration=Release if "%target_version%"=="" set target_version=1.2.3.4 +:: Automatically run clang-format on all .cpp and .h files under the specified directories before building. +call "%~dp0/find_clang_format.cmd" +if %ERRORLEVEL% neq 0 exit /b %ERRORLEVEL% + +set DIRS=cppwinrt fast_fwd natvis prebuild scratch strings test vsix +set EXTS=.cpp .h +for %%d in (%DIRS%) do call :format_files %~dp0%%d +goto :post_format + +:format_files + for %%e in (%EXTS%) do ( + for /R %1 %%f in (*%%e) do call :run_clang_format "%%f" + ) + goto :eof + +:run_clang_format + "%CLANG_FORMAT%" -style=file -i %1 + goto :eof + +:post_format + +:: NuGet restore all solutions before building if not exist ".\.nuget" mkdir ".\.nuget" if not exist ".\.nuget\nuget.exe" powershell -Command "$ProgressPreference = 'SilentlyContinue' ; Invoke-WebRequest https://dist.nuget.org/win-x86-commandline/latest/nuget.exe -OutFile .\.nuget\nuget.exe" @@ -16,6 +40,7 @@ call .nuget\nuget.exe restore cppwinrt.sln" call .nuget\nuget.exe restore natvis\cppwinrtvisualizer.sln call .nuget\nuget.exe restore test\nuget\NugetTest.sln +:: Build all solutions in order call msbuild /m /p:Configuration=%target_configuration%,Platform=%target_platform%,CppWinRTBuildVersion=%target_version% cppwinrt.sln /t:fast_fwd call msbuild /p:Configuration=%target_configuration%,Platform=%target_platform%,Deployment=Component;CppWinRTBuildVersion=%target_version% natvis\cppwinrtvisualizer.sln @@ -37,4 +62,5 @@ call msbuild /m /p:Configuration=%target_configuration%,Platform=%target_platfor call msbuild /m /p:Configuration=%target_configuration%,Platform=%target_platform%,CppWinRTBuildVersion=%target_version% cppwinrt.sln /t:test\test_module_lock_none call msbuild /m /p:Configuration=%target_configuration%,Platform=%target_platform%,CppWinRTBuildVersion=%target_version% cppwinrt.sln /t:test\old_tests\test_old +:: Run tests after building call run_tests.cmd %target_platform% %target_configuration% diff --git a/find_clang_format.cmd b/find_clang_format.cmd new file mode 100644 index 000000000..4529f0012 --- /dev/null +++ b/find_clang_format.cmd @@ -0,0 +1,14 @@ +@echo off +:: NOTE: No 'setlocal' since we're "returning" the definition of "CLANG_FORMAT" to the caller + +:: Clang format's behavior has changed over time, meaning that different machines with different versions of LLVM +:: installed may get different formatting behavior. In an attempt to ensure consistency, we use the clang-format.exe +:: that ships with Visual Studio. There may still be issues if two different machines have different versions of Visual +:: Studio installed, however this will hopefully improve things +set CLANG_FORMAT=%VCINSTALLDIR%\Tools\Llvm\bin\clang-format.exe +if not exist "%CLANG_FORMAT%" ( + set CLANG_FORMAT= + echo ERROR: clang-format.exe not found at %%VCINSTALLDIR%%\Tools\Llvm\bin\clang-format.exe + echo ERROR: Ensure that this script is being run from a Visual Studio command prompt + exit /B 1 +) diff --git a/strings/base_extern.h b/strings/base_extern.h index 2412f9f2c..88f822bef 100644 --- a/strings/base_extern.h +++ b/strings/base_extern.h @@ -1,4 +1,6 @@ +// clang-format off + __declspec(selectany) int32_t(__stdcall* winrt_to_hresult_handler)(void* address) noexcept {}; __declspec(selectany) winrt::hstring(__stdcall* winrt_to_message_handler)(void* address) {}; __declspec(selectany) void(__stdcall* winrt_throw_hresult_handler)(uint32_t lineNumber, char const* fileName, char const* functionName, void* returnAddress, winrt::hresult const result) noexcept {}; @@ -109,3 +111,5 @@ extern "C" } #undef WINRT_IMPL_LINK + +// clang-format on \ No newline at end of file From 0fb6876413af21c12f14ed45c7d2d922feecd6a6 Mon Sep 17 00:00:00 2001 From: David Machaj <46852402+dmachaj@users.noreply.github.com.> Date: Mon, 9 Dec 2024 12:06:30 -0800 Subject: [PATCH 2/9] Fix bug where build_test_all was wasting time formatting generated headers --- build_test_all.cmd | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/build_test_all.cmd b/build_test_all.cmd index 85f7570ab..7875165dd 100644 --- a/build_test_all.cmd +++ b/build_test_all.cmd @@ -27,6 +27,14 @@ goto :post_format goto :eof :run_clang_format + set filePath=%1 + :: The test subfolder has obj directories with many redundant copies of generated cppwinrt headers. The + :: cost of formatting these files is vastly higher than the cost of formatting the code that is checked in + :: to this repo. Skip any file path with "obj" as a substring. + if not !filePath:obj!==!filePath! ( + goto :eof + ) + echo Formatting !filePath! "%CLANG_FORMAT%" -style=file -i %1 goto :eof From 7abe7b310e9193eb3c7c251316d6c2471320a52f Mon Sep 17 00:00:00 2001 From: David Machaj <46852402+dmachaj@users.noreply.github.com.> Date: Mon, 9 Dec 2024 12:43:02 -0800 Subject: [PATCH 3/9] Fix up format script to work better when there are obj directories floating around. Re-run formatting from scratch --- .github/workflows/ci.yml | 6 ++++-- README.md | 3 +++ build_test_all.cmd | 26 ++------------------------ format_all_files.cmd | 39 +++++++++++++++++++++++++++++++++++++++ 4 files changed, 48 insertions(+), 26 deletions(-) create mode 100644 format_all_files.cmd diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d6117c61f..a1815b5ce 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -39,8 +39,10 @@ jobs: if %ERRORLEVEL% neq 0 ( echo ::error::This branch contains changes that have not been formatted with 'clang-format', echo NOTE: To resolve this issue, you can run 'clang-format' in the following ways: - echo * Run build_test_all.cmd which will run 'clang-format' on _all_ source files. This script is - echo simpler to run, however there's a chance it may touch additional files you never changed due to you having + echo * Run build_test_all.cmd which will run 'git clang-format' on all source files that have been modified + echo in your branch. + echo * Run 'format_all_files.cmd' which will format _all_ source files. This script is + echo simple to run, however there's a chance it may touch additional files you never changed due to you having echo a mis-matched version of 'clang-format'. This may require you to manually revert changes made by echo 'clang-format' to the locations where you made no code changes. echo. diff --git a/README.md b/README.md index f1ad34cd6..33b34bdd4 100644 --- a/README.md +++ b/README.md @@ -50,3 +50,6 @@ Before submitting a PR to the cppwinrt repo we ask that you first run `clang-for There is a CI check in place that will fail the build for your PR if you have not run `clang-format`. `clang-format` will run automatically as part of `build_test_all.cmd`, so if you use that script this should happen automatically. + +If for some reason you would like to force formatting of every file in the repo then you can run `format_all_files.cmd` to +do so. This will take longer than `git clang-format` that will only format files that you have modified. diff --git a/build_test_all.cmd b/build_test_all.cmd index 7875165dd..3293e37d9 100644 --- a/build_test_all.cmd +++ b/build_test_all.cmd @@ -15,30 +15,8 @@ if "%target_version%"=="" set target_version=1.2.3.4 call "%~dp0/find_clang_format.cmd" if %ERRORLEVEL% neq 0 exit /b %ERRORLEVEL% -set DIRS=cppwinrt fast_fwd natvis prebuild scratch strings test vsix -set EXTS=.cpp .h -for %%d in (%DIRS%) do call :format_files %~dp0%%d -goto :post_format - -:format_files - for %%e in (%EXTS%) do ( - for /R %1 %%f in (*%%e) do call :run_clang_format "%%f" - ) - goto :eof - -:run_clang_format - set filePath=%1 - :: The test subfolder has obj directories with many redundant copies of generated cppwinrt headers. The - :: cost of formatting these files is vastly higher than the cost of formatting the code that is checked in - :: to this repo. Skip any file path with "obj" as a substring. - if not !filePath:obj!==!filePath! ( - goto :eof - ) - echo Formatting !filePath! - "%CLANG_FORMAT%" -style=file -i %1 - goto :eof - -:post_format +echo Running clang-format on all modified files... +git clang-format origin/master --binary "%CLANG_FORMAT%" --style file -- cppwinrt/*.h cppwinrt/*.cpp fast_fwd/*.h fast_fwd/*.cpp natvis/*.h natvis/*.cpp prebuild/*.h prebuild/*.cpp scratch/*.h scratch/*.cpp strings/*.h strings/*.cpp test/*.h test/*.cpp vsix/*.h vsix/*.cpp :: NuGet restore all solutions before building if not exist ".\.nuget" mkdir ".\.nuget" diff --git a/format_all_files.cmd b/format_all_files.cmd new file mode 100644 index 000000000..2c2ced1c7 --- /dev/null +++ b/format_all_files.cmd @@ -0,0 +1,39 @@ +@echo off +setlocal +setlocal EnableDelayedExpansion + +:: This script is a more invasive version of formatting all files in the repo with clang-format. It will format files that have not +:: been modified locally. It is mainly intended to be a "reformat everything" script for when .clang-format is modified. + +call "%~dp0/find_clang_format.cmd" +if %ERRORLEVEL% neq 0 exit /b %ERRORLEVEL% + +if exist ".\test\nuget\obj" ( + echo Warning: test\nuget\obj subfolder exists and will have large numbers of header files. It is recommended to delete that folder before running this script. + pause +) + +set DIRS=cppwinrt fast_fwd natvis prebuild scratch strings test vsix +set EXTS=.cpp .h +for %%d in (%DIRS%) do call :format_files %~dp0%%d + +:format_files + for %%e in (%EXTS%) do ( + for /R %1 %%f in (*%%e) do call :run_clang_format "%%f" + ) + goto :eof + +:run_clang_format + set filePath=%1 + :: The test subfolder has obj directories with many redundant copies of generated cppwinrt headers. The + :: cost of formatting these files is vastly higher than the cost of formatting the code that is checked in + :: to this repo. Skip any file path with "obj" as a substring. + set IGNORED= + for /F "tokens=*" %%g in ('git check-ignore %1') do (set IGNORED=%%g) + if not [!IGNORED!]==[] ( + echo %1 is ignored by git, skipping + goto :eof + ) + echo Formatting !filePath! + "%CLANG_FORMAT%" -style=file -i %1 + goto :eof From 70985d78234bf658efb4a138c303cc52e1f9364e Mon Sep 17 00:00:00 2001 From: David Machaj <46852402+dmachaj@users.noreply.github.com.> Date: Mon, 9 Dec 2024 12:48:55 -0800 Subject: [PATCH 4/9] It helps if you push the modified files --- cppwinrt/cmd_reader.h | 92 +- cppwinrt/code_writers.h | 408 +- cppwinrt/component_writers.h | 165 +- cppwinrt/file_writers.h | 8 +- cppwinrt/helpers.h | 304 +- cppwinrt/main.cpp | 57 +- cppwinrt/settings.h | 2 +- cppwinrt/task_group.h | 6 +- cppwinrt/text_writer.h | 56 +- cppwinrt/type_writers.h | 201 +- natvis/cppwinrt_visualizer.cpp | 78 +- natvis/cppwinrt_visualizer.h | 22 +- natvis/dllmain.cpp | 6 +- natvis/object_visualizer.cpp | 328 +- natvis/object_visualizer.h | 22 +- natvis/pch.h | 50 +- natvis/property_visualizer.cpp | 60 +- natvis/property_visualizer.h | 22 +- natvis/type_resolver.cpp | 112 +- prebuild/main.cpp | 18 +- scratch/main.cpp | 3 +- strings/base_abi.h | 101 +- strings/base_activation.h | 81 +- strings/base_agile_ref.h | 28 +- strings/base_array.h | 140 +- strings/base_chrono.h | 29 +- strings/base_collections.h | 44 +- strings/base_collections_base.h | 140 +- strings/base_collections_input_iterable.h | 176 +- strings/base_collections_input_map.h | 46 +- strings/base_collections_input_map_view.h | 108 +- strings/base_collections_input_vector.h | 40 +- strings/base_collections_input_vector_view.h | 104 +- strings/base_collections_map.h | 65 +- strings/base_collections_vector.h | 103 +- strings/base_com_ptr.h | 136 +- strings/base_composable.h | 28 +- strings/base_coroutine_foundation.h | 197 +- strings/base_coroutine_system.h | 13 +- strings/base_coroutine_system_winui.h | 13 +- strings/base_coroutine_threadpool.h | 164 +- strings/base_coroutine_ui_core.h | 18 +- strings/base_deferral.h | 7 +- strings/base_delegate.h | 126 +- strings/base_error.h | 316 +- strings/base_events.h | 75 +- strings/base_fast_forward.h | 23 +- strings/base_foundation.h | 51 +- strings/base_handle.h | 18 +- strings/base_identity.h | 325 +- strings/base_implements.h | 519 +- strings/base_includes.h | 10 +- strings/base_iterator.h | 29 +- strings/base_lock.h | 9 +- strings/base_macros.h | 12 +- strings/base_marshaler.h | 12 +- strings/base_meta.h | 215 +- strings/base_natvis.h | 17 +- strings/base_reference_produce.h | 510 +- strings/base_reference_produce_1.h | 6 +- strings/base_security.h | 11 +- strings/base_std_hash.h | 19 +- strings/base_string.h | 141 +- strings/base_string_input.h | 17 +- strings/base_string_operators.h | 112 +- strings/base_stringable_format.h | 3 +- strings/base_types.h | 138 +- strings/base_version.h | 4 +- strings/base_version_odr.h | 1 - strings/base_weak_ref.h | 50 +- strings/base_windows.h | 102 +- strings/base_xaml_component_connector.h | 10 +- strings/base_xaml_component_connector_winui.h | 8 +- strings/base_xaml_typename.h | 77 +- .../ConsoleApplication1Class.cpp | 5 +- .../ConsoleApplication1Class.h | 10 +- test/nuget/TestApp/App.cpp | 15 +- test/nuget/TestApp/App.h | 2 +- test/nuget/TestApp/MainPage.cpp | 2 +- test/nuget/TestApp/MainPage.h | 7 +- .../TestRuntimeComponent1Class.cpp | 5 +- .../TestRuntimeComponent1Class.h | 10 +- .../TestRuntimeComponent2Class.cpp | 2 +- .../TestRuntimeComponent2Class.h | 10 +- test/nuget/TestRuntimeComponent2/module.cpp | 11 +- .../TestRuntimeComponent3Class.cpp | 2 +- .../TestRuntimeComponent3Class.h | 10 +- test/nuget/TestRuntimeComponent3/module.cpp | 11 +- .../TestRuntimeComponentCXClass.cpp | 10 +- .../TestRuntimeComponentCXClass.h | 5 +- .../CxClass.cpp | 2 +- .../CxClass.h | 7 +- .../TestRuntimeComponentEmpty/module.cpp | 11 +- ...ntimeComponentNamespaceUnderscoreClass.cpp | 5 +- ...RuntimeComponentNamespaceUnderscoreClass.h | 13 +- .../TestStaticLibrary1Class.cpp | 2 +- .../TestStaticLibrary1Class.h | 7 +- .../TestStaticLibrary2Class.cpp | 2 +- .../TestStaticLibrary2Class.h | 7 +- .../TestStaticLibrary3Class.cpp | 5 +- .../TestStaticLibrary3Class.h | 7 +- .../TestStaticLibrary4Class.cpp | 2 +- .../TestStaticLibrary4Class.h | 7 +- .../TestStaticLibrary5Class.cpp | 2 +- .../TestStaticLibrary5Class.h | 7 +- .../TestStaticLibrary6/TestNamespace.cpp | 3 +- test/nuget/TestStaticLibrary6/TestNamespace.h | 7 +- .../TestStaticLibrary6Class.cpp | 2 +- .../TestStaticLibrary6Class.h | 7 +- .../TestStaticLibrary7Class.cpp | 2 +- .../TestStaticLibrary7Class.h | 7 +- test/old_tests/Component/Component_h.h | 4601 ++++++++--------- test/old_tests/Component/CustomBase.cpp | 2 +- test/old_tests/Component/CustomBase.h | 11 +- test/old_tests/Component/Errors.cpp | 2 +- test/old_tests/Component/Errors.h | 7 +- test/old_tests/Component/Events.cpp | 4 +- test/old_tests/Component/Events.h | 9 +- test/old_tests/Component/FastInput.cpp | 11 +- test/old_tests/Component/FastInput.h | 14 +- test/old_tests/Component/FastInputMap.cpp | 2 +- test/old_tests/Component/FastInputMap.h | 12 +- test/old_tests/Component/FastInputVector.cpp | 5 +- test/old_tests/Component/FastInputVector.h | 12 +- test/old_tests/Component/NonCachedStatic.h | 2 +- test/old_tests/Component/Parameters.cpp | 2 +- test/old_tests/Component/Parameters.h | 7 +- test/old_tests/Component/Static.h | 4 +- test/old_tests/Component/Structures.cpp | 2 +- test/old_tests/Component/Structures.h | 7 +- test/old_tests/Component/pch.h | 2 +- test/old_tests/Composable/Base.cpp | 6 +- test/old_tests/Composable/Base.h | 13 +- test/old_tests/Composable/Composable_h.h | 958 ++-- test/old_tests/Composable/Derived.cpp | 2 +- test/old_tests/Composable/Derived.h | 11 +- test/old_tests/UnitTests/Bindable.cpp | 10 +- test/old_tests/UnitTests/Boxing2.cpp | 19 +- test/old_tests/UnitTests/Composable.cpp | 44 +- test/old_tests/UnitTests/Errors.cpp | 21 +- test/old_tests/UnitTests/Events.cpp | 85 +- test/old_tests/UnitTests/FastInput.cpp | 108 +- test/old_tests/UnitTests/FastStrings.cpp | 26 +- test/old_tests/UnitTests/Generics.cpp | 3 +- test/old_tests/UnitTests/Hash.cpp | 1 - .../UnitTests/IInspectable_GetIids.cpp | 29 +- .../IInspectable_GetRuntimeClassName.cpp | 3 +- .../UnitTests/IInspectable_GetTrustLevel.cpp | 3 +- test/old_tests/UnitTests/IReference.cpp | 20 +- .../UnitTests/IUnknown_QueryInterface.cpp | 4 +- test/old_tests/UnitTests/Main.cpp | 9 +- test/old_tests/UnitTests/Parameters.cpp | 4 +- test/old_tests/UnitTests/Reference.cpp | 13 +- test/old_tests/UnitTests/Release.cpp | 4 +- test/old_tests/UnitTests/Security.cpp | 10 +- test/old_tests/UnitTests/StructCodeGen.cpp | 2 +- test/old_tests/UnitTests/Structures.cpp | 1 - test/old_tests/UnitTests/TryLookup.cpp | 54 +- test/old_tests/UnitTests/VariadicDelegate.cpp | 47 +- test/old_tests/UnitTests/abi_guard.cpp | 38 +- test/old_tests/UnitTests/agile_ref.cpp | 22 +- test/old_tests/UnitTests/agility.cpp | 27 +- .../old_tests/UnitTests/apartment_context.cpp | 189 +- test/old_tests/UnitTests/array.cpp | 102 +- test/old_tests/UnitTests/as.cpp | 5 +- test/old_tests/UnitTests/as_implements.cpp | 8 +- test/old_tests/UnitTests/async.cpp | 671 +-- test/old_tests/UnitTests/async_cancel.cpp | 55 +- test/old_tests/UnitTests/boxing.cpp | 8 +- test/old_tests/UnitTests/capture.cpp | 3 +- test/old_tests/UnitTests/casts.cpp | 2 +- test/old_tests/UnitTests/clock.cpp | 15 +- test/old_tests/UnitTests/collection_base.cpp | 223 +- test/old_tests/UnitTests/com_ptr.cpp | 37 +- test/old_tests/UnitTests/com_ref.cpp | 9 +- .../UnitTests/conditional_implements.cpp | 16 +- .../UnitTests/conditional_implements_pure.cpp | 13 +- test/old_tests/UnitTests/constexpr.cpp | 12 +- test/old_tests/UnitTests/delegate.cpp | 97 +- test/old_tests/UnitTests/delegate_lambda.cpp | 33 +- .../UnitTests/delegate_weak_strong.cpp | 60 +- test/old_tests/UnitTests/enum_flags.cpp | 5 +- test/old_tests/UnitTests/error_chaining.cpp | 148 +- test/old_tests/UnitTests/event_consume.cpp | 73 +- test/old_tests/UnitTests/event_produce.cpp | 160 +- test/old_tests/UnitTests/factory_cache.cpp | 2 +- test/old_tests/UnitTests/foundation.cpp | 14 +- .../UnitTests/get_activation_factory.cpp | 1 - test/old_tests/UnitTests/handle.cpp | 4 +- test/old_tests/UnitTests/hresult_error.cpp | 77 +- test/old_tests/UnitTests/hstring.cpp | 15 +- .../old_tests/UnitTests/implements_nested.cpp | 7 +- test/old_tests/UnitTests/interop.cpp | 28 +- test/old_tests/UnitTests/make_self.cpp | 2 - test/old_tests/UnitTests/marshal.cpp | 7 +- test/old_tests/UnitTests/meta.cpp | 42 +- test/old_tests/UnitTests/natvis.cpp | 76 +- test/old_tests/UnitTests/param_hstring.cpp | 4 +- test/old_tests/UnitTests/param_iterable.cpp | 51 +- test/old_tests/UnitTests/param_map.cpp | 15 +- test/old_tests/UnitTests/param_map_view.cpp | 22 +- test/old_tests/UnitTests/param_vector.cpp | 16 +- .../old_tests/UnitTests/param_vector_view.cpp | 20 +- test/old_tests/UnitTests/pch.h | 2 +- test/old_tests/UnitTests/produce.cpp | 59 +- .../UnitTests/produce_IPropertyValue.h | 192 +- test/old_tests/UnitTests/produce_async.cpp | 128 +- test/old_tests/UnitTests/produce_map.cpp | 33 +- test/old_tests/UnitTests/produce_vector.cpp | 52 +- test/old_tests/UnitTests/properties.cpp | 2 +- test/old_tests/UnitTests/range_for.cpp | 16 +- test/old_tests/UnitTests/reflect.cpp | 37 +- test/old_tests/UnitTests/sdk.cpp | 1 - .../UnitTests/single_threaded_map.cpp | 41 +- .../UnitTests/single_threaded_vector.cpp | 27 +- test/old_tests/UnitTests/smart_pointers.cpp | 48 +- test/old_tests/UnitTests/streams.cpp | 2 +- test/old_tests/UnitTests/struct.cpp | 18 +- test/old_tests/UnitTests/to_hstring.cpp | 4 +- test/old_tests/UnitTests/weak.cpp | 27 +- test/old_tests/UnitTests/xaml_typename.cpp | 2 +- test/test/GetMany.cpp | 76 +- test/test/abi_args.cpp | 8 +- test/test/abi_guard.cpp | 28 +- test/test/agile_ref.cpp | 2 +- test/test/agility.cpp | 21 +- test/test/async_auto_cancel.cpp | 8 +- test/test/async_cancel_callback.cpp | 17 +- test/test/async_check_cancel.cpp | 8 +- test/test/async_completed.cpp | 11 +- test/test/async_local.cpp | 8 +- test/test/async_no_suspend.cpp | 20 +- test/test/async_progress.cpp | 16 +- test/test/async_propagate_cancel.cpp | 11 +- test/test/async_result.cpp | 8 +- test/test/async_return.cpp | 5 +- test/test/async_suspend.cpp | 8 +- test/test/async_throw.cpp | 8 +- test/test/async_wait_for.cpp | 11 +- test/test/await_adapter.cpp | 7 +- test/test/await_completed.cpp | 2 +- test/test/box_array.cpp | 15 +- test/test/box_delegate.cpp | 5 +- test/test/capture.cpp | 3 +- test/test/cmd_reader.cpp | 19 +- test/test/coro_foundation.cpp | 2 +- test/test/coro_system.cpp | 2 +- test/test/coro_threadpool.cpp | 2 +- test/test/coro_ui_core.cpp | 2 +- test/test/custom_activation.cpp | 2 +- test/test/custom_error.cpp | 21 +- test/test/delegate.cpp | 67 +- test/test/delegates.cpp | 40 +- test/test/disconnected.cpp | 116 +- test/test/error_info.cpp | 2 +- test/test/event_clear.cpp | 10 +- test/test/event_deferral.cpp | 4 +- test/test/final_release.cpp | 2 +- test/test/generic_type_names.cpp | 174 +- test/test/generic_types.h | 17 +- test/test/guid.cpp | 3 +- test/test/hresult_class_not_registered.cpp | 4 +- test/test/iid_ppv_args.cpp | 2 +- test/test/in_params.cpp | 22 +- test/test/in_params_abi.cpp | 16 +- test/test/initialize.cpp | 36 +- test/test/inspectable_interop.cpp | 4 +- test/test/interop.cpp | 24 +- test/test/invalid_events.cpp | 16 +- test/test/main.cpp | 7 +- test/test/missing_required_interfaces.cpp | 5 +- test/test/module_lock_dll.cpp | 8 +- test/test/multi_threaded_common.h | 62 +- test/test/multi_threaded_map.cpp | 164 +- test/test/multi_threaded_vector.cpp | 238 +- test/test/names.cpp | 3 +- test/test/out_params.cpp | 6 +- test/test/out_params_abi.cpp | 8 +- test/test/out_params_bad.cpp | 5 +- test/test/parent_includes.cpp | 2 +- test/test/pch.h | 25 +- test/test/return_params.cpp | 2 +- test/test/return_params_abi.cpp | 12 +- .../single_threaded_observable_vector.cpp | 72 +- test/test/tearoff.cpp | 13 +- test/test/thread_pool.cpp | 5 +- test/test/uniform_in_params.cpp | 28 +- test/test/variadic_delegate.cpp | 29 +- test/test/when.cpp | 5 +- test/test_component/Class.cpp | 76 +- test/test_component/Class.h | 59 +- test/test_component/Optional.h | 7 +- test/test_component/OverloadClass.cpp | 2 +- test/test_component/OverloadClass.h | 7 +- test/test_component/Simple.cpp | 2 +- test/test_component/Simple.h | 15 +- test/test_component/Velocity.Class1.cpp | 5 +- test/test_component/Velocity.Class1.h | 7 +- test/test_component/Velocity.Class2.cpp | 5 +- test/test_component/Velocity.Class2.h | 7 +- test/test_component/Velocity.Class4.cpp | 23 +- test/test_component/Velocity.Class4.h | 7 +- test/test_component/Windows.Class.cpp | 2 +- test/test_component/Windows.Class.h | 7 +- test/test_component_base/HierarchyA.cpp | 10 +- test/test_component_base/HierarchyA.h | 7 +- test/test_component_base/HierarchyB.cpp | 5 +- test/test_component_base/HierarchyB.h | 7 +- .../Nested.HierarchyC.cpp | 5 +- .../Nested.HierarchyC.h | 7 +- .../Nested.HierarchyD.cpp | 2 +- .../Nested.HierarchyD.h | 10 +- .../Composition.CompositionObject.cpp | 11 +- .../Composition.CompositionObject.h | 3 +- .../Composition.Compositor.cpp | 2 +- .../Composition.Compositor.h | 7 +- .../Composition.SpriteVisual.cpp | 12 +- .../Composition.SpriteVisual.h | 2 +- .../Composition.Visual.cpp | 8 +- test/test_component_fast/Composition.Visual.h | 3 +- test/test_component_fast/Nomadic.cpp | 2 +- test/test_component_fast/Nomadic.h | 7 +- test/test_component_fast/Simple.cpp | 2 +- test/test_component_fast/Simple.h | 7 +- test/test_component_folders/Class.cpp | 2 +- test/test_component_folders/Class.h | 7 +- .../Nested.NestedClass.cpp | 2 +- .../Nested.NestedClass.h | 7 +- test/test_component_no_pch/Class.cpp | 2 +- test/test_component_no_pch/Class.h | 7 +- test/test_cpp20/array_span.cpp | 9 +- test/test_cpp20/await_completed.cpp | 2 +- test/test_cpp20/custom_error.cpp | 8 +- test/test_cpp20/hstring.cpp | 16 +- test/test_cpp20/main.cpp | 7 +- test/test_cpp20/pch.h | 2 +- .../custom_error.cpp | 8 +- test/test_cpp20_no_sourcelocation/main.cpp | 7 +- test/test_cpp20_no_sourcelocation/pch.h | 2 +- test/test_fast/Nomadic.cpp | 2 +- test/test_fast/main.cpp | 7 +- test/test_fast_fwd/FastForwarderTests.cpp | 67 +- test/test_fast_fwd/main.cpp | 7 +- test/test_module_lock_custom/main.cpp | 11 +- test/test_module_lock_none/main.cpp | 19 +- test/test_slow/main.cpp | 7 +- vsix/ItemTemplates/BlankPage/BlankPage.cpp | 2 +- vsix/ItemTemplates/BlankPage/BlankPage.h | 13 +- .../BlankUserControl/BlankUserControl.cpp | 2 +- .../BlankUserControl/BlankUserControl.h | 13 +- vsix/ItemTemplates/ViewModel/ViewModel.cpp | 2 +- vsix/ItemTemplates/ViewModel/ViewModel.h | 7 +- .../WindowsApplication/resource.h | 10 +- .../VC/Windows Universal/BlankApp/App.cpp | 15 +- .../VC/Windows Universal/BlankApp/App.h | 2 +- .../Windows Universal/BlankApp/MainPage.cpp | 2 +- .../VC/Windows Universal/BlankApp/MainPage.h | 11 +- .../VC/Windows Universal/CoreApp/App.cpp | 51 +- .../Windows Universal/StaticLibrary/Class.cpp | 2 +- .../Windows Universal/StaticLibrary/Class.h | 7 +- .../WindowsRuntimeComponent/Class.cpp | 2 +- .../WindowsRuntimeComponent/Class.h | 7 +- 362 files changed, 9387 insertions(+), 9284 deletions(-) diff --git a/cppwinrt/cmd_reader.h b/cppwinrt/cmd_reader.h index 7faf49e4f..f65714bde 100644 --- a/cppwinrt/cmd_reader.h +++ b/cppwinrt/cmd_reader.h @@ -32,8 +32,7 @@ namespace cppwinrt explicit registry_key(HKEY handle) : handle(handle) - { - } + {} ~registry_key() noexcept { @@ -44,8 +43,7 @@ namespace cppwinrt } }; - template - struct com_ptr + template struct com_ptr { T* ptr{}; @@ -91,12 +89,9 @@ namespace cppwinrt { com_ptr stream; - auto streamResult = SHCreateStreamOnFileW( - xml_path.c_str(), - STGM_READ, &stream.ptr); - if (xml_path_requirement == xml_requirement::optional && - (streamResult == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND) || - streamResult == HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND))) + auto streamResult = SHCreateStreamOnFileW(xml_path.c_str(), STGM_READ, &stream.ptr); + if (xml_path_requirement == xml_requirement::optional && (streamResult == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND) || + streamResult == HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND))) { return; } @@ -104,10 +99,7 @@ namespace cppwinrt com_ptr reader; - check_xml(CreateXmlReader( - __uuidof(IXmlReader), - reinterpret_cast(&reader.ptr), - nullptr)); + check_xml(CreateXmlReader(__uuidof(IXmlReader), reinterpret_cast(&reader.ptr), nullptr)); check_xml(reader->SetInput(stream.ptr)); XmlNodeType node_type = XmlNodeType_None; @@ -153,13 +145,13 @@ namespace cppwinrt HKEY key; if (0 != RegOpenKeyExW( - HKEY_LOCAL_MACHINE, - L"SOFTWARE\\Microsoft\\Windows Kits\\Installed Roots", - 0, - // https://task.ms/29349404 - The SDK sometimes stores the 64 bit location into KitsRoot10 which is wrong, - // this breaks 64-bit cppwinrt.exe, so work around this by forcing to use the WoW64 hive. - KEY_READ | KEY_WOW64_32KEY, - &key)) + HKEY_LOCAL_MACHINE, + L"SOFTWARE\\Microsoft\\Windows Kits\\Installed Roots", + 0, + // https://task.ms/29349404 - The SDK sometimes stores the 64 bit location into KitsRoot10 which is + // wrong, this breaks 64-bit cppwinrt.exe, so work around this by forcing to use the WoW64 hive. + KEY_READ | KEY_WOW64_32KEY, + &key)) { throw std::invalid_argument("Could not find the Windows SDK in the registry"); } @@ -173,26 +165,14 @@ namespace cppwinrt DWORD path_size = 0; - if (0 != RegQueryValueExW( - key.handle, - L"KitsRoot10", - nullptr, - nullptr, - nullptr, - &path_size)) + if (0 != RegQueryValueExW(key.handle, L"KitsRoot10", nullptr, nullptr, nullptr, &path_size)) { throw std::invalid_argument("Could not find the Windows SDK path in the registry"); } std::wstring root((path_size / sizeof(wchar_t)) - 1, L'?'); - RegQueryValueExW( - key.handle, - L"KitsRoot10", - nullptr, - nullptr, - reinterpret_cast(root.data()), - &path_size); + RegQueryValueExW(key.handle, L"KitsRoot10", nullptr, nullptr, reinterpret_cast(root.data()), &path_size); return root; } @@ -258,7 +238,7 @@ namespace cppwinrt char* next_part = subkey.data(); bool force_newer = false; - for (size_t i = 0; ; ++i) + for (size_t i = 0;; ++i) { auto version_part = strtoul(next_part, &next_part, 10); @@ -303,8 +283,7 @@ namespace cppwinrt throw std::invalid_argument(message); } - template - [[noreturn]] inline void throw_invalid(std::string message, T const&... args) + template [[noreturn]] inline void throw_invalid(std::string message, T const&... args) { (message.append(args), ...); throw std::invalid_argument(message); @@ -314,7 +293,7 @@ namespace cppwinrt { static constexpr uint32_t no_min = 0; static constexpr uint32_t no_max = UINT_MAX; - + std::string_view name; uint32_t min{ no_min }; uint32_t max{ no_max }; @@ -325,7 +304,7 @@ namespace cppwinrt struct reader { template - reader(C const argc, V const argv, const option(& options)[numOptions]) + reader(C const argc, V const argv, const option (&options)[numOptions]) { #ifdef _DEBUG { @@ -410,8 +389,7 @@ namespace cppwinrt return result->second.front(); } - template - auto files(std::string_view const& name, F directory_filter) const + template auto files(std::string_view const& name, F directory_filter) const { std::set files; @@ -449,12 +427,14 @@ namespace cppwinrt #if defined(_WIN32) || defined(_WIN64) std::array local{}; #ifdef _WIN64 - ExpandEnvironmentStringsA("%windir%\\System32\\WinMetadata", local.data(), static_cast(local.size())); + ExpandEnvironmentStringsA( + "%windir%\\System32\\WinMetadata", local.data(), static_cast(local.size())); #else - ExpandEnvironmentStringsA("%windir%\\SysNative\\WinMetadata", local.data(), static_cast(local.size())); + ExpandEnvironmentStringsA( + "%windir%\\SysNative\\WinMetadata", local.data(), static_cast(local.size())); #endif add_directory(local.data()); -#else /* defined(_WIN32) || defined(_WIN64) */ +#else /* defined(_WIN32) || defined(_WIN64) */ throw_invalid("Spec '", path, "' not supported outside of Windows"); #endif /* defined(_WIN32) || defined(_WIN64) */ continue; @@ -466,7 +446,7 @@ namespace cppwinrt { #if defined(_WIN32) || defined(_WIN64) sdk_version = get_sdk_version(); -#else /* defined(_WIN32) || defined(_WIN64) */ +#else /* defined(_WIN32) || defined(_WIN64) */ throw_invalid("Spec '", path, "' not supported outside of Windows"); #endif /* defined(_WIN32) || defined(_WIN64) */ } @@ -505,7 +485,7 @@ namespace cppwinrt // Not all Extension SDKs include an SDKManifest.xml file; ignore those which do not (e.g. WindowsIoT). add_files_from_xml(files, sdk_version, xml_path, sdk_path, xml_requirement::optional); } -#else /* defined(_WIN32) || defined(_WIN64) */ +#else /* defined(_WIN32) || defined(_WIN64) */ throw_invalid("Spec '", path, "' not supported outside of Windows"); #endif /* defined(_WIN32) || defined(_WIN64) */ @@ -520,18 +500,16 @@ namespace cppwinrt auto files(std::string_view const& name) const { - return files(name, [](auto&&) {return true; }); + return files(name, [](auto&&) { return true; }); } private: - inline bool starts_with(std::string_view const& value, std::string_view const& match) noexcept { return 0 == value.compare(0, match.size(), match); } - template - auto find(O const& options, std::string_view const& arg) + template auto find(O const& options, std::string_view const& arg) { for (auto current = std::begin(options); current != std::end(options); ++current) { @@ -546,8 +524,7 @@ namespace cppwinrt std::map> m_options; - template - void extract_option(std::string_view arg, O const& options, L& last) + template void extract_option(std::string_view arg, O const& options, L& last) { if (arg[0] == '-' #if defined(_WIN32) || defined(_WIN64) @@ -580,12 +557,15 @@ namespace cppwinrt } } - template + template void extract_response_file(std::string_view const& arg, O const& options, L& last) { std::filesystem::path response_path{ std::string{ arg } }; std::string extension = response_path.extension().generic_string(); - std::transform(extension.begin(), extension.end(), extension.begin(), + std::transform( + extension.begin(), + extension.end(), + extension.begin(), [](auto c) { return static_cast(::tolower(c)); }); // Check if misuse of @ prefix, so if directory or metadata file instead of response file. @@ -699,4 +679,4 @@ namespace cppwinrt } } }; -} +} // namespace cppwinrt diff --git a/cppwinrt/code_writers.h b/cppwinrt/code_writers.h index 0ff1887d1..564b0fcbb 100644 --- a/cppwinrt/code_writers.h +++ b/cppwinrt/code_writers.h @@ -7,31 +7,40 @@ namespace cppwinrt writer& w; void (*finisher)(writer&); - finish_with(writer& w, void (*finisher)(writer&)) : w(w), finisher(finisher) {} - finish_with(finish_with const&)= delete; + finish_with(writer& w, void (*finisher)(writer&)) : + w(w), finisher(finisher) + {} + finish_with(finish_with const&) = delete; void operator=(finish_with const&) = delete; - ~finish_with() { finisher(w); } + ~finish_with() + { + finisher(w); + } }; static void write_nothing(writer&) - { - } + {} static void write_preamble(writer& w) { if (settings.license) { - w.write(R"(// C++/WinRT v% + w.write( + R"(// C++/WinRT v% % -)", CPPWINRT_VERSION_STRING, settings.license_template); +)", + CPPWINRT_VERSION_STRING, + settings.license_template); } else { - w.write(R"(// WARNING: Please don't edit this file. It was generated by C++/WinRT v% + w.write( + R"(// WARNING: Please don't edit this file. It was generated by C++/WinRT v% -)", CPPWINRT_VERSION_STRING); +)", + CPPWINRT_VERSION_STRING); } } @@ -68,7 +77,7 @@ namespace cppwinrt static void write_open_file_guard(writer& w, std::string_view const& file_name, char impl = 0) { write_include_guard(w); - + std::string mangled_name; for (auto&& c : file_name) @@ -89,8 +98,7 @@ namespace cppwinrt w.write(format, mangled_name, mangled_name); } - template - [[nodiscard]] static finish_with wrap_open_file_guard(writer& w, Args&&... args) + template [[nodiscard]] static finish_with wrap_open_file_guard(writer& w, Args&&... args) { write_open_file_guard(w, std::forward(args)...); return { w, write_close_file_guard }; @@ -313,8 +321,7 @@ namespace cppwinrt return; } - if (type_name == "Windows.Foundation.DateTime" || - type_name == "Windows.Foundation.TimeSpan") + if (type_name == "Windows.Foundation.DateTime" || type_name == "Windows.Foundation.TimeSpan") { // Don't forward declare these since they're not structs. return; @@ -322,12 +329,8 @@ namespace cppwinrt if (type_name.name_space == "Windows.Foundation.Numerics") { - if (type_name.name == "Matrix3x2" || - type_name.name == "Matrix4x4" || - type_name.name == "Plane" || - type_name.name == "Quaternion" || - type_name.name == "Vector2" || - type_name.name == "Vector3" || + if (type_name.name == "Matrix3x2" || type_name.name == "Matrix4x4" || type_name.name == "Plane" || + type_name.name == "Quaternion" || type_name.name == "Vector2" || type_name.name == "Vector3" || type_name.name == "Vector4") { // Don't forward declare these since they're already defined with different names. @@ -349,16 +352,15 @@ namespace cppwinrt auto format = R"( template <%> struct WINRT_IMPL_EMPTY_BASES %; )"; - w.write(format, - bind(generics), - remove_tick(type_name.name)); + w.write(format, bind(generics), remove_tick(type_name.name)); } static void write_guid_value(writer& w, std::vector const& args) { using std::get; - w.write_printf("0x%08X,0x%04X,0x%04X,{ 0x%02X,0x%02X,0x%02X,0x%02X,0x%02X,0x%02X,0x%02X,0x%02X }", + w.write_printf( + "0x%08X,0x%04X,0x%04X,{ 0x%02X,0x%02X,0x%02X,0x%02X,0x%02X,0x%02X,0x%02X,0x%02X }", get(get(args[0].value).value), get(get(args[1].value).value), get(get(args[2].value).value), @@ -376,7 +378,8 @@ namespace cppwinrt { using std::get; - w.write_printf("%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X", + w.write_printf( + "%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X", get(get(args[0].value).value), get(get(args[1].value).value), get(get(args[2].value).value), @@ -406,10 +409,7 @@ namespace cppwinrt auto format = R"( template <%> struct category<%>{ using type = generic_category<%>; }; )"; - w.write(format, - bind(generics), - type, - bind_list(", ", generics)); + w.write(format, bind(generics), type, bind_list(", ", generics)); } } @@ -448,7 +448,8 @@ namespace cppwinrt auto format = R"( template <%> inline constexpr auto name_v<%> = zcombine(L"%.%<"%, L">"); )"; - w.write(format, + w.write( + format, bind(generics), type, type_name.name_space, @@ -463,7 +464,8 @@ namespace cppwinrt if (!attribute) { - throw_invalid("'Windows.Foundation.Metadata.GuidAttribute' attribute for type '", type.TypeNamespace(), ".", type.TypeName(), "' not found"); + throw_invalid( + "'Windows.Foundation.Metadata.GuidAttribute' attribute for type '", type.TypeNamespace(), ".", type.TypeName(), "' not found"); } auto generics = type.GenericParam(); @@ -474,10 +476,7 @@ namespace cppwinrt auto format = R"( template <> inline constexpr guid guid_v<%>{ % }; // % )"; - w.write(format, - type, - bind(guid), - bind(guid)); + w.write(format, type, bind(guid), bind(guid)); } else { @@ -485,7 +484,8 @@ namespace cppwinrt template <%> inline constexpr guid generic_guid_v<%>{ % }; // % )"; - w.write(format, + w.write( + format, bind(generics), type, type, @@ -723,13 +723,16 @@ namespace cppwinrt auto bases = get_bases(pair->second); - std::for_each(bases.rbegin(), bases.rend(), [&](auto&& base) - { - auto format = R"( virtual void* __stdcall base_%() noexcept = 0; + std::for_each( + bases.rbegin(), + bases.rend(), + [&](auto&& base) + { + auto format = R"( virtual void* __stdcall base_%() noexcept = 0; )"; - w.write(format, base.TypeName()); - }); + w.write(format, base.TypeName()); + }); for (auto&& [name, info] : get_interfaces(w, pair->second)) { @@ -737,7 +740,7 @@ namespace cppwinrt { continue; } - + if (!info.fastabi) { break; @@ -777,12 +780,9 @@ namespace cppwinrt { )"; - w.write(format, - bind(generics), - type); + w.write(format, bind(generics), type); } - auto format = R"( virtual int32_t __stdcall %(%) noexcept = 0; )"; @@ -796,10 +796,16 @@ namespace cppwinrt } catch (std::exception const& e) { - throw_invalid(e.what(), - "\n method: ", get_name(method), - "\n type: ", type.TypeNamespace(), ".", type.TypeName(), - "\n database: ", type.get_database().path()); + throw_invalid( + e.what(), + "\n method: ", + get_name(method), + "\n type: ", + type.TypeNamespace(), + ".", + type.TypeName(), + "\n database: ", + type.get_database().path()); } } @@ -826,10 +832,7 @@ namespace cppwinrt auto method = get_delegate_method(type); method_signature signature{ method }; - w.write(format, - bind(generics), - type, - bind(signature)); + w.write(format, bind(generics), type, bind(signature)); } static void write_field_abi(writer& w, Field const& field) @@ -853,12 +856,7 @@ namespace cppwinrt type_name type_name(type); auto impl_name = get_impl_name(type_name.name_space, type_name.name); - w.write(format, - impl_name, - bind_each(type.FieldList()), - type_name.name_space, type_name.name, - impl_name); - + w.write(format, impl_name, bind_each(type.FieldList()), type_name.name_space, type_name.name, impl_name); } static void write_consume_params(writer& w, method_signature const& signature) @@ -990,7 +988,8 @@ namespace cppwinrt auto method_name = get_name(method); auto type = method.Parent(); - w.write(" %auto %(%) const%;\n", + w.write( + " %auto %(%) const%;\n", is_get_overload(method) ? "[[nodiscard]] " : "", method_name, bind(signature), @@ -1002,13 +1001,7 @@ namespace cppwinrt [[nodiscard]] auto %(auto_revoke_t, %) const; )"; - w.write(format, - method_name, - type, - type, - method_name, - method_name, - bind(signature)); + w.write(format, method_name, type, type, method_name, method_name, bind(signature)); } } @@ -1055,10 +1048,7 @@ namespace cppwinrt auto abi_guard = w.push_abi_types(true); auto delegate_guard = w.push_delegate_types(delegate_types); - w.write(format, - signature.return_param_name(), - signature.return_signature(), - signature.return_param_name()); + w.write(format, signature.return_param_name(), signature.return_signature(), signature.return_param_name()); } else if (category == param_category::object_type || category == param_category::string_type) { @@ -1088,16 +1078,15 @@ namespace cppwinrt if (category == param_category::array_type) { - w.write("\n return %{ %, %_impl_size, take_ownership_from_abi };", + w.write( + "\n return %{ %, %_impl_size, take_ownership_from_abi };", signature.return_signature(), signature.return_param_name(), signature.return_param_name()); } else if (category == param_category::object_type || category == param_category::string_type) { - w.write("\n return %{ %, take_ownership_from_abi };", - signature.return_signature(), - signature.return_param_name()); + w.write("\n return %{ %, take_ownership_from_abi };", signature.return_signature(), signature.return_param_name()); } else { @@ -1116,7 +1105,12 @@ namespace cppwinrt } } - static void write_consume_definition(writer& w, TypeDef const& type, MethodDef const& method, std::pair const& generics, std::string_view const& type_impl_name) + static void write_consume_definition( + writer& w, + TypeDef const& type, + MethodDef const& method, + std::pair const& generics, + std::string_view const& type_impl_name) { auto method_name = get_name(method); method_signature signature{ method }; @@ -1131,8 +1125,8 @@ namespace cppwinrt // we intentionally ignore errors when unregistering event handlers to be consistent with event_revoker // // The `noexcept` versions will crash if check_hresult throws but that is no different than previous - // behavior where it would not check the cast result and nullptr crash. At least the exception will terminate - // immediately while preserving the error code and local variables. + // behavior where it would not check the cast result and nullptr crash. At least the exception will + // terminate immediately while preserving the error code and local variables. format = R"( template auto consume_%::%(%) const noexcept {% if constexpr (!std::is_same_v) @@ -1190,7 +1184,8 @@ namespace cppwinrt )"; } - w.write(format, + w.write( + format, bind(generics), type_impl_name, bind(generics), @@ -1215,7 +1210,8 @@ namespace cppwinrt } )"; - w.write(format, + w.write( + format, bind(generics), type_impl_name, bind(generics), @@ -1239,7 +1235,8 @@ namespace cppwinrt } )"; - w.write(format, + w.write( + format, class_type.TypeName(), method_name, bind(signature), @@ -1256,7 +1253,8 @@ namespace cppwinrt } )"; - w.write(format, + w.write( + format, class_type.TypeName(), method_name, bind(signature), @@ -1581,8 +1579,8 @@ namespace cppwinrt }; )"; - - w.write(format, + w.write( + format, impl_name, bind_each(type.MethodList()), bind(type), @@ -1602,8 +1600,8 @@ namespace cppwinrt }; )"; - - w.write(format, + w.write( + format, bind(generics), impl_name, bind_each(type.MethodList()), @@ -1629,7 +1627,8 @@ namespace cppwinrt bool optional{}; bool zero{}; - call(signature.Type(), + call( + signature.Type(), [&](ElementType type) { if (out && type == ElementType::Object) @@ -1660,22 +1659,14 @@ namespace cppwinrt { auto category = get_category(type); - clear = category == category::class_type || category == category::interface_type || category == category::delegate_type; + clear = category == category::class_type || category == category::interface_type || + category == category::delegate_type; zero = category == category::struct_type; } }, - [&](GenericTypeIndex const&) - { - clear = true; - }, - [](GenericMethodTypeIndex) - { - throw_invalid("Generic methods not supported."); - }, - [&](GenericTypeInstSig const&) - { - clear = true; - }); + [&](GenericTypeIndex const&) { clear = true; }, + [](GenericMethodTypeIndex) { throw_invalid("Generic methods not supported."); }, + [&](GenericTypeInstSig const&) { clear = true; }); if (signature.is_szarray()) { @@ -1708,19 +1699,14 @@ namespace cppwinrt auto format = R"( zero_abi<%>(%, __%Size); )"; - w.write(format, - signature.Type(), - param_name, - param_name); + w.write(format, signature.Type(), param_name, param_name); } else { auto format = R"( zero_abi<%>(%); )"; - w.write(format, - signature.Type(), - param_name); + w.write(format, signature.Type(), param_name); } } else if (optional) @@ -1765,7 +1751,8 @@ namespace cppwinrt { if (param.Flags().In()) { - w.write("array_view<@ const>(reinterpret_cast<@ const *>(%), reinterpret_cast<@ const *>(%) + __%Size)", + w.write( + "array_view<@ const>(reinterpret_cast<@ const *>(%), reinterpret_cast<@ const *>(%) + __%Size)", param_type, param_type, param_name, @@ -1775,14 +1762,12 @@ namespace cppwinrt } else if (param_signature->ByRef()) { - w.write("detach_abi<@>(__%Size, %)", - param_type, - param_name, - param_name); + w.write("detach_abi<@>(__%Size, %)", param_type, param_name, param_name); } else { - w.write("array_view<@>(reinterpret_cast<@*>(%), reinterpret_cast<@*>(%) + __%Size)", + w.write( + "array_view<@>(reinterpret_cast<@*>(%), reinterpret_cast<@*>(%) + __%Size)", param_type, param_type, param_name, @@ -1799,9 +1784,7 @@ namespace cppwinrt { if (category != param_category::fundamental_type) { - w.write("*reinterpret_cast<% const*>(&%)", - param_type, - param_name); + w.write("*reinterpret_cast<% const*>(&%)", param_type, param_name); } else { @@ -1816,9 +1799,7 @@ namespace cppwinrt } else if (category != param_category::fundamental_type) { - w.write("*reinterpret_cast<@*>(%)", - param_type, - param_name); + w.write("*reinterpret_cast<@*>(%)", param_type, param_name); } else { @@ -1837,15 +1818,12 @@ namespace cppwinrt if (method_signature.return_signature().Type().is_szarray()) { - w.write("std::tie(*__%Size, *%) = detach_abi(%(%));", - name, - name, - upcall, - bind(method_signature)); + w.write("std::tie(*__%Size, *%) = detach_abi(%(%));", name, name, upcall, bind(method_signature)); } else { - w.write("*% = detach_from<%>(%(%));", + w.write( + "*% = detach_from<%>(%(%));", name, method_signature.return_signature(), upcall, @@ -1854,9 +1832,7 @@ namespace cppwinrt } else { - w.write("%(%);", - upcall, - bind(method_signature)); + w.write("%(%);", upcall, bind(method_signature)); } for (auto&& [param, param_signature] : method_signature.params()) @@ -1901,7 +1877,8 @@ namespace cppwinrt std::string upcall = "this->shim()."; upcall += get_name(method); - w.write(format, + w.write( + format, get_abi_name(method), bind(signature), bind(signature), @@ -1924,17 +1901,20 @@ namespace cppwinrt auto bases = get_bases(pair->second); - std::for_each(bases.rbegin(), bases.rend(), [&](auto && base) - { - auto format = R"( void* __stdcall base_%() noexcept final + std::for_each( + bases.rbegin(), + bases.rend(), + [&](auto&& base) + { + auto format = R"( void* __stdcall base_%() noexcept final { return this->shim().base_%(); } )"; - auto base_name = base.TypeName(); - w.write(format, base_name, base_name); - }); + auto base_name = base.TypeName(); + w.write(format, base_name, base_name); + }); for (auto&& [name, info] : get_interfaces(w, pair->second)) { @@ -1966,7 +1946,8 @@ namespace cppwinrt auto wrap = wrap_lean_and_mean(w, lean_and_mean); - w.write(format, + w.write( + format, bind(generics), type, type, @@ -1989,7 +1970,8 @@ namespace cppwinrt method_signature signature{ method }; - w.write(format, + w.write( + format, get_name(method), bind(signature), is_noexcept(method) ? " noexcept" : "", @@ -2012,10 +1994,7 @@ struct WINRT_IMPL_EMPTY_BASES produce_dispatch_to_overridable { if (info.overridable && !info.base) { - w.write(format, - interface_name, - interface_name, - bind_each(info.type.MethodList())); + w.write(format, interface_name, interface_name, bind_each(info.type.MethodList())); } } } @@ -2031,7 +2010,8 @@ struct WINRT_IMPL_EMPTY_BASES produce_dispatch_to_overridable method_signature signature{ method }; auto method_name = get_name(method); - w.write(format, + w.write( + format, interface_name, method_name, bind(signature), @@ -2172,10 +2152,7 @@ struct WINRT_IMPL_EMPTY_BASES produce_dispatch_to_overridable auto format = "impl::call_factory<%, %>([&](% const& f)"; - w.write(format, - type.TypeName(), - factory_name, - factory_name); + w.write(format, type.TypeName(), factory_name, factory_name); } static void write_optimized_call_factory(writer& w, TypeDef const& type, TypeDef const& factory, method_signature const& signature) @@ -2195,7 +2172,8 @@ struct WINRT_IMPL_EMPTY_BASES produce_dispatch_to_overridable { auto format = "impl::call_factory_cast<%(*)(% const&), %, %>([](% const& f) { return f.%(); })"; - w.write(format, + w.write( + format, signature.return_signature(), factory_name, type.TypeName(), @@ -2207,12 +2185,7 @@ struct WINRT_IMPL_EMPTY_BASES produce_dispatch_to_overridable { auto format = "impl::call_factory<%, %>([&](% const& f) { return f.%(%); })"; - w.write(format, - type.TypeName(), - factory_name, - factory_name, - get_name(signature.method()), - bind(signature)); + w.write(format, type.TypeName(), factory_name, factory_name, get_name(signature.method()), bind(signature)); } } @@ -2239,7 +2212,8 @@ struct WINRT_IMPL_EMPTY_BASES produce_dispatch_to_overridable auto& params = signature.params(); params.resize(params.size() - 2); - w.write(format, + w.write( + format, type_name, bind(signature), bind(type, factory.type), @@ -2268,11 +2242,7 @@ struct WINRT_IMPL_EMPTY_BASES produce_dispatch_to_overridable { auto type_name = info.type.TypeName(); - w.write(format, - type_name, - type_name, - info.type, - bind_each(info.type.MethodList())); + w.write(format, type_name, type_name, info.type, bind_each(info.type.MethodList())); } } } @@ -2298,9 +2268,8 @@ struct WINRT_IMPL_EMPTY_BASES produce_dispatch_to_overridable for (auto&& [interface_name, info] : interfaces) { - w.write(info.overridable - ? " using %T::%;\n" - : " using impl::consume_t::%;\n", + w.write( + info.overridable ? " using %T::%;\n" : " using impl::consume_t::%;\n", interface_name, method_name); } @@ -2340,7 +2309,8 @@ struct WINRT_IMPL_EMPTY_BASES produce_dispatch_to_overridable auto type_name = type.TypeName(); auto interfaces = get_interfaces(w, type); - w.write(format, + w.write( + format, type_name, bind(interfaces), bind(interfaces), @@ -2397,10 +2367,7 @@ struct WINRT_IMPL_EMPTY_BASES produce_dispatch_to_overridable for (auto&& interface_name : interfaces) { - w.write(" using impl::consume_t<%, %>::%;\n", - type_name, - interface_name, - method_name); + w.write(" using impl::consume_t<%, %>::%;\n", type_name, interface_name, method_name); } } } @@ -2444,16 +2411,11 @@ struct WINRT_IMPL_EMPTY_BASES produce_dispatch_to_overridable { if (default_interface_name == interface_name) { - w.write(" using %::%;\n", - interface_name, - method_name); + w.write(" using %::%;\n", interface_name, method_name); } else { - w.write(" using impl::consume_t<%, %>::%;\n", - type_name, - interface_name, - method_name); + w.write(" using impl::consume_t<%, %>::%;\n", type_name, interface_name, method_name); } } } @@ -2476,7 +2438,8 @@ struct WINRT_IMPL_EMPTY_BASES produce_dispatch_to_overridable %% }; )"; - w.write(format, + w.write( + format, type_name, type_name, bind(type), @@ -2499,7 +2462,8 @@ struct WINRT_IMPL_EMPTY_BASES produce_dispatch_to_overridable %% }; )"; - w.write(format, + w.write( + format, bind(generics), type_name, type, @@ -2545,7 +2509,8 @@ struct WINRT_IMPL_EMPTY_BASES produce_dispatch_to_overridable method_signature signature{ get_delegate_method(type) }; - w.write(format, + w.write( + format, type_name, bind(generics), type_name, @@ -2579,7 +2544,8 @@ struct WINRT_IMPL_EMPTY_BASES produce_dispatch_to_overridable auto guard{ w.push_generic_params(generics) }; method_signature signature{ get_delegate_method(type) }; - w.write(format, + w.write( + format, bind(generics), type, type, @@ -2640,7 +2606,8 @@ struct WINRT_IMPL_EMPTY_BASES produce_dispatch_to_overridable type_name = remove_tick(type_name); - w.write(format, + w.write( + format, bind(generics), type_name, bind_list(", ", generics), @@ -2730,7 +2697,8 @@ struct WINRT_IMPL_EMPTY_BASES produce_dispatch_to_overridable } )"; - w.write(format, + w.write( + format, type_name, type_name, type_name, @@ -2764,9 +2732,7 @@ struct WINRT_IMPL_EMPTY_BASES produce_dispatch_to_overridable static void write_struct_field(writer& w, std::pair const& field) { - w.write(" @ % {};\n", - field.second, - field.first); + w.write(" @ % {};\n", field.second, field.first); } static void write_struct_equality(writer& w, std::vector> const& fields) @@ -2805,8 +2771,7 @@ struct WINRT_IMPL_EMPTY_BASES produce_dispatch_to_overridable struct complex_struct { complex_struct(writer& w, TypeDef const& type) : - type(type), - is_noexcept(!has_reference(type)) + type(type), is_noexcept(!has_reference(type)) { for (auto&& field : type.FieldList()) { @@ -2873,7 +2838,8 @@ struct WINRT_IMPL_EMPTY_BASES produce_dispatch_to_overridable auto name = type.type.TypeName(); std::string_view is_noexcept = type.is_noexcept ? " noexcept" : ""; - w.write(format, + w.write( + format, name, bind_each(type.fields), name, @@ -3038,7 +3004,8 @@ struct WINRT_IMPL_EMPTY_BASES produce_dispatch_to_overridable { method_signature signature{ method }; - w.write(" %%(%);\n", + w.write( + " %%(%);\n", signature.params().size() == 1 ? "explicit " : "", type_name, bind(signature)); @@ -3053,7 +3020,8 @@ struct WINRT_IMPL_EMPTY_BASES produce_dispatch_to_overridable auto& params = signature.params(); params.resize(params.size() - 2); - w.write(" %%(%);\n", + w.write( + " %%(%);\n", signature.params().size() == 1 ? "explicit " : "", type_name, bind(signature)); @@ -3073,7 +3041,8 @@ struct WINRT_IMPL_EMPTY_BASES produce_dispatch_to_overridable } )"; - w.write(format, + w.write( + format, type_name, type_name, bind(signature), @@ -3098,7 +3067,8 @@ struct WINRT_IMPL_EMPTY_BASES produce_dispatch_to_overridable } )"; - w.write(format, + w.write( + format, type_name, type_name, bind(signature), @@ -3112,7 +3082,6 @@ struct WINRT_IMPL_EMPTY_BASES produce_dispatch_to_overridable inner_param); } - static void write_static_declaration(writer& w, std::pair const& factory, TypeDef const& type) { if (!factory.second.statics) @@ -3130,7 +3099,8 @@ struct WINRT_IMPL_EMPTY_BASES produce_dispatch_to_overridable if (is_opt_type) { - w.write(" %static % %(%);\n", + w.write( + " %static % %(%);\n", is_get_overload(method) ? "[[nodiscard]] " : "", signature.return_signature(), method_name, @@ -3138,7 +3108,8 @@ struct WINRT_IMPL_EMPTY_BASES produce_dispatch_to_overridable } else { - w.write(" %static auto %(%);\n", + w.write( + " %static auto %(%);\n", is_get_overload(method) ? "[[nodiscard]] " : "", method_name, bind(signature)); @@ -3149,29 +3120,20 @@ struct WINRT_IMPL_EMPTY_BASES produce_dispatch_to_overridable { auto format = R"( using %_revoker = impl::factory_event_revoker<%, &impl::abi_t<%>::remove_%>; )"; - w.write(format, - method_name, - factory.second.type, - factory.second.type, - method_name); + w.write(format, method_name, factory.second.type, factory.second.type, method_name); } if (is_opt_type) { auto format = R"( [[nodiscard]] static %_revoker %(auto_revoke_t, %); )"; - w.write(format, - method_name, - method_name, - bind(signature)); + w.write(format, method_name, method_name, bind(signature)); } else { auto format = R"( [[nodiscard]] static auto %(auto_revoke_t, %); )"; - w.write(format, - method_name, - bind(signature)); + w.write(format, method_name, bind(signature)); } } } @@ -3191,7 +3153,8 @@ struct WINRT_IMPL_EMPTY_BASES produce_dispatch_to_overridable } )"; - w.write(format, + w.write( + format, type_name, method_name, bind(signature), @@ -3208,7 +3171,8 @@ struct WINRT_IMPL_EMPTY_BASES produce_dispatch_to_overridable } )"; - w.write(format, + w.write( + format, type_name, method_name, bind(signature), @@ -3255,13 +3219,7 @@ struct WINRT_IMPL_EMPTY_BASES produce_dispatch_to_overridable )"; } - w.write(format, - type_name, - type_name, - type_name, - type_name, - type_name, - type_name); + w.write(format, type_name, type_name, type_name, type_name, type_name, type_name); } else { @@ -3291,7 +3249,8 @@ struct WINRT_IMPL_EMPTY_BASES produce_dispatch_to_overridable %%% }; )"; - w.write(format, + w.write( + format, type_name, base_type, bind(type), @@ -3316,7 +3275,8 @@ struct WINRT_IMPL_EMPTY_BASES produce_dispatch_to_overridable %%% }; )"; - w.write(format, + w.write( + format, type_name, base_type, bind(type), @@ -3339,10 +3299,7 @@ struct WINRT_IMPL_EMPTY_BASES produce_dispatch_to_overridable % }; )"; - w.write(format, - type_name, - type_name, - bind_each(factories, type)); + w.write(format, type_name, type_name, bind_each(factories, type)); } static void write_class(writer& w, TypeDef const& type) @@ -3368,9 +3325,7 @@ struct WINRT_IMPL_EMPTY_BASES produce_dispatch_to_overridable { auto generics = type.GenericParam(); - w.write(" template<%> struct hash<%> : winrt::impl::hash_base {};\n", - bind(generics), - type); + w.write(" template<%> struct hash<%> : winrt::impl::hash_base {};\n", bind(generics), type); } static void write_std_formatter(writer& w, TypeDef const& type) @@ -3379,7 +3334,8 @@ struct WINRT_IMPL_EMPTY_BASES produce_dispatch_to_overridable { auto generics = type.GenericParam(); - w.write(" template<%> struct formatter<%, wchar_t> : formatter {};\n", + w.write( + " template<%> struct formatter<%, wchar_t> : formatter {};\n", bind(generics), type); } @@ -3442,4 +3398,4 @@ struct WINRT_IMPL_EMPTY_BASES produce_dispatch_to_overridable w.write(strings::base_stringable_format_1); } } -} +} // namespace cppwinrt diff --git a/cppwinrt/component_writers.h b/cppwinrt/component_writers.h index 4a2cce556..7b6cfc73b 100644 --- a/cppwinrt/component_writers.h +++ b/cppwinrt/component_writers.h @@ -13,7 +13,7 @@ namespace cppwinrt continue; } - for (auto&&[name, info] : get_interfaces(w, base)) + for (auto&& [name, info] : get_interfaces(w, base)) { if (info.base) { @@ -112,10 +112,7 @@ namespace cppwinrt } )"; - w.write(format, - type_namespace, - type_name, - impl_name); + w.write(format, type_namespace, type_name, impl_name); } else { @@ -126,11 +123,7 @@ namespace cppwinrt } )"; - w.write(format, - type_namespace, - type_name, - type_namespace, - type_name); + w.write(format, type_namespace, type_name, type_namespace, type_name); } } @@ -160,7 +153,8 @@ void* __stdcall %_get_activation_factory([[maybe_unused]] std::wstring_view cons } )"; - w.write(format, + w.write( + format, bind_each(classes), settings.component_lib, settings.component_lib, @@ -203,16 +197,14 @@ int32_t __stdcall WINRT_GetActivationFactory(void* classId, void** factory) noex catch (...) { return winrt::to_hresult(); } )"; - w.write(format, - settings.component_lib, - settings.component_lib); + w.write(format, settings.component_lib, settings.component_lib); } static void write_component_interfaces(writer& w, TypeDef const& type) { bool const fastabi = has_fastabi(type); - for (auto&&[interface_name, info] : get_interfaces(w, type)) + for (auto&& [interface_name, info] : get_interfaces(w, type)) { if (!info.base && !info.is_default && !is_always_disabled(info.type)) { @@ -242,7 +234,7 @@ catch (...) { return winrt::to_hresult(); } w.write(", composing"); - for (auto&&[interface_name, info] : get_interfaces(w, base_type)) + for (auto&& [interface_name, info] : get_interfaces(w, base_type)) { if (info.overridable && !is_always_disabled(info.type)) { @@ -265,7 +257,8 @@ catch (...) { return winrt::to_hresult(); } std::rotate(params.begin(), params.end() - 2, params.end()); w.param_names = true; - w.write(format, + w.write( + format, get_name(method), bind(signature), signature.return_signature(), @@ -283,10 +276,7 @@ catch (...) { return winrt::to_hresult(); } method_signature signature{ method }; w.param_names = true; - w.write(format, - get_name(method), - bind(signature), - bind(signature)); + w.write(format, get_name(method), bind(signature), bind(signature)); } static void write_component_static_forwarder(writer& w, MethodDef const& method) @@ -300,18 +290,14 @@ catch (...) { return winrt::to_hresult(); } method_signature signature{ method }; w.param_names = true; - w.write(format, - get_name(method), - bind(signature), - get_name(method), - bind(signature)); + w.write(format, get_name(method), bind(signature), get_name(method), bind(signature)); } static void write_component_forwarders(writer& w, std::map const& factories) { bool default_constructor{}; - for (auto&&[factory_name, factory] : factories) + for (auto&& [factory_name, factory] : factories) { if (factory.type && is_always_disabled(factory.type)) { @@ -357,13 +343,13 @@ catch (...) { return winrt::to_hresult(); } static void write_component_factory_interfaces(writer& w, std::map const& factories) { - for (auto&&[factory_name, factory] : factories) + for (auto&& [factory_name, factory] : factories) { if (!factory.type || is_always_disabled(factory.type)) { continue; } - + w.write(", %", factory_name); } } @@ -382,10 +368,7 @@ catch (...) { return winrt::to_hresult(); } } )"; - w.write(format, - impl_name, - type_namespace, - type_name); + w.write(format, impl_name, type_namespace, type_name); } if (!settings.component_opt) @@ -395,7 +378,7 @@ catch (...) { return winrt::to_hresult(); } auto wrap_type = wrap_type_namespace(w, type_namespace); - for (auto&&[factory_name, factory] : get_factories(w, type)) + for (auto&& [factory_name, factory] : get_factories(w, type)) { if (factory.type && is_always_disabled(factory.type)) { @@ -412,12 +395,7 @@ catch (...) { return winrt::to_hresult(); } } )"; - w.write(format, - type_name, - type_name, - type_name, - type_namespace, - type_name); + w.write(format, type_name, type_name, type_name, type_namespace, type_name); } else { @@ -431,7 +409,8 @@ catch (...) { return winrt::to_hresult(); } } )"; - w.write(format, + w.write( + format, type_name, type_name, bind(signature), @@ -456,7 +435,8 @@ catch (...) { return winrt::to_hresult(); } } )"; - w.write(format, + w.write( + format, type_name, type_name, bind(signature), @@ -483,7 +463,8 @@ catch (...) { return winrt::to_hresult(); } } )"; - w.write(format, + w.write( + format, signature.return_signature(), type_name, method_name, @@ -504,7 +485,8 @@ catch (...) { return winrt::to_hresult(); } bool ignore_return = is_put_overload(method) || !signature.return_signature(); - w.write(format, + w.write( + format, signature.return_signature(), type_name, method_name, @@ -525,7 +507,8 @@ catch (...) { return winrt::to_hresult(); } } )"; - w.write(format, + w.write( + format, type_name, method_name, type_name, @@ -594,7 +577,7 @@ catch (...) { return winrt::to_hresult(); } auto type_name = type.TypeName(); - for (auto&&[factory_name, factory] : get_factories(w, base_type)) + for (auto&& [factory_name, factory] : get_factories(w, base_type)) { if (!factory.composable || is_always_disabled(factory.type)) { @@ -613,7 +596,8 @@ catch (...) { return winrt::to_hresult(); } } )"; - w.write(format, + w.write( + format, type_name, bind(signature), base_type, @@ -661,10 +645,7 @@ catch (...) { return winrt::to_hresult(); } break; } - w.write(format, - name, - name, - offset); + w.write(format, name, name, offset); auto methods = info.type.MethodList(); offset += methods.second - methods.first; @@ -780,7 +761,7 @@ catch (...) { return winrt::to_hresult(); } external_requires = ",\n impl::require(factories), @@ -909,17 +892,12 @@ namespace winrt::@::implementation )"; std::string upper(type_name); - std::transform(upper.begin(), upper.end(), upper.begin(), [](char c) {return static_cast(::toupper(c)); }); + std::transform( + upper.begin(), upper.end(), upper.begin(), [](char c) { return static_cast(::toupper(c)); }); auto include_path = get_generated_component_filename(type); - w.write(format, - upper, - include_path, - include_path, - type_namespace, - type_name, - type_name); + w.write(format, upper, include_path, include_path, type_namespace, type_name, type_name); } } @@ -935,11 +913,7 @@ namespace winrt::@::implementation if (base_type && settings.component_filter.includes(base_type)) { - w.write(" : %T<%, @::implementation::%>", - type_name, - type_name, - base_type.TypeNamespace(), - base_type.TypeName()); + w.write(" : %T<%, @::implementation::%>", type_name, type_name, base_type.TypeNamespace(), base_type.TypeName()); } else { @@ -951,7 +925,7 @@ namespace winrt::@::implementation { auto type_name = type.TypeName(); - for (auto&&[factory_name, factory] : get_factories(w, type)) + for (auto&& [factory_name, factory] : get_factories(w, type)) { if (factory.activatable || factory.composable) { @@ -975,9 +949,7 @@ namespace winrt::@::implementation continue; } - w.write(" %(%);\n", - type_name, - bind(signature)); + w.write(" %(%);\n", type_name, bind(signature)); } } else if (factory.statics) @@ -988,7 +960,8 @@ namespace winrt::@::implementation w.async_types = signature.is_async(); auto method_name = get_name(method); - w.write(" static % %(%)%;\n", + w.write( + " static % %(%)%;\n", signature.return_signature(), method_name, bind(signature), @@ -997,14 +970,15 @@ namespace winrt::@::implementation } } - for (auto&&[interface_name, info] : get_interfaces(w, type)) + for (auto&& [interface_name, info] : get_interfaces(w, type)) { if (info.base) { continue; } - w.generic_param_stack.insert(w.generic_param_stack.end(), info.generic_param_stack.begin(), info.generic_param_stack.end()); + w.generic_param_stack.insert( + w.generic_param_stack.end(), info.generic_param_stack.begin(), info.generic_param_stack.end()); for (auto&& method : info.type.MethodList()) { @@ -1012,7 +986,8 @@ namespace winrt::@::implementation w.async_types = signature.is_async(); auto method_name = get_name(method); - w.write(" % %(%)%;\n", + w.write( + " % %(%)%;\n", signature.return_signature(), method_name, bind(signature), @@ -1074,7 +1049,8 @@ namespace winrt::@::implementation } )"; - w.write(format, + w.write( + format, get_generated_component_filename(type), base_include, bind(), @@ -1083,7 +1059,6 @@ namespace winrt::@::implementation bind(type), type_name, bind(type)); - } if (has_factory_members(w, type)) @@ -1095,12 +1070,7 @@ namespace winrt::@::implementation }; } )"; - w.write(format, - type_namespace, - type_name, - type_name, - type_name, - type_name); + w.write(format, type_namespace, type_name, type_name, type_name, type_name); } } @@ -1108,7 +1078,7 @@ namespace winrt::@::implementation { auto type_name = type.TypeName(); - for (auto&&[factory_name, factory] : get_factories(w, type)) + for (auto&& [factory_name, factory] : get_factories(w, type)) { if (factory.activatable || factory.composable) { @@ -1138,10 +1108,7 @@ namespace winrt::@::implementation continue; } - w.write(format, - type_name, - type_name, - bind(signature)); + w.write(format, type_name, type_name, bind(signature)); } } else if (factory.statics) @@ -1158,7 +1125,8 @@ namespace winrt::@::implementation w.async_types = signature.is_async(); auto method_name = get_name(method); - w.write(format, + w.write( + format, signature.return_signature(), type_name, method_name, @@ -1168,14 +1136,15 @@ namespace winrt::@::implementation } } - for (auto&&[interface_name, info] : get_interfaces(w, type)) + for (auto&& [interface_name, info] : get_interfaces(w, type)) { if (info.base) { continue; } - w.generic_param_stack.insert(w.generic_param_stack.end(), info.generic_param_stack.begin(), info.generic_param_stack.end()); + w.generic_param_stack.insert( + w.generic_param_stack.end(), info.generic_param_stack.begin(), info.generic_param_stack.end()); for (auto&& method : info.type.MethodList()) { @@ -1189,7 +1158,8 @@ namespace winrt::@::implementation w.async_types = signature.is_async(); auto method_name = get_name(method); - w.write(format, + w.write( + format, signature.return_signature(), type_name, method_name, @@ -1228,10 +1198,7 @@ namespace winrt::@::implementation %} )"; - w.write(format, - bind(), - type.TypeNamespace(), - bind(type)); + w.write(format, bind(), type.TypeNamespace(), bind(type)); } static void write_component_fast_abi_thunk(writer& w) @@ -1254,9 +1221,7 @@ namespace winrt::@::implementation winrt_ff_thunk%, #endif )"; - w.write(format, - slot, - slot); + w.write(format, slot, slot); } } -} +} // namespace cppwinrt diff --git a/cppwinrt/file_writers.h b/cppwinrt/file_writers.h index ed9386b4e..249bc2524 100644 --- a/cppwinrt/file_writers.h +++ b/cppwinrt/file_writers.h @@ -55,12 +55,12 @@ namespace cppwinrt auto const fast_abi_size = get_fastabi_size(w, classes); - w.write(strings::base_fast_forward, + w.write( + strings::base_fast_forward, fast_abi_size, fast_abi_size, bind(), bind()); - } w.flush_to_file(settings.output_folder + "winrt/fast_forward.h"); } @@ -209,7 +209,7 @@ namespace cppwinrt { auto wrap_format = wrap_ifdef(w, "__cpp_lib_format"); w.write_each(members.interfaces); - w.write_each(members.classes); + w.write_each(members.classes); } } @@ -319,4 +319,4 @@ namespace cppwinrt write_component_cpp(w, type); w.flush_to_file(path); } -} +} // namespace cppwinrt diff --git a/cppwinrt/helpers.h b/cppwinrt/helpers.h index 522d0bcd1..f781bc87e 100644 --- a/cppwinrt/helpers.h +++ b/cppwinrt/helpers.h @@ -20,8 +20,7 @@ namespace cppwinrt struct method_signature { explicit method_signature(MethodDef const& method) : - m_method(method), - m_signature(method.Signature()) + m_method(method), m_signature(method.Signature()) { auto params = method.ParamList(); @@ -75,11 +74,11 @@ namespace cppwinrt bool is_async() const { - // WinRT parameter passing conventions include the notion that input parameters of collection types may be read - // or copied but should not be stored directly since this would lead to instability as the collection is shared - // by the caller and callee. The exception to this rule is property setters where the callee may simply store a - // reference to the collection. The collection thus becomes async in the sense that it is expected to remain - // valid beyond the duration of the call. + // WinRT parameter passing conventions include the notion that input parameters of collection types may be + // read or copied but should not be stored directly since this would lead to instability as the collection + // is shared by the caller and callee. The exception to this rule is property setters where the callee may + // simply store a reference to the collection. The collection thus becomes async in the sense that it is + // expected to remain valid beyond the duration of the call. if (is_put_overload(m_method)) { @@ -93,7 +92,8 @@ namespace cppwinrt bool async{}; - call(m_signature.ReturnType().Type().Type(), + call( + m_signature.ReturnType().Type().Type(), [&](coded_index const& type) { auto const& [type_namespace, type_name] = get_type_namespace_and_name(type); @@ -105,19 +105,16 @@ namespace cppwinrt if (type_namespace == "Windows.Foundation") { - async = - type_name == "IAsyncOperation`1" || - type_name == "IAsyncActionWithProgress`1" || - type_name == "IAsyncOperationWithProgress`2"; + async = type_name == "IAsyncOperation`1" || type_name == "IAsyncActionWithProgress`1" || + type_name == "IAsyncOperationWithProgress`2"; } }, - [](auto&&) {}); + [](auto&&) {}); return async; } private: - MethodDef m_method; MethodDefSig m_signature; std::vector> m_params; @@ -150,50 +147,45 @@ namespace cppwinrt namespace impl { - template - struct variant_index; + template struct variant_index; - template - struct variant_index + template struct variant_index { static constexpr bool found = std::is_same_v; - static constexpr std::size_t value = std::conditional_t, - variant_index>::value + (found ? 0 : 1); + static constexpr std::size_t value = + std::conditional_t, variant_index>::value + + (found ? 0 : 1); }; - } + } // namespace impl - template - struct variant_index; + template struct variant_index; template struct variant_index, T> : impl::variant_index - { - }; + {}; - template - constexpr std::size_t variant_index_v = variant_index::value; + template constexpr std::size_t variant_index_v = variant_index::value; - template - auto get_integer_attribute(FixedArgSig const& signature) + template auto get_integer_attribute(FixedArgSig const& signature) { auto variant = std::get(signature.value).value; switch (variant.index()) { - case variant_index_v>: return static_cast(std::get>(variant)); - case variant_index_v>: return static_cast(std::get>(variant)); - default: return std::get(variant); // Likely throws, but that's intentional + case variant_index_v>: + return static_cast(std::get>(variant)); + case variant_index_v>: + return static_cast(std::get>(variant)); + default: + return std::get(variant); // Likely throws, but that's intentional } } - template - auto get_attribute_value(FixedArgSig const& signature) + template auto get_attribute_value(FixedArgSig const& signature) { return std::get(std::get(signature.value).value); } - template - auto get_attribute_value(CustomAttribute const& attribute, uint32_t const arg) + template auto get_attribute_value(CustomAttribute const& attribute, uint32_t const arg) { return get_attribute_value(attribute.Value().FixedArgs()[arg]); } @@ -244,7 +236,7 @@ namespace cppwinrt static bool has_fastabi(TypeDef const& type) { - return settings.fastabi&& has_attribute(type, "Windows.Foundation.Metadata", "FastAbiAttribute"); + return settings.fastabi && has_attribute(type, "Windows.Foundation.Metadata", "FastAbiAttribute"); } static bool is_always_disabled(TypeDef const& type) @@ -303,10 +295,10 @@ namespace cppwinrt auto extends = derived.Extends(); if (!extends) { - return{}; + return {}; } - auto const&[extends_namespace, extends_name] = get_type_namespace_and_name(extends); + auto const& [extends_namespace, extends_name] = get_type_namespace_and_name(extends); if (extends_name == "Object" && extends_namespace == "System") { return {}; @@ -314,7 +306,6 @@ namespace cppwinrt return find_required(extends); }; - static auto get_bases(TypeDef const& type) { std::vector bases; @@ -360,19 +351,11 @@ namespace cppwinrt contract_version result{}; result.version = get_integer_attribute(args[1]); - call(std::get(args[0].value).value, - [&](ElemSig::SystemType t) - { - result.name = t.name; - }, - [&](std::string_view name) - { - result.name = name; - }, - [](auto&&) - { - assert(false); - }); + call( + std::get(args[0].value).value, + [&](ElemSig::SystemType t) { result.name = t.name; }, + [&](std::string_view name) { result.name = name; }, + [](auto&&) { assert(false); }); return result; } @@ -433,10 +416,10 @@ namespace cppwinrt if (!prev.contract_to.empty()) { - auto itr = std::find_if(previous_contracts.begin(), previous_contracts.end(), [&](auto const& ver) - { - return ver.name == prev.contract_to; - }); + auto itr = std::find_if( + previous_contracts.begin(), + previous_contracts.end(), + [&](auto const& ver) { return ver.name == prev.contract_to; }); if (itr != previous_contracts.end()) { *itr = previous_contracts.back(); @@ -512,10 +495,10 @@ namespace cppwinrt for (size_t size = result.previous_contracts.size() - 1; size; --size) { auto& last = result.previous_contracts[size]; - auto itr = std::find_if(result.previous_contracts.begin(), result.previous_contracts.begin() + size, [&](auto const& prev) - { - return prev.contract_to == last.contract_from; - }); + auto itr = std::find_if( + result.previous_contracts.begin(), + result.previous_contracts.begin() + size, + [&](auto const& prev) { return prev.contract_to == last.contract_from; }); assert(itr != result.previous_contracts.end()); std::swap(*itr, result.previous_contracts[size - 1]); } @@ -545,10 +528,7 @@ namespace cppwinrt static interface_info* find(get_interfaces_t& interfaces, std::string_view const& name) { - auto pair = std::find_if(interfaces.begin(), interfaces.end(), [&](auto&& pair) - { - return pair.first == name; - }); + auto pair = std::find_if(interfaces.begin(), interfaces.end(), [&](auto&& pair) { return pair.first == name; }); if (pair == interfaces.end()) { @@ -570,7 +550,14 @@ namespace cppwinrt } } - static void get_interfaces_impl(writer& w, get_interfaces_t& result, bool defaulted, bool overridable, bool base, std::vector> const& generic_param_stack, std::pair&& children) + static void get_interfaces_impl( + writer& w, + get_interfaces_t& result, + bool defaulted, + bool overridable, + bool base, + std::vector> const& generic_param_stack, + std::pair&& children) { for (auto&& impl : children) { @@ -605,40 +592,41 @@ namespace cppwinrt switch (type.type()) { - case TypeDefOrRef::TypeDef: - { - info.type = type.TypeDef(); - break; - } - case TypeDefOrRef::TypeRef: - { - info.type = find_required(type.TypeRef()); - w.add_depends(info.type); - break; - } - case TypeDefOrRef::TypeSpec: - { - auto type_signature = type.TypeSpec().Signature(); + case TypeDefOrRef::TypeDef: + { + info.type = type.TypeDef(); + break; + } + case TypeDefOrRef::TypeRef: + { + info.type = find_required(type.TypeRef()); + w.add_depends(info.type); + break; + } + case TypeDefOrRef::TypeSpec: + { + auto type_signature = type.TypeSpec().Signature(); - std::vector names; + std::vector names; - for (auto&& arg : type_signature.GenericTypeInst().GenericArgs()) - { - names.push_back(w.write_temp("%", arg)); - } + for (auto&& arg : type_signature.GenericTypeInst().GenericArgs()) + { + names.push_back(w.write_temp("%", arg)); + } - info.generic_param_stack.push_back(std::move(names)); + info.generic_param_stack.push_back(std::move(names)); - guard = w.push_generic_params(type_signature.GenericTypeInst()); - auto signature = type_signature.GenericTypeInst(); - info.type = find_required(signature.GenericType()); + guard = w.push_generic_params(type_signature.GenericTypeInst()); + auto signature = type_signature.GenericTypeInst(); + info.type = find_required(signature.GenericType()); - break; - } + break; + } } info.exclusive = has_attribute(info.type, "Windows.Foundation.Metadata", "ExclusiveToAttribute"); - get_interfaces_impl(w, result, info.defaulted, info.overridable, base, info.generic_param_stack, info.type.InterfaceImpl()); + get_interfaces_impl( + w, result, info.defaulted, info.overridable, base, info.generic_param_stack, info.type.InterfaceImpl()); insert_or_assign(result, name, std::move(info)); } }; @@ -670,10 +658,10 @@ namespace cppwinrt auto introduced = get_initial_contract_version(pair.second.type); pair.second.relative_version.second = introduced.version; - auto itr = std::find_if(history.previous_contracts.begin(), history.previous_contracts.end(), [&](previous_contract const& prev) - { - return prev.contract_from == introduced.name; - }); + auto itr = std::find_if( + history.previous_contracts.begin(), + history.previous_contracts.end(), + [&](previous_contract const& prev) { return prev.contract_from == introduced.name; }); if (itr != history.previous_contracts.end()) { pair.second.relative_version.first = static_cast(itr - history.previous_contracts.begin()); @@ -686,52 +674,53 @@ namespace cppwinrt } } - std::partial_sort(result.begin(), result.begin() + count, result.end(), [](auto&& left_pair, auto&& right_pair) - { - auto& left = left_pair.second; - auto& right = right_pair.second; - - // Sort by base before is_default because each base will have a default. - if (left.base != right.base) + std::partial_sort( + result.begin(), + result.begin() + count, + result.end(), + [](auto&& left_pair, auto&& right_pair) { - return !left.base; - } + auto& left = left_pair.second; + auto& right = right_pair.second; - if (left.is_default != right.is_default) - { - return left.is_default; - } + // Sort by base before is_default because each base will have a default. + if (left.base != right.base) + { + return !left.base; + } - if (left.overridable != right.overridable) - { - return !left.overridable; - } + if (left.is_default != right.is_default) + { + return left.is_default; + } - if (left.exclusive != right.exclusive) - { - return left.exclusive; - } + if (left.overridable != right.overridable) + { + return !left.overridable; + } - auto left_enabled = is_always_enabled(left.type); - auto right_enabled = is_always_enabled(right.type); + if (left.exclusive != right.exclusive) + { + return left.exclusive; + } - if (left_enabled != right_enabled) - { - return left_enabled; - } + auto left_enabled = is_always_enabled(left.type); + auto right_enabled = is_always_enabled(right.type); - if (left.relative_version != right.relative_version) - { - return left.relative_version < right.relative_version; - } + if (left_enabled != right_enabled) + { + return left_enabled; + } + + if (left.relative_version != right.relative_version) + { + return left.relative_version < right.relative_version; + } - return left_pair.first < right_pair.first; - }); + return left_pair.first < right_pair.first; + }); - std::for_each_n(result.begin(), count, [](auto && pair) - { - pair.second.fastabi = true; - }); + std::for_each_n(result.begin(), count, [](auto&& pair) { pair.second.fastabi = true; }); return result; } @@ -906,7 +895,8 @@ namespace cppwinrt param_category result{}; - call(signature.Type(), + call( + signature.Type(), [&](ElementType type) { if (type == ElementType::String) @@ -963,14 +953,8 @@ namespace cppwinrt return; } }, - [&](GenericTypeInstSig const&) - { - result = param_category::object_type; - }, - [&](auto&&) - { - result = param_category::generic_type; - }); + [&](GenericTypeInstSig const&) { result = param_category::object_type; }, + [&](auto&&) { result = param_category::generic_type; }); return result; } @@ -979,14 +963,15 @@ namespace cppwinrt { bool object{}; - call(signature.Type(), + call( + signature.Type(), [&](ElementType type) - { - if (type == ElementType::Object) { - object = true; - } - }, + if (type == ElementType::Object) + { + object = true; + } + }, [](auto&&) {}); return object; @@ -996,10 +981,7 @@ namespace cppwinrt { auto methods = type.MethodList(); - auto method = std::find_if(begin(methods), end(methods), [](auto&& method) - { - return method.Name() == "Invoke"; - }); + auto method = std::find_if(begin(methods), end(methods), [](auto&& method) { return method.Name() == "Invoke"; }); if (method == end(methods)) { @@ -1067,7 +1049,7 @@ namespace cppwinrt static bool has_factory_members(writer& w, TypeDef const& type) { - for (auto&&[factory_name, factory] : get_factories(w, type)) + for (auto&& [factory_name, factory] : get_factories(w, type)) { if (!factory.type || !empty(factory.type.MethodList())) { @@ -1080,7 +1062,7 @@ namespace cppwinrt static bool is_composable(writer& w, TypeDef const& type) { - for (auto&&[factory_name, factory] : get_factories(w, type)) + for (auto&& [factory_name, factory] : get_factories(w, type)) { if (factory.composable) { @@ -1093,7 +1075,7 @@ namespace cppwinrt static bool has_composable_constructors(writer& w, TypeDef const& type) { - for (auto&&[interface_name, factory] : get_factories(w, type)) + for (auto&& [interface_name, factory] : get_factories(w, type)) { if (factory.composable && !empty(factory.type.MethodList())) { @@ -1106,12 +1088,8 @@ namespace cppwinrt static bool has_projected_types(cache::namespace_members const& members) { - return - !members.interfaces.empty() || - !members.classes.empty() || - !members.enums.empty() || - !members.structs.empty() || - !members.delegates.empty(); + return !members.interfaces.empty() || !members.classes.empty() || !members.enums.empty() || + !members.structs.empty() || !members.delegates.empty(); } static bool can_produce(TypeDef const& type, cache const& c) @@ -1145,4 +1123,4 @@ namespace cppwinrt return settings.component_filter.includes(class_name); } -} +} // namespace cppwinrt diff --git a/cppwinrt/main.cpp b/cppwinrt/main.cpp index 70a55b076..155f75f0e 100644 --- a/cppwinrt/main.cpp +++ b/cppwinrt/main.cpp @@ -13,10 +13,10 @@ namespace cppwinrt { settings_type settings; - struct usage_exception {}; + struct usage_exception + {}; - static constexpr option options[] - { + static constexpr option options[]{ { "input", 0, option::no_max, "", "Windows metadata to include in projection" }, { "reference", 0, option::no_max, "", "Windows metadata to reference from projection" }, { "output", 0, 1, "", "Location of generated projection and component templates" }, @@ -35,8 +35,8 @@ namespace cppwinrt { "library", 0, 1, "", "Specify library prefix (defaults to winrt)" }, { "filter" }, // One or more prefixes to include in input (same as -include) { "license", 0, 1, "[]", "Generate license comment from template file" }, - { "brackets", 0, 0 }, // Use angle brackets for #includes (defaults to quotes) - { "fastabi", 0, 0 }, // Enable support for the Fast ABI + { "brackets", 0, 0 }, // Use angle brackets for #includes (defaults to quotes) + { "fastabi", 0, 0 }, // Enable support for the Fast ABI { "ignore_velocity", 0, 0 }, // Ignore feature staging metadata and always include implementations { "synchronous", 0, 0 }, // Instructs cppwinrt to run on a single thread to avoid file system issues in batch builds }; @@ -50,7 +50,7 @@ namespace cppwinrt static auto printOption = [](writer& w, option const& opt) { - if(opt.desc.empty()) + if (opt.desc.empty()) { return; } @@ -72,12 +72,12 @@ Where is one or more of: path Path to winmd file or recursively scanned folder )" #if defined(_WIN32) || defined(_WIN64) -R"( local Local ^%WinDir^%\System32\WinMetadata folder + R"( local Local ^%WinDir^%\System32\WinMetadata folder sdk[+] Current version of Windows SDK [with extensions] 10.0.12345.0[+] Specific version of Windows SDK [with extensions] )" #endif - ; + ; w.write(format, CPPWINRT_VERSION_STRING, bind_each(printOption, options)); } @@ -100,17 +100,17 @@ R"( local Local ^%WinDir^%\System32\WinMetadata folder settings.output_folder = canonical(output_folder).string(); settings.output_folder += std::filesystem::path::preferred_separator; - for (auto && include : args.values("include")) + for (auto&& include : args.values("include")) { settings.include.insert(include); } - for (auto && include : args.values("filter")) + for (auto&& include : args.values("filter")) { settings.include.insert(include); } - for (auto && exclude : args.values("exclude")) + for (auto&& exclude : args.values("exclude")) { settings.exclude.insert(exclude); } @@ -208,10 +208,8 @@ R"( local Local ^%WinDir^%\System32\WinMetadata folder for (auto file : settings.input) { - auto db = std::find_if(c.databases().begin(), c.databases().end(), [&](auto&& db) - { - return db.path() == file; - }); + auto db = + std::find_if(c.databases().begin(), c.databases().end(), [&](auto&& db) { return db.path() == file; }); for (auto&& type : db->TypeDef) { @@ -228,7 +226,7 @@ R"( local Local ^%WinDir^%\System32\WinMetadata folder } settings.projection_filter = { include, {} }; - + settings.component_filter = { settings.include.empty() ? include : settings.include, settings.exclude }; } @@ -298,7 +296,11 @@ R"( local Local ^%WinDir^%\System32\WinMetadata folder } process_args(args); - cache c{ get_files_to_cache(), [](TypeDef const& type) { return type.Flags().WindowsRuntime(); } }; + cache c{ get_files_to_cache(), + [](TypeDef const& type) + { + return type.Flags().WindowsRuntime(); + } }; remove_foundation_types(c); build_filters(c); settings.base = settings.base || (!settings.component && settings.projection_filter.empty()); @@ -348,7 +350,7 @@ R"( local Local ^%WinDir^%\System32\WinMetadata folder ixx.write(strings::base_includes); ixx.write("\nexport module winrt;\n#define WINRT_EXPORT export\n\n"); - for (auto&&[ns, members] : c.namespaces()) + for (auto&& [ns, members] : c.namespaces()) { if (!has_projected_types(members) || !settings.projection_filter.includes(members)) { @@ -357,13 +359,14 @@ R"( local Local ^%WinDir^%\System32\WinMetadata folder ixx.write("#include \"winrt/%.h\"\n", ns); - group.add([&, &ns = ns, &members = members] - { - write_namespace_0_h(ns, members); - write_namespace_1_h(ns, members); - write_namespace_2_h(ns, members); - write_namespace_h(c, ns, members); - }); + group.add( + [&, &ns = ns, &members = members] + { + write_namespace_0_h(ns, members); + write_namespace_1_h(ns, members); + write_namespace_2_h(ns, members); + write_namespace_h(c, ns, members); + }); } if (settings.base) @@ -376,7 +379,7 @@ R"( local Local ^%WinDir^%\System32\WinMetadata folder { std::vector classes; - for (auto&&[ns, members] : c.namespaces()) + for (auto&& [ns, members] : c.namespaces()) { for (auto&& type : members.classes) { @@ -422,7 +425,7 @@ R"( local Local ^%WinDir^%\System32\WinMetadata folder w.flush_to_console(result == 0); return result; } -} +} // namespace cppwinrt int main(int const argc, char** argv) { diff --git a/cppwinrt/settings.h b/cppwinrt/settings.h index e07df4ea2..2f53a27d5 100644 --- a/cppwinrt/settings.h +++ b/cppwinrt/settings.h @@ -34,4 +34,4 @@ namespace cppwinrt }; extern settings_type settings; -} +} // namespace cppwinrt diff --git a/cppwinrt/task_group.h b/cppwinrt/task_group.h index 800b8eb40..bba2612f6 100644 --- a/cppwinrt/task_group.h +++ b/cppwinrt/task_group.h @@ -22,8 +22,7 @@ namespace cppwinrt m_synchronous = synchronous; } - template - void add(T&& callback) + template void add(T&& callback) { if (m_synchronous) { @@ -51,8 +50,7 @@ namespace cppwinrt } private: - std::vector> m_tasks; bool m_synchronous{}; }; -} +} // namespace cppwinrt diff --git a/cppwinrt/text_writer.h b/cppwinrt/text_writer.h index 0b7c07a4e..f339a277c 100644 --- a/cppwinrt/text_writer.h +++ b/cppwinrt/text_writer.h @@ -16,8 +16,7 @@ namespace cppwinrt return static_cast(std::stringstream() << file.rdbuf()).str(); } - template - struct writer_base + template struct writer_base { writer_base(writer_base const&) = delete; writer_base& operator=(writer_base const&) = delete; @@ -27,8 +26,7 @@ namespace cppwinrt m_first.reserve(16 * 1024); } - template - void write(std::string_view const& value, Args const&... args) + template void write(std::string_view const& value, Args const&... args) { #if defined(_DEBUG) auto expected = count_placeholders(value); @@ -38,8 +36,7 @@ namespace cppwinrt write_segment(value, args...); } - template - std::string write_temp(std::string_view const& value, Args const&... args) + template std::string write_temp(std::string_view const& value, Args const&... args) { #if defined(_DEBUG) bool restore_debug_trace = debug_trace; @@ -98,8 +95,7 @@ namespace cppwinrt write(value); } - template >> - void write(F const& f) + template >> void write(F const& f) { f(*static_cast(this)); } @@ -134,8 +130,7 @@ namespace cppwinrt write(std::to_string(value)); } - template - void write_printf(char const* format, Args const&... args) + template void write_printf(char const* format, Args const&... args) { char buffer[128]; #if defined(_WIN32) || defined(_WIN64) @@ -151,8 +146,7 @@ namespace cppwinrt write(std::string_view{ buffer, size }); } - template - void write_each(List const& list, Args const&... args) + template void write_each(List const& list, Args const&... args) { for (auto&& item : list) { @@ -181,13 +175,13 @@ namespace cppwinrt file.exceptions(std::ofstream::failbit | std::ofstream::badbit); try { - file.open(filename, std::ios::out | std::ios::binary); - file.write(m_first.data(), m_first.size()); - file.write(m_second.data(), m_second.size()); + file.open(filename, std::ios::out | std::ios::binary); + file.write(m_first.data(), m_first.size()); + file.write(m_second.data(), m_second.size()); } catch (std::ofstream::failure const& e) { - throw std::filesystem::filesystem_error(e.what(), filename, std::io_errc::stream); + throw std::filesystem::filesystem_error(e.what(), filename, std::io_errc::stream); } } m_first.clear(); @@ -242,7 +236,6 @@ namespace cppwinrt #endif private: - static constexpr uint32_t count_placeholders(std::string_view const& format) noexcept { uint32_t count{}; @@ -326,13 +319,12 @@ namespace cppwinrt std::vector m_first; }; - - template - struct indented_writer_base : writer_base + template struct indented_writer_base : writer_base { struct indent_guard { - indent_guard(indented_writer_base& w, int32_t offset = 1) noexcept : m_writer(w), m_offset(offset) + indent_guard(indented_writer_base& w, int32_t offset = 1) noexcept : + m_writer(w), m_offset(offset) { m_writer.m_indent += m_offset; } @@ -347,7 +339,6 @@ namespace cppwinrt int32_t m_offset{}; }; - void write_indent() { for (int32_t i = 0; i < m_indent; i++) @@ -405,8 +396,7 @@ namespace cppwinrt writer_base::write_impl(value); } - template - std::string write_temp(std::string_view const& value, Args const& ... args) + template std::string write_temp(std::string_view const& value, Args const&... args) { auto restore_indent = m_indent; m_indent = 0; @@ -421,9 +411,7 @@ namespace cppwinrt int32_t m_indent{}; }; - - template - auto bind(Args&&... args) + template auto bind(Args&&... args) { return [&](auto& writer) { @@ -431,8 +419,7 @@ namespace cppwinrt }; } - template - auto bind(F fwrite, Args const&... args) + template auto bind(F fwrite, Args const&... args) { return [&, fwrite](auto& writer) { @@ -440,8 +427,7 @@ namespace cppwinrt }; } - template - auto bind_each(List const& list, Args const&... args) + template auto bind_each(List const& list, Args const&... args) { return [&](auto& writer) { @@ -452,8 +438,7 @@ namespace cppwinrt }; } - template - auto bind_each(List const& list, Args const&... args) + template auto bind_each(List const& list, Args const&... args) { return [&](auto& writer) { @@ -499,8 +484,7 @@ namespace cppwinrt }; } - template - auto bind_list(std::string_view const& delimiter, T const& list) + template auto bind_list(std::string_view const& delimiter, T const& list) { return [&](auto& writer) { @@ -521,4 +505,4 @@ namespace cppwinrt } }; } -} +} // namespace cppwinrt diff --git a/cppwinrt/type_writers.h b/cppwinrt/type_writers.h index 0fa3e5f8d..1243dbbf0 100644 --- a/cppwinrt/type_writers.h +++ b/cppwinrt/type_writers.h @@ -11,10 +11,12 @@ namespace cppwinrt return 0 == value.compare(0, match.size(), match); } - template struct visit_overload : T... { using T::operator()...; }; + template struct visit_overload : T... + { + using T::operator()...; + }; - template - auto call(V&& variant, C&&...call) + template auto call(V&& variant, C&&... call) { return std::visit(visit_overload{ std::forward(call)... }, std::forward(variant)); } @@ -25,16 +27,12 @@ namespace cppwinrt std::string_view name_space; explicit type_name(TypeDef const& type) : - name(type.TypeName()), - name_space(type.TypeNamespace()) - { - } + name(type.TypeName()), name_space(type.TypeNamespace()) + {} explicit type_name(TypeRef const& type) : - name(type.TypeName()), - name_space(type.TypeNamespace()) - { - } + name(type.TypeName()), name_space(type.TypeNamespace()) + {} explicit type_name(coded_index const& type) { @@ -74,8 +72,7 @@ namespace cppwinrt return name.substr(0, name.rfind('`')); } - template - auto get_impl_name(First const& first, Rest const&... rest) + template auto get_impl_name(First const& first, Rest const&... rest) { std::string result; @@ -94,13 +91,41 @@ namespace cppwinrt static bool transform_special_numeric_type(std::string_view& name) { - if (name == "Matrix3x2") { name = "float3x2"; return true; } - else if (name == "Matrix4x4") { name = "float4x4"; return true; } - else if (name == "Plane") { name = "plane"; return true; } - else if (name == "Quaternion") { name = "quaternion"; return true; } - else if (name == "Vector2") { name = "float2"; return true; } - else if (name == "Vector3") { name = "float3"; return true; } - else if (name == "Vector4") { name = "float4"; return true; } + if (name == "Matrix3x2") + { + name = "float3x2"; + return true; + } + else if (name == "Matrix4x4") + { + name = "float4x4"; + return true; + } + else if (name == "Plane") + { + name = "plane"; + return true; + } + else if (name == "Quaternion") + { + name = "quaternion"; + return true; + } + else if (name == "Vector2") + { + name = "float2"; + return true; + } + else if (name == "Vector3") + { + name = "float3"; + return true; + } + else if (name == "Vector4") + { + name = "float4"; + return true; + } return false; } @@ -127,8 +152,8 @@ namespace cppwinrt struct generic_param_guard { - explicit generic_param_guard(writer* arg = nullptr) - : owner(arg) + explicit generic_param_guard(writer* arg = nullptr) : + owner(arg) {} ~generic_param_guard() @@ -139,8 +164,8 @@ namespace cppwinrt } } - generic_param_guard(generic_param_guard&& other) - : owner(other.owner) + generic_param_guard(generic_param_guard&& other) : + owner(other.owner) { other.owner = nullptr; } @@ -155,16 +180,14 @@ namespace cppwinrt writer* owner; }; - template - struct member_value_guard + template struct member_value_guard { writer* const owner; - T writer::* const member; + T writer::*const member; T const previous; - explicit member_value_guard(writer* arg, T writer::* ptr, T value) : + explicit member_value_guard(writer* arg, T writer::*ptr, T value) : owner(arg), member(ptr), previous(std::exchange(owner->*member, value)) - { - } + {} ~member_value_guard() { @@ -173,7 +196,6 @@ namespace cppwinrt member_value_guard(member_value_guard const&) = delete; member_value_guard& operator=(member_value_guard const&) = delete; - }; void add_depends(TypeDef const& type) @@ -337,13 +359,34 @@ namespace cppwinrt { if (ns == "Windows.Foundation.Numerics") { - if (name == "Matrix3x2") { name = "float3x2"; } - else if (name == "Matrix4x4") { name = "float4x4"; } - else if (name == "Plane") { name = "plane"; } - else if (name == "Quaternion") { name = "quaternion"; } - else if (name == "Vector2") { name = "float2"; } - else if (name == "Vector3") { name = "float3"; } - else if (name == "Vector4") { name = "float4"; } + if (name == "Matrix3x2") + { + name = "float3x2"; + } + else if (name == "Matrix4x4") + { + name = "float4x4"; + } + else if (name == "Plane") + { + name = "plane"; + } + else if (name == "Quaternion") + { + name = "quaternion"; + } + else if (name == "Vector2") + { + name = "float2"; + } + else if (name == "Vector3") + { + name = "float3"; + } + else if (name == "Vector4") + { + name = "float4"; + } write("winrt::@::%", ns, name); } @@ -396,7 +439,7 @@ namespace cppwinrt else { auto generic_type = type.GenericType(); - auto[ns, name] = get_type_namespace_and_name(generic_type); + auto [ns, name] = get_type_namespace_and_name(generic_type); name.remove_suffix(name.size() - name.rfind('`')); add_depends(find_required(generic_type)); @@ -468,21 +511,58 @@ namespace cppwinrt void write(TypeSig::value_type const& type) { - call(type, + call( + type, [&](ElementType type) { - if (type == ElementType::Boolean) { write("bool"); } - else if (type == ElementType::Char) { write("char16_t"); } - else if (type == ElementType::I1) { write("int8_t"); } - else if (type == ElementType::U1) { write("uint8_t"); } - else if (type == ElementType::I2) { write("int16_t"); } - else if (type == ElementType::U2) { write("uint16_t"); } - else if (type == ElementType::I4) { write("int32_t"); } - else if (type == ElementType::U4) { write("uint32_t"); } - else if (type == ElementType::I8) { write("int64_t"); } - else if (type == ElementType::U8) { write("uint64_t"); } - else if (type == ElementType::R4) { write("float"); } - else if (type == ElementType::R8) { write("double"); } + if (type == ElementType::Boolean) + { + write("bool"); + } + else if (type == ElementType::Char) + { + write("char16_t"); + } + else if (type == ElementType::I1) + { + write("int8_t"); + } + else if (type == ElementType::U1) + { + write("uint8_t"); + } + else if (type == ElementType::I2) + { + write("int16_t"); + } + else if (type == ElementType::U2) + { + write("uint16_t"); + } + else if (type == ElementType::I4) + { + write("int32_t"); + } + else if (type == ElementType::U4) + { + write("uint32_t"); + } + else if (type == ElementType::I8) + { + write("int64_t"); + } + else if (type == ElementType::U8) + { + write("uint64_t"); + } + else if (type == ElementType::R4) + { + write("float"); + } + else if (type == ElementType::R8) + { + write("double"); + } else if (type == ElementType::String) { if (abi_types) @@ -514,14 +594,8 @@ namespace cppwinrt assert(false); } }, - [&](GenericTypeIndex var) - { - write(generic_param_stack.back()[var.index]); - }, - [&](auto&& type) - { - write(type); - }); + [&](GenericTypeIndex var) { write(generic_param_stack.back()[var.index]); }, + [&](auto&& type) { write(type); }); } void write(TypeSig const& signature) @@ -558,10 +632,7 @@ namespace cppwinrt auto format = R"(#include %winrt/%.h% )"; - write(format, - settings.brackets ? '<' : '\"', - include, - settings.brackets ? '>' : '\"'); + write(format, settings.brackets ? '<' : '\"', include, settings.brackets ? '>' : '\"'); } void write_depends(std::string_view const& ns, char impl = 0) @@ -597,4 +668,4 @@ namespace cppwinrt flush_to_file(filename); } }; -} +} // namespace cppwinrt diff --git a/natvis/cppwinrt_visualizer.cpp b/natvis/cppwinrt_visualizer.cpp index f6affd566..a81bb6fbb 100644 --- a/natvis/cppwinrt_visualizer.cpp +++ b/natvis/cppwinrt_visualizer.cpp @@ -44,7 +44,8 @@ HRESULT DownloadMetadata(DkmProcess* process, std::filesystem::path const& remot auto remote_file_size = remote_listing->FileSize(); file_time_type remote_file_time{ file_time_type::duration(remote_listing->LastWriteTime()) }; auto remote_file_path = remote_listing->FilePath(); - auto remote_file_name = remote_listing->FileName(); remote_file_name; + auto remote_file_name = remote_listing->FileName(); + remote_file_name; if (exists(local_path)) { auto local_file_time = last_write_time(local_path); @@ -115,7 +116,7 @@ void LoadMetadata(DkmProcess* process, WCHAR const* processPath, std::string_vie break; } probe_file = probe_file.substr(0, pos); - } + } } TypeDef FindType(DkmProcess* process, std::string_view const& typeName) @@ -128,8 +129,10 @@ TypeDef FindType(DkmProcess* process, std::string_view const& typeName) type = db->find(typeName); if (!type) { - NatvisDiagnostic(process, - std::wstring(L"Could not find metadata for ") + std::wstring(typeName.begin(), typeName.end()), NatvisDiagnosticLevel::Error); + NatvisDiagnostic( + process, + std::wstring(L"Could not find metadata for ") + std::wstring(typeName.begin(), typeName.end()), + NatvisDiagnosticLevel::Error); } } return type; @@ -169,15 +172,16 @@ cppwinrt_visualizer::cppwinrt_visualizer() } catch (...) { - // If unable to read metadata, don't take down VS + // If unable to read metadata, don't take down VS } // Log an event for telemetry purposes when the visualizer is brought online com_ptr eventName; - if SUCCEEDED(DkmString::Create(DkmSourceString(L"vs/vc/diagnostics/cppwinrtvisualizer/objectconstructed"), eventName.put())) + if SUCCEEDED (DkmString::Create( + DkmSourceString(L"vs/vc/diagnostics/cppwinrtvisualizer/objectconstructed"), eventName.put())) { com_ptr error; - if SUCCEEDED(DkmTelemetryEvent::Create(eventName.get(), nullptr, nullptr, error.put())) + if SUCCEEDED (DkmTelemetryEvent::Create(eventName.get(), nullptr, nullptr, error.put())) { error->Post(); } @@ -192,9 +196,7 @@ cppwinrt_visualizer::~cppwinrt_visualizer() } HRESULT cppwinrt_visualizer::EvaluateVisualizedExpression( - _In_ DkmVisualizedExpression* pVisualizedExpression, - _Deref_out_ DkmEvaluationResult** ppResultObject -) + _In_ DkmVisualizedExpression* pVisualizedExpression, _Deref_out_ DkmEvaluationResult** ppResultObject) { try { @@ -213,8 +215,7 @@ HRESULT cppwinrt_visualizer::EvaluateVisualizedExpression( objectType = ObjectType::Projection; } // Visualize nested object properties via raw ABI pointers - else if ((wcscmp(bstrTypeName, L"winrt::impl::IInspectable") == 0) || - (wcscmp(bstrTypeName, L"winrt::impl::inspectable_abi") == 0)) + else if ((wcscmp(bstrTypeName, L"winrt::impl::IInspectable") == 0) || (wcscmp(bstrTypeName, L"winrt::impl::inspectable_abi") == 0)) { objectType = ObjectType::Abi; } @@ -231,8 +232,8 @@ HRESULT cppwinrt_visualizer::EvaluateVisualizedExpression( else { // unrecognized type - NatvisDiagnostic(pVisualizedExpression, - std::wstring(L"Unrecognized type: ") + (LPWSTR)bstrTypeName, NatvisDiagnosticLevel::Error); + NatvisDiagnostic( + pVisualizedExpression, std::wstring(L"Unrecognized type: ") + (LPWSTR)bstrTypeName, NatvisDiagnosticLevel::Error); return S_OK; } @@ -243,8 +244,11 @@ HRESULT cppwinrt_visualizer::EvaluateVisualizedExpression( catch (...) { // If something goes wrong, just fail to display object/property. Don't take down VS. - NatvisDiagnostic(pVisualizedExpression, - L"Exception in cppwinrt_visualizer::EvaluateVisualizedExpression", NatvisDiagnosticLevel::Error, to_hresult()); + NatvisDiagnostic( + pVisualizedExpression, + L"Exception in cppwinrt_visualizer::EvaluateVisualizedExpression", + NatvisDiagnosticLevel::Error, + to_hresult()); return E_FAIL; } } @@ -252,8 +256,7 @@ HRESULT cppwinrt_visualizer::EvaluateVisualizedExpression( HRESULT cppwinrt_visualizer::UseDefaultEvaluationBehavior( _In_ DkmVisualizedExpression* /*pVisualizedExpression*/, _Out_ bool* pUseDefaultEvaluationBehavior, - _Deref_out_opt_ DkmEvaluationResult** ppDefaultEvaluationResult -) + _Deref_out_opt_ DkmEvaluationResult** ppDefaultEvaluationResult) { *pUseDefaultEvaluationBehavior = false; *ppDefaultEvaluationResult = nullptr; @@ -266,8 +269,7 @@ HRESULT cppwinrt_visualizer::GetChildren( _In_ UINT32 InitialRequestSize, _In_ DkmInspectionContext* pInspectionContext, _Out_ DkmArray* pInitialChildren, - _Deref_out_ DkmEvaluationResultEnumContext** ppEnumContext -) + _Deref_out_ DkmEvaluationResultEnumContext** ppEnumContext) { try { @@ -283,7 +285,8 @@ HRESULT cppwinrt_visualizer::GetChildren( hr = pVisualizedExpression->GetDataItem(pPropertyVisualizer.put()); if (SUCCEEDED(hr)) { - IF_FAIL_RET(pPropertyVisualizer->GetChildren(InitialRequestSize, pInspectionContext, pInitialChildren, ppEnumContext)); + IF_FAIL_RET(pPropertyVisualizer->GetChildren( + InitialRequestSize, pInspectionContext, pInitialChildren, ppEnumContext)); } } @@ -292,8 +295,8 @@ HRESULT cppwinrt_visualizer::GetChildren( catch (...) { // If something goes wrong, just fail to display object/property. Don't take down VS. - NatvisDiagnostic(pVisualizedExpression, - L"Exception in cppwinrt_visualizer::GetChildren", NatvisDiagnosticLevel::Error, to_hresult()); + NatvisDiagnostic( + pVisualizedExpression, L"Exception in cppwinrt_visualizer::GetChildren", NatvisDiagnosticLevel::Error, to_hresult()); return E_FAIL; } } @@ -303,8 +306,7 @@ HRESULT cppwinrt_visualizer::GetItems( _In_ DkmEvaluationResultEnumContext* pEnumContext, _In_ UINT32 StartIndex, _In_ UINT32 Count, - _Out_ DkmArray* pItems -) + _Out_ DkmArray* pItems) { try { @@ -329,18 +331,14 @@ HRESULT cppwinrt_visualizer::GetItems( catch (...) { // If something goes wrong, just fail to display object/property. Don't take down VS. - NatvisDiagnostic(pVisualizedExpression, - L"Exception in cppwinrt_visualizer::GetItems", NatvisDiagnosticLevel::Error, to_hresult()); + NatvisDiagnostic( + pVisualizedExpression, L"Exception in cppwinrt_visualizer::GetItems", NatvisDiagnosticLevel::Error, to_hresult()); return E_FAIL; } } HRESULT cppwinrt_visualizer::SetValueAsString( - _In_ DkmVisualizedExpression* pVisualizedExpression, - _In_ DkmString* pValue, - _In_ UINT32 Timeout, - _Deref_out_opt_ DkmString** ppErrorText -) + _In_ DkmVisualizedExpression* pVisualizedExpression, _In_ DkmString* pValue, _In_ UINT32 Timeout, _Deref_out_opt_ DkmString** ppErrorText) { try { @@ -356,16 +354,13 @@ HRESULT cppwinrt_visualizer::SetValueAsString( catch (...) { // If something goes wrong, just fail to update object/property. Don't take down VS. - NatvisDiagnostic(pVisualizedExpression, - L"Exception in cppwinrt_visualizer::SetValueAsString", NatvisDiagnosticLevel::Error, to_hresult()); + NatvisDiagnostic( + pVisualizedExpression, L"Exception in cppwinrt_visualizer::SetValueAsString", NatvisDiagnosticLevel::Error, to_hresult()); return E_FAIL; } } -HRESULT cppwinrt_visualizer::GetUnderlyingString( - _In_ DkmVisualizedExpression* pVisualizedExpression, - _Deref_out_opt_ DkmString** ppStringValue -) +HRESULT cppwinrt_visualizer::GetUnderlyingString(_In_ DkmVisualizedExpression* pVisualizedExpression, _Deref_out_opt_ DkmString** ppStringValue) { try { @@ -381,8 +376,11 @@ HRESULT cppwinrt_visualizer::GetUnderlyingString( catch (...) { // If something goes wrong, just fail to display object/property. Don't take down VS. - NatvisDiagnostic(pVisualizedExpression->RuntimeInstance()->Process(), - L"Exception in cppwinrt_visualizer::GetUnderlyingString", NatvisDiagnosticLevel::Error, to_hresult()); + NatvisDiagnostic( + pVisualizedExpression->RuntimeInstance()->Process(), + L"Exception in cppwinrt_visualizer::GetUnderlyingString", + NatvisDiagnosticLevel::Error, + to_hresult()); return E_FAIL; } } diff --git a/natvis/cppwinrt_visualizer.h b/natvis/cppwinrt_visualizer.h index 5f12ec39a..4ddd99372 100644 --- a/natvis/cppwinrt_visualizer.h +++ b/natvis/cppwinrt_visualizer.h @@ -1,42 +1,36 @@ #pragma once -struct cppwinrt_visualizer : winrt::implements +struct cppwinrt_visualizer + : winrt::implements { cppwinrt_visualizer(); ~cppwinrt_visualizer(); STDMETHOD(EvaluateVisualizedExpression)( _In_ Microsoft::VisualStudio::Debugger::Evaluation::DkmVisualizedExpression* pVisualizedExpression, - _Deref_out_ Microsoft::VisualStudio::Debugger::Evaluation::DkmEvaluationResult** ppResultObject - ); + _Deref_out_ Microsoft::VisualStudio::Debugger::Evaluation::DkmEvaluationResult** ppResultObject); STDMETHOD(UseDefaultEvaluationBehavior)( _In_ Microsoft::VisualStudio::Debugger::Evaluation::DkmVisualizedExpression* pVisualizedExpression, _Out_ bool* pUseDefaultEvaluationBehavior, - _Deref_out_opt_ Microsoft::VisualStudio::Debugger::Evaluation::DkmEvaluationResult** ppDefaultEvaluationResult - ); + _Deref_out_opt_ Microsoft::VisualStudio::Debugger::Evaluation::DkmEvaluationResult** ppDefaultEvaluationResult); STDMETHOD(GetChildren)( _In_ Microsoft::VisualStudio::Debugger::Evaluation::DkmVisualizedExpression* pVisualizedExpression, _In_ UINT32 InitialRequestSize, _In_ Microsoft::VisualStudio::Debugger::Evaluation::DkmInspectionContext* pInspectionContext, _Out_ Microsoft::VisualStudio::Debugger::DkmArray* pInitialChildren, - _Deref_out_ Microsoft::VisualStudio::Debugger::Evaluation::DkmEvaluationResultEnumContext** ppEnumContext - ); + _Deref_out_ Microsoft::VisualStudio::Debugger::Evaluation::DkmEvaluationResultEnumContext** ppEnumContext); STDMETHOD(GetItems)( _In_ Microsoft::VisualStudio::Debugger::Evaluation::DkmVisualizedExpression* pVisualizedExpression, _In_ Microsoft::VisualStudio::Debugger::Evaluation::DkmEvaluationResultEnumContext* pEnumContext, _In_ UINT32 StartIndex, _In_ UINT32 Count, - _Out_ Microsoft::VisualStudio::Debugger::DkmArray* pItems - ); + _Out_ Microsoft::VisualStudio::Debugger::DkmArray* pItems); STDMETHOD(SetValueAsString)( _In_ Microsoft::VisualStudio::Debugger::Evaluation::DkmVisualizedExpression* pVisualizedExpression, _In_ Microsoft::VisualStudio::Debugger::DkmString* pValue, _In_ UINT32 Timeout, - _Deref_out_opt_ Microsoft::VisualStudio::Debugger::DkmString** ppErrorText - ); + _Deref_out_opt_ Microsoft::VisualStudio::Debugger::DkmString** ppErrorText); STDMETHOD(GetUnderlyingString)( _In_ Microsoft::VisualStudio::Debugger::Evaluation::DkmVisualizedExpression* pVisualizedExpression, - _Deref_out_opt_ Microsoft::VisualStudio::Debugger::DkmString** ppStringValue - ); + _Deref_out_opt_ Microsoft::VisualStudio::Debugger::DkmString** ppStringValue); }; diff --git a/natvis/dllmain.cpp b/natvis/dllmain.cpp index 89e54da63..18f333977 100644 --- a/natvis/dllmain.cpp +++ b/natvis/dllmain.cpp @@ -22,17 +22,17 @@ struct cppwinrt_visualizer_factory : implements factory = make(); - + return factory->QueryInterface(riid, ppv); } catch (...) diff --git a/natvis/object_visualizer.cpp b/natvis/object_visualizer.cpp index 5308c33fc..cff3cf1f0 100644 --- a/natvis/object_visualizer.cpp +++ b/natvis/object_visualizer.cpp @@ -10,15 +10,13 @@ using namespace winrt; using namespace winmd::reader; #define IID_IInspectable L"AF86E2E0-B12D-4C6A-9C5A-D7AA65101E90" -#define IID_IStringable L"96369F54-8EB6-48F0-ABCE-C1B211E627C3" +#define IID_IStringable L"96369F54-8EB6-48F0-ABCE-C1B211E627C3" constexpr struct { PCWSTR propField; PCWSTR displayType; -} -g_categoryData[] = -{ +} g_categoryData[] = { { L"b", L"bool" }, { L"c", L"wchar_t" }, { L"i1", L"int8_t" }, @@ -91,7 +89,14 @@ HRESULT NatvisDiagnostic(DkmProcess* process, std::wstring_view const& messageTe com_ptr pUserMessageText; IF_FAIL_RET(DkmString::Create(DkmSourceString(userMessage.c_str()), pUserMessageText.put())); com_ptr pUserMessage; - IF_FAIL_RET(DkmUserMessage::Create(process->Connection(), process, DkmUserMessageOutputKind::UnfilteredOutputWindowMessage, pUserMessageText.get(), 0, errorCode, pUserMessage.put())); + IF_FAIL_RET(DkmUserMessage::Create( + process->Connection(), + process, + DkmUserMessageOutputKind::UnfilteredOutputWindowMessage, + pUserMessageText.get(), + 0, + errorCode, + pUserMessage.put())); return pUserMessage->Post(); } @@ -100,13 +105,16 @@ static HRESULT EvaluatePropertyExpression( _In_ DkmVisualizedExpression* pExpression, _In_ DkmPointerValueHome* pObject, ObjectType objectType, - _Out_ com_ptr& pEvaluationResult -) + _Out_ com_ptr& pEvaluationResult) { wchar_t abiAddress[40]; auto process = pExpression->RuntimeInstance()->Process(); bool is64Bit = ((process->SystemInformation()->Flags() & DefaultPort::DkmSystemInformationFlags::Is64Bit) != 0); - swprintf_s(abiAddress, is64Bit ? L"%s0x%I64x" : L"%s0x%08x", objectType == ObjectType::Abi ? L"(::IUnknown*)" : L"*(::IUnknown**)", pObject->Address()); + swprintf_s( + abiAddress, + is64Bit ? L"%s0x%I64x" : L"%s0x%08x", + objectType == ObjectType::Abi ? L"(::IUnknown*)" : L"*(::IUnknown**)", + pObject->Address()); wchar_t wszEvalText[500]; std::wstring propCast; PCWSTR propField; @@ -119,25 +127,22 @@ static HRESULT EvaluatePropertyExpression( propField = L"v"; propCast = L"*(" + prop.abiType + L"*)"; } - swprintf_s(wszEvalText, L"%sWINRT_abi_val(%s, L\"{%s}\", %i).%s", propCast.c_str(), abiAddress, prop.iid.c_str(), prop.index, propField); + swprintf_s( + wszEvalText, L"%sWINRT_abi_val(%s, L\"{%s}\", %i).%s", propCast.c_str(), abiAddress, prop.iid.c_str(), prop.index, propField); com_ptr pEvalText; IF_FAIL_RET(DkmString::Create(DkmSourceString(wszEvalText), pEvalText.put())); NatvisDiagnostic(process, wszEvalText, NatvisDiagnosticLevel::Verbose); - auto evalFlags = DkmEvaluationFlags::TreatAsExpression | DkmEvaluationFlags::ForceEvaluationNow | DkmEvaluationFlags::ForceRealFuncEval; + auto evalFlags = DkmEvaluationFlags::TreatAsExpression | DkmEvaluationFlags::ForceEvaluationNow | + DkmEvaluationFlags::ForceRealFuncEval; auto inspectionContext = pExpression->InspectionContext(); com_ptr pLanguageExpression; IF_FAIL_RET(DkmLanguageExpression::Create( - inspectionContext->Language(), - evalFlags, - pEvalText.get(), - DkmDataItem::Null(), - pLanguageExpression.put() - )); + inspectionContext->Language(), evalFlags, pEvalText.get(), DkmDataItem::Null(), pLanguageExpression.put())); com_ptr pInspectionContext; - if ( (pExpression->InspectionContext()->EvaluationFlags() & evalFlags) != evalFlags) + if ((pExpression->InspectionContext()->EvaluationFlags() & evalFlags) != evalFlags) { DkmInspectionContext::Create( inspectionContext->InspectionSession(), @@ -149,8 +154,7 @@ static HRESULT EvaluatePropertyExpression( inspectionContext->Radix(), inspectionContext->Language(), inspectionContext->ReturnValue(), - pInspectionContext.put() - ); + pInspectionContext.put()); } else { @@ -158,11 +162,7 @@ static HRESULT EvaluatePropertyExpression( } auto hr = pExpression->EvaluateExpressionCallback( - pInspectionContext.get(), - pLanguageExpression.get(), - pExpression->StackFrame(), - pEvaluationResult.put() - ); + pInspectionContext.get(), pLanguageExpression.get(), pExpression->StackFrame(), pEvaluationResult.put()); if (hr != S_OK) { NatvisDiagnostic(process, L"EvaluateExpressionCallback failed", NatvisDiagnosticLevel::Warning, hr); @@ -175,8 +175,7 @@ static HRESULT EvaluatePropertyString( _In_ DkmVisualizedExpression* pExpression, _In_ DkmPointerValueHome* pObject, ObjectType objectType, - _Out_ com_ptr& pValue -) + _Out_ com_ptr& pValue) { com_ptr pEvaluationResult; IF_FAIL_RET(EvaluatePropertyExpression(prop, pExpression, pObject, objectType, pEvaluationResult)); @@ -192,11 +191,7 @@ static HRESULT EvaluatePropertyString( return S_OK; } -static std::string GetRuntimeClass( - _In_ DkmVisualizedExpression* pExpression, - _In_ DkmPointerValueHome* pObject, - ObjectType objectType -) +static std::string GetRuntimeClass(_In_ DkmVisualizedExpression* pExpression, _In_ DkmPointerValueHome* pObject, ObjectType objectType) { com_ptr pValue; EvaluatePropertyString({ IID_IInspectable, -2, PropertyCategory::String }, pExpression, pObject, objectType, pValue); @@ -208,11 +203,7 @@ static std::string GetRuntimeClass( } static HRESULT ObjectToString( - _In_ DkmVisualizedExpression* pExpression, - _In_ DkmPointerValueHome* pObject, - ObjectType objectType, - _Out_ com_ptr& pValue -) + _In_ DkmVisualizedExpression* pExpression, _In_ DkmPointerValueHome* pObject, ObjectType objectType, _Out_ com_ptr& pValue) { if (SUCCEEDED(EvaluatePropertyString({ IID_IStringable, 0, PropertyCategory::String }, pExpression, pObject, objectType, pValue))) { @@ -221,7 +212,7 @@ static HRESULT ObjectToString( return S_OK; } pValue = nullptr; - + // WINRT_abi_val returned 0, which may be success or failure (due to VirtualQuery validation) // Call back for the runtime class name to determine which it was if (!GetRuntimeClass(pExpression, pObject, objectType).empty()) @@ -239,8 +230,7 @@ static HRESULT CreateChildVisualizedExpression( _In_ PropertyData const& prop, _In_ DkmVisualizedExpression* pParent, ObjectType objectType, - _Deref_out_ DkmChildVisualizedExpression** ppResult -) + _Deref_out_ DkmChildVisualizedExpression** ppResult) { *ppResult = nullptr; @@ -267,7 +257,7 @@ static HRESULT CreateChildVisualizedExpression( IF_FAIL_RET(ObjectToString(pParent, pChildPointer.get(), ObjectType::Abi, pValue)); } } - if(!isNonNullObject) + if (!isNonNullObject) { com_ptr expressionValueHome = make_com_ptr(pParent->ValueHome()); pChildPointer = expressionValueHome.as(); @@ -307,8 +297,7 @@ static HRESULT CreateChildVisualizedExpression( pSuccessEvaluationResult->CustomUIVisualizers(), pSuccessEvaluationResult->ExternalModules(), DkmDataItem::Null(), - pVisualizedResult.put() - )); + pVisualizedResult.put())); com_ptr pChildVisualizedExpression; IF_FAIL_RET(DkmChildVisualizedExpression::Create( @@ -321,17 +310,18 @@ static HRESULT CreateChildVisualizedExpression( pParent, 2, DkmDataItem::Null(), - pChildVisualizedExpression.put() - )); + pChildVisualizedExpression.put())); if (isNonNullObject) { - com_ptr pObjectVisualizer = make_self(pChildVisualizedExpression.get(), ObjectType::Abi); + com_ptr pObjectVisualizer = + make_self(pChildVisualizedExpression.get(), ObjectType::Abi); IF_FAIL_RET(pChildVisualizedExpression->SetDataItem(DkmDataCreationDisposition::CreateNew, pObjectVisualizer.get())); } else { - com_ptr pPropertyVisualizer = make_self(pChildVisualizedExpression.get(), pSuccessEvaluationResult.get()); + com_ptr pPropertyVisualizer = + make_self(pChildVisualizedExpression.get(), pSuccessEvaluationResult.get()); IF_FAIL_RET(pChildVisualizedExpression->SetDataItem(DkmDataCreationDisposition::CreateNew, pPropertyVisualizer.get())); } @@ -350,8 +340,8 @@ void GetInterfaceData( Microsoft::VisualStudio::Debugger::DkmProcess* process, coded_index index, _Inout_ std::vector& propertyData, - _Out_ bool& isStringable -){ + _Out_ bool& isStringable) +{ auto [type, propIid] = ResolveTypeInterface(process, index); if (!type) { @@ -380,95 +370,113 @@ void GetInterfaceData( std::wstring propDisplayType; auto retType = method.Signature().ReturnType(); - std::visit(overloaded{ - [&](ElementType type) - { - if ((ElementType::Boolean <= type) && (type <= ElementType::String)) - { - propCategory = (PropertyCategory)(static_cast::type>(type) - - static_cast::type>(ElementType::Boolean)); - } - else if (type == ElementType::Object) - { - //propDisplayType = L"winrt::Windows::Foundation::IInspectable"; - //propCategory = PropertyCategory::Class; - //propAbiType = L"winrt::impl::inspectable_abi*"; - } - }, - [&](coded_index const& index) - { - auto type = ResolveType(process, index); - if (!type) - { - return; - } - - auto typeName = type.TypeName(); - if (typeName == "GUID"sv) - { - propCategory = PropertyCategory::Guid; - } - else - { - auto ns = std::string(type.TypeNamespace()); - auto name = std::string(type.TypeName()); - - // Map numeric type names - if (ns == "Windows.Foundation.Numerics") - { - if (name == "Matrix3x2") { name = "float3x2"; } - else if (name == "Matrix4x4") { name = "float4x4"; } - else if (name == "Plane") { name = "plane"; } - else if (name == "Quaternion") { name = "quaternion"; } - else if (name == "Vector2") { name = "float2"; } - else if (name == "Vector3") { name = "float3"; } - else if (name == "Vector4") { name = "float4"; } - } - - // Types come back from winmd files with '.', need to be '::' - // Ex. Windows.Foundation.Uri needs to be Windows::Foundation::Uri - auto fullTypeName = ns + "::" + name; - wchar_t cppTypename[500]; - size_t i, j; - for (i = 0, j = 0; i < (fullTypeName.length() + 1); i++, j++) - { - if (fullTypeName[i] == L'.') + std::visit( + overloaded{ [&](ElementType type) { - cppTypename[j++] = L':'; - cppTypename[j] = L':'; - } - else + if ((ElementType::Boolean <= type) && (type <= ElementType::String)) + { + propCategory = + (PropertyCategory)(static_cast::type>(type) - + static_cast::type>(ElementType::Boolean)); + } + else if (type == ElementType::Object) + { + // propDisplayType = L"winrt::Windows::Foundation::IInspectable"; + // propCategory = PropertyCategory::Class; + // propAbiType = L"winrt::impl::inspectable_abi*"; + } + }, + [&](coded_index const& index) { - cppTypename[j] = fullTypeName[i]; - } - } - - propDisplayType = std::wstring(L"winrt::") + cppTypename; - if(get_category(type) == category::class_type) - { - propCategory = PropertyCategory::Class; - propAbiType = L"winrt::impl::inspectable_abi*"; - } - else - { - propCategory = PropertyCategory::Value; - propAbiType = propDisplayType; - } - } - }, - [&](GenericTypeIndex /*var*/) - { - NatvisDiagnostic(process, L"Generics not yet supported", NatvisDiagnosticLevel::Warning); - }, - [&](GenericMethodTypeIndex /*var*/) - { - NatvisDiagnostic(process, L"Generics not yet supported", NatvisDiagnosticLevel::Warning); - }, - [&](GenericTypeInstSig const& /*type*/) - { - NatvisDiagnostic(process, L"Generics not yet supported", NatvisDiagnosticLevel::Warning); - } - }, retType.Type().Type()); + auto type = ResolveType(process, index); + if (!type) + { + return; + } + + auto typeName = type.TypeName(); + if (typeName == "GUID"sv) + { + propCategory = PropertyCategory::Guid; + } + else + { + auto ns = std::string(type.TypeNamespace()); + auto name = std::string(type.TypeName()); + + // Map numeric type names + if (ns == "Windows.Foundation.Numerics") + { + if (name == "Matrix3x2") + { + name = "float3x2"; + } + else if (name == "Matrix4x4") + { + name = "float4x4"; + } + else if (name == "Plane") + { + name = "plane"; + } + else if (name == "Quaternion") + { + name = "quaternion"; + } + else if (name == "Vector2") + { + name = "float2"; + } + else if (name == "Vector3") + { + name = "float3"; + } + else if (name == "Vector4") + { + name = "float4"; + } + } + + // Types come back from winmd files with '.', need to be '::' + // Ex. Windows.Foundation.Uri needs to be Windows::Foundation::Uri + auto fullTypeName = ns + "::" + name; + wchar_t cppTypename[500]; + size_t i, j; + for (i = 0, j = 0; i < (fullTypeName.length() + 1); i++, j++) + { + if (fullTypeName[i] == L'.') + { + cppTypename[j++] = L':'; + cppTypename[j] = L':'; + } + else + { + cppTypename[j] = fullTypeName[i]; + } + } + + propDisplayType = std::wstring(L"winrt::") + cppTypename; + if (get_category(type) == category::class_type) + { + propCategory = PropertyCategory::Class; + propAbiType = L"winrt::impl::inspectable_abi*"; + } + else + { + propCategory = PropertyCategory::Value; + propAbiType = propDisplayType; + } + } + }, + [&](GenericTypeIndex /*var*/) + { NatvisDiagnostic(process, L"Generics not yet supported", NatvisDiagnosticLevel::Warning); }, + [&](GenericMethodTypeIndex /*var*/) + { NatvisDiagnostic(process, L"Generics not yet supported", NatvisDiagnosticLevel::Warning); }, + [&](GenericTypeInstSig const& /*type*/) + { + NatvisDiagnostic(process, L"Generics not yet supported", NatvisDiagnosticLevel::Warning); + } }, + retType.Type().Type()); if (propCategory) { @@ -505,7 +513,7 @@ void object_visualizer::GetTypeProperties(Microsoft::VisualStudio::Debugger::Dkm if (get_category(type) == category::class_type) { auto const& [extends_namespace, extends_name] = get_base_class_namespace_and_name(type); - if(!extends_namespace.empty() && !extends_name.empty()) + if (!extends_namespace.empty() && !extends_name.empty()) { auto base_type = std::string(extends_namespace) + "." + std::string(extends_name); if (base_type != "System.Object") @@ -530,7 +538,8 @@ void object_visualizer::GetTypeProperties(Microsoft::VisualStudio::Debugger::Dkm } } -HRESULT object_visualizer::CreateEvaluationResult(_In_ DkmVisualizedExpression* pVisualizedExpression, _In_ ObjectType objectType, _Deref_out_ DkmEvaluationResult** ppResultObject) +HRESULT object_visualizer::CreateEvaluationResult( + _In_ DkmVisualizedExpression* pVisualizedExpression, _In_ ObjectType objectType, _Deref_out_ DkmEvaluationResult** ppResultObject) { com_ptr pObjectVisualizer = make_self(pVisualizedExpression, objectType); @@ -548,7 +557,8 @@ static std::set g_refresh_cache; bool requires_refresh(UINT64 address, DkmEvaluationFlags_t evalFlags) { auto refreshed = g_refresh_cache.find(address) != g_refresh_cache.end(); - return !refreshed && ((evalFlags & DkmEvaluationFlags::EnableExtendedSideEffects) != DkmEvaluationFlags::EnableExtendedSideEffects); + return !refreshed && + ((evalFlags & DkmEvaluationFlags::EnableExtendedSideEffects) != DkmEvaluationFlags::EnableExtendedSideEffects); } void cache_refresh(UINT64 address) { @@ -560,24 +570,25 @@ bool requires_refresh(UINT64, DkmEvaluationFlags_t) return false; } void cache_refresh(UINT64) -{ -} +{} #endif HRESULT object_visualizer::CreateEvaluationResult(_Deref_out_ DkmEvaluationResult** ppResultObject) { - com_ptr pRootVisualizedExpression = m_pVisualizedExpression.as(); + com_ptr pRootVisualizedExpression = + m_pVisualizedExpression.as(); auto valueHome = make_com_ptr(m_pVisualizedExpression->ValueHome()); com_ptr pPointerValueHome = valueHome.as(); auto address = pPointerValueHome->Address(); - + com_ptr pValue; DkmEvaluationResultFlags_t evalResultFlags = DkmEvaluationResultFlags::ReadOnly | DkmEvaluationResultFlags::Expandable; if (requires_refresh(address, m_pVisualizedExpression->InspectionContext()->EvaluationFlags())) { IF_FAIL_RET(DkmString::Create(L"", pValue.put())); - evalResultFlags |= DkmEvaluationResultFlags::EnableExtendedSideEffectsUponRefresh | DkmEvaluationResultFlags::CanEvaluateNow; + evalResultFlags |= + DkmEvaluationResultFlags::EnableExtendedSideEffectsUponRefresh | DkmEvaluationResultFlags::CanEvaluateNow; } else { @@ -586,7 +597,8 @@ HRESULT object_visualizer::CreateEvaluationResult(_Deref_out_ DkmEvaluationResul } com_ptr pAddress; - IF_FAIL_RET(DkmDataAddress::Create(m_pVisualizedExpression->StackFrame()->RuntimeInstance(), address, nullptr, pAddress.put())); + IF_FAIL_RET( + DkmDataAddress::Create(m_pVisualizedExpression->StackFrame()->RuntimeInstance(), address, nullptr, pAddress.put())); com_ptr pSuccessEvaluationResult; IF_FAIL_RET(DkmSuccessEvaluationResult::Create( @@ -606,8 +618,7 @@ HRESULT object_visualizer::CreateEvaluationResult(_Deref_out_ DkmEvaluationResul (DkmReadOnlyCollection*)nullptr, (DkmReadOnlyCollection*)nullptr, DkmDataItem::Null(), - pSuccessEvaluationResult.put() - )); + pSuccessEvaluationResult.put())); pSuccessEvaluationResult->SetDataItem(DkmDataCreationDisposition::CreateNew, this); @@ -632,15 +643,20 @@ HRESULT object_visualizer::GetChildren( catch (std::invalid_argument const& e) { std::string_view message(e.what()); - NatvisDiagnostic(m_pVisualizedExpression.get(), + NatvisDiagnostic( + m_pVisualizedExpression.get(), std::wstring(L"Exception in object_visualizer::GetPropertyData: ") + - std::wstring(message.begin(), message.end()), - NatvisDiagnosticLevel::Error, to_hresult()); + std::wstring(message.begin(), message.end()), + NatvisDiagnosticLevel::Error, + to_hresult()); } catch (...) { - NatvisDiagnostic(m_pVisualizedExpression.get(), - L"Exception in object_visualizer::GetPropertyData", NatvisDiagnosticLevel::Error, to_hresult()); + NatvisDiagnostic( + m_pVisualizedExpression.get(), + L"Exception in object_visualizer::GetPropertyData", + NatvisDiagnosticLevel::Error, + to_hresult()); } } @@ -671,11 +687,11 @@ HRESULT object_visualizer::GetItems( auto pParent = pVisualizedExpression; auto childCount = std::min(m_propertyData.size() - StartIndex, (size_t)Count); - for(auto i = 0; i < childCount; ++i) + for (auto i = 0; i < childCount; ++i) { auto& prop = m_propertyData[i + (size_t)StartIndex]; com_ptr pPropertyVisualized; - if(FAILED(CreateChildVisualizedExpression(prop, pParent, m_objectType, pPropertyVisualized.put()))) + if (FAILED(CreateChildVisualizedExpression(prop, pParent, m_objectType, pPropertyVisualized.put()))) { com_ptr pErrorMessage; IF_FAIL_RET(DkmString::Create(L"", pErrorMessage.put())); @@ -692,8 +708,7 @@ HRESULT object_visualizer::GetItems( pErrorMessage.get(), DkmEvaluationResultFlags::ExceptionThrown, DkmDataItem::Null(), - pVisualizedResult.put() - )); + pVisualizedResult.put())); IF_FAIL_RET(DkmChildVisualizedExpression::Create( pParent->InspectionContext(), @@ -705,8 +720,7 @@ HRESULT object_visualizer::GetItems( pParent, 2, DkmDataItem::Null(), - pPropertyVisualized.put() - )); + pPropertyVisualized.put())); } resultValues.Members[i] = pPropertyVisualized.detach(); } diff --git a/natvis/object_visualizer.h b/natvis/object_visualizer.h index ad83d79d7..f008a5d3b 100644 --- a/natvis/object_visualizer.h +++ b/natvis/object_visualizer.h @@ -27,7 +27,7 @@ enum class ObjectType }; // Metadata for resolving a runtime class property value -struct PropertyData +struct PropertyData { std::wstring iid; int32_t index; @@ -37,10 +37,10 @@ struct PropertyData std::wstring displayName; }; -// object_visualizer provides the visualization data model for WinRT objects, +// object_visualizer provides the visualization data model for WinRT objects, // both for root-level RAII IInspectables, and for nested ABI IInspectable properties. -struct __declspec(uuid("c7da92da-3bc9-4312-8a93-46f480663980")) -object_visualizer : winrt::implements +struct __declspec(uuid("c7da92da-3bc9-4312-8a93-46f480663980")) object_visualizer + : winrt::implements { object_visualizer(Microsoft::VisualStudio::Debugger::Evaluation::DkmVisualizedExpression* pVisualizedExpression, ObjectType objectType) { @@ -49,10 +49,12 @@ object_visualizer : winrt::implements } ~object_visualizer() - { - } + {} - static HRESULT CreateEvaluationResult(_In_ Microsoft::VisualStudio::Debugger::Evaluation::DkmVisualizedExpression* pVisualizedExpression, _In_ ObjectType objectType, _Deref_out_ Microsoft::VisualStudio::Debugger::Evaluation::DkmEvaluationResult** ppResultObject); + static HRESULT CreateEvaluationResult( + _In_ Microsoft::VisualStudio::Debugger::Evaluation::DkmVisualizedExpression* pVisualizedExpression, + _In_ ObjectType objectType, + _Deref_out_ Microsoft::VisualStudio::Debugger::Evaluation::DkmEvaluationResult** ppResultObject); HRESULT CreateEvaluationResult(_Deref_out_ Microsoft::VisualStudio::Debugger::Evaluation::DkmEvaluationResult** ppResultObject); @@ -60,16 +62,14 @@ object_visualizer : winrt::implements _In_ UINT32 InitialRequestSize, _In_ Microsoft::VisualStudio::Debugger::Evaluation::DkmInspectionContext* pInspectionContext, _Out_ Microsoft::VisualStudio::Debugger::DkmArray* pInitialChildren, - _Deref_out_ Microsoft::VisualStudio::Debugger::Evaluation::DkmEvaluationResultEnumContext** ppEnumContext - ); + _Deref_out_ Microsoft::VisualStudio::Debugger::Evaluation::DkmEvaluationResultEnumContext** ppEnumContext); HRESULT GetItems( _In_ Microsoft::VisualStudio::Debugger::Evaluation::DkmVisualizedExpression* pVisualizedExpression, _In_ Microsoft::VisualStudio::Debugger::Evaluation::DkmEvaluationResultEnumContext* pEnumContext, _In_ UINT32 StartIndex, _In_ UINT32 Count, - _Out_ Microsoft::VisualStudio::Debugger::DkmArray* pItems - ); + _Out_ Microsoft::VisualStudio::Debugger::DkmArray* pItems); private: void GetPropertyData(); diff --git a/natvis/pch.h b/natvis/pch.h index c687b1f09..d3794f26e 100644 --- a/natvis/pch.h +++ b/natvis/pch.h @@ -1,6 +1,6 @@ #pragma once -#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers +#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers #define NOMINMAX #include @@ -42,11 +42,17 @@ #include #ifndef IF_FAIL_RET -#define IF_FAIL_RET(expr) { HRESULT _hr = (expr); if(FAILED(_hr)) { return(_hr); } } +#define IF_FAIL_RET(expr) \ + { \ + HRESULT _hr = (expr); \ + if (FAILED(_hr)) \ + { \ + return (_hr); \ + } \ + } #endif -template -winrt::com_ptr make_com_ptr(T* ptr) +template winrt::com_ptr make_com_ptr(T* ptr) { winrt::com_ptr result; result.copy_from(ptr); @@ -62,22 +68,32 @@ enum class NatvisDiagnosticLevel Verbose }; NatvisDiagnosticLevel GetNatvisDiagnosticLevel(); -HRESULT NatvisDiagnostic(Microsoft::VisualStudio::Debugger::DkmProcess* process, std::wstring_view const& messageText, NatvisDiagnosticLevel level, HRESULT errorCode = S_OK); -inline HRESULT NatvisDiagnostic(Microsoft::VisualStudio::Debugger::Evaluation::DkmVisualizedExpression* expression, std::wstring_view const& messageText, NatvisDiagnosticLevel level, HRESULT errorCode = S_OK) +HRESULT NatvisDiagnostic( + Microsoft::VisualStudio::Debugger::DkmProcess* process, + std::wstring_view const& messageText, + NatvisDiagnosticLevel level, + HRESULT errorCode = S_OK); +inline HRESULT NatvisDiagnostic( + Microsoft::VisualStudio::Debugger::Evaluation::DkmVisualizedExpression* expression, + std::wstring_view const& messageText, + NatvisDiagnosticLevel level, + HRESULT errorCode = S_OK) { return NatvisDiagnostic(expression->RuntimeInstance()->Process(), messageText, level, errorCode); } -template struct overloaded : T... { using T::operator()...; }; -template overloaded(T...)->overloaded; +template struct overloaded : T... +{ + using T::operator()...; +}; +template overloaded(T...) -> overloaded; [[noreturn]] inline void throw_invalid(std::string const& message) { throw std::invalid_argument(message); } -template -[[noreturn]] inline void throw_invalid(std::string message, T const&... args) +template [[noreturn]] inline void throw_invalid(std::string message, T const&... args) { (message.append(args), ...); throw std::invalid_argument(message); @@ -89,9 +105,11 @@ inline bool starts_with(std::string_view const& value, std::string_view const& m } winmd::reader::TypeDef FindType(Microsoft::VisualStudio::Debugger::DkmProcess* process, std::string_view const& typeName); -winmd::reader::TypeDef FindType(Microsoft::VisualStudio::Debugger::DkmProcess* process, std::string_view const& typeNamespace, std::string_view const& typeName); +winmd::reader::TypeDef FindType( + Microsoft::VisualStudio::Debugger::DkmProcess* process, std::string_view const& typeNamespace, std::string_view const& typeName); -inline winmd::reader::TypeDef ResolveType(Microsoft::VisualStudio::Debugger::DkmProcess* process, winmd::reader::coded_index index) noexcept +inline winmd::reader::TypeDef ResolveType( + Microsoft::VisualStudio::Debugger::DkmProcess* process, winmd::reader::coded_index index) noexcept { switch (index.type()) { @@ -99,12 +117,12 @@ inline winmd::reader::TypeDef ResolveType(Microsoft::VisualStudio::Debugger::Dkm return index.TypeDef(); case winmd::reader::TypeDefOrRef::TypeRef: return FindType(process, index.TypeRef().TypeNamespace(), index.TypeRef().TypeName()); - default: //case TypeDefOrRef::TypeSpec: - return winmd::reader::find_required(index.TypeSpec().Signature(). - GenericTypeInst().GenericType().TypeRef()); + default: // case TypeDefOrRef::TypeSpec: + return winmd::reader::find_required(index.TypeSpec().Signature().GenericTypeInst().GenericType().TypeRef()); } } -std::pair ResolveTypeInterface(Microsoft::VisualStudio::Debugger::DkmProcess* process, winmd::reader::coded_index index); +std::pair ResolveTypeInterface( + Microsoft::VisualStudio::Debugger::DkmProcess* process, winmd::reader::coded_index index); void ClearTypeResolver(); diff --git a/natvis/property_visualizer.cpp b/natvis/property_visualizer.cpp index 716ad3613..28cdfbf3b 100644 --- a/natvis/property_visualizer.cpp +++ b/natvis/property_visualizer.cpp @@ -8,29 +8,30 @@ using namespace Microsoft::VisualStudio::Debugger::Evaluation; using namespace winmd::reader; HRESULT property_visualizer::GetChildren( - _In_ UINT32 InitialRequestSize, - _In_ DkmInspectionContext* pInspectionContext, - _Out_ DkmArray* pVisualizedInitialChildren, - _Deref_out_ DkmEvaluationResultEnumContext** ppEnumContext - ) + _In_ UINT32 InitialRequestSize, + _In_ DkmInspectionContext* pInspectionContext, + _Out_ DkmArray* pVisualizedInitialChildren, + _Deref_out_ DkmEvaluationResultEnumContext** ppEnumContext) { - // Forward this on to the EE. + // Forward this on to the EE. CAutoDkmArray initialChildren; - IF_FAIL_RET(m_pVisualizedExpression->GetChildrenCallback(m_pEEEvaluationResult.get(), InitialRequestSize, pInspectionContext, &initialChildren, ppEnumContext)); + IF_FAIL_RET(m_pVisualizedExpression->GetChildrenCallback( + m_pEEEvaluationResult.get(), InitialRequestSize, pInspectionContext, &initialChildren, ppEnumContext)); // Need to create a DkmArray of DkmChildVisualizedExpression that contain the evaluation results and return that. DkmAllocArray(initialChildren.Length, pVisualizedInitialChildren); - + for (DWORD i = 0; i < initialChildren.Length; i++) { auto pCurrEvaluationResult = make_com_ptr(initialChildren.Members[i]); - + if (pCurrEvaluationResult->TagValue() != DkmEvaluationResult::Tag::SuccessResult) { return E_FAIL; } - DkmSuccessEvaluationResult* pCurrSuccessEvaluationResult = (DkmSuccessEvaluationResult*)(pCurrEvaluationResult.get()); + DkmSuccessEvaluationResult* pCurrSuccessEvaluationResult = + (DkmSuccessEvaluationResult*)(pCurrEvaluationResult.get()); winrt::com_ptr pPointerValueHome; IF_FAIL_RET(DkmPointerValueHome::Create(pCurrSuccessEvaluationResult->Address()->Value(), pPointerValueHome.put())); @@ -46,8 +47,7 @@ HRESULT property_visualizer::GetChildren( m_pVisualizedExpression.get(), // (parent) i, this, - pChildVisualizedExpression.put() - )); + pChildVisualizedExpression.put())); pVisualizedInitialChildren->Members[i] = pChildVisualizedExpression.detach(); } @@ -56,28 +56,28 @@ HRESULT property_visualizer::GetChildren( } HRESULT property_visualizer::GetItems( - _In_ DkmEvaluationResultEnumContext* pEnumContext, - _In_ UINT32 StartIndex, - _In_ UINT32 Count, - _Out_ DkmArray* pItems - ) + _In_ DkmEvaluationResultEnumContext* pEnumContext, + _In_ UINT32 StartIndex, + _In_ UINT32 Count, + _Out_ DkmArray* pItems) { - // Forward this on to the EE. + // Forward this on to the EE. CAutoDkmArray evaluationResults; IF_FAIL_RET(m_pVisualizedExpression->GetItemsCallback(pEnumContext, StartIndex, Count, &evaluationResults)); DkmAllocArray(evaluationResults.Length, pItems); - + for (DWORD i = 0; i < evaluationResults.Length; i++) { auto pCurrEvaluationResult = make_com_ptr(evaluationResults.Members[i]); - + if (pCurrEvaluationResult->TagValue() != DkmEvaluationResult::Tag::SuccessResult) { return E_FAIL; } - DkmSuccessEvaluationResult* pCurrSuccessEvaluationResult = (DkmSuccessEvaluationResult*)(pCurrEvaluationResult.get()); + DkmSuccessEvaluationResult* pCurrSuccessEvaluationResult = + (DkmSuccessEvaluationResult*)(pCurrEvaluationResult.get()); winrt::com_ptr pPointerValueHome; auto address = pCurrSuccessEvaluationResult->Address(); @@ -94,33 +94,25 @@ HRESULT property_visualizer::GetItems( m_pVisualizedExpression.get(), // (parent) i, this, - pChildVisualizedExpression.put() - )); + pChildVisualizedExpression.put())); pItems->Members[i] = pChildVisualizedExpression.detach(); } - return S_OK; } -HRESULT property_visualizer::SetValueAsString( - _In_ DkmString* pValue, - _In_ UINT32 Timeout, - _Deref_out_opt_ DkmString** ppErrorText - ) +HRESULT property_visualizer::SetValueAsString(_In_ DkmString* pValue, _In_ UINT32 Timeout, _Deref_out_opt_ DkmString** ppErrorText) { - // Forward this on to the EE. + // Forward this on to the EE. IF_FAIL_RET(m_pVisualizedExpression->SetValueAsStringCallback(m_pEEEvaluationResult.get(), pValue, Timeout, ppErrorText)); return S_OK; } -HRESULT property_visualizer::GetUnderlyingString( - _Deref_out_opt_ DkmString** ppStringValue - ) +HRESULT property_visualizer::GetUnderlyingString(_Deref_out_opt_ DkmString** ppStringValue) { - // Forward this on to the EE. + // Forward this on to the EE. IF_FAIL_RET(m_pVisualizedExpression->GetUnderlyingStringCallback(m_pEEEvaluationResult.get(), ppStringValue)); return S_OK; diff --git a/natvis/property_visualizer.h b/natvis/property_visualizer.h index 990973217..022f1ad27 100644 --- a/natvis/property_visualizer.h +++ b/natvis/property_visualizer.h @@ -1,10 +1,10 @@ #pragma once -// property_visualizer provides the visualization data model for leaf (non-WinRT object) +// property_visualizer provides the visualization data model for leaf (non-WinRT object) // nodes in the WinRT object graph, forwarding its implementation back to the expression // evaluator for external types. -struct __declspec(uuid("87feab93-47a3-4f55-b48b-a29317fa52da")) -property_visualizer : winrt::implements +struct __declspec(uuid("87feab93-47a3-4f55-b48b-a29317fa52da")) property_visualizer + : winrt::implements { property_visualizer( _In_ Microsoft::VisualStudio::Debugger::Evaluation::DkmChildVisualizedExpression* pVisualizedExpression, @@ -15,32 +15,26 @@ property_visualizer : winrt::implements } ~property_visualizer() - { - } + {} HRESULT GetChildren( _In_ UINT32 InitialRequestSize, _In_ Microsoft::VisualStudio::Debugger::Evaluation::DkmInspectionContext* pInspectionContext, _Out_ Microsoft::VisualStudio::Debugger::DkmArray* pInitialChildren, - _Deref_out_ Microsoft::VisualStudio::Debugger::Evaluation::DkmEvaluationResultEnumContext** ppEnumContext - ); + _Deref_out_ Microsoft::VisualStudio::Debugger::Evaluation::DkmEvaluationResultEnumContext** ppEnumContext); HRESULT GetItems( _In_ Microsoft::VisualStudio::Debugger::Evaluation::DkmEvaluationResultEnumContext* pEnumContext, _In_ UINT32 StartIndex, _In_ UINT32 Count, - _Out_ Microsoft::VisualStudio::Debugger::DkmArray* pItems - ); + _Out_ Microsoft::VisualStudio::Debugger::DkmArray* pItems); HRESULT SetValueAsString( _In_ Microsoft::VisualStudio::Debugger::DkmString* pValue, _In_ UINT32 Timeout, - _Deref_out_opt_ Microsoft::VisualStudio::Debugger::DkmString** ppErrorText - ); + _Deref_out_opt_ Microsoft::VisualStudio::Debugger::DkmString** ppErrorText); - HRESULT GetUnderlyingString( - _Deref_out_opt_ Microsoft::VisualStudio::Debugger::DkmString** ppStringValue - ); + HRESULT GetUnderlyingString(_Deref_out_opt_ Microsoft::VisualStudio::Debugger::DkmString** ppStringValue); private: // The DkmVisualizedExpression created for this object. diff --git a/natvis/type_resolver.cpp b/natvis/type_resolver.cpp index 17999997f..536a75db5 100644 --- a/natvis/type_resolver.cpp +++ b/natvis/type_resolver.cpp @@ -13,8 +13,7 @@ static bool has_attribute(T const& row, std::string_view const& type_namespace, return static_cast(get_attribute(row, type_namespace, type_name)); } -template -static auto call(V&& variant, C&& ...call) +template static auto call(V&& variant, C&&... call) { return std::visit(overloaded{ std::forward(call)... }, std::forward(variant)); } @@ -32,28 +31,25 @@ static guid get_guid(TypeDef const& type) throw_invalid("'Windows.Foundation.Metadata.GuidAttribute' attribute for type '", get_full_name(type), "' not found"); } auto args = attribute.Value().FixedArgs(); - return - { - std::get(std::get(args[0].value).value), - std::get(std::get(args[1].value).value), - std::get(std::get(args[2].value).value), - { - std::get(std::get(args[3].value).value), - std::get(std::get(args[4].value).value), - std::get(std::get(args[5].value).value), - std::get(std::get(args[6].value).value), - std::get(std::get(args[7].value).value), - std::get(std::get(args[8].value).value), - std::get(std::get(args[9].value).value), - std::get(std::get(args[10].value).value) - } - }; + return { std::get(std::get(args[0].value).value), + std::get(std::get(args[1].value).value), + std::get(std::get(args[2].value).value), + { std::get(std::get(args[3].value).value), + std::get(std::get(args[4].value).value), + std::get(std::get(args[5].value).value), + std::get(std::get(args[6].value).value), + std::get(std::get(args[7].value).value), + std::get(std::get(args[8].value).value), + std::get(std::get(args[9].value).value), + std::get(std::get(args[10].value).value) } }; } static std::wstring format_guid(guid guid) { std::wstring guid_str(68, L'?'); - int count = swprintf_s(guid_str.data(), guid_str.size() + 1, + int count = swprintf_s( + guid_str.data(), + guid_str.size() + 1, L"%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X", guid.Data1, guid.Data2, @@ -93,7 +89,7 @@ struct signature_generator return get_signature(type.TypeDef()); case TypeDefOrRef::TypeRef: return get_signature(type.TypeRef()); - default: //case TypeDefOrRef::TypeSpec: + default: // case TypeDefOrRef::TypeSpec: return get_signature(type.TypeSpec().Signature().GenericTypeInst()); } } @@ -126,7 +122,9 @@ struct signature_generator { auto guid = get_guid(type); std::string guid_str(70, '?'); - int count = sprintf_s(guid_str.data(), guid_str.size() + 1, + int count = sprintf_s( + guid_str.data(), + guid_str.size() + 1, "{%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}", guid.Data1, guid.Data2, @@ -151,7 +149,7 @@ struct signature_generator return get_guid_signature(type.TypeDef()); case TypeDefOrRef::TypeRef: return get_guid_signature(find_required(type.TypeRef())); - default: //case TypeDefOrRef::TypeSpec: + default: // case TypeDefOrRef::TypeSpec: return get_guid_signature(type.TypeSpec().Signature().GenericTypeInst().GenericType()); } } @@ -170,31 +168,46 @@ struct signature_generator static std::string get_signature(TypeSig::value_type const& type) { - return call(type, [&](ElementType type) -> std::string - { - switch (type) + return call( + type, + [&](ElementType type) -> std::string { - case ElementType::Boolean: return "b1"; - case ElementType::Char: return "c2"; - case ElementType::I1: return "i1"; - case ElementType::U1: return "u1"; - case ElementType::I2: return "i2"; - case ElementType::U2: return "u2"; - case ElementType::I4: return "i4"; - case ElementType::U4: return "u4"; - case ElementType::I8: return "i8"; - case ElementType::U8: return "u8"; - case ElementType::R4: return "f4"; - case ElementType::R8: return "f8"; - case ElementType::String: return "string"; - case ElementType::Object: return "cinterface(IInspectable)"; - default: assert(false); return ""; - } - }, - [&](auto&& type) - { - return get_signature(type); - }); + switch (type) + { + case ElementType::Boolean: + return "b1"; + case ElementType::Char: + return "c2"; + case ElementType::I1: + return "i1"; + case ElementType::U1: + return "u1"; + case ElementType::I2: + return "i2"; + case ElementType::U2: + return "u2"; + case ElementType::I4: + return "i4"; + case ElementType::U4: + return "u4"; + case ElementType::I8: + return "i8"; + case ElementType::U8: + return "u8"; + case ElementType::R4: + return "f4"; + case ElementType::R8: + return "f8"; + case ElementType::String: + return "string"; + case ElementType::Object: + return "cinterface(IInspectable)"; + default: + assert(false); + return ""; + } + }, + [&](auto&& type) { return get_signature(type); }); } static std::string get_signature(TypeDef const& type) @@ -209,7 +222,7 @@ struct signature_generator return get_enum_signature(type); case category::struct_type: return get_struct_signature(type); - default: //case category::delegate_type: + default: // case category::delegate_type: return "delegate(" + get_guid_signature(type) + ")"; } } @@ -268,7 +281,7 @@ static auto calculate_sha1(std::vector const& input) static guid generate_guid(coded_index const& type) { - constexpr guid namespace_guid = { 0xd57af411, 0x737b, 0xc042,{ 0xab, 0xae, 0x87, 0x8b, 0x1e, 0x16, 0xad, 0xee } }; + constexpr guid namespace_guid = { 0xd57af411, 0x737b, 0xc042, { 0xab, 0xae, 0x87, 0x8b, 0x1e, 0x16, 0xad, 0xee } }; constexpr auto namespace_bytes = winrt::impl::to_array(namespace_guid); std::vector buffer{ namespace_bytes.begin(), namespace_bytes.end() }; @@ -291,8 +304,7 @@ std::pair ResolveTypeInterface(DkmProcess* process, coded return {}; } - auto guid = index.type() == TypeDefOrRef::TypeSpec ? - format_guid(generate_guid(index)) : format_guid(get_guid(type)); + auto guid = index.type() == TypeDefOrRef::TypeSpec ? format_guid(generate_guid(index)) : format_guid(get_guid(type)); auto type_guid = std::pair{ type, guid }; _cache[index] = type_guid; diff --git a/prebuild/main.cpp b/prebuild/main.cpp index 3e427d32b..2ccce63c2 100644 --- a/prebuild/main.cpp +++ b/prebuild/main.cpp @@ -1,9 +1,7 @@ #include "pch.h" struct writer : cppwinrt::writer_base -{ - -}; +{}; int main(int const argc, char** argv) { @@ -40,12 +38,14 @@ namespace cppwinrt::strings { auto view = cppwinrt::file_to_string(path.string()); - strings_h.write(R"(extern char const %[%]; + strings_h.write( + R"(extern char const %[%]; )", name.string(), static_cast(view.size() + 1)); - strings_cpp.write(R"(extern char const %[] = R"xyz()xyz" + strings_cpp.write( + R"(extern char const %[] = R"xyz()xyz" )", name.string()); @@ -56,7 +56,8 @@ namespace cppwinrt::strings { auto const size = std::min(size_t{ 16'000 }, remainder.size()); auto const chunk = remainder.substr(0, size); - strings_cpp.write(R"(R"xyz(%)xyz" + strings_cpp.write( + R"(R"xyz(%)xyz" )", chunk); @@ -77,7 +78,8 @@ namespace cppwinrt::strings { writer version_rc; - version_rc.write(R"( + version_rc.write( + R"( #include "winres.h" VS_VERSION_INFO VERSIONINFO @@ -112,7 +114,7 @@ BEGIN END END )", - CPPWINRT_VERSION_STRING); + CPPWINRT_VERSION_STRING); std::filesystem::create_directories(argv[2]); auto const output = std::filesystem::canonical(argv[2]); diff --git a/scratch/main.cpp b/scratch/main.cpp index f12a4d942..c694987e5 100644 --- a/scratch/main.cpp +++ b/scratch/main.cpp @@ -3,5 +3,4 @@ using namespace winrt; int main() -{ -} +{} diff --git a/strings/base_abi.h b/strings/base_abi.h index d1eab2950..71db44a58 100644 --- a/strings/base_abi.h +++ b/strings/base_abi.h @@ -33,7 +33,8 @@ namespace winrt::impl }; }; - struct WINRT_IMPL_NOVTABLE IAgileObject : unknown_abi {}; + struct WINRT_IMPL_NOVTABLE IAgileObject : unknown_abi + {}; struct WINRT_IMPL_NOVTABLE IAgileReference : unknown_abi { @@ -42,9 +43,12 @@ namespace winrt::impl struct WINRT_IMPL_NOVTABLE IMarshal : unknown_abi { - virtual int32_t __stdcall GetUnmarshalClass(guid const& riid, void* pv, uint32_t dwDestContext, void* pvDestContext, uint32_t mshlflags, guid* pCid) noexcept = 0; - virtual int32_t __stdcall GetMarshalSizeMax(guid const& riid, void* pv, uint32_t dwDestContext, void* pvDestContext, uint32_t mshlflags, uint32_t* pSize) noexcept = 0; - virtual int32_t __stdcall MarshalInterface(void* pStm, guid const& riid, void* pv, uint32_t dwDestContext, void* pvDestContext, uint32_t mshlflags) noexcept = 0; + virtual int32_t __stdcall GetUnmarshalClass( + guid const& riid, void* pv, uint32_t dwDestContext, void* pvDestContext, uint32_t mshlflags, guid* pCid) noexcept = 0; + virtual int32_t __stdcall GetMarshalSizeMax( + guid const& riid, void* pv, uint32_t dwDestContext, void* pvDestContext, uint32_t mshlflags, uint32_t* pSize) noexcept = 0; + virtual int32_t __stdcall MarshalInterface( + void* pStm, guid const& riid, void* pv, uint32_t dwDestContext, void* pvDestContext, uint32_t mshlflags) noexcept = 0; virtual int32_t __stdcall UnmarshalInterface(void* pStm, guid const& riid, void** ppv) noexcept = 0; virtual int32_t __stdcall ReleaseMarshalData(void* pStm) noexcept = 0; virtual int32_t __stdcall DisconnectObject(uint32_t dwReserved) noexcept = 0; @@ -86,7 +90,8 @@ namespace winrt::impl struct WINRT_IMPL_NOVTABLE IRestrictedErrorInfo : unknown_abi { - virtual int32_t __stdcall GetErrorDetails(bstr* description, int32_t* error, bstr* restrictedDescription, bstr* capabilitySid) noexcept = 0; + virtual int32_t __stdcall GetErrorDetails( + bstr* description, int32_t* error, bstr* restrictedDescription, bstr* capabilitySid) noexcept = 0; virtual int32_t __stdcall GetReference(bstr* reference) noexcept = 0; }; @@ -111,7 +116,12 @@ namespace winrt::impl struct WINRT_IMPL_NOVTABLE IContextCallback : unknown_abi { - virtual int32_t __stdcall ContextCallback(int32_t(__stdcall* callback)(com_callback_args*), com_callback_args* args, guid const& iid, int method, void* reserved) noexcept = 0; + virtual int32_t __stdcall ContextCallback( + int32_t(__stdcall* callback)(com_callback_args*), + com_callback_args* args, + guid const& iid, + int method, + void* reserved) noexcept = 0; }; struct WINRT_IMPL_NOVTABLE IServerSecurity : unknown_abi @@ -142,23 +152,62 @@ namespace winrt::impl using type = int64_t; }; - template <> inline constexpr guid guid_v{ 0x00000000, 0x0000, 0x0000, { 0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x46 } }; - template <> inline constexpr guid guid_v{ 0xAF86E2E0, 0xB12D, 0x4C6A, { 0x9C,0x5A,0xD7,0xAA,0x65,0x10,0x1E,0x90 } }; - template <> inline constexpr guid guid_v{ 0x00000035, 0x0000, 0x0000, { 0xc0,0x00,0x00,0x00,0x00,0x00,0x00,0x46 } }; - template <> inline constexpr guid guid_v{ 0x94EA2B94, 0xE9CC, 0x49E0, { 0xC0,0xFF,0xEE,0x64,0xCA,0x8F,0x5B,0x90 } }; - template <> inline constexpr guid guid_v{ 0xC03F6A43, 0x65A4, 0x9818, { 0x98,0x7E,0xE0,0xB8,0x10,0xD2,0xA6,0xF2 } }; - template <> inline constexpr guid guid_v{ 0x00000003, 0x0000, 0x0000, { 0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x46 } }; - template <> inline constexpr guid guid_v{ 0x00000146, 0x0000, 0x0000, { 0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x46 } }; - template <> inline constexpr guid guid_v{ 0x17b0e613, 0x942a, 0x422d, { 0x90,0x4c,0xf9,0x0d,0xc7,0x1a,0x7d,0xae } }; - template <> inline constexpr guid guid_v{ 0x1b0d3570, 0x0877, 0x5ec2, { 0x8a,0x2c,0x3b,0x95,0x39,0x50,0x6a,0xca } }; - template <> inline constexpr guid guid_v{ 0x00000037, 0x0000, 0x0000, { 0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x46 } }; - template <> inline constexpr guid guid_v{ 0x00000038, 0x0000, 0x0000, { 0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x46 } }; - template <> inline constexpr guid guid_v{ 0x82BA7092, 0x4C88, 0x427D, { 0xA7,0xBC,0x16,0xDD,0x93,0xFE,0xB6,0x7E } }; - template <> inline constexpr guid guid_v{ 0x1CF2B120, 0x547D, 0x101B, { 0x8E,0x65,0x08,0x00,0x2B,0x2B,0xD1,0x19 } }; - template <> inline constexpr guid guid_v{ 0x5746E5C4, 0x5B97, 0x424C, { 0xB6,0x20,0x28,0x22,0x91,0x57,0x34,0xDD } }; - template <> inline constexpr guid guid_v{ 0x0A299774, 0x3E4E, 0xFC42, { 0x1D,0x9D,0x72,0xCE,0xE1,0x05,0xCA,0x57 } }; - template <> inline constexpr guid guid_v{ 0x000001da, 0x0000, 0x0000, { 0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x46 } }; - template <> inline constexpr guid guid_v{ 0x0000013E, 0x0000, 0x0000, { 0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x46 } }; - template <> inline constexpr guid guid_v{ 0x905a0fef, 0xbc53, 0x11df, { 0x8c,0x49,0x00,0x1e,0x4f,0xc6,0x86,0xda } }; - template <> inline constexpr guid guid_v{ 0x5b0d3235, 0x4dba, 0x4d44, { 0x86,0x5e,0x8f,0x1d,0x0e,0x4f,0xd0,0x4d } }; -} + template <> + inline constexpr guid guid_v{ + 0x00000000, 0x0000, 0x0000, { 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46 } + }; + template <> + inline constexpr guid guid_v{ + 0xAF86E2E0, 0xB12D, 0x4C6A, { 0x9C, 0x5A, 0xD7, 0xAA, 0x65, 0x10, 0x1E, 0x90 } + }; + template <> + inline constexpr guid guid_v{ + 0x00000035, 0x0000, 0x0000, { 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46 } + }; + template <> + inline constexpr guid guid_v{ 0x94EA2B94, 0xE9CC, 0x49E0, { 0xC0, 0xFF, 0xEE, 0x64, 0xCA, 0x8F, 0x5B, 0x90 } }; + template <> + inline constexpr guid guid_v{ 0xC03F6A43, 0x65A4, 0x9818, { 0x98, 0x7E, 0xE0, 0xB8, 0x10, 0xD2, 0xA6, 0xF2 } }; + template <> + inline constexpr guid guid_v{ 0x00000003, 0x0000, 0x0000, { 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46 } }; + template <> + inline constexpr guid guid_v{ + 0x00000146, 0x0000, 0x0000, { 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46 } + }; + template <> + inline constexpr guid guid_v{ 0x17b0e613, 0x942a, 0x422d, { 0x90, 0x4c, 0xf9, 0x0d, 0xc7, 0x1a, 0x7d, 0xae } }; + template <> + inline constexpr guid guid_v{ + 0x1b0d3570, 0x0877, 0x5ec2, { 0x8a, 0x2c, 0x3b, 0x95, 0x39, 0x50, 0x6a, 0xca } + }; + template <> + inline constexpr guid guid_v{ 0x00000037, 0x0000, 0x0000, { 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46 } }; + template <> + inline constexpr guid guid_v{ + 0x00000038, 0x0000, 0x0000, { 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46 } + }; + template <> + inline constexpr guid guid_v{ + 0x82BA7092, 0x4C88, 0x427D, { 0xA7, 0xBC, 0x16, 0xDD, 0x93, 0xFE, 0xB6, 0x7E } + }; + template <> + inline constexpr guid guid_v{ 0x1CF2B120, 0x547D, 0x101B, { 0x8E, 0x65, 0x08, 0x00, 0x2B, 0x2B, 0xD1, 0x19 } }; + template <> + inline constexpr guid guid_v{ + 0x5746E5C4, 0x5B97, 0x424C, { 0xB6, 0x20, 0x28, 0x22, 0x91, 0x57, 0x34, 0xDD } + }; + template <> + inline constexpr guid guid_v{ + 0x0A299774, 0x3E4E, 0xFC42, { 0x1D, 0x9D, 0x72, 0xCE, 0xE1, 0x05, 0xCA, 0x57 } + }; + template <> + inline constexpr guid guid_v{ 0x000001da, 0x0000, 0x0000, { 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46 } }; + template <> + inline constexpr guid guid_v{ 0x0000013E, 0x0000, 0x0000, { 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46 } }; + template <> + inline constexpr guid guid_v{ 0x905a0fef, 0xbc53, 0x11df, { 0x8c, 0x49, 0x00, 0x1e, 0x4f, 0xc6, 0x86, 0xda } }; + template <> + inline constexpr guid guid_v{ + 0x5b0d3235, 0x4dba, 0x4d44, { 0x86, 0x5e, 0x8f, 0x1d, 0x0e, 0x4f, 0xd0, 0x4d } + }; +} // namespace winrt::impl diff --git a/strings/base_activation.h b/strings/base_activation.h index be24c6ad9..e2be7473d 100644 --- a/strings/base_activation.h +++ b/strings/base_activation.h @@ -19,7 +19,8 @@ namespace winrt::impl using library_handle = handle_type; template - WINRT_IMPL_NOINLINE hresult get_runtime_activation_factory_impl(param::hstring const& name, winrt::guid const& guid, void** result) noexcept + WINRT_IMPL_NOINLINE hresult + get_runtime_activation_factory_impl(param::hstring const& name, winrt::guid const& guid, void** result) noexcept { if (winrt_activation_handler) { @@ -30,7 +31,8 @@ namespace winrt::impl if (hr == impl::error_not_initialized) { - auto usage = reinterpret_cast(WINRT_IMPL_GetProcAddress(load_library(L"combase.dll"), "CoIncrementMTAUsage")); + auto usage = reinterpret_cast( + WINRT_IMPL_GetProcAddress(load_library(L"combase.dll"), "CoIncrementMTAUsage")); if (!usage) { @@ -65,7 +67,8 @@ namespace winrt::impl continue; } - auto library_call = reinterpret_cast(WINRT_IMPL_GetProcAddress(library.get(), "DllGetActivationFactory")); + auto library_call = reinterpret_cast( + WINRT_IMPL_GetProcAddress(library.get(), "DllGetActivationFactory")); if (!library_call) { @@ -99,9 +102,10 @@ namespace winrt::impl template hresult get_runtime_activation_factory(param::hstring const& name, void** result) noexcept { - return get_runtime_activation_factory_impl>(name, guid_of(), result); + return get_runtime_activation_factory_impl>( + name, guid_of(), result); } -} +} // namespace winrt::impl WINRT_EXPORT namespace winrt { @@ -120,7 +124,7 @@ WINRT_EXPORT namespace winrt #endif #if defined(__GNUC__) && defined(__aarch64__) -#define WINRT_IMPL_INTERLOCKED_READ_MEMORY_BARRIER __asm__ __volatile__ ("dmb ish"); +#define WINRT_IMPL_INTERLOCKED_READ_MEMORY_BARRIER __asm__ __volatile__("dmb ish"); #elif defined _M_ARM64 #define WINRT_IMPL_INTERLOCKED_READ_MEMORY_BARRIER (__dmb(_ARM64_BARRIER_ISH)); #endif @@ -173,8 +177,7 @@ namespace winrt::impl #pragma clang diagnostic pop #endif - template - T* interlocked_read_pointer(T* const volatile* target) noexcept + template T* interlocked_read_pointer(T* const volatile* target) noexcept { #ifdef _WIN64 return (T*)interlocked_read_64((int64_t*)target); @@ -187,7 +190,7 @@ namespace winrt::impl inline constexpr uint32_t memory_allocation_alignment{ 16 }; #ifdef _MSC_VER #pragma warning(push) -#pragma warning(disable:4324) // structure was padded due to alignment specifier +#pragma warning(disable : 4324) // structure was padded due to alignment specifier #endif struct alignas(16) slist_entry { @@ -234,7 +237,8 @@ namespace winrt::impl factory_count_guard(factory_count_guard const&) = delete; factory_count_guard& operator=(factory_count_guard const&) = delete; - explicit factory_count_guard(size_t& count) noexcept : m_count(count) + explicit factory_count_guard(size_t& count) noexcept : + m_count(count) { #ifndef WINRT_NO_MODULE_LOCK #ifdef _WIN64 @@ -257,7 +261,6 @@ namespace winrt::impl } private: - size_t& m_count; }; @@ -331,13 +334,14 @@ namespace winrt::impl // entry->next must be read before entry->clear() is called since the InterlockedCompareExchange // inside clear() will allow another thread to add the entry back to the cache. slist_entry* next = entry->next; - reinterpret_cast(reinterpret_cast(entry) - offsetof(factory_cache_entry_base, m_next))->clear(); + reinterpret_cast( + reinterpret_cast(entry) - offsetof(factory_cache_entry_base, m_next)) + ->clear(); entry = next; } } private: - alignas(memory_allocation_alignment) slist_header m_list; }; @@ -347,11 +351,9 @@ namespace winrt::impl return cache; } - template - struct factory_cache_entry : factory_cache_entry_base + template struct factory_cache_entry : factory_cache_entry_base { - template - WINRT_IMPL_NOINLINE auto call(F&& callback) + template WINRT_IMPL_NOINLINE auto call(F&& callback) { #ifdef WINRT_DIAGNOSTICS get_diagnostics_info().add_factory(); @@ -371,7 +373,8 @@ namespace winrt::impl { factory_count_guard const guard(m_value.count); - if (nullptr == _InterlockedCompareExchangePointer(reinterpret_cast(&m_value.object), *reinterpret_cast(&object), nullptr)) + if (nullptr == _InterlockedCompareExchangePointer( + reinterpret_cast(&m_value.object), *reinterpret_cast(&object), nullptr)) { *reinterpret_cast(&object) = nullptr; #ifndef WINRT_NO_MODULE_LOCK @@ -384,8 +387,7 @@ namespace winrt::impl } }; - template - factory_cache_entry factory_cache_entry_v{}; + template factory_cache_entry factory_cache_entry_v{}; template auto call_factory(F&& callback) @@ -442,18 +444,23 @@ namespace winrt::impl return { result, take_ownership_from_abi }; } - template struct produce : produce_base + template + struct produce : produce_base { - int32_t __stdcall ActivateInstance(void** instance) noexcept final try + int32_t __stdcall ActivateInstance(void** instance) noexcept final + try { *instance = nullptr; typename D::abi_guard guard(this->shim()); *instance = detach_abi(this->shim().ActivateInstance()); return 0; } - catch (...) { return to_hresult(); } + catch (...) + { + return to_hresult(); + } }; -} +} // namespace winrt::impl WINRT_EXPORT namespace winrt { @@ -484,10 +491,7 @@ WINRT_EXPORT namespace winrt // Normally, the callback avoids having to return a ref-counted object and the resulting AddRef/Release bump. // In this case we do want a unique reference, so we use the lambda to return one and thus produce an // AddRef'd object that is returned to the caller. - return impl::call_factory([](auto&& factory) - { - return factory; - }); + return impl::call_factory([](auto&& factory) { return factory; }); } template @@ -497,7 +501,7 @@ WINRT_EXPORT namespace winrt } template - auto try_get_activation_factory(hresult_error& exception) noexcept + auto try_get_activation_factory(hresult_error & exception) noexcept { return impl::try_get_activation_factory(name_of(), &exception); } @@ -535,27 +539,28 @@ WINRT_EXPORT namespace winrt { struct IActivationFactory : IInspectable { - IActivationFactory(std::nullptr_t = nullptr) noexcept {} - IActivationFactory(void* ptr, take_ownership_from_abi_t) noexcept : IInspectable(ptr, take_ownership_from_abi) {} + IActivationFactory(std::nullptr_t = nullptr) noexcept + {} + IActivationFactory(void* ptr, take_ownership_from_abi_t) noexcept : + IInspectable(ptr, take_ownership_from_abi) + {} - template - T ActivateInstance() const + template T ActivateInstance() const { IInspectable instance; check_hresult((*(impl::abi_t**)this)->ActivateInstance(put_abi(instance))); return instance.try_as(); } }; - } + } // namespace Windows::Foundation } namespace winrt::impl { - template - T fast_activate(Windows::Foundation::IActivationFactory const& factory) + template T fast_activate(Windows::Foundation::IActivationFactory const& factory) { void* result{}; check_hresult((*(impl::abi_t**)&factory)->ActivateInstance(&result)); - return{ result, take_ownership_from_abi }; + return { result, take_ownership_from_abi }; } -} +} // namespace winrt::impl diff --git a/strings/base_agile_ref.h b/strings/base_agile_ref.h index b85cb7e61..6034840fd 100644 --- a/strings/base_agile_ref.h +++ b/strings/base_agile_ref.h @@ -1,7 +1,7 @@ WINRT_EXPORT namespace winrt { -#if defined (WINRT_NO_MODULE_LOCK) +#if defined(WINRT_NO_MODULE_LOCK) // Defining WINRT_NO_MODULE_LOCK is appropriate for apps (executables) or pinned DLLs (that don't support unloading) // and can thus avoid the synchronization overhead imposed by the default module lock. @@ -29,7 +29,7 @@ WINRT_EXPORT namespace winrt return lock{}; } -#elif defined (WINRT_CUSTOM_MODULE_LOCK) +#elif defined(WINRT_CUSTOM_MODULE_LOCK) // When WINRT_CUSTOM_MODULE_LOCK is defined, you must provide an implementation of winrt::get_module_lock() // that returns an object that implements operator++ and operator--. @@ -49,11 +49,9 @@ WINRT_EXPORT namespace winrt namespace winrt::impl { - template - struct module_lock_updater; + template struct module_lock_updater; - template<> - struct module_lock_updater + template <> struct module_lock_updater { module_lock_updater() noexcept { @@ -66,8 +64,8 @@ namespace winrt::impl } }; - template<> - struct module_lock_updater {}; + template <> struct module_lock_updater + {}; using update_module_lock = module_lock_updater; @@ -80,14 +78,14 @@ namespace winrt::impl { return WINRT_IMPL_RoGetAgileReference(0, iid, object, reference); } -} +} // namespace winrt::impl WINRT_EXPORT namespace winrt { - template - struct agile_ref + template struct agile_ref { - agile_ref(std::nullptr_t = nullptr) noexcept {} + agile_ref(std::nullptr_t = nullptr) noexcept + {} agile_ref(impl::com_ref const& object) { @@ -115,14 +113,12 @@ WINRT_EXPORT namespace winrt } private: - com_ptr m_ref; }; - template agile_ref(T const&)->agile_ref>; + template agile_ref(T const&) -> agile_ref>; - template - agile_ref> make_agile(T const& object) + template agile_ref> make_agile(T const& object) { return object; } diff --git a/strings/base_array.h b/strings/base_array.h index a4f570614..7b815b605 100644 --- a/strings/base_array.h +++ b/strings/base_array.h @@ -1,8 +1,7 @@ WINRT_EXPORT namespace winrt { - template - struct array_view + template struct array_view { using value_type = T; using size_type = uint32_t; @@ -18,13 +17,11 @@ WINRT_EXPORT namespace winrt array_view() noexcept = default; array_view(pointer data, size_type size) noexcept : - m_data(data), - m_size(size) + m_data(data), m_size(size) {} array_view(pointer first, pointer last) noexcept : - m_data(first), - m_size(static_cast(last - first)) + m_data(first), m_size(static_cast(last - first)) {} array_view(std::initializer_list value) noexcept : @@ -34,7 +31,7 @@ WINRT_EXPORT namespace winrt #ifdef __cpp_lib_span template array_view(std::span span) noexcept : - array_view(span.data(), static_cast(span.size())) + array_view(span.data(), static_cast(span.size())) { WINRT_ASSERT(span.size() <= UINT_MAX); } @@ -46,21 +43,19 @@ WINRT_EXPORT namespace winrt #endif template - array_view(C(&value)[N]) noexcept : + array_view(C (&value)[N]) noexcept : array_view(value, N) {} template array_view(std::vector& value) noexcept : array_view(data(value), static_cast(value.size())) - { - } + {} template array_view(std::vector const& value) noexcept : array_view(data(value), static_cast(value.size())) - { - } + {} template array_view(std::array& value) noexcept : @@ -73,8 +68,8 @@ WINRT_EXPORT namespace winrt {} template - array_view(array_view const& other, - std::enable_if_t, int> = 0) noexcept : + array_view(array_view const& other, std::enable_if_t, int> = 0) noexcept + : array_view(other.data(), other.size()) {} @@ -113,13 +108,13 @@ WINRT_EXPORT namespace winrt reference front() noexcept { WINRT_ASSERT(m_size > 0); - return*m_data; + return *m_data; } const_reference front() const noexcept { WINRT_ASSERT(m_size > 0); - return*m_data; + return *m_data; } reference back() noexcept @@ -210,40 +205,39 @@ WINRT_EXPORT namespace winrt } protected: - pointer m_data{ nullptr }; size_type m_size{ 0 }; private: - - template - auto data(std::vector const& value) noexcept + template auto data(std::vector const& value) noexcept { - static_assert(!std::is_same_v, "Cannot use std::vector as an array_view. Consider std::array or std::unique_ptr."); + static_assert( + !std::is_same_v, + "Cannot use std::vector as an array_view. Consider std::array or std::unique_ptr."); return value.data(); } - template - auto data(std::vector& value) noexcept + template auto data(std::vector& value) noexcept { - static_assert(!std::is_same_v, "Cannot use std::vector as an array_view. Consider std::array or std::unique_ptr."); + static_assert( + !std::is_same_v, + "Cannot use std::vector as an array_view. Consider std::array or std::unique_ptr."); return value.data(); } }; template array_view(C(&value)[N]) -> array_view; - template array_view(std::vector& value) -> array_view; + template array_view(std::vector & value) -> array_view; template array_view(std::vector const& value) -> array_view; - template array_view(std::array& value) -> array_view; + template array_view(std::array & value) -> array_view; template array_view(std::array const& value) -> array_view; #ifdef __cpp_lib_span - template array_view(std::span& value) -> array_view; + template array_view(std::span & value) -> array_view; template array_view(std::span const& value) -> array_view; #endif - template - struct com_array : array_view + template struct com_array : array_view { using typename array_view::value_type; using typename array_view::size_type; @@ -267,8 +261,7 @@ WINRT_EXPORT namespace winrt com_array(void* ptr, uint32_t const count, take_ownership_from_abi_t) noexcept : array_view(static_cast(ptr), static_cast(ptr) + count) - { - } + {} com_array(size_type const count, value_type const& value) { @@ -295,15 +288,15 @@ WINRT_EXPORT namespace winrt #ifdef __cpp_lib_span template - explicit com_array(std::span span) noexcept : - com_array(span.data(), span.data() + span.size()) + explicit com_array(std::span span) noexcept : + com_array(span.data(), span.data() + span.size()) { WINRT_ASSERT(span.size() <= UINT_MAX); } #endif template - explicit com_array(U const(&value)[N]) : + explicit com_array(U const (&value)[N]) : com_array(value, value + N) {} @@ -330,7 +323,7 @@ WINRT_EXPORT namespace winrt this->m_size = other.m_size; other.m_data = nullptr; other.m_size = 0; - return*this; + return *this; } ~com_array() noexcept @@ -340,7 +333,10 @@ WINRT_EXPORT namespace winrt void clear() noexcept { - if (this->m_data == nullptr) { return; } + if (this->m_data == nullptr) + { + return; + } std::destroy(this->begin(), this->end()); @@ -356,7 +352,6 @@ WINRT_EXPORT namespace winrt } private: - void alloc(size_type const size) { WINRT_ASSERT(this->empty()); @@ -391,8 +386,7 @@ WINRT_EXPORT namespace winrt return result; } - template - friend std::pair> detach_abi(com_array& object) noexcept; + template friend std::pair> detach_abi(com_array& object) noexcept; }; template com_array(uint32_t, C const&) -> com_array>; @@ -407,38 +401,46 @@ WINRT_EXPORT namespace winrt template com_array(std::span const& value) -> com_array>; #endif - namespace impl { template inline constexpr bool array_comparable = std::is_same_v, std::remove_cv_t>; } - template , int> = 0> + template , int> = 0> bool operator==(array_view const& left, array_view const& right) noexcept { return std::equal(left.begin(), left.end(), right.begin(), right.end()); } - template , int> = 0> + template , int> = 0> bool operator<(array_view const& left, array_view const& right) noexcept { return std::lexicographical_compare(left.begin(), left.end(), right.begin(), right.end()); } template , int> = 0> - bool operator!=(array_view const& left, array_view const& right) noexcept { return !(left == right); } - template , int> = 0> - bool operator>(array_view const& left, array_view const& right) noexcept { return right < left; } - template , int> = 0> - bool operator<=(array_view const& left, array_view const& right) noexcept { return !(right < left); } + bool operator!=(array_view const& left, array_view const& right) noexcept + { + return !(left == right); + } + template , int> = 0> + bool operator>(array_view const& left, array_view const& right) noexcept + { + return right < left; + } + template , int> = 0> + bool operator<=(array_view const& left, array_view const& right) noexcept + { + return !(right < left); + } template , int> = 0> - bool operator>=(array_view const& left, array_view const& right) noexcept { return !(left < right); } + bool operator>=(array_view const& left, array_view const& right) noexcept + { + return !(left < right); + } - template - auto get_abi(array_view object) noexcept + template auto get_abi(array_view object) noexcept { auto data = object.size() ? object.data() : (T*)alignof(T); @@ -452,8 +454,7 @@ WINRT_EXPORT namespace winrt } } - template - auto put_abi(array_view object) noexcept + template auto put_abi(array_view object) noexcept { if constexpr (!std::is_trivially_destructible_v) { @@ -463,21 +464,18 @@ WINRT_EXPORT namespace winrt return get_abi(object); } - template - auto put_abi(com_array& object) noexcept + template auto put_abi(com_array & object) noexcept { object.clear(); return reinterpret_cast*>(&object); } - template - std::pair> detach_abi(com_array& object) noexcept + template std::pair> detach_abi(com_array & object) noexcept { return object.detach_abi(); } - template - auto detach_abi(com_array&& object) noexcept + template auto detach_abi(com_array && object) noexcept { return detach_abi(object); } @@ -485,12 +483,12 @@ WINRT_EXPORT namespace winrt namespace winrt::impl { - template - struct array_size_proxy + template struct array_size_proxy { array_size_proxy& operator=(array_size_proxy const&) = delete; - array_size_proxy(com_array& value) noexcept : m_value(value) + array_size_proxy(com_array& value) noexcept : + m_value(value) {} ~array_size_proxy() noexcept @@ -510,21 +508,19 @@ namespace winrt::impl } private: - com_array& m_value; uint32_t m_size{ 0 }; }; - template - array_size_proxy put_size_abi(com_array& object) noexcept + template array_size_proxy put_size_abi(com_array& object) noexcept { return array_size_proxy(object); } - template - struct com_array_proxy + template struct com_array_proxy { - com_array_proxy(uint32_t* size, winrt::impl::arg_out* value) noexcept : m_size(size), m_value(value) + com_array_proxy(uint32_t* size, winrt::impl::arg_out* value) noexcept : + m_size(size), m_value(value) {} ~com_array_proxy() noexcept @@ -544,17 +540,15 @@ namespace winrt::impl } private: - uint32_t* m_size; arg_out* m_value; com_array m_temp; }; -} +} // namespace winrt::impl WINRT_EXPORT namespace winrt { - template - auto detach_abi(uint32_t* __valueSize, impl::arg_out* value) noexcept + template auto detach_abi(uint32_t * __valueSize, impl::arg_out * value) noexcept { return impl::com_array_proxy(__valueSize, value); } diff --git a/strings/base_chrono.h b/strings/base_chrono.h index d48cd703b..05be540d6 100644 --- a/strings/base_chrono.h +++ b/strings/base_chrono.h @@ -7,15 +7,14 @@ WINRT_EXPORT namespace winrt file_time() noexcept = default; - constexpr explicit file_time(uint64_t const value) noexcept : value(value) - { - } + constexpr explicit file_time(uint64_t const value) noexcept : + value(value) + {} #ifdef _FILETIME_ - constexpr file_time(FILETIME const& value) noexcept - : value(value.dwLowDateTime | (static_cast(value.dwHighDateTime) << 32)) - { - } + constexpr file_time(FILETIME const& value) noexcept : + value(value.dwLowDateTime | (static_cast(value.dwHighDateTime) << 32)) + {} operator FILETIME() const noexcept { @@ -42,7 +41,8 @@ WINRT_EXPORT namespace winrt static time_t to_time_t(time_point const& time) noexcept { - return static_cast(std::chrono::system_clock::to_time_t(std::chrono::time_point_cast(to_sys(time)))); + return static_cast(std::chrono::system_clock::to_time_t( + std::chrono::time_point_cast(to_sys(time)))); } static time_point from_time_t(time_t time) noexcept @@ -71,24 +71,25 @@ WINRT_EXPORT namespace winrt } template - static std::chrono::time_point> - to_sys(std::chrono::time_point const& tp) + static std::chrono::time_point> to_sys( + std::chrono::time_point const& tp) { return epoch + tp.time_since_epoch(); } template - static std::chrono::time_point> - from_sys(std::chrono::time_point const& tp) + static std::chrono::time_point> from_sys( + std::chrono::time_point const& tp) { using result_t = std::chrono::time_point>; return result_t{ tp - epoch }; } private: - // system_clock epoch is 00:00:00, Jan 1 1970. // This is 11644473600 seconds after Windows FILETIME epoch of 00:00:00, Jan 1 1601. - static constexpr std::chrono::time_point epoch{ std::chrono::seconds{ -11644473600 } }; + static constexpr std::chrono::time_point epoch{ + std::chrono::seconds{ -11644473600 } + }; }; } diff --git a/strings/base_collections.h b/strings/base_collections.h index cba0864b3..3287ca033 100644 --- a/strings/base_collections.h +++ b/strings/base_collections.h @@ -3,28 +3,24 @@ namespace winrt::impl { namespace wfc = Windows::Foundation::Collections; - template - auto consume_Windows_Foundation_Collections_IIterable::begin() const + template auto consume_Windows_Foundation_Collections_IIterable::begin() const { return get_begin_iterator(static_cast(*this)); } - template - auto consume_Windows_Foundation_Collections_IIterable::end() const + template auto consume_Windows_Foundation_Collections_IIterable::end() const { return get_end_iterator(static_cast(*this)); } - template - struct key_value_pair; + template struct key_value_pair; template - struct key_value_pair> : implements>, wfc::IKeyValuePair> + struct key_value_pair> + : implements>, wfc::IKeyValuePair> { key_value_pair(K key, V value) : - m_key(std::move(key)), - m_value(std::move(value)) - { - } + m_key(std::move(key)), m_value(std::move(value)) + {} K Key() const { @@ -37,16 +33,15 @@ namespace winrt::impl } private: - K const m_key; V const m_value; }; - template - struct is_key_value_pair : std::false_type {}; + template struct is_key_value_pair : std::false_type + {}; - template - struct is_key_value_pair> : std::true_type {}; + template struct is_key_value_pair> : std::true_type + {}; struct input_scope { @@ -64,7 +59,6 @@ namespace winrt::impl } private: - bool m_invalid{}; }; @@ -73,12 +67,10 @@ namespace winrt::impl struct iterator_type { iterator_type(no_collection_version const&) noexcept - { - } + {} void check_version(no_collection_version const&) const noexcept - { - } + {} }; }; @@ -88,8 +80,7 @@ namespace winrt::impl { iterator_type(collection_version const& version) noexcept : m_snapshot(version.get_version()) - { - } + {} void check_version(collection_version const& version) const { @@ -100,7 +91,6 @@ namespace winrt::impl } private: - uint32_t const m_snapshot; }; @@ -115,12 +105,10 @@ namespace winrt::impl } private: - std::atomic m_version{}; }; - template - struct range_container + template struct range_container { T const first; T const last; @@ -135,4 +123,4 @@ namespace winrt::impl return last; } }; -} +} // namespace winrt::impl diff --git a/strings/base_collections_base.h b/strings/base_collections_base.h index f3ede9ed4..c641e0663 100644 --- a/strings/base_collections_base.h +++ b/strings/base_collections_base.h @@ -1,6 +1,7 @@ namespace winrt::impl { - struct nop_lock_guard {}; + struct nop_lock_guard + {}; struct single_threaded_collection_base { @@ -19,24 +20,21 @@ namespace winrt::impl { [[nodiscard]] auto acquire_exclusive() const { - return slim_lock_guard{m_mutex}; + return slim_lock_guard{ m_mutex }; } [[nodiscard]] auto acquire_shared() const { - return slim_shared_lock_guard{m_mutex}; + return slim_shared_lock_guard{ m_mutex }; } private: - mutable slim_mutex m_mutex; }; - template - using container_type_t = std::decay_t().get_container())>; + template using container_type_t = std::decay_t().get_container())>; - template - struct removed_values + template struct removed_values { void assign(container_type_t& value) { @@ -56,12 +54,11 @@ namespace winrt::impl } }; - template - struct removed_value + template struct removed_value { // Trivially destructible; okay to run destructor under lock - template - void assign(U&&) {} + template void assign(U&&) + {} }; template @@ -69,27 +66,23 @@ namespace winrt::impl { std::optional m_value; - template - void assign(U&& value) + template void assign(U&& value) { m_value.emplace(std::move(value)); } }; -} +} // namespace winrt::impl WINRT_EXPORT namespace winrt { - template - struct iterable_base : Version + template struct iterable_base : Version { - template - static constexpr auto const& wrap_value(U const& value) noexcept + template static constexpr auto const& wrap_value(U const& value) noexcept { return value; } - template - static constexpr auto const& unwrap_value(U const& value) noexcept + template static constexpr auto const& unwrap_value(U const& value) noexcept { return value; } @@ -113,8 +106,7 @@ WINRT_EXPORT namespace winrt } protected: - - template + template auto copy_n(InputIt first, Size count, OutputIt result) const { if constexpr (std::is_same_v().get_container().begin())>> && !impl::is_key_value_pair::value) @@ -123,22 +115,27 @@ WINRT_EXPORT namespace winrt } else { - return std::transform(first, std::next(first, count), result, [&](auto&& value) - { - if constexpr (!impl::is_key_value_pair::value) + return std::transform( + first, + std::next(first, count), + result, + [&](auto&& value) { - return static_cast(*this).unwrap_value(value); - } - else - { - return make>(static_cast(*this).unwrap_value(value.first), static_cast(*this).unwrap_value(value.second)); - } - }); + if constexpr (!impl::is_key_value_pair::value) + { + return static_cast(*this).unwrap_value(value); + } + else + { + return make>( + static_cast(*this).unwrap_value(value.first), + static_cast(*this).unwrap_value(value.second)); + } + }); } } private: - struct iterator : Version::iterator_type, implements> { void abi_enter() @@ -152,9 +149,7 @@ WINRT_EXPORT namespace winrt } explicit iterator(D* const owner) noexcept : - Version::iterator_type(*owner), - m_current(owner->get_container().begin()), - m_end(owner->get_container().end()) + Version::iterator_type(*owner), m_current(owner->get_container().begin()), m_end(owner->get_container().end()) { m_owner.copy_from(owner); } @@ -199,7 +194,6 @@ WINRT_EXPORT namespace winrt } private: - T current_value_withlock() const { WINRT_ASSERT(m_current != m_end); @@ -209,7 +203,8 @@ WINRT_EXPORT namespace winrt } else { - return make>(m_owner->unwrap_value(m_current->first), m_owner->unwrap_value(m_current->second)); + return make>( + m_owner->unwrap_value(m_current->first), m_owner->unwrap_value(m_current->second)); } } @@ -254,7 +249,8 @@ WINRT_EXPORT namespace winrt throw hresult_out_of_bounds(); } - return static_cast(*this).unwrap_value(*std::next(static_cast(*this).get_container().begin(), index)); + return static_cast(*this).unwrap_value( + *std::next(static_cast(*this).get_container().begin(), index)); } uint32_t Size() const noexcept @@ -266,10 +262,10 @@ WINRT_EXPORT namespace winrt bool IndexOf(T const& value, uint32_t& index) const noexcept { [[maybe_unused]] auto guard = static_cast(*this).acquire_shared(); - auto first = std::find_if(static_cast(*this).get_container().begin(), static_cast(*this).get_container().end(), [&](auto&& match) - { - return value == static_cast(*this).unwrap_value(match); - }); + auto first = std::find_if( + static_cast(*this).get_container().begin(), + static_cast(*this).get_container().end(), + [&](auto&& match) { return value == static_cast(*this).unwrap_value(match); }); index = static_cast(first - static_cast(*this).get_container().begin()); return index < container_size(); @@ -289,15 +285,14 @@ WINRT_EXPORT namespace winrt } private: - uint32_t container_size() const noexcept { - return static_cast(std::distance(static_cast(*this).get_container().begin(), static_cast(*this).get_container().end())); + return static_cast(std::distance( + static_cast(*this).get_container().begin(), static_cast(*this).get_container().end())); } }; - template - struct vector_base : vector_view_base + template struct vector_base : vector_view_base { Windows::Foundation::Collections::IVectorView GetView() const noexcept { @@ -329,7 +324,8 @@ WINRT_EXPORT namespace winrt } this->increment_version(); - static_cast(*this).get_container().insert(static_cast(*this).get_container().begin() + index, static_cast(*this).wrap_value(value)); + static_cast(*this).get_container().insert( + static_cast(*this).get_container().begin() + index, static_cast(*this).wrap_value(value)); } void RemoveAt(uint32_t const index) @@ -390,9 +386,7 @@ WINRT_EXPORT namespace winrt } private: - - template - void assign(InputIt first, InputIt last) + template void assign(InputIt first, InputIt last) { if constexpr (std::is_same_v::value_type>) { @@ -404,16 +398,16 @@ WINRT_EXPORT namespace winrt WINRT_ASSERT(container.empty()); container.reserve(std::distance(first, last)); - std::transform(first, last, std::back_inserter(container), [&](auto&& value) - { - return static_cast(*this).wrap_value(value); - }); + std::transform( + first, + last, + std::back_inserter(container), + [&](auto&& value) { return static_cast(*this).wrap_value(value); }); } } }; - template - struct observable_vector_base : vector_base + template struct observable_vector_base : vector_base { event_token VectorChanged(Windows::Foundation::Collections::VectorChangedEventHandler const& handler) { @@ -468,23 +462,19 @@ WINRT_EXPORT namespace winrt } protected: - void call_changed(Windows::Foundation::Collections::CollectionChange const change, uint32_t const index) { m_changed(static_cast(*this), make(change, index)); } private: - event> m_changed; struct args : implements { args(Windows::Foundation::Collections::CollectionChange const change, uint32_t const index) noexcept : - m_change(change), - m_index(index) - { - } + m_change(change), m_index(index) + {} Windows::Foundation::Collections::CollectionChange CollectionChange() const noexcept { @@ -497,7 +487,6 @@ WINRT_EXPORT namespace winrt } private: - Windows::Foundation::Collections::CollectionChange const m_change; uint32_t const m_index; }; @@ -528,7 +517,8 @@ WINRT_EXPORT namespace winrt bool HasKey(K const& key) const noexcept { [[maybe_unused]] auto guard = static_cast(*this).acquire_shared(); - return static_cast(*this).get_container().find(static_cast(*this).wrap_value(key)) != static_cast(*this).get_container().end(); + return static_cast(*this).get_container().find(static_cast(*this).wrap_value(key)) != + static_cast(*this).get_container().end(); } void Split(Windows::Foundation::Collections::IMapView& first, Windows::Foundation::Collections::IMapView& second) const noexcept @@ -538,8 +528,7 @@ WINRT_EXPORT namespace winrt } }; - template - struct map_base : map_view_base + template struct map_base : map_view_base { Windows::Foundation::Collections::IMapView GetView() const { @@ -552,7 +541,8 @@ WINRT_EXPORT namespace winrt [[maybe_unused]] auto guard = static_cast(*this).acquire_exclusive(); this->increment_version(); - auto [itr, added] = static_cast(*this).get_container().emplace(static_cast(*this).wrap_value(key), static_cast(*this).wrap_value(value)); + auto [itr, added] = static_cast(*this).get_container().emplace( + static_cast(*this).wrap_value(key), static_cast(*this).wrap_value(value)); if (!added) { oldValue.assign(itr->second); @@ -587,8 +577,7 @@ WINRT_EXPORT namespace winrt } }; - template - struct observable_map_base : map_base + template struct observable_map_base : map_base { event_token MapChanged(Windows::Foundation::Collections::MapChangedEventHandler const& handler) { @@ -620,23 +609,19 @@ WINRT_EXPORT namespace winrt } protected: - void call_changed(Windows::Foundation::Collections::CollectionChange const change, K const& key) { m_changed(static_cast(*this), make(change, key)); } private: - event> m_changed; struct args : implements> { args(Windows::Foundation::Collections::CollectionChange const change, K const& key) noexcept : - m_change(change), - m_key(key) - { - } + m_change(change), m_key(key) + {} Windows::Foundation::Collections::CollectionChange CollectionChange() const noexcept { @@ -649,7 +634,6 @@ WINRT_EXPORT namespace winrt } private: - Windows::Foundation::Collections::CollectionChange const m_change; K const m_key; }; diff --git a/strings/base_collections_input_iterable.h b/strings/base_collections_input_iterable.h index e75211c30..6f65007d9 100644 --- a/strings/base_collections_input_iterable.h +++ b/strings/base_collections_input_iterable.h @@ -2,15 +2,14 @@ namespace winrt::impl { template - struct input_iterable : - implements, non_agile, no_weak_ref, wfc::IIterable>, - iterable_base, T> + struct input_iterable : implements, non_agile, no_weak_ref, wfc::IIterable>, + iterable_base, T> { static_assert(std::is_same_v>, "Must be constructed with rvalue."); - explicit input_iterable(Container&& values) : m_values(std::forward(values)) - { - } + explicit input_iterable(Container&& values) : + m_values(std::forward(values)) + {} auto& get_container() const noexcept { @@ -18,24 +17,22 @@ namespace winrt::impl } private: - Container const m_values; }; template - struct scoped_input_iterable : - input_scope, - implements, non_agile, no_weak_ref, wfc::IIterable>, - iterable_base, T> + struct scoped_input_iterable : input_scope, + implements, non_agile, no_weak_ref, wfc::IIterable>, + iterable_base, T> { void abi_enter() const { check_scope(); } - scoped_input_iterable(InputIt first, InputIt last) : m_begin(first), m_end(last) - { - } + scoped_input_iterable(InputIt first, InputIt last) : + m_begin(first), m_end(last) + {} auto get_container() const noexcept { @@ -44,24 +41,20 @@ namespace winrt::impl #if defined(_DEBUG) && !defined(WINRT_NO_MAKE_DETECTION) void use_make_function_to_create_this_object() final - { - } + {} #endif private: - InputIt const m_begin; InputIt const m_end; }; - template - auto make_input_iterable(Container&& values) + template auto make_input_iterable(Container&& values) { return make>(std::forward(values)); } - template - auto make_scoped_input_iterable(InputIt first, InputIt last) + template auto make_scoped_input_iterable(InputIt first, InputIt last) { using interface_type = wfc::IIterable; std::pair result; @@ -70,24 +63,23 @@ namespace winrt::impl result.second = ptr; return result; } -} +} // namespace winrt::impl WINRT_EXPORT namespace winrt::param { - template - struct iterable + template struct iterable { using value_type = T; using interface_type = Windows::Foundation::Collections::IIterable; iterable(std::nullptr_t) noexcept - { - } + {} iterable(iterable const& values) = delete; iterable& operator=(iterable const& values) = delete; - iterable(interface_type const& values) noexcept : m_owned(false) + iterable(interface_type const& values) noexcept : + m_owned(false) { attach_abi(m_pair.first, winrt::get_abi(values)); } @@ -99,28 +91,28 @@ WINRT_EXPORT namespace winrt::param } template - iterable(std::vector&& values) : m_pair(impl::make_input_iterable(std::move(values)), nullptr) - { - } + iterable(std::vector&& values) : + m_pair(impl::make_input_iterable(std::move(values)), nullptr) + {} template - iterable(std::vector const& values) : m_pair(impl::make_scoped_input_iterable(values.begin(), values.end())) - { - } + iterable(std::vector const& values) : + m_pair(impl::make_scoped_input_iterable(values.begin(), values.end())) + {} - iterable(std::initializer_list values) : m_pair(impl::make_scoped_input_iterable(values.begin(), values.end())) - { - } + iterable(std::initializer_list values) : + m_pair(impl::make_scoped_input_iterable(values.begin(), values.end())) + {} template , int> = 0> - iterable(std::initializer_list values) : m_pair(impl::make_scoped_input_iterable(values.begin(), values.end())) - { - } + iterable(std::initializer_list values) : + m_pair(impl::make_scoped_input_iterable(values.begin(), values.end())) + {} - template - iterable(InputIt first, InputIt last) : m_pair(impl::make_scoped_input_iterable(first, last)) - { - } + template + iterable(InputIt first, InputIt last) : + m_pair(impl::make_scoped_input_iterable(first, last)) + {} ~iterable() noexcept { @@ -135,31 +127,29 @@ WINRT_EXPORT namespace winrt::param } } - operator interface_type const& () const noexcept + operator interface_type const&() const noexcept { return m_pair.first; } private: - std::pair m_pair; bool m_owned{ true }; }; - template - struct iterable> + template struct iterable> { using value_type = Windows::Foundation::Collections::IKeyValuePair; using interface_type = Windows::Foundation::Collections::IIterable; iterable(std::nullptr_t) noexcept - { - } + {} iterable(iterable const& values) = delete; iterable& operator=(iterable const& values) = delete; - iterable(interface_type const& values) noexcept : m_owned(false) + iterable(interface_type const& values) noexcept : + m_owned(false) { attach_abi(m_pair.first, winrt::get_abi(values)); } @@ -171,33 +161,33 @@ WINRT_EXPORT namespace winrt::param } template - iterable(std::map&& values) : m_pair(impl::make_input_iterable(std::move(values)), nullptr) - { - } + iterable(std::map&& values) : + m_pair(impl::make_input_iterable(std::move(values)), nullptr) + {} template - iterable(std::map const& values) : m_pair(impl::make_scoped_input_iterable(values.begin(), values.end())) - { - } + iterable(std::map const& values) : + m_pair(impl::make_scoped_input_iterable(values.begin(), values.end())) + {} template - iterable(std::unordered_map&& values) : m_pair(impl::make_input_iterable(std::move(values)), nullptr) - { - } + iterable(std::unordered_map&& values) : + m_pair(impl::make_input_iterable(std::move(values)), nullptr) + {} template - iterable(std::unordered_map const& values) : m_pair(impl::make_scoped_input_iterable(values.begin(), values.end())) - { - } + iterable(std::unordered_map const& values) : + m_pair(impl::make_scoped_input_iterable(values.begin(), values.end())) + {} - iterable(std::initializer_list> values) : m_pair(impl::make_scoped_input_iterable(values.begin(), values.end())) - { - } + iterable(std::initializer_list> values) : + m_pair(impl::make_scoped_input_iterable(values.begin(), values.end())) + {} - template - iterable(InputIt first, InputIt last) : m_pair(impl::make_scoped_input_iterable(first, last)) - { - } + template + iterable(InputIt first, InputIt last) : + m_pair(impl::make_scoped_input_iterable(first, last)) + {} ~iterable() noexcept { @@ -212,37 +202,34 @@ WINRT_EXPORT namespace winrt::param } } - operator interface_type const& () const noexcept + operator interface_type const&() const noexcept { return m_pair.first; } private: - std::pair m_pair; bool m_owned{ true }; }; - template - auto get_abi(iterable const& object) noexcept + template auto get_abi(iterable const& object) noexcept { return *(void**)(&object); } - template - struct async_iterable + template struct async_iterable { using value_type = T; using interface_type = Windows::Foundation::Collections::IIterable; async_iterable(std::nullptr_t) noexcept - { - } + {} async_iterable(async_iterable const& values) = delete; async_iterable& operator=(async_iterable const& values) = delete; - async_iterable(interface_type const& values) noexcept : m_owned(false) + async_iterable(interface_type const& values) noexcept : + m_owned(false) { attach_abi(m_interface, winrt::get_abi(values)); } @@ -256,13 +243,11 @@ WINRT_EXPORT namespace winrt::param template async_iterable(std::vector&& values) : m_interface(impl::make_input_iterable(std::move(values))) - { - } + {} async_iterable(std::initializer_list values) : m_interface(impl::make_input_iterable(std::vector(values))) - { - } + {} ~async_iterable() noexcept { @@ -272,31 +257,29 @@ WINRT_EXPORT namespace winrt::param } } - operator interface_type const& () const noexcept + operator interface_type const&() const noexcept { return m_interface; } private: - interface_type m_interface; bool m_owned{ true }; }; - template - struct async_iterable> + template struct async_iterable> { using value_type = Windows::Foundation::Collections::IKeyValuePair; using interface_type = Windows::Foundation::Collections::IIterable; async_iterable(std::nullptr_t) noexcept - { - } + {} async_iterable(async_iterable const& values) = delete; async_iterable& operator=(async_iterable const& values) = delete; - async_iterable(interface_type const& values) noexcept : m_owned(false) + async_iterable(interface_type const& values) noexcept : + m_owned(false) { attach_abi(m_interface, winrt::get_abi(values)); } @@ -310,19 +293,16 @@ WINRT_EXPORT namespace winrt::param template async_iterable(std::map&& values) : m_interface(impl::make_input_iterable(std::move(values))) - { - } + {} template async_iterable(std::unordered_map&& values) : m_interface(impl::make_input_iterable(std::move(values))) - { - } + {} async_iterable(std::initializer_list> values) : m_interface(impl::make_input_iterable(std::map(values))) - { - } + {} ~async_iterable() noexcept { @@ -332,19 +312,17 @@ WINRT_EXPORT namespace winrt::param } } - operator interface_type const& () const noexcept + operator interface_type const&() const noexcept { return m_interface; } private: - interface_type m_interface; bool m_owned{ true }; }; - template - auto get_abi(async_iterable const& object) noexcept + template auto get_abi(async_iterable const& object) noexcept { return *(void**)(&object); } diff --git a/strings/base_collections_input_map.h b/strings/base_collections_input_map.h index b33975fe6..83a527949 100644 --- a/strings/base_collections_input_map.h +++ b/strings/base_collections_input_map.h @@ -2,16 +2,16 @@ namespace winrt::impl { template - struct map_impl : - implements, wfc::IMap, wfc::IMapView, wfc::IIterable>>, - map_base, K, V>, - ThreadingBase + struct map_impl + : implements, wfc::IMap, wfc::IMapView, wfc::IIterable>>, + map_base, K, V>, + ThreadingBase { static_assert(std::is_same_v>, "Must be constructed with rvalue."); - explicit map_impl(Container&& values) : m_values(std::forward(values)) - { - } + explicit map_impl(Container&& values) : + m_values(std::forward(values)) + {} auto& get_container() noexcept { @@ -23,40 +23,37 @@ namespace winrt::impl return m_values; } - using ThreadingBase::acquire_shared; using ThreadingBase::acquire_exclusive; + using ThreadingBase::acquire_shared; private: - Container m_values; }; template using input_map = map_impl; - template - auto make_input_map(Container&& values) + template auto make_input_map(Container&& values) { return make>(std::forward(values)); } -} +} // namespace winrt::impl WINRT_EXPORT namespace winrt::param { - template - struct map + template struct map { using value_type = Windows::Foundation::Collections::IKeyValuePair; using interface_type = Windows::Foundation::Collections::IMap; map(std::nullptr_t) noexcept - { - } + {} map(map const& values) = delete; map& operator=(map const& values) = delete; - map(interface_type const& values) noexcept : m_owned(false) + map(interface_type const& values) noexcept : + m_owned(false) { attach_abi(m_interface, winrt::get_abi(values)); } @@ -70,19 +67,16 @@ WINRT_EXPORT namespace winrt::param template map(std::map&& values) : m_interface(impl::make_input_map(std::move(values))) - { - } + {} template map(std::unordered_map&& values) : m_interface(impl::make_input_map(std::move(values))) - { - } + {} map(std::initializer_list> values) : m_interface(impl::make_input_map(std::map(values))) - { - } + {} ~map() noexcept { @@ -92,19 +86,17 @@ WINRT_EXPORT namespace winrt::param } } - operator interface_type const& () const noexcept + operator interface_type const&() const noexcept { return m_interface; } private: - interface_type m_interface; bool m_owned{ true }; }; - template - auto get_abi(map const& object) noexcept + template auto get_abi(map const& object) noexcept { return *(void**)(&object); } diff --git a/strings/base_collections_input_map_view.h b/strings/base_collections_input_map_view.h index bfd8d82a9..be84e57d1 100644 --- a/strings/base_collections_input_map_view.h +++ b/strings/base_collections_input_map_view.h @@ -2,15 +2,15 @@ namespace winrt::impl { template - struct input_map_view : - implements, non_agile, no_weak_ref, wfc::IMapView, wfc::IIterable>>, - map_view_base, K, V> + struct input_map_view + : implements, non_agile, no_weak_ref, wfc::IMapView, wfc::IIterable>>, + map_view_base, K, V> { static_assert(std::is_same_v>, "Must be constructed with rvalue."); - explicit input_map_view(Container&& values) : m_values(std::forward(values)) - { - } + explicit input_map_view(Container&& values) : + m_values(std::forward(values)) + {} auto& get_container() const noexcept { @@ -18,24 +18,23 @@ namespace winrt::impl } private: - Container const m_values; }; template - struct scoped_input_map_view : - input_scope, - implements, non_agile, no_weak_ref, wfc::IMapView, wfc::IIterable>>, - map_view_base, K, V> + struct scoped_input_map_view + : input_scope, + implements, non_agile, no_weak_ref, wfc::IMapView, wfc::IIterable>>, + map_view_base, K, V> { void abi_enter() const { check_scope(); } - explicit scoped_input_map_view(Container const& values) : m_values(values) - { - } + explicit scoped_input_map_view(Container const& values) : + m_values(values) + {} auto& get_container() const noexcept { @@ -44,23 +43,19 @@ namespace winrt::impl #if defined(_DEBUG) && !defined(WINRT_NO_MAKE_DETECTION) void use_make_function_to_create_this_object() final - { - } + {} #endif private: - Container const& m_values; }; - template - auto make_input_map_view(Container&& values) + template auto make_input_map_view(Container&& values) { return make>(std::forward(values)); } - template - auto make_scoped_input_map_view(Container const& values) + template auto make_scoped_input_map_view(Container const& values) { using interface_type = wfc::IMapView; std::pair result; @@ -69,24 +64,23 @@ namespace winrt::impl result.second = ptr; return result; } -} +} // namespace winrt::impl WINRT_EXPORT namespace winrt::param { - template - struct map_view + template struct map_view { using value_type = Windows::Foundation::Collections::IKeyValuePair; using interface_type = Windows::Foundation::Collections::IMapView; map_view(std::nullptr_t) noexcept - { - } + {} map_view(map_view const& values) = delete; map_view& operator=(map_view const& values) = delete; - map_view(interface_type const& values) noexcept : m_owned(false) + map_view(interface_type const& values) noexcept : + m_owned(false) { attach_abi(m_pair.first, winrt::get_abi(values)); } @@ -98,28 +92,28 @@ WINRT_EXPORT namespace winrt::param } template - map_view(std::map&& values) : m_pair(impl::make_input_map_view(std::move(values)), nullptr) - { - } + map_view(std::map&& values) : + m_pair(impl::make_input_map_view(std::move(values)), nullptr) + {} template - map_view(std::map const& values) : m_pair(impl::make_scoped_input_map_view(values)) - { - } + map_view(std::map const& values) : + m_pair(impl::make_scoped_input_map_view(values)) + {} template - map_view(std::unordered_map&& values) : m_pair(impl::make_input_map_view(std::move(values)), nullptr) - { - } + map_view(std::unordered_map&& values) : + m_pair(impl::make_input_map_view(std::move(values)), nullptr) + {} template - map_view(std::unordered_map const& values) : m_pair(impl::make_scoped_input_map_view(values)) - { - } + map_view(std::unordered_map const& values) : + m_pair(impl::make_scoped_input_map_view(values)) + {} - map_view(std::initializer_list> values) : m_pair(impl::make_input_map_view(std::map(values)), nullptr) - { - } + map_view(std::initializer_list> values) : + m_pair(impl::make_input_map_view(std::map(values)), nullptr) + {} ~map_view() noexcept { @@ -134,37 +128,34 @@ WINRT_EXPORT namespace winrt::param } } - operator interface_type const& () const noexcept + operator interface_type const&() const noexcept { return m_pair.first; } private: - std::pair m_pair; bool m_owned{ true }; }; - template - auto get_abi(map_view const& object) noexcept + template auto get_abi(map_view const& object) noexcept { return *(void**)(&object); } - template - struct async_map_view + template struct async_map_view { using value_type = Windows::Foundation::Collections::IKeyValuePair; using interface_type = Windows::Foundation::Collections::IMapView; async_map_view(std::nullptr_t) noexcept - { - } + {} async_map_view(async_map_view const& values) = delete; async_map_view& operator=(async_map_view const& values) = delete; - async_map_view(interface_type const& values) noexcept : m_owned(false) + async_map_view(interface_type const& values) noexcept : + m_owned(false) { attach_abi(m_interface, winrt::get_abi(values)); } @@ -178,19 +169,16 @@ WINRT_EXPORT namespace winrt::param template async_map_view(std::map&& values) : m_interface(impl::make_input_map_view(std::move(values))) - { - } + {} template async_map_view(std::unordered_map&& values) : m_interface(impl::make_input_map_view(std::move(values))) - { - } + {} async_map_view(std::initializer_list> values) : m_interface(impl::make_input_map_view(std::map(values))) - { - } + {} ~async_map_view() noexcept { @@ -200,19 +188,17 @@ WINRT_EXPORT namespace winrt::param } } - operator interface_type const& () const noexcept + operator interface_type const&() const noexcept { return m_interface; } private: - interface_type m_interface; bool m_owned{ true }; }; - template - auto get_abi(async_map_view const& object) noexcept + template auto get_abi(async_map_view const& object) noexcept { return *(void**)(&object); } diff --git a/strings/base_collections_input_vector.h b/strings/base_collections_input_vector.h index b5b76de38..512bfda33 100644 --- a/strings/base_collections_input_vector.h +++ b/strings/base_collections_input_vector.h @@ -2,16 +2,16 @@ namespace winrt::impl { template - struct vector_impl : - implements, wfc::IVector, wfc::IVectorView, wfc::IIterable>, - vector_base, T>, - ThreadingBase + struct vector_impl + : implements, wfc::IVector, wfc::IVectorView, wfc::IIterable>, + vector_base, T>, + ThreadingBase { static_assert(std::is_same_v>, "Must be constructed with rvalue."); - explicit vector_impl(Container&& values) : m_values(std::forward(values)) - { - } + explicit vector_impl(Container&& values) : + m_values(std::forward(values)) + {} auto& get_container() noexcept { @@ -23,34 +23,32 @@ namespace winrt::impl return m_values; } - using ThreadingBase::acquire_shared; using ThreadingBase::acquire_exclusive; + using ThreadingBase::acquire_shared; private: - Container m_values; }; template using input_vector = vector_impl; -} +} // namespace winrt::impl WINRT_EXPORT namespace winrt::param { - template - struct vector + template struct vector { using value_type = T; using interface_type = Windows::Foundation::Collections::IVector; vector(std::nullptr_t) noexcept - { - } + {} vector(vector const& values) = delete; vector& operator=(vector const& values) = delete; - vector(interface_type const& values) noexcept : m_owned(false) + vector(interface_type const& values) noexcept : + m_owned(false) { attach_abi(m_interface, winrt::get_abi(values)); } @@ -64,13 +62,11 @@ WINRT_EXPORT namespace winrt::param template vector(std::vector&& values) : m_interface(make>>(std::move(values))) - { - } + {} vector(std::initializer_list values) : m_interface(make>>(values)) - { - } + {} ~vector() noexcept { @@ -80,19 +76,17 @@ WINRT_EXPORT namespace winrt::param } } - operator interface_type const& () const noexcept + operator interface_type const&() const noexcept { return m_interface; } private: - interface_type m_interface; bool m_owned = true; }; - template - auto get_abi(vector const& object) noexcept + template auto get_abi(vector const& object) noexcept { return *(void**)(&object); } diff --git a/strings/base_collections_input_vector_view.h b/strings/base_collections_input_vector_view.h index 3793e239a..26002953f 100644 --- a/strings/base_collections_input_vector_view.h +++ b/strings/base_collections_input_vector_view.h @@ -2,15 +2,15 @@ namespace winrt::impl { template - struct input_vector_view : - implements, non_agile, no_weak_ref, wfc::IVectorView, wfc::IIterable>, - vector_view_base, T> + struct input_vector_view + : implements, non_agile, no_weak_ref, wfc::IVectorView, wfc::IIterable>, + vector_view_base, T> { static_assert(std::is_same_v>, "Must be constructed with rvalue."); - explicit input_vector_view(Container&& values) : m_values(std::forward(values)) - { - } + explicit input_vector_view(Container&& values) : + m_values(std::forward(values)) + {} auto& get_container() const noexcept { @@ -18,24 +18,23 @@ namespace winrt::impl } private: - Container const m_values; }; template - struct scoped_input_vector_view : - input_scope, - implements, non_agile, no_weak_ref, wfc::IVectorView, wfc::IIterable>, - vector_view_base, T> + struct scoped_input_vector_view + : input_scope, + implements, non_agile, no_weak_ref, wfc::IVectorView, wfc::IIterable>, + vector_view_base, T> { void abi_enter() const { check_scope(); } - scoped_input_vector_view(InputIt first, InputIt last) : m_begin(first), m_end(last) - { - } + scoped_input_vector_view(InputIt first, InputIt last) : + m_begin(first), m_end(last) + {} auto get_container() const noexcept { @@ -44,18 +43,15 @@ namespace winrt::impl #if defined(_DEBUG) && !defined(WINRT_NO_MAKE_DETECTION) void use_make_function_to_create_this_object() final - { - } + {} #endif private: - InputIt const m_begin; InputIt const m_end; }; - template - auto make_scoped_input_vector_view(InputIt first, InputIt last) + template auto make_scoped_input_vector_view(InputIt first, InputIt last) { using interface_type = wfc::IVectorView; std::pair result; @@ -64,24 +60,23 @@ namespace winrt::impl result.second = ptr; return result; } -} +} // namespace winrt::impl WINRT_EXPORT namespace winrt::param { - template - struct vector_view + template struct vector_view { using value_type = T; using interface_type = Windows::Foundation::Collections::IVectorView; vector_view(std::nullptr_t) noexcept - { - } + {} vector_view(vector_view const& values) = delete; vector_view& operator=(vector_view const& values) = delete; - vector_view(interface_type const& values) noexcept : m_owned(false) + vector_view(interface_type const& values) noexcept : + m_owned(false) { attach_abi(m_pair.first, winrt::get_abi(values)); } @@ -93,28 +88,28 @@ WINRT_EXPORT namespace winrt::param } template - vector_view(std::vector&& values) : m_pair(make>>(std::move(values)), nullptr) - { - } + vector_view(std::vector&& values) : + m_pair(make>>(std::move(values)), nullptr) + {} template - vector_view(std::vector const& values) : m_pair(impl::make_scoped_input_vector_view(values.begin(), values.end())) - { - } + vector_view(std::vector const& values) : + m_pair(impl::make_scoped_input_vector_view(values.begin(), values.end())) + {} - vector_view(std::initializer_list values) : m_pair(impl::make_scoped_input_vector_view(values.begin(), values.end())) - { - } + vector_view(std::initializer_list values) : + m_pair(impl::make_scoped_input_vector_view(values.begin(), values.end())) + {} template , int> = 0> - vector_view(std::initializer_list values) : m_pair(impl::make_scoped_input_vector_view(values.begin(), values.end())) - { - } + vector_view(std::initializer_list values) : + m_pair(impl::make_scoped_input_vector_view(values.begin(), values.end())) + {} - template - vector_view(InputIt first, InputIt last) : m_pair(impl::make_scoped_input_vector_view(first, last)) - { - } + template + vector_view(InputIt first, InputIt last) : + m_pair(impl::make_scoped_input_vector_view(first, last)) + {} ~vector_view() noexcept { @@ -129,37 +124,34 @@ WINRT_EXPORT namespace winrt::param } } - operator interface_type const& () const noexcept + operator interface_type const&() const noexcept { return m_pair.first; } private: - std::pair m_pair; bool m_owned{ true }; }; - template - auto get_abi(vector_view const& object) noexcept + template auto get_abi(vector_view const& object) noexcept { return *(void**)(&object); } - template - struct async_vector_view + template struct async_vector_view { using value_type = T; using interface_type = Windows::Foundation::Collections::IVectorView; async_vector_view(std::nullptr_t) noexcept - { - } + {} async_vector_view(async_vector_view const& values) = delete; async_vector_view& operator=(async_vector_view const& values) = delete; - async_vector_view(interface_type const& values) noexcept : m_owned(false) + async_vector_view(interface_type const& values) noexcept : + m_owned(false) { attach_abi(m_interface, winrt::get_abi(values)); } @@ -173,13 +165,11 @@ WINRT_EXPORT namespace winrt::param template async_vector_view(std::vector&& values) : m_interface(make>>(std::move(values))) - { - } + {} async_vector_view(std::initializer_list values) : m_interface(make>>(values)) - { - } + {} ~async_vector_view() noexcept { @@ -189,19 +179,17 @@ WINRT_EXPORT namespace winrt::param } } - operator interface_type const& () const noexcept + operator interface_type const&() const noexcept { return m_interface; } private: - interface_type m_interface; bool m_owned{ true }; }; - template - auto get_abi(async_vector_view const& object) noexcept + template auto get_abi(async_vector_view const& object) noexcept { return *(void**)(&object); } diff --git a/strings/base_collections_map.h b/strings/base_collections_map.h index f4bd74baf..9d9da01fd 100644 --- a/strings/base_collections_map.h +++ b/strings/base_collections_map.h @@ -5,16 +5,20 @@ namespace winrt::impl using multi_threaded_map = map_impl; template - struct observable_map_impl : - implements, wfc::IObservableMap, wfc::IMap, wfc::IMapView, wfc::IIterable>>, - observable_map_base, K, V>, - ThreadingBase + struct observable_map_impl : implements< + observable_map_impl, + wfc::IObservableMap, + wfc::IMap, + wfc::IMapView, + wfc::IIterable>>, + observable_map_base, K, V>, + ThreadingBase { static_assert(std::is_same_v>, "Must be constructed with rvalue."); - explicit observable_map_impl(Container&& values) : m_values(std::forward(values)) - { - } + explicit observable_map_impl(Container&& values) : + m_values(std::forward(values)) + {} auto& get_container() noexcept { @@ -26,11 +30,10 @@ namespace winrt::impl return m_values; } - using ThreadingBase::acquire_shared; using ThreadingBase::acquire_exclusive; + using ThreadingBase::acquire_shared; private: - Container m_values; }; @@ -39,7 +42,7 @@ namespace winrt::impl template using multi_threaded_observable_map = observable_map_impl; -} +} // namespace winrt::impl WINRT_EXPORT namespace winrt { @@ -50,13 +53,13 @@ WINRT_EXPORT namespace winrt } template , typename Allocator = std::allocator>> - Windows::Foundation::Collections::IMap single_threaded_map(std::map&& values) + Windows::Foundation::Collections::IMap single_threaded_map(std::map && values) { return make>>(std::move(values)); } template , typename KeyEqual = std::equal_to, typename Allocator = std::allocator>> - Windows::Foundation::Collections::IMap single_threaded_map(std::unordered_map&& values) + Windows::Foundation::Collections::IMap single_threaded_map(std::unordered_map && values) { return make>>(std::move(values)); } @@ -68,13 +71,13 @@ WINRT_EXPORT namespace winrt } template , typename Allocator = std::allocator>> - Windows::Foundation::Collections::IMap multi_threaded_map(std::map&& values) + Windows::Foundation::Collections::IMap multi_threaded_map(std::map && values) { return make>>(std::move(values)); } template , typename KeyEqual = std::equal_to, typename Allocator = std::allocator>> - Windows::Foundation::Collections::IMap multi_threaded_map(std::unordered_map&& values) + Windows::Foundation::Collections::IMap multi_threaded_map(std::unordered_map && values) { return make>>(std::move(values)); } @@ -86,13 +89,15 @@ WINRT_EXPORT namespace winrt } template , typename Allocator = std::allocator>> - Windows::Foundation::Collections::IObservableMap single_threaded_observable_map(std::map&& values) + Windows::Foundation::Collections::IObservableMap single_threaded_observable_map( + std::map && values) { return make>>(std::move(values)); } template , typename KeyEqual = std::equal_to, typename Allocator = std::allocator>> - Windows::Foundation::Collections::IObservableMap single_threaded_observable_map(std::unordered_map&& values) + Windows::Foundation::Collections::IObservableMap single_threaded_observable_map( + std::unordered_map && values) { return make>>(std::move(values)); } @@ -100,41 +105,43 @@ WINRT_EXPORT namespace winrt template , typename Allocator = std::allocator>> Windows::Foundation::Collections::IObservableMap multi_threaded_observable_map() { - return make>>(std::map{}); + return make>>( + std::map{}); } template , typename Allocator = std::allocator>> - Windows::Foundation::Collections::IObservableMap multi_threaded_observable_map(std::map&& values) + Windows::Foundation::Collections::IObservableMap multi_threaded_observable_map( + std::map && values) { return make>>(std::move(values)); } template , typename KeyEqual = std::equal_to, typename Allocator = std::allocator>> - Windows::Foundation::Collections::IObservableMap multi_threaded_observable_map(std::unordered_map&& values) + Windows::Foundation::Collections::IObservableMap multi_threaded_observable_map( + std::unordered_map && values) { - return make>>(std::move(values)); + return make>>( + std::move(values)); } } namespace std { - template - struct tuple_size> - : integral_constant - { - }; + template + struct tuple_size> : integral_constant + {}; - template + template struct tuple_element> { static_assert(Idx < 2, "key-value pair index out of bounds"); using type = conditional_t; }; -} +} // namespace std namespace winrt::Windows::Foundation::Collections { - template + template std::tuple_element_t> get(IKeyValuePair const& kvp) { static_assert(Idx < 2, "key-value pair index out of bounds"); @@ -147,4 +154,4 @@ namespace winrt::Windows::Foundation::Collections return kvp.Value(); } } -} +} // namespace winrt::Windows::Foundation::Collections diff --git a/strings/base_collections_vector.h b/strings/base_collections_vector.h index cef7ef2d3..2358b469c 100644 --- a/strings/base_collections_vector.h +++ b/strings/base_collections_vector.h @@ -5,17 +5,21 @@ namespace winrt::impl using multi_threaded_vector = vector_impl; template - struct inspectable_observable_vector : - observable_vector_base, Windows::Foundation::IInspectable>, - implements, - wfc::IObservableVector, wfc::IVector, wfc::IVectorView, wfc::IIterable>, - ThreadingBase + struct inspectable_observable_vector + : observable_vector_base, Windows::Foundation::IInspectable>, + implements< + inspectable_observable_vector, + wfc::IObservableVector, + wfc::IVector, + wfc::IVectorView, + wfc::IIterable>, + ThreadingBase { static_assert(std::is_same_v>, "Must be constructed with rvalue."); - explicit inspectable_observable_vector(Container&& values) : m_values(std::forward(values)) - { - } + explicit inspectable_observable_vector(Container&& values) : + m_values(std::forward(values)) + {} auto& get_container() noexcept { @@ -27,24 +31,31 @@ namespace winrt::impl return m_values; } - using ThreadingBase::acquire_shared; using ThreadingBase::acquire_exclusive; + using ThreadingBase::acquire_shared; private: - Container m_values; }; template - using multi_threaded_inspectable_observable_vector = inspectable_observable_vector; + using multi_threaded_inspectable_observable_vector = + inspectable_observable_vector; template - struct convertible_observable_vector : - observable_vector_base, T>, - implements, - wfc::IObservableVector, wfc::IVector, wfc::IVectorView, wfc::IIterable, - wfc::IObservableVector, wfc::IVector, wfc::IVectorView, wfc::IIterable>, - ThreadingBase + struct convertible_observable_vector + : observable_vector_base, T>, + implements< + convertible_observable_vector, + wfc::IObservableVector, + wfc::IVector, + wfc::IVectorView, + wfc::IIterable, + wfc::IObservableVector, + wfc::IVector, + wfc::IVectorView, + wfc::IIterable>, + ThreadingBase { static_assert(!std::is_same_v); static_assert(std::is_same_v>, "Must be constructed with rvalue."); @@ -52,9 +63,9 @@ namespace winrt::impl using container_type = convertible_observable_vector; using base_type = observable_vector_base, T>; - explicit convertible_observable_vector(Container&& values) : m_values(std::forward(values)) - { - } + explicit convertible_observable_vector(Container&& values) : + m_values(std::forward(values)) + {} auto& get_container() noexcept { @@ -66,8 +77,8 @@ namespace winrt::impl return m_values; } - using ThreadingBase::acquire_shared; using ThreadingBase::acquire_exclusive; + using ThreadingBase::acquire_shared; auto First() { @@ -149,10 +160,11 @@ namespace winrt::impl uint32_t const actual = (std::min)(static_cast(m_values.size() - startIndex), values.size()); - std::transform(m_values.begin() + startIndex, m_values.begin() + startIndex + actual, values.begin(), [&](auto && value) - { - return box_value(value); - }); + std::transform( + m_values.begin() + startIndex, + m_values.begin() + startIndex + actual, + values.begin(), + [&](auto&& value) { return box_value(value); }); return actual; } @@ -205,10 +217,11 @@ namespace winrt::impl Container new_values; new_values.reserve(values.size()); - std::transform(values.begin(), values.end(), std::back_inserter(new_values), [&](auto && value) - { - return unbox_value(value); - }); + std::transform( + values.begin(), + values.end(), + std::back_inserter(new_values), + [&](auto&& value) { return unbox_value(value); }); base_type::ReplaceAll(std::move(new_values)); } @@ -217,17 +230,15 @@ namespace winrt::impl event_token VectorChanged(wfc::VectorChangedEventHandler const& handler) { - return base_type::VectorChanged([handler](auto && sender, auto && args) - { - handler(sender.template try_as>(), args); - }); + return base_type::VectorChanged( + [handler](auto&& sender, auto&& args) + { handler(sender.template try_as>(), args); }); } private: - - struct iterator : - impl::collection_version::iterator_type, - implements> + struct iterator + : impl::collection_version::iterator_type, + implements> { explicit iterator(container_type* const container) noexcept : impl::collection_version::iterator_type(*container), @@ -274,17 +285,14 @@ namespace winrt::impl check_version(*m_owner); uint32_t const actual = (std::min)(static_cast(std::distance(m_current, m_end)), values.size()); - std::transform(m_current, m_current + actual, values.begin(), [&](auto && value) - { - return box_value(value); - }); + std::transform( + m_current, m_current + actual, values.begin(), [&](auto&& value) { return box_value(value); }); std::advance(m_current, actual); return actual; } private: - com_ptr m_owner; decltype(m_owner->get_container().begin()) m_current; decltype(m_owner->get_container().end()) const m_end; @@ -294,8 +302,9 @@ namespace winrt::impl }; template - using multi_threaded_convertible_observable_vector = convertible_observable_vector; -} + using multi_threaded_convertible_observable_vector = + convertible_observable_vector; +} // namespace winrt::impl WINRT_EXPORT namespace winrt { @@ -312,7 +321,8 @@ WINRT_EXPORT namespace winrt } template > - Windows::Foundation::Collections::IObservableVector single_threaded_observable_vector(std::vector&& values = {}) + Windows::Foundation::Collections::IObservableVector single_threaded_observable_vector( + std::vector&& values = {}) { if constexpr (std::is_same_v) { @@ -325,7 +335,8 @@ WINRT_EXPORT namespace winrt } template > - Windows::Foundation::Collections::IObservableVector multi_threaded_observable_vector(std::vector&& values = {}) + Windows::Foundation::Collections::IObservableVector multi_threaded_observable_vector( + std::vector&& values = {}) { if constexpr (std::is_same_v) { diff --git a/strings/base_com_ptr.h b/strings/base_com_ptr.h index 14a9a0851..6d7c40669 100644 --- a/strings/base_com_ptr.h +++ b/strings/base_com_ptr.h @@ -1,8 +1,7 @@ WINRT_EXPORT namespace winrt { - template - struct com_ptr; + template struct com_ptr; } namespace winrt::impl @@ -11,57 +10,57 @@ namespace winrt::impl { void** result; - template - operator T** () + template operator T**() { return reinterpret_cast(result); } }; - template - int32_t capture_to(void**result, F function, Args&& ...args) + template int32_t capture_to(void** result, F function, Args&&... args) { return function(args..., guid_of(), capture_decay{ result }); } - template || std::is_union_v, int> = 0> - int32_t capture_to(void** result, O* object, M method, Args&& ...args) + template || std::is_union_v, int> = 0> + int32_t capture_to(void** result, O* object, M method, Args&&... args) { return (object->*method)(args..., guid_of(), capture_decay{ result }); } - template - int32_t capture_to(void** result, com_ptr const& object, M method, Args&& ...args); -} + template + int32_t capture_to(void** result, com_ptr const& object, M method, Args&&... args); +} // namespace winrt::impl WINRT_EXPORT namespace winrt { - template - struct com_ptr + template struct com_ptr { using type = impl::abi_t; - com_ptr(std::nullptr_t = nullptr) noexcept {} + com_ptr(std::nullptr_t = nullptr) noexcept + {} - com_ptr(void* ptr, take_ownership_from_abi_t) noexcept : m_ptr(static_cast(ptr)) - { - } + com_ptr(void* ptr, take_ownership_from_abi_t) noexcept : + m_ptr(static_cast(ptr)) + {} - com_ptr(com_ptr const& other) noexcept : m_ptr(other.m_ptr) + com_ptr(com_ptr const& other) noexcept : + m_ptr(other.m_ptr) { add_ref(); } template - com_ptr(com_ptr const& other) noexcept : m_ptr(other.m_ptr) + com_ptr(com_ptr const& other) noexcept : + m_ptr(other.m_ptr) { add_ref(); } template - com_ptr(com_ptr&& other) noexcept : m_ptr(std::exchange(other.m_ptr, {})) - { - } + com_ptr(com_ptr&& other) noexcept : + m_ptr(std::exchange(other.m_ptr, {})) + {} ~com_ptr() noexcept { @@ -71,7 +70,7 @@ WINRT_EXPORT namespace winrt com_ptr& operator=(com_ptr const& other) noexcept { copy_ref(other.m_ptr); - return*this; + return *this; } com_ptr& operator=(com_ptr&& other) noexcept @@ -82,22 +81,20 @@ WINRT_EXPORT namespace winrt m_ptr = std::exchange(other.m_ptr, {}); } - return*this; + return *this; } - template - com_ptr& operator=(com_ptr const& other) noexcept + template com_ptr& operator=(com_ptr const& other) noexcept { copy_ref(other.m_ptr); - return*this; + return *this; } - template - com_ptr& operator=(com_ptr&& other) noexcept + template com_ptr& operator=(com_ptr&& other) noexcept { release_ref(); m_ptr = std::exchange(other.m_ptr, {}); - return*this; + return *this; } explicit operator bool() const noexcept @@ -147,26 +144,22 @@ WINRT_EXPORT namespace winrt std::swap(left.m_ptr, right.m_ptr); } - template - auto as() const + template auto as() const { return impl::as(m_ptr); } - template - auto try_as() const noexcept + template auto try_as() const noexcept { return impl::try_as(m_ptr); } - template - void as(To& to) const + template void as(To& to) const { to = as>(); } - template - bool try_as(To& to) const noexcept + template bool try_as(To& to) const noexcept { if constexpr (impl::is_com_interface_v || !std::is_same_v>) { @@ -197,20 +190,17 @@ WINRT_EXPORT namespace winrt *other = m_ptr; } - template - bool try_capture(Args&&...args) + template bool try_capture(Args&&... args) { return impl::capture_to(put_void(), std::forward(args)...) >= 0; } - template - void capture(Args&&...args) + template void capture(Args&&... args) { check_hresult(impl::capture_to(put_void(), std::forward(args)...)); } private: - void copy_ref(type* other) noexcept { if (m_ptr != other) @@ -242,108 +232,91 @@ WINRT_EXPORT namespace winrt std::exchange(m_ptr, {})->Release(); } - template - friend struct com_ptr; + template friend struct com_ptr; type* m_ptr{}; }; - template - impl::com_ref try_capture(Args&& ...args) + template impl::com_ref try_capture(Args && ... args) { void* result{}; impl::capture_to(&result, std::forward(args)...); return { result, take_ownership_from_abi }; } - template - impl::com_ref capture(Args&& ...args) + template impl::com_ref capture(Args && ... args) { void* result{}; check_hresult(impl::capture_to(&result, std::forward(args)...)); return { result, take_ownership_from_abi }; } - template - auto get_abi(com_ptr const& object) noexcept + template auto get_abi(com_ptr const& object) noexcept { return object.get(); } - template - auto put_abi(com_ptr& object) noexcept + template auto put_abi(com_ptr & object) noexcept { return object.put_void(); } - template - void attach_abi(com_ptr& object, impl::abi_t* value) noexcept + template void attach_abi(com_ptr & object, impl::abi_t * value) noexcept { object.attach(value); } - template - auto detach_abi(com_ptr& object) noexcept + template auto detach_abi(com_ptr & object) noexcept { return object.detach(); } - template - bool operator==(com_ptr const& left, com_ptr const& right) noexcept + template bool operator==(com_ptr const& left, com_ptr const& right) noexcept { return get_abi(left) == get_abi(right); } - template - bool operator==(com_ptr const& left, std::nullptr_t) noexcept + template bool operator==(com_ptr const& left, std::nullptr_t) noexcept { return get_abi(left) == nullptr; } - template - bool operator==(std::nullptr_t, com_ptr const& right) noexcept + template bool operator==(std::nullptr_t, com_ptr const& right) noexcept { return nullptr == get_abi(right); } - template - bool operator!=(com_ptr const& left, com_ptr const& right) noexcept + template bool operator!=(com_ptr const& left, com_ptr const& right) noexcept { return !(left == right); } - template - bool operator!=(com_ptr const& left, std::nullptr_t) noexcept + template bool operator!=(com_ptr const& left, std::nullptr_t) noexcept { return !(left == nullptr); } - template - bool operator!=(std::nullptr_t, com_ptr const& right) noexcept + template bool operator!=(std::nullptr_t, com_ptr const& right) noexcept { return !(nullptr == right); } - template - bool operator<(com_ptr const& left, com_ptr const& right) noexcept + template bool operator<(com_ptr const& left, com_ptr const& right) noexcept { return get_abi(left) < get_abi(right); } - template - bool operator>(com_ptr const& left, com_ptr const& right) noexcept + template bool operator>(com_ptr const& left, com_ptr const& right) noexcept { return right < left; } - template - bool operator<=(com_ptr const& left, com_ptr const& right) noexcept + template bool operator<=(com_ptr const& left, com_ptr const& right) noexcept { return !(right < left); } - template - bool operator>=(com_ptr const& left, com_ptr const& right) noexcept + template bool operator>=(com_ptr const& left, com_ptr const& right) noexcept { return !(left < right); } @@ -351,15 +324,14 @@ WINRT_EXPORT namespace winrt namespace winrt::impl { - template - int32_t capture_to(void** result, com_ptr const& object, M method, Args&& ...args) + template + int32_t capture_to(void** result, com_ptr const& object, M method, Args&&... args) { return (object.get()->*(method))(args..., guid_of(), capture_decay{ result }); } -} +} // namespace winrt::impl -template -void** IID_PPV_ARGS_Helper(winrt::com_ptr* ptr) noexcept +template void** IID_PPV_ARGS_Helper(winrt::com_ptr* ptr) noexcept { return winrt::put_abi(*ptr); } diff --git a/strings/base_composable.h b/strings/base_composable.h index 7f675c970..63e7ea033 100644 --- a/strings/base_composable.h +++ b/strings/base_composable.h @@ -1,13 +1,14 @@ namespace winrt::impl { - template - struct composable_factory + template struct composable_factory { template static I CreateInstance(const Windows::Foundation::IInspectable& outer, Windows::Foundation::IInspectable& inner, Args&&... args) { - static_assert(std::is_base_of_v, "Requested interface must derive from winrt::Windows::Foundation::IInspectable"); + static_assert( + std::is_base_of_v, + "Requested interface must derive from winrt::Windows::Foundation::IInspectable"); inner = CreateInstanceImpl(outer, std::forward(args)...); return inner.as(); } @@ -26,8 +27,7 @@ namespace winrt::impl } }; - template - class WINRT_IMPL_EMPTY_BASES produce_dispatch_to_overridable_base + template class WINRT_IMPL_EMPTY_BASES produce_dispatch_to_overridable_base { protected: D& shim() noexcept @@ -48,23 +48,21 @@ namespace winrt::impl } }; - template - struct produce_dispatch_to_overridable; + template struct produce_dispatch_to_overridable; - template - class dispatch_to_overridable + template class dispatch_to_overridable { class wrapper : public produce_dispatch_to_overridable... { D& instance; - template - friend class produce_dispatch_to_overridable_base; + template friend class produce_dispatch_to_overridable_base; - template - friend class dispatch_to_overridable; + template friend class dispatch_to_overridable; - explicit wrapper(D& d) : instance(d) {} + explicit wrapper(D& d) : + instance(d) + {} public: wrapper(const wrapper&) = delete; @@ -77,4 +75,4 @@ namespace winrt::impl return wrapper{ instance }; } }; -} +} // namespace winrt::impl diff --git a/strings/base_coroutine_foundation.h b/strings/base_coroutine_foundation.h index 670a65403..c9ddb4eaa 100644 --- a/strings/base_coroutine_foundation.h +++ b/strings/base_coroutine_foundation.h @@ -1,14 +1,11 @@ namespace winrt::impl { - template - struct async_completed_handler; + template struct async_completed_handler; - template - using async_completed_handler_t = typename async_completed_handler::type; + template using async_completed_handler_t = typename async_completed_handler::type; - template <> - struct async_completed_handler + template <> struct async_completed_handler { using type = Windows::Foundation::AsyncActionCompletedHandler; }; @@ -19,8 +16,7 @@ namespace winrt::impl using type = Windows::Foundation::AsyncActionWithProgressCompletedHandler; }; - template - struct async_completed_handler> + template struct async_completed_handler> { using type = Windows::Foundation::AsyncOperationCompletedHandler; }; @@ -38,16 +34,14 @@ namespace winrt::impl WINRT_ASSERT(!is_sta_thread()); } - template - std::pair make_delegate_with_shared_state(H&& handler) + template std::pair make_delegate_with_shared_state(H&& handler) { auto d = make_delegate(std::forward(handler)); auto abi = reinterpret_cast*>(get_abi(d)); return { std::move(d), abi }; } - template - auto wait_for_completed(Async const& async, uint32_t const timeout) + template auto wait_for_completed(Async const& async, uint32_t const timeout) { struct shared_type { @@ -67,8 +61,7 @@ namespace winrt::impl return shared->status; } - template - auto wait_for(Async const& async, Windows::Foundation::TimeSpan const& timeout) + template auto wait_for(Async const& async, Windows::Foundation::TimeSpan const& timeout) { check_sta_blocking_wait(); auto const milliseconds = std::chrono::duration_cast(timeout).count(); @@ -84,8 +77,7 @@ namespace winrt::impl } } - template - auto wait_get(Async const& async) + template auto wait_get(Async const& async) { check_sta_blocking_wait(); @@ -99,23 +91,26 @@ namespace winrt::impl return async.GetResults(); } - struct ignore_apartment_context {}; + struct ignore_apartment_context + {}; - template - struct disconnect_aware_handler : private std::conditional_t + template + struct disconnect_aware_handler + : private std::conditional_t { - disconnect_aware_handler(Awaiter* awaiter, coroutine_handle<> handle) noexcept - : m_awaiter(awaiter), m_handle(handle) { } + disconnect_aware_handler(Awaiter* awaiter, coroutine_handle<> handle) noexcept : + m_awaiter(awaiter), m_handle(handle) + {} disconnect_aware_handler(disconnect_aware_handler&& other) = default; ~disconnect_aware_handler() { - if (m_handle.value) Complete(); + if (m_handle.value) + Complete(); } - template - void operator()(Async&&, Windows::Foundation::AsyncStatus status) + template void operator()(Async&&, Windows::Foundation::AsyncStatus status) { m_awaiter.value->status = status; Complete(); @@ -153,8 +148,10 @@ namespace winrt::impl template struct await_adapter : cancellable_awaiter> { - template - await_adapter(T&& async) : async(std::forward(async)) { } + template + await_adapter(T&& async) : + async(std::forward(async)) + {} std::conditional_t async; Windows::Foundation::AsyncStatus status = Windows::Foundation::AsyncStatus::Started; @@ -163,10 +160,8 @@ namespace winrt::impl void enable_cancellation(cancellable_promise* promise) { - promise->set_canceller([](void* parameter) - { - cancel_asynchronously(reinterpret_cast(parameter)->async); - }, this); + promise->set_canceller( + [](void* parameter) { cancel_asynchronously(reinterpret_cast(parameter)->async); }, this); } bool await_ready() const noexcept @@ -174,8 +169,7 @@ namespace winrt::impl return false; } - template - bool await_suspend(coroutine_handle handle) + template bool await_suspend(coroutine_handle handle) { this->set_cancellable_promise_from_handle(handle); return register_completed_callback(handle); @@ -208,14 +202,12 @@ namespace winrt::impl async.Cancel(); } catch (hresult_error const&) - { - } + {} } }; #endif - template - auto consume_Windows_Foundation_IAsyncAction::get() const + template auto consume_Windows_Foundation_IAsyncAction::get() const { impl::wait_get(static_cast(static_cast(*this))); } @@ -225,45 +217,52 @@ namespace winrt::impl return impl::wait_for(static_cast(static_cast(*this)), timeout); } - template - auto consume_Windows_Foundation_IAsyncOperation::get() const + template auto consume_Windows_Foundation_IAsyncOperation::get() const { return impl::wait_get(static_cast const&>(static_cast(*this))); } template auto consume_Windows_Foundation_IAsyncOperation::wait_for(Windows::Foundation::TimeSpan const& timeout) const { - return impl::wait_for(static_cast const&>(static_cast(*this)), timeout); + return impl::wait_for( + static_cast const&>(static_cast(*this)), timeout); } template auto consume_Windows_Foundation_IAsyncActionWithProgress::get() const { - impl::wait_get(static_cast const&>(static_cast(*this))); + impl::wait_get( + static_cast const&>(static_cast(*this))); } template auto consume_Windows_Foundation_IAsyncActionWithProgress::wait_for(Windows::Foundation::TimeSpan const& timeout) const { - return impl::wait_for(static_cast const&>(static_cast(*this)), timeout); + return impl::wait_for( + static_cast const&>(static_cast(*this)), timeout); } template auto consume_Windows_Foundation_IAsyncOperationWithProgress::get() const { - return impl::wait_get(static_cast const&>(static_cast(*this))); + return impl::wait_get(static_cast const&>( + static_cast(*this))); } template - auto consume_Windows_Foundation_IAsyncOperationWithProgress::wait_for(Windows::Foundation::TimeSpan const& timeout) const + auto consume_Windows_Foundation_IAsyncOperationWithProgress::wait_for( + Windows::Foundation::TimeSpan const& timeout) const { - return impl::wait_for(static_cast const&>(static_cast(*this)), timeout); + return impl::wait_for( + static_cast const&>( + static_cast(*this)), + timeout); } -} +} // namespace winrt::impl #ifdef WINRT_IMPL_COROUTINES WINRT_EXPORT namespace winrt { - template>> - inline impl::await_adapter, false> resume_agile(Async&& async) + template >> + inline impl::await_adapter, false> resume_agile(Async && async) { return { std::forward(async) }; }; @@ -273,54 +272,56 @@ WINRT_EXPORT namespace winrt::Windows::Foundation { inline impl::await_adapter operator co_await(IAsyncAction const& async) { - return{ async }; + return { async }; } template impl::await_adapter> operator co_await(IAsyncActionWithProgress const& async) { - return{ async }; + return { async }; } template impl::await_adapter> operator co_await(IAsyncOperation const& async) { - return{ async }; + return { async }; } template - impl::await_adapter> operator co_await(IAsyncOperationWithProgress const& async) + impl::await_adapter> operator co_await( + IAsyncOperationWithProgress const& async) { - return{ async }; + return { async }; } } #endif WINRT_EXPORT namespace winrt { - struct get_progress_token_t {}; + struct get_progress_token_t + {}; inline get_progress_token_t get_progress_token() noexcept { - return{}; + return {}; } - struct get_cancellation_token_t {}; + struct get_cancellation_token_t + {}; inline get_cancellation_token_t get_cancellation_token() noexcept { - return{}; + return {}; } } namespace winrt::impl { - template - struct cancellation_token + template struct cancellation_token { - cancellation_token(Promise* promise) noexcept : m_promise(promise) - { - } + cancellation_token(Promise* promise) noexcept : + m_promise(promise) + {} bool await_ready() const noexcept { @@ -328,8 +329,7 @@ namespace winrt::impl } void await_suspend(coroutine_handle<>) const noexcept - { - } + {} cancellation_token await_resume() const noexcept { @@ -352,17 +352,14 @@ namespace winrt::impl } private: - Promise* m_promise; }; - template - struct progress_token + template struct progress_token { progress_token(Promise* promise) noexcept : m_promise(promise) - { - } + {} bool await_ready() const noexcept { @@ -370,8 +367,7 @@ namespace winrt::impl } void await_suspend(coroutine_handle<>) const noexcept - { - } + {} progress_token await_resume() const noexcept { @@ -383,15 +379,13 @@ namespace winrt::impl m_promise->set_progress(result); } - template - void set_result(T&& value) const + template void set_result(T&& value) const { static_assert(!std::is_same_v, "Setting preliminary results requires IAsync...WithProgress"); m_promise->return_value(std::forward(value)); } private: - Promise* m_promise; }; @@ -498,8 +492,7 @@ namespace winrt::impl } void Close() const noexcept - { - } + {} auto GetResults() { @@ -526,7 +519,6 @@ namespace winrt::impl WINRT_ASSERT(status == AsyncStatus::Error || status == AsyncStatus::Canceled); std::rethrow_exception(m_exception); } - } AsyncInterface get_return_object() const noexcept @@ -535,12 +527,10 @@ namespace winrt::impl } void get_return_value() const noexcept - { - } + {} void copy_return_value() const noexcept - { - } + {} void set_completed() noexcept { @@ -568,7 +558,7 @@ namespace winrt::impl suspend_never initial_suspend() const noexcept { - return{}; + return {}; } struct final_suspend_awaiter @@ -581,8 +571,7 @@ namespace winrt::impl } void await_resume() const noexcept - { - } + {} bool await_suspend(coroutine_handle<>) const noexcept { @@ -606,7 +595,9 @@ namespace winrt::impl void unhandled_exception() noexcept { slim_lock_guard const guard(m_lock); - WINRT_ASSERT(m_status.load(std::memory_order_relaxed) == AsyncStatus::Started || m_status.load(std::memory_order_relaxed) == AsyncStatus::Canceled); + WINRT_ASSERT( + m_status.load(std::memory_order_relaxed) == AsyncStatus::Started || + m_status.load(std::memory_order_relaxed) == AsyncStatus::Canceled); m_exception = std::current_exception(); try @@ -623,8 +614,7 @@ namespace winrt::impl } } - template - Expression&& await_transform(Expression&& expression) + template Expression&& await_transform(Expression&& expression) { if (Status() == AsyncStatus::Canceled) { @@ -636,12 +626,12 @@ namespace winrt::impl cancellation_token await_transform(get_cancellation_token_t) noexcept { - return{ static_cast(this) }; + return { static_cast(this) }; } progress_token await_transform(get_progress_token_t) noexcept { - return{ static_cast(this) }; + return { static_cast(this) }; } void cancellation_callback(winrt::delegate<>&& cancel) noexcept @@ -664,12 +654,10 @@ namespace winrt::impl #if defined(_DEBUG) && !defined(WINRT_NO_MAKE_DETECTION) void use_make_function_to_create_this_object() final - { - } + {} #endif protected: - void rethrow_if_failed(AsyncStatus status) const { if (status == AsyncStatus::Error || status == AsyncStatus::Canceled) @@ -685,7 +673,7 @@ namespace winrt::impl std::atomic m_status; bool m_completed_assigned{ false }; }; -} +} // namespace winrt::impl #ifdef __cpp_lib_coroutine namespace std @@ -693,21 +681,20 @@ namespace std namespace std::experimental #endif { - template - struct coroutine_traits + template struct coroutine_traits { struct promise_type final : winrt::impl::promise_base { void return_void() const noexcept - { - } + {} }; }; template struct coroutine_traits, Args...> { - struct promise_type final : winrt::impl::promise_base, TProgress> + struct promise_type final + : winrt::impl::promise_base, TProgress> { using ProgressHandler = winrt::Windows::Foundation::AsyncActionProgressHandler; @@ -724,8 +711,7 @@ namespace std::experimental } void return_void() const noexcept - { - } + {} void set_progress(TProgress const& result) { @@ -742,7 +728,8 @@ namespace std::experimental template struct coroutine_traits, Args...> { - struct promise_type final : winrt::impl::promise_base> + struct promise_type final + : winrt::impl::promise_base> { TResult get_return_value() noexcept { @@ -771,8 +758,8 @@ namespace std::experimental template struct coroutine_traits, Args...> { - struct promise_type final : winrt::impl::promise_base, TProgress> + struct promise_type final + : winrt::impl::promise_base, TProgress> { using ProgressHandler = winrt::Windows::Foundation::AsyncOperationProgressHandler; @@ -827,15 +814,13 @@ namespace std::experimental WINRT_EXPORT namespace winrt { #ifdef WINRT_IMPL_COROUTINES - template - Windows::Foundation::IAsyncAction when_all(T... async) + template Windows::Foundation::IAsyncAction when_all(T... async) { (void(co_await async), ...); co_return; } - template - T when_any(T const& first, Rest const& ... rest) + template T when_any(T const& first, Rest const&... rest) { static_assert(impl::has_category_v, "T must be WinRT async type such as IAsyncAction or IAsyncOperation."); static_assert((std::is_same_v && ...), "All when_any parameters must be the same type."); diff --git a/strings/base_coroutine_system.h b/strings/base_coroutine_system.h index b893bd1b5..f01ea5e2a 100644 --- a/strings/base_coroutine_system.h +++ b/strings/base_coroutine_system.h @@ -7,11 +7,10 @@ WINRT_EXPORT namespace winrt { struct awaitable { - awaitable(Windows::System::DispatcherQueue const& dispatcher, Windows::System::DispatcherQueuePriority const priority) noexcept : - m_dispatcher(dispatcher), - m_priority(priority) - { - } + awaitable(Windows::System::DispatcherQueue const& dispatcher, Windows::System::DispatcherQueuePriority const priority) noexcept + : + m_dispatcher(dispatcher), m_priority(priority) + {} bool await_ready() const noexcept { @@ -25,7 +24,9 @@ WINRT_EXPORT namespace winrt bool await_suspend(impl::coroutine_handle<> handle) { - return m_dispatcher.TryEnqueue(m_priority, [handle, this] + return m_dispatcher.TryEnqueue( + m_priority, + [handle, this] { m_queued = true; handle(); diff --git a/strings/base_coroutine_system_winui.h b/strings/base_coroutine_system_winui.h index ecb3cf766..5dfdef368 100644 --- a/strings/base_coroutine_system_winui.h +++ b/strings/base_coroutine_system_winui.h @@ -7,11 +7,10 @@ WINRT_EXPORT namespace winrt { struct awaitable { - awaitable(Microsoft::System::DispatcherQueue const& dispatcher, Microsoft::System::DispatcherQueuePriority const priority) noexcept : - m_dispatcher(dispatcher), - m_priority(priority) - { - } + awaitable(Microsoft::System::DispatcherQueue const& dispatcher, Microsoft::System::DispatcherQueuePriority const priority) noexcept + : + m_dispatcher(dispatcher), m_priority(priority) + {} bool await_ready() const noexcept { @@ -25,7 +24,9 @@ WINRT_EXPORT namespace winrt bool await_suspend(impl::coroutine_handle<> handle) { - return m_dispatcher.TryEnqueue(m_priority, [handle, this] + return m_dispatcher.TryEnqueue( + m_priority, + [handle, this] { m_queued = true; handle(); diff --git a/strings/base_coroutine_threadpool.h b/strings/base_coroutine_threadpool.h index 0faaa1acd..90173581c 100644 --- a/strings/base_coroutine_threadpool.h +++ b/strings/base_coroutine_threadpool.h @@ -41,9 +41,8 @@ namespace winrt::impl case 0: /* APTTYPE_STA */ case 3: /* APTTYPE_MAINSTA */ return true; - case 2: /* APTTYPE_NA */ - return type.second == 3 /* APTTYPEQUALIFIER_NA_ON_STA */ || - type.second == 5 /* APTTYPEQUALIFIER_NA_ON_MAINSTA */; + case 2: /* APTTYPE_NA */ + return type.second == 3 /* APTTYPEQUALIFIER_NA_ON_STA */ || type.second == 5 /* APTTYPEQUALIFIER_NA_ON_MAINSTA */; } return false; } @@ -51,7 +50,9 @@ namespace winrt::impl struct resume_apartment_context { resume_apartment_context() = default; - resume_apartment_context(std::nullptr_t) : m_context(nullptr), m_context_type(-1) {} + resume_apartment_context(std::nullptr_t) : + m_context(nullptr), m_context_type(-1) + {} bool valid() const noexcept { @@ -73,7 +74,8 @@ namespace winrt::impl com_callback_args args{}; args.data = handle.address(); - auto result = context->ContextCallback(resume_apartment_callback, &args, guid_of(), 5, nullptr); + auto result = context->ContextCallback( + resume_apartment_callback, &args, guid_of(), 5, nullptr); if (result < 0) { // Resume the coroutine on the wrong apartment, but tell it why. @@ -86,7 +88,8 @@ namespace winrt::impl struct threadpool_resume { threadpool_resume(com_ptr const& context, coroutine_handle<> handle, int32_t* failure) : - m_context(context), m_handle(handle), m_failure(failure) { } + m_context(context), m_handle(handle), m_failure(failure) + {} com_ptr m_context; coroutine_handle<> m_handle; int32_t* m_failure; @@ -111,7 +114,8 @@ namespace winrt::impl [[nodiscard]] inline auto resume_apartment(resume_apartment_context const& context, coroutine_handle<> handle, int32_t* failure) { WINRT_ASSERT(context.valid()); - if ((context.m_context == nullptr) || (context.m_context == try_capture(WINRT_IMPL_CoGetObjectContext))) + if ((context.m_context == nullptr) || + (context.m_context == try_capture(WINRT_IMPL_CoGetObjectContext))) { return false; } @@ -130,13 +134,13 @@ namespace winrt::impl return resume_apartment_sync(context.m_context, handle, failure); } } -} +} // namespace winrt::impl WINRT_EXPORT namespace winrt { struct cancellable_promise { - using canceller_t = void(*)(void*); + using canceller_t = void (*)(void*); void set_canceller(canceller_t canceller, void* context) { @@ -188,8 +192,7 @@ WINRT_EXPORT namespace winrt bool m_propagate_cancellation{ false }; }; - template - struct cancellable_awaiter + template struct cancellable_awaiter { cancellable_awaiter() noexcept = default; cancellable_awaiter(cancellable_awaiter const&) = default; @@ -205,8 +208,7 @@ WINRT_EXPORT namespace winrt void operator=(cancellable_awaiter const&) = delete; protected: - template - void set_cancellable_promise_from_handle(impl::coroutine_handle const& handle) + template void set_cancellable_promise_from_handle(impl::coroutine_handle const& handle) { if constexpr (std::is_base_of_v) { @@ -240,8 +242,7 @@ WINRT_EXPORT namespace winrt } void await_resume() const noexcept - { - } + {} void await_suspend(impl::coroutine_handle<> handle) const { @@ -252,14 +253,13 @@ WINRT_EXPORT namespace winrt return awaitable{}; } - template - [[nodiscard]] auto resume_background(T const& context) noexcept + template [[nodiscard]] auto resume_background(T const& context) noexcept { struct awaitable { - awaitable(T const& context) : m_context(context) - { - } + awaitable(T const& context) : + m_context(context) + {} bool await_ready() const noexcept { @@ -267,8 +267,7 @@ WINRT_EXPORT namespace winrt } void await_resume() const noexcept - { - } + {} void await_suspend(impl::coroutine_handle<> resume) { @@ -281,7 +280,6 @@ WINRT_EXPORT namespace winrt } private: - static void __stdcall callback(void*, void* context) noexcept { auto that = static_cast(context); @@ -299,10 +297,18 @@ WINRT_EXPORT namespace winrt struct apartment_context { apartment_context() = default; - apartment_context(std::nullptr_t) : context(nullptr) { } + apartment_context(std::nullptr_t) : + context(nullptr) + {} - operator bool() const noexcept { return context.valid(); } - bool operator!() const noexcept { return !context.valid(); } + operator bool() const noexcept + { + return context.valid(); + } + bool operator!() const noexcept + { + return !context.valid(); + } impl::resume_apartment_context context; }; @@ -336,32 +342,33 @@ namespace winrt::impl { explicit timespan_awaiter(Windows::Foundation::TimeSpan duration) noexcept : m_duration(duration) - { - } + {} #if defined(__GNUC__) && !defined(__clang__) // HACK: GCC seems to require a move when calling operator co_await // on the return value of resume_after. // This might be related to upstream bug: // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=99575 - timespan_awaiter(timespan_awaiter &&other) noexcept : - m_timer{std::move(other.m_timer)}, - m_duration{std::move(other.m_duration)}, - m_handle{std::move(other.m_handle)}, - m_state{other.m_state.load()} + timespan_awaiter(timespan_awaiter&& other) noexcept : + m_timer{ std::move(other.m_timer) }, + m_duration{ std::move(other.m_duration) }, + m_handle{ std::move(other.m_handle) }, + m_state{ other.m_state.load() } {} #endif void enable_cancellation(cancellable_promise* promise) { - promise->set_canceller([](void* context) - { - auto that = static_cast(context); - if (that->m_state.exchange(state::canceled, std::memory_order_acquire) == state::pending) + promise->set_canceller( + [](void* context) { - that->fire_immediately(); - } - }, this); + auto that = static_cast(context); + if (that->m_state.exchange(state::canceled, std::memory_order_acquire) == state::pending) + { + that->fire_immediately(); + } + }, + this); } bool await_ready() const noexcept @@ -369,8 +376,7 @@ namespace winrt::impl return m_duration.count() <= 0; } - template - void await_suspend(impl::coroutine_handle handle) + template void await_suspend(impl::coroutine_handle handle) { set_cancellable_promise_from_handle(handle); @@ -430,7 +436,12 @@ namespace winrt::impl } }; - enum class state { idle, pending, canceled }; + enum class state + { + idle, + pending, + canceled + }; handle_type m_timer; Windows::Foundation::TimeSpan m_duration; @@ -441,8 +452,7 @@ namespace winrt::impl struct signal_awaiter : cancellable_awaiter { signal_awaiter(void* handle, Windows::Foundation::TimeSpan timeout) noexcept : - m_timeout(timeout), - m_handle(handle) + m_timeout(timeout), m_handle(handle) {} #if defined(__GNUC__) && !defined(__clang__) @@ -450,26 +460,28 @@ namespace winrt::impl // on the return value of resume_on_signal. // This might be related to upstream bug: // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=99575 - signal_awaiter(signal_awaiter &&other) noexcept : - m_wait{std::move(other.m_wait)}, - m_timeout{std::move(other.m_timeout)}, - m_handle{std::move(other.m_handle)}, - m_result{std::move(other.m_result)}, - m_resume{std::move(other.m_resume)}, - m_state{other.m_state.load()} + signal_awaiter(signal_awaiter&& other) noexcept : + m_wait{ std::move(other.m_wait) }, + m_timeout{ std::move(other.m_timeout) }, + m_handle{ std::move(other.m_handle) }, + m_result{ std::move(other.m_result) }, + m_resume{ std::move(other.m_resume) }, + m_state{ other.m_state.load() } {} #endif void enable_cancellation(cancellable_promise* promise) { - promise->set_canceller([](void* context) - { - auto that = static_cast(context); - if (that->m_state.exchange(state::canceled, std::memory_order_acquire) == state::pending) + promise->set_canceller( + [](void* context) { - that->fire_immediately(); - } - }, this); + auto that = static_cast(context); + if (that->m_state.exchange(state::canceled, std::memory_order_acquire) == state::pending) + { + that->fire_immediately(); + } + }, + this); } bool await_ready() const noexcept @@ -477,8 +489,7 @@ namespace winrt::impl return WINRT_IMPL_WaitForSingleObject(m_handle, 0) == 0; } - template - void await_suspend(impl::coroutine_handle resume) + template void await_suspend(impl::coroutine_handle resume) { set_cancellable_promise_from_handle(resume); @@ -496,7 +507,6 @@ namespace winrt::impl } private: - void create_threadpool_wait() { m_wait.attach(check_pointer(WINRT_IMPL_CreateThreadpoolWait(callback, this, nullptr))); @@ -542,7 +552,12 @@ namespace winrt::impl } }; - enum class state { idle, pending, canceled }; + enum class state + { + idle, + pending, + canceled + }; handle_type m_wait; Windows::Foundation::TimeSpan m_timeout; @@ -551,14 +566,14 @@ namespace winrt::impl impl::coroutine_handle<> m_resume{ nullptr }; std::atomic m_state{ state::idle }; }; -} +} // namespace winrt::impl WINRT_EXPORT namespace winrt { #ifdef WINRT_IMPL_COROUTINES inline impl::apartment_awaiter operator co_await(apartment_context const& context) { - return{ context }; + return { context }; } #endif @@ -599,8 +614,7 @@ WINRT_EXPORT namespace winrt } void await_resume() const noexcept - { - } + {} void await_suspend(impl::coroutine_handle<> handle) { @@ -611,7 +625,6 @@ WINRT_EXPORT namespace winrt } private: - static void __stdcall callback(void*, void* context) noexcept { impl::coroutine_handle<>::from_address(context)(); @@ -659,7 +672,8 @@ WINRT_EXPORT namespace winrt environment m_environment; }; - struct fire_and_forget {}; + struct fire_and_forget + {}; } #ifdef __cpp_lib_coroutine @@ -668,28 +682,26 @@ namespace std namespace std::experimental #endif { - template - struct coroutine_traits + template struct coroutine_traits { struct promise_type { winrt::fire_and_forget get_return_object() const noexcept { - return{}; + return {}; } void return_void() const noexcept - { - } + {} suspend_never initial_suspend() const noexcept { - return{}; + return {}; } suspend_never final_suspend() const noexcept { - return{}; + return {}; } void unhandled_exception() const noexcept diff --git a/strings/base_coroutine_ui_core.h b/strings/base_coroutine_ui_core.h index dab34c8de..e33492782 100644 --- a/strings/base_coroutine_ui_core.h +++ b/strings/base_coroutine_ui_core.h @@ -7,11 +7,10 @@ WINRT_EXPORT namespace winrt { struct awaitable { - awaitable(Windows::UI::Core::CoreDispatcher const& dispatcher, Windows::UI::Core::CoreDispatcherPriority const priority) noexcept : - m_dispatcher(dispatcher), - m_priority(priority) - { - } + awaitable(Windows::UI::Core::CoreDispatcher const& dispatcher, Windows::UI::Core::CoreDispatcherPriority const priority) noexcept + : + m_dispatcher(dispatcher), m_priority(priority) + {} bool await_ready() const noexcept { @@ -19,19 +18,14 @@ WINRT_EXPORT namespace winrt } void await_resume() const noexcept - { - } + {} void await_suspend(impl::coroutine_handle<> handle) const { - m_dispatcher.RunAsync(m_priority, [handle] - { - handle(); - }); + m_dispatcher.RunAsync(m_priority, [handle] { handle(); }); } private: - Windows::UI::Core::CoreDispatcher const& m_dispatcher; Windows::UI::Core::CoreDispatcherPriority const m_priority; }; diff --git a/strings/base_deferral.h b/strings/base_deferral.h index ceab1cd4b..e86df48be 100644 --- a/strings/base_deferral.h +++ b/strings/base_deferral.h @@ -2,8 +2,7 @@ WINRT_EXPORT namespace winrt { #ifdef WINRT_IMPL_COROUTINES - template - struct deferrable_event_args + template struct deferrable_event_args { Windows::Foundation::Deferral GetDeferral() { @@ -15,7 +14,8 @@ WINRT_EXPORT namespace winrt throw hresult_illegal_method_call(); } - Windows::Foundation::Deferral deferral{ {static_cast(*this).get_strong(), &deferrable_event_args::one_deferral_completed } }; + Windows::Foundation::Deferral deferral{ { static_cast(*this).get_strong(), + &deferrable_event_args::one_deferral_completed } }; ++m_outstanding_deferrals; return deferral; } @@ -36,7 +36,6 @@ WINRT_EXPORT namespace winrt } private: - using coroutine_handle = impl::coroutine_handle<>; void one_deferral_completed() diff --git a/strings/base_delegate.h b/strings/base_delegate.h index 8902b3cc6..2694773f4 100644 --- a/strings/base_delegate.h +++ b/strings/base_delegate.h @@ -3,7 +3,7 @@ namespace winrt::impl { #if defined(_MSC_VER) #pragma warning(push) -#pragma warning(disable:4458) // declaration hides class member (okay because we do not use named members of base class) +#pragma warning(disable : 4458) // declaration hides class member (okay because we do not use named members of base class) #endif struct implements_delegate_base @@ -43,9 +43,9 @@ namespace winrt::impl template struct implements_delegate : abi_t, implements_delegate_base, H, update_module_lock { - implements_delegate(H&& handler) : H(std::forward(handler)) - { - } + implements_delegate(H&& handler) : + H(std::forward(handler)) + {} int32_t __stdcall QueryInterface(guid const& id, void** result) noexcept final { @@ -70,14 +70,13 @@ namespace winrt::impl } }; - template - T make_delegate(H&& handler) + template T make_delegate(H&& handler) { - return { static_cast(static_cast*>(new delegate(std::forward(handler)))), take_ownership_from_abi }; + return { static_cast(static_cast*>(new delegate(std::forward(handler)))), + take_ownership_from_abi }; } - template - T make_agile_delegate(T const& delegate) noexcept + template T make_agile_delegate(T const& delegate) noexcept { if constexpr (!has_category_v) { @@ -96,7 +95,7 @@ namespace winrt::impl if (ref) { - return [ref = std::move(ref), id](auto&& ... args) + return [ref = std::move(ref), id](auto&&... args) { T delegate; ref->Resolve(id, put_abi(delegate)); @@ -108,20 +107,19 @@ namespace winrt::impl } } - template - struct WINRT_IMPL_NOVTABLE variadic_delegate_abi : unknown_abi + template struct WINRT_IMPL_NOVTABLE variadic_delegate_abi : unknown_abi { - virtual R invoke(Args const& ...) = 0; + virtual R invoke(Args const&...) = 0; }; template struct variadic_delegate final : variadic_delegate_abi, implements_delegate_base, H, update_module_lock { - variadic_delegate(H&& handler) : H(std::forward(handler)) - { - } + variadic_delegate(H&& handler) : + H(std::forward(handler)) + {} - R invoke(Args const& ... args) final + R invoke(Args const&... args) final { if constexpr (std::is_void_v) { @@ -156,74 +154,90 @@ namespace winrt::impl } }; - template - struct WINRT_IMPL_EMPTY_BASES delegate_base : Windows::Foundation::IUnknown + template struct WINRT_IMPL_EMPTY_BASES delegate_base : Windows::Foundation::IUnknown { - delegate_base(std::nullptr_t = nullptr) noexcept {} - delegate_base(void* ptr, take_ownership_from_abi_t) noexcept : IUnknown(ptr, take_ownership_from_abi) {} + delegate_base(std::nullptr_t = nullptr) noexcept + {} + delegate_base(void* ptr, take_ownership_from_abi_t) noexcept : + IUnknown(ptr, take_ownership_from_abi) + {} template delegate_base(L handler) : delegate_base(make(std::forward(handler))) {} - template delegate_base(F* handler) : - delegate_base([=](auto&& ... args) { return handler(args...); }) + template + delegate_base(F* handler) : + delegate_base([=](auto&&... args) { return handler(args...); }) {} - template delegate_base(O* object, M method) : - delegate_base([=](auto&& ... args) { return ((*object).*(method))(args...); }) + template + delegate_base(O* object, M method) : + delegate_base([=](auto&&... args) { return ((*object).*(method))(args...); }) {} - template delegate_base(com_ptr&& object, M method) : - delegate_base([o = std::move(object), method](auto&& ... args) { return ((*o).*(method))(args...); }) - { - } + template + delegate_base(com_ptr&& object, M method) : + delegate_base([o = std::move(object), method](auto&&... args) { return ((*o).*(method))(args...); }) + {} - template delegate_base(winrt::weak_ref&& object, LM&& lambda_or_method) : - delegate_base([o = std::move(object), lm = std::forward(lambda_or_method)](auto&&... args) { if (auto s = o.get()) { - if constexpr (std::is_member_function_pointer_v) ((*s).*(lm))(args...); - else lm(args...); - }}) - { - } + template + delegate_base(winrt::weak_ref&& object, LM&& lambda_or_method) : + delegate_base( + [o = std::move(object), lm = std::forward(lambda_or_method)](auto&&... args) + { + if (auto s = o.get()) + { + if constexpr (std::is_member_function_pointer_v) + ((*s).*(lm))(args...); + else + lm(args...); + } + }) + {} - template delegate_base(std::shared_ptr&& object, M method) : - delegate_base([o = std::move(object), method](auto&& ... args) { return ((*o).*(method))(args...); }) - { - } + template + delegate_base(std::shared_ptr&& object, M method) : + delegate_base([o = std::move(object), method](auto&&... args) { return ((*o).*(method))(args...); }) + {} - template delegate_base(std::weak_ptr&& object, LM&& lambda_or_method) : - delegate_base([o = std::move(object), lm = std::forward(lambda_or_method)](auto&&... args) { if (auto s = o.lock()) { - if constexpr (std::is_member_function_pointer_v) ((*s).*(lm))(args...); - else lm(args...); - }}) - { - } + template + delegate_base(std::weak_ptr&& object, LM&& lambda_or_method) : + delegate_base( + [o = std::move(object), lm = std::forward(lambda_or_method)](auto&&... args) + { + if (auto s = o.lock()) + { + if constexpr (std::is_member_function_pointer_v) + ((*s).*(lm))(args...); + else + lm(args...); + } + }) + {} - auto operator()(Args const& ... args) const + auto operator()(Args const&... args) const { - return (*(variadic_delegate_abi * *)this)->invoke(args...); + return (*(variadic_delegate_abi**)this)->invoke(args...); } private: - - template - static delegate_base make(H&& handler) + template static delegate_base make(H&& handler) { - return { static_cast(new variadic_delegate(std::forward(handler))), take_ownership_from_abi }; + return { static_cast(new variadic_delegate(std::forward(handler))), + take_ownership_from_abi }; } }; #if defined(_MSC_VER) #pragma warning(pop) #endif -} +} // namespace winrt::impl WINRT_EXPORT namespace winrt { - template - struct WINRT_IMPL_EMPTY_BASES delegate : impl::delegate_base + template struct WINRT_IMPL_EMPTY_BASES delegate : impl::delegate_base { using impl::delegate_base::delegate_base; }; diff --git a/strings/base_error.h b/strings/base_error.h index 85de70f63..922143e95 100644 --- a/strings/base_error.h +++ b/strings/base_error.h @@ -45,7 +45,7 @@ namespace winrt::impl { wchar_t const* back = message + size - 1; - while (size&& iswspace(*back)) + while (size && iswspace(*back)) { --size; --back; @@ -58,7 +58,8 @@ namespace winrt::impl { handle_type message; - uint32_t const size = WINRT_IMPL_FormatMessageW(0x00001300, // FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS + uint32_t const size = WINRT_IMPL_FormatMessageW( + 0x00001300, // FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS nullptr, code, 0x00000400, // MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT) @@ -78,7 +79,7 @@ namespace winrt::impl { return ((int32_t)((x) | 0x10000000)); } -} +} // namespace winrt::impl WINRT_EXPORT namespace winrt { @@ -92,10 +93,8 @@ WINRT_EXPORT namespace winrt hresult_error& operator=(hresult_error&&) = default; hresult_error(hresult_error const& other) noexcept : - m_code(other.m_code), - m_info(other.m_info) - { - } + m_code(other.m_code), m_info(other.m_info) + {} hresult_error& operator=(hresult_error const& other) noexcept { @@ -104,17 +103,28 @@ WINRT_EXPORT namespace winrt return *this; } - explicit hresult_error(hresult const code, winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : m_code(verify_error(code)) + explicit hresult_error( + hresult const code, + winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : + m_code(verify_error(code)) { originate(code, nullptr, sourceInformation); } - hresult_error(hresult const code, param::hstring const& message, winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : m_code(verify_error(code)) + hresult_error( + hresult const code, + param::hstring const& message, + winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : + m_code(verify_error(code)) { originate(code, get_abi(message), sourceInformation); } - hresult_error(hresult const code, take_ownership_from_abi_t, winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : m_code(verify_error(code)) + hresult_error( + hresult const code, + take_ownership_from_abi_t, + winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : + m_code(verify_error(code)) { com_ptr info; WINRT_IMPL_GetErrorInfo(0, info.put_void()); @@ -181,8 +191,7 @@ WINRT_EXPORT namespace winrt return impl::message_from_hresult(m_code); } - template - auto try_as() const noexcept + template auto try_as() const noexcept { return m_info.try_as(); } @@ -198,17 +207,24 @@ WINRT_EXPORT namespace winrt } private: - - void originate(hresult const code, void* message, winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept + void originate( + hresult const code, + void* message, + winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept { WINRT_VERIFY(WINRT_IMPL_RoOriginateLanguageException(code, message, nullptr)); - // This is an extension point that can be filled in by other libraries (such as WIL) to get call outs when errors are - // originated. This is intended for logging purposes. When possible include the std::source_information so that accurate - // information is available on the caller who generated the error. + // This is an extension point that can be filled in by other libraries (such as WIL) to get call outs when + // errors are originated. This is intended for logging purposes. When possible include the + // std::source_information so that accurate information is available on the caller who generated the error. if (winrt_throw_hresult_handler) { - winrt_throw_hresult_handler(sourceInformation.line(), sourceInformation.file_name(), sourceInformation.function_name(), WINRT_IMPL_RETURNADDRESS(), code); + winrt_throw_hresult_handler( + sourceInformation.line(), + sourceInformation.file_name(), + sourceInformation.function_name(), + WINRT_IMPL_RETURNADDRESS(), + code); } com_ptr info; @@ -222,7 +238,6 @@ WINRT_EXPORT namespace winrt return code; } - #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-private-field" @@ -240,100 +255,250 @@ WINRT_EXPORT namespace winrt struct hresult_access_denied : hresult_error { - hresult_access_denied(winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : hresult_error(impl::error_access_denied, sourceInformation) {} - hresult_access_denied(param::hstring const& message, winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : hresult_error(impl::error_access_denied, message, sourceInformation) {} - hresult_access_denied(take_ownership_from_abi_t, winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : hresult_error(impl::error_access_denied, take_ownership_from_abi, sourceInformation) {} + hresult_access_denied( + winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : + hresult_error(impl::error_access_denied, sourceInformation) + {} + hresult_access_denied( + param::hstring const& message, + winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : + hresult_error(impl::error_access_denied, message, sourceInformation) + {} + hresult_access_denied( + take_ownership_from_abi_t, + winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : + hresult_error(impl::error_access_denied, take_ownership_from_abi, sourceInformation) + {} }; struct hresult_wrong_thread : hresult_error { - hresult_wrong_thread(winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : hresult_error(impl::error_wrong_thread, sourceInformation) {} - hresult_wrong_thread(param::hstring const& message, winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : hresult_error(impl::error_wrong_thread, message, sourceInformation) {} - hresult_wrong_thread(take_ownership_from_abi_t, winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : hresult_error(impl::error_wrong_thread, take_ownership_from_abi, sourceInformation) {} + hresult_wrong_thread( + winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : + hresult_error(impl::error_wrong_thread, sourceInformation) + {} + hresult_wrong_thread( + param::hstring const& message, + winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : + hresult_error(impl::error_wrong_thread, message, sourceInformation) + {} + hresult_wrong_thread( + take_ownership_from_abi_t, + winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : + hresult_error(impl::error_wrong_thread, take_ownership_from_abi, sourceInformation) + {} }; struct hresult_not_implemented : hresult_error { - hresult_not_implemented(winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : hresult_error(impl::error_not_implemented, sourceInformation) {} - hresult_not_implemented(param::hstring const& message, winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : hresult_error(impl::error_not_implemented, message, sourceInformation) {} - hresult_not_implemented(take_ownership_from_abi_t, winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : hresult_error(impl::error_not_implemented, take_ownership_from_abi, sourceInformation) {} + hresult_not_implemented( + winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : + hresult_error(impl::error_not_implemented, sourceInformation) + {} + hresult_not_implemented( + param::hstring const& message, + winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : + hresult_error(impl::error_not_implemented, message, sourceInformation) + {} + hresult_not_implemented( + take_ownership_from_abi_t, + winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : + hresult_error(impl::error_not_implemented, take_ownership_from_abi, sourceInformation) + {} }; struct hresult_invalid_argument : hresult_error { - hresult_invalid_argument(winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : hresult_error(impl::error_invalid_argument, sourceInformation) {} - hresult_invalid_argument(param::hstring const& message, winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : hresult_error(impl::error_invalid_argument, message, sourceInformation) {} - hresult_invalid_argument(take_ownership_from_abi_t, winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : hresult_error(impl::error_invalid_argument, take_ownership_from_abi, sourceInformation) {} + hresult_invalid_argument( + winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : + hresult_error(impl::error_invalid_argument, sourceInformation) + {} + hresult_invalid_argument( + param::hstring const& message, + winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : + hresult_error(impl::error_invalid_argument, message, sourceInformation) + {} + hresult_invalid_argument( + take_ownership_from_abi_t, + winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : + hresult_error(impl::error_invalid_argument, take_ownership_from_abi, sourceInformation) + {} }; struct hresult_out_of_bounds : hresult_error { - hresult_out_of_bounds(winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : hresult_error(impl::error_out_of_bounds, sourceInformation) {} - hresult_out_of_bounds(param::hstring const& message, winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : hresult_error(impl::error_out_of_bounds, message, sourceInformation) {} - hresult_out_of_bounds(take_ownership_from_abi_t, winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : hresult_error(impl::error_out_of_bounds, take_ownership_from_abi, sourceInformation) {} + hresult_out_of_bounds( + winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : + hresult_error(impl::error_out_of_bounds, sourceInformation) + {} + hresult_out_of_bounds( + param::hstring const& message, + winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : + hresult_error(impl::error_out_of_bounds, message, sourceInformation) + {} + hresult_out_of_bounds( + take_ownership_from_abi_t, + winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : + hresult_error(impl::error_out_of_bounds, take_ownership_from_abi, sourceInformation) + {} }; struct hresult_no_interface : hresult_error { - hresult_no_interface(winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : hresult_error(impl::error_no_interface, sourceInformation) {} - hresult_no_interface(param::hstring const& message, winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : hresult_error(impl::error_no_interface, message, sourceInformation) {} - hresult_no_interface(take_ownership_from_abi_t, winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : hresult_error(impl::error_no_interface, take_ownership_from_abi, sourceInformation) {} + hresult_no_interface( + winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : + hresult_error(impl::error_no_interface, sourceInformation) + {} + hresult_no_interface( + param::hstring const& message, + winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : + hresult_error(impl::error_no_interface, message, sourceInformation) + {} + hresult_no_interface( + take_ownership_from_abi_t, + winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : + hresult_error(impl::error_no_interface, take_ownership_from_abi, sourceInformation) + {} }; struct hresult_class_not_available : hresult_error { - hresult_class_not_available(winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : hresult_error(impl::error_class_not_available, sourceInformation) {} - hresult_class_not_available(param::hstring const& message, winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : hresult_error(impl::error_class_not_available, message, sourceInformation) {} - hresult_class_not_available(take_ownership_from_abi_t, winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : hresult_error(impl::error_class_not_available, take_ownership_from_abi, sourceInformation) {} + hresult_class_not_available( + winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : + hresult_error(impl::error_class_not_available, sourceInformation) + {} + hresult_class_not_available( + param::hstring const& message, + winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : + hresult_error(impl::error_class_not_available, message, sourceInformation) + {} + hresult_class_not_available( + take_ownership_from_abi_t, + winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : + hresult_error(impl::error_class_not_available, take_ownership_from_abi, sourceInformation) + {} }; struct hresult_class_not_registered : hresult_error { - hresult_class_not_registered(winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : hresult_error(impl::error_class_not_registered, sourceInformation) {} - hresult_class_not_registered(param::hstring const& message, winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : hresult_error(impl::error_class_not_registered, message, sourceInformation) {} - hresult_class_not_registered(take_ownership_from_abi_t, winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : hresult_error(impl::error_class_not_registered, take_ownership_from_abi, sourceInformation) {} + hresult_class_not_registered( + winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : + hresult_error(impl::error_class_not_registered, sourceInformation) + {} + hresult_class_not_registered( + param::hstring const& message, + winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : + hresult_error(impl::error_class_not_registered, message, sourceInformation) + {} + hresult_class_not_registered( + take_ownership_from_abi_t, + winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : + hresult_error(impl::error_class_not_registered, take_ownership_from_abi, sourceInformation) + {} }; struct hresult_changed_state : hresult_error { - hresult_changed_state(winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : hresult_error(impl::error_changed_state, sourceInformation) {} - hresult_changed_state(param::hstring const& message, winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : hresult_error(impl::error_changed_state, message, sourceInformation) {} - hresult_changed_state(take_ownership_from_abi_t, winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : hresult_error(impl::error_changed_state, take_ownership_from_abi, sourceInformation) {} + hresult_changed_state( + winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : + hresult_error(impl::error_changed_state, sourceInformation) + {} + hresult_changed_state( + param::hstring const& message, + winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : + hresult_error(impl::error_changed_state, message, sourceInformation) + {} + hresult_changed_state( + take_ownership_from_abi_t, + winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : + hresult_error(impl::error_changed_state, take_ownership_from_abi, sourceInformation) + {} }; struct hresult_illegal_method_call : hresult_error { - hresult_illegal_method_call(winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : hresult_error(impl::error_illegal_method_call, sourceInformation) {} - hresult_illegal_method_call(param::hstring const& message, winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : hresult_error(impl::error_illegal_method_call, message, sourceInformation) {} - hresult_illegal_method_call(take_ownership_from_abi_t, winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : hresult_error(impl::error_illegal_method_call, take_ownership_from_abi, sourceInformation) {} + hresult_illegal_method_call( + winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : + hresult_error(impl::error_illegal_method_call, sourceInformation) + {} + hresult_illegal_method_call( + param::hstring const& message, + winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : + hresult_error(impl::error_illegal_method_call, message, sourceInformation) + {} + hresult_illegal_method_call( + take_ownership_from_abi_t, + winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : + hresult_error(impl::error_illegal_method_call, take_ownership_from_abi, sourceInformation) + {} }; struct hresult_illegal_state_change : hresult_error { - hresult_illegal_state_change(winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : hresult_error(impl::error_illegal_state_change, sourceInformation) {} - hresult_illegal_state_change(param::hstring const& message, winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : hresult_error(impl::error_illegal_state_change, message, sourceInformation) {} - hresult_illegal_state_change(take_ownership_from_abi_t, winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : hresult_error(impl::error_illegal_state_change, take_ownership_from_abi, sourceInformation) {} + hresult_illegal_state_change( + winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : + hresult_error(impl::error_illegal_state_change, sourceInformation) + {} + hresult_illegal_state_change( + param::hstring const& message, + winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : + hresult_error(impl::error_illegal_state_change, message, sourceInformation) + {} + hresult_illegal_state_change( + take_ownership_from_abi_t, + winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : + hresult_error(impl::error_illegal_state_change, take_ownership_from_abi, sourceInformation) + {} }; struct hresult_illegal_delegate_assignment : hresult_error { - hresult_illegal_delegate_assignment(winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : hresult_error(impl::error_illegal_delegate_assignment, sourceInformation) {} - hresult_illegal_delegate_assignment(param::hstring const& message, winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : hresult_error(impl::error_illegal_delegate_assignment, message, sourceInformation) {} - hresult_illegal_delegate_assignment(take_ownership_from_abi_t, winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : hresult_error(impl::error_illegal_delegate_assignment, take_ownership_from_abi, sourceInformation) {} + hresult_illegal_delegate_assignment( + winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : + hresult_error(impl::error_illegal_delegate_assignment, sourceInformation) + {} + hresult_illegal_delegate_assignment( + param::hstring const& message, + winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : + hresult_error(impl::error_illegal_delegate_assignment, message, sourceInformation) + {} + hresult_illegal_delegate_assignment( + take_ownership_from_abi_t, + winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : + hresult_error(impl::error_illegal_delegate_assignment, take_ownership_from_abi, sourceInformation) + {} }; struct hresult_canceled : hresult_error { - hresult_canceled(winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : hresult_error(impl::error_canceled, sourceInformation) {} - hresult_canceled(param::hstring const& message, winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : hresult_error(impl::error_canceled, message, sourceInformation) {} - hresult_canceled(take_ownership_from_abi_t, winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : hresult_error(impl::error_canceled, take_ownership_from_abi, sourceInformation) {} + hresult_canceled(winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept + : + hresult_error(impl::error_canceled, sourceInformation) + {} + hresult_canceled( + param::hstring const& message, + winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : + hresult_error(impl::error_canceled, message, sourceInformation) + {} + hresult_canceled( + take_ownership_from_abi_t, + winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) noexcept : + hresult_error(impl::error_canceled, take_ownership_from_abi, sourceInformation) + {} }; - [[noreturn]] inline WINRT_IMPL_NOINLINE void throw_hresult(hresult const result, winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) + [[noreturn]] inline WINRT_IMPL_NOINLINE void throw_hresult( + hresult const result, + winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) { if (winrt_throw_hresult_handler) { - winrt_throw_hresult_handler(sourceInformation.line(), sourceInformation.file_name(), sourceInformation.function_name(), WINRT_IMPL_RETURNADDRESS(), result); + winrt_throw_hresult_handler( + sourceInformation.line(), + sourceInformation.file_name(), + sourceInformation.function_name(), + WINRT_IMPL_RETURNADDRESS(), + result); } if (result == impl::error_bad_alloc) @@ -467,7 +632,8 @@ WINRT_EXPORT namespace winrt } } - [[noreturn]] inline void throw_last_error(winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) + [[noreturn]] inline void throw_last_error( + winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) { throw_hresult(impl::hresult_from_win32(WINRT_IMPL_GetLastError()), sourceInformation); } @@ -481,8 +647,9 @@ WINRT_EXPORT namespace winrt return result; } - template - void check_nt(T result, winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) + template + void check_nt( + T result, winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) { if (result != 0) { @@ -490,8 +657,9 @@ WINRT_EXPORT namespace winrt } } - template - void check_win32(T result, winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) + template + void check_win32( + T result, winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) { if (result != 0) { @@ -499,19 +667,21 @@ WINRT_EXPORT namespace winrt } } - template - T check_bool(T result, winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) + template + T check_bool( + T result, winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) { if (!result) { winrt::throw_last_error(sourceInformation); } - + return result; } - template - T* check_pointer(T* pointer, winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) + template + T* check_pointer( + T * pointer, winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) { if (!pointer) { @@ -530,7 +700,9 @@ WINRT_EXPORT namespace winrt namespace winrt::impl { - inline hresult check_hresult_allow_bounds(hresult const result, winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) + inline hresult check_hresult_allow_bounds( + hresult const result, + winrt::impl::slim_source_location const& sourceInformation = winrt::impl::slim_source_location::current()) { if (result != impl::error_out_of_bounds && result != impl::error_fail && result != impl::error_file_not_found) { @@ -538,6 +710,6 @@ namespace winrt::impl } return result; } -} +} // namespace winrt::impl #undef WINRT_IMPL_RETURNADDRESS diff --git a/strings/base_events.h b/strings/base_events.h index 77952474e..e15f769d6 100644 --- a/strings/base_events.h +++ b/strings/base_events.h @@ -16,13 +16,13 @@ WINRT_EXPORT namespace winrt return left.value == right.value; } - struct auto_revoke_t {}; + struct auto_revoke_t + {}; inline constexpr auto_revoke_t auto_revoke{}; - template - struct event_revoker + template struct event_revoker { - using method_type = int32_t(__stdcall impl::abi_t::*)(winrt::event_token); + using method_type = int32_t (__stdcall impl::abi_t::*)(winrt::event_token); event_revoker() noexcept = default; event_revoker(event_revoker const&) = delete; @@ -44,9 +44,7 @@ WINRT_EXPORT namespace winrt template event_revoker(U&& object, method_type method, event_token token) : - m_object(std::forward(object)), - m_method(method), - m_token(token) + m_object(std::forward(object)), m_method(method), m_token(token) {} ~event_revoker() noexcept @@ -68,16 +66,14 @@ WINRT_EXPORT namespace winrt } private: - weak_ref m_object; method_type m_method{}; event_token m_token{}; }; - template - struct factory_event_revoker + template struct factory_event_revoker { - using method_type = int32_t(__stdcall impl::abi_t::*)(winrt::event_token); + using method_type = int32_t (__stdcall impl::abi_t::*)(winrt::event_token); factory_event_revoker() noexcept = default; factory_event_revoker(factory_event_revoker const&) = delete; @@ -99,9 +95,7 @@ WINRT_EXPORT namespace winrt template factory_event_revoker(U&& object, method_type method, event_token token) noexcept : - m_object(std::forward(object)), - m_method(method), - m_token(token) + m_object(std::forward(object)), m_method(method), m_token(token) {} ~factory_event_revoker() noexcept @@ -123,7 +117,6 @@ WINRT_EXPORT namespace winrt } private: - I m_object; method_type m_method{}; event_token m_token{}; @@ -132,8 +125,7 @@ WINRT_EXPORT namespace winrt namespace winrt::impl { - template - struct event_revoker + template struct event_revoker { event_revoker() noexcept = default; event_revoker(event_revoker const&) = delete; @@ -146,9 +138,8 @@ namespace winrt::impl return *this; } - event_revoker(I const& object, event_token token) - : m_object(object) - , m_token(token) + event_revoker(I const& object, event_token token) : + m_object(object), m_token(token) {} operator winrt::event_revoker() && noexcept @@ -193,8 +184,7 @@ namespace winrt::impl event_token m_token{}; }; - template - struct factory_event_revoker + template struct factory_event_revoker { factory_event_revoker() noexcept = default; factory_event_revoker(factory_event_revoker const&) = delete; @@ -206,9 +196,8 @@ namespace winrt::impl factory_event_revoker(std::move(other)).swap(*this); return *this; } - factory_event_revoker(I const& object, event_token token) - : m_object(object) - , m_token(token) + factory_event_revoker(I const& object, event_token token) : + m_object(object), m_token(token) {} operator winrt::factory_event_revoker() && noexcept @@ -248,26 +237,26 @@ namespace winrt::impl ((*reinterpret_cast**>(&object))->*(Method))(m_token); } } + private: I m_object; event_token m_token{}; }; - template - Revoker make_event_revoker(S source, event_token token) + template Revoker make_event_revoker(S source, event_token token) { return { static_cast(*source), token }; } - template - struct event_array + template struct event_array { using value_type = T; using reference = value_type&; using pointer = value_type*; using iterator = value_type*; - explicit event_array(uint32_t const count) noexcept : m_size(count) + explicit event_array(uint32_t const count) noexcept : + m_size(count) { std::uninitialized_fill_n(data(), count, value_type()); } @@ -293,7 +282,7 @@ namespace winrt::impl reference back() noexcept { WINRT_ASSERT(m_size > 0); - return*(data() + m_size - 1); + return *(data() + m_size - 1); } iterator begin() noexcept @@ -317,7 +306,6 @@ namespace winrt::impl } private: - pointer data() noexcept { return reinterpret_cast(this + 1); @@ -327,14 +315,13 @@ namespace winrt::impl uint32_t m_size{ 0 }; }; - template - com_ptr> make_event_array(uint32_t const capacity) + template com_ptr> make_event_array(uint32_t const capacity) { - void* raw = ::operator new(sizeof(event_array) + (sizeof(T)* capacity)); + void* raw = ::operator new(sizeof(event_array) + (sizeof(T) * capacity)); #ifdef _MSC_VER -#pragma warning(suppress: 6386) +#pragma warning(suppress : 6386) #endif - return { new(raw) event_array(capacity), take_ownership_from_abi }; + return { new (raw) event_array(capacity), take_ownership_from_abi }; } WINRT_IMPL_NOINLINE inline bool report_failed_invoke() @@ -352,8 +339,7 @@ namespace winrt::impl return true; } - template - bool invoke(Delegate const& delegate, Arg const&... args) noexcept + template bool invoke(Delegate const& delegate, Arg const&... args) noexcept { try { @@ -366,18 +352,17 @@ namespace winrt::impl return true; } -} +} // namespace winrt::impl WINRT_EXPORT namespace winrt { - template - struct event + template struct event { using delegate_type = Delegate; event() = default; event(event const&) = delete; - event& operator =(event const&) = delete; + event& operator=(event const&) = delete; explicit operator bool() const noexcept { @@ -464,8 +449,7 @@ WINRT_EXPORT namespace winrt } } - template - void operator()(Arg const&... args) + template void operator()(Arg const&... args) { delegate_array temp_targets; @@ -487,7 +471,6 @@ WINRT_EXPORT namespace winrt } private: - WINRT_IMPL_NOINLINE event_token add_agile(delegate_type delegate) { event_token token{}; diff --git a/strings/base_fast_forward.h b/strings/base_fast_forward.h index 88d99469a..e27f6d85d 100644 --- a/strings/base_fast_forward.h +++ b/strings/base_fast_forward.h @@ -21,15 +21,14 @@ static_assert(WINRT_FAST_ABI_SIZE >= %); namespace winrt::impl { // Thunk definitions are in arch-specific assembly sources -% - struct fast_abi_forwarder + % struct fast_abi_forwarder { struct guid { uint32_t Data1; uint16_t Data2; uint16_t Data3; - uint8_t Data4[8]; + uint8_t Data4[8]; inline bool operator!=(guid const& right) const noexcept { return memcmp(this, &right, sizeof(guid)); @@ -106,33 +105,25 @@ namespace winrt::impl return self->m_owner->GetTrustLevel(level); } - static inline void* const s_vtable[] = - { - QueryInterface, - AddRef, - Release, - GetIids, - GetRuntimeClassName, - GetTrustLevel, -% }; + static inline void* const s_vtable[] = { QueryInterface, AddRef, Release, GetIids, + GetRuntimeClassName, GetTrustLevel, % }; }; // Enforce assumptions made by thunk asm code static_assert(offsetof(fast_abi_forwarder, m_vfptr) == 0); static_assert(offsetof(fast_abi_forwarder, m_owner) == sizeof(fast_abi_forwarder::m_vfptr)); static_assert(offsetof(fast_abi_forwarder, m_offset) == sizeof(fast_abi_forwarder::m_vfptr) + sizeof(fast_abi_forwarder::m_owner)); -} +} // namespace winrt::impl namespace winrt { - template - auto make_fast_abi_forwarder(void* owner, TGuid const& guid, size_t offset) + template auto make_fast_abi_forwarder(void* owner, TGuid const& guid, size_t offset) { using ff_guid = impl::fast_abi_forwarder::guid; static_assert(sizeof(ff_guid) == sizeof(TGuid)); return new impl::fast_abi_forwarder(owner, *reinterpret_cast(&guid), offset); } -} +} // namespace winrt #undef WINRT_IMPL_STRING #undef WINRT_IMPL_STRING_1 diff --git a/strings/base_foundation.h b/strings/base_foundation.h index ea8881edc..df31538ef 100644 --- a/strings/base_foundation.h +++ b/strings/base_foundation.h @@ -8,14 +8,14 @@ WINRT_EXPORT namespace winrt::Windows::Foundation Point() noexcept = default; - constexpr Point(float X, float Y) noexcept - : X(X), Y(Y) + constexpr Point(float X, float Y) noexcept : + X(X), Y(Y) {} #ifdef WINRT_IMPL_NUMERICS - constexpr Point(Numerics::float2 const& value) noexcept - : X(value.x), Y(value.y) + constexpr Point(Numerics::float2 const& value) noexcept : + X(value.x), Y(value.y) {} operator Numerics::float2() const noexcept @@ -43,14 +43,14 @@ WINRT_EXPORT namespace winrt::Windows::Foundation Size() noexcept = default; - constexpr Size(float Width, float Height) noexcept - : Width(Width), Height(Height) + constexpr Size(float Width, float Height) noexcept : + Width(Width), Height(Height) {} #ifdef WINRT_IMPL_NUMERICS - constexpr Size(Numerics::float2 const& value) noexcept - : Width(value.x), Height(value.y) + constexpr Size(Numerics::float2 const& value) noexcept : + Width(value.x), Height(value.y) {} operator Numerics::float2() const noexcept @@ -84,7 +84,7 @@ WINRT_EXPORT namespace winrt::Windows::Foundation X(X), Y(Y), Width(Width), Height(Height) {} - constexpr Rect(Point const& point, Size const& size) noexcept : + constexpr Rect(Point const& point, Size const& size) noexcept : X(point.X), Y(point.Y), Width(size.Width), Height(size.Height) {} }; @@ -115,7 +115,7 @@ namespace winrt::impl { using type = struct_category; }; - + template <> struct category { using type = struct_category; @@ -123,13 +123,20 @@ namespace winrt::impl #ifdef WINRT_IMPL_NUMERICS - template <> inline constexpr auto& name_v = L"Windows.Foundation.Numerics.Vector2"; - template <> inline constexpr auto& name_v = L"Windows.Foundation.Numerics.Vector3"; - template <> inline constexpr auto& name_v = L"Windows.Foundation.Numerics.Vector4"; - template <> inline constexpr auto& name_v = L"Windows.Foundation.Numerics.Matrix3x2"; - template <> inline constexpr auto& name_v = L"Windows.Foundation.Numerics.Matrix4x4"; - template <> inline constexpr auto& name_v = L"Windows.Foundation.Numerics.Quaternion"; - template <> inline constexpr auto& name_v = L"Windows.Foundation.Numerics.Plane"; + template <> + inline constexpr auto& name_v = L"Windows.Foundation.Numerics.Vector2"; + template <> + inline constexpr auto& name_v = L"Windows.Foundation.Numerics.Vector3"; + template <> + inline constexpr auto& name_v = L"Windows.Foundation.Numerics.Vector4"; + template <> + inline constexpr auto& name_v = L"Windows.Foundation.Numerics.Matrix3x2"; + template <> + inline constexpr auto& name_v = L"Windows.Foundation.Numerics.Matrix4x4"; + template <> + inline constexpr auto& name_v = L"Windows.Foundation.Numerics.Quaternion"; + template <> + inline constexpr auto& name_v = L"Windows.Foundation.Numerics.Plane"; template <> struct category { @@ -153,12 +160,8 @@ namespace winrt::impl template <> struct category { - using type = struct_category< - float, float, float, float, - float, float, float, float, - float, float, float, float, - float, float, float, float - >; + using type = + struct_category; }; template <> struct category @@ -172,4 +175,4 @@ namespace winrt::impl }; #endif -} +} // namespace winrt::impl diff --git a/strings/base_handle.h b/strings/base_handle.h index 7a65af7b3..ae141ac23 100644 --- a/strings/base_handle.h +++ b/strings/base_handle.h @@ -1,20 +1,19 @@ WINRT_EXPORT namespace winrt { - template - struct handle_type + template struct handle_type { using type = typename T::type; handle_type() noexcept = default; - explicit handle_type(type value) noexcept : m_value(value) - { - } + explicit handle_type(type value) noexcept : + m_value(value) + {} - handle_type(handle_type&& other) noexcept : m_value(other.detach()) - { - } + handle_type(handle_type&& other) noexcept : + m_value(other.detach()) + {} handle_type& operator=(handle_type&& other) noexcept { @@ -23,7 +22,7 @@ WINRT_EXPORT namespace winrt attach(other.detach()); } - return*this; + return *this; } ~handle_type() noexcept @@ -75,7 +74,6 @@ WINRT_EXPORT namespace winrt } private: - type m_value = T::invalid(); }; diff --git a/strings/base_identity.h b/strings/base_identity.h index 0f4a163b6..80207d856 100644 --- a/strings/base_identity.h +++ b/strings/base_identity.h @@ -1,17 +1,14 @@ WINRT_EXPORT namespace winrt { - template - using default_interface = typename impl::default_interface::type; + template using default_interface = typename impl::default_interface::type; - template - constexpr guid const& guid_of() noexcept + template constexpr guid const& guid_of() noexcept { return impl::guid_v>; } - template - bool is_guid_of(guid const& id) noexcept + template bool is_guid_of(guid const& id) noexcept { return ((id == guid_of()) || ...); } @@ -25,20 +22,17 @@ namespace winrt::impl return { value[Index]... }; } - template - constexpr auto to_array(std::array const& value) noexcept + template constexpr auto to_array(std::array const& value) noexcept { return value; } - template - constexpr auto to_array(char const(&value)[Size]) noexcept + template constexpr auto to_array(char const (&value)[Size]) noexcept { return to_array(value, std::make_index_sequence()); } - template - constexpr auto to_array(wchar_t const(&value)[Size]) noexcept + template constexpr auto to_array(wchar_t const (&value)[Size]) noexcept { return to_array(value, std::make_index_sequence()); } @@ -60,13 +54,13 @@ namespace winrt::impl } template - constexpr auto concat(std::array const& left, T const(&right)[RightSize]) noexcept + constexpr auto concat(std::array const& left, T const (&right)[RightSize]) noexcept { return concat(left, to_array(right)); } template - constexpr auto concat(T const(&left)[LeftSize], std::array const& right) noexcept + constexpr auto concat(T const (&left)[LeftSize], std::array const& right) noexcept { return concat(to_array(left), right); } @@ -74,17 +68,16 @@ namespace winrt::impl template constexpr auto concat(std::array const& left, T const right) noexcept { - return concat(left, std::array{right}); + return concat(left, std::array{ right }); } template constexpr auto concat(T const left, std::array const& right) noexcept { - return concat(std::array{left}, right); + return concat(std::array{ left }, right); } - template - constexpr auto combine(First const& first, Rest const&... rest) noexcept + template constexpr auto combine(First const& first, Rest const&... rest) noexcept { if constexpr (sizeof...(rest) == 0) { @@ -97,7 +90,11 @@ namespace winrt::impl } template - constexpr std::array zconcat_base(std::array const& left, std::array const& right, std::index_sequence const, std::index_sequence const) noexcept + constexpr std::array zconcat_base( + std::array const& left, + std::array const& right, + std::index_sequence const, + std::index_sequence const) noexcept { return { left[LI]..., right[RI]..., T{} }; } @@ -109,19 +106,17 @@ namespace winrt::impl } template - constexpr std::array to_zarray_base(T const(&value)[S], std::index_sequence const) noexcept + constexpr std::array to_zarray_base(T const (&value)[S], std::index_sequence const) noexcept { return { value[I]... }; } - template - constexpr auto to_zarray(T const(&value)[S]) noexcept + template constexpr auto to_zarray(T const (&value)[S]) noexcept { return to_zarray_base(value, std::make_index_sequence()); } - template - constexpr auto to_zarray(std::array const& value) noexcept + template constexpr auto to_zarray(std::array const& value) noexcept { return value; } @@ -141,7 +136,10 @@ namespace winrt::impl constexpr std::array to_array(uint32_t value) noexcept { - return { static_cast(value & 0x000000ff), static_cast((value & 0x0000ff00) >> 8), static_cast((value & 0x00ff0000) >> 16), static_cast((value & 0xff000000) >> 24) }; + return { static_cast(value & 0x000000ff), + static_cast((value & 0x0000ff00) >> 8), + static_cast((value & 0x00ff0000) >> 16), + static_cast((value & 0xff000000) >> 24) }; } constexpr std::array to_array(uint16_t value) noexcept @@ -151,55 +149,63 @@ namespace winrt::impl constexpr auto to_array(guid const& value) noexcept { - return combine(to_array(value.Data1), to_array(value.Data2), to_array(value.Data3), - std::array{ value.Data4[0], value.Data4[1], value.Data4[2], value.Data4[3], value.Data4[4], value.Data4[5], value.Data4[6], value.Data4[7] }); + return combine( + to_array(value.Data1), + to_array(value.Data2), + to_array(value.Data3), + std::array{ value.Data4[0], + value.Data4[1], + value.Data4[2], + value.Data4[3], + value.Data4[4], + value.Data4[5], + value.Data4[6], + value.Data4[7] }); } - template - constexpr T to_hex_digit(uint8_t value) noexcept + template constexpr T to_hex_digit(uint8_t value) noexcept { value &= 0xF; return value < 10 ? static_cast('0') + value : static_cast('a') + (value - 10); } - template - constexpr std::array uint8_to_hex(uint8_t const value) noexcept + template constexpr std::array uint8_to_hex(uint8_t const value) noexcept { return { to_hex_digit(value >> 4), to_hex_digit(value & 0xF) }; } - template - constexpr auto uint16_to_hex(uint16_t value) noexcept + template constexpr auto uint16_to_hex(uint16_t value) noexcept { return combine(uint8_to_hex(static_cast(value >> 8)), uint8_to_hex(value & 0xFF)); } - template - constexpr auto uint32_to_hex(uint32_t const value) noexcept + template constexpr auto uint32_to_hex(uint32_t const value) noexcept { return combine(uint16_to_hex(value >> 16), uint16_to_hex(value & 0xFFFF)); } - template - constexpr auto to_array(guid const& value) noexcept + template constexpr auto to_array(guid const& value) noexcept { - return combine - ( - std::array{'{'}, - uint32_to_hex(value.Data1), std::array{'-'}, - uint16_to_hex(value.Data2), std::array{'-'}, - uint16_to_hex(value.Data3), std::array{'-'}, - uint16_to_hex(value.Data4[0] << 8 | value.Data4[1]), std::array{'-'}, + return combine( + std::array{ '{' }, + uint32_to_hex(value.Data1), + std::array{ '-' }, + uint16_to_hex(value.Data2), + std::array{ '-' }, + uint16_to_hex(value.Data3), + std::array{ '-' }, + uint16_to_hex(value.Data4[0] << 8 | value.Data4[1]), + std::array{ '-' }, uint16_to_hex(value.Data4[2] << 8 | value.Data4[3]), uint16_to_hex(value.Data4[4] << 8 | value.Data4[5]), uint16_to_hex(value.Data4[6] << 8 | value.Data4[7]), - std::array{'}'} - ); + std::array{ '}' }); } constexpr uint32_t to_guid(uint8_t a, uint8_t b, uint8_t c, uint8_t d) noexcept { - return (static_cast(d) << 24) | (static_cast(c) << 16) | (static_cast(b) << 8) | static_cast(a); + return (static_cast(d) << 24) | (static_cast(c) << 16) | (static_cast(b) << 8) | + static_cast(a); } constexpr uint16_t to_guid(uint8_t a, uint8_t b) noexcept @@ -207,16 +213,12 @@ namespace winrt::impl return (static_cast(b) << 8) | static_cast(a); } - template - constexpr guid to_guid(std::array const& arr) noexcept + template constexpr guid to_guid(std::array const& arr) noexcept { - return - { - to_guid(arr[0], arr[1], arr[2], arr[3]), - to_guid(arr[4], arr[5]), - to_guid(arr[6], arr[7]), - { arr[8], arr[9], arr[10], arr[11], arr[12], arr[13], arr[14], arr[15] } - }; + return { to_guid(arr[0], arr[1], arr[2], arr[3]), + to_guid(arr[4], arr[5]), + to_guid(arr[6], arr[7]), + { arr[8], arr[9], arr[10], arr[11], arr[12], arr[13], arr[14], arr[15] } }; } constexpr uint32_t endian_swap(uint32_t value) noexcept @@ -252,7 +254,7 @@ namespace winrt::impl constexpr auto sha1_rotl(uint8_t bits, uint32_t word) noexcept { - return (word << bits) | (word >> (32 - bits)); + return (word << bits) | (word >> (32 - bits)); } constexpr auto sha_ch(uint32_t x, uint32_t y, uint32_t z) noexcept @@ -270,7 +272,8 @@ namespace winrt::impl return (x & y) ^ (x & z) ^ (y & z); } - constexpr std::array process_msg_block(uint8_t const* input, size_t start_pos, std::array const& intermediate_hash) noexcept + constexpr std::array process_msg_block( + uint8_t const* input, size_t start_pos, std::array const& intermediate_hash) noexcept { uint32_t const K[4] = { 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6 }; std::array W = {}; @@ -337,32 +340,37 @@ namespace winrt::impl A = temp; } - return { intermediate_hash[0] + A, intermediate_hash[1] + B, intermediate_hash[2] + C, intermediate_hash[3] + D, intermediate_hash[4] + E }; + return { intermediate_hash[0] + A, + intermediate_hash[1] + B, + intermediate_hash[2] + C, + intermediate_hash[3] + D, + intermediate_hash[4] + E }; } template - constexpr std::array process_msg_block(std::array const& input, size_t start_pos, std::array const& intermediate_hash) noexcept + constexpr std::array process_msg_block( + std::array const& input, size_t start_pos, std::array const& intermediate_hash) noexcept { return process_msg_block(input.data(), start_pos, intermediate_hash); } constexpr std::array size_to_bytes(size_t size) noexcept { - return - { - static_cast((size & 0xff00000000000000) >> 56), - static_cast((size & 0x00ff000000000000) >> 48), - static_cast((size & 0x0000ff0000000000) >> 40), - static_cast((size & 0x000000ff00000000) >> 32), - static_cast((size & 0x00000000ff000000) >> 24), - static_cast((size & 0x0000000000ff0000) >> 16), - static_cast((size & 0x000000000000ff00) >> 8), - static_cast((size & 0x00000000000000ff) >> 0) - }; + return { static_cast((size & 0xff00000000000000) >> 56), + static_cast((size & 0x00ff000000000000) >> 48), + static_cast((size & 0x0000ff0000000000) >> 40), + static_cast((size & 0x000000ff00000000) >> 32), + static_cast((size & 0x00000000ff000000) >> 24), + static_cast((size & 0x0000000000ff0000) >> 16), + static_cast((size & 0x000000000000ff00) >> 8), + static_cast((size & 0x00000000000000ff) >> 0) }; } template - constexpr std::array make_remaining([[maybe_unused]] std::array const& input, [[maybe_unused]] size_t start_pos, std::index_sequence) noexcept + constexpr std::array make_remaining( + [[maybe_unused]] std::array const& input, + [[maybe_unused]] size_t start_pos, + std::index_sequence) noexcept { return { input[Index + start_pos]..., 0x80 }; } @@ -387,7 +395,8 @@ namespace winrt::impl } template - constexpr std::array finalize_remaining_buffer(std::array const& input, std::array const& intermediate_hash) noexcept + constexpr std::array finalize_remaining_buffer( + std::array const& input, std::array const& intermediate_hash) noexcept { if constexpr (Size == 64) { @@ -410,8 +419,7 @@ namespace winrt::impl return get_result(intermediate_hash, std::make_index_sequence<20>{}); } - template - constexpr auto calculate_sha1(std::array const& input) noexcept + template constexpr auto calculate_sha1(std::array const& input) noexcept { std::array intermediate_hash{ 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0 }; size_t i = 0; @@ -426,10 +434,9 @@ namespace winrt::impl return get_result(intermediate_hash); } - template - constexpr guid generate_guid(std::array const& value) noexcept + template constexpr guid generate_guid(std::array const& value) noexcept { - guid namespace_guid = { 0xd57af411, 0x737b, 0xc042,{ 0xab, 0xae, 0x87, 0x8b, 0x1e, 0x16, 0xad, 0xee } }; + guid namespace_guid = { 0xd57af411, 0x737b, 0xc042, { 0xab, 0xae, 0x87, 0x8b, 0x1e, 0x16, 0xad, 0xee } }; auto buffer = combine(to_array(namespace_guid), char_to_byte_array(value, std::make_index_sequence())); auto hash = calculate_sha1(buffer); @@ -438,39 +445,29 @@ namespace winrt::impl return set_named_guid_fields(little_endian_guid); } - template - struct arg_collection + template struct arg_collection { constexpr static auto data{ combine(to_array(signature::data), ";", arg_collection::data) }; }; - template - struct arg_collection + template struct arg_collection { constexpr static auto data{ to_array(signature::data) }; }; - template - struct pinterface_guid + template struct pinterface_guid { #ifdef _MSC_VER -#pragma warning(suppress: 4307) +#pragma warning(suppress : 4307) #endif static constexpr guid value{ generate_guid(signature::data) }; }; template #ifdef _MSC_VER -#pragma warning(suppress: 4307) +#pragma warning(suppress : 4307) #endif - inline constexpr auto name_v - { - combine - ( - to_array(guid_of()), - std::array{ L'\0' } - ) - }; + inline constexpr auto name_v{ combine(to_array(guid_of()), std::array{ L'\0' }) }; constexpr size_t to_utf8_size(wchar_t const value) noexcept { @@ -508,8 +505,7 @@ namespace winrt::impl return 3; } - template - constexpr size_t to_utf8_size() noexcept + template constexpr size_t to_utf8_size() noexcept { auto input = to_array(name_v); size_t length = 0; @@ -522,8 +518,7 @@ namespace winrt::impl return length; } - template - constexpr auto to_utf8() noexcept + template constexpr auto to_utf8() noexcept { auto input = to_array(name_v); std::array()> output{}; @@ -537,11 +532,9 @@ namespace winrt::impl return output; } - template - constexpr guid generic_guid_v{}; + template constexpr guid generic_guid_v{}; - template - constexpr auto& basic_signature_v = ""; + template constexpr auto& basic_signature_v = ""; template <> inline constexpr auto& basic_signature_v = "b1"; template <> inline constexpr auto& basic_signature_v = "i1"; @@ -557,7 +550,8 @@ namespace winrt::impl template <> inline constexpr auto& basic_signature_v = "c2"; template <> inline constexpr auto& basic_signature_v = "g16"; template <> inline constexpr auto& basic_signature_v = "string"; - template <> inline constexpr auto& basic_signature_v = "cinterface(IInspectable)"; + template <> + inline constexpr auto& basic_signature_v = "cinterface(IInspectable)"; template <> inline constexpr auto& name_v = L"Boolean"; template <> inline constexpr auto& name_v = L"Int8"; @@ -580,85 +574,130 @@ namespace winrt::impl template <> inline constexpr auto& name_v = L"Windows.Foundation.DateTime"; template <> inline constexpr auto& name_v = L"IAgileObject"; - template <> struct category { using type = basic_category; }; - template <> struct category { using type = basic_category; }; - template <> struct category { using type = basic_category; }; - template <> struct category { using type = basic_category; }; - template <> struct category { using type = basic_category; }; - template <> struct category { using type = basic_category; }; - template <> struct category { using type = basic_category; }; - template <> struct category { using type = basic_category; }; - template <> struct category { using type = basic_category; }; - template <> struct category { using type = basic_category; }; - template <> struct category { using type = basic_category; }; - template <> struct category { using type = basic_category; }; - template <> struct category { using type = basic_category; }; - template <> struct category { using type = struct_category; }; - template <> struct category { using type = struct_category; }; - template <> struct category { using type = basic_category; }; - template <> struct category { using type = struct_category; }; - template <> struct category { using type = struct_category; }; + template <> struct category + { + using type = basic_category; + }; + template <> struct category + { + using type = basic_category; + }; + template <> struct category + { + using type = basic_category; + }; + template <> struct category + { + using type = basic_category; + }; + template <> struct category + { + using type = basic_category; + }; + template <> struct category + { + using type = basic_category; + }; + template <> struct category + { + using type = basic_category; + }; + template <> struct category + { + using type = basic_category; + }; + template <> struct category + { + using type = basic_category; + }; + template <> struct category + { + using type = basic_category; + }; + template <> struct category + { + using type = basic_category; + }; + template <> struct category + { + using type = basic_category; + }; + template <> struct category + { + using type = basic_category; + }; + template <> struct category + { + using type = struct_category; + }; + template <> struct category + { + using type = struct_category; + }; + template <> struct category + { + using type = basic_category; + }; + template <> struct category + { + using type = struct_category; + }; + template <> struct category + { + using type = struct_category; + }; - template - struct category_signature + template struct category_signature { constexpr static auto data{ to_array(basic_signature_v) }; }; - template - struct category_signature + template struct category_signature { using enum_type = std::underlying_type_t; constexpr static auto data{ combine("enum(", to_utf8(), ";", signature::data, ")") }; }; - template - struct category_signature, T> + template struct category_signature, T> { constexpr static auto data{ combine("struct(", to_utf8(), ";", arg_collection::data, ")") }; }; - template - struct category_signature + template struct category_signature { constexpr static auto data{ combine("rc(", to_utf8(), ";", signature>::data, ")") }; }; - template - struct category_signature, T> + template struct category_signature, T> { - constexpr static auto data{ combine("pinterface(", to_array(generic_guid_v), ";", arg_collection::data, ")") }; + constexpr static auto data{ combine( + "pinterface(", to_array(generic_guid_v), ";", arg_collection::data, ")") }; }; - template - struct category_signature + template struct category_signature { constexpr static auto data{ to_array(guid_of()) }; }; - template - struct category_signature + template struct category_signature { constexpr static auto data{ combine("delegate(", to_array(guid_of()), ")") }; }; - template - constexpr std::wstring_view to_wstring_view(std::array const& value) noexcept + template constexpr std::wstring_view to_wstring_view(std::array const& value) noexcept { return { value.data(), Size - 1 }; } - template - constexpr std::wstring_view to_wstring_view(wchar_t const (&value)[Size]) noexcept + template constexpr std::wstring_view to_wstring_view(wchar_t const (&value)[Size]) noexcept { return { value, Size - 1 }; } -} +} // namespace winrt::impl WINRT_EXPORT namespace winrt { - template - constexpr auto name_of() noexcept + template constexpr auto name_of() noexcept { return impl::to_wstring_view(impl::name_v); } diff --git a/strings/base_implements.h b/strings/base_implements.h index 0847f5019..8ae6f854d 100644 --- a/strings/base_implements.h +++ b/strings/base_implements.h @@ -12,88 +12,87 @@ namespace winrt::impl { marker() = delete; }; -} +} // namespace winrt::impl WINRT_EXPORT namespace winrt { - struct non_agile : impl::marker {}; - struct no_weak_ref : impl::marker {}; - struct composing : impl::marker {}; - struct composable : impl::marker {}; - struct no_module_lock : impl::marker {}; - struct static_lifetime : impl::marker {}; + struct non_agile : impl::marker + {}; + struct no_weak_ref : impl::marker + {}; + struct composing : impl::marker + {}; + struct composable : impl::marker + {}; + struct no_module_lock : impl::marker + {}; + struct static_lifetime : impl::marker + {}; - template - struct cloaked : Interface {}; + template struct cloaked : Interface + {}; - template - struct implements; + template struct implements; } namespace winrt::impl { - template - using tuple_cat_t = decltype(std::tuple_cat(std::declval()...)); + template using tuple_cat_t = decltype(std::tuple_cat(std::declval()...)); - template