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