File: SwiftOptionSet.cpp

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (256 lines) | stat: -rw-r--r-- 8,426 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
//===-- SwiftOptionSet.cpp --------------------------------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#include "SwiftOptionSet.h"

#include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
#include "Plugins/TypeSystem/Swift/SwiftASTContext.h"
#include "lldb/Core/ValueObject.h"
#include "lldb/Symbol/CompilerType.h"
#include "lldb/Utility/LLDBLog.h"
#include "lldb/Utility/Log.h"
#include "lldb/Utility/StreamString.h"

#include "clang/AST/Decl.h"
#include "llvm/ADT/StringRef.h"

using namespace lldb;
using namespace lldb_private;
using namespace lldb_private::formatters;
using namespace lldb_private::formatters::swift;

/// If this is a Clang enum wrapped in a Swift type, return the clang::EnumDecl.
static std::pair<clang::EnumDecl *, std::shared_ptr<TypeSystemClang>>
GetAsEnumDecl(CompilerType swift_type) {
  swift_type = swift_type.GetCanonicalType();
  if (!swift_type)
    return {nullptr, nullptr};

  auto swift_ast_ctx =
      swift_type.GetTypeSystem().dyn_cast_or_null<TypeSystemSwift>();
  if (!swift_ast_ctx)
    return {nullptr, nullptr};

  CompilerType clang_type;
  if (!swift_ast_ctx->IsImportedType(swift_type.GetOpaqueQualType(),
                                     &clang_type))
    return {nullptr, nullptr};

  if (!clang_type.IsValid())
    return {nullptr, nullptr};

  auto clang_ts = clang_type.GetTypeSystem().dyn_cast_or_null<TypeSystemClang>();
  if (!clang_ts)
    return {nullptr, nullptr};

  auto qual_type = clang::QualType::getFromOpaquePtr(
      clang_type.GetCanonicalType().GetOpaqueQualType());
  if (qual_type->getTypeClass() != clang::Type::TypeClass::Enum)
    return {nullptr, nullptr};

  if (const clang::EnumType *enum_type = qual_type->getAs<clang::EnumType>())
    return {enum_type->getDecl(), clang_ts};
  return {nullptr, nullptr};
}

bool lldb_private::formatters::swift::SwiftOptionSetSummaryProvider::
    WouldEvenConsiderFormatting(CompilerType swift_type) {
  return GetAsEnumDecl(swift_type).first;
}

lldb_private::formatters::swift::SwiftOptionSetSummaryProvider::
    SwiftOptionSetSummaryProvider(CompilerType clang_type)
    : TypeSummaryImpl(TypeSummaryImpl::Kind::eInternal,
                      TypeSummaryImpl::Flags()),
      m_type(clang_type), m_cases() {}

void lldb_private::formatters::swift::SwiftOptionSetSummaryProvider::
    FillCasesIfNeeded(const ExecutionContext *exe_ctx) {
  if (m_cases.has_value())
    return;

  m_cases = CasesVector();
  auto decl_ts = GetAsEnumDecl(m_type);
  clang::EnumDecl *enum_decl = decl_ts.first;
  if (!enum_decl)
    return;

  // FIXME: Delete this type reconstruction block. For GetSwiftName() to
  // fully work, ClangImporter's ImportName class needs to be made
  // standalone and provided with a callback to read the APINote
  // information.
  auto ts = m_type.GetTypeSystem();
  TypeSystemSwift *tss = nullptr;
  std::shared_ptr<SwiftASTContext> swift_ast_ctx;
  if (auto trts =
          ts.dyn_cast_or_null<TypeSystemSwiftTypeRef>()) {
    tss = trts.get();
    CompilerType ast_type = trts->ReconstructType(m_type, exe_ctx);
    swift_ast_ctx =
        ast_type.GetTypeSystem().dyn_cast_or_null<SwiftASTContext>();
    if (swift_ast_ctx) {
      auto ast_decl_ts = GetAsEnumDecl(ast_type);
      if (ast_decl_ts.first) {
        tss = swift_ast_ctx.get();
        enum_decl = ast_decl_ts.first;
        m_type = ast_type;
      } else {
        LLDB_LOG(GetLog(LLDBLog::DataFormatters),
                 "Cannot get Clang type for {0}",
                 m_type.GetMangledTypeName());
      }
    } else {
      LLDB_LOG(GetLog(LLDBLog::DataFormatters), "Cannot reconstruct {0}",
               m_type.GetMangledTypeName());
    }
  }
  if (!tss) {
    LLDB_LOG(GetLog(LLDBLog::DataFormatters), "No typesystem");
    return;
  }

  auto iter = enum_decl->enumerator_begin(), end = enum_decl->enumerator_end();
  for (; iter != end; ++iter) {
    clang::EnumConstantDecl *case_decl = *iter;
    if (case_decl) {
      llvm::APInt case_init_val(case_decl->getInitVal());
      // Extend all cases to 64 bits so that equality check is fast
      // but if they are larger than 64, I am going to get out of that
      // case and then pick it up again as unmatched data at the end.
      if (case_init_val.getBitWidth() < 64)
        case_init_val = case_init_val.zext(64);
      if (case_init_val.getBitWidth() > 64)
        continue;
      ConstString case_name(tss->GetSwiftName(case_decl, *decl_ts.second));
      m_cases->push_back({case_init_val, case_name});
    }
  }
}

std::string lldb_private::formatters::swift::SwiftOptionSetSummaryProvider::
    GetDescription() {
  StreamString sstr;
  sstr.Printf("`%s `%s%s%s%s%s%s%s", "Swift OptionSet summary provider",
              Cascades() ? "" : " (not cascading)", " (may show children)",
              !DoesPrintValue(nullptr) ? " (hide value)" : "",
              IsOneLiner() ? " (one-line printout)" : "",
              SkipsPointers() ? " (skip pointers)" : "",
              SkipsReferences() ? " (skip references)" : "",
              HideNames(nullptr) ? " (hide member names)" : "");
  return sstr.GetString().str();
}

static bool ReadValueIfAny(ValueObject &valobj, llvm::APInt &value) {
  ValueObjectSP most_qualified_sp(valobj.GetQualifiedRepresentationIfAvailable(
      lldb::eDynamicDontRunTarget, true));

  bool success;
  value = llvm::APInt(64, most_qualified_sp->GetValueAsUnsigned(0, &success));
  return success;
}

static ValueObjectSP GetRawValue(ValueObject *valobj) {
  if (!valobj)
    return nullptr;

  static ConstString g_rawValue("rawValue");

  auto rawValue_sp = valobj->GetChildMemberWithName(g_rawValue, true);

  return rawValue_sp;
}

bool lldb_private::formatters::swift::SwiftOptionSetSummaryProvider::
    FormatObject(ValueObject *valobj, std::string &dest,
                 const TypeSummaryOptions &options) {
  auto rawValue_sp = GetRawValue(valobj);
  if (!rawValue_sp)
    return false;

  llvm::APInt value;
  if (!ReadValueIfAny(*rawValue_sp, value))
    return false;

  {
    ExecutionContext exe_ctx = valobj->GetExecutionContextRef().Lock(false);
    FillCasesIfNeeded(&exe_ctx);
  }

  StreamString ss;
  bool first_match = true;
  bool any_match = false;

  llvm::APInt matched_value(llvm::APInt::getZero(64));

  // Look for an exact case match first.
  for (auto val_name : *m_cases) {
    llvm::APInt case_value = val_name.first;
    // Print single valued sets without using enclosing brackets.
    // `WouldEvenConsiderFormatting` can't opt out early because it
    // has only the type, but needs the value for this case.
    if (case_value == value) {
      ss << '.' << val_name.second;
      dest.assign(ss.GetData());
      return true;
    }
  }

  // Look for ORed cases next.
  for (auto val_name : *m_cases) {
    llvm::APInt case_value = val_name.first;
    // Don't display the zero case in an option set unless it's the
    // only value.
    if (case_value == 0 && value != 0)
      continue;
    if ((case_value & value) == case_value) {
      any_match = true;
      if (first_match) {
        ss << "[." << val_name.second;
        first_match = false;
      } else {
        ss << ", ." << val_name.second;
      }

      matched_value |= case_value;

      // If we matched everything, get out.
      if (matched_value == value)
        break;
    }
  }

  if (!any_match)
    return false;

  if (matched_value != value) {
    // Print the unaccounted-for bits separately.
    llvm::APInt residual = value & ~matched_value;
    llvm::SmallString<24> string;
    residual.toString(string, 16, false);
    ss << ", 0x" << string;
  }
  ss << ']';

  dest.assign(ss.GetData());
  return true;
}

bool lldb_private::formatters::swift::SwiftOptionSetSummaryProvider::
    DoesPrintChildren(ValueObject *valobj) const {
  auto rawValue_sp = GetRawValue(valobj);
  if (!rawValue_sp)
    return false;

  llvm::APInt value;
  // only show children if you couldn't read the value of rawValue
  return (false == ReadValueIfAny(*rawValue_sp, value));
}