blob: 35dc41756a6ce58d6599e4091a64c7696328b489 [file] [log] [blame]
Googlerb56d7092021-11-26 12:38:29 +00001// Part of the Crubit project, under the Apache License v2.0 with LLVM
2// Exceptions. See /LICENSE for license information.
3// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
4
5#include "lifetime_annotations/lifetime.h"
6
Lukasz Anforowiczcec7a8a2022-04-27 10:24:51 -07007#include "absl/strings/str_cat.h"
Googlerb56d7092021-11-26 12:38:29 +00008
Martin Brænne1a207c52022-04-19 00:05:38 -07009namespace clang {
10namespace tidy {
11namespace lifetimes {
Googlerb56d7092021-11-26 12:38:29 +000012
13constexpr int INVALID_LIFETIME_ID_EMPTY = 0;
14constexpr int INVALID_LIFETIME_ID_TOMBSTONE = 1;
15constexpr int STATIC_LIFETIME_ID = -1;
16constexpr int FIRST_VARIABLE_LIFETIME_ID = 2;
17constexpr int FIRST_LOCAL_LIFETIME_ID = -2;
18
19std::atomic<int> Lifetime::next_variable_id_{FIRST_VARIABLE_LIFETIME_ID};
20
21std::atomic<int> Lifetime::next_local_id_{FIRST_LOCAL_LIFETIME_ID};
22
23Lifetime::Lifetime() : id_(INVALID_LIFETIME_ID_EMPTY) {}
24
25Lifetime Lifetime::CreateVariable() { return Lifetime(next_variable_id_++); }
26
27Lifetime Lifetime::Static() { return Lifetime(STATIC_LIFETIME_ID); }
28
29Lifetime Lifetime::CreateLocal() { return Lifetime(next_local_id_--); }
30
31bool Lifetime::IsVariable() const {
32 assert(IsValid());
33 return id_ > 0;
34}
35
36bool Lifetime::IsConstant() const {
37 assert(IsValid());
38 return !IsVariable();
39}
40
41bool Lifetime::IsLocal() const {
42 assert(IsValid());
43 return id_ <= FIRST_LOCAL_LIFETIME_ID;
44}
45
46std::string Lifetime::DebugString() const {
47 assert(IsValid());
48
49 switch (id_) {
50 case INVALID_LIFETIME_ID_EMPTY:
51 return "INVALID_EMPTY";
52 case INVALID_LIFETIME_ID_TOMBSTONE:
53 return "INVALID_TOMBSTONE";
54 case STATIC_LIFETIME_ID:
55 return "'static";
56 default:
57 if (id_ <= FIRST_LOCAL_LIFETIME_ID) {
58 return absl::StrCat("'local", -id_);
59 } else {
60 return absl::StrCat("'", id_);
61 }
62 }
63}
64
65Lifetime::Lifetime(int id) : id_(id) {}
66
67Lifetime Lifetime::InvalidEmpty() {
68 return Lifetime(INVALID_LIFETIME_ID_EMPTY);
69}
70
71Lifetime Lifetime::InvalidTombstone() {
72 return Lifetime(INVALID_LIFETIME_ID_TOMBSTONE);
73}
74
75bool Lifetime::IsValid() const {
76 return id_ != INVALID_LIFETIME_ID_EMPTY &&
77 id_ != INVALID_LIFETIME_ID_TOMBSTONE;
78}
79
80std::ostream& operator<<(std::ostream& os, Lifetime lifetime) {
81 return os << lifetime.DebugString();
82}
83
Martin Brænne1a207c52022-04-19 00:05:38 -070084} // namespace lifetimes
85} // namespace tidy
86} // namespace clang