Tensor Comprehensions
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
canonicalize.h
Go to the documentation of this file.
1 
16 #pragma once
17 
18 #include <string>
19 
20 #include "tc/lang/tree.h"
21 #include "tc/lang/tree_views.h"
22 
23 namespace lang {
24 
25 // takes a tree after semantic analysis and create
26 // a canonicalized version that is agnostic to the choice of identifiers
28  struct Context {
29  std::unordered_map<std::string, std::string> identMap;
30  std::string rename(const std::string& name) {
31  auto it = identMap.find(name);
32  if (it != identMap.end()) {
33  return it->second;
34  }
35  std::string canonicalName = "i" + std::to_string(identMap.size());
36  identMap[name] = canonicalName;
37  return canonicalName;
38  }
39 
40  TreeRef apply(TreeRef node) {
41  if (node->kind() == TK_IDENT) {
42  return Ident::create(node->range(), rename(Ident(node).name()));
43  }
44  if (node->kind() == TK_APPLY) {
45  throw ErrorReport(node)
46  << "canonicalize is only valid on trees after Sema has been run "
47  << "but it encountered a TK_APPLY node, which Sema removes";
48  }
49  return node->map([&](TreeRef ref) { return apply(ref); });
50  }
51  };
52 
53  Context ctx;
54  return ctx.apply(tree);
55 }
56 } // namespace lang
Definition: tree_views.h:109
TreeRef canonicalize(TreeRef tree)
Definition: canonicalize.h:27
static TreeRef create(const SourceRange &range, const std::string &name)
Definition: tree_views.h:127
Definition: error_report.h:22
std::shared_ptr< Tree > TreeRef
Definition: tree.h:44