xref: /llvm-project/lldb/source/DataFormatters/FormatManager.cpp (revision ee64dfd953f89a9d3df3c13a28b1bce33f33f4cb)
1 //===-- FormatManager.cpp ----------------------------------------*- C++-*-===//
2 //
3 // 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
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "lldb/DataFormatters/FormatManager.h"
10 
11 #include "llvm/ADT/STLExtras.h"
12 
13 
14 #include "lldb/Core/Debugger.h"
15 #include "lldb/DataFormatters/FormattersHelpers.h"
16 #include "lldb/DataFormatters/LanguageCategory.h"
17 #include "lldb/Target/ExecutionContext.h"
18 #include "lldb/Target/Language.h"
19 #include "lldb/Utility/Log.h"
20 
21 using namespace lldb;
22 using namespace lldb_private;
23 using namespace lldb_private::formatters;
24 
25 struct FormatInfo {
26   Format format;
27   const char format_char;  // One or more format characters that can be used for
28                            // this format.
29   const char *format_name; // Long format name that can be used to specify the
30                            // current format
31 };
32 
33 static constexpr FormatInfo g_format_infos[] = {
34     {eFormatDefault, '\0', "default"},
35     {eFormatBoolean, 'B', "boolean"},
36     {eFormatBinary, 'b', "binary"},
37     {eFormatBytes, 'y', "bytes"},
38     {eFormatBytesWithASCII, 'Y', "bytes with ASCII"},
39     {eFormatChar, 'c', "character"},
40     {eFormatCharPrintable, 'C', "printable character"},
41     {eFormatComplexFloat, 'F', "complex float"},
42     {eFormatCString, 's', "c-string"},
43     {eFormatDecimal, 'd', "decimal"},
44     {eFormatEnum, 'E', "enumeration"},
45     {eFormatHex, 'x', "hex"},
46     {eFormatHexUppercase, 'X', "uppercase hex"},
47     {eFormatFloat, 'f', "float"},
48     {eFormatOctal, 'o', "octal"},
49     {eFormatOSType, 'O', "OSType"},
50     {eFormatUnicode16, 'U', "unicode16"},
51     {eFormatUnicode32, '\0', "unicode32"},
52     {eFormatUnsigned, 'u', "unsigned decimal"},
53     {eFormatPointer, 'p', "pointer"},
54     {eFormatVectorOfChar, '\0', "char[]"},
55     {eFormatVectorOfSInt8, '\0', "int8_t[]"},
56     {eFormatVectorOfUInt8, '\0', "uint8_t[]"},
57     {eFormatVectorOfSInt16, '\0', "int16_t[]"},
58     {eFormatVectorOfUInt16, '\0', "uint16_t[]"},
59     {eFormatVectorOfSInt32, '\0', "int32_t[]"},
60     {eFormatVectorOfUInt32, '\0', "uint32_t[]"},
61     {eFormatVectorOfSInt64, '\0', "int64_t[]"},
62     {eFormatVectorOfUInt64, '\0', "uint64_t[]"},
63     {eFormatVectorOfFloat16, '\0', "float16[]"},
64     {eFormatVectorOfFloat32, '\0', "float32[]"},
65     {eFormatVectorOfFloat64, '\0', "float64[]"},
66     {eFormatVectorOfUInt128, '\0', "uint128_t[]"},
67     {eFormatComplexInteger, 'I', "complex integer"},
68     {eFormatCharArray, 'a', "character array"},
69     {eFormatAddressInfo, 'A', "address"},
70     {eFormatHexFloat, '\0', "hex float"},
71     {eFormatInstruction, 'i', "instruction"},
72     {eFormatVoid, 'v', "void"},
73     {eFormatUnicode8, 'u', "unicode8"},
74 };
75 
76 static_assert((sizeof(g_format_infos) / sizeof(g_format_infos[0])) ==
77                   kNumFormats,
78               "All formats must have a corresponding info entry.");
79 
80 static uint32_t g_num_format_infos = llvm::array_lengthof(g_format_infos);
81 
82 static bool GetFormatFromFormatChar(char format_char, Format &format) {
83   for (uint32_t i = 0; i < g_num_format_infos; ++i) {
84     if (g_format_infos[i].format_char == format_char) {
85       format = g_format_infos[i].format;
86       return true;
87     }
88   }
89   format = eFormatInvalid;
90   return false;
91 }
92 
93 static bool GetFormatFromFormatName(const char *format_name,
94                                     bool partial_match_ok, Format &format) {
95   uint32_t i;
96   for (i = 0; i < g_num_format_infos; ++i) {
97     if (strcasecmp(g_format_infos[i].format_name, format_name) == 0) {
98       format = g_format_infos[i].format;
99       return true;
100     }
101   }
102 
103   if (partial_match_ok) {
104     for (i = 0; i < g_num_format_infos; ++i) {
105       if (strcasestr(g_format_infos[i].format_name, format_name) ==
106           g_format_infos[i].format_name) {
107         format = g_format_infos[i].format;
108         return true;
109       }
110     }
111   }
112   format = eFormatInvalid;
113   return false;
114 }
115 
116 void FormatManager::Changed() {
117   ++m_last_revision;
118   m_format_cache.Clear();
119   std::lock_guard<std::recursive_mutex> guard(m_language_categories_mutex);
120   for (auto &iter : m_language_categories_map) {
121     if (iter.second)
122       iter.second->GetFormatCache().Clear();
123   }
124 }
125 
126 bool FormatManager::GetFormatFromCString(const char *format_cstr,
127                                          bool partial_match_ok,
128                                          lldb::Format &format) {
129   bool success = false;
130   if (format_cstr && format_cstr[0]) {
131     if (format_cstr[1] == '\0') {
132       success = GetFormatFromFormatChar(format_cstr[0], format);
133       if (success)
134         return true;
135     }
136 
137     success = GetFormatFromFormatName(format_cstr, partial_match_ok, format);
138   }
139   if (!success)
140     format = eFormatInvalid;
141   return success;
142 }
143 
144 char FormatManager::GetFormatAsFormatChar(lldb::Format format) {
145   for (uint32_t i = 0; i < g_num_format_infos; ++i) {
146     if (g_format_infos[i].format == format)
147       return g_format_infos[i].format_char;
148   }
149   return '\0';
150 }
151 
152 const char *FormatManager::GetFormatAsCString(Format format) {
153   if (format >= eFormatDefault && format < kNumFormats)
154     return g_format_infos[format].format_name;
155   return nullptr;
156 }
157 
158 void FormatManager::EnableAllCategories() {
159   m_categories_map.EnableAllCategories();
160   std::lock_guard<std::recursive_mutex> guard(m_language_categories_mutex);
161   for (auto &iter : m_language_categories_map) {
162     if (iter.second)
163       iter.second->Enable();
164   }
165 }
166 
167 void FormatManager::DisableAllCategories() {
168   m_categories_map.DisableAllCategories();
169   std::lock_guard<std::recursive_mutex> guard(m_language_categories_mutex);
170   for (auto &iter : m_language_categories_map) {
171     if (iter.second)
172       iter.second->Disable();
173   }
174 }
175 
176 void FormatManager::GetPossibleMatches(
177     ValueObject &valobj, CompilerType compiler_type, uint32_t reason,
178     lldb::DynamicValueType use_dynamic, FormattersMatchVector &entries,
179     bool did_strip_ptr, bool did_strip_ref, bool did_strip_typedef,
180     bool root_level) {
181   compiler_type = compiler_type.GetTypeForFormatters();
182   ConstString type_name(compiler_type.GetConstTypeName());
183   if (valobj.GetBitfieldBitSize() > 0) {
184     StreamString sstring;
185     sstring.Printf("%s:%d", type_name.AsCString(), valobj.GetBitfieldBitSize());
186     ConstString bitfieldname(sstring.GetString());
187     entries.push_back(
188         {bitfieldname, 0, did_strip_ptr, did_strip_ref, did_strip_typedef});
189     reason |= lldb_private::eFormatterChoiceCriterionStrippedBitField;
190   }
191 
192   if (!compiler_type.IsMeaninglessWithoutDynamicResolution()) {
193     entries.push_back(
194         {type_name, reason, did_strip_ptr, did_strip_ref, did_strip_typedef});
195 
196     ConstString display_type_name(compiler_type.GetDisplayTypeName());
197     if (display_type_name != type_name)
198       entries.push_back({display_type_name, reason, did_strip_ptr,
199                          did_strip_ref, did_strip_typedef});
200   }
201 
202   for (bool is_rvalue_ref = true, j = true;
203        j && compiler_type.IsReferenceType(nullptr, &is_rvalue_ref); j = false) {
204     CompilerType non_ref_type = compiler_type.GetNonReferenceType();
205     GetPossibleMatches(
206         valobj, non_ref_type,
207         reason |
208             lldb_private::eFormatterChoiceCriterionStrippedPointerReference,
209         use_dynamic, entries, did_strip_ptr, true, did_strip_typedef);
210     if (non_ref_type.IsTypedefType()) {
211       CompilerType deffed_referenced_type = non_ref_type.GetTypedefedType();
212       deffed_referenced_type =
213           is_rvalue_ref ? deffed_referenced_type.GetRValueReferenceType()
214                         : deffed_referenced_type.GetLValueReferenceType();
215       GetPossibleMatches(
216           valobj, deffed_referenced_type,
217           reason | lldb_private::eFormatterChoiceCriterionNavigatedTypedefs,
218           use_dynamic, entries, did_strip_ptr, did_strip_ref,
219           true); // this is not exactly the usual meaning of stripping typedefs
220     }
221   }
222 
223   if (compiler_type.IsPointerType()) {
224     CompilerType non_ptr_type = compiler_type.GetPointeeType();
225     GetPossibleMatches(
226         valobj, non_ptr_type,
227         reason |
228             lldb_private::eFormatterChoiceCriterionStrippedPointerReference,
229         use_dynamic, entries, true, did_strip_ref, did_strip_typedef);
230     if (non_ptr_type.IsTypedefType()) {
231       CompilerType deffed_pointed_type =
232           non_ptr_type.GetTypedefedType().GetPointerType();
233       GetPossibleMatches(
234           valobj, deffed_pointed_type,
235           reason | lldb_private::eFormatterChoiceCriterionNavigatedTypedefs,
236           use_dynamic, entries, did_strip_ptr, did_strip_ref,
237           true); // this is not exactly the usual meaning of stripping typedefs
238     }
239   }
240 
241   for (lldb::LanguageType language_type :
242        GetCandidateLanguages(valobj.GetObjectRuntimeLanguage())) {
243     if (Language *language = Language::FindPlugin(language_type)) {
244       for (ConstString candidate :
245            language->GetPossibleFormattersMatches(valobj, use_dynamic)) {
246         entries.push_back(
247             {candidate,
248              reason | lldb_private::eFormatterChoiceCriterionLanguagePlugin,
249              did_strip_ptr, did_strip_ref, did_strip_typedef});
250       }
251     }
252   }
253 
254   // try to strip typedef chains
255   if (compiler_type.IsTypedefType()) {
256     CompilerType deffed_type = compiler_type.GetTypedefedType();
257     GetPossibleMatches(
258         valobj, deffed_type,
259         reason | lldb_private::eFormatterChoiceCriterionNavigatedTypedefs,
260         use_dynamic, entries, did_strip_ptr, did_strip_ref, true);
261   }
262 
263   if (root_level) {
264     do {
265       if (!compiler_type.IsValid())
266         break;
267 
268       CompilerType unqual_compiler_ast_type =
269           compiler_type.GetFullyUnqualifiedType();
270       if (!unqual_compiler_ast_type.IsValid())
271         break;
272       if (unqual_compiler_ast_type.GetOpaqueQualType() !=
273           compiler_type.GetOpaqueQualType())
274         GetPossibleMatches(valobj, unqual_compiler_ast_type, reason,
275                            use_dynamic, entries, did_strip_ptr, did_strip_ref,
276                            did_strip_typedef);
277     } while (false);
278 
279     // if all else fails, go to static type
280     if (valobj.IsDynamic()) {
281       lldb::ValueObjectSP static_value_sp(valobj.GetStaticValue());
282       if (static_value_sp)
283         GetPossibleMatches(
284             *static_value_sp.get(), static_value_sp->GetCompilerType(),
285             reason | lldb_private::eFormatterChoiceCriterionWentToStaticValue,
286             use_dynamic, entries, did_strip_ptr, did_strip_ref,
287             did_strip_typedef, true);
288     }
289   }
290 }
291 
292 lldb::TypeFormatImplSP
293 FormatManager::GetFormatForType(lldb::TypeNameSpecifierImplSP type_sp) {
294   if (!type_sp)
295     return lldb::TypeFormatImplSP();
296   lldb::TypeFormatImplSP format_chosen_sp;
297   uint32_t num_categories = m_categories_map.GetCount();
298   lldb::TypeCategoryImplSP category_sp;
299   uint32_t prio_category = UINT32_MAX;
300   for (uint32_t category_id = 0; category_id < num_categories; category_id++) {
301     category_sp = GetCategoryAtIndex(category_id);
302     if (!category_sp->IsEnabled())
303       continue;
304     lldb::TypeFormatImplSP format_current_sp =
305         category_sp->GetFormatForType(type_sp);
306     if (format_current_sp &&
307         (format_chosen_sp.get() == nullptr ||
308          (prio_category > category_sp->GetEnabledPosition()))) {
309       prio_category = category_sp->GetEnabledPosition();
310       format_chosen_sp = format_current_sp;
311     }
312   }
313   return format_chosen_sp;
314 }
315 
316 lldb::TypeSummaryImplSP
317 FormatManager::GetSummaryForType(lldb::TypeNameSpecifierImplSP type_sp) {
318   if (!type_sp)
319     return lldb::TypeSummaryImplSP();
320   lldb::TypeSummaryImplSP summary_chosen_sp;
321   uint32_t num_categories = m_categories_map.GetCount();
322   lldb::TypeCategoryImplSP category_sp;
323   uint32_t prio_category = UINT32_MAX;
324   for (uint32_t category_id = 0; category_id < num_categories; category_id++) {
325     category_sp = GetCategoryAtIndex(category_id);
326     if (!category_sp->IsEnabled())
327       continue;
328     lldb::TypeSummaryImplSP summary_current_sp =
329         category_sp->GetSummaryForType(type_sp);
330     if (summary_current_sp &&
331         (summary_chosen_sp.get() == nullptr ||
332          (prio_category > category_sp->GetEnabledPosition()))) {
333       prio_category = category_sp->GetEnabledPosition();
334       summary_chosen_sp = summary_current_sp;
335     }
336   }
337   return summary_chosen_sp;
338 }
339 
340 lldb::TypeFilterImplSP
341 FormatManager::GetFilterForType(lldb::TypeNameSpecifierImplSP type_sp) {
342   if (!type_sp)
343     return lldb::TypeFilterImplSP();
344   lldb::TypeFilterImplSP filter_chosen_sp;
345   uint32_t num_categories = m_categories_map.GetCount();
346   lldb::TypeCategoryImplSP category_sp;
347   uint32_t prio_category = UINT32_MAX;
348   for (uint32_t category_id = 0; category_id < num_categories; category_id++) {
349     category_sp = GetCategoryAtIndex(category_id);
350     if (!category_sp->IsEnabled())
351       continue;
352     lldb::TypeFilterImplSP filter_current_sp(
353         (TypeFilterImpl *)category_sp->GetFilterForType(type_sp).get());
354     if (filter_current_sp &&
355         (filter_chosen_sp.get() == nullptr ||
356          (prio_category > category_sp->GetEnabledPosition()))) {
357       prio_category = category_sp->GetEnabledPosition();
358       filter_chosen_sp = filter_current_sp;
359     }
360   }
361   return filter_chosen_sp;
362 }
363 
364 lldb::ScriptedSyntheticChildrenSP
365 FormatManager::GetSyntheticForType(lldb::TypeNameSpecifierImplSP type_sp) {
366   if (!type_sp)
367     return lldb::ScriptedSyntheticChildrenSP();
368   lldb::ScriptedSyntheticChildrenSP synth_chosen_sp;
369   uint32_t num_categories = m_categories_map.GetCount();
370   lldb::TypeCategoryImplSP category_sp;
371   uint32_t prio_category = UINT32_MAX;
372   for (uint32_t category_id = 0; category_id < num_categories; category_id++) {
373     category_sp = GetCategoryAtIndex(category_id);
374     if (!category_sp->IsEnabled())
375       continue;
376     lldb::ScriptedSyntheticChildrenSP synth_current_sp(
377         (ScriptedSyntheticChildren *)category_sp->GetSyntheticForType(type_sp)
378             .get());
379     if (synth_current_sp &&
380         (synth_chosen_sp.get() == nullptr ||
381          (prio_category > category_sp->GetEnabledPosition()))) {
382       prio_category = category_sp->GetEnabledPosition();
383       synth_chosen_sp = synth_current_sp;
384     }
385   }
386   return synth_chosen_sp;
387 }
388 
389 void FormatManager::ForEachCategory(TypeCategoryMap::ForEachCallback callback) {
390   m_categories_map.ForEach(callback);
391   std::lock_guard<std::recursive_mutex> guard(m_language_categories_mutex);
392   for (const auto &entry : m_language_categories_map) {
393     if (auto category_sp = entry.second->GetCategory()) {
394       if (!callback(category_sp))
395         break;
396     }
397   }
398 }
399 
400 lldb::TypeCategoryImplSP
401 FormatManager::GetCategory(ConstString category_name, bool can_create) {
402   if (!category_name)
403     return GetCategory(m_default_category_name);
404   lldb::TypeCategoryImplSP category;
405   if (m_categories_map.Get(category_name, category))
406     return category;
407 
408   if (!can_create)
409     return lldb::TypeCategoryImplSP();
410 
411   m_categories_map.Add(
412       category_name,
413       lldb::TypeCategoryImplSP(new TypeCategoryImpl(this, category_name)));
414   return GetCategory(category_name);
415 }
416 
417 lldb::Format FormatManager::GetSingleItemFormat(lldb::Format vector_format) {
418   switch (vector_format) {
419   case eFormatVectorOfChar:
420     return eFormatCharArray;
421 
422   case eFormatVectorOfSInt8:
423   case eFormatVectorOfSInt16:
424   case eFormatVectorOfSInt32:
425   case eFormatVectorOfSInt64:
426     return eFormatDecimal;
427 
428   case eFormatVectorOfUInt8:
429   case eFormatVectorOfUInt16:
430   case eFormatVectorOfUInt32:
431   case eFormatVectorOfUInt64:
432   case eFormatVectorOfUInt128:
433     return eFormatHex;
434 
435   case eFormatVectorOfFloat16:
436   case eFormatVectorOfFloat32:
437   case eFormatVectorOfFloat64:
438     return eFormatFloat;
439 
440   default:
441     return lldb::eFormatInvalid;
442   }
443 }
444 
445 bool FormatManager::ShouldPrintAsOneLiner(ValueObject &valobj) {
446   // if settings say no oneline whatsoever
447   if (valobj.GetTargetSP().get() &&
448       !valobj.GetTargetSP()->GetDebugger().GetAutoOneLineSummaries())
449     return false; // then don't oneline
450 
451   // if this object has a summary, then ask the summary
452   if (valobj.GetSummaryFormat().get() != nullptr)
453     return valobj.GetSummaryFormat()->IsOneLiner();
454 
455   // no children, no party
456   if (valobj.GetNumChildren() == 0)
457     return false;
458 
459   // ask the type if it has any opinion about this eLazyBoolCalculate == no
460   // opinion; other values should be self explanatory
461   CompilerType compiler_type(valobj.GetCompilerType());
462   if (compiler_type.IsValid()) {
463     switch (compiler_type.ShouldPrintAsOneLiner(&valobj)) {
464     case eLazyBoolNo:
465       return false;
466     case eLazyBoolYes:
467       return true;
468     case eLazyBoolCalculate:
469       break;
470     }
471   }
472 
473   size_t total_children_name_len = 0;
474 
475   for (size_t idx = 0; idx < valobj.GetNumChildren(); idx++) {
476     bool is_synth_val = false;
477     ValueObjectSP child_sp(valobj.GetChildAtIndex(idx, true));
478     // something is wrong here - bail out
479     if (!child_sp)
480       return false;
481 
482     // also ask the child's type if it has any opinion
483     CompilerType child_compiler_type(child_sp->GetCompilerType());
484     if (child_compiler_type.IsValid()) {
485       switch (child_compiler_type.ShouldPrintAsOneLiner(child_sp.get())) {
486       case eLazyBoolYes:
487       // an opinion of yes is only binding for the child, so keep going
488       case eLazyBoolCalculate:
489         break;
490       case eLazyBoolNo:
491         // but if the child says no, then it's a veto on the whole thing
492         return false;
493       }
494     }
495 
496     // if we decided to define synthetic children for a type, we probably care
497     // enough to show them, but avoid nesting children in children
498     if (child_sp->GetSyntheticChildren().get() != nullptr) {
499       ValueObjectSP synth_sp(child_sp->GetSyntheticValue());
500       // wait.. wat? just get out of here..
501       if (!synth_sp)
502         return false;
503       // but if we only have them to provide a value, keep going
504       if (!synth_sp->MightHaveChildren() &&
505           synth_sp->DoesProvideSyntheticValue())
506         is_synth_val = true;
507       else
508         return false;
509     }
510 
511     total_children_name_len += child_sp->GetName().GetLength();
512 
513     // 50 itself is a "randomly" chosen number - the idea is that
514     // overly long structs should not get this treatment
515     // FIXME: maybe make this a user-tweakable setting?
516     if (total_children_name_len > 50)
517       return false;
518 
519     // if a summary is there..
520     if (child_sp->GetSummaryFormat()) {
521       // and it wants children, then bail out
522       if (child_sp->GetSummaryFormat()->DoesPrintChildren(child_sp.get()))
523         return false;
524     }
525 
526     // if this child has children..
527     if (child_sp->GetNumChildren()) {
528       // ...and no summary...
529       // (if it had a summary and the summary wanted children, we would have
530       // bailed out anyway
531       //  so this only makes us bail out if this has no summary and we would
532       //  then print children)
533       if (!child_sp->GetSummaryFormat() && !is_synth_val) // but again only do
534                                                           // that if not a
535                                                           // synthetic valued
536                                                           // child
537         return false;                                     // then bail out
538     }
539   }
540   return true;
541 }
542 
543 ConstString FormatManager::GetValidTypeName(ConstString type) {
544   return ::GetValidTypeName_Impl(type);
545 }
546 
547 ConstString FormatManager::GetTypeForCache(ValueObject &valobj,
548                                            lldb::DynamicValueType use_dynamic) {
549   ValueObjectSP valobj_sp = valobj.GetQualifiedRepresentationIfAvailable(
550       use_dynamic, valobj.IsSynthetic());
551   if (valobj_sp && valobj_sp->GetCompilerType().IsValid()) {
552     if (!valobj_sp->GetCompilerType().IsMeaninglessWithoutDynamicResolution())
553       return valobj_sp->GetQualifiedTypeName();
554   }
555   return ConstString();
556 }
557 
558 std::vector<lldb::LanguageType>
559 FormatManager::GetCandidateLanguages(lldb::LanguageType lang_type) {
560   switch (lang_type) {
561   case lldb::eLanguageTypeC:
562   case lldb::eLanguageTypeC89:
563   case lldb::eLanguageTypeC99:
564   case lldb::eLanguageTypeC11:
565   case lldb::eLanguageTypeC_plus_plus:
566   case lldb::eLanguageTypeC_plus_plus_03:
567   case lldb::eLanguageTypeC_plus_plus_11:
568   case lldb::eLanguageTypeC_plus_plus_14:
569     return {lldb::eLanguageTypeC_plus_plus, lldb::eLanguageTypeObjC};
570   default:
571     return {lang_type};
572   }
573   llvm_unreachable("Fully covered switch");
574 }
575 
576 LanguageCategory *
577 FormatManager::GetCategoryForLanguage(lldb::LanguageType lang_type) {
578   std::lock_guard<std::recursive_mutex> guard(m_language_categories_mutex);
579   auto iter = m_language_categories_map.find(lang_type),
580        end = m_language_categories_map.end();
581   if (iter != end)
582     return iter->second.get();
583   LanguageCategory *lang_category = new LanguageCategory(lang_type);
584   m_language_categories_map[lang_type] =
585       LanguageCategory::UniquePointer(lang_category);
586   return lang_category;
587 }
588 
589 template <typename ImplSP>
590 ImplSP FormatManager::GetHardcoded(FormattersMatchData &match_data) {
591   ImplSP retval_sp;
592   for (lldb::LanguageType lang_type : match_data.GetCandidateLanguages()) {
593     if (LanguageCategory *lang_category = GetCategoryForLanguage(lang_type)) {
594       if (lang_category->GetHardcoded(*this, match_data, retval_sp))
595         return retval_sp;
596     }
597   }
598   return retval_sp;
599 }
600 
601 template <typename ImplSP>
602 ImplSP FormatManager::Get(ValueObject &valobj,
603                           lldb::DynamicValueType use_dynamic) {
604   FormattersMatchData match_data(valobj, use_dynamic);
605   if (ImplSP retval_sp = GetCached<ImplSP>(match_data))
606     return retval_sp;
607 
608   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_DATAFORMATTERS));
609 
610   LLDB_LOGF(log, "[%s] Search failed. Giving language a chance.", __FUNCTION__);
611   for (lldb::LanguageType lang_type : match_data.GetCandidateLanguages()) {
612     if (LanguageCategory *lang_category = GetCategoryForLanguage(lang_type)) {
613       ImplSP retval_sp;
614       if (lang_category->Get(match_data, retval_sp))
615         if (retval_sp) {
616           LLDB_LOGF(log, "[%s] Language search success. Returning.",
617                     __FUNCTION__);
618           return retval_sp;
619         }
620     }
621   }
622 
623   LLDB_LOGF(log, "[%s] Search failed. Giving hardcoded a chance.",
624             __FUNCTION__);
625   return GetHardcoded<ImplSP>(match_data);
626 }
627 
628 template <typename ImplSP>
629 ImplSP FormatManager::GetCached(FormattersMatchData &match_data) {
630   ImplSP retval_sp;
631   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_DATAFORMATTERS));
632   if (match_data.GetTypeForCache()) {
633     LLDB_LOGF(log, "\n\n[%s] Looking into cache for type %s", __FUNCTION__,
634               match_data.GetTypeForCache().AsCString("<invalid>"));
635     if (m_format_cache.Get(match_data.GetTypeForCache(), retval_sp)) {
636       if (log) {
637         LLDB_LOGF(log, "[%s] Cache search success. Returning.", __FUNCTION__);
638         LLDB_LOGV(log, "Cache hits: {0} - Cache Misses: {1}",
639                   m_format_cache.GetCacheHits(),
640                   m_format_cache.GetCacheMisses());
641       }
642       return retval_sp;
643     }
644     LLDB_LOGF(log, "[%s] Cache search failed. Going normal route",
645               __FUNCTION__);
646   }
647 
648   m_categories_map.Get(match_data, retval_sp);
649   if (match_data.GetTypeForCache() && (!retval_sp || !retval_sp->NonCacheable())) {
650     LLDB_LOGF(log, "[%s] Caching %p for type %s", __FUNCTION__,
651               static_cast<void *>(retval_sp.get()),
652               match_data.GetTypeForCache().AsCString("<invalid>"));
653     m_format_cache.Set(match_data.GetTypeForCache(), retval_sp);
654   }
655   LLDB_LOGV(log, "Cache hits: {0} - Cache Misses: {1}",
656             m_format_cache.GetCacheHits(), m_format_cache.GetCacheMisses());
657   return retval_sp;
658 }
659 
660 lldb::TypeFormatImplSP
661 FormatManager::GetFormat(ValueObject &valobj,
662                          lldb::DynamicValueType use_dynamic) {
663   return Get<lldb::TypeFormatImplSP>(valobj, use_dynamic);
664 }
665 
666 lldb::TypeSummaryImplSP
667 FormatManager::GetSummaryFormat(ValueObject &valobj,
668                                 lldb::DynamicValueType use_dynamic) {
669   return Get<lldb::TypeSummaryImplSP>(valobj, use_dynamic);
670 }
671 
672 lldb::SyntheticChildrenSP
673 FormatManager::GetSyntheticChildren(ValueObject &valobj,
674                                     lldb::DynamicValueType use_dynamic) {
675   return Get<lldb::SyntheticChildrenSP>(valobj, use_dynamic);
676 }
677 
678 FormatManager::FormatManager()
679     : m_last_revision(0), m_format_cache(), m_language_categories_mutex(),
680       m_language_categories_map(), m_named_summaries_map(this),
681       m_categories_map(this), m_default_category_name(ConstString("default")),
682       m_system_category_name(ConstString("system")),
683       m_vectortypes_category_name(ConstString("VectorTypes")) {
684   LoadSystemFormatters();
685   LoadVectorFormatters();
686 
687   EnableCategory(m_vectortypes_category_name, TypeCategoryMap::Last,
688                  lldb::eLanguageTypeObjC_plus_plus);
689   EnableCategory(m_system_category_name, TypeCategoryMap::Last,
690                  lldb::eLanguageTypeObjC_plus_plus);
691 }
692 
693 void FormatManager::LoadSystemFormatters() {
694   TypeSummaryImpl::Flags string_flags;
695   string_flags.SetCascades(true)
696       .SetSkipPointers(true)
697       .SetSkipReferences(false)
698       .SetDontShowChildren(true)
699       .SetDontShowValue(false)
700       .SetShowMembersOneLiner(false)
701       .SetHideItemNames(false);
702 
703   TypeSummaryImpl::Flags string_array_flags;
704   string_array_flags.SetCascades(true)
705       .SetSkipPointers(true)
706       .SetSkipReferences(false)
707       .SetDontShowChildren(true)
708       .SetDontShowValue(true)
709       .SetShowMembersOneLiner(false)
710       .SetHideItemNames(false);
711 
712   lldb::TypeSummaryImplSP string_format(
713       new StringSummaryFormat(string_flags, "${var%s}"));
714 
715   lldb::TypeSummaryImplSP string_array_format(
716       new StringSummaryFormat(string_array_flags, "${var%s}"));
717 
718   RegularExpression any_size_char_arr(llvm::StringRef("char \\[[0-9]+\\]"));
719 
720   TypeCategoryImpl::SharedPointer sys_category_sp =
721       GetCategory(m_system_category_name);
722 
723   sys_category_sp->GetTypeSummariesContainer()->Add(ConstString("char *"),
724                                                     string_format);
725   sys_category_sp->GetTypeSummariesContainer()->Add(
726       ConstString("unsigned char *"), string_format);
727   sys_category_sp->GetRegexTypeSummariesContainer()->Add(
728       std::move(any_size_char_arr), string_array_format);
729 
730   lldb::TypeSummaryImplSP ostype_summary(
731       new StringSummaryFormat(TypeSummaryImpl::Flags()
732                                   .SetCascades(false)
733                                   .SetSkipPointers(true)
734                                   .SetSkipReferences(true)
735                                   .SetDontShowChildren(true)
736                                   .SetDontShowValue(false)
737                                   .SetShowMembersOneLiner(false)
738                                   .SetHideItemNames(false),
739                               "${var%O}"));
740 
741   sys_category_sp->GetTypeSummariesContainer()->Add(ConstString("OSType"),
742                                                     ostype_summary);
743 
744   TypeFormatImpl::Flags fourchar_flags;
745   fourchar_flags.SetCascades(true).SetSkipPointers(true).SetSkipReferences(
746       true);
747 
748   AddFormat(sys_category_sp, lldb::eFormatOSType, ConstString("FourCharCode"),
749             fourchar_flags);
750 }
751 
752 void FormatManager::LoadVectorFormatters() {
753   TypeCategoryImpl::SharedPointer vectors_category_sp =
754       GetCategory(m_vectortypes_category_name);
755 
756   TypeSummaryImpl::Flags vector_flags;
757   vector_flags.SetCascades(true)
758       .SetSkipPointers(true)
759       .SetSkipReferences(false)
760       .SetDontShowChildren(true)
761       .SetDontShowValue(false)
762       .SetShowMembersOneLiner(true)
763       .SetHideItemNames(true);
764 
765   AddStringSummary(vectors_category_sp, "${var.uint128}",
766                    ConstString("builtin_type_vec128"), vector_flags);
767 
768   AddStringSummary(vectors_category_sp, "", ConstString("float [4]"),
769                    vector_flags);
770   AddStringSummary(vectors_category_sp, "", ConstString("int32_t [4]"),
771                    vector_flags);
772   AddStringSummary(vectors_category_sp, "", ConstString("int16_t [8]"),
773                    vector_flags);
774   AddStringSummary(vectors_category_sp, "", ConstString("vDouble"),
775                    vector_flags);
776   AddStringSummary(vectors_category_sp, "", ConstString("vFloat"),
777                    vector_flags);
778   AddStringSummary(vectors_category_sp, "", ConstString("vSInt8"),
779                    vector_flags);
780   AddStringSummary(vectors_category_sp, "", ConstString("vSInt16"),
781                    vector_flags);
782   AddStringSummary(vectors_category_sp, "", ConstString("vSInt32"),
783                    vector_flags);
784   AddStringSummary(vectors_category_sp, "", ConstString("vUInt16"),
785                    vector_flags);
786   AddStringSummary(vectors_category_sp, "", ConstString("vUInt8"),
787                    vector_flags);
788   AddStringSummary(vectors_category_sp, "", ConstString("vUInt16"),
789                    vector_flags);
790   AddStringSummary(vectors_category_sp, "", ConstString("vUInt32"),
791                    vector_flags);
792   AddStringSummary(vectors_category_sp, "", ConstString("vBool32"),
793                    vector_flags);
794 }
795