Marco Poletti | b5239c9 | 2022-05-11 09:46:05 -0700 | [diff] [blame] | 1 | // 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 Gribenko | dac4d43 | 2023-07-28 06:14:35 -0700 | [diff] [blame] | 7 | #include <string> |
| 8 | |
Marco Poletti | b5239c9 | 2022-05-11 09:46:05 -0700 | [diff] [blame] | 9 | #include "absl/strings/str_split.h" |
Marco Poletti | b5239c9 | 2022-05-11 09:46:05 -0700 | [diff] [blame] | 10 | #include "clang/AST/Decl.h" |
Dmitri Gribenko | dac4d43 | 2023-07-28 06:14:35 -0700 | [diff] [blame] | 11 | #include "clang/AST/DeclBase.h" |
| 12 | #include "llvm/Support/raw_ostream.h" |
Marco Poletti | b5239c9 | 2022-05-11 09:46:05 -0700 | [diff] [blame] | 13 | #include "third_party/re2/re2.h" |
| 14 | |
| 15 | namespace crubit_rs_from_cc { |
| 16 | |
Marco Poletti | 8e21c12 | 2022-05-24 09:40:58 -0700 | [diff] [blame] | 17 | void 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 Poletti | b5239c9 | 2022-05-11 09:46:05 -0700 | [diff] [blame] | 26 | } |
| 27 | |
Marco Poletti | 8e21c12 | 2022-05-24 09:40:58 -0700 | [diff] [blame] | 28 | void 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 | |
| 39 | void Converter::ConvertUnhandled(const clang::Decl* decl) { |
Marco Poletti | b5239c9 | 2022-05-11 09:46:05 -0700 | [diff] [blame] | 40 | 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 |