9 #ifndef MLIR_LIB_TARGET_IRDLTOCPP_TEMPLATINGUTILS_H
10 #define MLIR_LIB_TARGET_IRDLTOCPP_TEMPLATINGUTILS_H
12 #include "llvm/ADT/SmallString.h"
13 #include "llvm/ADT/StringMap.h"
14 #include "llvm/ADT/StringRef.h"
15 #include "llvm/Support/ErrorHandling.h"
16 #include "llvm/Support/raw_ostream.h"
23 using dictionary = llvm::StringMap<llvm::SmallString<8>>;
33 bool processingReplacementToken =
false;
34 while (!str.empty()) {
35 auto [token, remainder] = str.split(
"__");
37 if (processingReplacementToken) {
38 assert(!token.empty() &&
"replacement name cannot be empty");
39 bytecode.emplace_back(ReplacementToken{token});
42 bytecode.emplace_back(LiteralToken{token});
45 processingReplacementToken = !processingReplacementToken;
53 for (
auto instruction : bytecode) {
54 if (
auto *inst = std::get_if<LiteralToken>(&instruction)) {
59 if (
auto *inst = std::get_if<ReplacementToken>(&instruction)) {
60 auto replacement = replacements.find(inst->keyName);
62 if (replacement == replacements.end()) {
63 llvm::errs() <<
"Missing template key: " << inst->keyName <<
"\n";
64 llvm_unreachable(
"Missing template key");
67 out << replacement->second;
71 llvm_unreachable(
"non-exhaustive bytecode visit");
80 struct ReplacementToken {
81 llvm::StringRef keyName;
84 std::vector<std::variant<LiteralToken, ReplacementToken>> bytecode;
Template Code as used by IRDL-to-Cpp.
void render(llvm::raw_ostream &out, const dictionary &replacements) const
Render will apply a dictionary to the Template and send the rendered result to the specified output s...
Template(llvm::StringRef str)
llvm::StringMap< llvm::SmallString< 8 > > dictionary
A dictionary stores a mapping of template variable names to their assigned string values.