Checks that the file contains a header guard. Logs an error if no #ifndef header guard is present. For other headers, checks that the full pathname is used. Args: filename: The name of the C++ header file. clean_lines: A CleansedLines instance containing the file. er
(filename, clean_lines, error, cppvar)
| 2618 | |
| 2619 | |
| 2620 | def CheckForHeaderGuard(filename, clean_lines, error, cppvar): |
| 2621 | """Checks that the file contains a header guard. |
| 2622 | |
| 2623 | Logs an error if no #ifndef header guard is present. For other |
| 2624 | headers, checks that the full pathname is used. |
| 2625 | |
| 2626 | Args: |
| 2627 | filename: The name of the C++ header file. |
| 2628 | clean_lines: A CleansedLines instance containing the file. |
| 2629 | error: The function to call with any errors found. |
| 2630 | """ |
| 2631 | |
| 2632 | # Don't check for header guards if there are error suppression |
| 2633 | # comments somewhere in this file. |
| 2634 | # |
| 2635 | # Because this is silencing a warning for a nonexistent line, we |
| 2636 | # only support the very specific NOLINT(build/header_guard) syntax, |
| 2637 | # and not the general NOLINT or NOLINT(*) syntax. |
| 2638 | raw_lines = clean_lines.lines_without_raw_strings |
| 2639 | for i in raw_lines: |
| 2640 | if re.search(r"//\s*NOLINT\(build/header_guard\)", i): |
| 2641 | return |
| 2642 | |
| 2643 | # Allow pragma once instead of header guards |
| 2644 | for i in raw_lines: |
| 2645 | if re.search(r"^\s*#pragma\s+once", i): |
| 2646 | return |
| 2647 | |
| 2648 | ifndef = "" |
| 2649 | ifndef_linenum = 0 |
| 2650 | define = "" |
| 2651 | endif = "" |
| 2652 | endif_linenum = 0 |
| 2653 | for linenum, line in enumerate(raw_lines): |
| 2654 | linesplit = line.split() |
| 2655 | if len(linesplit) >= 2: |
| 2656 | # find the first occurrence of #ifndef and #define, save arg |
| 2657 | if not ifndef and linesplit[0] == "#ifndef": |
| 2658 | # set ifndef to the header guard presented on the #ifndef line. |
| 2659 | ifndef = linesplit[1] |
| 2660 | ifndef_linenum = linenum |
| 2661 | if not define and linesplit[0] == "#define": |
| 2662 | define = linesplit[1] |
| 2663 | # find the last occurrence of #endif, save entire line |
| 2664 | if line.startswith("#endif"): |
| 2665 | endif = line |
| 2666 | endif_linenum = linenum |
| 2667 | |
| 2668 | if not ifndef or not define or ifndef != define: |
| 2669 | error( |
| 2670 | filename, |
| 2671 | 0, |
| 2672 | "build/header_guard", |
| 2673 | 5, |
| 2674 | f"No #ifndef header guard found, suggested CPP variable is: {cppvar}", |
| 2675 | ) |
| 2676 | return |
| 2677 |
no test coverage detected
searching dependent graphs…