slang_rs_reflection.cpp revision 6b64b2bd2daf45a4a8bd8b5a11d09410bd53455f
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    "addMatrix",   // RSExportPrimitiveType::DataTypeRSMatrix2x2
218    "addMatrix",   // RSExportPrimitiveType::DataTypeRSMatrix3x3
219    "addMatrix",   // 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 << ".addMatrix(" << 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  mGeneratedFileNames->push_back(ClassName);
1237
1238  genTypeItemClass(C, ERT);
1239
1240  // Declare item buffer and item buffer packer
1241  C.indent() << "private "RS_TYPE_ITEM_CLASS_NAME" "RS_TYPE_ITEM_BUFFER_NAME"[]"
1242      ";" << std::endl;
1243  C.indent() << "private FieldPacker "RS_TYPE_ITEM_BUFFER_PACKER_NAME";"
1244             << std::endl;
1245
1246  genTypeClassConstructor(C, ERT);
1247  genTypeClassCopyToArray(C, ERT);
1248  genTypeClassItemSetter(C, ERT);
1249  genTypeClassItemGetter(C, ERT);
1250  genTypeClassComponentSetter(C, ERT);
1251  genTypeClassComponentGetter(C, ERT);
1252  genTypeClassCopyAll(C, ERT);
1253  genTypeClassResize(C);
1254
1255  C.endClass();
1256
1257  C.resetFieldIndex();
1258  C.clearFieldIndexMap();
1259
1260  return true;
1261}
1262
1263void RSReflection::genTypeItemClass(Context &C,
1264                                    const RSExportRecordType *ERT) {
1265  C.indent() << "static public class "RS_TYPE_ITEM_CLASS_NAME;
1266  C.startBlock();
1267
1268  C.indent() << "public static final int sizeof = "
1269             << RSExportType::GetTypeAllocSize(ERT) << ";" << std::endl;
1270
1271  // Member elements
1272  C.out() << std::endl;
1273  for (RSExportRecordType::const_field_iterator FI = ERT->fields_begin(),
1274           FE = ERT->fields_end();
1275       FI != FE;
1276       FI++) {
1277    C.indent() << GetTypeName((*FI)->getType()) << " " << (*FI)->getName()
1278               << ";" << std::endl;
1279  }
1280
1281  // Constructor
1282  C.out() << std::endl;
1283  C.indent() << RS_TYPE_ITEM_CLASS_NAME"()";
1284  C.startBlock();
1285
1286  for (RSExportRecordType::const_field_iterator FI = ERT->fields_begin(),
1287           FE = ERT->fields_end();
1288       FI != FE;
1289       FI++) {
1290    const RSExportRecordType::Field *F = *FI;
1291    genAllocateVarOfType(C, F->getType(), F->getName());
1292  }
1293
1294  // end Constructor
1295  C.endBlock();
1296
1297  // end Item class
1298  C.endBlock();
1299
1300  return;
1301}
1302
1303void RSReflection::genTypeClassConstructor(Context &C,
1304                                           const RSExportRecordType *ERT) {
1305  const char *RenderScriptVar = "rs";
1306
1307  C.startFunction(Context::AM_Public,
1308                  true,
1309                  "Element",
1310                  "createElement",
1311                  1,
1312                  "RenderScript", RenderScriptVar);
1313  genBuildElement(C, "eb", ERT, RenderScriptVar, /* IsInline = */false);
1314  C.endFunction();
1315
1316  C.startFunction(Context::AM_Public,
1317                  false,
1318                  NULL,
1319                  C.getClassName(),
1320                  2,
1321                  "RenderScript", RenderScriptVar,
1322                  "int", "count");
1323
1324  C.indent() << RS_TYPE_ITEM_BUFFER_NAME" = null;" << std::endl;
1325  C.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME" = null;" << std::endl;
1326  C.indent() << "mElement = createElement(" << RenderScriptVar << ");"
1327             << std::endl;
1328  // Call init() in super class
1329  C.indent() << "init(" << RenderScriptVar << ", count);" << std::endl;
1330  C.endFunction();
1331
1332  C.startFunction(Context::AM_Public,
1333                  false,
1334                  NULL,
1335                  C.getClassName(),
1336                  3,
1337                  "RenderScript", RenderScriptVar,
1338                  "int", "count",
1339                  "int", "usages");
1340
1341  C.indent() << RS_TYPE_ITEM_BUFFER_NAME" = null;" << std::endl;
1342  C.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME" = null;" << std::endl;
1343  C.indent() << "mElement = createElement(" << RenderScriptVar << ");"
1344             << std::endl;
1345  // Call init() in super class
1346  C.indent() << "init(" << RenderScriptVar << ", count, usages);" << std::endl;
1347  C.endFunction();
1348
1349  return;
1350}
1351
1352void RSReflection::genTypeClassCopyToArray(Context &C,
1353                                           const RSExportRecordType *ERT) {
1354  C.startFunction(Context::AM_Private,
1355                  false,
1356                  "void",
1357                  "copyToArray",
1358                  2,
1359                  RS_TYPE_ITEM_CLASS_NAME, "i",
1360                  "int", "index");
1361
1362  genNewItemBufferPackerIfNull(C);
1363  C.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME
1364                ".reset(index * "RS_TYPE_ITEM_CLASS_NAME".sizeof);"
1365             << std::endl;
1366
1367  genPackVarOfType(C, ERT, "i", RS_TYPE_ITEM_BUFFER_PACKER_NAME);
1368
1369  C.endFunction();
1370  return;
1371}
1372
1373void RSReflection::genTypeClassItemSetter(Context &C,
1374                                          const RSExportRecordType *ERT) {
1375  C.startFunction(Context::AM_Public,
1376                  false,
1377                  "void",
1378                  "set",
1379                  3,
1380                  RS_TYPE_ITEM_CLASS_NAME, "i",
1381                  "int", "index",
1382                  "boolean", "copyNow");
1383  genNewItemBufferIfNull(C, NULL);
1384  C.indent() << RS_TYPE_ITEM_BUFFER_NAME"[index] = i;" << std::endl;
1385
1386  C.indent() << "if (copyNow) ";
1387  C.startBlock();
1388
1389  C.indent() << "copyToArray(i, index);" << std::endl;
1390  C.indent() << "mAllocation.setFromFieldPacker(index, "
1391                  RS_TYPE_ITEM_BUFFER_PACKER_NAME");" << std::endl;
1392
1393  // End of if (copyNow)
1394  C.endBlock();
1395
1396  C.endFunction();
1397  return;
1398}
1399
1400void RSReflection::genTypeClassItemGetter(Context &C,
1401                                          const RSExportRecordType *ERT) {
1402  C.startFunction(Context::AM_Public,
1403                  false,
1404                  RS_TYPE_ITEM_CLASS_NAME,
1405                  "get",
1406                  1,
1407                  "int", "index");
1408  C.indent() << "if ("RS_TYPE_ITEM_BUFFER_NAME" == null) return null;"
1409             << std::endl;
1410  C.indent() << "return "RS_TYPE_ITEM_BUFFER_NAME"[index];" << std::endl;
1411  C.endFunction();
1412  return;
1413}
1414
1415void RSReflection::genTypeClassComponentSetter(Context &C,
1416                                               const RSExportRecordType *ERT) {
1417  for (RSExportRecordType::const_field_iterator FI = ERT->fields_begin(),
1418           FE = ERT->fields_end();
1419       FI != FE;
1420       FI++) {
1421    const RSExportRecordType::Field *F = *FI;
1422    size_t FieldOffset = F->getOffsetInParent();
1423    size_t FieldStoreSize = RSExportType::GetTypeStoreSize(F->getType());
1424    unsigned FieldIndex = C.getFieldIndex(F);
1425
1426    C.startFunction(Context::AM_Public,
1427                    false,
1428                    "void",
1429                    "set_" + F->getName(), 3,
1430                    "int", "index",
1431                    GetTypeName(F->getType()).c_str(), "v",
1432                    "boolean", "copyNow");
1433    genNewItemBufferPackerIfNull(C);
1434    genNewItemBufferIfNull(C, "index");
1435    C.indent() << RS_TYPE_ITEM_BUFFER_NAME"[index]." << F->getName()
1436               << " = v;" << std::endl;
1437
1438    C.indent() << "if (copyNow) ";
1439    C.startBlock();
1440
1441    if (FieldOffset > 0)
1442      C.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME
1443                    ".reset(index * "RS_TYPE_ITEM_CLASS_NAME".sizeof + "
1444                 << FieldOffset << ");" << std::endl;
1445    else
1446      C.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME
1447                    ".reset(index * "RS_TYPE_ITEM_CLASS_NAME".sizeof);"
1448                 << std::endl;
1449    genPackVarOfType(C, F->getType(), "v", RS_TYPE_ITEM_BUFFER_PACKER_NAME);
1450
1451    C.indent() << "FieldPacker fp = new FieldPacker(" << FieldStoreSize << ");"
1452               << std::endl;
1453    genPackVarOfType(C, F->getType(), "v", "fp");
1454    C.indent() << "mAllocation.setFromFieldPacker(index, " << FieldIndex
1455               << ", fp);"
1456               << std::endl;
1457
1458    // End of if (copyNow)
1459    C.endBlock();
1460
1461    C.endFunction();
1462  }
1463  return;
1464}
1465
1466void RSReflection::genTypeClassComponentGetter(Context &C,
1467                                               const RSExportRecordType *ERT) {
1468  for (RSExportRecordType::const_field_iterator FI = ERT->fields_begin(),
1469           FE = ERT->fields_end();
1470       FI != FE;
1471       FI++) {
1472    const RSExportRecordType::Field *F = *FI;
1473    C.startFunction(Context::AM_Public,
1474                    false,
1475                    GetTypeName(F->getType()).c_str(),
1476                    "get_" + F->getName(),
1477                    1,
1478                    "int", "index");
1479    C.indent() << "if ("RS_TYPE_ITEM_BUFFER_NAME" == null) return "
1480               << GetTypeNullValue(F->getType()) << ";" << std::endl;
1481    C.indent() << "return "RS_TYPE_ITEM_BUFFER_NAME"[index]." << F->getName()
1482               << ";" << std::endl;
1483    C.endFunction();
1484  }
1485  return;
1486}
1487
1488void RSReflection::genTypeClassCopyAll(Context &C,
1489                                       const RSExportRecordType *ERT) {
1490  C.startFunction(Context::AM_Public, false, "void", "copyAll", 0);
1491
1492  C.indent() << "for (int ct = 0; ct < "RS_TYPE_ITEM_BUFFER_NAME".length; ct++)"
1493                  " copyToArray("RS_TYPE_ITEM_BUFFER_NAME"[ct], ct);"
1494             << std::endl;
1495  C.indent() << "mAllocation.setFromFieldPacker(0, "
1496                  RS_TYPE_ITEM_BUFFER_PACKER_NAME");"
1497             << std::endl;
1498
1499  C.endFunction();
1500  return;
1501}
1502
1503void RSReflection::genTypeClassResize(Context &C) {
1504  C.startFunction(Context::AM_Public,
1505                  false,
1506                  "void",
1507                  "resize",
1508                  1,
1509                  "int", "newSize");
1510
1511  C.indent() << "if (mItemArray != null) ";
1512  C.startBlock();
1513  C.indent() << "int oldSize = mItemArray.length;" << std::endl;
1514  C.indent() << "int copySize = Math.min(oldSize, newSize);" << std::endl;
1515  C.indent() << "if (newSize == oldSize) return;" << std::endl;
1516  C.indent() << "Item ni[] = new Item[newSize];" << std::endl;
1517  C.indent() << "System.arraycopy(mItemArray, 0, ni, 0, copySize);"
1518             << std::endl;
1519  C.indent() << "mItemArray = ni;" << std::endl;
1520  C.endBlock();
1521  C.indent() << "mAllocation.resize(newSize);" << std::endl;
1522
1523  C.indent() << "if (" RS_TYPE_ITEM_BUFFER_PACKER_NAME " != null) "
1524                  RS_TYPE_ITEM_BUFFER_PACKER_NAME " = "
1525                    "new FieldPacker(" RS_TYPE_ITEM_CLASS_NAME
1526                      ".sizeof * getType().getX()/* count */"
1527                        ");" << std::endl;
1528
1529  C.endFunction();
1530  return;
1531}
1532
1533/******************** Methods to generate type class /end ********************/
1534
1535/********** Methods to create Element in Java of given record type ***********/
1536void RSReflection::genBuildElement(Context &C,
1537                                   const char *ElementBuilderName,
1538                                   const RSExportRecordType *ERT,
1539                                   const char *RenderScriptVar,
1540                                   bool IsInline) {
1541  C.indent() << "Element.Builder " << ElementBuilderName << " = "
1542      "new Element.Builder(" << RenderScriptVar << ");" << std::endl;
1543
1544  // eb.add(...)
1545  genAddElementToElementBuilder(C,
1546                                ERT,
1547                                "",
1548                                ElementBuilderName,
1549                                RenderScriptVar,
1550                                /* ArraySize = */0);
1551
1552  if (!IsInline)
1553    C.indent() << "return " << ElementBuilderName << ".create();" << std::endl;
1554  return;
1555}
1556
1557#define EB_ADD(x) do {                                              \
1558  C.indent() << ElementBuilderName                                  \
1559             << ".add(" << x << ", \"" << VarName << "\"";  \
1560  if (ArraySize > 0)                                                \
1561    C.out() << ", " << ArraySize;                                   \
1562  C.out() << ");" << std::endl;                                     \
1563  C.incFieldIndex();                                                \
1564} while (false)
1565
1566void RSReflection::genAddElementToElementBuilder(Context &C,
1567                                                 const RSExportType *ET,
1568                                                 const std::string &VarName,
1569                                                 const char *ElementBuilderName,
1570                                                 const char *RenderScriptVar,
1571                                                 unsigned ArraySize) {
1572  const char *ElementConstruct = GetBuiltinElementConstruct(ET);
1573
1574  if (ElementConstruct != NULL) {
1575    EB_ADD(ElementConstruct << "(" << RenderScriptVar << ")");
1576  } else {
1577    if ((ET->getClass() == RSExportType::ExportClassPrimitive) ||
1578        (ET->getClass() == RSExportType::ExportClassVector)) {
1579      const RSExportPrimitiveType *EPT =
1580          static_cast<const RSExportPrimitiveType*>(ET);
1581      const char *DataKindName = GetElementDataKindName(EPT->getKind());
1582      const char *DataTypeName = GetElementDataTypeName(EPT->getType());
1583      int Size = (ET->getClass() == RSExportType::ExportClassVector) ?
1584          static_cast<const RSExportVectorType*>(ET)->getNumElement() :
1585          1;
1586
1587      switch (EPT->getKind()) {
1588        case RSExportPrimitiveType::DataKindPixelL:
1589        case RSExportPrimitiveType::DataKindPixelA:
1590        case RSExportPrimitiveType::DataKindPixelLA:
1591        case RSExportPrimitiveType::DataKindPixelRGB:
1592        case RSExportPrimitiveType::DataKindPixelRGBA: {
1593          // Element.createPixel()
1594          EB_ADD("Element.createPixel(" << RenderScriptVar << ", "
1595                                        << DataTypeName << ", "
1596                                        << DataKindName << ")");
1597          break;
1598        }
1599        case RSExportPrimitiveType::DataKindUser:
1600        default: {
1601          if (EPT->getClass() == RSExportType::ExportClassPrimitive) {
1602            // Element.createUser()
1603            EB_ADD("Element.createUser(" << RenderScriptVar << ", "
1604                                         << DataTypeName << ")");
1605          } else {
1606            assert((ET->getClass() == RSExportType::ExportClassVector) &&
1607                   "Unexpected type.");
1608            EB_ADD("Element.createVector(" << RenderScriptVar << ", "
1609                                           << DataTypeName << ", "
1610                                           << Size << ")");
1611          }
1612          break;
1613        }
1614      }
1615#ifndef NDEBUG
1616    } else if (ET->getClass() == RSExportType::ExportClassPointer) {
1617      // Pointer type variable should be resolved in
1618      // GetBuiltinElementConstruct()
1619      assert(false && "??");
1620    } else if (ET->getClass() == RSExportType::ExportClassMatrix) {
1621      // Matrix type variable should be resolved
1622      // in GetBuiltinElementConstruct()
1623      assert(false && "??");
1624#endif
1625    } else if (ET->getClass() == RSExportType::ExportClassConstantArray) {
1626      const RSExportConstantArrayType *ECAT =
1627          static_cast<const RSExportConstantArrayType *>(ET);
1628
1629      const RSExportType *ElementType = ECAT->getElementType();
1630      if (ElementType->getClass() != RSExportType::ExportClassRecord) {
1631        genAddElementToElementBuilder(C,
1632                                      ECAT->getElementType(),
1633                                      VarName,
1634                                      ElementBuilderName,
1635                                      RenderScriptVar,
1636                                      ECAT->getSize());
1637      } else {
1638        std::string NewElementBuilderName(ElementBuilderName);
1639        NewElementBuilderName.append(1, '_');
1640
1641        genBuildElement(C,
1642                        NewElementBuilderName.c_str(),
1643                        static_cast<const RSExportRecordType*>(ElementType),
1644                        RenderScriptVar,
1645                        /* IsInline = */true);
1646        ArraySize = ECAT->getSize();
1647        EB_ADD(NewElementBuilderName << ".create()");
1648      }
1649    } else if (ET->getClass() == RSExportType::ExportClassRecord) {
1650      // Simalar to case of RSExportType::ExportClassRecord in genPackVarOfType.
1651      //
1652      // TODO(zonr): Generalize these two function such that there's no
1653      //             duplicated codes.
1654      const RSExportRecordType *ERT =
1655          static_cast<const RSExportRecordType*>(ET);
1656      int Pos = 0;    // relative pos from now on
1657
1658      for (RSExportRecordType::const_field_iterator I = ERT->fields_begin(),
1659               E = ERT->fields_end();
1660           I != E;
1661           I++) {
1662        const RSExportRecordType::Field *F = *I;
1663        std::string FieldName;
1664        int FieldOffset = F->getOffsetInParent();
1665        int FieldStoreSize = RSExportType::GetTypeStoreSize(F->getType());
1666        int FieldAllocSize = RSExportType::GetTypeAllocSize(F->getType());
1667
1668        if (!VarName.empty())
1669          FieldName = VarName + "." + F->getName();
1670        else
1671          FieldName = F->getName();
1672
1673        // Alignment
1674        genAddPaddingToElementBuiler(C,
1675                                     (FieldOffset - Pos),
1676                                     ElementBuilderName,
1677                                     RenderScriptVar);
1678
1679        // eb.add(...)
1680        C.addFieldIndexMapping(F);
1681        if (F->getType()->getClass() != RSExportType::ExportClassRecord) {
1682          genAddElementToElementBuilder(C,
1683                                        F->getType(),
1684                                        FieldName,
1685                                        ElementBuilderName,
1686                                        RenderScriptVar,
1687                                        0);
1688        } else {
1689          std::string NewElementBuilderName(ElementBuilderName);
1690          NewElementBuilderName.append(1, '_');
1691
1692          genBuildElement(C,
1693                          NewElementBuilderName.c_str(),
1694                          static_cast<const RSExportRecordType*>(F->getType()),
1695                          RenderScriptVar,
1696                          /* IsInline = */true);
1697
1698          const std::string &VarName = FieldName;  // Hack for EB_ADD macro
1699          EB_ADD(NewElementBuilderName << ".create()");
1700        }
1701
1702        // There is padding within the field type
1703        genAddPaddingToElementBuiler(C,
1704                                     (FieldAllocSize - FieldStoreSize),
1705                                     ElementBuilderName,
1706                                     RenderScriptVar);
1707
1708        Pos = FieldOffset + FieldAllocSize;
1709      }
1710
1711      // There maybe some padding after the struct
1712      size_t RecordStoreSize = RSExportType::GetTypeStoreSize(ERT);
1713
1714      genAddPaddingToElementBuiler(C,
1715                                   RecordStoreSize - Pos,
1716                                   ElementBuilderName,
1717                                   RenderScriptVar);
1718    } else {
1719      assert(false && "Unknown class of type");
1720    }
1721  }
1722}
1723
1724void RSReflection::genAddPaddingToElementBuiler(Context &C,
1725                                                int PaddingSize,
1726                                                const char *ElementBuilderName,
1727                                                const char *RenderScriptVar) {
1728  unsigned ArraySize = 0;   // Hack the EB_ADD macro
1729  while (PaddingSize > 0) {
1730    const std::string &VarName = C.createPaddingField();
1731    if (PaddingSize >= 4) {
1732      EB_ADD("Element.U32(" << RenderScriptVar << ")");
1733      PaddingSize -= 4;
1734    } else if (PaddingSize >= 2) {
1735      EB_ADD("Element.U16(" << RenderScriptVar << ")");
1736      PaddingSize -= 2;
1737    } else if (PaddingSize >= 1) {
1738      EB_ADD("Element.U8(" << RenderScriptVar << ")");
1739      PaddingSize -= 1;
1740    }
1741  }
1742  return;
1743}
1744
1745#undef EB_ADD
1746/******** Methods to create Element in Java of given record type /end ********/
1747
1748bool RSReflection::reflect(const std::string &OutputPathBase,
1749                           const std::string &OutputPackageName,
1750                           const std::string &InputFileName,
1751                           const std::string &OutputBCFileName) {
1752  Context *C = NULL;
1753  std::string ResourceId = "";
1754
1755  if (!GetClassNameFromFileName(OutputBCFileName, ResourceId))
1756    return false;
1757
1758  if (ResourceId.empty())
1759    ResourceId = "<Resource ID>";
1760
1761  if (OutputPackageName.empty() || OutputPackageName == "-")
1762    C = new Context(OutputPathBase, InputFileName, "<Package Name>",
1763                    ResourceId, true);
1764  else
1765    C = new Context(OutputPathBase, InputFileName, OutputPackageName,
1766                    ResourceId, false);
1767
1768  if (C != NULL) {
1769    std::string ErrorMsg, ScriptClassName;
1770    // class ScriptC_<ScriptName>
1771    if (!GetClassNameFromFileName(InputFileName, ScriptClassName))
1772      return false;
1773
1774    if (ScriptClassName.empty())
1775      ScriptClassName = "<Input Script Name>";
1776
1777    ScriptClassName.insert(0, RS_SCRIPT_CLASS_NAME_PREFIX);
1778
1779    if (mRSContext->getLicenseNote() != NULL) {
1780      C->setLicenseNote(*(mRSContext->getLicenseNote()));
1781    }
1782
1783    if (!genScriptClass(*C, ScriptClassName, ErrorMsg)) {
1784      std::cerr << "Failed to generate class " << ScriptClassName << " ("
1785                << ErrorMsg << ")" << std::endl;
1786      return false;
1787    }
1788
1789    mGeneratedFileNames->push_back(ScriptClassName);
1790
1791    // class ScriptField_<TypeName>
1792    for (RSContext::const_export_type_iterator TI =
1793             mRSContext->export_types_begin(),
1794             TE = mRSContext->export_types_end();
1795         TI != TE;
1796         TI++) {
1797      const RSExportType *ET = TI->getValue();
1798
1799      if (ET->getClass() == RSExportType::ExportClassRecord) {
1800        const RSExportRecordType *ERT =
1801            static_cast<const RSExportRecordType*>(ET);
1802
1803        if (!ERT->isArtificial() && !genTypeClass(*C, ERT, ErrorMsg)) {
1804          std::cerr << "Failed to generate type class for struct '"
1805                    << ERT->getName() << "' (" << ErrorMsg << ")" << std::endl;
1806          return false;
1807        }
1808      }
1809    }
1810  }
1811
1812  return true;
1813}
1814
1815/************************** RSReflection::Context **************************/
1816const char *const RSReflection::Context::ApacheLicenseNote =
1817    "/*\n"
1818    " * Copyright (C) 2010 The Android Open Source Project\n"
1819    " *\n"
1820    " * Licensed under the Apache License, Version 2.0 (the \"License\");\n"
1821    " * you may not use this file except in compliance with the License.\n"
1822    " * You may obtain a copy of the License at\n"
1823    " *\n"
1824    " *      http://www.apache.org/licenses/LICENSE-2.0\n"
1825    " *\n"
1826    " * Unless required by applicable law or agreed to in writing, software\n"
1827    " * distributed under the License is distributed on an \"AS IS\" BASIS,\n"
1828    " * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or "
1829    "implied.\n"
1830    " * See the License for the specific language governing permissions and\n"
1831    " * limitations under the License.\n"
1832    " */\n"
1833    "\n";
1834
1835const char *const RSReflection::Context::Import[] = {
1836  // RenderScript java class
1837  "android.renderscript.*",
1838  // Import R
1839  "android.content.res.Resources",
1840  // Import for debugging
1841  // "android.util.Log",
1842};
1843
1844bool RSReflection::Context::openClassFile(const std::string &ClassName,
1845                                          std::string &ErrorMsg) {
1846  if (!mUseStdout) {
1847    mOF.clear();
1848    std::string Path =
1849        RSSlangReflectUtils::ComputePackagedPath(mOutputPathBase.c_str(),
1850                                                 mPackageName.c_str());
1851
1852    if (!SlangUtils::CreateDirectoryWithParents(Path, &ErrorMsg))
1853      return false;
1854
1855    std::string ClassFile = Path + "/" + ClassName + ".java";
1856
1857    mOF.open(ClassFile.c_str());
1858    if (!mOF.good()) {
1859      ErrorMsg = "failed to open file '" + ClassFile + "' for write";
1860      return false;
1861    }
1862  }
1863  return true;
1864}
1865
1866const char *RSReflection::Context::AccessModifierStr(AccessModifier AM) {
1867  switch (AM) {
1868    case AM_Public: return "public"; break;
1869    case AM_Protected: return "protected"; break;
1870    case AM_Private: return "private"; break;
1871    default: return ""; break;
1872  }
1873}
1874
1875bool RSReflection::Context::startClass(AccessModifier AM,
1876                                       bool IsStatic,
1877                                       const std::string &ClassName,
1878                                       const char *SuperClassName,
1879                                       std::string &ErrorMsg) {
1880  if (mVerbose)
1881    std::cout << "Generating " << ClassName << ".java ..." << std::endl;
1882
1883  // Open file for class
1884  if (!openClassFile(ClassName, ErrorMsg))
1885    return false;
1886
1887  // License
1888  out() << mLicenseNote;
1889
1890  // Notice of generated file
1891  out() << "/*" << std::endl;
1892  out() << " * This file is auto-generated. DO NOT MODIFY!" << std::endl;
1893  out() << " * The source RenderScript file: " << mInputRSFile << std::endl;
1894  out() << " */" << std::endl;
1895
1896  // Package
1897  if (!mPackageName.empty())
1898    out() << "package " << mPackageName << ";" << std::endl;
1899  out() << std::endl;
1900
1901  // Imports
1902  for (unsigned i = 0; i < (sizeof(Import) / sizeof(const char*)); i++)
1903    out() << "import " << Import[i] << ";" << std::endl;
1904  out() << std::endl;
1905
1906  // All reflected classes should be annotated as hidden, so that they won't
1907  // be exposed in SDK.
1908  out() << "/**" << std::endl;
1909  out() << " * @hide" << std::endl;
1910  out() << " */" << std::endl;
1911
1912  out() << AccessModifierStr(AM) << ((IsStatic) ? " static" : "") << " class "
1913        << ClassName;
1914  if (SuperClassName != NULL)
1915    out() << " extends " << SuperClassName;
1916
1917  startBlock();
1918
1919  mClassName = ClassName;
1920
1921  return true;
1922}
1923
1924void RSReflection::Context::endClass() {
1925  endBlock();
1926  if (!mUseStdout)
1927    mOF.close();
1928  clear();
1929  return;
1930}
1931
1932void RSReflection::Context::startBlock(bool ShouldIndent) {
1933  if (ShouldIndent)
1934    indent() << "{" << std::endl;
1935  else
1936    out() << " {" << std::endl;
1937  incIndentLevel();
1938  return;
1939}
1940
1941void RSReflection::Context::endBlock() {
1942  decIndentLevel();
1943  indent() << "}" << std::endl << std::endl;
1944  return;
1945}
1946
1947void RSReflection::Context::startTypeClass(const std::string &ClassName) {
1948  indent() << "public static class " << ClassName;
1949  startBlock();
1950  return;
1951}
1952
1953void RSReflection::Context::endTypeClass() {
1954  endBlock();
1955  return;
1956}
1957
1958void RSReflection::Context::startFunction(AccessModifier AM,
1959                                          bool IsStatic,
1960                                          const char *ReturnType,
1961                                          const std::string &FunctionName,
1962                                          int Argc, ...) {
1963  ArgTy Args;
1964  va_list vl;
1965  va_start(vl, Argc);
1966
1967  for (int i = 0; i < Argc; i++) {
1968    const char *ArgType = va_arg(vl, const char*);
1969    const char *ArgName = va_arg(vl, const char*);
1970
1971    Args.push_back(std::make_pair(ArgType, ArgName));
1972  }
1973  va_end(vl);
1974
1975  startFunction(AM, IsStatic, ReturnType, FunctionName, Args);
1976
1977  return;
1978}
1979
1980void RSReflection::Context::startFunction(AccessModifier AM,
1981                                          bool IsStatic,
1982                                          const char *ReturnType,
1983                                          const std::string &FunctionName,
1984                                          const ArgTy &Args) {
1985  indent() << AccessModifierStr(AM) << ((IsStatic) ? " static " : " ")
1986           << ((ReturnType) ? ReturnType : "") << " " << FunctionName << "(";
1987
1988  bool FirstArg = true;
1989  for (ArgTy::const_iterator I = Args.begin(), E = Args.end();
1990       I != E;
1991       I++) {
1992    if (!FirstArg)
1993      out() << ", ";
1994    else
1995      FirstArg = false;
1996
1997    out() << I->first << " " << I->second;
1998  }
1999
2000  out() << ")";
2001  startBlock();
2002
2003  return;
2004}
2005
2006void RSReflection::Context::endFunction() {
2007  endBlock();
2008  return;
2009}
2010
2011}  // namespace slang
2012