slang_rs_context.cpp revision 3fd0a94a5cf1656569b1aea07043cc63939dcb46
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                     PragmaList *Pragmas)
49    : mPP(PP),
50      mCtx(Ctx),
51      mTarget(Target),
52      mPragmas(Pragmas),
53      mTargetData(NULL),
54      mLLVMContext(llvm::getGlobalContext()),
55      mLicenseNote(NULL),
56      version(0) {
57  // For #pragma rs export_type
58  PP.AddPragmaHandler(
59      "rs", RSPragmaHandler::CreatePragmaExportTypeHandler(this));
60
61  // For #pragma rs java_package_name
62  PP.AddPragmaHandler(
63      "rs", RSPragmaHandler::CreatePragmaJavaPackageNameHandler(this));
64
65  // For #pragma rs set_reflect_license
66  PP.AddPragmaHandler(
67      "rs", RSPragmaHandler::CreatePragmaReflectLicenseHandler(this));
68
69  // For #pragma version
70  PP.AddPragmaHandler(RSPragmaHandler::CreatePragmaVersionHandler(this));
71
72  // Prepare target data
73  mTargetData = new llvm::TargetData(Target.getTargetDescription());
74
75  return;
76}
77
78bool RSContext::processExportVar(const clang::VarDecl *VD) {
79  assert(!VD->getName().empty() && "Variable name should not be empty");
80
81  // TODO(zonr): some check on variable
82
83  RSExportType *ET = RSExportType::CreateFromDecl(this, VD);
84  if (!ET)
85    return false;
86
87  RSExportVar *EV = new RSExportVar(this, VD, ET);
88  if (EV == NULL)
89    return false;
90  else
91    mExportVars.push_back(EV);
92
93  return true;
94}
95
96static bool isSpecialRSFunc(const llvm::StringRef& Name) {
97  static llvm::StringRef FuncInit("init");
98  static llvm::StringRef FuncRoot("root");
99  return Name.equals(FuncInit) || Name.equals(FuncRoot);
100}
101
102bool RSContext::processExportFunc(const clang::FunctionDecl *FD) {
103  assert(!FD->getName().empty() && "Function name should not be empty");
104
105  if (!FD->isThisDeclarationADefinition()) {
106    return true;
107  }
108
109  if (FD->getStorageClass() != clang::SC_None) {
110    fprintf(stderr, "RSContext::processExportFunc : cannot export extern or "
111                    "static function '%s'\n", FD->getName().str().c_str());
112    return false;
113  }
114
115  // Do not reflect specialized RS functions like init/root.
116  if (isSpecialRSFunc(FD->getName())) {
117    return true;
118  }
119
120  RSExportFunc *EF = RSExportFunc::Create(this, FD);
121  if (EF == NULL)
122    return false;
123  else
124    mExportFuncs.push_back(EF);
125
126  return true;
127}
128
129
130bool RSContext::processExportType(const llvm::StringRef &Name) {
131  clang::TranslationUnitDecl *TUDecl = mCtx.getTranslationUnitDecl();
132
133  assert(TUDecl != NULL && "Translation unit declaration (top-level "
134                           "declaration) is null object");
135
136  const clang::IdentifierInfo *II = mPP.getIdentifierInfo(Name);
137  if (II == NULL)
138    // TODO(zonr): alert identifier @Name mark as an exportable type cannot be
139    //             found
140    return false;
141
142  clang::DeclContext::lookup_const_result R = TUDecl->lookup(II);
143  RSExportType *ET = NULL;
144
145  for (clang::DeclContext::lookup_const_iterator I = R.first, E = R.second;
146       I != E;
147       I++) {
148    clang::NamedDecl *const ND = *I;
149    const clang::Type *T = NULL;
150
151    switch (ND->getKind()) {
152      case clang::Decl::Typedef: {
153        T = static_cast<const clang::TypedefDecl*>(
154            ND)->getCanonicalDecl()->getUnderlyingType().getTypePtr();
155        break;
156      }
157      case clang::Decl::Record: {
158        T = static_cast<const clang::RecordDecl*>(ND)->getTypeForDecl();
159        break;
160      }
161      default: {
162        // unsupported, skip
163        break;
164      }
165    }
166
167    if (T != NULL)
168      ET = RSExportType::Create(this, T);
169  }
170
171  return (ET != NULL);
172}
173
174bool RSContext::processExport() {
175  // Export variable
176  clang::TranslationUnitDecl *TUDecl = mCtx.getTranslationUnitDecl();
177  for (clang::DeclContext::decl_iterator DI = TUDecl->decls_begin(),
178           DE = TUDecl->decls_end();
179       DI != DE;
180       DI++) {
181    if (DI->getKind() == clang::Decl::Var) {
182      clang::VarDecl *VD = (clang::VarDecl*) (*DI);
183      if (VD->getLinkage() == clang::ExternalLinkage) {
184        if (!processExportVar(VD)) {
185          fprintf(stderr, "RSContext::processExport : failed to export var "
186                          "'%s'\n", VD->getNameAsString().c_str());
187          return false;
188        }
189      }
190    } else if (DI->getKind() == clang::Decl::Function) {
191      // Export functions
192      clang::FunctionDecl *FD = (clang::FunctionDecl*) (*DI);
193      if (FD->getLinkage() == clang::ExternalLinkage) {
194        if (!processExportFunc(FD)) {
195          fprintf(stderr, "RSContext::processExport : failed to export func "
196                          "'%s'\n", FD->getNameAsString().c_str());
197          return false;
198        }
199      }
200    }
201  }
202
203  // Finally, export type forcely set to be exported by user
204  for (NeedExportTypeSet::const_iterator EI = mNeedExportTypes.begin(),
205           EE = mNeedExportTypes.end();
206       EI != EE;
207       EI++) {
208    if (!processExportType(EI->getKey())) {
209      fprintf(stderr, "RSContext::processExport : failed to export type "
210              "'%s'\n", EI->getKey().str().c_str());
211      return false;
212    }
213  }
214
215  return true;
216}
217
218bool RSContext::insertExportType(const llvm::StringRef &TypeName,
219                                 RSExportType *ET) {
220  ExportTypeMap::value_type *NewItem =
221      ExportTypeMap::value_type::Create(TypeName.begin(),
222                                        TypeName.end(),
223                                        mExportTypes.getAllocator(),
224                                        ET);
225
226  if (mExportTypes.insert(NewItem)) {
227    return true;
228  } else {
229    free(NewItem);
230    return false;
231  }
232}
233
234bool RSContext::reflectToJava(const std::string &OutputPathBase,
235                              const std::string &OutputPackageName,
236                              const std::string &InputFileName,
237                              const std::string &OutputBCFileName,
238                              std::string *RealPackageName) {
239  if (RealPackageName != NULL)
240    RealPackageName->clear();
241
242  const std::string &PackageName =
243      ((OutputPackageName.empty()) ? mReflectJavaPackageName :
244                                     OutputPackageName);
245  if (PackageName.empty()) {
246    std::cerr << "Error: Missing \"#pragma rs "
247              << "java_package_name(com.foo.bar)\" in "
248              << InputFileName << std::endl;
249    return false;
250  }
251
252  // Copy back the really applied package name
253  RealPackageName->assign(PackageName);
254
255  RSReflection *R = new RSReflection(this);
256  bool ret = R->reflect(OutputPathBase, PackageName,
257                        InputFileName, OutputBCFileName);
258  if (!ret)
259    fprintf(stderr, "RSContext::reflectToJava : failed to do reflection "
260                    "(%s)\n", R->getLastError());
261  delete R;
262  return ret;
263}
264
265RSContext::~RSContext() {
266  delete mLicenseNote;
267  delete mTargetData;
268  for (ExportableList::iterator I = mExportables.begin(),
269          E = mExportables.end();
270       I != E;
271       I++) {
272    if (!(*I)->isKeep())
273      delete *I;
274  }
275}
276
277}  // namespace slang
278