Skip to content

Commit df4457e

Browse files
authored
Use intrinsics for source location if available (cppcheck-opensource#5449)
Sometimes the compiler supports the intrinsic even if the C++ runtime doesnt yet.
1 parent 50ba506 commit df4457e

1 file changed

Lines changed: 35 additions & 3 deletions

File tree

lib/sourcelocation.h

Lines changed: 35 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,20 @@
1919
#ifndef sourcelocationH
2020
#define sourcelocationH
2121

22+
#ifndef __has_builtin
23+
#define __has_builtin(x) 0 // Compatibility with non-clang compilers.
24+
#endif
25+
26+
#ifndef __has_include
27+
#define __has_include(x) 0 // Compatibility with non-clang compilers.
28+
#endif
29+
2230
#ifdef __CPPCHECK__
2331
#define CPPCHECK_HAS_SOURCE_LOCATION 0
2432
#define CPPCHECK_HAS_SOURCE_LOCATION_TS 0
25-
#elif defined(__has_include)
33+
#define CPPCHECK_HAS_SOURCE_LOCATION_INTRINSICS 0
34+
#else
35+
2636
#if __has_include(<source_location>) && __cplusplus >= 202003L
2737
#define CPPCHECK_HAS_SOURCE_LOCATION 1
2838
#else
@@ -33,9 +43,16 @@
3343
#else
3444
#define CPPCHECK_HAS_SOURCE_LOCATION_TS 0
3545
#endif
46+
47+
#if __has_builtin(__builtin_FILE)
48+
#define CPPCHECK_HAS_SOURCE_LOCATION_INTRINSICS 1
49+
#if !__has_builtin(__builtin_COLUMN)
50+
#define __builtin_COLUMN() 0
51+
#endif
3652
#else
37-
#define CPPCHECK_HAS_SOURCE_LOCATION 0
38-
#define CPPCHECK_HAS_SOURCE_LOCATION_TS 0
53+
#define CPPCHECK_HAS_SOURCE_LOCATION_INTRINSICS 0
54+
#endif
55+
3956
#endif
4057

4158
#if CPPCHECK_HAS_SOURCE_LOCATION
@@ -47,9 +64,24 @@ using SourceLocation = std::experimental::source_location;
4764
#else
4865
#include <cstdint>
4966
struct SourceLocation {
67+
#if CPPCHECK_HAS_SOURCE_LOCATION_INTRINSICS
68+
static SourceLocation current(std::uint_least32_t line = __builtin_LINE(),
69+
std::uint_least32_t column = __builtin_COLUMN(),
70+
const char* file_name = __builtin_FILE(),
71+
const char* function_name = __builtin_FUNCTION())
72+
{
73+
SourceLocation result{};
74+
result.m_line = line;
75+
result.m_column = column;
76+
result.m_file_name = file_name;
77+
result.m_function_name = function_name;
78+
return result;
79+
}
80+
#else
5081
static SourceLocation current() {
5182
return SourceLocation();
5283
}
84+
#endif
5385
std::uint_least32_t m_line = 0;
5486
std::uint_least32_t m_column = 0;
5587
const char* m_file_name = "";

0 commit comments

Comments
 (0)