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