xref: /llvm-project/lldb/source/DataFormatters/FormatManager.cpp (revision 7034794b314d9de808de004d22b47f18d134757d)
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 lldb::TypeValidatorImplSP
390 FormatManager::GetValidatorForType(lldb::TypeNameSpecifierImplSP type_sp) {
391   if (!type_sp)
392     return lldb::TypeValidatorImplSP();
393   lldb::TypeValidatorImplSP validator_chosen_sp;
394   uint32_t num_categories = m_categories_map.GetCount();
395   lldb::TypeCategoryImplSP category_sp;
396   uint32_t prio_category = UINT32_MAX;
397   for (uint32_t category_id = 0; category_id < num_categories; category_id++) {
398     category_sp = GetCategoryAtIndex(category_id);
399     if (!category_sp->IsEnabled())
400       continue;
401     lldb::TypeValidatorImplSP validator_current_sp(
402         category_sp->GetValidatorForType(type_sp).get());
403     if (validator_current_sp &&
404         (validator_chosen_sp.get() == nullptr ||
405          (prio_category > category_sp->GetEnabledPosition()))) {
406       prio_category = category_sp->GetEnabledPosition();
407       validator_chosen_sp = validator_current_sp;
408     }
409   }
410   return validator_chosen_sp;
411 }
412 
413 void FormatManager::ForEachCategory(TypeCategoryMap::ForEachCallback callback) {
414   m_categories_map.ForEach(callback);
415   std::lock_guard<std::recursive_mutex> guard(m_language_categories_mutex);
416   for (const auto &entry : m_language_categories_map) {
417     if (auto category_sp = entry.second->GetCategory()) {
418       if (!callback(category_sp))
419         break;
420     }
421   }
422 }
423 
424 lldb::TypeCategoryImplSP
425 FormatManager::GetCategory(ConstString category_name, bool can_create) {
426   if (!category_name)
427     return GetCategory(m_default_category_name);
428   lldb::TypeCategoryImplSP category;
429   if (m_categories_map.Get(category_name, category))
430     return category;
431 
432   if (!can_create)
433     return lldb::TypeCategoryImplSP();
434 
435   m_categories_map.Add(
436       category_name,
437       lldb::TypeCategoryImplSP(new TypeCategoryImpl(this, category_name)));
438   return GetCategory(category_name);
439 }
440 
441 lldb::Format FormatManager::GetSingleItemFormat(lldb::Format vector_format) {
442   switch (vector_format) {
443   case eFormatVectorOfChar:
444     return eFormatCharArray;
445 
446   case eFormatVectorOfSInt8:
447   case eFormatVectorOfSInt16:
448   case eFormatVectorOfSInt32:
449   case eFormatVectorOfSInt64:
450     return eFormatDecimal;
451 
452   case eFormatVectorOfUInt8:
453   case eFormatVectorOfUInt16:
454   case eFormatVectorOfUInt32:
455   case eFormatVectorOfUInt64:
456   case eFormatVectorOfUInt128:
457     return eFormatHex;
458 
459   case eFormatVectorOfFloat16:
460   case eFormatVectorOfFloat32:
461   case eFormatVectorOfFloat64:
462     return eFormatFloat;
463 
464   default:
465     return lldb::eFormatInvalid;
466   }
467 }
468 
469 bool FormatManager::ShouldPrintAsOneLiner(ValueObject &valobj) {
470   // if settings say no oneline whatsoever
471   if (valobj.GetTargetSP().get() &&
472       !valobj.GetTargetSP()->GetDebugger().GetAutoOneLineSummaries())
473     return false; // then don't oneline
474 
475   // if this object has a summary, then ask the summary
476   if (valobj.GetSummaryFormat().get() != nullptr)
477     return valobj.GetSummaryFormat()->IsOneLiner();
478 
479   // no children, no party
480   if (valobj.GetNumChildren() == 0)
481     return false;
482 
483   // ask the type if it has any opinion about this eLazyBoolCalculate == no
484   // opinion; other values should be self explanatory
485   CompilerType compiler_type(valobj.GetCompilerType());
486   if (compiler_type.IsValid()) {
487     switch (compiler_type.ShouldPrintAsOneLiner(&valobj)) {
488     case eLazyBoolNo:
489       return false;
490     case eLazyBoolYes:
491       return true;
492     case eLazyBoolCalculate:
493       break;
494     }
495   }
496 
497   size_t total_children_name_len = 0;
498 
499   for (size_t idx = 0; idx < valobj.GetNumChildren(); idx++) {
500     bool is_synth_val = false;
501     ValueObjectSP child_sp(valobj.GetChildAtIndex(idx, true));
502     // something is wrong here - bail out
503     if (!child_sp)
504       return false;
505 
506     // also ask the child's type if it has any opinion
507     CompilerType child_compiler_type(child_sp->GetCompilerType());
508     if (child_compiler_type.IsValid()) {
509       switch (child_compiler_type.ShouldPrintAsOneLiner(child_sp.get())) {
510       case eLazyBoolYes:
511       // an opinion of yes is only binding for the child, so keep going
512       case eLazyBoolCalculate:
513         break;
514       case eLazyBoolNo:
515         // but if the child says no, then it's a veto on the whole thing
516         return false;
517       }
518     }
519 
520     // if we decided to define synthetic children for a type, we probably care
521     // enough to show them, but avoid nesting children in children
522     if (child_sp->GetSyntheticChildren().get() != nullptr) {
523       ValueObjectSP synth_sp(child_sp->GetSyntheticValue());
524       // wait.. wat? just get out of here..
525       if (!synth_sp)
526         return false;
527       // but if we only have them to provide a value, keep going
528       if (!synth_sp->MightHaveChildren() &&
529           synth_sp->DoesProvideSyntheticValue())
530         is_synth_val = true;
531       else
532         return false;
533     }
534 
535     total_children_name_len += child_sp->GetName().GetLength();
536 
537     // 50 itself is a "randomly" chosen number - the idea is that
538     // overly long structs should not get this treatment
539     // FIXME: maybe make this a user-tweakable setting?
540     if (total_children_name_len > 50)
541       return false;
542 
543     // if a summary is there..
544     if (child_sp->GetSummaryFormat()) {
545       // and it wants children, then bail out
546       if (child_sp->GetSummaryFormat()->DoesPrintChildren(child_sp.get()))
547         return false;
548     }
549 
550     // if this child has children..
551     if (child_sp->GetNumChildren()) {
552       // ...and no summary...
553       // (if it had a summary and the summary wanted children, we would have
554       // bailed out anyway
555       //  so this only makes us bail out if this has no summary and we would
556       //  then print children)
557       if (!child_sp->GetSummaryFormat() && !is_synth_val) // but again only do
558                                                           // that if not a
559                                                           // synthetic valued
560                                                           // child
561         return false;                                     // then bail out
562     }
563   }
564   return true;
565 }
566 
567 ConstString FormatManager::GetValidTypeName(ConstString type) {
568   return ::GetValidTypeName_Impl(type);
569 }
570 
571 ConstString FormatManager::GetTypeForCache(ValueObject &valobj,
572                                            lldb::DynamicValueType use_dynamic) {
573   ValueObjectSP valobj_sp = valobj.GetQualifiedRepresentationIfAvailable(
574       use_dynamic, valobj.IsSynthetic());
575   if (valobj_sp && valobj_sp->GetCompilerType().IsValid()) {
576     if (!valobj_sp->GetCompilerType().IsMeaninglessWithoutDynamicResolution())
577       return valobj_sp->GetQualifiedTypeName();
578   }
579   return ConstString();
580 }
581 
582 std::vector<lldb::LanguageType>
583 FormatManager::GetCandidateLanguages(lldb::LanguageType lang_type) {
584   switch (lang_type) {
585   case lldb::eLanguageTypeC:
586   case lldb::eLanguageTypeC89:
587   case lldb::eLanguageTypeC99:
588   case lldb::eLanguageTypeC11:
589   case lldb::eLanguageTypeC_plus_plus:
590   case lldb::eLanguageTypeC_plus_plus_03:
591   case lldb::eLanguageTypeC_plus_plus_11:
592   case lldb::eLanguageTypeC_plus_plus_14:
593     return {lldb::eLanguageTypeC_plus_plus, lldb::eLanguageTypeObjC};
594   default:
595     return {lang_type};
596   }
597   llvm_unreachable("Fully covered switch");
598 }
599 
600 LanguageCategory *
601 FormatManager::GetCategoryForLanguage(lldb::LanguageType lang_type) {
602   std::lock_guard<std::recursive_mutex> guard(m_language_categories_mutex);
603   auto iter = m_language_categories_map.find(lang_type),
604        end = m_language_categories_map.end();
605   if (iter != end)
606     return iter->second.get();
607   LanguageCategory *lang_category = new LanguageCategory(lang_type);
608   m_language_categories_map[lang_type] =
609       LanguageCategory::UniquePointer(lang_category);
610   return lang_category;
611 }
612 
613 template <typename ImplSP>
614 ImplSP FormatManager::GetHardcoded(FormattersMatchData &match_data) {
615   ImplSP retval_sp;
616   for (lldb::LanguageType lang_type : match_data.GetCandidateLanguages()) {
617     if (LanguageCategory *lang_category = GetCategoryForLanguage(lang_type)) {
618       if (lang_category->GetHardcoded(*this, match_data, retval_sp))
619         return retval_sp;
620     }
621   }
622   return retval_sp;
623 }
624 
625 template <typename ImplSP> ImplSP
626 FormatManager::GetCached(ValueObject &valobj,
627                          lldb::DynamicValueType use_dynamic) {
628   ImplSP retval_sp;
629   FormattersMatchData match_data(valobj, use_dynamic);
630   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_DATAFORMATTERS));
631   if (match_data.GetTypeForCache()) {
632     LLDB_LOGF(log, "\n\n[%s] Looking into cache for type %s", __FUNCTION__,
633               match_data.GetTypeForCache().AsCString("<invalid>"));
634     if (m_format_cache.Get(match_data.GetTypeForCache(), retval_sp)) {
635       if (log) {
636         LLDB_LOGF(log, "[%s] Cache search success. Returning.", __FUNCTION__);
637         LLDB_LOGV(log, "Cache hits: {0} - Cache Misses: {1}",
638                   m_format_cache.GetCacheHits(),
639                   m_format_cache.GetCacheMisses());
640       }
641       return retval_sp;
642     }
643     LLDB_LOGF(log, "[%s] Cache search failed. Going normal route",
644               __FUNCTION__);
645   }
646 
647   m_categories_map.Get(match_data, retval_sp);
648   if (!retval_sp) {
649     LLDB_LOGF(log, "[%s] Search failed. Giving language a chance.",
650               __FUNCTION__);
651     for (lldb::LanguageType lang_type : match_data.GetCandidateLanguages()) {
652       if (LanguageCategory *lang_category = GetCategoryForLanguage(lang_type)) {
653         if (lang_category->Get(match_data, retval_sp))
654           break;
655       }
656     }
657     if (retval_sp) {
658       LLDB_LOGF(log, "[%s] Language search success. Returning.", __FUNCTION__);
659       return retval_sp;
660     }
661   }
662   if (!retval_sp) {
663     LLDB_LOGF(log, "[%s] Search failed. Giving hardcoded a chance.", __FUNCTION__);
664     retval_sp = GetHardcoded<ImplSP>(match_data);
665   }
666 
667   if (match_data.GetTypeForCache() && (!retval_sp || !retval_sp->NonCacheable())) {
668     LLDB_LOGF(log, "[%s] Caching %p for type %s", __FUNCTION__,
669               static_cast<void *>(retval_sp.get()),
670               match_data.GetTypeForCache().AsCString("<invalid>"));
671     m_format_cache.Set(match_data.GetTypeForCache(), retval_sp);
672   }
673   LLDB_LOGV(log, "Cache hits: {0} - Cache Misses: {1}",
674             m_format_cache.GetCacheHits(), m_format_cache.GetCacheMisses());
675   return retval_sp;
676 }
677 
678 lldb::TypeFormatImplSP
679 FormatManager::GetFormat(ValueObject &valobj,
680                          lldb::DynamicValueType use_dynamic) {
681   return GetCached<lldb::TypeFormatImplSP>(valobj, use_dynamic);
682 }
683 
684 lldb::TypeSummaryImplSP
685 FormatManager::GetSummaryFormat(ValueObject &valobj,
686                                 lldb::DynamicValueType use_dynamic) {
687   return GetCached<lldb::TypeSummaryImplSP>(valobj, use_dynamic);
688 }
689 
690 lldb::SyntheticChildrenSP
691 FormatManager::GetSyntheticChildren(ValueObject &valobj,
692                                     lldb::DynamicValueType use_dynamic) {
693   return GetCached<lldb::SyntheticChildrenSP>(valobj, use_dynamic);
694 }
695 
696 lldb::TypeValidatorImplSP
697 FormatManager::GetValidator(ValueObject &valobj,
698                             lldb::DynamicValueType use_dynamic) {
699   return GetCached<lldb::TypeValidatorImplSP>(valobj, use_dynamic);
700 }
701 
702 FormatManager::FormatManager()
703     : m_last_revision(0), m_format_cache(), m_language_categories_mutex(),
704       m_language_categories_map(), m_named_summaries_map(this),
705       m_categories_map(this), m_default_category_name(ConstString("default")),
706       m_system_category_name(ConstString("system")),
707       m_vectortypes_category_name(ConstString("VectorTypes")) {
708   LoadSystemFormatters();
709   LoadVectorFormatters();
710 
711   EnableCategory(m_vectortypes_category_name, TypeCategoryMap::Last,
712                  lldb::eLanguageTypeObjC_plus_plus);
713   EnableCategory(m_system_category_name, TypeCategoryMap::Last,
714                  lldb::eLanguageTypeObjC_plus_plus);
715 }
716 
717 void FormatManager::LoadSystemFormatters() {
718   TypeSummaryImpl::Flags string_flags;
719   string_flags.SetCascades(true)
720       .SetSkipPointers(true)
721       .SetSkipReferences(false)
722       .SetDontShowChildren(true)
723       .SetDontShowValue(false)
724       .SetShowMembersOneLiner(false)
725       .SetHideItemNames(false);
726 
727   TypeSummaryImpl::Flags string_array_flags;
728   string_array_flags.SetCascades(true)
729       .SetSkipPointers(true)
730       .SetSkipReferences(false)
731       .SetDontShowChildren(true)
732       .SetDontShowValue(true)
733       .SetShowMembersOneLiner(false)
734       .SetHideItemNames(false);
735 
736   lldb::TypeSummaryImplSP string_format(
737       new StringSummaryFormat(string_flags, "${var%s}"));
738 
739   lldb::TypeSummaryImplSP string_array_format(
740       new StringSummaryFormat(string_array_flags, "${var%s}"));
741 
742   RegularExpression any_size_char_arr(llvm::StringRef("char \\[[0-9]+\\]"));
743 
744   TypeCategoryImpl::SharedPointer sys_category_sp =
745       GetCategory(m_system_category_name);
746 
747   sys_category_sp->GetTypeSummariesContainer()->Add(ConstString("char *"),
748                                                     string_format);
749   sys_category_sp->GetTypeSummariesContainer()->Add(
750       ConstString("unsigned char *"), string_format);
751   sys_category_sp->GetRegexTypeSummariesContainer()->Add(
752       std::move(any_size_char_arr), string_array_format);
753 
754   lldb::TypeSummaryImplSP ostype_summary(
755       new StringSummaryFormat(TypeSummaryImpl::Flags()
756                                   .SetCascades(false)
757                                   .SetSkipPointers(true)
758                                   .SetSkipReferences(true)
759                                   .SetDontShowChildren(true)
760                                   .SetDontShowValue(false)
761                                   .SetShowMembersOneLiner(false)
762                                   .SetHideItemNames(false),
763                               "${var%O}"));
764 
765   sys_category_sp->GetTypeSummariesContainer()->Add(ConstString("OSType"),
766                                                     ostype_summary);
767 
768   TypeFormatImpl::Flags fourchar_flags;
769   fourchar_flags.SetCascades(true).SetSkipPointers(true).SetSkipReferences(
770       true);
771 
772   AddFormat(sys_category_sp, lldb::eFormatOSType, ConstString("FourCharCode"),
773             fourchar_flags);
774 }
775 
776 void FormatManager::LoadVectorFormatters() {
777   TypeCategoryImpl::SharedPointer vectors_category_sp =
778       GetCategory(m_vectortypes_category_name);
779 
780   TypeSummaryImpl::Flags vector_flags;
781   vector_flags.SetCascades(true)
782       .SetSkipPointers(true)
783       .SetSkipReferences(false)
784       .SetDontShowChildren(true)
785       .SetDontShowValue(false)
786       .SetShowMembersOneLiner(true)
787       .SetHideItemNames(true);
788 
789   AddStringSummary(vectors_category_sp, "${var.uint128}",
790                    ConstString("builtin_type_vec128"), vector_flags);
791 
792   AddStringSummary(vectors_category_sp, "", ConstString("float [4]"),
793                    vector_flags);
794   AddStringSummary(vectors_category_sp, "", ConstString("int32_t [4]"),
795                    vector_flags);
796   AddStringSummary(vectors_category_sp, "", ConstString("int16_t [8]"),
797                    vector_flags);
798   AddStringSummary(vectors_category_sp, "", ConstString("vDouble"),
799                    vector_flags);
800   AddStringSummary(vectors_category_sp, "", ConstString("vFloat"),
801                    vector_flags);
802   AddStringSummary(vectors_category_sp, "", ConstString("vSInt8"),
803                    vector_flags);
804   AddStringSummary(vectors_category_sp, "", ConstString("vSInt16"),
805                    vector_flags);
806   AddStringSummary(vectors_category_sp, "", ConstString("vSInt32"),
807                    vector_flags);
808   AddStringSummary(vectors_category_sp, "", ConstString("vUInt16"),
809                    vector_flags);
810   AddStringSummary(vectors_category_sp, "", ConstString("vUInt8"),
811                    vector_flags);
812   AddStringSummary(vectors_category_sp, "", ConstString("vUInt16"),
813                    vector_flags);
814   AddStringSummary(vectors_category_sp, "", ConstString("vUInt32"),
815                    vector_flags);
816   AddStringSummary(vectors_category_sp, "", ConstString("vBool32"),
817                    vector_flags);
818 }
819