1 //===-- YAMLSerialization.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 // A YAML index file is a sequence of tagged entries.
10 // Each entry either encodes a Symbol or the list of references to a symbol
11 // (a "ref bundle").
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "Index.h"
16 #include "Relation.h"
17 #include "Serialization.h"
18 #include "SymbolLocation.h"
19 #include "SymbolOrigin.h"
20 #include "dex/Dex.h"
21 #include "support/Logger.h"
22 #include "support/Trace.h"
23 #include "llvm/ADT/Optional.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/Support/Allocator.h"
27 #include "llvm/Support/Errc.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/Support/StringSaver.h"
30 #include "llvm/Support/YAMLTraits.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include <cstdint>
33 
34 LLVM_YAML_IS_SEQUENCE_VECTOR(clang::clangd::Symbol::IncludeHeaderWithReferences)
35 LLVM_YAML_IS_SEQUENCE_VECTOR(clang::clangd::Ref)
36 
37 namespace {
38 using RefBundle =
39     std::pair<clang::clangd::SymbolID, std::vector<clang::clangd::Ref>>;
40 // This is a pale imitation of std::variant<Symbol, RefBundle, Relation>
41 struct VariantEntry {
42   llvm::Optional<clang::clangd::Symbol> Symbol;
43   llvm::Optional<RefBundle> Refs;
44   llvm::Optional<clang::clangd::Relation> Relation;
45   llvm::Optional<clang::clangd::IncludeGraphNode> Source;
46   llvm::Optional<clang::tooling::CompileCommand> Cmd;
47 };
48 // A class helps YAML to serialize the 32-bit encoded position (Line&Column),
49 // as YAMLIO can't directly map bitfields.
50 struct YPosition {
51   uint32_t Line;
52   uint32_t Column;
53 };
54 
55 // avoid ODR violation of specialization for non-owned CompileCommand
56 struct CompileCommandYAML : clang::tooling::CompileCommand {};
57 
58 } // namespace
59 namespace llvm {
60 namespace yaml {
61 
62 using clang::clangd::FileDigest;
63 using clang::clangd::IncludeGraph;
64 using clang::clangd::IncludeGraphNode;
65 using clang::clangd::Ref;
66 using clang::clangd::RefKind;
67 using clang::clangd::Relation;
68 using clang::clangd::RelationKind;
69 using clang::clangd::Symbol;
70 using clang::clangd::SymbolID;
71 using clang::clangd::SymbolLocation;
72 using clang::index::SymbolInfo;
73 using clang::index::SymbolKind;
74 using clang::index::SymbolLanguage;
75 using clang::tooling::CompileCommand;
76 
77 // Helper to (de)serialize the SymbolID. We serialize it as a hex string.
78 struct NormalizedSymbolID {
79   NormalizedSymbolID(IO &) {}
80   NormalizedSymbolID(IO &, const SymbolID &ID) {
81     llvm::raw_string_ostream OS(HexString);
82     OS << ID;
83   }
84 
85   SymbolID denormalize(IO &I) {
86     auto ID = SymbolID::fromStr(HexString);
87     if (!ID) {
88       I.setError(llvm::toString(ID.takeError()));
89       return SymbolID();
90     }
91     return *ID;
92   }
93 
94   std::string HexString;
95 };
96 
97 struct NormalizedSymbolFlag {
98   NormalizedSymbolFlag(IO &) {}
99   NormalizedSymbolFlag(IO &, Symbol::SymbolFlag F) {
100     Flag = static_cast<uint8_t>(F);
101   }
102 
103   Symbol::SymbolFlag denormalize(IO &) {
104     return static_cast<Symbol::SymbolFlag>(Flag);
105   }
106 
107   uint8_t Flag = 0;
108 };
109 
110 template <> struct MappingTraits<YPosition> {
111   static void mapping(IO &IO, YPosition &Value) {
112     IO.mapRequired("Line", Value.Line);
113     IO.mapRequired("Column", Value.Column);
114   }
115 };
116 
117 struct NormalizedPosition {
118   using Position = clang::clangd::SymbolLocation::Position;
119   NormalizedPosition(IO &) {}
120   NormalizedPosition(IO &, const Position &Pos) {
121     P.Line = Pos.line();
122     P.Column = Pos.column();
123   }
124 
125   Position denormalize(IO &) {
126     Position Pos;
127     Pos.setLine(P.Line);
128     Pos.setColumn(P.Column);
129     return Pos;
130   }
131   YPosition P;
132 };
133 
134 struct NormalizedFileURI {
135   NormalizedFileURI(IO &) {}
136   NormalizedFileURI(IO &, const char *FileURI) { URI = FileURI; }
137 
138   const char *denormalize(IO &IO) {
139     assert(IO.getContext() &&
140            "Expecting an UniqueStringSaver to allocate data");
141     return static_cast<llvm::UniqueStringSaver *>(IO.getContext())
142         ->save(URI)
143         .data();
144   }
145 
146   std::string URI;
147 };
148 
149 template <> struct MappingTraits<SymbolLocation> {
150   static void mapping(IO &IO, SymbolLocation &Value) {
151     MappingNormalization<NormalizedFileURI, const char *> NFile(IO,
152                                                                 Value.FileURI);
153     IO.mapRequired("FileURI", NFile->URI);
154     MappingNormalization<NormalizedPosition, SymbolLocation::Position> NStart(
155         IO, Value.Start);
156     IO.mapRequired("Start", NStart->P);
157     MappingNormalization<NormalizedPosition, SymbolLocation::Position> NEnd(
158         IO, Value.End);
159     IO.mapRequired("End", NEnd->P);
160   }
161 };
162 
163 template <> struct MappingTraits<SymbolInfo> {
164   static void mapping(IO &IO, SymbolInfo &SymInfo) {
165     // FIXME: expose other fields?
166     IO.mapRequired("Kind", SymInfo.Kind);
167     IO.mapRequired("Lang", SymInfo.Lang);
168   }
169 };
170 
171 template <>
172 struct MappingTraits<clang::clangd::Symbol::IncludeHeaderWithReferences> {
173   static void mapping(IO &IO,
174                       clang::clangd::Symbol::IncludeHeaderWithReferences &Inc) {
175     IO.mapRequired("Header", Inc.IncludeHeader);
176     IO.mapRequired("References", Inc.References);
177   }
178 };
179 
180 template <> struct MappingTraits<Symbol> {
181   static void mapping(IO &IO, Symbol &Sym) {
182     MappingNormalization<NormalizedSymbolID, SymbolID> NSymbolID(IO, Sym.ID);
183     MappingNormalization<NormalizedSymbolFlag, Symbol::SymbolFlag> NSymbolFlag(
184         IO, Sym.Flags);
185     IO.mapRequired("ID", NSymbolID->HexString);
186     IO.mapRequired("Name", Sym.Name);
187     IO.mapRequired("Scope", Sym.Scope);
188     IO.mapRequired("SymInfo", Sym.SymInfo);
189     IO.mapOptional("CanonicalDeclaration", Sym.CanonicalDeclaration,
190                    SymbolLocation());
191     IO.mapOptional("Definition", Sym.Definition, SymbolLocation());
192     IO.mapOptional("References", Sym.References, 0u);
193     IO.mapOptional("Flags", NSymbolFlag->Flag);
194     IO.mapOptional("Signature", Sym.Signature);
195     IO.mapOptional("TemplateSpecializationArgs",
196                    Sym.TemplateSpecializationArgs);
197     IO.mapOptional("CompletionSnippetSuffix", Sym.CompletionSnippetSuffix);
198     IO.mapOptional("Documentation", Sym.Documentation);
199     IO.mapOptional("ReturnType", Sym.ReturnType);
200     IO.mapOptional("Type", Sym.Type);
201     IO.mapOptional("IncludeHeaders", Sym.IncludeHeaders);
202   }
203 };
204 
205 template <> struct ScalarEnumerationTraits<SymbolLanguage> {
206   static void enumeration(IO &IO, SymbolLanguage &Value) {
207     IO.enumCase(Value, "C", SymbolLanguage::C);
208     IO.enumCase(Value, "Cpp", SymbolLanguage::CXX);
209     IO.enumCase(Value, "ObjC", SymbolLanguage::ObjC);
210     IO.enumCase(Value, "Swift", SymbolLanguage::Swift);
211   }
212 };
213 
214 template <> struct ScalarEnumerationTraits<SymbolKind> {
215   static void enumeration(IO &IO, SymbolKind &Value) {
216 #define DEFINE_ENUM(name) IO.enumCase(Value, #name, SymbolKind::name)
217 
218     DEFINE_ENUM(Unknown);
219     DEFINE_ENUM(Function);
220     DEFINE_ENUM(Module);
221     DEFINE_ENUM(Namespace);
222     DEFINE_ENUM(NamespaceAlias);
223     DEFINE_ENUM(Macro);
224     DEFINE_ENUM(Enum);
225     DEFINE_ENUM(Struct);
226     DEFINE_ENUM(Class);
227     DEFINE_ENUM(Protocol);
228     DEFINE_ENUM(Extension);
229     DEFINE_ENUM(Union);
230     DEFINE_ENUM(TypeAlias);
231     DEFINE_ENUM(Function);
232     DEFINE_ENUM(Variable);
233     DEFINE_ENUM(Field);
234     DEFINE_ENUM(EnumConstant);
235     DEFINE_ENUM(InstanceMethod);
236     DEFINE_ENUM(ClassMethod);
237     DEFINE_ENUM(StaticMethod);
238     DEFINE_ENUM(InstanceProperty);
239     DEFINE_ENUM(ClassProperty);
240     DEFINE_ENUM(StaticProperty);
241     DEFINE_ENUM(Constructor);
242     DEFINE_ENUM(Destructor);
243     DEFINE_ENUM(ConversionFunction);
244     DEFINE_ENUM(Parameter);
245     DEFINE_ENUM(Using);
246 
247 #undef DEFINE_ENUM
248   }
249 };
250 
251 template <> struct MappingTraits<RefBundle> {
252   static void mapping(IO &IO, RefBundle &Refs) {
253     MappingNormalization<NormalizedSymbolID, SymbolID> NSymbolID(IO,
254                                                                  Refs.first);
255     IO.mapRequired("ID", NSymbolID->HexString);
256     IO.mapRequired("References", Refs.second);
257   }
258 };
259 
260 struct NormalizedRefKind {
261   NormalizedRefKind(IO &) {}
262   NormalizedRefKind(IO &, RefKind O) { Kind = static_cast<uint8_t>(O); }
263 
264   RefKind denormalize(IO &) { return static_cast<RefKind>(Kind); }
265 
266   uint8_t Kind = 0;
267 };
268 
269 template <> struct MappingTraits<Ref> {
270   static void mapping(IO &IO, Ref &R) {
271     MappingNormalization<NormalizedRefKind, RefKind> NKind(IO, R.Kind);
272     IO.mapRequired("Kind", NKind->Kind);
273     IO.mapRequired("Location", R.Location);
274   }
275 };
276 
277 struct NormalizedSymbolRole {
278   NormalizedSymbolRole(IO &) {}
279   NormalizedSymbolRole(IO &IO, RelationKind R) {
280     Kind = static_cast<uint8_t>(R);
281   }
282 
283   RelationKind denormalize(IO &IO) { return static_cast<RelationKind>(Kind); }
284 
285   uint8_t Kind = 0;
286 };
287 
288 template <> struct MappingTraits<SymbolID> {
289   static void mapping(IO &IO, SymbolID &ID) {
290     MappingNormalization<NormalizedSymbolID, SymbolID> NSymbolID(IO, ID);
291     IO.mapRequired("ID", NSymbolID->HexString);
292   }
293 };
294 
295 template <> struct MappingTraits<Relation> {
296   static void mapping(IO &IO, Relation &Relation) {
297     MappingNormalization<NormalizedSymbolRole, RelationKind> NRole(
298         IO, Relation.Predicate);
299     IO.mapRequired("Subject", Relation.Subject);
300     IO.mapRequired("Predicate", NRole->Kind);
301     IO.mapRequired("Object", Relation.Object);
302   }
303 };
304 
305 struct NormalizedSourceFlag {
306   NormalizedSourceFlag(IO &) {}
307   NormalizedSourceFlag(IO &, IncludeGraphNode::SourceFlag O) {
308     Flag = static_cast<uint8_t>(O);
309   }
310 
311   IncludeGraphNode::SourceFlag denormalize(IO &) {
312     return static_cast<IncludeGraphNode::SourceFlag>(Flag);
313   }
314 
315   uint8_t Flag = 0;
316 };
317 
318 struct NormalizedFileDigest {
319   NormalizedFileDigest(IO &) {}
320   NormalizedFileDigest(IO &, const FileDigest &Digest) {
321     HexString = llvm::toHex(Digest);
322   }
323 
324   FileDigest denormalize(IO &I) {
325     FileDigest Digest;
326     if (HexString.size() == Digest.size() * 2 &&
327         llvm::all_of(HexString, llvm::isHexDigit)) {
328       memcpy(Digest.data(), llvm::fromHex(HexString).data(), Digest.size());
329     } else {
330       I.setError(std::string("Bad hex file digest: ") + HexString);
331     }
332     return Digest;
333   }
334 
335   std::string HexString;
336 };
337 
338 template <> struct MappingTraits<IncludeGraphNode> {
339   static void mapping(IO &IO, IncludeGraphNode &Node) {
340     IO.mapRequired("URI", Node.URI);
341     MappingNormalization<NormalizedSourceFlag, IncludeGraphNode::SourceFlag>
342         NSourceFlag(IO, Node.Flags);
343     IO.mapRequired("Flags", NSourceFlag->Flag);
344     MappingNormalization<NormalizedFileDigest, FileDigest> NDigest(IO,
345                                                                    Node.Digest);
346     IO.mapRequired("Digest", NDigest->HexString);
347     IO.mapRequired("DirectIncludes", Node.DirectIncludes);
348   }
349 };
350 
351 template <> struct MappingTraits<CompileCommandYAML> {
352   static void mapping(IO &IO, CompileCommandYAML &Cmd) {
353     IO.mapRequired("Directory", Cmd.Directory);
354     IO.mapRequired("CommandLine", Cmd.CommandLine);
355   }
356 };
357 
358 template <> struct MappingTraits<VariantEntry> {
359   static void mapping(IO &IO, VariantEntry &Variant) {
360     if (IO.mapTag("!Symbol", Variant.Symbol.hasValue())) {
361       if (!IO.outputting())
362         Variant.Symbol.emplace();
363       MappingTraits<Symbol>::mapping(IO, *Variant.Symbol);
364     } else if (IO.mapTag("!Refs", Variant.Refs.hasValue())) {
365       if (!IO.outputting())
366         Variant.Refs.emplace();
367       MappingTraits<RefBundle>::mapping(IO, *Variant.Refs);
368     } else if (IO.mapTag("!Relations", Variant.Relation.hasValue())) {
369       if (!IO.outputting())
370         Variant.Relation.emplace();
371       MappingTraits<Relation>::mapping(IO, *Variant.Relation);
372     } else if (IO.mapTag("!Source", Variant.Source.hasValue())) {
373       if (!IO.outputting())
374         Variant.Source.emplace();
375       MappingTraits<IncludeGraphNode>::mapping(IO, *Variant.Source);
376     } else if (IO.mapTag("!Cmd", Variant.Cmd.hasValue())) {
377       if (!IO.outputting())
378         Variant.Cmd.emplace();
379       MappingTraits<CompileCommandYAML>::mapping(
380           IO, static_cast<CompileCommandYAML &>(*Variant.Cmd));
381     }
382   }
383 };
384 
385 } // namespace yaml
386 } // namespace llvm
387 
388 namespace clang {
389 namespace clangd {
390 
391 void writeYAML(const IndexFileOut &O, llvm::raw_ostream &OS) {
392   llvm::yaml::Output Yout(OS);
393   for (const auto &Sym : *O.Symbols) {
394     VariantEntry Entry;
395     Entry.Symbol = Sym;
396     Yout << Entry;
397   }
398   if (O.Refs)
399     for (auto &Sym : *O.Refs) {
400       VariantEntry Entry;
401       Entry.Refs = Sym;
402       Yout << Entry;
403     }
404   if (O.Relations)
405     for (auto &R : *O.Relations) {
406       VariantEntry Entry;
407       Entry.Relation = R;
408       Yout << Entry;
409     }
410   if (O.Sources) {
411     for (const auto &Source : *O.Sources) {
412       VariantEntry Entry;
413       Entry.Source = Source.getValue();
414       Yout << Entry;
415     }
416   }
417   if (O.Cmd) {
418     VariantEntry Entry;
419     Entry.Cmd = *O.Cmd;
420     Yout << Entry;
421   }
422 }
423 
424 llvm::Expected<IndexFileIn> readYAML(llvm::StringRef Data,
425                                      SymbolOrigin Origin) {
426   SymbolSlab::Builder Symbols;
427   RefSlab::Builder Refs;
428   RelationSlab::Builder Relations;
429   llvm::BumpPtrAllocator
430       Arena; // store the underlying data of Position::FileURI.
431   llvm::UniqueStringSaver Strings(Arena);
432   llvm::yaml::Input Yin(Data, &Strings);
433   IncludeGraph Sources;
434   llvm::Optional<tooling::CompileCommand> Cmd;
435   while (Yin.setCurrentDocument()) {
436     llvm::yaml::EmptyContext Ctx;
437     VariantEntry Variant;
438     yamlize(Yin, Variant, true, Ctx);
439     if (Yin.error())
440       return llvm::errorCodeToError(Yin.error());
441 
442     if (Variant.Symbol) {
443       Variant.Symbol->Origin = Origin;
444       Symbols.insert(*Variant.Symbol);
445     }
446     if (Variant.Refs)
447       for (const auto &Ref : Variant.Refs->second)
448         Refs.insert(Variant.Refs->first, Ref);
449     if (Variant.Relation)
450       Relations.insert(*Variant.Relation);
451     if (Variant.Source) {
452       auto &IGN = Variant.Source.getValue();
453       auto Entry = Sources.try_emplace(IGN.URI).first;
454       Entry->getValue() = std::move(IGN);
455       // Fixup refs to refer to map keys which will live on
456       Entry->getValue().URI = Entry->getKey();
457       for (auto &Include : Entry->getValue().DirectIncludes)
458         Include = Sources.try_emplace(Include).first->getKey();
459     }
460     if (Variant.Cmd)
461       Cmd = *Variant.Cmd;
462     Yin.nextDocument();
463   }
464 
465   IndexFileIn Result;
466   Result.Symbols.emplace(std::move(Symbols).build());
467   Result.Refs.emplace(std::move(Refs).build());
468   Result.Relations.emplace(std::move(Relations).build());
469   if (Sources.size())
470     Result.Sources = std::move(Sources);
471   Result.Cmd = std::move(Cmd);
472   return std::move(Result);
473 }
474 
475 std::string toYAML(const Symbol &S) {
476   std::string Buf;
477   {
478     llvm::raw_string_ostream OS(Buf);
479     llvm::yaml::Output Yout(OS);
480     Symbol Sym = S; // copy: Yout<< requires mutability.
481     Yout << Sym;
482   }
483   return Buf;
484 }
485 
486 std::string toYAML(const std::pair<SymbolID, llvm::ArrayRef<Ref>> &Data) {
487   RefBundle Refs = {Data.first, Data.second};
488   std::string Buf;
489   {
490     llvm::raw_string_ostream OS(Buf);
491     llvm::yaml::Output Yout(OS);
492     Yout << Refs;
493   }
494   return Buf;
495 }
496 
497 std::string toYAML(const Relation &R) {
498   std::string Buf;
499   {
500     llvm::raw_string_ostream OS(Buf);
501     llvm::yaml::Output Yout(OS);
502     Relation Rel = R; // copy: Yout<< requires mutability.
503     Yout << Rel;
504   }
505   return Buf;
506 }
507 
508 std::string toYAML(const Ref &R) {
509   std::string Buf;
510   {
511     llvm::raw_string_ostream OS(Buf);
512     llvm::yaml::Output Yout(OS);
513     Ref Reference = R; // copy: Yout<< requires mutability.
514     Yout << Reference;
515   }
516   return Buf;
517 }
518 
519 } // namespace clangd
520 } // namespace clang
521