1 //
2 //
3 // Copyright 2017 gRPC authors.
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 //     http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16 //
17 //
18 
19 #ifndef GRPC_SRC_CORE_LIB_GPRPP_DEBUG_LOCATION_H
20 #define GRPC_SRC_CORE_LIB_GPRPP_DEBUG_LOCATION_H
21 
22 #if defined(__has_builtin)
23 #if __has_builtin(__builtin_FILE)
24 #define GRPC_DEFAULT_FILE __builtin_FILE()
25 #endif
26 #endif
27 #ifndef GRPC_DEFAULT_FILE
28 #define GRPC_DEFAULT_FILE "<unknown>"
29 #endif
30 #if defined(__has_builtin)
31 #if __has_builtin(__builtin_LINE)
32 #define GRPC_DEFAULT_LINE __builtin_LINE()
33 #endif
34 #endif
35 #ifndef GRPC_DEFAULT_LINE
36 #define GRPC_DEFAULT_LINE -1
37 #endif
38 
39 namespace grpc_core {
40 
41 class SourceLocation {
42  public:
43   // NOLINTNEXTLINE
44   SourceLocation(const char* file = GRPC_DEFAULT_FILE,
45                  int line = GRPC_DEFAULT_LINE)
file_(file)46       : file_(file), line_(line) {}
file()47   const char* file() const { return file_; }
line()48   int line() const { return line_; }
49 
50  private:
51   const char* file_;
52   int line_;
53 };
54 
55 // Used for tracking file and line where a call is made for debug builds.
56 // No-op for non-debug builds.
57 // Callers can use the DEBUG_LOCATION macro in either case.
58 #ifndef NDEBUG
59 class DebugLocation {
60  public:
61   DebugLocation(const char* file = GRPC_DEFAULT_FILE,
62                 int line = GRPC_DEFAULT_LINE)
location_(file,line)63       : location_(file, line) {}
file()64   const char* file() const { return location_.file(); }
line()65   int line() const { return location_.line(); }
66 
67  private:
68   SourceLocation location_;
69 };
70 #else
71 class DebugLocation {
72  public:
DebugLocation()73   DebugLocation() {}
DebugLocation(const char *,int)74   DebugLocation(const char* /* file */, int /* line */) {}
file()75   const char* file() const { return nullptr; }
line()76   int line() const { return -1; }
77 };
78 #endif
79 
80 #define DEBUG_LOCATION ::grpc_core::DebugLocation(__FILE__, __LINE__)
81 
82 }  // namespace grpc_core
83 
84 #endif  // GRPC_SRC_CORE_LIB_GPRPP_DEBUG_LOCATION_H
85