1// Copyright 2020 the V8 project authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef INCLUDE_CPPGC_SOURCE_LOCATION_H_
6#define INCLUDE_CPPGC_SOURCE_LOCATION_H_
7
8#include <cstddef>
9#include <string>
10
11#include "v8config.h"  // NOLINT(build/include_directory)
12
13#if defined(__has_builtin)
14#define CPPGC_SUPPORTS_SOURCE_LOCATION                                   \
15  (__has_builtin(__builtin_FUNCTION) && __has_builtin(__builtin_FILE) && \
16   __has_builtin(__builtin_LINE))  // NOLINT
17#elif defined(V8_CC_GNU) && __GNUC__ >= 7
18#define CPPGC_SUPPORTS_SOURCE_LOCATION 1
19#elif defined(V8_CC_INTEL) && __ICC >= 1800
20#define CPPGC_SUPPORTS_SOURCE_LOCATION 1
21#else
22#define CPPGC_SUPPORTS_SOURCE_LOCATION 0
23#endif
24
25namespace cppgc {
26
27/**
28 * Encapsulates source location information. Mimics C++20's
29 * `std::source_location`.
30 */
31class V8_EXPORT SourceLocation final {
32 public:
33  /**
34   * Construct source location information corresponding to the location of the
35   * call site.
36   */
37#if CPPGC_SUPPORTS_SOURCE_LOCATION
38  static constexpr SourceLocation Current(
39      const char* function = __builtin_FUNCTION(),
40      const char* file = __builtin_FILE(), size_t line = __builtin_LINE()) {
41    return SourceLocation(function, file, line);
42  }
43#else
44  static constexpr SourceLocation Current() { return SourceLocation(); }
45#endif  // CPPGC_SUPPORTS_SOURCE_LOCATION
46
47  /**
48   * Constructs unspecified source location information.
49   */
50  constexpr SourceLocation() = default;
51
52  /**
53   * Returns the name of the function associated with the position represented
54   * by this object, if any.
55   *
56   * \returns the function name as cstring.
57   */
58  constexpr const char* Function() const { return function_; }
59
60  /**
61   * Returns the name of the current source file represented by this object.
62   *
63   * \returns the file name as cstring.
64   */
65  constexpr const char* FileName() const { return file_; }
66
67  /**
68   * Returns the line number represented by this object.
69   *
70   * \returns the line number.
71   */
72  constexpr size_t Line() const { return line_; }
73
74  /**
75   * Returns a human-readable string representing this object.
76   *
77   * \returns a human-readable string representing source location information.
78   */
79  std::string ToString() const;
80
81 private:
82  constexpr SourceLocation(const char* function, const char* file, size_t line)
83      : function_(function), file_(file), line_(line) {}
84
85  const char* function_ = nullptr;
86  const char* file_ = nullptr;
87  size_t line_ = 0u;
88};
89
90}  // namespace cppgc
91
92#endif  // INCLUDE_CPPGC_SOURCE_LOCATION_H_
93