blob: 7ae251b04f34825b0857ea9337bc4f178a1bce95 [file] [log] [blame]
Adrian Prantlc53d3682018-08-15 22:48:48 +00001//===-- LibCxxOptional.cpp --------------------------------------*- C++ -*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Adrian Prantlc53d3682018-08-15 22:48:48 +00006//
7//===----------------------------------------------------------------------===//
8
9#include "LibCxx.h"
10#include "lldb/DataFormatters/FormattersHelpers.h"
11
12using namespace lldb;
13using namespace lldb_private;
14
15namespace {
16
17class OptionalFrontEnd : public SyntheticChildrenFrontEnd {
18public:
19 OptionalFrontEnd(ValueObject &valobj) : SyntheticChildrenFrontEnd(valobj) {
20 Update();
21 }
22
23 size_t GetIndexOfChildWithName(const ConstString &name) override {
24 return formatters::ExtractIndexFromString(name.GetCString());
25 }
26
27 bool MightHaveChildren() override { return true; }
28 bool Update() override;
29 size_t CalculateNumChildren() override { return m_size; }
30 ValueObjectSP GetChildAtIndex(size_t idx) override;
31
32private:
33 size_t m_size = 0;
34 ValueObjectSP m_base_sp;
35};
36} // namespace
37
38bool OptionalFrontEnd::Update() {
39 ValueObjectSP engaged_sp(
40 m_backend.GetChildMemberWithName(ConstString("__engaged_"), true));
41
42 if (!engaged_sp)
43 return false;
44
45 // __engaged_ is a bool flag and is true if the optional contains a value.
46 // Converting it to unsigned gives us a size of 1 if it contains a value
Shafik Yaghmourf4babef2018-09-10 23:18:32 +000047 // and 0 if not.
Adrian Prantlc53d3682018-08-15 22:48:48 +000048 m_size = engaged_sp->GetValueAsUnsigned(0);
49
50 return false;
51}
52
53ValueObjectSP OptionalFrontEnd::GetChildAtIndex(size_t idx) {
54 if (idx >= m_size)
55 return ValueObjectSP();
56
57 // __val_ contains the underlying value of an optional if it has one.
58 // Currently because it is part of an anonymous union GetChildMemberWithName()
59 // does not peer through and find it unless we are at the parent itself.
60 // We can obtain the parent through __engaged_.
61 ValueObjectSP val_sp(
62 m_backend.GetChildMemberWithName(ConstString("__engaged_"), true)
63 ->GetParent()
64 ->GetChildAtIndex(0, true)
65 ->GetChildMemberWithName(ConstString("__val_"), true));
66
67 if (!val_sp)
68 return ValueObjectSP();
69
70 CompilerType holder_type = val_sp->GetCompilerType();
71
72 if (!holder_type)
73 return ValueObjectSP();
74
75 return val_sp->Clone(ConstString(llvm::formatv("Value").str()));
76}
77
78SyntheticChildrenFrontEnd *
79formatters::LibcxxOptionalFrontEndCreator(CXXSyntheticChildren *,
80 lldb::ValueObjectSP valobj_sp) {
81 if (valobj_sp)
82 return new OptionalFrontEnd(*valobj_sp);
83 return nullptr;
84}