https://devblogs.microsoft.com/cppblog/how-we-used-cpp20-to-eliminate-an-entire-class-of-runtime-bugs/ Skip to main content [RE1Mu3b] Microsoft C++ Team Blog C++ Team Blog C++ Team Blog * Home * DevBlogs * Developer + Visual Studio + Visual Studio Code + Visual Studio for Mac + DevOps + Developer support + CSE Developer + Engineering@Microsoft + Azure SDK + IoT + Command Line + Perf and Diagnostics + Dr. International + Notification Hubs + Math in Office * Technology + DirectX + PIX + SurfaceDuo + Startups + Sustainable Engineering + Windows AI Platform * Languages + C++ + C# + F# + Visual Basic + TypeScript + PowerShell Community + PowerShell Team + Python + Q# + JavaScript + Java + Java Blog in Chinese * .NET + .NET + .NET MAUI + Blazor + ASP.NET + NuGet + Xamarin * Platform Development + #ifdef Windows + Apps for Windows + Azure Depth Platform + Azure Government + Bing Dev Center + Microsoft Edge Dev + Microsoft Azure + Microsoft 365 Developer + Old New Thing + Windows MIDI and Music dev + Windows Search Platform * Data Development + Azure Cosmos DB + Azure Data Studio + Azure SQL + OData + Revolutions R + SQL Server Data Tools * More [ ] Search Search Cancel How we used C++20 to eliminate an entire class of runtime bugs [png] Cameron January 13th, 20222 C++20 is here and has been supported in MSVC since 16.11, but today's post is not about how you can use it, but rather how we used it to effectively eliminate an entire class of runtime bugs by hoisting a check into compile-time. Let's get right into it! Humble beginnings In compiler design one of the very first things you need is a way to convey to the programmer that their source code has an error or warn them if their code might not behave as expected. In MSVC our error infrastructure looks something like this: enum ErrorNumber { C2000, C2001, C2002, ... }; void error(ErrorNumber, ...); The way error works is that each ErrorNumber has a corresponding string entry which represents the text we want to display to the user. These text strings can be anything from: C2056 -> "illegal expression" to: C7627 -> "'%1$T': is not a valid template argument for '%2$S'", but what are these %1$T and %2$S things? These are some of the compiler's format-specifiers to display certain types of structures in the compiler to the user in a readable way. The double-edged sword of format-specifiers Format-specifiers provide a lot of flexibility and power to us as compiler developers. Format-specifiers can more clearly illustrate why a diagnostic was issued and provide the user with more context into the problem. The problem with format-specifiers is that they are not type checked in the call to error, so if we happen to get an argument type wrong or did not pass an argument at all it will almost certainly end up in a runtime error later for the user. Other problems arise when you want to refactor a diagnostic message into something clearer, but to do that you need to query every caller of that diagnostic message and ensure that the refactor agrees with the arguments being passed to error. We have three high-level goals when designing a system that can check our format-specifiers: 1. Validate that argument types passed into our diagnostic APIs at compile-time so authoring a mistake is caught as early as possible. 2. Minimize changes made to callers of diagnostic APIs. This is to ensure well-formed calls retain their original structure (no disruption to future calls as well). 3. Minimize changes made to implementation details of the callee. We should not change the behavior of the diagnostic routines at runtime. There are, of course, some solutions introduced with later C++ standards which could aid in trying to remedy this problem. For one, once variadic templates were introduced into the language we could have tried some template metaprogramming to try and type check the calls to error, but that would require a separate lookup table since constexpr and templates were limited in what they could do. C++14/17 both introduced a lot of improvements to constexpr and non-type template arguments. Something like this would work great: constexpr ErrorToMessage error_to_message[] = { { C2000, fetch_message(C2000) }, { C2001, fetch_message(C2001) }, ... }; template constexpr bool are_arguments_valid(ErrorNumber n) { /* 1. fetch message 2. parse specifiers 3. check each specifier against the parameter pack Ts... */ return result; } So we finally had the tools to try and check the format-specifiers at compile-time. But there was still a problem: we still did not have a way to silently check all the existing calls to error meaning that we would have to add an extra layer of indirection between the call sites of error to ensure that the ErrorNumber could fetch the string at compile-time and check the argument types against it. In C++17 this will not work: template void error(ErrorNumber n, Ts&&... ts) { assert(are_arguments_valid(n)); /* do error stuff */ } And we cannot make error itself constexpr because it does a lot of constexpr-unfriendly things. Additionally, adjusting all the call sites to something like: error(a, b, c) so that we can check the error number as a compile-time expression is unsavory and would cause a lot of unnecessary churn in the compiler. C++20 to the rescue! C++20 introduced an important tool for us to enable compile-time checking, consteval. consteval is in the family of constexpr but the language guarantees that a function adorned with consteval will be evaluated at compile-time. A well-known library by the name of fmtlib introduced compile-time checking as part of the core API and it did so without changing any call sites, assuming the call site was well-formed according to the library. Imagine a simplified version of fmt: template void fmt(const char* format, T); int main() { fmt("valid", 10); // compiles fmt("oops", 10); // compiles? fmt("valid", "foo"); // compiles? } Where the intent is that format should always be equal to "valid" and T should always be an int. The code in main is ill-formed according to the library in this case, but nothing validates that at compile-time. fmtlib accomplished compile-time checking using a little trick with user-defined types: #include #include // Exposition only #define FAIL_CONSTEVAL throw template struct Checker { consteval Checker(const char* fmt) { if (fmt != std::string_view{ "valid" }) // #1 FAIL_CONSTEVAL; // T must be an int if (!std::is_same_v) // #2 FAIL_CONSTEVAL; } }; template void fmt(std::type_identity_t> checked, T); int main() { fmt("valid", 10); // compiles fmt("oops", 10); // fails at #1 fmt("valid", "foo"); // fails at #2 } Note: you need to use the std::type_identity_t trick to keep checked from participating in type deduction. We only want it to deduce the rest of the arguments and use their deduced types as template arguments to Checker. You can fiddle with the example for yourself using Compiler Explorer. Tying it all together The code above is powerful in that it gives us a tool which can perform additional safety checking without changing any caller which is well-formed. Using the technique above we applied compile-time checking to all our error, warning, and note message routines. The code used in the compiler is nearly identical to the fmt above except that the argument to Checker is an ErrorNumber. In total we identified ~120 instances where we were either passing the incorrect number of arguments to a diagnostic API or where we passed the wrong type for a particular format-specifier. Over the years we have received bugs regarding strange compiler behavior when emitting a diagnostic or a straight-up ICE (Internal Compiler Error) because the format-specifiers were looking for arguments which were incorrect or did not exist. Using C++20 we have largely eliminated possibility of such bugs happening in the future and while offering the ability for us to safely refactor diagnostic messages, made possible by one little keyword: consteval. Closing As always, we welcome your feedback. Feel free to send any comments through e-mail at visualcpp@microsoft.com or through Twitter @visualc . Also, feel free to follow me on Twitter @starfreakclone. If you encounter other problems with MSVC in VS 2019/2022 please let us know via the Report a Problem option, either from the installer or the Visual Studio IDE itself. For suggestions or bug reports, let us know through DevComm. [png] Cameron DaCamara Follow Posted in C++Tagged C++ C++20 compiler constexpr safety Read next Visual Studio Code C++ December 2021 Update: clang-tidy The latest insiders release of the C++ extension is here, bringing clang-tidy support to VS Code! Clang-tidy is a clang-based C++ linter tool that detects common errors ... [png] Julia Reid December 14, 2021 3 comments The /fp:contract flag and changes to FP modes in VS2022 The /fp:contract flag and changes to FP modes in VS2022 In this blog we will cover a new feature we have added to the MSVC version 17.0 compiler in VS2022 that impacts ... [png] Gautham Beeraka (Intel Americas Inc) December 14, 2021 0 comment 2 comments Leave a commentCancel reply Log in to join the discussion. * [png] Roman Dremov January 14, 2022 2:50 pm collapse this comment If you are set on C++20, I suggest using concepts to constrain template types. Much cleaner than other type tricks and traits. Also, I am surprised you uncovered 120 format errors in your error reporting code. Did you not have a negative test for every error? This is a common practice, at least in my company. Log in to Reply + [png] Cameron DaCamaraMicrosoft employee January 14, 2022 6:09 pm collapse this comment Hi Roman, Yes, we use concepts in the compiler religiously. Concepts help you better reason about the semantics of the types being passed into a function, but in the case of our diagnostic message APIs a concept doesn't make a lot of sense because the semantics of how to interact with the type is dictated by the format string itself, so you can't reasonably create a concept to constrain the parameter pack. The compile-time format-specifier checking constrains them for you. > Did you not have a negative test for every error? We do. We have around 250,000 tests which run on each commit and a significant portion of them are negative tests looking for a specific error. Given the age of the compiler though, it is hard to say that we test every possible code path to an individual call to `error`-because there may be multiple places where the same error, warning, or note are emitted. The solution presented in the article helps us reason about every code path no matter how the compiler gets there. Log in to Reply Relevant Links Getting Started with C++ in VS Bring Your Existing C++ Code to VS C++ Code Editing & Navigation C++ Unit Testing C++ Debugging & Diagnostics Collaborating with Your Team in VS C++ Windows Development C++ Linux Development C++ Android & iOS Development C++ Game Development Topics C++ Announcement CMake New Feature Linux Visual Studio Code Diagnostics General C++ Series performance Vcpkg OpenFolder Writing Code Experimental New User Documentation Survey faster Clang IoT Containers Coroutine VC++ Migration Documentation Migration DevLab C++ Q&A Series Featured Trip Report embedded Mobile Archive January 2022 December 2021 November 2021 October 2021 September 2021 August 2021 July 2021 June 2021 May 2021 April 2021 March 2021 February 2021 January 2021 December 2020 November 2020 October 2020 September 2020 August 2020 July 2020 June 2020 May 2020 April 2020 March 2020 February 2020 January 2020 December 2019 November 2019 October 2019 September 2019 August 2019 July 2019 June 2019 May 2019 April 2019 March 2019 February 2019 January 2019 December 2018 November 2018 October 2018 September 2018 August 2018 July 2018 June 2018 May 2018 April 2018 March 2018 February 2018 January 2018 December 2017 November 2017 October 2017 September 2017 August 2017 July 2017 June 2017 May 2017 April 2017 March 2017 February 2017 January 2017 December 2016 November 2016 October 2016 September 2016 August 2016 July 2016 June 2016 May 2016 April 2016 March 2016 February 2016 January 2016 December 2015 November 2015 October 2015 September 2015 August 2015 July 2015 June 2015 May 2015 April 2015 March 2015 February 2015 January 2015 December 2014 November 2014 October 2014 September 2014 August 2014 July 2014 June 2014 May 2014 April 2014 March 2014 February 2014 January 2014 December 2013 November 2013 October 2013 September 2013 August 2013 July 2013 June 2013 May 2013 April 2013 March 2013 February 2013 January 2013 December 2012 November 2012 October 2012 September 2012 August 2012 July 2012 June 2012 May 2012 April 2012 March 2012 February 2012 January 2012 December 2011 November 2011 October 2011 September 2011 August 2011 July 2011 June 2011 May 2011 April 2011 March 2011 February 2011 January 2011 December 2010 November 2010 October 2010 September 2010 August 2010 July 2010 June 2010 May 2010 April 2010 March 2010 February 2010 January 2010 December 2009 November 2009 October 2009 September 2009 August 2009 July 2009 June 2009 May 2009 April 2009 March 2009 February 2009 January 2009 December 2008 November 2008 October 2008 September 2008 August 2008 July 2008 June 2008 May 2008 April 2008 March 2008 February 2008 January 2008 December 2007 November 2007 October 2007 September 2007 August 2007 July 2007 June 2007 May 2007 April 2007 March 2007 February 2007 January 2007 December 2006 November 2006 October 2006 September 2006 August 2006 July 2006 June 2006 May 2006 Stay informed Login Insert/edit link Close Enter the destination URL URL [ ] Link Text [ ] [ ] Open link in a new tab Or link to existing content Search [ ] No search term specified. Showing recent items. Search or use up and down arrow keys to select an item. Cancel [Add Link] Code Block x Paste your code snippet [ ] Cancel Ok What's new * Surface Pro 8 * Surface Laptop Studio * Surface Pro X * Surface Go 3 * Surface Duo 2 * Surface Pro 7+ * Windows 11 apps * HoloLens 2 Microsoft Store * Account profile * Download Center * Microsoft Store support * Returns * Order tracking * Virtual workshops and training * Microsoft Store Promise * Flexible Payments Education * Microsoft in education * Office for students * Office 365 for schools * Deals for students & parents * Microsoft Azure in education Enterprise * Azure * AppSource * Automotive * Government * Healthcare * Manufacturing * Financial services * Retail Developer * Microsoft Visual Studio * Windows Dev Center * Developer Center * Microsoft developer program * Channel 9 * Microsoft 365 Dev Center * Microsoft 365 Developer Program * Microsoft Garage Company * Careers * About Microsoft * Company news * Privacy at Microsoft * Investors * Diversity and inclusion * Accessibility * Security English (United States) * Sitemap * Contact Microsoft * Privacy * Manage cookies * Terms of use * Trademarks * Safety & eco * About our ads * (c) Microsoft 2022