slang_rs_context.cpp revision 96ab06cbe40b2d73c0eb614f814cd761d8962b6b
1/*
2 * Copyright 2010, The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "slang_rs_context.h"
18
19#include <string>
20
21#include "clang/AST/ASTContext.h"
22#include "clang/AST/Decl.h"
23#include "clang/AST/DeclBase.h"
24#include "clang/AST/Type.h"
25
26#include "clang/Basic/Linkage.h"
27#include "clang/Basic/TargetInfo.h"
28
29#include "clang/Index/ASTLocation.h"
30
31#include "llvm/LLVMContext.h"
32
33#include "llvm/Target/TargetData.h"
34
35#include "slang.h"
36#include "slang_rs_export_func.h"
37#include "slang_rs_export_type.h"
38#include "slang_rs_export_var.h"
39#include "slang_rs_exportable.h"
40#include "slang_rs_pragma_handler.h"
41#include "slang_rs_reflection.h"
42
43namespace slang {
44
45RSContext::RSContext(clang::Preprocessor &PP,
46                     clang::ASTContext &Ctx,
47                     const clang::TargetInfo &Target)
48    : mPP(PP),
49      mCtx(Ctx),
50      mTarget(Target),
51      mTargetData(NULL),
52      mLLVMContext(llvm::getGlobalContext()),
53      mLicenseNote(NULL),
54      version(0) {
55  // For #pragma rs export_type
56  PP.AddPragmaHandler(
57      "rs", RSPragmaHandler::CreatePragmaExportTypeHandler(this));
58
59  // For #pragma rs java_package_name
60  PP.AddPragmaHandler(
61      "rs", RSPragmaHandler::CreatePragmaJavaPackageNameHandler(this));
62
63  // For #pragma rs set_reflect_license
64  PP.AddPragmaHandler(
65      "rs", RSPragmaHandler::CreatePragmaReflectLicenseHandler(this));
66
67  // For #pragma version
68  PP.AddPragmaHandler(RSPragmaHandler::CreatePragmaVersionHandler(this));
69
70  // Prepare target data
71  mTargetData = new llvm::TargetData(Target.getTargetDescription());
72
73  return;
74}
75
76bool RSContext::processExportVar(const clang::VarDecl *VD) {
77  assert(!VD->getName().empty() && "Variable name should not be empty");
78
79  // TODO(zonr): some check on variable
80
81  RSExportType *ET = RSExportType::CreateFromDecl(this, VD);
82  if (!ET)
83    return false;
84
85  RSExportVar *EV = new RSExportVar(this, VD, ET);
86  if (EV == NULL)
87    return false;
88  else
89    mExportVars.push_back(EV);
90
91  return true;
92}
93
94static bool isSpecialRSFunc(const llvm::StringRef& Name) {
95  static llvm::StringRef FuncInit("init");
96  static llvm::StringRef FuncRoot("root");
97  return Name.equals(FuncInit) || Name.equals(FuncRoot);
98}
99
100bool RSContext::processExportFunc(const clang::FunctionDecl *FD) {
101  assert(!FD->getName().empty() && "Function name should not be empty");
102
103  if (!FD->isThisDeclarationADefinition()) {
104    return true;
105  }
106
107  if (FD->getStorageClass() != clang::SC_None) {
108    fprintf(stderr, "RSContext::processExportFunc : cannot export extern or "
109                    "static function '%s'\n", FD->getName().str().c_str());
110    return false;
111  }
112
113  // Do not reflect specialized RS functions like init/root.
114  if (isSpecialRSFunc(FD->getName())) {
115    return true;
116  }
117
118  RSExportFunc *EF = RSExportFunc::Create(this, FD);
119  if (EF == NULL)
120    return false;
121  else
122    mExportFuncs.push_back(EF);
123
124  return true;
125}
126
127
128bool RSContext::processExportType(const llvm::StringRef &Name) {
129  clang::TranslationUnitDecl *TUDecl = mCtx.getTranslationUnitDecl();
130
131  assert(TUDecl != NULL && "Translation unit declaration (top-level "
132                           "declaration) is null object");
133
134  const clang::IdentifierInfo *II = mPP.getIdentifierInfo(Name);
135  if (II == NULL)
136    // TODO(zonr): alert identifier @Name mark as an exportable type cannot be
137    //             found
138    return false;
139
140  clang::DeclContext::lookup_const_result R = TUDecl->lookup(II);
141  RSExportType *ET = NULL;
142
143  for (clang::DeclContext::lookup_const_iterator I = R.first, E = R.second;
144       I != E;
145       I++) {
146    clang::NamedDecl *const ND = *I;
147    const clang::Type *T = NULL;
148
149    switch (ND->getKind()) {
150      case clang::Decl::Typedef: {
151        T = static_cast<const clang::TypedefDecl*>(
152            ND)->getCanonicalDecl()->getUnderlyingType().getTypePtr();
153        break;
154      }
155      case clang::Decl::Record: {
156        T = static_cast<const clang::RecordDecl*>(ND)->getTypeForDecl();
157        break;
158      }
159      default: {
160        // unsupported, skip
161        break;
162      }
163    }
164
165    if (T != NULL)
166      ET = RSExportType::Create(this, T);
167  }
168
169  return (ET != NULL);
170}
171
172bool RSContext::processExport() {
173  // Export variable
174  clang::TranslationUnitDecl *TUDecl = mCtx.getTranslationUnitDecl();
175  for (clang::DeclContext::decl_iterator DI = TUDecl->decls_begin(),
176           DE = TUDecl->decls_end();
177       DI != DE;
178       DI++) {
179    if (DI->getKind() == clang::Decl::Var) {
180      clang::VarDecl *VD = (clang::VarDecl*) (*DI);
181      if (VD->getLinkage() == clang::ExternalLinkage) {
182        if (!processExportVar(VD)) {
183          fprintf(stderr, "RSContext::processExport : failed to export var "
184                          "'%s'\n", VD->getNameAsString().c_str());
185          return false;
186        }
187      }
188    } else if (DI->getKind() == clang::Decl::Function) {
189      // Export functions
190      clang::FunctionDecl *FD = (clang::FunctionDecl*) (*DI);
191      if (FD->getLinkage() == clang::ExternalLinkage) {
192        if (!processExportFunc(FD)) {
193          fprintf(stderr, "RSContext::processExport : failed to export func "
194                          "'%s'\n", FD->getNameAsString().c_str());
195          return false;
196        }
197      }
198    }
199  }
200
201  // Finally, export type forcely set to be exported by user
202  for (NeedExportTypeSet::const_iterator EI = mNeedExportTypes.begin(),
203           EE = mNeedExportTypes.end();
204       EI != EE;
205       EI++) {
206    if (!processExportType(EI->getKey())) {
207      fprintf(stderr, "RSContext::processExport : failed to export type "
208              "'%s'\n", EI->getKey().str().c_str());
209      return false;
210    }
211  }
212
213  return true;
214}
215
216bool RSContext::insertExportType(const llvm::StringRef &TypeName,
217                                 RSExportType *ET) {
218  ExportTypeMap::value_type *NewItem =
219      ExportTypeMap::value_type::Create(TypeName.begin(),
220                                        TypeName.end(),
221                                        mExportTypes.getAllocator(),
222                                        ET);
223
224  if (mExportTypes.insert(NewItem)) {
225    return true;
226  } else {
227    free(NewItem);
228    return false;
229  }
230}
231
232bool RSContext::reflectToJava(const std::string &OutputPathBase,
233                              const std::string &OutputPackageName,
234                              const std::string &InputFileName,
235                              const std::string &OutputBCFileName,
236                              std::string *RealPackageName) {
237  if (RealPackageName != NULL)
238    RealPackageName->clear();
239
240  const std::string &PackageName =
241      ((OutputPackageName.empty()) ? mReflectJavaPackageName :
242                                     OutputPackageName);
243  if (PackageName.empty()) {
244    std::cerr << "Error: Missing \"#pragma rs "
245              << "java_package_name(com.foo.bar)\" in "
246              << InputFileName << std::endl;
247    return false;
248  }
249
250  // Copy back the really applied package name
251  RealPackageName->assign(PackageName);
252
253  RSReflection *R = new RSReflection(this);
254  bool ret = R->reflect(OutputPathBase, PackageName,
255                        InputFileName, OutputBCFileName);
256  if (!ret)
257    fprintf(stderr, "RSContext::reflectToJava : failed to do reflection "
258                    "(%s)\n", R->getLastError());
259  delete R;
260  return ret;
261}
262
263RSContext::~RSContext() {
264  delete mLicenseNote;
265  delete mTargetData;
266  for (ExportableList::iterator I = mExportables.begin(),
267          E = mExportables.end();
268       I != E;
269       I++) {
270    if (!(*I)->isKeep())
271      delete *I;
272  }
273}
274
275}  // namespace slang
276