slang_rs_reflection.cpp revision 536aef0dd1befdfef5786e3a8bc80d81ccc3625b
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_reflection.h"
18
19#include <sys/stat.h>
20
21#include <cstdarg>
22#include <cctype>
23
24#include <algorithm>
25#include <string>
26#include <utility>
27
28#include "llvm/ADT/APFloat.h"
29#include "llvm/ADT/StringExtras.h"
30
31#include "slang_rs_context.h"
32#include "slang_rs_export_var.h"
33#include "slang_rs_export_func.h"
34#include "slang_rs_reflect_utils.h"
35#include "slang_utils.h"
36
37#define RS_SCRIPT_CLASS_NAME_PREFIX      "ScriptC_"
38#define RS_SCRIPT_CLASS_SUPER_CLASS_NAME "ScriptC"
39
40#define RS_TYPE_CLASS_NAME_PREFIX        "ScriptField_"
41#define RS_TYPE_CLASS_SUPER_CLASS_NAME   "android.renderscript.Script.FieldBase"
42
43#define RS_TYPE_ITEM_CLASS_NAME          "Item"
44
45#define RS_TYPE_ITEM_BUFFER_NAME         "mItemArray"
46#define RS_TYPE_ITEM_BUFFER_PACKER_NAME  "mIOBuffer"
47
48#define RS_EXPORT_VAR_INDEX_PREFIX       "mExportVarIdx_"
49#define RS_EXPORT_VAR_PREFIX             "mExportVar_"
50
51#define RS_EXPORT_FUNC_INDEX_PREFIX      "mExportFuncIdx_"
52
53#define RS_EXPORT_VAR_ALLOCATION_PREFIX  "mAlloction_"
54#define RS_EXPORT_VAR_DATA_STORAGE_PREFIX "mData_"
55
56namespace slang {
57
58// Some utility function using internal in RSReflection
59static bool GetClassNameFromFileName(const std::string &FileName,
60                                     std::string &ClassName) {
61  ClassName.clear();
62
63  if (FileName.empty() || (FileName == "-"))
64    return true;
65
66  ClassName =
67      RSSlangReflectUtils::JavaClassNameFromRSFileName(FileName.c_str());
68
69  return true;
70}
71
72static const char *GetPrimitiveTypeName(const RSExportPrimitiveType *EPT) {
73  static const char *PrimitiveTypeJavaNameMap[] = {
74    "",         // RSExportPrimitiveType::DataTypeFloat16
75    "float",    // RSExportPrimitiveType::DataTypeFloat32
76    "double",   // RSExportPrimitiveType::DataTypeFloat64
77    "byte",     // RSExportPrimitiveType::DataTypeSigned8
78    "short",    // RSExportPrimitiveType::DataTypeSigned16
79    "int",      // RSExportPrimitiveType::DataTypeSigned32
80    "long",     // RSExportPrimitiveType::DataTypeSigned64
81    "short",    // RSExportPrimitiveType::DataTypeUnsigned8
82    "int",      // RSExportPrimitiveType::DataTypeUnsigned16
83    "long",     // RSExportPrimitiveType::DataTypeUnsigned32
84    "long",     // RSExportPrimitiveType::DataTypeUnsigned64
85    "boolean",  // RSExportPrimitiveType::DataTypeBoolean
86
87    "int",      // RSExportPrimitiveType::DataTypeUnsigned565
88    "int",      // RSExportPrimitiveType::DataTypeUnsigned5551
89    "int",      // RSExportPrimitiveType::DataTypeUnsigned4444
90
91    "",     // (Dummy) RSExportPrimitiveType::DataTypeRSMatrix2x2
92    "",     // (Dummy) RSExportPrimitiveType::DataTypeRSMatrix3x3
93    "",     // (Dummy) RSExportPrimitiveType::DataTypeRSMatrix4x4
94
95    "Element",      // RSExportPrimitiveType::DataTypeRSElement
96    "Type",         // RSExportPrimitiveType::DataTypeRSType
97    "Allocation",   // RSExportPrimitiveType::DataTypeRSAllocation
98    "Sampler",      // RSExportPrimitiveType::DataTypeRSSampler
99    "Script",       // RSExportPrimitiveType::DataTypeRSScript
100    "Mesh",         // RSExportPrimitiveType::DataTypeRSMesh
101    "ProgramFragment",  // RSExportPrimitiveType::DataTypeRSProgramFragment
102    "ProgramVertex",    // RSExportPrimitiveType::DataTypeRSProgramVertex
103    "ProgramRaster",    // RSExportPrimitiveType::DataTypeRSProgramRaster
104    "ProgramStore",     // RSExportPrimitiveType::DataTypeRSProgramStore
105    "Font",     // RSExportPrimitiveType::DataTypeRSFont
106  };
107  unsigned TypeId = EPT->getType();
108
109  if (TypeId < (sizeof(PrimitiveTypeJavaNameMap) / sizeof(const char*))) {
110    return PrimitiveTypeJavaNameMap[ EPT->getType() ];
111  }
112
113  assert(false && "GetPrimitiveTypeName : Unknown primitive data type");
114  return NULL;
115}
116
117static const char *GetVectorTypeName(const RSExportVectorType *EVT) {
118  static const char *VectorTypeJavaNameMap[][3] = {
119    /* 0 */ { "Byte2",  "Byte3",    "Byte4" },
120    /* 1 */ { "Short2", "Short3",   "Short4" },
121    /* 2 */ { "Int2",   "Int3",     "Int4" },
122    /* 3 */ { "Long2",  "Long3",    "Long4" },
123    /* 4 */ { "Float2", "Float3",   "Float4" },
124  };
125
126  const char **BaseElement = NULL;
127
128  switch (EVT->getType()) {
129    case RSExportPrimitiveType::DataTypeSigned8:
130    case RSExportPrimitiveType::DataTypeBoolean: {
131      BaseElement = VectorTypeJavaNameMap[0];
132      break;
133    }
134    case RSExportPrimitiveType::DataTypeSigned16:
135    case RSExportPrimitiveType::DataTypeUnsigned8: {
136      BaseElement = VectorTypeJavaNameMap[1];
137      break;
138    }
139    case RSExportPrimitiveType::DataTypeSigned32:
140    case RSExportPrimitiveType::DataTypeUnsigned16: {
141      BaseElement = VectorTypeJavaNameMap[2];
142      break;
143    }
144    case RSExportPrimitiveType::DataTypeSigned64:
145    case RSExportPrimitiveType::DataTypeUnsigned64:
146    case RSExportPrimitiveType::DataTypeUnsigned32: {
147      BaseElement = VectorTypeJavaNameMap[3];
148      break;
149    }
150    case RSExportPrimitiveType::DataTypeFloat32: {
151      BaseElement = VectorTypeJavaNameMap[4];
152      break;
153    }
154    default: {
155      assert(false && "RSReflection::genElementTypeName : Unsupported vector "
156                      "element data type");
157      break;
158    }
159  }
160
161  assert((EVT->getNumElement() > 1) &&
162         (EVT->getNumElement() <= 4) &&
163         "Number of element in vector type is invalid");
164
165  return BaseElement[EVT->getNumElement() - 2];
166}
167
168static const char *GetMatrixTypeName(const RSExportMatrixType *EMT) {
169  static const char *MatrixTypeJavaNameMap[] = {
170    /* 2x2 */ "Matrix2f",
171    /* 3x3 */ "Matrix3f",
172    /* 4x4 */ "Matrix4f",
173  };
174  unsigned Dim = EMT->getDim();
175
176  if ((Dim - 2) < (sizeof(MatrixTypeJavaNameMap) / sizeof(const char*)))
177    return MatrixTypeJavaNameMap[ EMT->getDim() - 2 ];
178
179  assert(false && "GetMatrixTypeName : Unsupported matrix dimension");
180  return NULL;
181}
182
183static const char *GetVectorAccessor(int Index) {
184  static const char *VectorAccessorMap[] = {
185    /* 0 */ "x",
186    /* 1 */ "y",
187    /* 2 */ "z",
188    /* 3 */ "w",
189  };
190
191  assert((Index >= 0) &&
192         (Index < (sizeof(VectorAccessorMap) / sizeof(const char*))) &&
193         "Out-of-bound index to access vector member");
194
195  return VectorAccessorMap[Index];
196}
197
198static const char *GetPackerAPIName(const RSExportPrimitiveType *EPT) {
199  static const char *PrimitiveTypePackerAPINameMap[] = {
200    "",         // RSExportPrimitiveType::DataTypeFloat16
201    "addF32",   // RSExportPrimitiveType::DataTypeFloat32
202    "addF64",   // RSExportPrimitiveType::DataTypeFloat64
203    "addI8",    // RSExportPrimitiveType::DataTypeSigned8
204    "addI16",   // RSExportPrimitiveType::DataTypeSigned16
205    "addI32",   // RSExportPrimitiveType::DataTypeSigned32
206    "addI64",   // RSExportPrimitiveType::DataTypeSigned64
207    "addU8",    // RSExportPrimitiveType::DataTypeUnsigned8
208    "addU16",   // RSExportPrimitiveType::DataTypeUnsigned16
209    "addU32",   // RSExportPrimitiveType::DataTypeUnsigned32
210    "addU64",   // RSExportPrimitiveType::DataTypeUnsigned64
211    "addBoolean",  // RSExportPrimitiveType::DataTypeBoolean
212
213    "addU16",   // RSExportPrimitiveType::DataTypeUnsigned565
214    "addU16",   // RSExportPrimitiveType::DataTypeUnsigned5551
215    "addU16",   // RSExportPrimitiveType::DataTypeUnsigned4444
216
217    "addObj",   // RSExportPrimitiveType::DataTypeRSMatrix2x2
218    "addObj",   // RSExportPrimitiveType::DataTypeRSMatrix3x3
219    "addObj",   // RSExportPrimitiveType::DataTypeRSMatrix4x4
220
221    "addObj",   // RSExportPrimitiveType::DataTypeRSElement
222    "addObj",   // RSExportPrimitiveType::DataTypeRSType
223    "addObj",   // RSExportPrimitiveType::DataTypeRSAllocation
224    "addObj",   // RSExportPrimitiveType::DataTypeRSSampler
225    "addObj",   // RSExportPrimitiveType::DataTypeRSScript
226    "addObj",   // RSExportPrimitiveType::DataTypeRSMesh
227    "addObj",   // RSExportPrimitiveType::DataTypeRSProgramFragment
228    "addObj",   // RSExportPrimitiveType::DataTypeRSProgramVertex
229    "addObj",   // RSExportPrimitiveType::DataTypeRSProgramRaster
230    "addObj",   // RSExportPrimitiveType::DataTypeRSProgramStore
231    "addObj",   // RSExportPrimitiveType::DataTypeRSFont
232  };
233  unsigned TypeId = EPT->getType();
234
235  if (TypeId < (sizeof(PrimitiveTypePackerAPINameMap) / sizeof(const char*)))
236    return PrimitiveTypePackerAPINameMap[ EPT->getType() ];
237
238  assert(false && "GetPackerAPIName : Unknown primitive data type");
239  return NULL;
240}
241
242static std::string GetTypeName(const RSExportType *ET) {
243  switch (ET->getClass()) {
244    case RSExportType::ExportClassPrimitive: {
245      return GetPrimitiveTypeName(
246                static_cast<const RSExportPrimitiveType*>(ET));
247    }
248    case RSExportType::ExportClassPointer: {
249      const RSExportType *PointeeType =
250          static_cast<const RSExportPointerType*>(ET)->getPointeeType();
251
252      if (PointeeType->getClass() != RSExportType::ExportClassRecord)
253        return "Allocation";
254      else
255        return RS_TYPE_CLASS_NAME_PREFIX + PointeeType->getName();
256    }
257    case RSExportType::ExportClassVector: {
258      return GetVectorTypeName(static_cast<const RSExportVectorType*>(ET));
259    }
260    case RSExportType::ExportClassMatrix: {
261      return GetMatrixTypeName(static_cast<const RSExportMatrixType*>(ET));
262    }
263    case RSExportType::ExportClassConstantArray: {
264      const RSExportConstantArrayType* CAT =
265          static_cast<const RSExportConstantArrayType*>(ET);
266      std::string ElementTypeName = GetTypeName(CAT->getElementType());
267      ElementTypeName.append("[]");
268      return ElementTypeName;
269    }
270    case RSExportType::ExportClassRecord: {
271      return RS_TYPE_CLASS_NAME_PREFIX + ET->getName() +
272                 "."RS_TYPE_ITEM_CLASS_NAME;
273    }
274    default: {
275      assert(false && "Unknown class of type");
276    }
277  }
278
279  return "";
280}
281
282static const char *GetTypeNullValue(const RSExportType *ET) {
283  switch (ET->getClass()) {
284    case RSExportType::ExportClassPrimitive: {
285      const RSExportPrimitiveType *EPT =
286          static_cast<const RSExportPrimitiveType*>(ET);
287      if (EPT->isRSObjectType())
288        return "null";
289      else if (EPT->getType() == RSExportPrimitiveType::DataTypeBoolean)
290        return "false";
291      else
292        return "0";
293      break;
294    }
295    case RSExportType::ExportClassPointer:
296    case RSExportType::ExportClassVector:
297    case RSExportType::ExportClassMatrix:
298    case RSExportType::ExportClassConstantArray:
299    case RSExportType::ExportClassRecord: {
300      return "null";
301      break;
302    }
303    default: {
304      assert(false && "Unknown class of type");
305    }
306  }
307  return "";
308}
309
310static const char *GetBuiltinElementConstruct(const RSExportType *ET) {
311  if (ET->getClass() == RSExportType::ExportClassPrimitive) {
312    const RSExportPrimitiveType *EPT =
313        static_cast<const RSExportPrimitiveType*>(ET);
314    if (EPT->getKind() == RSExportPrimitiveType::DataKindUser) {
315      static const char *PrimitiveBuiltinElementConstructMap[] = {
316        NULL,               // RSExportPrimitiveType::DataTypeFloat16
317        "Element.F32",      // RSExportPrimitiveType::DataTypeFloat32
318        "Element.F64",      // RSExportPrimitiveType::DataTypeFloat64
319        "Element.I8",       // RSExportPrimitiveType::DataTypeSigned8
320        NULL,               // RSExportPrimitiveType::DataTypeSigned16
321        "Element.I32",      // RSExportPrimitiveType::DataTypeSigned32
322        "Element.I64",      // RSExportPrimitiveType::DataTypeSigned64
323        "Element.U8",       // RSExportPrimitiveType::DataTypeUnsigned8
324        NULL,               // RSExportPrimitiveType::DataTypeUnsigned16
325        "Element.U32",      // RSExportPrimitiveType::DataTypeUnsigned32
326        "Element.U64",      // RSExportPrimitiveType::DataTypeUnsigned64
327        "Element.BOOLEAN",  // RSExportPrimitiveType::DataTypeBoolean
328
329        NULL,   // RSExportPrimitiveType::DataTypeUnsigned565
330        NULL,   // RSExportPrimitiveType::DataTypeUnsigned5551
331        NULL,   // RSExportPrimitiveType::DataTypeUnsigned4444
332
333        NULL,   // (Dummy) RSExportPrimitiveType::DataTypeRSMatrix2x2
334        NULL,   // (Dummy) RSExportPrimitiveType::DataTypeRSMatrix3x3
335        NULL,   // (Dummy) RSExportPrimitiveType::DataTypeRSMatrix4x4
336
337        "Element.ELEMENT",      // RSExportPrimitiveType::DataTypeRSElement
338        "Element.TYPE",         // RSExportPrimitiveType::DataTypeRSType
339        "Element.ALLOCATION",   // RSExportPrimitiveType::DataTypeRSAllocation
340        "Element.SAMPLER",      // RSExportPrimitiveType::DataTypeRSSampler
341        "Element.SCRIPT",       // RSExportPrimitiveType::DataTypeRSScript
342        "Element.MESH",         // RSExportPrimitiveType::DataTypeRSMesh
343        "Element.PROGRAM_FRAGMENT",
344          // RSExportPrimitiveType::DataTypeRSProgramFragment
345        "Element.PROGRAM_VERTEX",
346          // RSExportPrimitiveType::DataTypeRSProgramVertex
347        "Element.PROGRAM_RASTER",
348          // RSExportPrimitiveType::DataTypeRSProgramRaster
349        "Element.PROGRAM_STORE",
350          // RSExportPrimitiveType::DataTypeRSProgramStore
351        "Element.FONT",
352          // RSExportPrimitiveType::DataTypeRSFont
353      };
354      unsigned TypeId = EPT->getType();
355
356      if (TypeId <
357          (sizeof(PrimitiveBuiltinElementConstructMap) / sizeof(const char*)))
358        return PrimitiveBuiltinElementConstructMap[ EPT->getType() ];
359    } else if (EPT->getKind() == RSExportPrimitiveType::DataKindPixelA) {
360      if (EPT->getType() == RSExportPrimitiveType::DataTypeUnsigned8)
361        return "Element.A_8";
362    } else if (EPT->getKind() == RSExportPrimitiveType::DataKindPixelRGB) {
363      if (EPT->getType() == RSExportPrimitiveType::DataTypeUnsigned565)
364        return "Element.RGB_565";
365      else if (EPT->getType() == RSExportPrimitiveType::DataTypeUnsigned8)
366        return "Element.RGB_888";
367    } else if (EPT->getKind() == RSExportPrimitiveType::DataKindPixelRGBA) {
368      if (EPT->getType() == RSExportPrimitiveType::DataTypeUnsigned5551)
369        return "Element.RGBA_5551";
370      else if (EPT->getType() == RSExportPrimitiveType::DataTypeUnsigned4444)
371        return "Element.RGBA_4444";
372      else if (EPT->getType() == RSExportPrimitiveType::DataTypeUnsigned8)
373        return "Element.RGBA_8888";
374    }
375  } else if (ET->getClass() == RSExportType::ExportClassVector) {
376    const RSExportVectorType *EVT = static_cast<const RSExportVectorType*>(ET);
377    if (EVT->getKind() == RSExportPrimitiveType::DataKindUser) {
378      if (EVT->getType() == RSExportPrimitiveType::DataTypeFloat32) {
379        if (EVT->getNumElement() == 2)
380          return "Element.F32_2";
381        else if (EVT->getNumElement() == 3)
382          return "Element.F32_3";
383        else if (EVT->getNumElement() == 4)
384          return "Element.F32_4";
385      } else if (EVT->getType() == RSExportPrimitiveType::DataTypeUnsigned8) {
386        if (EVT->getNumElement() == 4)
387          return "Element.U8_4";
388      }
389    }
390  } else if (ET->getClass() == RSExportType::ExportClassMatrix) {
391    const RSExportMatrixType *EMT = static_cast<const RSExportMatrixType *>(ET);
392    switch (EMT->getDim()) {
393      case 2: return "Element.MATRIX_2X2";
394      case 3: return "Element.MATRIX_3X3";
395      case 4: return "Element.MATRIX_4X4";
396      default: assert(false && "Unsupported dimension of matrix");
397    }
398  } else if (ET->getClass() == RSExportType::ExportClassPointer) {
399    // Treat pointer type variable as unsigned int
400    // TODO(zonr): this is target dependent
401    return "Element.USER_I32";
402  }
403
404  return NULL;
405}
406
407static const char *GetElementDataKindName(RSExportPrimitiveType::DataKind DK) {
408  static const char *ElementDataKindNameMap[] = {
409    "Element.DataKind.USER",        // RSExportPrimitiveType::DataKindUser
410    "Element.DataKind.PIXEL_L",     // RSExportPrimitiveType::DataKindPixelL
411    "Element.DataKind.PIXEL_A",     // RSExportPrimitiveType::DataKindPixelA
412    "Element.DataKind.PIXEL_LA",    // RSExportPrimitiveType::DataKindPixelLA
413    "Element.DataKind.PIXEL_RGB",   // RSExportPrimitiveType::DataKindPixelRGB
414    "Element.DataKind.PIXEL_RGBA",  // RSExportPrimitiveType::DataKindPixelRGBA
415  };
416
417  if (static_cast<unsigned>(DK) <
418      (sizeof(ElementDataKindNameMap) / sizeof(const char*)))
419    return ElementDataKindNameMap[ DK ];
420  else
421    return NULL;
422}
423
424static const char *GetElementDataTypeName(RSExportPrimitiveType::DataType DT) {
425  static const char *ElementDataTypeNameMap[] = {
426    NULL,                            // RSExportPrimitiveType::DataTypeFloat16
427    "Element.DataType.FLOAT_32",     // RSExportPrimitiveType::DataTypeFloat32
428    "Element.DataType.FLOAT_64",     // RSExportPrimitiveType::DataTypeFloat64
429    "Element.DataType.SIGNED_8",     // RSExportPrimitiveType::DataTypeSigned8
430    "Element.DataType.SIGNED_16",    // RSExportPrimitiveType::DataTypeSigned16
431    "Element.DataType.SIGNED_32",    // RSExportPrimitiveType::DataTypeSigned32
432    "Element.DataType.SIGNED_64",    // RSExportPrimitiveType::DataTypeSigned64
433    "Element.DataType.UNSIGNED_8",   // RSExportPrimitiveType::DataTypeUnsigned8
434    "Element.DataType.UNSIGNED_16",
435      // RSExportPrimitiveType::DataTypeUnsigned16
436    "Element.DataType.UNSIGNED_32",
437      // RSExportPrimitiveType::DataTypeUnsigned32
438    "Element.DataType.UNSIGNED_64",
439      // RSExportPrimitiveType::DataTypeUnsigned64
440    "Element.DataType.BOOLEAN",
441      // RSExportPrimitiveType::DataTypeBoolean
442
443    // RSExportPrimitiveType::DataTypeUnsigned565
444    "Element.DataType.UNSIGNED_5_6_5",
445    // RSExportPrimitiveType::DataTypeUnsigned5551
446    "Element.DataType.UNSIGNED_5_5_5_1",
447    // RSExportPrimitiveType::DataTypeUnsigned4444
448    "Element.DataType.UNSIGNED_4_4_4_4",
449
450    // DataTypeRSMatrix* must have been resolved in GetBuiltinElementConstruct()
451    NULL,  // (Dummy) RSExportPrimitiveType::DataTypeRSMatrix2x2
452    NULL,  // (Dummy) RSExportPrimitiveType::DataTypeRSMatrix3x3
453    NULL,  // (Dummy) RSExportPrimitiveType::DataTypeRSMatrix4x4
454
455    "Element.DataType.RS_ELEMENT",  // RSExportPrimitiveType::DataTypeRSElement
456    "Element.DataType.RS_TYPE",     // RSExportPrimitiveType::DataTypeRSType
457      // RSExportPrimitiveType::DataTypeRSAllocation
458    "Element.DataType.RS_ALLOCATION",
459      // RSExportPrimitiveType::DataTypeRSSampler
460    "Element.DataType.RS_SAMPLER",
461      // RSExportPrimitiveType::DataTypeRSScript
462    "Element.DataType.RS_SCRIPT",
463      // RSExportPrimitiveType::DataTypeRSMesh
464    "Element.DataType.RS_MESH",
465      // RSExportPrimitiveType::DataTypeRSProgramFragment
466    "Element.DataType.RS_PROGRAM_FRAGMENT",
467      // RSExportPrimitiveType::DataTypeRSProgramVertex
468    "Element.DataType.RS_PROGRAM_VERTEX",
469      // RSExportPrimitiveType::DataTypeRSProgramRaster
470    "Element.DataType.RS_PROGRAM_RASTER",
471      // RSExportPrimitiveType::DataTypeRSProgramStore
472    "Element.DataType.RS_PROGRAM_STORE",
473      // RSExportPrimitiveType::DataTypeRSFont
474    "Element.DataType.RS_FONT",
475  };
476
477  if (static_cast<unsigned>(DT) <
478      (sizeof(ElementDataTypeNameMap) / sizeof(const char*)))
479    return ElementDataTypeNameMap[ DT ];
480  else
481    return NULL;
482}
483
484/********************** Methods to generate script class **********************/
485bool RSReflection::genScriptClass(Context &C,
486                                  const std::string &ClassName,
487                                  std::string &ErrorMsg) {
488  if (!C.startClass(Context::AM_Public,
489                    false,
490                    ClassName,
491                    RS_SCRIPT_CLASS_SUPER_CLASS_NAME,
492                    ErrorMsg))
493    return false;
494
495  genScriptClassConstructor(C);
496
497  // Reflect export variable
498  for (RSContext::const_export_var_iterator I = mRSContext->export_vars_begin(),
499           E = mRSContext->export_vars_end();
500       I != E;
501       I++)
502    genExportVariable(C, *I);
503
504  // Reflect export function
505  for (RSContext::const_export_func_iterator
506           I = mRSContext->export_funcs_begin(),
507           E = mRSContext->export_funcs_end();
508       I != E; I++)
509    genExportFunction(C, *I);
510
511  C.endClass();
512
513  return true;
514}
515
516void RSReflection::genScriptClassConstructor(Context &C) {
517  C.indent() << "// Constructor" << std::endl;
518  C.startFunction(Context::AM_Public,
519                  false,
520                  NULL,
521                  C.getClassName(),
522                  3,
523                  "RenderScript", "rs",
524                  "Resources", "resources",
525                  "int", "id");
526  // Call constructor of super class
527  C.indent() << "super(rs, resources, id);" << std::endl;
528
529  // If an exported variable has initial value, reflect it
530
531  for (RSContext::const_export_var_iterator I = mRSContext->export_vars_begin(),
532           E = mRSContext->export_vars_end();
533       I != E;
534       I++) {
535    const RSExportVar *EV = *I;
536    if (!EV->getInit().isUninit())
537      genInitExportVariable(C, EV->getType(), EV->getName(), EV->getInit());
538  }
539
540  C.endFunction();
541
542  return;
543}
544
545void RSReflection::genInitBoolExportVariable(Context &C,
546                                             const std::string &VarName,
547                                             const clang::APValue &Val) {
548  assert(!Val.isUninit() && "Not a valid initializer");
549
550  C.indent() << RS_EXPORT_VAR_PREFIX << VarName << " = ";
551  assert((Val.getKind() == clang::APValue::Int) &&
552         "Bool type has wrong initial APValue");
553
554  C.out() << ((Val.getInt().getSExtValue() == 0) ? "false" : "true")
555          << ";" << std::endl;
556
557  return;
558}
559
560void RSReflection::genInitPrimitiveExportVariable(
561      Context &C,
562      const std::string &VarName,
563      const clang::APValue &Val) {
564  assert(!Val.isUninit() && "Not a valid initializer");
565
566  C.indent() << RS_EXPORT_VAR_PREFIX << VarName << " = ";
567  switch (Val.getKind()) {
568    case clang::APValue::Int: {
569      llvm::APInt api = Val.getInt();
570      C.out() << api.getSExtValue();
571      if (api.getBitWidth() > 32) {
572        C.out() << "L";
573      }
574      break;
575    }
576    case clang::APValue::Float: {
577      llvm::APFloat apf = Val.getFloat();
578      if (&apf.getSemantics() == &llvm::APFloat::IEEEsingle) {
579        C.out() << apf.convertToFloat() << "f";
580      } else {
581        C.out() << apf.convertToDouble();
582      }
583      break;
584    }
585
586    case clang::APValue::ComplexInt:
587    case clang::APValue::ComplexFloat:
588    case clang::APValue::LValue:
589    case clang::APValue::Vector: {
590      assert(false && "Primitive type cannot have such kind of initializer");
591      break;
592    }
593    default: {
594      assert(false && "Unknown kind of initializer");
595    }
596  }
597  C.out() << ";" << std::endl;
598
599  return;
600}
601
602void RSReflection::genInitExportVariable(Context &C,
603                                         const RSExportType *ET,
604                                         const std::string &VarName,
605                                         const clang::APValue &Val) {
606  assert(!Val.isUninit() && "Not a valid initializer");
607
608  switch (ET->getClass()) {
609    case RSExportType::ExportClassPrimitive: {
610      const RSExportPrimitiveType *EPT =
611          static_cast<const RSExportPrimitiveType*>(ET);
612      if (EPT->getType() == RSExportPrimitiveType::DataTypeBoolean) {
613        genInitBoolExportVariable(C, VarName, Val);
614      } else {
615        genInitPrimitiveExportVariable(C, VarName, Val);
616      }
617      break;
618    }
619    case RSExportType::ExportClassPointer: {
620      if (!Val.isInt() || Val.getInt().getSExtValue() != 0)
621        std::cout << "Initializer which is non-NULL to pointer type variable "
622                     "will be ignored" << std::endl;
623      break;
624    }
625    case RSExportType::ExportClassVector: {
626      const RSExportVectorType *EVT =
627          static_cast<const RSExportVectorType*>(ET);
628      switch (Val.getKind()) {
629        case clang::APValue::Int:
630        case clang::APValue::Float: {
631          for (unsigned i = 0; i < EVT->getNumElement(); i++) {
632            std::string Name =  VarName + "." + GetVectorAccessor(i);
633            genInitPrimitiveExportVariable(C, Name, Val);
634          }
635          break;
636        }
637        case clang::APValue::Vector: {
638          C.indent() << RS_EXPORT_VAR_PREFIX << VarName << " = new "
639                     << GetVectorTypeName(EVT) << "();" << std::endl;
640
641          unsigned NumElements =
642              std::min(static_cast<unsigned>(EVT->getNumElement()),
643                       Val.getVectorLength());
644          for (unsigned i = 0; i < NumElements; i++) {
645            const clang::APValue &ElementVal = Val.getVectorElt(i);
646            std::string Name = VarName + "." + GetVectorAccessor(i);
647            genInitPrimitiveExportVariable(C, Name, ElementVal);
648          }
649          break;
650        }
651        case clang::APValue::Uninitialized:
652        case clang::APValue::ComplexInt:
653        case clang::APValue::ComplexFloat:
654        case clang::APValue::LValue: {
655          assert(false && "Unexpected type of value of initializer.");
656        }
657      }
658      break;
659    }
660    // TODO(zonr): Resolving initializer of a record (and matrix) type variable
661    // is complex. It cannot obtain by just simply evaluating the initializer
662    // expression.
663    case RSExportType::ExportClassMatrix:
664    case RSExportType::ExportClassConstantArray:
665    case RSExportType::ExportClassRecord: {
666#if 0
667      unsigned InitIndex = 0;
668      const RSExportRecordType *ERT =
669          static_cast<const RSExportRecordType*>(ET);
670
671      assert((Val.getKind() == clang::APValue::Vector) && "Unexpected type of "
672             "initializer for record type variable");
673
674      C.indent() << RS_EXPORT_VAR_PREFIX << VarName
675                 << " = new "RS_TYPE_CLASS_NAME_PREFIX << ERT->getName()
676                 <<  "."RS_TYPE_ITEM_CLASS_NAME"();" << std::endl;
677
678      for (RSExportRecordType::const_field_iterator I = ERT->fields_begin(),
679               E = ERT->fields_end();
680           I != E;
681           I++) {
682        const RSExportRecordType::Field *F = *I;
683        std::string FieldName = VarName + "." + F->getName();
684
685        if (InitIndex > Val.getVectorLength())
686          break;
687
688        genInitPrimitiveExportVariable(C,
689                                       FieldName,
690                                       Val.getVectorElt(InitIndex++));
691      }
692#endif
693      assert(false && "Unsupported initializer for record/matrix/constant "
694                      "array type variable currently");
695      break;
696    }
697    default: {
698      assert(false && "Unknown class of type");
699    }
700  }
701  return;
702}
703
704void RSReflection::genExportVariable(Context &C, const RSExportVar *EV) {
705  const RSExportType *ET = EV->getType();
706
707  C.indent() << "private final static int "RS_EXPORT_VAR_INDEX_PREFIX
708             << EV->getName() << " = " << C.getNextExportVarSlot() << ";"
709             << std::endl;
710
711  switch (ET->getClass()) {
712    case RSExportType::ExportClassPrimitive: {
713      genPrimitiveTypeExportVariable(C, EV);
714      break;
715    }
716    case RSExportType::ExportClassPointer: {
717      genPointerTypeExportVariable(C, EV);
718      break;
719    }
720    case RSExportType::ExportClassVector: {
721      genVectorTypeExportVariable(C, EV);
722      break;
723    }
724    case RSExportType::ExportClassMatrix: {
725      genMatrixTypeExportVariable(C, EV);
726      break;
727    }
728    case RSExportType::ExportClassConstantArray: {
729      genConstantArrayTypeExportVariable(C, EV);
730      break;
731    }
732    case RSExportType::ExportClassRecord: {
733      genRecordTypeExportVariable(C, EV);
734      break;
735    }
736    default: {
737      assert(false && "Unknown class of type");
738    }
739  }
740
741  return;
742}
743
744void RSReflection::genExportFunction(Context &C, const RSExportFunc *EF) {
745  C.indent() << "private final static int "RS_EXPORT_FUNC_INDEX_PREFIX
746             << EF->getName() << " = " << C.getNextExportFuncSlot() << ";"
747             << std::endl;
748
749  // invoke_*()
750  Context::ArgTy Args;
751
752  if (EF->hasParam()) {
753    for (RSExportFunc::const_param_iterator I = EF->params_begin(),
754             E = EF->params_end();
755         I != E;
756         I++) {
757      Args.push_back(std::make_pair(GetTypeName((*I)->getType()),
758                                    (*I)->getName()));
759    }
760  }
761
762  C.startFunction(Context::AM_Public,
763                  false,
764                  "void",
765                  "invoke_" + EF->getName(),
766                  Args);
767
768  if (!EF->hasParam()) {
769    C.indent() << "invoke("RS_EXPORT_FUNC_INDEX_PREFIX << EF->getName() << ");"
770               << std::endl;
771  } else {
772    const RSExportRecordType *ERT = EF->getParamPacketType();
773    std::string FieldPackerName = EF->getName() + "_fp";
774
775    if (genCreateFieldPacker(C, ERT, FieldPackerName.c_str()))
776      genPackVarOfType(C, ERT, NULL, FieldPackerName.c_str());
777
778    C.indent() << "invoke("RS_EXPORT_FUNC_INDEX_PREFIX << EF->getName() << ", "
779               << FieldPackerName << ");" << std::endl;
780  }
781
782  C.endFunction();
783  return;
784}
785
786void RSReflection::genPrimitiveTypeExportVariable(
787    Context &C,
788    const RSExportVar *EV) {
789  assert((EV->getType()->getClass() == RSExportType::ExportClassPrimitive) &&
790         "Variable should be type of primitive here");
791
792  const RSExportPrimitiveType *EPT =
793      static_cast<const RSExportPrimitiveType*>(EV->getType());
794  const char *TypeName = GetPrimitiveTypeName(EPT);
795
796  C.indent() << "private " << TypeName << " "RS_EXPORT_VAR_PREFIX
797             << EV->getName() << ";" << std::endl;
798
799  // set_*()
800  if (!EV->isConst()) {
801    C.startFunction(Context::AM_Public,
802                    false,
803                    "void",
804                    "set_" + EV->getName(),
805                    1,
806                    TypeName, "v");
807    C.indent() << RS_EXPORT_VAR_PREFIX << EV->getName() << " = v;" << std::endl;
808
809    C.indent() << "setVar("RS_EXPORT_VAR_INDEX_PREFIX << EV->getName()
810               << ", v);" << std::endl;
811
812    C.endFunction();
813  }
814
815  genGetExportVariable(C, TypeName, EV->getName());
816
817  return;
818}
819
820void RSReflection::genPointerTypeExportVariable(Context &C,
821                                                const RSExportVar *EV) {
822  const RSExportType *ET = EV->getType();
823  const RSExportType *PointeeType;
824  std::string TypeName;
825
826  assert((ET->getClass() == RSExportType::ExportClassPointer) &&
827         "Variable should be type of pointer here");
828
829  PointeeType = static_cast<const RSExportPointerType*>(ET)->getPointeeType();
830  TypeName = GetTypeName(ET);
831
832  C.indent() << "private " << TypeName << " "RS_EXPORT_VAR_PREFIX
833             << EV->getName() << ";" << std::endl;
834
835  // bind_*()
836  C.startFunction(Context::AM_Public,
837                  false,
838                  "void",
839                  "bind_" + EV->getName(),
840                  1,
841                  TypeName.c_str(), "v");
842
843  C.indent() << RS_EXPORT_VAR_PREFIX << EV->getName() << " = v;" << std::endl;
844  C.indent() << "if (v == null) bindAllocation(null, "RS_EXPORT_VAR_INDEX_PREFIX
845             << EV->getName() << ");" << std::endl;
846
847  if (PointeeType->getClass() == RSExportType::ExportClassRecord)
848    C.indent() << "else bindAllocation(v.getAllocation(), "
849        RS_EXPORT_VAR_INDEX_PREFIX << EV->getName() << ");"
850               << std::endl;
851  else
852    C.indent() << "else bindAllocation(v, "RS_EXPORT_VAR_INDEX_PREFIX
853               << EV->getName() << ");" << std::endl;
854
855  C.endFunction();
856
857  genGetExportVariable(C, TypeName, EV->getName());
858
859  return;
860}
861
862void RSReflection::genVectorTypeExportVariable(Context &C,
863                                               const RSExportVar *EV) {
864  assert((EV->getType()->getClass() == RSExportType::ExportClassVector) &&
865         "Variable should be type of vector here");
866
867  const RSExportVectorType *EVT =
868      static_cast<const RSExportVectorType*>(EV->getType());
869  const char *TypeName = GetVectorTypeName(EVT);
870  const char *FieldPackerName = "fp";
871
872  C.indent() << "private " << TypeName << " "RS_EXPORT_VAR_PREFIX
873             << EV->getName() << ";" << std::endl;
874
875  // set_*()
876  if (!EV->isConst()) {
877    C.startFunction(Context::AM_Public,
878                    false,
879                    "void",
880                    "set_" + EV->getName(),
881                    1,
882                    TypeName, "v");
883    C.indent() << RS_EXPORT_VAR_PREFIX << EV->getName() << " = v;" << std::endl;
884
885    if (genCreateFieldPacker(C, EVT, FieldPackerName))
886      genPackVarOfType(C, EVT, "v", FieldPackerName);
887    C.indent() << "setVar("RS_EXPORT_VAR_INDEX_PREFIX << EV->getName() << ", "
888               << FieldPackerName << ");" << std::endl;
889
890    C.endFunction();
891  }
892
893  genGetExportVariable(C, TypeName, EV->getName());
894  return;
895}
896
897void RSReflection::genMatrixTypeExportVariable(Context &C,
898                                               const RSExportVar *EV) {
899  assert((EV->getType()->getClass() == RSExportType::ExportClassMatrix) &&
900         "Variable should be type of matrix here");
901
902  const RSExportMatrixType *EMT =
903      static_cast<const RSExportMatrixType*>(EV->getType());
904  const char *TypeName = GetMatrixTypeName(EMT);
905  const char *FieldPackerName = "fp";
906
907  C.indent() << "private " << TypeName << " "RS_EXPORT_VAR_PREFIX
908             << EV->getName() << ";" << std::endl;
909
910  // set_*()
911  if (!EV->isConst()) {
912    C.startFunction(Context::AM_Public,
913                    false,
914                    "void",
915                    "set_" + EV->getName(),
916                    1,
917                    TypeName, "v");
918    C.indent() << RS_EXPORT_VAR_PREFIX << EV->getName() << " = v;" << std::endl;
919
920    if (genCreateFieldPacker(C, EMT, FieldPackerName))
921      genPackVarOfType(C, EMT, "v", FieldPackerName);
922    C.indent() << "setVar("RS_EXPORT_VAR_INDEX_PREFIX << EV->getName() << ", "
923               << FieldPackerName << ");" << std::endl;
924
925    C.endFunction();
926  }
927
928  genGetExportVariable(C, TypeName, EV->getName());
929  return;
930}
931
932void RSReflection::genConstantArrayTypeExportVariable(
933    Context &C,
934    const RSExportVar *EV) {
935  assert((EV->getType()->getClass() == RSExportType::ExportClassConstantArray)&&
936         "Variable should be type of constant array here");
937
938  const RSExportConstantArrayType *ECAT =
939      static_cast<const RSExportConstantArrayType*>(EV->getType());
940  std::string TypeName = GetTypeName(ECAT);
941  const char *FieldPackerName = "fp";
942
943  C.indent() << "private " << TypeName << " "RS_EXPORT_VAR_PREFIX
944             << EV->getName() << ";" << std::endl;
945
946  // set_*()
947  if (!EV->isConst()) {
948    C.startFunction(Context::AM_Public,
949                    false,
950                    "void",
951                    "set_" + EV->getName(),
952                    1,
953                    TypeName.c_str(), "v");
954    C.indent() << RS_EXPORT_VAR_PREFIX << EV->getName() << " = v;" << std::endl;
955
956    if (genCreateFieldPacker(C, ECAT, FieldPackerName))
957      genPackVarOfType(C, ECAT, "v", FieldPackerName);
958    C.indent() << "setVar("RS_EXPORT_VAR_INDEX_PREFIX << EV->getName() << ", "
959               << FieldPackerName << ");" << std::endl;
960
961    C.endFunction();
962  }
963
964  genGetExportVariable(C, TypeName, EV->getName());
965  return;
966}
967
968void RSReflection::genRecordTypeExportVariable(Context &C,
969                                               const RSExportVar *EV) {
970  assert((EV->getType()->getClass() == RSExportType::ExportClassRecord) &&
971         "Variable should be type of struct here");
972
973  const RSExportRecordType *ERT =
974      static_cast<const RSExportRecordType*>(EV->getType());
975  std::string TypeName =
976      RS_TYPE_CLASS_NAME_PREFIX + ERT->getName() + "."RS_TYPE_ITEM_CLASS_NAME;
977  const char *FieldPackerName = "fp";
978
979  C.indent() << "private " << TypeName << " "RS_EXPORT_VAR_PREFIX
980             << EV->getName() << ";" << std::endl;
981
982  // set_*()
983  if (!EV->isConst()) {
984    C.startFunction(Context::AM_Public,
985                    false,
986                    "void",
987                    "set_" + EV->getName(),
988                    1,
989                    TypeName.c_str(), "v");
990    C.indent() << RS_EXPORT_VAR_PREFIX << EV->getName() << " = v;" << std::endl;
991
992    if (genCreateFieldPacker(C, ERT, FieldPackerName))
993      genPackVarOfType(C, ERT, "v", FieldPackerName);
994    C.indent() << "setVar("RS_EXPORT_VAR_INDEX_PREFIX << EV->getName()
995               << ", " << FieldPackerName << ");" << std::endl;
996
997    C.endFunction();
998  }
999
1000  genGetExportVariable(C, TypeName.c_str(), EV->getName());
1001  return;
1002}
1003
1004void RSReflection::genGetExportVariable(Context &C,
1005                                        const std::string &TypeName,
1006                                        const std::string &VarName) {
1007  C.startFunction(Context::AM_Public,
1008                  false,
1009                  TypeName.c_str(),
1010                  "get_" + VarName,
1011                  0);
1012
1013  C.indent() << "return "RS_EXPORT_VAR_PREFIX << VarName << ";" << std::endl;
1014
1015  C.endFunction();
1016  return;
1017}
1018
1019/******************* Methods to generate script class /end *******************/
1020
1021bool RSReflection::genCreateFieldPacker(Context &C,
1022                                        const RSExportType *ET,
1023                                        const char *FieldPackerName) {
1024  size_t AllocSize = RSExportType::GetTypeAllocSize(ET);
1025  if (AllocSize > 0)
1026    C.indent() << "FieldPacker " << FieldPackerName << " = new FieldPacker("
1027               << AllocSize << ");" << std::endl;
1028  else
1029    return false;
1030  return true;
1031}
1032
1033void RSReflection::genPackVarOfType(Context &C,
1034                                    const RSExportType *ET,
1035                                    const char *VarName,
1036                                    const char *FieldPackerName) {
1037  switch (ET->getClass()) {
1038    case RSExportType::ExportClassPrimitive:
1039    case RSExportType::ExportClassVector: {
1040      C.indent() << FieldPackerName << "."
1041                 << GetPackerAPIName(
1042                     static_cast<const RSExportPrimitiveType*>(ET))
1043                 << "(" << VarName << ");" << std::endl;
1044      break;
1045    }
1046    case RSExportType::ExportClassPointer: {
1047      // Must reflect as type Allocation in Java
1048      const RSExportType *PointeeType =
1049          static_cast<const RSExportPointerType*>(ET)->getPointeeType();
1050
1051      if (PointeeType->getClass() != RSExportType::ExportClassRecord)
1052        C.indent() << FieldPackerName << ".addI32(" << VarName
1053                   << ".getPtr());" << std::endl;
1054      else
1055        C.indent() << FieldPackerName << ".addI32(" << VarName
1056                   << ".getAllocation().getPtr());" << std::endl;
1057      break;
1058    }
1059    case RSExportType::ExportClassMatrix: {
1060      C.indent() << FieldPackerName << ".addObj(" << VarName << ");"
1061                 << std::endl;
1062      break;
1063    }
1064    case RSExportType::ExportClassConstantArray: {
1065      const RSExportConstantArrayType *ECAT =
1066          static_cast<const RSExportConstantArrayType *>(ET);
1067
1068      // TODO(zonr): more elegant way. Currently, we obtain the unique index
1069      //             variable (this method involves recursive call which means
1070      //             we may have more than one level loop, therefore we can't
1071      //             always use the same index variable name here) name given
1072      //             in the for-loop from counting the '.' in @VarName.
1073      unsigned Level = 0;
1074      size_t LastDotPos = 0;
1075      std::string ElementVarName(VarName);
1076
1077      while (LastDotPos != std::string::npos) {
1078        LastDotPos = ElementVarName.find_first_of('.', LastDotPos + 1);
1079        Level++;
1080      }
1081      std::string IndexVarName("ct");
1082      IndexVarName.append(llvm::utostr_32(Level));
1083
1084      C.indent() << "for (int " << IndexVarName << " = 0; " <<
1085                          IndexVarName << " < " << ECAT->getSize() << "; " <<
1086                          IndexVarName << "++)";
1087      C.startBlock();
1088
1089      ElementVarName.append("[" + IndexVarName + "]");
1090      genPackVarOfType(C, ECAT->getElementType(), ElementVarName.c_str(),
1091                       FieldPackerName);
1092
1093      C.endBlock();
1094      break;
1095    }
1096    case RSExportType::ExportClassRecord: {
1097      const RSExportRecordType *ERT =
1098          static_cast<const RSExportRecordType*>(ET);
1099      // Relative pos from now on in field packer
1100      unsigned Pos = 0;
1101
1102      for (RSExportRecordType::const_field_iterator I = ERT->fields_begin(),
1103               E = ERT->fields_end();
1104           I != E;
1105           I++) {
1106        const RSExportRecordType::Field *F = *I;
1107        std::string FieldName;
1108        size_t FieldOffset = F->getOffsetInParent();
1109        size_t FieldStoreSize = RSExportType::GetTypeStoreSize(F->getType());
1110        size_t FieldAllocSize = RSExportType::GetTypeAllocSize(F->getType());
1111
1112        if (VarName != NULL)
1113          FieldName = VarName + ("." + F->getName());
1114        else
1115          FieldName = F->getName();
1116
1117        if (FieldOffset > Pos)
1118          C.indent() << FieldPackerName << ".skip("
1119                     << (FieldOffset - Pos) << ");" << std::endl;
1120
1121        genPackVarOfType(C, F->getType(), FieldName.c_str(), FieldPackerName);
1122
1123        // There is padding in the field type
1124        if (FieldAllocSize > FieldStoreSize)
1125            C.indent() << FieldPackerName << ".skip("
1126                       << (FieldAllocSize - FieldStoreSize)
1127                       << ");" << std::endl;
1128
1129          Pos = FieldOffset + FieldAllocSize;
1130      }
1131
1132      // There maybe some padding after the struct
1133      size_t Padding = RSExportType::GetTypeAllocSize(ERT) - Pos;
1134      if (Padding > 0)
1135        C.indent() << FieldPackerName << ".skip(" << Padding << ");"
1136                   << std::endl;
1137      break;
1138    }
1139    default: {
1140      assert(false && "Unknown class of type");
1141    }
1142  }
1143
1144  return;
1145}
1146
1147void RSReflection::genAllocateVarOfType(Context &C,
1148                                        const RSExportType *T,
1149                                        const std::string &VarName) {
1150  switch (T->getClass()) {
1151    case RSExportType::ExportClassPrimitive: {
1152      // Primitive type like int in Java has its own storage once it's declared.
1153      //
1154      // FIXME: Should we allocate storage for RS object?
1155      // if (static_cast<const RSExportPrimitiveType *>(T)->isRSObjectType())
1156      //  C.indent() << VarName << " = new " << GetTypeName(T) << "();"
1157      //             << std::endl;
1158      break;
1159    }
1160    case RSExportType::ExportClassPointer: {
1161      // Pointer type is an instance of Allocation or a TypeClass whose value is
1162      // expected to be assigned by programmer later in Java program. Therefore
1163      // we don't reflect things like [VarName] = new Allocation();
1164      C.indent() << VarName << " = null;" << std::endl;
1165      break;
1166    }
1167    case RSExportType::ExportClassConstantArray: {
1168      const RSExportConstantArrayType *ECAT =
1169          static_cast<const RSExportConstantArrayType *>(T);
1170      const RSExportType *ElementType = ECAT->getElementType();
1171
1172      C.indent() << VarName << " = new " << GetTypeName(ElementType)
1173                 << "[" << ECAT->getSize() << "];" << std::endl;
1174
1175      // Primitive type element doesn't need allocation code.
1176      if (ElementType->getClass() != RSExportType::ExportClassPrimitive) {
1177        C.indent() << "for (int $ct = 0; $ct < " << ECAT->getSize() << "; "
1178                            "$ct++)";
1179        C.startBlock();
1180
1181        std::string ElementVarName(VarName);
1182        ElementVarName.append("[$ct]");
1183        genAllocateVarOfType(C, ElementType, ElementVarName);
1184
1185        C.endBlock();
1186      }
1187      break;
1188    }
1189    case RSExportType::ExportClassVector:
1190    case RSExportType::ExportClassMatrix:
1191    case RSExportType::ExportClassRecord: {
1192      C.indent() << VarName << " = new " << GetTypeName(T) << "();"
1193                 << std::endl;
1194      break;
1195    }
1196  }
1197  return;
1198}
1199
1200void RSReflection::genNewItemBufferIfNull(Context &C,
1201                                          const char *Index) {
1202  C.indent() << "if (" RS_TYPE_ITEM_BUFFER_NAME " == null) "
1203                  RS_TYPE_ITEM_BUFFER_NAME " = "
1204                    "new " RS_TYPE_ITEM_CLASS_NAME
1205                      "[getType().getX() /* count */];"
1206             << std::endl;
1207  if (Index != NULL)
1208    C.indent() << "if ("RS_TYPE_ITEM_BUFFER_NAME"[" << Index << "] == null) "
1209                    RS_TYPE_ITEM_BUFFER_NAME"[" << Index << "] = "
1210                      "new "RS_TYPE_ITEM_CLASS_NAME"();" << std::endl;
1211  return;
1212}
1213
1214void RSReflection::genNewItemBufferPackerIfNull(Context &C) {
1215  C.indent() << "if (" RS_TYPE_ITEM_BUFFER_PACKER_NAME " == null) "
1216                  RS_TYPE_ITEM_BUFFER_PACKER_NAME " = "
1217                    "new FieldPacker(" RS_TYPE_ITEM_CLASS_NAME
1218                      ".sizeof * getType().getX()/* count */"
1219                        ");" << std::endl;
1220  return;
1221}
1222
1223/********************** Methods to generate type class  **********************/
1224bool RSReflection::genTypeClass(Context &C,
1225                                const RSExportRecordType *ERT,
1226                                std::string &ErrorMsg) {
1227  std::string ClassName = RS_TYPE_CLASS_NAME_PREFIX + ERT->getName();
1228
1229  if (!C.startClass(Context::AM_Public,
1230                    false,
1231                    ClassName,
1232                    RS_TYPE_CLASS_SUPER_CLASS_NAME,
1233                    ErrorMsg))
1234    return false;
1235
1236  genTypeItemClass(C, ERT);
1237
1238  // Declare item buffer and item buffer packer
1239  C.indent() << "private "RS_TYPE_ITEM_CLASS_NAME" "RS_TYPE_ITEM_BUFFER_NAME"[]"
1240      ";" << std::endl;
1241  C.indent() << "private FieldPacker "RS_TYPE_ITEM_BUFFER_PACKER_NAME";"
1242             << std::endl;
1243
1244  genTypeClassConstructor(C, ERT);
1245  genTypeClassCopyToArray(C, ERT);
1246  genTypeClassItemSetter(C, ERT);
1247  genTypeClassItemGetter(C, ERT);
1248  genTypeClassComponentSetter(C, ERT);
1249  genTypeClassComponentGetter(C, ERT);
1250  genTypeClassCopyAll(C, ERT);
1251  genTypeClassResize(C);
1252
1253  C.endClass();
1254
1255  C.resetFieldIndex();
1256  C.clearFieldIndexMap();
1257
1258  return true;
1259}
1260
1261void RSReflection::genTypeItemClass(Context &C,
1262                                    const RSExportRecordType *ERT) {
1263  C.indent() << "static public class "RS_TYPE_ITEM_CLASS_NAME;
1264  C.startBlock();
1265
1266  C.indent() << "public static final int sizeof = "
1267             << RSExportType::GetTypeAllocSize(ERT) << ";" << std::endl;
1268
1269  // Member elements
1270  C.out() << std::endl;
1271  for (RSExportRecordType::const_field_iterator FI = ERT->fields_begin(),
1272           FE = ERT->fields_end();
1273       FI != FE;
1274       FI++) {
1275    C.indent() << GetTypeName((*FI)->getType()) << " " << (*FI)->getName()
1276               << ";" << std::endl;
1277  }
1278
1279  // Constructor
1280  C.out() << std::endl;
1281  C.indent() << RS_TYPE_ITEM_CLASS_NAME"()";
1282  C.startBlock();
1283
1284  for (RSExportRecordType::const_field_iterator FI = ERT->fields_begin(),
1285           FE = ERT->fields_end();
1286       FI != FE;
1287       FI++) {
1288    const RSExportRecordType::Field *F = *FI;
1289    genAllocateVarOfType(C, F->getType(), F->getName());
1290  }
1291
1292  // end Constructor
1293  C.endBlock();
1294
1295  // end Item class
1296  C.endBlock();
1297
1298  return;
1299}
1300
1301void RSReflection::genTypeClassConstructor(Context &C,
1302                                           const RSExportRecordType *ERT) {
1303  const char *RenderScriptVar = "rs";
1304
1305  C.startFunction(Context::AM_Public,
1306                  true,
1307                  "Element",
1308                  "createElement",
1309                  1,
1310                  "RenderScript", RenderScriptVar);
1311  genBuildElement(C, "eb", ERT, RenderScriptVar, /* IsInline = */false);
1312  C.endFunction();
1313
1314  C.startFunction(Context::AM_Public,
1315                  false,
1316                  NULL,
1317                  C.getClassName(),
1318                  2,
1319                  "RenderScript", RenderScriptVar,
1320                  "int", "count");
1321
1322  C.indent() << RS_TYPE_ITEM_BUFFER_NAME" = null;" << std::endl;
1323  C.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME" = null;" << std::endl;
1324  C.indent() << "mElement = createElement(" << RenderScriptVar << ");"
1325             << std::endl;
1326  // Call init() in super class
1327  C.indent() << "init(" << RenderScriptVar << ", count);" << std::endl;
1328  C.endFunction();
1329
1330  return;
1331}
1332
1333void RSReflection::genTypeClassCopyToArray(Context &C,
1334                                           const RSExportRecordType *ERT) {
1335  C.startFunction(Context::AM_Private,
1336                  false,
1337                  "void",
1338                  "copyToArray",
1339                  2,
1340                  RS_TYPE_ITEM_CLASS_NAME, "i",
1341                  "int", "index");
1342
1343  genNewItemBufferPackerIfNull(C);
1344  C.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME
1345                ".reset(index * "RS_TYPE_ITEM_CLASS_NAME".sizeof);"
1346             << std::endl;
1347
1348  genPackVarOfType(C, ERT, "i", RS_TYPE_ITEM_BUFFER_PACKER_NAME);
1349
1350  C.endFunction();
1351  return;
1352}
1353
1354void RSReflection::genTypeClassItemSetter(Context &C,
1355                                          const RSExportRecordType *ERT) {
1356  C.startFunction(Context::AM_Public,
1357                  false,
1358                  "void",
1359                  "set",
1360                  3,
1361                  RS_TYPE_ITEM_CLASS_NAME, "i",
1362                  "int", "index",
1363                  "boolean", "copyNow");
1364  genNewItemBufferIfNull(C, NULL);
1365  C.indent() << RS_TYPE_ITEM_BUFFER_NAME"[index] = i;" << std::endl;
1366
1367  C.indent() << "if (copyNow) ";
1368  C.startBlock();
1369
1370  C.indent() << "copyToArray(i, index);" << std::endl;
1371  C.indent() << "mAllocation.subData1D(index, 1, "
1372                  RS_TYPE_ITEM_BUFFER_PACKER_NAME".getData());" << std::endl;
1373
1374  // End of if (copyNow)
1375  C.endBlock();
1376
1377  C.endFunction();
1378  return;
1379}
1380
1381void RSReflection::genTypeClassItemGetter(Context &C,
1382                                          const RSExportRecordType *ERT) {
1383  C.startFunction(Context::AM_Public,
1384                  false,
1385                  RS_TYPE_ITEM_CLASS_NAME,
1386                  "get",
1387                  1,
1388                  "int", "index");
1389  C.indent() << "if ("RS_TYPE_ITEM_BUFFER_NAME" == null) return null;"
1390             << std::endl;
1391  C.indent() << "return "RS_TYPE_ITEM_BUFFER_NAME"[index];" << std::endl;
1392  C.endFunction();
1393  return;
1394}
1395
1396void RSReflection::genTypeClassComponentSetter(Context &C,
1397                                               const RSExportRecordType *ERT) {
1398  for (RSExportRecordType::const_field_iterator FI = ERT->fields_begin(),
1399           FE = ERT->fields_end();
1400       FI != FE;
1401       FI++) {
1402    const RSExportRecordType::Field *F = *FI;
1403    size_t FieldOffset = F->getOffsetInParent();
1404    size_t FieldStoreSize = RSExportType::GetTypeStoreSize(F->getType());
1405    unsigned FieldIndex = C.getFieldIndex(F);
1406
1407    C.startFunction(Context::AM_Public,
1408                    false,
1409                    "void",
1410                    "set_" + F->getName(), 3,
1411                    "int", "index",
1412                    GetTypeName(F->getType()).c_str(), "v",
1413                    "boolean", "copyNow");
1414    genNewItemBufferPackerIfNull(C);
1415    genNewItemBufferIfNull(C, "index");
1416    C.indent() << RS_TYPE_ITEM_BUFFER_NAME"[index]." << F->getName()
1417               << " = v;" << std::endl;
1418
1419    C.indent() << "if (copyNow) ";
1420    C.startBlock();
1421
1422    if (FieldOffset > 0)
1423      C.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME
1424                    ".reset(index * "RS_TYPE_ITEM_CLASS_NAME".sizeof + "
1425                 << FieldOffset << ");" << std::endl;
1426    else
1427      C.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME
1428                    ".reset(index * "RS_TYPE_ITEM_CLASS_NAME".sizeof);"
1429                 << std::endl;
1430    genPackVarOfType(C, F->getType(), "v", RS_TYPE_ITEM_BUFFER_PACKER_NAME);
1431
1432    C.indent() << "FieldPacker fp = new FieldPacker(" << FieldStoreSize << ");"
1433               << std::endl;
1434    genPackVarOfType(C, F->getType(), "v", "fp");
1435    C.indent() << "mAllocation.subElementData(index, " << FieldIndex << ", fp);"
1436               << std::endl;
1437
1438    // End of if (copyNow)
1439    C.endBlock();
1440
1441    C.endFunction();
1442  }
1443  return;
1444}
1445
1446void RSReflection::genTypeClassComponentGetter(Context &C,
1447                                               const RSExportRecordType *ERT) {
1448  for (RSExportRecordType::const_field_iterator FI = ERT->fields_begin(),
1449           FE = ERT->fields_end();
1450       FI != FE;
1451       FI++) {
1452    const RSExportRecordType::Field *F = *FI;
1453    C.startFunction(Context::AM_Public,
1454                    false,
1455                    GetTypeName(F->getType()).c_str(),
1456                    "get_" + F->getName(),
1457                    1,
1458                    "int", "index");
1459    C.indent() << "if ("RS_TYPE_ITEM_BUFFER_NAME" == null) return "
1460               << GetTypeNullValue(F->getType()) << ";" << std::endl;
1461    C.indent() << "return "RS_TYPE_ITEM_BUFFER_NAME"[index]." << F->getName()
1462               << ";" << std::endl;
1463    C.endFunction();
1464  }
1465  return;
1466}
1467
1468void RSReflection::genTypeClassCopyAll(Context &C,
1469                                       const RSExportRecordType *ERT) {
1470  C.startFunction(Context::AM_Public, false, "void", "copyAll", 0);
1471
1472  C.indent() << "for (int ct = 0; ct < "RS_TYPE_ITEM_BUFFER_NAME".length; ct++)"
1473                  " copyToArray("RS_TYPE_ITEM_BUFFER_NAME"[ct], ct);"
1474             << std::endl;
1475  C.indent() << "mAllocation.copyFrom("RS_TYPE_ITEM_BUFFER_PACKER_NAME".getData());"
1476             << std::endl;
1477
1478  C.endFunction();
1479  return;
1480}
1481
1482void RSReflection::genTypeClassResize(Context &C) {
1483  C.startFunction(Context::AM_Public,
1484                  false,
1485                  "void",
1486                  "resize",
1487                  1,
1488                  "int", "newSize");
1489
1490  C.indent() << "if (mItemArray != null) ";
1491  C.startBlock();
1492  C.indent() << "int oldSize = mItemArray.length;" << std::endl;
1493  C.indent() << "int copySize = Math.min(oldSize, newSize);" << std::endl;
1494  C.indent() << "if (newSize == oldSize) return;" << std::endl;
1495  C.indent() << "Item ni[] = new Item[newSize];" << std::endl;
1496  C.indent() << "System.arraycopy(mItemArray, 0, ni, 0, copySize);"
1497             << std::endl;
1498  C.indent() << "mItemArray = ni;" << std::endl;
1499  C.endBlock();
1500  C.indent() << "mAllocation.resize(newSize);" << std::endl;
1501
1502  C.endFunction();
1503  return;
1504}
1505
1506/******************** Methods to generate type class /end ********************/
1507
1508/********** Methods to create Element in Java of given record type ***********/
1509void RSReflection::genBuildElement(Context &C,
1510                                   const char *ElementBuilderName,
1511                                   const RSExportRecordType *ERT,
1512                                   const char *RenderScriptVar,
1513                                   bool IsInline) {
1514  C.indent() << "Element.Builder " << ElementBuilderName << " = "
1515      "new Element.Builder(" << RenderScriptVar << ");" << std::endl;
1516
1517  // eb.add(...)
1518  genAddElementToElementBuilder(C,
1519                                ERT,
1520                                "",
1521                                ElementBuilderName,
1522                                RenderScriptVar,
1523                                /* ArraySize = */0);
1524
1525  if (!IsInline)
1526    C.indent() << "return " << ElementBuilderName << ".create();" << std::endl;
1527  return;
1528}
1529
1530#define EB_ADD(x) do {                                              \
1531  C.indent() << ElementBuilderName                                  \
1532             << ".add(" << x << ", \"" << VarName << "\"";  \
1533  if (ArraySize > 0)                                                \
1534    C.out() << ", " << ArraySize;                                   \
1535  C.out() << ");" << std::endl;                                     \
1536  C.incFieldIndex();                                                \
1537} while (false)
1538
1539void RSReflection::genAddElementToElementBuilder(Context &C,
1540                                                 const RSExportType *ET,
1541                                                 const std::string &VarName,
1542                                                 const char *ElementBuilderName,
1543                                                 const char *RenderScriptVar,
1544                                                 unsigned ArraySize) {
1545  const char *ElementConstruct = GetBuiltinElementConstruct(ET);
1546
1547  if (ElementConstruct != NULL) {
1548    EB_ADD(ElementConstruct << "(" << RenderScriptVar << ")");
1549  } else {
1550    if ((ET->getClass() == RSExportType::ExportClassPrimitive) ||
1551        (ET->getClass() == RSExportType::ExportClassVector)) {
1552      const RSExportPrimitiveType *EPT =
1553          static_cast<const RSExportPrimitiveType*>(ET);
1554      const char *DataKindName = GetElementDataKindName(EPT->getKind());
1555      const char *DataTypeName = GetElementDataTypeName(EPT->getType());
1556      int Size = (ET->getClass() == RSExportType::ExportClassVector) ?
1557          static_cast<const RSExportVectorType*>(ET)->getNumElement() :
1558          1;
1559
1560      switch (EPT->getKind()) {
1561        case RSExportPrimitiveType::DataKindPixelL:
1562        case RSExportPrimitiveType::DataKindPixelA:
1563        case RSExportPrimitiveType::DataKindPixelLA:
1564        case RSExportPrimitiveType::DataKindPixelRGB:
1565        case RSExportPrimitiveType::DataKindPixelRGBA: {
1566          // Element.createPixel()
1567          EB_ADD("Element.createPixel(" << RenderScriptVar << ", "
1568                                        << DataTypeName << ", "
1569                                        << DataKindName << ")");
1570          break;
1571        }
1572        case RSExportPrimitiveType::DataKindUser:
1573        default: {
1574          if (EPT->getClass() == RSExportType::ExportClassPrimitive) {
1575            // Element.createUser()
1576            EB_ADD("Element.createUser(" << RenderScriptVar << ", "
1577                                         << DataTypeName << ")");
1578          } else {
1579            assert((ET->getClass() == RSExportType::ExportClassVector) &&
1580                   "Unexpected type.");
1581            EB_ADD("Element.createVector(" << RenderScriptVar << ", "
1582                                           << DataTypeName << ", "
1583                                           << Size << ")");
1584          }
1585          break;
1586        }
1587      }
1588#ifndef NDEBUG
1589    } else if (ET->getClass() == RSExportType::ExportClassPointer) {
1590      // Pointer type variable should be resolved in
1591      // GetBuiltinElementConstruct()
1592      assert(false && "??");
1593    } else if (ET->getClass() == RSExportType::ExportClassMatrix) {
1594      // Matrix type variable should be resolved
1595      // in GetBuiltinElementConstruct()
1596      assert(false && "??");
1597#endif
1598    } else if (ET->getClass() == RSExportType::ExportClassConstantArray) {
1599      const RSExportConstantArrayType *ECAT =
1600          static_cast<const RSExportConstantArrayType *>(ET);
1601
1602      const RSExportType *ElementType = ECAT->getElementType();
1603      if (ElementType->getClass() != RSExportType::ExportClassRecord) {
1604        genAddElementToElementBuilder(C,
1605                                      ECAT->getElementType(),
1606                                      VarName,
1607                                      ElementBuilderName,
1608                                      RenderScriptVar,
1609                                      ECAT->getSize());
1610      } else {
1611        std::string NewElementBuilderName(ElementBuilderName);
1612        NewElementBuilderName.append(1, '_');
1613
1614        genBuildElement(C,
1615                        NewElementBuilderName.c_str(),
1616                        static_cast<const RSExportRecordType*>(ElementType),
1617                        RenderScriptVar,
1618                        /* IsInline = */true);
1619        ArraySize = ECAT->getSize();
1620        EB_ADD(NewElementBuilderName << ".create()");
1621      }
1622    } else if (ET->getClass() == RSExportType::ExportClassRecord) {
1623      // Simalar to case of RSExportType::ExportClassRecord in genPackVarOfType.
1624      //
1625      // TODO(zonr): Generalize these two function such that there's no
1626      //             duplicated codes.
1627      const RSExportRecordType *ERT =
1628          static_cast<const RSExportRecordType*>(ET);
1629      int Pos = 0;    // relative pos from now on
1630
1631      for (RSExportRecordType::const_field_iterator I = ERT->fields_begin(),
1632               E = ERT->fields_end();
1633           I != E;
1634           I++) {
1635        const RSExportRecordType::Field *F = *I;
1636        std::string FieldName;
1637        int FieldOffset = F->getOffsetInParent();
1638        int FieldStoreSize = RSExportType::GetTypeStoreSize(F->getType());
1639        int FieldAllocSize = RSExportType::GetTypeAllocSize(F->getType());
1640
1641        if (!VarName.empty())
1642          FieldName = VarName + "." + F->getName();
1643        else
1644          FieldName = F->getName();
1645
1646        // Alignment
1647        genAddPaddingToElementBuiler(C,
1648                                     (FieldOffset - Pos),
1649                                     ElementBuilderName,
1650                                     RenderScriptVar);
1651
1652        // eb.add(...)
1653        C.addFieldIndexMapping(F);
1654        if (F->getType()->getClass() != RSExportType::ExportClassRecord) {
1655          genAddElementToElementBuilder(C,
1656                                        F->getType(),
1657                                        FieldName,
1658                                        ElementBuilderName,
1659                                        RenderScriptVar,
1660                                        0);
1661        } else {
1662          std::string NewElementBuilderName(ElementBuilderName);
1663          NewElementBuilderName.append(1, '_');
1664
1665          genBuildElement(C,
1666                          NewElementBuilderName.c_str(),
1667                          static_cast<const RSExportRecordType*>(F->getType()),
1668                          RenderScriptVar,
1669                          /* IsInline = */true);
1670
1671          const std::string &VarName = FieldName;  // Hack for EB_ADD macro
1672          EB_ADD(NewElementBuilderName << ".create()");
1673        }
1674
1675        // There is padding within the field type
1676        genAddPaddingToElementBuiler(C,
1677                                     (FieldAllocSize - FieldStoreSize),
1678                                     ElementBuilderName,
1679                                     RenderScriptVar);
1680
1681        Pos = FieldOffset + FieldAllocSize;
1682      }
1683
1684      // There maybe some padding after the struct
1685      size_t RecordStoreSize = RSExportType::GetTypeStoreSize(ERT);
1686
1687      genAddPaddingToElementBuiler(C,
1688                                   RecordStoreSize - Pos,
1689                                   ElementBuilderName,
1690                                   RenderScriptVar);
1691    } else {
1692      assert(false && "Unknown class of type");
1693    }
1694  }
1695}
1696
1697void RSReflection::genAddPaddingToElementBuiler(Context &C,
1698                                                int PaddingSize,
1699                                                const char *ElementBuilderName,
1700                                                const char *RenderScriptVar) {
1701  unsigned ArraySize = 0;   // Hack the EB_ADD macro
1702  while (PaddingSize > 0) {
1703    const std::string &VarName = C.createPaddingField();
1704    if (PaddingSize >= 4) {
1705      EB_ADD("Element.U32(" << RenderScriptVar << ")");
1706      PaddingSize -= 4;
1707    } else if (PaddingSize >= 2) {
1708      EB_ADD("Element.U16(" << RenderScriptVar << ")");
1709      PaddingSize -= 2;
1710    } else if (PaddingSize >= 1) {
1711      EB_ADD("Element.U8(" << RenderScriptVar << ")");
1712      PaddingSize -= 1;
1713    }
1714  }
1715  return;
1716}
1717
1718#undef EB_ADD
1719/******** Methods to create Element in Java of given record type /end ********/
1720
1721bool RSReflection::reflect(const std::string &OutputPathBase,
1722                           const std::string &OutputPackageName,
1723                           const std::string &InputFileName,
1724                           const std::string &OutputBCFileName) {
1725  Context *C = NULL;
1726  std::string ResourceId = "";
1727
1728  if (!GetClassNameFromFileName(OutputBCFileName, ResourceId))
1729    return false;
1730
1731  if (ResourceId.empty())
1732    ResourceId = "<Resource ID>";
1733
1734  if (OutputPackageName.empty() || OutputPackageName == "-")
1735    C = new Context(OutputPathBase, InputFileName, "<Package Name>",
1736                    ResourceId, true);
1737  else
1738    C = new Context(OutputPathBase, InputFileName, OutputPackageName,
1739                    ResourceId, false);
1740
1741  if (C != NULL) {
1742    std::string ErrorMsg, ScriptClassName;
1743    // class ScriptC_<ScriptName>
1744    if (!GetClassNameFromFileName(InputFileName, ScriptClassName))
1745      return false;
1746
1747    if (ScriptClassName.empty())
1748      ScriptClassName = "<Input Script Name>";
1749
1750    ScriptClassName.insert(0, RS_SCRIPT_CLASS_NAME_PREFIX);
1751
1752    if (mRSContext->getLicenseNote() != NULL) {
1753      C->setLicenseNote(*(mRSContext->getLicenseNote()));
1754    }
1755
1756    if (!genScriptClass(*C, ScriptClassName, ErrorMsg)) {
1757      std::cerr << "Failed to generate class " << ScriptClassName << " ("
1758                << ErrorMsg << ")" << std::endl;
1759      return false;
1760    }
1761
1762    // class ScriptField_<TypeName>
1763    for (RSContext::const_export_type_iterator TI =
1764             mRSContext->export_types_begin(),
1765             TE = mRSContext->export_types_end();
1766         TI != TE;
1767         TI++) {
1768      const RSExportType *ET = TI->getValue();
1769
1770      if (ET->getClass() == RSExportType::ExportClassRecord) {
1771        const RSExportRecordType *ERT =
1772            static_cast<const RSExportRecordType*>(ET);
1773
1774        if (!ERT->isArtificial() && !genTypeClass(*C, ERT, ErrorMsg)) {
1775          std::cerr << "Failed to generate type class for struct '"
1776                    << ERT->getName() << "' (" << ErrorMsg << ")" << std::endl;
1777          return false;
1778        }
1779      }
1780    }
1781  }
1782
1783  return true;
1784}
1785
1786/************************** RSReflection::Context **************************/
1787const char *const RSReflection::Context::ApacheLicenseNote =
1788    "/*\n"
1789    " * Copyright (C) 2010 The Android Open Source Project\n"
1790    " *\n"
1791    " * Licensed under the Apache License, Version 2.0 (the \"License\");\n"
1792    " * you may not use this file except in compliance with the License.\n"
1793    " * You may obtain a copy of the License at\n"
1794    " *\n"
1795    " *      http://www.apache.org/licenses/LICENSE-2.0\n"
1796    " *\n"
1797    " * Unless required by applicable law or agreed to in writing, software\n"
1798    " * distributed under the License is distributed on an \"AS IS\" BASIS,\n"
1799    " * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or "
1800    "implied.\n"
1801    " * See the License for the specific language governing permissions and\n"
1802    " * limitations under the License.\n"
1803    " */\n"
1804    "\n";
1805
1806const char *const RSReflection::Context::Import[] = {
1807  // RenderScript java class
1808  "android.renderscript.*",
1809  // Import R
1810  "android.content.res.Resources",
1811  // Import for debugging
1812  "android.util.Log",
1813};
1814
1815bool RSReflection::Context::openClassFile(const std::string &ClassName,
1816                                          std::string &ErrorMsg) {
1817  if (!mUseStdout) {
1818    mOF.clear();
1819    std::string Path =
1820        RSSlangReflectUtils::ComputePackagedPath(mOutputPathBase.c_str(),
1821                                                 mPackageName.c_str());
1822
1823    if (!SlangUtils::CreateDirectoryWithParents(Path, &ErrorMsg))
1824      return false;
1825
1826    std::string ClassFile = Path + "/" + ClassName + ".java";
1827
1828    mOF.open(ClassFile.c_str());
1829    if (!mOF.good()) {
1830      ErrorMsg = "failed to open file '" + ClassFile + "' for write";
1831      return false;
1832    }
1833  }
1834  return true;
1835}
1836
1837const char *RSReflection::Context::AccessModifierStr(AccessModifier AM) {
1838  switch (AM) {
1839    case AM_Public: return "public"; break;
1840    case AM_Protected: return "protected"; break;
1841    case AM_Private: return "private"; break;
1842    default: return ""; break;
1843  }
1844}
1845
1846bool RSReflection::Context::startClass(AccessModifier AM,
1847                                       bool IsStatic,
1848                                       const std::string &ClassName,
1849                                       const char *SuperClassName,
1850                                       std::string &ErrorMsg) {
1851  if (mVerbose)
1852    std::cout << "Generating " << ClassName << ".java ..." << std::endl;
1853
1854  // Open file for class
1855  if (!openClassFile(ClassName, ErrorMsg))
1856    return false;
1857
1858  // License
1859  out() << mLicenseNote;
1860
1861  // Notice of generated file
1862  out() << "/*" << std::endl;
1863  out() << " * This file is auto-generated. DO NOT MODIFY!" << std::endl;
1864  out() << " * The source RenderScript file: " << mInputRSFile << std::endl;
1865  out() << " */" << std::endl;
1866
1867  // Package
1868  if (!mPackageName.empty())
1869    out() << "package " << mPackageName << ";" << std::endl;
1870  out() << std::endl;
1871
1872  // Imports
1873  for (unsigned i = 0; i < (sizeof(Import) / sizeof(const char*)); i++)
1874    out() << "import " << Import[i] << ";" << std::endl;
1875  out() << std::endl;
1876
1877  // All reflected classes should be annotated as hidden, so that they won't
1878  // be exposed in SDK.
1879  out() << "/**" << std::endl;
1880  out() << " * @hide" << std::endl;
1881  out() << " */" << std::endl;
1882
1883  out() << AccessModifierStr(AM) << ((IsStatic) ? " static" : "") << " class "
1884        << ClassName;
1885  if (SuperClassName != NULL)
1886    out() << " extends " << SuperClassName;
1887
1888  startBlock();
1889
1890  mClassName = ClassName;
1891
1892  return true;
1893}
1894
1895void RSReflection::Context::endClass() {
1896  endBlock();
1897  if (!mUseStdout)
1898    mOF.close();
1899  clear();
1900  return;
1901}
1902
1903void RSReflection::Context::startBlock(bool ShouldIndent) {
1904  if (ShouldIndent)
1905    indent() << "{" << std::endl;
1906  else
1907    out() << " {" << std::endl;
1908  incIndentLevel();
1909  return;
1910}
1911
1912void RSReflection::Context::endBlock() {
1913  decIndentLevel();
1914  indent() << "}" << std::endl << std::endl;
1915  return;
1916}
1917
1918void RSReflection::Context::startTypeClass(const std::string &ClassName) {
1919  indent() << "public static class " << ClassName;
1920  startBlock();
1921  return;
1922}
1923
1924void RSReflection::Context::endTypeClass() {
1925  endBlock();
1926  return;
1927}
1928
1929void RSReflection::Context::startFunction(AccessModifier AM,
1930                                          bool IsStatic,
1931                                          const char *ReturnType,
1932                                          const std::string &FunctionName,
1933                                          int Argc, ...) {
1934  ArgTy Args;
1935  va_list vl;
1936  va_start(vl, Argc);
1937
1938  for (int i = 0; i < Argc; i++) {
1939    const char *ArgType = va_arg(vl, const char*);
1940    const char *ArgName = va_arg(vl, const char*);
1941
1942    Args.push_back(std::make_pair(ArgType, ArgName));
1943  }
1944  va_end(vl);
1945
1946  startFunction(AM, IsStatic, ReturnType, FunctionName, Args);
1947
1948  return;
1949}
1950
1951void RSReflection::Context::startFunction(AccessModifier AM,
1952                                          bool IsStatic,
1953                                          const char *ReturnType,
1954                                          const std::string &FunctionName,
1955                                          const ArgTy &Args) {
1956  indent() << AccessModifierStr(AM) << ((IsStatic) ? " static " : " ")
1957           << ((ReturnType) ? ReturnType : "") << " " << FunctionName << "(";
1958
1959  bool FirstArg = true;
1960  for (ArgTy::const_iterator I = Args.begin(), E = Args.end();
1961       I != E;
1962       I++) {
1963    if (!FirstArg)
1964      out() << ", ";
1965    else
1966      FirstArg = false;
1967
1968    out() << I->first << " " << I->second;
1969  }
1970
1971  out() << ")";
1972  startBlock();
1973
1974  return;
1975}
1976
1977void RSReflection::Context::endFunction() {
1978  endBlock();
1979  return;
1980}
1981
1982}  // namespace slang
1983