Joos1W Compiler Framework
All Classes Functions Typedefs Pages
Mangling.cc
1 #include "codegen/Mangling.h"
2 #include <string_view>
3 
4 #include "ast/AST.h"
5 
6 namespace codegen {
7 
8 void Mangler::MangleCanonicalName(std::string_view name) {
9  for(unsigned i = 0; i < name.size(); i++) {
10  unsigned partSize = 0;
11  for(unsigned j = i; j < name.size() && name[j] != '.'; j++, partSize++)
12  ;
13  ss << partSize << name.substr(i, partSize);
14  i += partSize;
15  }
16  ss << "E";
17 }
18 
19 void Mangler::MangleType(ast::Type const* ty) {
20  if(ty->isPrimitive()) {
21  auto* bt = cast<ast::BuiltInType>(ty);
22  switch(bt->getKind()) {
23  case ast::BuiltInType::Kind::Boolean:
24  ss << "B";
25  break;
26  case ast::BuiltInType::Kind::Char:
27  ss << "c";
28  break;
29  case ast::BuiltInType::Kind::Short:
30  ss << "s";
31  break;
32  case ast::BuiltInType::Kind::Int:
33  ss << "i";
34  break;
35  case ast::BuiltInType::Kind::Byte:
36  ss << "b";
37  break;
38  case ast::BuiltInType::Kind::String:
39  ss << "S";
40  break;
41  default:
42  assert(false && "None type not supported");
43  }
44  } else if(ty->isArray()) {
45  ss << "A";
46  MangleType(cast<ast::ArrayType>(ty)->getElementType());
47  } else {
48  auto* rt = cast<ast::ReferenceType>(ty)->decl();
49  // If java.lang.String
50  if(rt == NR.GetJavaLang().String) {
51  ss << "S";
52  } else if(rt == NR.GetJavaLang().Object) {
53  ss << "O";
54  } else {
55  ss << "R";
56  MangleCanonicalName(rt->getCanonicalName());
57  }
58  }
59 }
60 
61 void Mangler::MangleFunctionName(ast::MethodDecl const* decl) {
62  ss << "_JF";
63  if(!decl->modifiers().isStatic()) ss << "C";
64  // Split canonical name into parts
65  MangleCanonicalName(decl->getCanonicalName());
66  // Add the function signature
67  if(decl->returnTy().type)
68  MangleType(decl->returnTy().type);
69  else
70  ss << "v";
71  for(auto* param : decl->parameters()) {
72  MangleType(param->type());
73  }
74 }
75 
76 } // namespace codegen