blob: d00d27bcc598bba1d0123ade4ea52f8ba2c0477a [file] [log] [blame]
Marco Polettib5239c92022-05-11 09:46:05 -07001// Part of the Crubit project, under the Apache License v2.0 with LLVM
2// Exceptions. See /LICENSE for license information.
3// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
4
5#include "migrator/rs_from_cc/converter.h"
6
Dmitri Gribenkodac4d432023-07-28 06:14:35 -07007#include <string>
8
Marco Polettib5239c92022-05-11 09:46:05 -07009#include "absl/strings/str_split.h"
Marco Polettib5239c92022-05-11 09:46:05 -070010#include "clang/AST/Decl.h"
Dmitri Gribenkodac4d432023-07-28 06:14:35 -070011#include "clang/AST/DeclBase.h"
12#include "llvm/Support/raw_ostream.h"
Marco Polettib5239c92022-05-11 09:46:05 -070013#include "third_party/re2/re2.h"
14
15namespace crubit_rs_from_cc {
16
Marco Poletti8e21c122022-05-24 09:40:58 -070017void Converter::Convert(const clang::TranslationUnitDecl* translation_unit) {
18 for (clang::Decl* decl : translation_unit->decls()) {
19 if (decl->getBeginLoc().isInvalid()) {
20 // Skip declarations with invalid locations, e.g. builtins that Clang
21 // generates.
22 continue;
23 }
24 Convert(decl);
25 }
Marco Polettib5239c92022-05-11 09:46:05 -070026}
27
Marco Poletti8e21c122022-05-24 09:40:58 -070028void Converter::Convert(const clang::Decl* decl) {
29 switch (decl->getKind()) {
30 case clang::Decl::TranslationUnit:
31 Convert(dynamic_cast<const clang::TranslationUnitDecl*>(decl));
32 break;
33
34 default:
35 ConvertUnhandled(decl);
36 }
37}
38
39void Converter::ConvertUnhandled(const clang::Decl* decl) {
Marco Polettib5239c92022-05-11 09:46:05 -070040 std::string ast;
41 llvm::raw_string_ostream os(ast);
42 decl->dump(os);
43 os.flush();
44 result_ += "\n";
45 result_ += "// Unsupported decl:\n//\n";
46 // Remove addresses since they're not useful and add non-determinism that
47 // would break golden testing.
48 // Also remove spaces at the end of each line, those are a pain in golden
49 // tests since IDEs often strip spaces at end of line.
50 RE2::GlobalReplace(&ast, "(?m) 0x[a-z0-9]+| +$", "");
51 for (auto line : absl::StrSplit(ast, '\n')) {
52 if (line.empty()) {
53 continue;
54 }
55 result_ += "// ";
56 result_ += line;
57 result_ += '\n';
58 }
59}
60
61} // namespace crubit_rs_from_cc