nullability.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. // Copyright 2023 The Abseil Authors.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // https://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. //
  15. // -----------------------------------------------------------------------------
  16. // File: nullability.h
  17. // -----------------------------------------------------------------------------
  18. //
  19. // This header file defines a set of "templated annotations" for designating the
  20. // expected nullability of pointers. These annotations allow you to designate
  21. // pointers in one of three classification states:
  22. //
  23. // * "Non-null" (for pointers annotated `Nonnull<T>`), indicating that it is
  24. // invalid for the given pointer to ever be null.
  25. // * "Nullable" (for pointers annotated `Nullable<T>`), indicating that it is
  26. // valid for the given pointer to be null.
  27. // * "Unknown" (for pointers annotated `NullabilityUnknown<T>`), indicating
  28. // that the given pointer has not been yet classified as either nullable or
  29. // non-null. This is the default state of unannotated pointers.
  30. //
  31. // NOTE: unannotated pointers implicitly bear the annotation
  32. // `NullabilityUnknown<T>`; you should rarely, if ever, see this annotation used
  33. // in the codebase explicitly.
  34. //
  35. // -----------------------------------------------------------------------------
  36. // Nullability and Contracts
  37. // -----------------------------------------------------------------------------
  38. //
  39. // These nullability annotations allow you to more clearly specify contracts on
  40. // software components by narrowing the *preconditions*, *postconditions*, and
  41. // *invariants* of pointer state(s) in any given interface. It then depends on
  42. // context who is responsible for fulfilling the annotation's requirements.
  43. //
  44. // For example, a function may receive a pointer argument. Designating that
  45. // pointer argument as "non-null" tightens the precondition of the contract of
  46. // that function. It is then the responsibility of anyone calling such a
  47. // function to ensure that the passed pointer is not null.
  48. //
  49. // Similarly, a function may have a pointer as a return value. Designating that
  50. // return value as "non-null" tightens the postcondition of the contract of that
  51. // function. In this case, however, it is the responsibility of the function
  52. // itself to ensure that the returned pointer is not null.
  53. //
  54. // Clearly defining these contracts allows providers (and consumers) of such
  55. // pointers to have more confidence in their null state. If a function declares
  56. // a return value as "non-null", for example, the caller should not need to
  57. // check whether the returned value is `nullptr`; it can simply assume the
  58. // pointer is valid.
  59. //
  60. // Of course most interfaces already have expectations on the nullability state
  61. // of pointers, and these expectations are, in effect, a contract; often,
  62. // however, those contracts are either poorly or partially specified, assumed,
  63. // or misunderstood. These nullability annotations are designed to allow you to
  64. // formalize those contracts within the codebase.
  65. //
  66. // -----------------------------------------------------------------------------
  67. // Using Nullability Annotations
  68. // -----------------------------------------------------------------------------
  69. //
  70. // It is important to note that these annotations are not distinct strong
  71. // *types*. They are alias templates defined to be equal to the underlying
  72. // pointer type. A pointer annotated `Nonnull<T*>`, for example, is simply a
  73. // pointer of type `T*`. Each annotation acts as a form of documentation about
  74. // the contract for the given pointer. Each annotation requires providers or
  75. // consumers of these pointers across API boundaries to take appropriate steps
  76. // when setting or using these pointers:
  77. //
  78. // * "Non-null" pointers should never be null. It is the responsibility of the
  79. // provider of this pointer to ensure that the pointer may never be set to
  80. // null. Consumers of such pointers can treat such pointers as non-null.
  81. // * "Nullable" pointers may or may not be null. Consumers of such pointers
  82. // should precede any usage of that pointer (e.g. a dereference operation)
  83. // with a a `nullptr` check.
  84. // * "Unknown" pointers may be either "non-null" or "nullable" but have not been
  85. // definitively determined to be in either classification state. Providers of
  86. // such pointers across API boundaries should determine -- over time -- to
  87. // annotate the pointer in either of the above two states. Consumers of such
  88. // pointers across an API boundary should continue to treat such pointers as
  89. // they currently do.
  90. //
  91. // Example:
  92. //
  93. // // PaySalary() requires the passed pointer to an `Employee` to be non-null.
  94. // void PaySalary(absl::Nonnull<Employee *> e) {
  95. // pay(e->salary); // OK to dereference
  96. // }
  97. //
  98. // // CompleteTransaction() guarantees the returned pointer to an `Account` to
  99. // // be non-null.
  100. // absl::Nonnull<Account *> balance CompleteTransaction(double fee) {
  101. // ...
  102. // }
  103. //
  104. // // Note that specifying a nullability annotation does not prevent someone
  105. // // from violating the contract:
  106. //
  107. // Nullable<Employee *> find(Map& employees, std::string_view name);
  108. //
  109. // void g(Map& employees) {
  110. // Employee *e = find(employees, "Pat");
  111. // // `e` can now be null.
  112. // PaySalary(e); // Violates contract, but compiles!
  113. // }
  114. //
  115. // Nullability annotations, in other words, are useful for defining and
  116. // narrowing contracts; *enforcement* of those contracts depends on use and any
  117. // additional (static or dynamic analysis) tooling.
  118. //
  119. // NOTE: The "unknown" annotation state indicates that a pointer's contract has
  120. // not yet been positively identified. The unknown state therefore acts as a
  121. // form of documentation of your technical debt, and a codebase that adopts
  122. // nullability annotations should aspire to annotate every pointer as either
  123. // "non-null" or "nullable".
  124. //
  125. // -----------------------------------------------------------------------------
  126. // Applicability of Nullability Annotations
  127. // -----------------------------------------------------------------------------
  128. //
  129. // By default, nullability annotations are applicable to raw and smart
  130. // pointers. User-defined types can indicate compatibility with nullability
  131. // annotations by adding the ABSL_NULLABILITY_COMPATIBLE attribute.
  132. //
  133. // // Example:
  134. // struct ABSL_NULLABILITY_COMPATIBLE MyPtr {
  135. // ...
  136. // };
  137. //
  138. // Note: Compilers that don't support the `nullability_on_classes` feature will
  139. // allow nullability annotations to be applied to any type, not just ones
  140. // marked with `ABSL_NULLABILITY_COMPATIBLE`.
  141. //
  142. // DISCLAIMER:
  143. // ===========================================================================
  144. // These nullability annotations are primarily a human readable signal about the
  145. // intended contract of the pointer. They are not *types* and do not currently
  146. // provide any correctness guarantees. For example, a pointer annotated as
  147. // `Nonnull<T*>` is *not guaranteed* to be non-null, and the compiler won't
  148. // alert or prevent assignment of a `Nullable<T*>` to a `Nonnull<T*>`.
  149. // ===========================================================================
  150. #ifndef ABSL_BASE_NULLABILITY_H_
  151. #define ABSL_BASE_NULLABILITY_H_
  152. #include "absl/base/config.h"
  153. #include "absl/base/internal/nullability_impl.h"
  154. // ABSL_POINTERS_DEFAULT_NONNULL
  155. //
  156. // This macro specifies that all unannotated pointer types within the given
  157. // file are designated as nonnull (instead of the default "unknown"). This macro
  158. // exists as a standalone statement and applies default nonnull behavior to all
  159. // subsequent pointers; as a result, place this macro as the first non-comment,
  160. // non-`#include` line in a file.
  161. //
  162. // Example:
  163. //
  164. // #include "absl/base/nullability.h"
  165. //
  166. // ABSL_POINTERS_DEFAULT_NONNULL
  167. //
  168. // void FillMessage(Message *m); // implicitly non-null
  169. // absl::Nullable<T*> GetNullablePtr(); // explicitly nullable
  170. // absl::NullabilityUnknown<T*> GetUnknownPtr(); // explicitly unknown
  171. //
  172. // The macro can be safely used in header files -- it will not affect any files
  173. // that include it.
  174. //
  175. // In files with the macro, plain `T*` syntax means `absl::Nonnull<T*>`, and the
  176. // exceptions (`Nullable` and `NullabilityUnknown`) must be marked
  177. // explicitly. The same holds, correspondingly, for smart pointer types.
  178. //
  179. // For comparison, without the macro, all unannotated pointers would default to
  180. // unknown, and otherwise require explicit annotations to change this behavior:
  181. //
  182. // #include "absl/base/nullability.h"
  183. //
  184. // void FillMessage(absl::Nonnull<Message*> m); // explicitly non-null
  185. // absl::Nullable<T*> GetNullablePtr(); // explicitly nullable
  186. // T* GetUnknownPtr(); // implicitly unknown
  187. //
  188. // No-op except for being a human readable signal.
  189. #define ABSL_POINTERS_DEFAULT_NONNULL
  190. namespace absl {
  191. ABSL_NAMESPACE_BEGIN
  192. // absl::Nonnull (default with `ABSL_POINTERS_DEFAULT_NONNULL`)
  193. //
  194. // The indicated pointer is never null. It is the responsibility of the provider
  195. // of this pointer across an API boundary to ensure that the pointer is never
  196. // set to null. Consumers of this pointer across an API boundary may safely
  197. // dereference the pointer.
  198. //
  199. // Example:
  200. //
  201. // // `employee` is designated as not null.
  202. // void PaySalary(absl::Nonnull<Employee *> employee) {
  203. // pay(*employee); // OK to dereference
  204. // }
  205. template <typename T>
  206. using Nonnull = nullability_internal::NonnullImpl<T>;
  207. // absl::Nullable
  208. //
  209. // The indicated pointer may, by design, be either null or non-null. Consumers
  210. // of this pointer across an API boundary should perform a `nullptr` check
  211. // before performing any operation using the pointer.
  212. //
  213. // Example:
  214. //
  215. // // `employee` may be null.
  216. // void PaySalary(absl::Nullable<Employee *> employee) {
  217. // if (employee != nullptr) {
  218. // Pay(*employee); // OK to dereference
  219. // }
  220. // }
  221. template <typename T>
  222. using Nullable = nullability_internal::NullableImpl<T>;
  223. // absl::NullabilityUnknown (default without `ABSL_POINTERS_DEFAULT_NONNULL`)
  224. //
  225. // The indicated pointer has not yet been determined to be definitively
  226. // "non-null" or "nullable." Providers of such pointers across API boundaries
  227. // should, over time, annotate such pointers as either "non-null" or "nullable."
  228. // Consumers of these pointers across an API boundary should treat such pointers
  229. // with the same caution they treat currently unannotated pointers. Most
  230. // existing code will have "unknown" pointers, which should eventually be
  231. // migrated into one of the above two nullability states: `Nonnull<T>` or
  232. // `Nullable<T>`.
  233. //
  234. // NOTE: For files that do not specify `ABSL_POINTERS_DEFAULT_NONNULL`,
  235. // because this annotation is the global default state, unannotated pointers are
  236. // are assumed to have "unknown" semantics. This assumption is designed to
  237. // minimize churn and reduce clutter within the codebase.
  238. //
  239. // Example:
  240. //
  241. // // `employee`s nullability state is unknown.
  242. // void PaySalary(absl::NullabilityUnknown<Employee *> employee) {
  243. // Pay(*employee); // Potentially dangerous. API provider should investigate.
  244. // }
  245. //
  246. // Note that a pointer without an annotation, by default, is assumed to have the
  247. // annotation `NullabilityUnknown`.
  248. //
  249. // // `employee`s nullability state is unknown.
  250. // void PaySalary(Employee* employee) {
  251. // Pay(*employee); // Potentially dangerous. API provider should investigate.
  252. // }
  253. template <typename T>
  254. using NullabilityUnknown = nullability_internal::NullabilityUnknownImpl<T>;
  255. ABSL_NAMESPACE_END
  256. } // namespace absl
  257. // ABSL_NULLABILITY_COMPATIBLE
  258. //
  259. // Indicates that a class is compatible with nullability annotations.
  260. //
  261. // For example:
  262. //
  263. // struct ABSL_NULLABILITY_COMPATIBLE MyPtr {
  264. // ...
  265. // };
  266. //
  267. // Note: Compilers that don't support the `nullability_on_classes` feature will
  268. // allow nullability annotations to be applied to any type, not just ones marked
  269. // with `ABSL_NULLABILITY_COMPATIBLE`.
  270. #if ABSL_HAVE_FEATURE(nullability_on_classes)
  271. #define ABSL_NULLABILITY_COMPATIBLE _Nullable
  272. #else
  273. #define ABSL_NULLABILITY_COMPATIBLE
  274. #endif
  275. // ABSL_NONNULL
  276. // ABSL_NULLABLE
  277. // ABSL_NULLABILITY_UNKNOWN
  278. //
  279. // These macros are analogues of the alias template nullability annotations
  280. // above.
  281. //
  282. // Example:
  283. // int* ABSL_NULLABLE foo;
  284. // Is equivalent to:
  285. // absl::Nullable<int*> foo;
  286. #if defined(__clang__) && !defined(__OBJC__) && \
  287. ABSL_HAVE_FEATURE(nullability_on_classes)
  288. #define ABSL_NONNULL _Nonnull
  289. #define ABSL_NULLABLE _Nullable
  290. #define ABSL_NULLABILITY_UNKNOWN _Null_unspecified
  291. #else
  292. #define ABSL_NONNULL
  293. #define ABSL_NULLABLE
  294. #define ABSL_NULLABILITY_UNKNOWN
  295. #endif
  296. #endif // ABSL_BASE_NULLABILITY_H_