xref: /llvm-project/lldb/source/DataFormatters/FormatManager.cpp (revision 63e5fb76ecfed3434252868d8cf07d676f979f2f)
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 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 
74 static uint32_t g_num_format_infos = llvm::array_lengthof(g_format_infos);
75 
76 static bool GetFormatFromFormatChar(char format_char, Format &format) {
77   for (uint32_t i = 0; i < g_num_format_infos; ++i) {
78     if (g_format_infos[i].format_char == format_char) {
79       format = g_format_infos[i].format;
80       return true;
81     }
82   }
83   format = eFormatInvalid;
84   return false;
85 }
86 
87 static bool GetFormatFromFormatName(const char *format_name,
88                                     bool partial_match_ok, Format &format) {
89   uint32_t i;
90   for (i = 0; i < g_num_format_infos; ++i) {
91     if (strcasecmp(g_format_infos[i].format_name, format_name) == 0) {
92       format = g_format_infos[i].format;
93       return true;
94     }
95   }
96 
97   if (partial_match_ok) {
98     for (i = 0; i < g_num_format_infos; ++i) {
99       if (strcasestr(g_format_infos[i].format_name, format_name) ==
100           g_format_infos[i].format_name) {
101         format = g_format_infos[i].format;
102         return true;
103       }
104     }
105   }
106   format = eFormatInvalid;
107   return false;
108 }
109 
110 void FormatManager::Changed() {
111   ++m_last_revision;
112   m_format_cache.Clear();
113   std::lock_guard<std::recursive_mutex> guard(m_language_categories_mutex);
114   for (auto &iter : m_language_categories_map) {
115     if (iter.second)
116       iter.second->GetFormatCache().Clear();
117   }
118 }
119 
120 bool FormatManager::GetFormatFromCString(const char *format_cstr,
121                                          bool partial_match_ok,
122                                          lldb::Format &format) {
123   bool success = false;
124   if (format_cstr && format_cstr[0]) {
125     if (format_cstr[1] == '\0') {
126       success = GetFormatFromFormatChar(format_cstr[0], format);
127       if (success)
128         return true;
129     }
130 
131     success = GetFormatFromFormatName(format_cstr, partial_match_ok, format);
132   }
133   if (!success)
134     format = eFormatInvalid;
135   return success;
136 }
137 
138 char FormatManager::GetFormatAsFormatChar(lldb::Format format) {
139   for (uint32_t i = 0; i < g_num_format_infos; ++i) {
140     if (g_format_infos[i].format == format)
141       return g_format_infos[i].format_char;
142   }
143   return '\0';
144 }
145 
146 const char *FormatManager::GetFormatAsCString(Format format) {
147   if (format >= eFormatDefault && format < kNumFormats)
148     return g_format_infos[format].format_name;
149   return nullptr;
150 }
151 
152 void FormatManager::EnableAllCategories() {
153   m_categories_map.EnableAllCategories();
154   std::lock_guard<std::recursive_mutex> guard(m_language_categories_mutex);
155   for (auto &iter : m_language_categories_map) {
156     if (iter.second)
157       iter.second->Enable();
158   }
159 }
160 
161 void FormatManager::DisableAllCategories() {
162   m_categories_map.DisableAllCategories();
163   std::lock_guard<std::recursive_mutex> guard(m_language_categories_mutex);
164   for (auto &iter : m_language_categories_map) {
165     if (iter.second)
166       iter.second->Disable();
167   }
168 }
169 
170 void FormatManager::GetPossibleMatches(
171     ValueObject &valobj, CompilerType compiler_type, uint32_t reason,
172     lldb::DynamicValueType use_dynamic, FormattersMatchVector &entries,
173     bool did_strip_ptr, bool did_strip_ref, bool did_strip_typedef,
174     bool root_level) {
175   compiler_type = compiler_type.GetTypeForFormatters();
176   ConstString type_name(compiler_type.GetConstTypeName());
177   if (valobj.GetBitfieldBitSize() > 0) {
178     StreamString sstring;
179     sstring.Printf("%s:%d", type_name.AsCString(), valobj.GetBitfieldBitSize());
180     ConstString bitfieldname(sstring.GetString());
181     entries.push_back(
182         {bitfieldname, 0, did_strip_ptr, did_strip_ref, did_strip_typedef});
183     reason |= lldb_private::eFormatterChoiceCriterionStrippedBitField;
184   }
185 
186   if (!compiler_type.IsMeaninglessWithoutDynamicResolution()) {
187     entries.push_back(
188         {type_name, reason, did_strip_ptr, did_strip_ref, did_strip_typedef});
189 
190     ConstString display_type_name(compiler_type.GetDisplayTypeName());
191     if (display_type_name != type_name)
192       entries.push_back({display_type_name, reason, did_strip_ptr,
193                          did_strip_ref, did_strip_typedef});
194   }
195 
196   for (bool is_rvalue_ref = true, j = true;
197        j && compiler_type.IsReferenceType(nullptr, &is_rvalue_ref); j = false) {
198     CompilerType non_ref_type = compiler_type.GetNonReferenceType();
199     GetPossibleMatches(
200         valobj, non_ref_type,
201         reason |
202             lldb_private::eFormatterChoiceCriterionStrippedPointerReference,
203         use_dynamic, entries, did_strip_ptr, true, did_strip_typedef);
204     if (non_ref_type.IsTypedefType()) {
205       CompilerType deffed_referenced_type = non_ref_type.GetTypedefedType();
206       deffed_referenced_type =
207           is_rvalue_ref ? deffed_referenced_type.GetRValueReferenceType()
208                         : deffed_referenced_type.GetLValueReferenceType();
209       GetPossibleMatches(
210           valobj, deffed_referenced_type,
211           reason | lldb_private::eFormatterChoiceCriterionNavigatedTypedefs,
212           use_dynamic, entries, did_strip_ptr, did_strip_ref,
213           true); // this is not exactly the usual meaning of stripping typedefs
214     }
215   }
216 
217   if (compiler_type.IsPointerType()) {
218     CompilerType non_ptr_type = compiler_type.GetPointeeType();
219     GetPossibleMatches(
220         valobj, non_ptr_type,
221         reason |
222             lldb_private::eFormatterChoiceCriterionStrippedPointerReference,
223         use_dynamic, entries, true, did_strip_ref, did_strip_typedef);
224     if (non_ptr_type.IsTypedefType()) {
225       CompilerType deffed_pointed_type =
226           non_ptr_type.GetTypedefedType().GetPointerType();
227       GetPossibleMatches(
228           valobj, deffed_pointed_type,
229           reason | lldb_private::eFormatterChoiceCriterionNavigatedTypedefs,
230           use_dynamic, entries, did_strip_ptr, did_strip_ref,
231           true); // this is not exactly the usual meaning of stripping typedefs
232     }
233   }
234 
235   for (lldb::LanguageType language_type : GetCandidateLanguages(valobj)) {
236     if (Language *language = Language::FindPlugin(language_type)) {
237       for (ConstString candidate :
238            language->GetPossibleFormattersMatches(valobj, use_dynamic)) {
239         entries.push_back(
240             {candidate,
241              reason | lldb_private::eFormatterChoiceCriterionLanguagePlugin,
242              did_strip_ptr, did_strip_ref, did_strip_typedef});
243       }
244     }
245   }
246 
247   // try to strip typedef chains
248   if (compiler_type.IsTypedefType()) {
249     CompilerType deffed_type = compiler_type.GetTypedefedType();
250     GetPossibleMatches(
251         valobj, deffed_type,
252         reason | lldb_private::eFormatterChoiceCriterionNavigatedTypedefs,
253         use_dynamic, entries, did_strip_ptr, did_strip_ref, true);
254   }
255 
256   if (root_level) {
257     do {
258       if (!compiler_type.IsValid())
259         break;
260 
261       CompilerType unqual_compiler_ast_type =
262           compiler_type.GetFullyUnqualifiedType();
263       if (!unqual_compiler_ast_type.IsValid())
264         break;
265       if (unqual_compiler_ast_type.GetOpaqueQualType() !=
266           compiler_type.GetOpaqueQualType())
267         GetPossibleMatches(valobj, unqual_compiler_ast_type, reason,
268                            use_dynamic, entries, did_strip_ptr, did_strip_ref,
269                            did_strip_typedef);
270     } while (false);
271 
272     // if all else fails, go to static type
273     if (valobj.IsDynamic()) {
274       lldb::ValueObjectSP static_value_sp(valobj.GetStaticValue());
275       if (static_value_sp)
276         GetPossibleMatches(
277             *static_value_sp.get(), static_value_sp->GetCompilerType(),
278             reason | lldb_private::eFormatterChoiceCriterionWentToStaticValue,
279             use_dynamic, entries, did_strip_ptr, did_strip_ref,
280             did_strip_typedef, true);
281     }
282   }
283 }
284 
285 lldb::TypeFormatImplSP
286 FormatManager::GetFormatForType(lldb::TypeNameSpecifierImplSP type_sp) {
287   if (!type_sp)
288     return lldb::TypeFormatImplSP();
289   lldb::TypeFormatImplSP format_chosen_sp;
290   uint32_t num_categories = m_categories_map.GetCount();
291   lldb::TypeCategoryImplSP category_sp;
292   uint32_t prio_category = UINT32_MAX;
293   for (uint32_t category_id = 0; category_id < num_categories; category_id++) {
294     category_sp = GetCategoryAtIndex(category_id);
295     if (!category_sp->IsEnabled())
296       continue;
297     lldb::TypeFormatImplSP format_current_sp =
298         category_sp->GetFormatForType(type_sp);
299     if (format_current_sp &&
300         (format_chosen_sp.get() == nullptr ||
301          (prio_category > category_sp->GetEnabledPosition()))) {
302       prio_category = category_sp->GetEnabledPosition();
303       format_chosen_sp = format_current_sp;
304     }
305   }
306   return format_chosen_sp;
307 }
308 
309 lldb::TypeSummaryImplSP
310 FormatManager::GetSummaryForType(lldb::TypeNameSpecifierImplSP type_sp) {
311   if (!type_sp)
312     return lldb::TypeSummaryImplSP();
313   lldb::TypeSummaryImplSP summary_chosen_sp;
314   uint32_t num_categories = m_categories_map.GetCount();
315   lldb::TypeCategoryImplSP category_sp;
316   uint32_t prio_category = UINT32_MAX;
317   for (uint32_t category_id = 0; category_id < num_categories; category_id++) {
318     category_sp = GetCategoryAtIndex(category_id);
319     if (!category_sp->IsEnabled())
320       continue;
321     lldb::TypeSummaryImplSP summary_current_sp =
322         category_sp->GetSummaryForType(type_sp);
323     if (summary_current_sp &&
324         (summary_chosen_sp.get() == nullptr ||
325          (prio_category > category_sp->GetEnabledPosition()))) {
326       prio_category = category_sp->GetEnabledPosition();
327       summary_chosen_sp = summary_current_sp;
328     }
329   }
330   return summary_chosen_sp;
331 }
332 
333 lldb::TypeFilterImplSP
334 FormatManager::GetFilterForType(lldb::TypeNameSpecifierImplSP type_sp) {
335   if (!type_sp)
336     return lldb::TypeFilterImplSP();
337   lldb::TypeFilterImplSP filter_chosen_sp;
338   uint32_t num_categories = m_categories_map.GetCount();
339   lldb::TypeCategoryImplSP category_sp;
340   uint32_t prio_category = UINT32_MAX;
341   for (uint32_t category_id = 0; category_id < num_categories; category_id++) {
342     category_sp = GetCategoryAtIndex(category_id);
343     if (!category_sp->IsEnabled())
344       continue;
345     lldb::TypeFilterImplSP filter_current_sp(
346         (TypeFilterImpl *)category_sp->GetFilterForType(type_sp).get());
347     if (filter_current_sp &&
348         (filter_chosen_sp.get() == nullptr ||
349          (prio_category > category_sp->GetEnabledPosition()))) {
350       prio_category = category_sp->GetEnabledPosition();
351       filter_chosen_sp = filter_current_sp;
352     }
353   }
354   return filter_chosen_sp;
355 }
356 
357 lldb::ScriptedSyntheticChildrenSP
358 FormatManager::GetSyntheticForType(lldb::TypeNameSpecifierImplSP type_sp) {
359   if (!type_sp)
360     return lldb::ScriptedSyntheticChildrenSP();
361   lldb::ScriptedSyntheticChildrenSP synth_chosen_sp;
362   uint32_t num_categories = m_categories_map.GetCount();
363   lldb::TypeCategoryImplSP category_sp;
364   uint32_t prio_category = UINT32_MAX;
365   for (uint32_t category_id = 0; category_id < num_categories; category_id++) {
366     category_sp = GetCategoryAtIndex(category_id);
367     if (!category_sp->IsEnabled())
368       continue;
369     lldb::ScriptedSyntheticChildrenSP synth_current_sp(
370         (ScriptedSyntheticChildren *)category_sp->GetSyntheticForType(type_sp)
371             .get());
372     if (synth_current_sp &&
373         (synth_chosen_sp.get() == nullptr ||
374          (prio_category > category_sp->GetEnabledPosition()))) {
375       prio_category = category_sp->GetEnabledPosition();
376       synth_chosen_sp = synth_current_sp;
377     }
378   }
379   return synth_chosen_sp;
380 }
381 
382 lldb::TypeValidatorImplSP
383 FormatManager::GetValidatorForType(lldb::TypeNameSpecifierImplSP type_sp) {
384   if (!type_sp)
385     return lldb::TypeValidatorImplSP();
386   lldb::TypeValidatorImplSP validator_chosen_sp;
387   uint32_t num_categories = m_categories_map.GetCount();
388   lldb::TypeCategoryImplSP category_sp;
389   uint32_t prio_category = UINT32_MAX;
390   for (uint32_t category_id = 0; category_id < num_categories; category_id++) {
391     category_sp = GetCategoryAtIndex(category_id);
392     if (!category_sp->IsEnabled())
393       continue;
394     lldb::TypeValidatorImplSP validator_current_sp(
395         category_sp->GetValidatorForType(type_sp).get());
396     if (validator_current_sp &&
397         (validator_chosen_sp.get() == nullptr ||
398          (prio_category > category_sp->GetEnabledPosition()))) {
399       prio_category = category_sp->GetEnabledPosition();
400       validator_chosen_sp = validator_current_sp;
401     }
402   }
403   return validator_chosen_sp;
404 }
405 
406 void FormatManager::ForEachCategory(TypeCategoryMap::ForEachCallback callback) {
407   m_categories_map.ForEach(callback);
408   std::lock_guard<std::recursive_mutex> guard(m_language_categories_mutex);
409   for (const auto &entry : m_language_categories_map) {
410     if (auto category_sp = entry.second->GetCategory()) {
411       if (!callback(category_sp))
412         break;
413     }
414   }
415 }
416 
417 lldb::TypeCategoryImplSP
418 FormatManager::GetCategory(ConstString category_name, bool can_create) {
419   if (!category_name)
420     return GetCategory(m_default_category_name);
421   lldb::TypeCategoryImplSP category;
422   if (m_categories_map.Get(category_name, category))
423     return category;
424 
425   if (!can_create)
426     return lldb::TypeCategoryImplSP();
427 
428   m_categories_map.Add(
429       category_name,
430       lldb::TypeCategoryImplSP(new TypeCategoryImpl(this, category_name)));
431   return GetCategory(category_name);
432 }
433 
434 lldb::Format FormatManager::GetSingleItemFormat(lldb::Format vector_format) {
435   switch (vector_format) {
436   case eFormatVectorOfChar:
437     return eFormatCharArray;
438 
439   case eFormatVectorOfSInt8:
440   case eFormatVectorOfSInt16:
441   case eFormatVectorOfSInt32:
442   case eFormatVectorOfSInt64:
443     return eFormatDecimal;
444 
445   case eFormatVectorOfUInt8:
446   case eFormatVectorOfUInt16:
447   case eFormatVectorOfUInt32:
448   case eFormatVectorOfUInt64:
449   case eFormatVectorOfUInt128:
450     return eFormatHex;
451 
452   case eFormatVectorOfFloat16:
453   case eFormatVectorOfFloat32:
454   case eFormatVectorOfFloat64:
455     return eFormatFloat;
456 
457   default:
458     return lldb::eFormatInvalid;
459   }
460 }
461 
462 bool FormatManager::ShouldPrintAsOneLiner(ValueObject &valobj) {
463   // if settings say no oneline whatsoever
464   if (valobj.GetTargetSP().get() &&
465       !valobj.GetTargetSP()->GetDebugger().GetAutoOneLineSummaries())
466     return false; // then don't oneline
467 
468   // if this object has a summary, then ask the summary
469   if (valobj.GetSummaryFormat().get() != nullptr)
470     return valobj.GetSummaryFormat()->IsOneLiner();
471 
472   // no children, no party
473   if (valobj.GetNumChildren() == 0)
474     return false;
475 
476   // ask the type if it has any opinion about this eLazyBoolCalculate == no
477   // opinion; other values should be self explanatory
478   CompilerType compiler_type(valobj.GetCompilerType());
479   if (compiler_type.IsValid()) {
480     switch (compiler_type.ShouldPrintAsOneLiner(&valobj)) {
481     case eLazyBoolNo:
482       return false;
483     case eLazyBoolYes:
484       return true;
485     case eLazyBoolCalculate:
486       break;
487     }
488   }
489 
490   size_t total_children_name_len = 0;
491 
492   for (size_t idx = 0; idx < valobj.GetNumChildren(); idx++) {
493     bool is_synth_val = false;
494     ValueObjectSP child_sp(valobj.GetChildAtIndex(idx, true));
495     // something is wrong here - bail out
496     if (!child_sp)
497       return false;
498 
499     // also ask the child's type if it has any opinion
500     CompilerType child_compiler_type(child_sp->GetCompilerType());
501     if (child_compiler_type.IsValid()) {
502       switch (child_compiler_type.ShouldPrintAsOneLiner(child_sp.get())) {
503       case eLazyBoolYes:
504       // an opinion of yes is only binding for the child, so keep going
505       case eLazyBoolCalculate:
506         break;
507       case eLazyBoolNo:
508         // but if the child says no, then it's a veto on the whole thing
509         return false;
510       }
511     }
512 
513     // if we decided to define synthetic children for a type, we probably care
514     // enough to show them, but avoid nesting children in children
515     if (child_sp->GetSyntheticChildren().get() != nullptr) {
516       ValueObjectSP synth_sp(child_sp->GetSyntheticValue());
517       // wait.. wat? just get out of here..
518       if (!synth_sp)
519         return false;
520       // but if we only have them to provide a value, keep going
521       if (!synth_sp->MightHaveChildren() &&
522           synth_sp->DoesProvideSyntheticValue())
523         is_synth_val = true;
524       else
525         return false;
526     }
527 
528     total_children_name_len += child_sp->GetName().GetLength();
529 
530     // 50 itself is a "randomly" chosen number - the idea is that
531     // overly long structs should not get this treatment
532     // FIXME: maybe make this a user-tweakable setting?
533     if (total_children_name_len > 50)
534       return false;
535 
536     // if a summary is there..
537     if (child_sp->GetSummaryFormat()) {
538       // and it wants children, then bail out
539       if (child_sp->GetSummaryFormat()->DoesPrintChildren(child_sp.get()))
540         return false;
541     }
542 
543     // if this child has children..
544     if (child_sp->GetNumChildren()) {
545       // ...and no summary...
546       // (if it had a summary and the summary wanted children, we would have
547       // bailed out anyway
548       //  so this only makes us bail out if this has no summary and we would
549       //  then print children)
550       if (!child_sp->GetSummaryFormat() && !is_synth_val) // but again only do
551                                                           // that if not a
552                                                           // synthetic valued
553                                                           // child
554         return false;                                     // then bail out
555     }
556   }
557   return true;
558 }
559 
560 ConstString FormatManager::GetValidTypeName(ConstString type) {
561   return ::GetValidTypeName_Impl(type);
562 }
563 
564 ConstString FormatManager::GetTypeForCache(ValueObject &valobj,
565                                            lldb::DynamicValueType use_dynamic) {
566   ValueObjectSP valobj_sp = valobj.GetQualifiedRepresentationIfAvailable(
567       use_dynamic, valobj.IsSynthetic());
568   if (valobj_sp && valobj_sp->GetCompilerType().IsValid()) {
569     if (!valobj_sp->GetCompilerType().IsMeaninglessWithoutDynamicResolution())
570       return valobj_sp->GetQualifiedTypeName();
571   }
572   return ConstString();
573 }
574 
575 std::vector<lldb::LanguageType>
576 FormatManager::GetCandidateLanguages(ValueObject &valobj) {
577   lldb::LanguageType lang_type = valobj.GetObjectRuntimeLanguage();
578   return GetCandidateLanguages(lang_type);
579 }
580 
581 std::vector<lldb::LanguageType>
582 FormatManager::GetCandidateLanguages(lldb::LanguageType lang_type) {
583   switch (lang_type) {
584   case lldb::eLanguageTypeC:
585   case lldb::eLanguageTypeC89:
586   case lldb::eLanguageTypeC99:
587   case lldb::eLanguageTypeC11:
588   case lldb::eLanguageTypeC_plus_plus:
589   case lldb::eLanguageTypeC_plus_plus_03:
590   case lldb::eLanguageTypeC_plus_plus_11:
591   case lldb::eLanguageTypeC_plus_plus_14:
592     return {lldb::eLanguageTypeC_plus_plus, lldb::eLanguageTypeObjC};
593   default:
594     return {lang_type};
595   }
596 }
597 
598 LanguageCategory *
599 FormatManager::GetCategoryForLanguage(lldb::LanguageType lang_type) {
600   std::lock_guard<std::recursive_mutex> guard(m_language_categories_mutex);
601   auto iter = m_language_categories_map.find(lang_type),
602        end = m_language_categories_map.end();
603   if (iter != end)
604     return iter->second.get();
605   LanguageCategory *lang_category = new LanguageCategory(lang_type);
606   m_language_categories_map[lang_type] =
607       LanguageCategory::UniquePointer(lang_category);
608   return lang_category;
609 }
610 
611 lldb::TypeFormatImplSP
612 FormatManager::GetHardcodedFormat(FormattersMatchData &match_data) {
613   TypeFormatImplSP retval_sp;
614 
615   for (lldb::LanguageType lang_type : match_data.GetCandidateLanguages()) {
616     if (LanguageCategory *lang_category = GetCategoryForLanguage(lang_type)) {
617       if (lang_category->GetHardcoded(*this, match_data, retval_sp))
618         break;
619     }
620   }
621 
622   return retval_sp;
623 }
624 
625 lldb::TypeFormatImplSP
626 FormatManager::GetFormat(ValueObject &valobj,
627                          lldb::DynamicValueType use_dynamic) {
628   FormattersMatchData match_data(valobj, use_dynamic);
629 
630   TypeFormatImplSP retval;
631   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_DATAFORMATTERS));
632   if (match_data.GetTypeForCache()) {
633     LLDB_LOGF(log,
634               "\n\n[FormatManager::GetFormat] Looking into cache for type %s",
635               match_data.GetTypeForCache().AsCString("<invalid>"));
636     if (m_format_cache.GetFormat(match_data.GetTypeForCache(), retval)) {
637       if (log) {
638         LLDB_LOGF(
639             log, "[FormatManager::GetFormat] Cache search success. Returning.");
640         LLDB_LOGV(log, "Cache hits: {0} - Cache Misses: {1}",
641                   m_format_cache.GetCacheHits(),
642                   m_format_cache.GetCacheMisses());
643       }
644       return retval;
645     }
646     LLDB_LOGF(
647         log,
648         "[FormatManager::GetFormat] Cache search failed. Going normal route");
649   }
650 
651   retval = m_categories_map.GetFormat(match_data);
652   if (!retval) {
653     LLDB_LOGF(log,
654               "[FormatManager::GetFormat] Search failed. Giving language a "
655               "chance.");
656     for (lldb::LanguageType lang_type : match_data.GetCandidateLanguages()) {
657       if (LanguageCategory *lang_category = GetCategoryForLanguage(lang_type)) {
658         if (lang_category->Get(match_data, retval))
659           break;
660       }
661     }
662     if (retval) {
663       LLDB_LOGF(
664           log,
665           "[FormatManager::GetFormat] Language search success. Returning.");
666       return retval;
667     }
668   }
669   if (!retval) {
670     LLDB_LOGF(log, "[FormatManager::GetFormat] Search failed. Giving hardcoded "
671                    "a chance.");
672     retval = GetHardcodedFormat(match_data);
673   }
674 
675   if (match_data.GetTypeForCache() && (!retval || !retval->NonCacheable())) {
676     LLDB_LOGF(log, "[FormatManager::GetFormat] Caching %p for type %s",
677               static_cast<void *>(retval.get()),
678               match_data.GetTypeForCache().AsCString("<invalid>"));
679     m_format_cache.SetFormat(match_data.GetTypeForCache(), retval);
680   }
681   LLDB_LOGV(log, "Cache hits: {0} - Cache Misses: {1}",
682             m_format_cache.GetCacheHits(), m_format_cache.GetCacheMisses());
683   return retval;
684 }
685 
686 lldb::TypeSummaryImplSP
687 FormatManager::GetHardcodedSummaryFormat(FormattersMatchData &match_data) {
688   TypeSummaryImplSP retval_sp;
689 
690   for (lldb::LanguageType lang_type : match_data.GetCandidateLanguages()) {
691     if (LanguageCategory *lang_category = GetCategoryForLanguage(lang_type)) {
692       if (lang_category->GetHardcoded(*this, match_data, retval_sp))
693         break;
694     }
695   }
696 
697   return retval_sp;
698 }
699 
700 lldb::TypeSummaryImplSP
701 FormatManager::GetSummaryFormat(ValueObject &valobj,
702                                 lldb::DynamicValueType use_dynamic) {
703   FormattersMatchData match_data(valobj, use_dynamic);
704 
705   TypeSummaryImplSP retval;
706   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_DATAFORMATTERS));
707   if (match_data.GetTypeForCache()) {
708     LLDB_LOGF(log,
709               "\n\n[FormatManager::GetSummaryFormat] Looking into cache "
710               "for type %s",
711               match_data.GetTypeForCache().AsCString("<invalid>"));
712     if (m_format_cache.GetSummary(match_data.GetTypeForCache(), retval)) {
713       if (log) {
714         LLDB_LOGF(log,
715                   "[FormatManager::GetSummaryFormat] Cache search success. "
716                   "Returning.");
717         LLDB_LOGV(log, "Cache hits: {0} - Cache Misses: {1}",
718                   m_format_cache.GetCacheHits(),
719                   m_format_cache.GetCacheMisses());
720       }
721       return retval;
722     }
723     LLDB_LOGF(log, "[FormatManager::GetSummaryFormat] Cache search failed. "
724                    "Going normal route");
725   }
726 
727   retval = m_categories_map.GetSummaryFormat(match_data);
728   if (!retval) {
729     LLDB_LOGF(log, "[FormatManager::GetSummaryFormat] Search failed. Giving "
730                    "language a chance.");
731     for (lldb::LanguageType lang_type : match_data.GetCandidateLanguages()) {
732       if (LanguageCategory *lang_category = GetCategoryForLanguage(lang_type)) {
733         if (lang_category->Get(match_data, retval))
734           break;
735       }
736     }
737     if (retval) {
738       LLDB_LOGF(log, "[FormatManager::GetSummaryFormat] Language search "
739                      "success. Returning.");
740       return retval;
741     }
742   }
743   if (!retval) {
744     LLDB_LOGF(log, "[FormatManager::GetSummaryFormat] Search failed. Giving "
745                    "hardcoded a chance.");
746     retval = GetHardcodedSummaryFormat(match_data);
747   }
748 
749   if (match_data.GetTypeForCache() && (!retval || !retval->NonCacheable())) {
750     LLDB_LOGF(log, "[FormatManager::GetSummaryFormat] Caching %p for type %s",
751               static_cast<void *>(retval.get()),
752               match_data.GetTypeForCache().AsCString("<invalid>"));
753     m_format_cache.SetSummary(match_data.GetTypeForCache(), retval);
754   }
755   LLDB_LOGV(log, "Cache hits: {0} - Cache Misses: {1}",
756             m_format_cache.GetCacheHits(), m_format_cache.GetCacheMisses());
757   return retval;
758 }
759 
760 lldb::SyntheticChildrenSP
761 FormatManager::GetHardcodedSyntheticChildren(FormattersMatchData &match_data) {
762   SyntheticChildrenSP retval_sp;
763 
764   for (lldb::LanguageType lang_type : match_data.GetCandidateLanguages()) {
765     if (LanguageCategory *lang_category = GetCategoryForLanguage(lang_type)) {
766       if (lang_category->GetHardcoded(*this, match_data, retval_sp))
767         break;
768     }
769   }
770 
771   return retval_sp;
772 }
773 
774 lldb::SyntheticChildrenSP
775 FormatManager::GetSyntheticChildren(ValueObject &valobj,
776                                     lldb::DynamicValueType use_dynamic) {
777   FormattersMatchData match_data(valobj, use_dynamic);
778 
779   SyntheticChildrenSP retval;
780   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_DATAFORMATTERS));
781   if (match_data.GetTypeForCache()) {
782     LLDB_LOGF(log,
783               "\n\n[FormatManager::GetSyntheticChildren] Looking into "
784               "cache for type %s",
785               match_data.GetTypeForCache().AsCString("<invalid>"));
786     if (m_format_cache.GetSynthetic(match_data.GetTypeForCache(), retval)) {
787       if (log) {
788         LLDB_LOGF(log, "[FormatManager::GetSyntheticChildren] Cache search "
789                        "success. Returning.");
790         LLDB_LOGV(log, "Cache hits: {0} - Cache Misses: {1}",
791                   m_format_cache.GetCacheHits(),
792                   m_format_cache.GetCacheMisses());
793       }
794       return retval;
795     }
796     LLDB_LOGF(log, "[FormatManager::GetSyntheticChildren] Cache search failed. "
797                    "Going normal route");
798   }
799 
800   retval = m_categories_map.GetSyntheticChildren(match_data);
801   if (!retval) {
802     LLDB_LOGF(log,
803               "[FormatManager::GetSyntheticChildren] Search failed. Giving "
804               "language a chance.");
805     for (lldb::LanguageType lang_type : match_data.GetCandidateLanguages()) {
806       if (LanguageCategory *lang_category = GetCategoryForLanguage(lang_type)) {
807         if (lang_category->Get(match_data, retval))
808           break;
809       }
810     }
811     if (retval) {
812       LLDB_LOGF(log, "[FormatManager::GetSyntheticChildren] Language search "
813                      "success. Returning.");
814       return retval;
815     }
816   }
817   if (!retval) {
818     LLDB_LOGF(log,
819               "[FormatManager::GetSyntheticChildren] Search failed. Giving "
820               "hardcoded a chance.");
821     retval = GetHardcodedSyntheticChildren(match_data);
822   }
823 
824   if (match_data.GetTypeForCache() && (!retval || !retval->NonCacheable())) {
825     LLDB_LOGF(log,
826               "[FormatManager::GetSyntheticChildren] Caching %p for type %s",
827               static_cast<void *>(retval.get()),
828               match_data.GetTypeForCache().AsCString("<invalid>"));
829     m_format_cache.SetSynthetic(match_data.GetTypeForCache(), retval);
830   }
831   LLDB_LOGV(log, "Cache hits: {0} - Cache Misses: {1}",
832             m_format_cache.GetCacheHits(), m_format_cache.GetCacheMisses());
833   return retval;
834 }
835 
836 lldb::TypeValidatorImplSP
837 FormatManager::GetValidator(ValueObject &valobj,
838                             lldb::DynamicValueType use_dynamic) {
839   FormattersMatchData match_data(valobj, use_dynamic);
840 
841   TypeValidatorImplSP retval;
842   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_DATAFORMATTERS));
843   if (match_data.GetTypeForCache()) {
844     LLDB_LOGF(
845         log, "\n\n[FormatManager::GetValidator] Looking into cache for type %s",
846         match_data.GetTypeForCache().AsCString("<invalid>"));
847     if (m_format_cache.GetValidator(match_data.GetTypeForCache(), retval)) {
848       if (log) {
849         LLDB_LOGF(
850             log,
851             "[FormatManager::GetValidator] Cache search success. Returning.");
852         LLDB_LOGV(log, "Cache hits: {0} - Cache Misses: {1}",
853                   m_format_cache.GetCacheHits(),
854                   m_format_cache.GetCacheMisses());
855       }
856       return retval;
857     }
858     LLDB_LOGF(log, "[FormatManager::GetValidator] Cache search failed. Going "
859                    "normal route");
860   }
861 
862   retval = m_categories_map.GetValidator(match_data);
863   if (!retval) {
864     LLDB_LOGF(log, "[FormatManager::GetValidator] Search failed. Giving "
865                    "language a chance.");
866     for (lldb::LanguageType lang_type : match_data.GetCandidateLanguages()) {
867       if (LanguageCategory *lang_category = GetCategoryForLanguage(lang_type)) {
868         if (lang_category->Get(match_data, retval))
869           break;
870       }
871     }
872     if (retval) {
873       LLDB_LOGF(log, "[FormatManager::GetValidator] Language search success. "
874                      "Returning.");
875       return retval;
876     }
877   }
878   if (!retval) {
879     LLDB_LOGF(log, "[FormatManager::GetValidator] Search failed. Giving "
880                    "hardcoded a chance.");
881     retval = GetHardcodedValidator(match_data);
882   }
883 
884   if (match_data.GetTypeForCache() && (!retval || !retval->NonCacheable())) {
885     LLDB_LOGF(log, "[FormatManager::GetValidator] Caching %p for type %s",
886               static_cast<void *>(retval.get()),
887               match_data.GetTypeForCache().AsCString("<invalid>"));
888     m_format_cache.SetValidator(match_data.GetTypeForCache(), retval);
889   }
890   LLDB_LOGV(log, "Cache hits: {0} - Cache Misses: {1}",
891             m_format_cache.GetCacheHits(), m_format_cache.GetCacheMisses());
892   return retval;
893 }
894 
895 lldb::TypeValidatorImplSP
896 FormatManager::GetHardcodedValidator(FormattersMatchData &match_data) {
897   TypeValidatorImplSP retval_sp;
898 
899   for (lldb::LanguageType lang_type : match_data.GetCandidateLanguages()) {
900     if (LanguageCategory *lang_category = GetCategoryForLanguage(lang_type)) {
901       if (lang_category->GetHardcoded(*this, match_data, retval_sp))
902         break;
903     }
904   }
905 
906   return retval_sp;
907 }
908 
909 FormatManager::FormatManager()
910     : m_last_revision(0), m_format_cache(), m_language_categories_mutex(),
911       m_language_categories_map(), m_named_summaries_map(this),
912       m_categories_map(this), m_default_category_name(ConstString("default")),
913       m_system_category_name(ConstString("system")),
914       m_vectortypes_category_name(ConstString("VectorTypes")) {
915   LoadSystemFormatters();
916   LoadVectorFormatters();
917 
918   EnableCategory(m_vectortypes_category_name, TypeCategoryMap::Last,
919                  lldb::eLanguageTypeObjC_plus_plus);
920   EnableCategory(m_system_category_name, TypeCategoryMap::Last,
921                  lldb::eLanguageTypeObjC_plus_plus);
922 }
923 
924 void FormatManager::LoadSystemFormatters() {
925   TypeSummaryImpl::Flags string_flags;
926   string_flags.SetCascades(true)
927       .SetSkipPointers(true)
928       .SetSkipReferences(false)
929       .SetDontShowChildren(true)
930       .SetDontShowValue(false)
931       .SetShowMembersOneLiner(false)
932       .SetHideItemNames(false);
933 
934   TypeSummaryImpl::Flags string_array_flags;
935   string_array_flags.SetCascades(true)
936       .SetSkipPointers(true)
937       .SetSkipReferences(false)
938       .SetDontShowChildren(true)
939       .SetDontShowValue(true)
940       .SetShowMembersOneLiner(false)
941       .SetHideItemNames(false);
942 
943   lldb::TypeSummaryImplSP string_format(
944       new StringSummaryFormat(string_flags, "${var%s}"));
945 
946   lldb::TypeSummaryImplSP string_array_format(
947       new StringSummaryFormat(string_array_flags, "${var%s}"));
948 
949   lldb::RegularExpressionSP any_size_char_arr(
950       new RegularExpression(llvm::StringRef("char \\[[0-9]+\\]")));
951   lldb::RegularExpressionSP any_size_wchar_arr(
952       new RegularExpression(llvm::StringRef("wchar_t \\[[0-9]+\\]")));
953 
954   TypeCategoryImpl::SharedPointer sys_category_sp =
955       GetCategory(m_system_category_name);
956 
957   sys_category_sp->GetTypeSummariesContainer()->Add(ConstString("char *"),
958                                                     string_format);
959   sys_category_sp->GetTypeSummariesContainer()->Add(
960       ConstString("unsigned char *"), string_format);
961   sys_category_sp->GetRegexTypeSummariesContainer()->Add(any_size_char_arr,
962                                                          string_array_format);
963 
964   lldb::TypeSummaryImplSP ostype_summary(
965       new StringSummaryFormat(TypeSummaryImpl::Flags()
966                                   .SetCascades(false)
967                                   .SetSkipPointers(true)
968                                   .SetSkipReferences(true)
969                                   .SetDontShowChildren(true)
970                                   .SetDontShowValue(false)
971                                   .SetShowMembersOneLiner(false)
972                                   .SetHideItemNames(false),
973                               "${var%O}"));
974 
975   sys_category_sp->GetTypeSummariesContainer()->Add(ConstString("OSType"),
976                                                     ostype_summary);
977 
978   TypeFormatImpl::Flags fourchar_flags;
979   fourchar_flags.SetCascades(true).SetSkipPointers(true).SetSkipReferences(
980       true);
981 
982   AddFormat(sys_category_sp, lldb::eFormatOSType, ConstString("FourCharCode"),
983             fourchar_flags);
984 }
985 
986 void FormatManager::LoadVectorFormatters() {
987   TypeCategoryImpl::SharedPointer vectors_category_sp =
988       GetCategory(m_vectortypes_category_name);
989 
990   TypeSummaryImpl::Flags vector_flags;
991   vector_flags.SetCascades(true)
992       .SetSkipPointers(true)
993       .SetSkipReferences(false)
994       .SetDontShowChildren(true)
995       .SetDontShowValue(false)
996       .SetShowMembersOneLiner(true)
997       .SetHideItemNames(true);
998 
999   AddStringSummary(vectors_category_sp, "${var.uint128}",
1000                    ConstString("builtin_type_vec128"), vector_flags);
1001 
1002   AddStringSummary(vectors_category_sp, "", ConstString("float [4]"),
1003                    vector_flags);
1004   AddStringSummary(vectors_category_sp, "", ConstString("int32_t [4]"),
1005                    vector_flags);
1006   AddStringSummary(vectors_category_sp, "", ConstString("int16_t [8]"),
1007                    vector_flags);
1008   AddStringSummary(vectors_category_sp, "", ConstString("vDouble"),
1009                    vector_flags);
1010   AddStringSummary(vectors_category_sp, "", ConstString("vFloat"),
1011                    vector_flags);
1012   AddStringSummary(vectors_category_sp, "", ConstString("vSInt8"),
1013                    vector_flags);
1014   AddStringSummary(vectors_category_sp, "", ConstString("vSInt16"),
1015                    vector_flags);
1016   AddStringSummary(vectors_category_sp, "", ConstString("vSInt32"),
1017                    vector_flags);
1018   AddStringSummary(vectors_category_sp, "", ConstString("vUInt16"),
1019                    vector_flags);
1020   AddStringSummary(vectors_category_sp, "", ConstString("vUInt8"),
1021                    vector_flags);
1022   AddStringSummary(vectors_category_sp, "", ConstString("vUInt16"),
1023                    vector_flags);
1024   AddStringSummary(vectors_category_sp, "", ConstString("vUInt32"),
1025                    vector_flags);
1026   AddStringSummary(vectors_category_sp, "", ConstString("vBool32"),
1027                    vector_flags);
1028 }
1029