Hans Wennborg | 8ee798d | 2020-02-07 15:30:35 | [diff] [blame] | 1 | # -Wmax-tokens |
| 2 | |
| 3 | This is an experiment that uses the compiler to limit the size of certain header |
| 4 | files as a way of tackling #include bloat. |
| 5 | |
| 6 | The main idea is to insert "back stops" for header sizes to ensure that header |
| 7 | cleanups don't regress without anyone noticing. |
| 8 | |
| 9 | A back stop is implementing using this pragma: |
| 10 | |
| 11 | ```c++ |
| 12 | #pragma clang max_tokens_here <num> |
| 13 | ``` |
| 14 | |
| 15 | It makes the compiler issue a -Wmax-tokens warning (which we treat as an error) |
| 16 | if the number of tokens after preprocessing at that point in the translation |
| 17 | unit exceeds num. |
| 18 | |
| 19 | For more background and data, see |
| 20 | [clang -Wmax-tokens: A Backstop for #include Bloat](https://docs.google.com/document/d/1xMkTZMKx9llnMPgso0jrx3ankI4cv60xeZ0y4ksf4wc/preview). |
| 21 | |
| 22 | |
| 23 | ## How to insert a header size back stop |
| 24 | |
| 25 | To limit the size of a header foo.h, insert the pragma directly after including |
| 26 | the header into its corresponding .cc file: |
| 27 | |
| 28 | ```c++ |
| 29 | // in foo.cc: |
| 30 | #include "foo.h" |
| 31 | #pragma clang max_tokens_here 123456 |
| 32 | |
| 33 | #include "blah.h" |
| 34 | ``` |
| 35 | |
| 36 | By inserting the pragma at this point, it captures the token count from |
| 37 | including the header in isolation. |
| 38 | |
| 39 | In order to not create unnecessary friction for developers, token limits should |
| 40 | only be imposed on headers with significant impact on build times: headers that |
| 41 | are (or were) large and widely included. |
| 42 | |
| 43 | |
| 44 | ## What to do when hitting a -Wmax-tokens warning |
| 45 | |
| 46 | Try using forward declarations or otherwise restructuring your change to |
| 47 | avoid growing the header beyond the limit. If that is infeasible, raise the |
| 48 | limit. |
Hans Wennborg | 72acf5e9 | 2020-05-12 00:21:31 | [diff] [blame] | 49 | |
| 50 | |
| 51 | ## Experiences |
| 52 | |
| 53 | - System headers on Chrome OS differ between boards and are not covered by the |
| 54 | commit queue. This means the token limits were not tailored to those builds, |
| 55 | causing build problems downstream. To avoid this, the -Wmax-tokens warning |
George Burgess IV | 192f55c | 2020-05-12 16:52:20 | [diff] [blame] | 56 | was disabled for Chrome OS (see |
| 57 | [crbug.com/1079053](https://crbug.com/1079053)). |