slang_rs_reflection.cpp revision 92b344a51c6c4934e96882bd401e4b13d6d03db8
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    case RSExportType::ExportClassConstantArray: {
223      return GetPrimitiveTypeName(
224                static_cast<const RSExportPrimitiveType*>(ET));
225      break;
226    }
227    case RSExportType::ExportClassPointer: {
228      const RSExportType *PointeeType =
229          static_cast<const RSExportPointerType*>(ET)->getPointeeType();
230
231      if (PointeeType->getClass() != RSExportType::ExportClassRecord)
232        return "Allocation";
233      else
234        return RS_TYPE_CLASS_NAME_PREFIX + PointeeType->getName();
235      break;
236    }
237    case RSExportType::ExportClassVector: {
238      return GetVectorTypeName(static_cast<const RSExportVectorType*>(ET));
239      break;
240    }
241    case RSExportType::ExportClassMatrix: {
242      return GetMatrixTypeName(static_cast<const RSExportMatrixType*>(ET));
243      break;
244    }
245    case RSExportType::ExportClassRecord: {
246      return RS_TYPE_CLASS_NAME_PREFIX + ET->getName() +
247                 "."RS_TYPE_ITEM_CLASS_NAME;
248      break;
249    }
250    default: {
251      assert(false && "Unknown class of type");
252    }
253  }
254
255  return "";
256}
257
258static const char *GetBuiltinElementConstruct(const RSExportType *ET) {
259  if (ET->getClass() == RSExportType::ExportClassPrimitive ||
260      ET->getClass() == RSExportType::ExportClassConstantArray) {
261    const RSExportPrimitiveType *EPT =
262        static_cast<const RSExportPrimitiveType*>(ET);
263    if (EPT->getKind() == RSExportPrimitiveType::DataKindUser) {
264      static const char *PrimitiveBuiltinElementConstructMap[] = {
265        NULL,   // RSExportPrimitiveType::DataTypeFloat16
266        "F32",  // RSExportPrimitiveType::DataTypeFloat32
267        "F64",  // RSExportPrimitiveType::DataTypeFloat64
268        "I8",   // RSExportPrimitiveType::DataTypeSigned8
269        NULL,   // RSExportPrimitiveType::DataTypeSigned16
270        "I32",  // RSExportPrimitiveType::DataTypeSigned32
271        "I64",  // RSExportPrimitiveType::DataTypeSigned64
272        "U8",   // RSExportPrimitiveType::DataTypeUnsigned8
273        NULL,   // RSExportPrimitiveType::DataTypeUnsigned16
274        "U32",  // RSExportPrimitiveType::DataTypeUnsigned32
275        NULL,   // RSExportPrimitiveType::DataTypeUnsigned64
276        "BOOLEAN",  // RSExportPrimitiveType::DataTypeBoolean
277
278        NULL,   // RSExportPrimitiveType::DataTypeUnsigned565
279        NULL,   // RSExportPrimitiveType::DataTypeUnsigned5551
280        NULL,   // RSExportPrimitiveType::DataTypeUnsigned4444
281
282        NULL,   // (Dummy) RSExportPrimitiveType::DataTypeRSMatrix2x2
283        NULL,   // (Dummy) RSExportPrimitiveType::DataTypeRSMatrix3x3
284        NULL,   // (Dummy) RSExportPrimitiveType::DataTypeRSMatrix4x4
285
286        "ELEMENT",      // RSExportPrimitiveType::DataTypeRSElement
287        "TYPE",         // RSExportPrimitiveType::DataTypeRSType
288        "ALLOCATION",   // RSExportPrimitiveType::DataTypeRSAllocation
289        "SAMPLER",      // RSExportPrimitiveType::DataTypeRSSampler
290        "SCRIPT",       // RSExportPrimitiveType::DataTypeRSScript
291        "MESH",         // RSExportPrimitiveType::DataTypeRSMesh
292        "PROGRAM_FRAGMENT",  // RSExportPrimitiveType::DataTypeRSProgramFragment
293        "PROGRAM_VERTEX",    // RSExportPrimitiveType::DataTypeRSProgramVertex
294        "PROGRAM_RASTER",    // RSExportPrimitiveType::DataTypeRSProgramRaster
295        "PROGRAM_STORE",     // RSExportPrimitiveType::DataTypeRSProgramStore
296        "FONT",       // RSExportPrimitiveType::DataTypeRSFont
297      };
298      unsigned TypeId = EPT->getType();
299
300      if (TypeId <
301          (sizeof(PrimitiveBuiltinElementConstructMap) / sizeof(const char*)))
302        return PrimitiveBuiltinElementConstructMap[ EPT->getType() ];
303    } else if (EPT->getKind() == RSExportPrimitiveType::DataKindPixelA) {
304      if (EPT->getType() == RSExportPrimitiveType::DataTypeUnsigned8)
305        return "A_8";
306    } else if (EPT->getKind() == RSExportPrimitiveType::DataKindPixelRGB) {
307      if (EPT->getType() == RSExportPrimitiveType::DataTypeUnsigned565)
308        return "RGB_565";
309      else if (EPT->getType() == RSExportPrimitiveType::DataTypeUnsigned8)
310        return "RGB_888";
311    } else if (EPT->getKind() == RSExportPrimitiveType::DataKindPixelRGBA) {
312      if (EPT->getType() == RSExportPrimitiveType::DataTypeUnsigned5551)
313        return "RGBA_5551";
314      else if (EPT->getType() == RSExportPrimitiveType::DataTypeUnsigned4444)
315        return "RGBA_4444";
316      else if (EPT->getType() == RSExportPrimitiveType::DataTypeUnsigned8)
317        return "RGBA_8888";
318    }
319  } else if (ET->getClass() == RSExportType::ExportClassVector) {
320    const RSExportVectorType *EVT = static_cast<const RSExportVectorType*>(ET);
321    if (EVT->getKind() == RSExportPrimitiveType::DataKindUser) {
322      if (EVT->getType() == RSExportPrimitiveType::DataTypeFloat32) {
323        if (EVT->getNumElement() == 2)
324          return "F32_2";
325        else if (EVT->getNumElement() == 3)
326          return "F32_3";
327        else if (EVT->getNumElement() == 4)
328          return "F32_4";
329      } else if (EVT->getType() == RSExportPrimitiveType::DataTypeUnsigned8) {
330        if (EVT->getNumElement() == 4)
331          return "U8_4";
332      }
333    }
334  } else if (ET->getClass() == RSExportType::ExportClassMatrix) {
335    const RSExportMatrixType *EMT = static_cast<const RSExportMatrixType *>(ET);
336    switch (EMT->getDim()) {
337      case 2: {
338        return "MATRIX_2X2";
339        break;
340      }
341      case 3: {
342        return "MATRIX_3X3";
343        break;
344      }
345      case 4: {
346        return "MATRIX_4X4";
347        break;
348      }
349      default: {
350        assert(false && "Unsupported dimension of matrix");
351      }
352    }
353  } else if (ET->getClass() == RSExportType::ExportClassPointer) {
354    // Treat pointer type variable as unsigned int
355    // TODO(zonr): this is target dependent
356    return "USER_I32";
357  }
358
359  return NULL;
360}
361
362static const char *GetElementDataKindName(RSExportPrimitiveType::DataKind DK) {
363  static const char *ElementDataKindNameMap[] = {
364    "Element.DataKind.USER",        // RSExportPrimitiveType::DataKindUser
365    "Element.DataKind.PIXEL_L",     // RSExportPrimitiveType::DataKindPixelL
366    "Element.DataKind.PIXEL_A",     // RSExportPrimitiveType::DataKindPixelA
367    "Element.DataKind.PIXEL_LA",    // RSExportPrimitiveType::DataKindPixelLA
368    "Element.DataKind.PIXEL_RGB",   // RSExportPrimitiveType::DataKindPixelRGB
369    "Element.DataKind.PIXEL_RGBA",  // RSExportPrimitiveType::DataKindPixelRGBA
370  };
371
372  if (static_cast<unsigned>(DK) <
373      (sizeof(ElementDataKindNameMap) / sizeof(const char*)))
374    return ElementDataKindNameMap[ DK ];
375  else
376    return NULL;
377}
378
379static const char *GetElementDataTypeName(RSExportPrimitiveType::DataType DT) {
380  static const char *ElementDataTypeNameMap[] = {
381    NULL,                           // RSExportPrimitiveType::DataTypeFloat16
382    "Element.DataType.FLOAT_32",    // RSExportPrimitiveType::DataTypeFloat32
383    "Element.DataType.FLOAT_64",    // RSExportPrimitiveType::DataTypeFloat64
384    "Element.DataType.SIGNED_8",    // RSExportPrimitiveType::DataTypeSigned8
385    "Element.DataType.SIGNED_16",   // RSExportPrimitiveType::DataTypeSigned16
386    "Element.DataType.SIGNED_32",   // RSExportPrimitiveType::DataTypeSigned32
387    "Element.DataType.SIGNED_64",   // RSExportPrimitiveType::DataTypeSigned64
388    "Element.DataType.UNSIGNED_8",  // RSExportPrimitiveType::DataTypeUnsigned8
389    "Element.DataType.UNSIGNED_16", // RSExportPrimitiveType::DataTypeUnsigned16
390    "Element.DataType.UNSIGNED_32", // RSExportPrimitiveType::DataTypeUnsigned32
391    NULL,                           // RSExportPrimitiveType::DataTypeUnsigned64
392    "Element.DataType.BOOLEAN",     // RSExportPrimitiveType::DataTypeBoolean
393
394    // RSExportPrimitiveType::DataTypeUnsigned565
395    "Element.DataType.UNSIGNED_5_6_5",
396    // RSExportPrimitiveType::DataTypeUnsigned5551
397    "Element.DataType.UNSIGNED_5_5_5_1",
398    // RSExportPrimitiveType::DataTypeUnsigned4444
399    "Element.DataType.UNSIGNED_4_4_4_4",
400
401    // DataTypeRSMatrix* must have been resolved in GetBuiltinElementConstruct()
402    NULL, // (Dummy) RSExportPrimitiveType::DataTypeRSMatrix2x2
403    NULL, // (Dummy) RSExportPrimitiveType::DataTypeRSMatrix3x3
404    NULL, // (Dummy) RSExportPrimitiveType::DataTypeRSMatrix4x4
405
406    "Element.DataType.RS_ELEMENT",  // RSExportPrimitiveType::DataTypeRSElement
407    "Element.DataType.RS_TYPE",     // RSExportPrimitiveType::DataTypeRSType
408      // RSExportPrimitiveType::DataTypeRSAllocation
409    "Element.DataType.RS_ALLOCATION",
410      // RSExportPrimitiveType::DataTypeRSSampler
411    "Element.DataType.RS_SAMPLER",
412      // RSExportPrimitiveType::DataTypeRSScript
413    "Element.DataType.RS_SCRIPT",
414      // RSExportPrimitiveType::DataTypeRSMesh
415    "Element.DataType.RS_MESH",
416      // RSExportPrimitiveType::DataTypeRSProgramFragment
417    "Element.DataType.RS_PROGRAM_FRAGMENT",
418      // RSExportPrimitiveType::DataTypeRSProgramVertex
419    "Element.DataType.RS_PROGRAM_VERTEX",
420      // RSExportPrimitiveType::DataTypeRSProgramRaster
421    "Element.DataType.RS_PROGRAM_RASTER",
422      // RSExportPrimitiveType::DataTypeRSProgramStore
423    "Element.DataType.RS_PROGRAM_STORE",
424      // RSExportPrimitiveType::DataTypeRSFont
425    "Element.DataType.RS_FONT",
426  };
427
428  if (static_cast<unsigned>(DT) <
429      (sizeof(ElementDataTypeNameMap) / sizeof(const char*)))
430    return ElementDataTypeNameMap[ DT ];
431  else
432    return NULL;
433}
434
435bool RSReflection::openScriptFile(Context &C,
436                                  const std::string &ClassName,
437                                  std::string &ErrorMsg) {
438  if (!C.mUseStdout) {
439    C.mOF.clear();
440    std::string _path = RSSlangReflectUtils::ComputePackagedPath(
441        mRSContext->getReflectJavaPathName().c_str(),
442        C.getPackageName().c_str());
443
444    RSSlangReflectUtils::mkdir_p(_path.c_str());
445    C.mOF.open((_path + "/" + ClassName + ".java").c_str());
446    if (!C.mOF.good()) {
447      ErrorMsg = "failed to open file '" + _path + "/" + ClassName
448          + ".java' for write";
449
450      return false;
451    }
452  }
453  return true;
454}
455
456/********************** Methods to generate script class **********************/
457bool RSReflection::genScriptClass(Context &C,
458                                  const std::string &ClassName,
459                                  std::string &ErrorMsg) {
460  // Open the file
461  if (!openScriptFile(C, ClassName, ErrorMsg)) {
462    return false;
463  }
464
465  if (!C.startClass(Context::AM_Public,
466                    false,
467                    ClassName,
468                    RS_SCRIPT_CLASS_SUPER_CLASS_NAME,
469                    ErrorMsg))
470    return false;
471
472  genScriptClassConstructor(C);
473
474  // Reflect export variable
475  for (RSContext::const_export_var_iterator I = mRSContext->export_vars_begin(),
476           E = mRSContext->export_vars_end();
477       I != E;
478       I++)
479    genExportVariable(C, *I);
480
481  // Reflect export function
482  for (RSContext::const_export_func_iterator
483           I = mRSContext->export_funcs_begin(),
484           E = mRSContext->export_funcs_end();
485       I != E; I++)
486    genExportFunction(C, *I);
487
488  C.endClass();
489
490  return true;
491}
492
493void RSReflection::genScriptClassConstructor(Context &C) {
494  C.indent() << "// Constructor" << std::endl;
495  C.startFunction(Context::AM_Public,
496                  false,
497                  NULL,
498                  C.getClassName(),
499                  4,
500                  "RenderScript",
501                  "rs",
502                  "Resources",
503                  "resources",
504                  "int",
505                  "id",
506                  "boolean",
507                  "isRoot");
508  // Call constructor of super class
509  C.indent() << "super(rs, resources, id, isRoot);" << std::endl;
510
511  // If an exported variable has initial value, reflect it
512
513  for (RSContext::const_export_var_iterator I = mRSContext->export_vars_begin(),
514           E = mRSContext->export_vars_end();
515       I != E;
516       I++) {
517    const RSExportVar *EV = *I;
518    if (!EV->getInit().isUninit())
519      genInitExportVariable(C, EV->getType(), EV->getName(), EV->getInit());
520  }
521
522  C.endFunction();
523  return;
524}
525
526void RSReflection::genInitBoolExportVariable(Context &C,
527                                             const std::string &VarName,
528                                             const clang::APValue &Val) {
529  assert(!Val.isUninit() && "Not a valid initializer");
530
531  C.indent() << RS_EXPORT_VAR_PREFIX << VarName << " = ";
532  assert((Val.getKind() == clang::APValue::Int) &&
533         "Bool type has wrong initial APValue");
534
535  C.out() << ((Val.getInt().getSExtValue() == 0) ? "false" : "true")
536          << ";" << std::endl;
537
538  return;
539}
540
541void RSReflection::genInitPrimitiveExportVariable(Context &C,
542                                                  const std::string &VarName,
543                                                  const clang::APValue &Val) {
544  assert(!Val.isUninit() && "Not a valid initializer");
545
546  C.indent() << RS_EXPORT_VAR_PREFIX << VarName << " = ";
547  switch (Val.getKind()) {
548    case clang::APValue::Int: {
549      C.out() << Val.getInt().getSExtValue();
550      break;
551    }
552    case clang::APValue::Float: {
553      llvm::APFloat apf = Val.getFloat();
554      if (&apf.getSemantics() == &llvm::APFloat::IEEEsingle) {
555        C.out() << apf.convertToFloat() << "f";
556      } else {
557        C.out() << apf.convertToDouble();
558      }
559      break;
560    }
561
562    case clang::APValue::ComplexInt:
563    case clang::APValue::ComplexFloat:
564    case clang::APValue::LValue:
565    case clang::APValue::Vector: {
566      assert(false && "Primitive type cannot have such kind of initializer");
567      break;
568    }
569    default: {
570      assert(false && "Unknown kind of initializer");
571    }
572  }
573  C.out() << ";" << std::endl;
574
575  return;
576}
577
578void RSReflection::genInitExportVariable(Context &C,
579                                         const RSExportType *ET,
580                                         const std::string &VarName,
581                                         const clang::APValue &Val) {
582  assert(!Val.isUninit() && "Not a valid initializer");
583
584  switch (ET->getClass()) {
585    case RSExportType::ExportClassPrimitive:
586    case RSExportType::ExportClassConstantArray: {
587      const RSExportPrimitiveType *EPT =
588          static_cast<const RSExportPrimitiveType*>(ET);
589      if (EPT->getType() == RSExportPrimitiveType::DataTypeBoolean) {
590        genInitBoolExportVariable(C, VarName, Val);
591      } else {
592        genInitPrimitiveExportVariable(C, VarName, Val);
593      }
594      break;
595    }
596
597    case RSExportType::ExportClassPointer: {
598      if (!Val.isInt() || Val.getInt().getSExtValue() != 0)
599        std::cout << "Initializer which is non-NULL to pointer type variable "
600                     "will be ignored" << std::endl;
601      break;
602    }
603
604    case RSExportType::ExportClassVector: {
605      const RSExportVectorType *EVT =
606          static_cast<const RSExportVectorType*>(ET);
607      switch (Val.getKind()) {
608        case clang::APValue::Int:
609        case clang::APValue::Float: {
610          for (int i = 0; i < EVT->getNumElement(); i++) {
611            std::string Name =  VarName + "." + GetVectorAccessor(i);
612            genInitPrimitiveExportVariable(C, Name, Val);
613          }
614          break;
615        }
616
617        case clang::APValue::Vector: {
618          C.indent() << RS_EXPORT_VAR_PREFIX << VarName << " = new "
619                     << GetVectorTypeName(EVT) << "();" << std::endl;
620
621          unsigned NumElements =
622              std::min(static_cast<unsigned>(EVT->getNumElement()),
623                       Val.getVectorLength());
624          for (unsigned i = 0; i < NumElements; i++) {
625            const clang::APValue &ElementVal = Val.getVectorElt(i);
626            std::string Name = VarName + "." + GetVectorAccessor(i);
627            genInitPrimitiveExportVariable(C, Name, ElementVal);
628          }
629          break;
630        }
631
632        case clang::APValue::Uninitialized:
633        case clang::APValue::ComplexInt:
634        case clang::APValue::ComplexFloat:
635        case clang::APValue::LValue: {
636          assert(false && "Unexpected type of value of initializer.");
637        }
638      }
639      break;
640    }
641
642    // TODO(zonr): Resolving initializer of a record (and matrix) type variable
643    // is complex. It cannot obtain by just simply evaluating the initializer
644    // expression.
645    case RSExportType::ExportClassMatrix:
646    case RSExportType::ExportClassRecord: {
647#if 0
648      unsigned InitIndex = 0;
649      const RSExportRecordType *ERT =
650          static_cast<const RSExportRecordType*>(ET);
651
652      assert((Val.getKind() == clang::APValue::Vector) && "Unexpected type of "
653             "initializer for record type variable");
654
655      C.indent() << RS_EXPORT_VAR_PREFIX << VarName
656                 << " = new "RS_TYPE_CLASS_NAME_PREFIX << ERT->getName()
657                 <<  "."RS_TYPE_ITEM_CLASS_NAME"();" << std::endl;
658
659      for (RSExportRecordType::const_field_iterator I = ERT->fields_begin(),
660               E = ERT->fields_end();
661           I != E;
662           I++) {
663        const RSExportRecordType::Field *F = *I;
664        std::string FieldName = VarName + "." + F->getName();
665
666        if (InitIndex > Val.getVectorLength())
667          break;
668
669        genInitPrimitiveExportVariable(C,
670                                       FieldName,
671                                       Val.getVectorElt(InitIndex++));
672      }
673#endif
674      assert(false && "Unsupported initializer for record type variable "
675                      "currently");
676      break;
677    }
678
679    default: {
680      assert(false && "Unknown class of type");
681    }
682  }
683  return;
684}
685
686void RSReflection::genExportVariable(Context &C, const RSExportVar *EV) {
687  const RSExportType *ET = EV->getType();
688
689  C.indent() << "private final static int "RS_EXPORT_VAR_INDEX_PREFIX
690             << EV->getName() << " = " << C.getNextExportVarSlot() << ";"
691             << std::endl;
692
693  switch (ET->getClass()) {
694    case RSExportType::ExportClassPrimitive:
695    case RSExportType::ExportClassConstantArray: {
696      genPrimitiveTypeExportVariable(C, EV);
697      break;
698    }
699    case RSExportType::ExportClassPointer: {
700      genPointerTypeExportVariable(C, EV);
701      break;
702    }
703    case RSExportType::ExportClassVector: {
704      genVectorTypeExportVariable(C, EV);
705      break;
706    }
707    case RSExportType::ExportClassMatrix: {
708      genMatrixTypeExportVariable(C, EV);
709      break;
710    }
711    case RSExportType::ExportClassRecord: {
712      genRecordTypeExportVariable(C, EV);
713      break;
714    }
715    default: {
716      assert(false && "Unknown class of type");
717    }
718  }
719
720  return;
721}
722
723void RSReflection::genExportFunction(Context &C, const RSExportFunc *EF) {
724  C.indent() << "private final static int "RS_EXPORT_FUNC_INDEX_PREFIX
725             << EF->getName() << " = " << C.getNextExportFuncSlot() << ";"
726             << std::endl;
727
728  // invoke_*()
729  Context::ArgTy Args;
730
731  for (RSExportFunc::const_param_iterator I = EF->params_begin(),
732           E = EF->params_end();
733       I != E;
734       I++) {
735    const RSExportFunc::Parameter *P = *I;
736    Args.push_back(make_pair(GetTypeName(P->getType()), P->getName()));
737  }
738
739  C.startFunction(Context::AM_Public,
740                  false,
741                  "void",
742                  "invoke_" + EF->getName(),
743                  Args);
744
745  if (!EF->hasParam()) {
746    C.indent() << "invoke("RS_EXPORT_FUNC_INDEX_PREFIX << EF->getName() << ");"
747               << std::endl;
748  } else {
749    const RSExportRecordType *ERT = EF->getParamPacketType();
750    std::string FieldPackerName = EF->getName() + "_fp";
751
752    if (genCreateFieldPacker(C, ERT, FieldPackerName.c_str()))
753      genPackVarOfType(C, ERT, NULL, FieldPackerName.c_str());
754
755    C.indent() << "invoke("RS_EXPORT_FUNC_INDEX_PREFIX << EF->getName() << ", "
756               << FieldPackerName << ");" << std::endl;
757  }
758
759  C.endFunction();
760  return;
761}
762
763void RSReflection::genPrimitiveTypeExportVariable(Context &C,
764                                                  const RSExportVar *EV) {
765  assert((EV->getType()->getClass() == RSExportType::ExportClassPrimitive ||
766          EV->getType()->getClass() == RSExportType::ExportClassConstantArray)
767         && "Variable should be type of primitive here");
768
769  const RSExportPrimitiveType *EPT =
770      static_cast<const RSExportPrimitiveType*>(EV->getType());
771  const char *TypeName = GetPrimitiveTypeName(EPT);
772
773  C.indent() << "private " << TypeName << " "RS_EXPORT_VAR_PREFIX
774             << EV->getName() << ";" << std::endl;
775
776  // set_*()
777  if (!EV->isConst()) {
778    C.startFunction(Context::AM_Public,
779                    false,
780                    "void",
781                    "set_" + EV->getName(),
782                    1,
783                    TypeName,
784                    "v");
785    C.indent() << RS_EXPORT_VAR_PREFIX << EV->getName() << " = v;" << std::endl;
786
787    if (EPT->isRSObjectType())
788      C.indent() << "setVar("RS_EXPORT_VAR_INDEX_PREFIX << EV->getName()
789                 << ", (v == null) ? 0 : v.getID());" << std::endl;
790    else
791      C.indent() << "setVar("RS_EXPORT_VAR_INDEX_PREFIX << EV->getName()
792                 << ", v);" << std::endl;
793
794    C.endFunction();
795  }
796
797  genGetExportVariable(C, TypeName, EV->getName());
798
799  return;
800}
801
802void RSReflection::genPointerTypeExportVariable(Context &C,
803                                                const RSExportVar *EV) {
804  const RSExportType *ET = EV->getType();
805  const RSExportType *PointeeType;
806  std::string TypeName;
807
808  assert((ET->getClass() == RSExportType::ExportClassPointer) &&
809         "Variable should be type of pointer here");
810
811  PointeeType = static_cast<const RSExportPointerType*>(ET)->getPointeeType();
812  TypeName = GetTypeName(ET);
813
814  // bind_*()
815  C.indent() << "private " << TypeName << " "RS_EXPORT_VAR_PREFIX
816             << EV->getName() << ";" << std::endl;
817
818  C.startFunction(Context::AM_Public,
819                  false,
820                  "void",
821                  "bind_" + EV->getName(),
822                  1,
823                  TypeName.c_str(),
824                  "v");
825
826  C.indent() << RS_EXPORT_VAR_PREFIX << EV->getName() << " = v;" << std::endl;
827  C.indent() << "if (v == null) bindAllocation(null, "RS_EXPORT_VAR_INDEX_PREFIX
828             << EV->getName() << ");" << std::endl;
829
830  if (PointeeType->getClass() == RSExportType::ExportClassRecord)
831    C.indent() << "else bindAllocation(v.getAllocation(), "
832        RS_EXPORT_VAR_INDEX_PREFIX << EV->getName() << ");"
833               << std::endl;
834  else
835    C.indent() << "else bindAllocation(v, "RS_EXPORT_VAR_INDEX_PREFIX
836               << EV->getName() << ");" << std::endl;
837
838  C.endFunction();
839
840  genGetExportVariable(C, TypeName, EV->getName());
841
842  return;
843}
844
845void RSReflection::genVectorTypeExportVariable(Context &C,
846                                               const RSExportVar *EV) {
847  assert((EV->getType()->getClass() == RSExportType::ExportClassVector) &&
848         "Variable should be type of vector here");
849
850  const RSExportVectorType *EVT =
851      static_cast<const RSExportVectorType*>(EV->getType());
852  const char *TypeName = GetVectorTypeName(EVT);
853  const char *FieldPackerName = "fp";
854
855  C.indent() << "private " << TypeName << " "RS_EXPORT_VAR_PREFIX
856             << EV->getName() << ";" << std::endl;
857
858  // set_*()
859  if (!EV->isConst()) {
860    C.startFunction(Context::AM_Public,
861                    false,
862                    "void",
863                    "set_" + EV->getName(),
864                    1,
865                    TypeName,
866                    "v");
867    C.indent() << RS_EXPORT_VAR_PREFIX << EV->getName() << " = v;" << std::endl;
868
869    if (genCreateFieldPacker(C, EVT, FieldPackerName))
870      genPackVarOfType(C, EVT, "v", FieldPackerName);
871    C.indent() << "setVar("RS_EXPORT_VAR_INDEX_PREFIX << EV->getName() << ", "
872               << FieldPackerName << ");" << std::endl;
873
874    C.endFunction();
875  }
876
877  genGetExportVariable(C, TypeName, EV->getName());
878  return;
879}
880
881void RSReflection::genMatrixTypeExportVariable(Context &C,
882                                               const RSExportVar *EV) {
883  assert((EV->getType()->getClass() == RSExportType::ExportClassMatrix) &&
884         "Variable should be type of matrix here");
885
886  const RSExportMatrixType *EMT =
887      static_cast<const RSExportMatrixType*>(EV->getType());
888  const char *TypeName = GetMatrixTypeName(EMT);
889  const char *FieldPackerName = "fp";
890
891  C.indent() << "private " << TypeName << " "RS_EXPORT_VAR_PREFIX
892             << EV->getName() << ";" << std::endl;
893
894  // set_*()
895  if (!EV->isConst()) {
896    C.startFunction(Context::AM_Public,
897                    false,
898                    "void",
899                    "set_" + EV->getName(),
900                    1,
901                    TypeName, "v");
902    C.indent() << RS_EXPORT_VAR_PREFIX << EV->getName() << " = v;" << std::endl;
903
904    if (genCreateFieldPacker(C, EMT, FieldPackerName))
905      genPackVarOfType(C, EMT, "v", FieldPackerName);
906    C.indent() << "setVar("RS_EXPORT_VAR_INDEX_PREFIX << EV->getName() << ", "
907               << FieldPackerName << ");" << std::endl;
908
909    C.endFunction();
910  }
911
912  genGetExportVariable(C, TypeName, EV->getName());
913  return;
914}
915
916void RSReflection::genRecordTypeExportVariable(Context &C,
917                                               const RSExportVar *EV) {
918  assert((EV->getType()->getClass() == RSExportType::ExportClassRecord) &&
919         "Variable should be type of struct here");
920
921  const RSExportRecordType *ERT =
922      static_cast<const RSExportRecordType*>(EV->getType());
923  std::string TypeName =
924      RS_TYPE_CLASS_NAME_PREFIX + ERT->getName() + "."RS_TYPE_ITEM_CLASS_NAME;
925  const char *FieldPackerName = "fp";
926
927  C.indent() << "private " << TypeName << " "RS_EXPORT_VAR_PREFIX
928             << EV->getName() << ";" << std::endl;
929
930  // set_*()
931  if (!EV->isConst()) {
932    C.startFunction(Context::AM_Public,
933                    false,
934                    "void",
935                    "set_" + EV->getName(),
936                    1,
937                    TypeName.c_str(),
938                    "v");
939    C.indent() << RS_EXPORT_VAR_PREFIX << EV->getName() << " = v;" << std::endl;
940
941    if (genCreateFieldPacker(C, ERT, FieldPackerName))
942      genPackVarOfType(C, ERT, "v", FieldPackerName);
943    C.indent() << "setVar("RS_EXPORT_VAR_INDEX_PREFIX << EV->getName()
944               << ", " << FieldPackerName << ");" << std::endl;
945
946    C.endFunction();
947  }
948
949  genGetExportVariable(C, TypeName.c_str(), EV->getName());
950  return;
951}
952
953void RSReflection::genGetExportVariable(Context &C,
954                                        const std::string &TypeName,
955                                        const std::string &VarName) {
956  C.startFunction(Context::AM_Public,
957                  false,
958                  TypeName.c_str(),
959                  "get_" + VarName,
960                  0);
961
962  C.indent() << "return "RS_EXPORT_VAR_PREFIX << VarName << ";" << std::endl;
963
964  C.endFunction();
965  return;
966}
967
968/******************* Methods to generate script class /end *******************/
969
970bool RSReflection::genCreateFieldPacker(Context &C,
971                                        const RSExportType *ET,
972                                        const char *FieldPackerName) {
973  size_t AllocSize = RSExportType::GetTypeAllocSize(ET);
974  if (AllocSize > 0)
975    C.indent() << "FieldPacker " << FieldPackerName << " = new FieldPacker("
976               << AllocSize << ");" << std::endl;
977  else
978    return false;
979  return true;
980}
981
982void RSReflection::genPackVarOfType(Context &C,
983                                    const RSExportType *ET,
984                                    const char *VarName,
985                                    const char *FieldPackerName) {
986  switch (ET->getClass()) {
987    case RSExportType::ExportClassPrimitive:
988    case RSExportType::ExportClassVector: {
989      C.indent() << FieldPackerName << "."
990                 << GetPackerAPIName(
991                     static_cast<const RSExportPrimitiveType*>(ET))
992                 << "(" << VarName << ");" << std::endl;
993      break;
994    }
995    case RSExportType::ExportClassConstantArray: {
996      if (ET->getName().compare("addObj") == 0) {
997        C.indent() << FieldPackerName << "." << "addObj" << "("
998                   << VarName << ");" << std::endl;
999      } else {
1000        C.indent() << FieldPackerName << "."
1001                   << GetPackerAPIName(
1002                       static_cast<const RSExportPrimitiveType*>(ET))
1003                   << "(" << VarName << ");" << std::endl;
1004      }
1005      break;
1006    }
1007    case RSExportType::ExportClassPointer: {
1008      // Must reflect as type Allocation in Java
1009      const RSExportType *PointeeType =
1010          static_cast<const RSExportPointerType*>(ET)->getPointeeType();
1011
1012      if (PointeeType->getClass() != RSExportType::ExportClassRecord)
1013        C.indent() << FieldPackerName << ".addI32(" << VarName
1014                   << ".getPtr());" << std::endl;
1015      else
1016        C.indent() << FieldPackerName << ".addI32(" << VarName
1017                   << ".getAllocation().getPtr());" << std::endl;
1018      break;
1019    }
1020    case RSExportType::ExportClassMatrix: {
1021      C.indent() << FieldPackerName << ".addObj(" << VarName << ");"
1022                 << std::endl;
1023      break;
1024    }
1025    case RSExportType::ExportClassRecord: {
1026      const RSExportRecordType *ERT =
1027          static_cast<const RSExportRecordType*>(ET);
1028      // Relative pos from now on in field packer
1029      unsigned Pos = 0;
1030
1031      for (RSExportRecordType::const_field_iterator I = ERT->fields_begin(),
1032               E = ERT->fields_end();
1033           I != E;
1034           I++) {
1035        const RSExportRecordType::Field *F = *I;
1036        std::string FieldName;
1037        size_t FieldOffset = F->getOffsetInParent();
1038        size_t FieldStoreSize = RSExportType::GetTypeStoreSize(F->getType());
1039        size_t FieldAllocSize = RSExportType::GetTypeAllocSize(F->getType());
1040
1041        if (VarName != NULL)
1042          FieldName = VarName + ("." + F->getName());
1043        else
1044          FieldName = F->getName();
1045
1046        if (FieldOffset > Pos)
1047          C.indent() << FieldPackerName << ".skip("
1048                     << (FieldOffset - Pos) << ");" << std::endl;
1049
1050        genPackVarOfType(C, F->getType(), FieldName.c_str(), FieldPackerName);
1051
1052        // There is padding in the field type
1053        if (FieldAllocSize > FieldStoreSize)
1054            C.indent() << FieldPackerName << ".skip("
1055                       << (FieldAllocSize - FieldStoreSize)
1056                       << ");" << std::endl;
1057
1058          Pos = FieldOffset + FieldAllocSize;
1059      }
1060
1061      // There maybe some padding after the struct
1062      size_t Padding = RSExportType::GetTypeAllocSize(ERT) - Pos;
1063      if (Padding > 0)
1064        C.indent() << FieldPackerName << ".skip(" << Padding << ");"
1065                   << std::endl;
1066      break;
1067    }
1068    default: {
1069      assert(false && "Unknown class of type");
1070    }
1071  }
1072
1073  return;
1074}
1075
1076void RSReflection::genNewItemBufferIfNull(Context &C, const char *Index) {
1077  C.indent() << "if ("RS_TYPE_ITEM_BUFFER_NAME" == null) "
1078                  RS_TYPE_ITEM_BUFFER_NAME" = "
1079                    "new "RS_TYPE_ITEM_CLASS_NAME"[mType.getX() /* count */];"
1080             << std::endl;
1081  if (Index != NULL)
1082    C.indent() << "if ("RS_TYPE_ITEM_BUFFER_NAME"[" << Index << "] == null) "
1083                    RS_TYPE_ITEM_BUFFER_NAME"[" << Index << "] = "
1084                      "new "RS_TYPE_ITEM_CLASS_NAME"();" << std::endl;
1085  return;
1086}
1087
1088void RSReflection::genNewItemBufferPackerIfNull(Context &C) {
1089  C.indent() << "if ("RS_TYPE_ITEM_BUFFER_PACKER_NAME" == null) "
1090                  RS_TYPE_ITEM_BUFFER_PACKER_NAME" = "
1091                    "new FieldPacker("
1092                      RS_TYPE_ITEM_CLASS_NAME".sizeof * mType.getX()/* count */"
1093                    ");" << std::endl;
1094  return;
1095}
1096
1097/********************** Methods to generate type class  **********************/
1098bool RSReflection::genTypeClass(Context &C,
1099                                const RSExportRecordType *ERT,
1100                                std::string &ErrorMsg) {
1101  std::string ClassName = RS_TYPE_CLASS_NAME_PREFIX + ERT->getName();
1102
1103  // Open the file
1104  if (!openScriptFile(C, ClassName, ErrorMsg)) {
1105    return false;
1106  }
1107
1108  if (!C.startClass(Context::AM_Public,
1109                    false,
1110                    ClassName,
1111                    RS_TYPE_CLASS_SUPER_CLASS_NAME,
1112                    ErrorMsg))
1113    return false;
1114
1115  if (!genTypeItemClass(C, ERT, ErrorMsg))
1116    return false;
1117
1118  // Declare item buffer and item buffer packer
1119  C.indent() << "private "RS_TYPE_ITEM_CLASS_NAME" "RS_TYPE_ITEM_BUFFER_NAME"[]"
1120      ";" << std::endl;
1121  C.indent() << "private FieldPacker "RS_TYPE_ITEM_BUFFER_PACKER_NAME";"
1122             << std::endl;
1123
1124  genTypeClassConstructor(C, ERT);
1125  genTypeClassCopyToArray(C, ERT);
1126  genTypeClassItemSetter(C, ERT);
1127  genTypeClassItemGetter(C, ERT);
1128  genTypeClassComponentSetter(C, ERT);
1129  genTypeClassComponentGetter(C, ERT);
1130  genTypeClassCopyAll(C, ERT);
1131
1132  C.endClass();
1133
1134  C.resetFieldIndex();
1135  C.clearFieldIndexMap();
1136
1137  return true;
1138}
1139
1140bool RSReflection::genTypeItemClass(Context &C,
1141                                    const RSExportRecordType *ERT,
1142                                    std::string &ErrorMsg) {
1143  C.indent() << "static public class "RS_TYPE_ITEM_CLASS_NAME;
1144  C.startBlock();
1145
1146  C.indent() << "public static final int sizeof = "
1147             << RSExportType::GetTypeAllocSize(ERT) << ";" << std::endl;
1148
1149  // Member elements
1150  C.out() << std::endl;
1151  for (RSExportRecordType::const_field_iterator FI = ERT->fields_begin(),
1152           FE = ERT->fields_end();
1153       FI != FE;
1154       FI++) {
1155    C.indent() << GetTypeName((*FI)->getType()) << " " << (*FI)->getName()
1156               << ";" << std::endl;
1157  }
1158
1159  // Constructor
1160  C.out() << std::endl;
1161  C.indent() << RS_TYPE_ITEM_CLASS_NAME"()";
1162  C.startBlock();
1163
1164  for (RSExportRecordType::const_field_iterator FI = ERT->fields_begin(),
1165           FE = ERT->fields_end();
1166       FI != FE;
1167       FI++) {
1168    const RSExportRecordType::Field *F = *FI;
1169    if ((F->getType()->getClass() == RSExportType::ExportClassVector) ||
1170        (F->getType()->getClass() == RSExportType::ExportClassMatrix) ||
1171        (F->getType()->getClass() == RSExportType::ExportClassRecord) ||
1172        (F->getType()->getClass() == RSExportType::ExportClassConstantArray)) {
1173      C.indent() << F->getName() << " = new " << GetTypeName(F->getType())
1174                 << "();" << std::endl;
1175    }
1176  }
1177
1178  // end Constructor
1179  C.endBlock();
1180
1181  // end Item class
1182  C.endBlock();
1183
1184  return true;
1185}
1186
1187void RSReflection::genTypeClassConstructor(Context &C,
1188                                           const RSExportRecordType *ERT) {
1189  const char *RenderScriptVar = "rs";
1190
1191  C.startFunction(Context::AM_Public,
1192                  true,
1193                  "Element",
1194                  "createElement",
1195                  1,
1196                  "RenderScript",
1197                  RenderScriptVar);
1198  genBuildElement(C, ERT, RenderScriptVar);
1199  C.endFunction();
1200
1201  C.startFunction(Context::AM_Public,
1202                  false,
1203                  NULL,
1204                  C.getClassName(),
1205                  2,
1206                  "RenderScript",
1207                  RenderScriptVar,
1208                  "int",
1209                  "count");
1210
1211  C.indent() << RS_TYPE_ITEM_BUFFER_NAME" = null;" << std::endl;
1212  C.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME" = null;" << std::endl;
1213  C.indent() << "mElement = createElement(" << RenderScriptVar << ");"
1214             << std::endl;
1215  // Call init() in super class
1216  C.indent() << "init(" << RenderScriptVar << ", count);" << std::endl;
1217  C.endFunction();
1218
1219  return;
1220}
1221
1222void RSReflection::genTypeClassCopyToArray(Context &C,
1223                                           const RSExportRecordType *ERT) {
1224  C.startFunction(Context::AM_Private,
1225                  false,
1226                  "void",
1227                  "copyToArray",
1228                  2,
1229                  RS_TYPE_ITEM_CLASS_NAME,
1230                  "i",
1231                  "int",
1232                  "index");
1233
1234  genNewItemBufferPackerIfNull(C);
1235  C.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME
1236                ".reset(index * "RS_TYPE_ITEM_CLASS_NAME".sizeof);"
1237             << std::endl;
1238
1239  genPackVarOfType(C, ERT, "i", RS_TYPE_ITEM_BUFFER_PACKER_NAME);
1240
1241  C.endFunction();
1242  return;
1243}
1244
1245void RSReflection::genTypeClassItemSetter(Context &C,
1246                                          const RSExportRecordType *ERT) {
1247  C.startFunction(Context::AM_Public,
1248                  false,
1249                  "void",
1250                  "set",
1251                  3,
1252                  RS_TYPE_ITEM_CLASS_NAME,
1253                  "i",
1254                  "int",
1255                  "index",
1256                  "boolean",
1257                  "copyNow");
1258  genNewItemBufferIfNull(C, NULL);
1259  C.indent() << RS_TYPE_ITEM_BUFFER_NAME"[index] = i;" << std::endl;
1260
1261  C.indent() << "if (copyNow) ";
1262  C.startBlock();
1263
1264  C.indent() << "copyToArray(i, index);" << std::endl;
1265  C.indent() << "mAllocation.subData1D(index, 1, "
1266                  RS_TYPE_ITEM_BUFFER_PACKER_NAME".getData());" << std::endl;
1267
1268  // End of if (copyNow)
1269  C.endBlock();
1270
1271  C.endFunction();
1272  return;
1273}
1274
1275void RSReflection::genTypeClassItemGetter(Context &C,
1276                                          const RSExportRecordType *ERT) {
1277  C.startFunction(Context::AM_Public,
1278                  false,
1279                  RS_TYPE_ITEM_CLASS_NAME,
1280                  "get",
1281                  1,
1282                  "int",
1283                  "index");
1284  C.indent() << "if ("RS_TYPE_ITEM_BUFFER_NAME" == null) return null;"
1285             << std::endl;
1286  C.indent() << "return "RS_TYPE_ITEM_BUFFER_NAME"[index];" << std::endl;
1287  C.endFunction();
1288  return;
1289}
1290
1291void RSReflection::genTypeClassComponentSetter(Context &C,
1292                                               const RSExportRecordType *ERT) {
1293  for (RSExportRecordType::const_field_iterator FI = ERT->fields_begin(),
1294           FE = ERT->fields_end();
1295       FI != FE;
1296       FI++) {
1297    const RSExportRecordType::Field *F = *FI;
1298    size_t FieldOffset = F->getOffsetInParent();
1299    size_t FieldStoreSize = RSExportType::GetTypeStoreSize(F->getType());
1300    unsigned FieldIndex = C.getFieldIndex(F);
1301
1302    C.startFunction(Context::AM_Public,
1303                    false,
1304                    "void",
1305                    "set_" + F->getName(), 3,
1306                    "int",
1307                    "index",
1308                    GetTypeName(F->getType()).c_str(),
1309                    "v",
1310                    "boolean",
1311                    "copyNow");
1312    genNewItemBufferPackerIfNull(C);
1313    genNewItemBufferIfNull(C, "index");
1314    C.indent() << RS_TYPE_ITEM_BUFFER_NAME"[index]." << F->getName()
1315               << " = v;" << std::endl;
1316
1317    C.indent() << "if (copyNow) ";
1318    C.startBlock();
1319
1320    if (FieldOffset > 0)
1321      C.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME
1322                    ".reset(index * "RS_TYPE_ITEM_CLASS_NAME".sizeof + "
1323                 << FieldOffset << ");" << std::endl;
1324    else
1325      C.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME
1326                    ".reset(index * "RS_TYPE_ITEM_CLASS_NAME".sizeof);"
1327                 << std::endl;
1328    genPackVarOfType(C, F->getType(), "v", RS_TYPE_ITEM_BUFFER_PACKER_NAME);
1329
1330    C.indent() << "FieldPacker fp = new FieldPacker(" << FieldStoreSize << ");"
1331               << std::endl;
1332    genPackVarOfType(C, F->getType(), "v", "fp");
1333    C.indent() << "mAllocation.subElementData(index, " << FieldIndex << ", fp);"
1334               << std::endl;
1335
1336    // End of if (copyNow)
1337    C.endBlock();
1338
1339    C.endFunction();
1340  }
1341  return;
1342}
1343
1344void RSReflection::genTypeClassComponentGetter(Context &C,
1345                                               const RSExportRecordType *ERT) {
1346  for (RSExportRecordType::const_field_iterator FI = ERT->fields_begin(),
1347           FE = ERT->fields_end();
1348       FI != FE;
1349       FI++) {
1350    const RSExportRecordType::Field *F = *FI;
1351    C.startFunction(Context::AM_Public,
1352                    false,
1353                    GetTypeName(F->getType()).c_str(),
1354                    "get_" + F->getName(),
1355                    1,
1356                    "int",
1357                    "index");
1358    C.indent() << "return "RS_TYPE_ITEM_BUFFER_NAME"[index]." << F->getName()
1359               << ";" << std::endl;
1360    C.endFunction();
1361  }
1362  return;
1363}
1364
1365void RSReflection::genTypeClassCopyAll(Context &C,
1366                                       const RSExportRecordType *ERT) {
1367  C.startFunction(Context::AM_Public, false, "void", "copyAll", 0);
1368
1369  C.indent() << "for (int ct=0; ct < "RS_TYPE_ITEM_BUFFER_NAME".length; ct++) "
1370      "copyToArray("RS_TYPE_ITEM_BUFFER_NAME"[ct], ct);"
1371             << std::endl;
1372  C.indent() << "mAllocation.data("RS_TYPE_ITEM_BUFFER_PACKER_NAME".getData());"
1373             << std::endl;
1374
1375  C.endFunction();
1376  return;
1377}
1378
1379/******************** Methods to generate type class /end ********************/
1380
1381/********** Methods to create Element in Java of given record type ***********/
1382void RSReflection::genBuildElement(Context &C, const RSExportRecordType *ERT,
1383                                   const char *RenderScriptVar) {
1384  const char *ElementBuilderName = "eb";
1385
1386  // Create element builder
1387  //    C.startBlock(true);
1388
1389  C.indent() << "Element.Builder " << ElementBuilderName << " = "
1390      "new Element.Builder(" << RenderScriptVar << ");" << std::endl;
1391
1392  // eb.add(...)
1393  genAddElementToElementBuilder(C,
1394                                ERT,
1395                                "",
1396                                ElementBuilderName,
1397                                RenderScriptVar);
1398
1399  C.indent() << "return " << ElementBuilderName << ".create();" << std::endl;
1400
1401  //   C.endBlock();
1402  return;
1403}
1404
1405#define EB_ADD(x)                                                   \
1406  C.indent() << ElementBuilderName                                  \
1407             << ".add(Element." << x << ", \"" << VarName << "\");" \
1408             << std::endl;                                          \
1409  C.incFieldIndex()
1410
1411void RSReflection::genAddElementToElementBuilder(Context &C,
1412                                                 const RSExportType *ET,
1413                                                 const std::string &VarName,
1414                                                 const char *ElementBuilderName,
1415                                                 const char *RenderScriptVar) {
1416  const char *ElementConstruct = GetBuiltinElementConstruct(ET);
1417
1418  if (ElementConstruct != NULL) {
1419    EB_ADD(ElementConstruct << "(" << RenderScriptVar << ")");
1420  } else {
1421    if ((ET->getClass() == RSExportType::ExportClassPrimitive) ||
1422        (ET->getClass() == RSExportType::ExportClassVector)    ||
1423        (ET->getClass() == RSExportType::ExportClassConstantArray)) {
1424      const RSExportPrimitiveType *EPT =
1425          static_cast<const RSExportPrimitiveType*>(ET);
1426      const char *DataKindName = GetElementDataKindName(EPT->getKind());
1427      const char *DataTypeName = GetElementDataTypeName(EPT->getType());
1428      int Size = (ET->getClass() == RSExportType::ExportClassVector) ?
1429          static_cast<const RSExportVectorType*>(ET)->getNumElement() :
1430          1;
1431
1432      switch (EPT->getKind()) {
1433        case RSExportPrimitiveType::DataKindPixelL:
1434        case RSExportPrimitiveType::DataKindPixelA:
1435        case RSExportPrimitiveType::DataKindPixelLA:
1436        case RSExportPrimitiveType::DataKindPixelRGB:
1437        case RSExportPrimitiveType::DataKindPixelRGBA: {
1438          // Element.createPixel()
1439          EB_ADD("createPixel(" << RenderScriptVar << ", "
1440                                << DataTypeName << ", "
1441                                << DataKindName << ")");
1442          break;
1443        }
1444        case RSExportPrimitiveType::DataKindUser:
1445        default: {
1446          if (EPT->getClass() == RSExportType::ExportClassPrimitive ||
1447              EPT->getClass() == RSExportType::ExportClassConstantArray) {
1448            // Element.createUser()
1449            EB_ADD("createUser(" << RenderScriptVar << ", "
1450                                 << DataTypeName << ")");
1451          } else {
1452            assert((ET->getClass() == RSExportType::ExportClassVector) &&
1453                   "Unexpected type.");
1454            EB_ADD("createVector(" << RenderScriptVar << ", "
1455                                   << DataTypeName << ", "
1456                                   << Size << ")");
1457          }
1458          break;
1459        }
1460      }
1461#ifndef NDEBUG
1462    } else if (ET->getClass() == RSExportType::ExportClassPointer) {
1463      // Pointer type variable should be resolved in
1464      // GetBuiltinElementConstruct()
1465      assert(false && "??");
1466    } else if (ET->getClass() == RSExportType::ExportClassMatrix) {
1467      // Matrix type variable should be resolved
1468      // in GetBuiltinElementConstruct()
1469      assert(false && "??");
1470#endif
1471    } else if (ET->getClass() == RSExportType::ExportClassRecord) {
1472      // Simalar to case of RSExportType::ExportClassRecord in genPackVarOfType.
1473      //
1474      // TODO(zonr): Generalize these two function such that there's no
1475      //             duplicated codes.
1476      const RSExportRecordType *ERT =
1477          static_cast<const RSExportRecordType*>(ET);
1478      int Pos = 0;    // relative pos from now on
1479
1480      for (RSExportRecordType::const_field_iterator I = ERT->fields_begin(),
1481               E = ERT->fields_end();
1482           I != E;
1483           I++) {
1484        const RSExportRecordType::Field *F = *I;
1485        std::string FieldName;
1486        int FieldOffset = F->getOffsetInParent();
1487        int FieldStoreSize = RSExportType::GetTypeStoreSize(F->getType());
1488        int FieldAllocSize = RSExportType::GetTypeAllocSize(F->getType());
1489
1490        if (!VarName.empty())
1491          FieldName = VarName + "." + F->getName();
1492        else
1493          FieldName = F->getName();
1494
1495        // Alignment
1496        genAddPaddingToElementBuiler(C,
1497                                     (FieldOffset - Pos),
1498                                     ElementBuilderName,
1499                                     RenderScriptVar);
1500
1501        // eb.add(...)
1502        C.addFieldIndexMapping(F);
1503        genAddElementToElementBuilder(C,
1504                                      F->getType(),
1505                                      FieldName,
1506                                      ElementBuilderName,
1507                                      RenderScriptVar);
1508
1509        // There is padding within the field type
1510        genAddPaddingToElementBuiler(C,
1511                                     (FieldAllocSize - FieldStoreSize),
1512                                     ElementBuilderName,
1513                                     RenderScriptVar);
1514
1515        Pos = FieldOffset + FieldAllocSize;
1516      }
1517
1518      // There maybe some padding after the struct
1519      //unsigned char align = RSExportType::GetTypeAlignment(ERT);
1520      //size_t siz = RSExportType::GetTypeAllocSize(ERT);
1521      size_t siz1 = RSExportType::GetTypeStoreSize(ERT);
1522
1523      genAddPaddingToElementBuiler(C,
1524                                   siz1 - Pos,
1525                                   ElementBuilderName,
1526                                   RenderScriptVar);
1527    } else {
1528      assert(false && "Unknown class of type");
1529    }
1530  }
1531}
1532
1533void RSReflection::genAddPaddingToElementBuiler(Context &C,
1534                                                int PaddingSize,
1535                                                const char *ElementBuilderName,
1536                                                const char *RenderScriptVar) {
1537  while (PaddingSize > 0) {
1538    const std::string &VarName = C.createPaddingField();
1539    if (PaddingSize >= 4) {
1540      EB_ADD("U32(" << RenderScriptVar << ")");
1541      PaddingSize -= 4;
1542    } else if (PaddingSize >= 2) {
1543      EB_ADD("U16(" << RenderScriptVar << ")");
1544      PaddingSize -= 2;
1545    } else if (PaddingSize >= 1) {
1546      EB_ADD("U8(" << RenderScriptVar << ")");
1547      PaddingSize -= 1;
1548    }
1549  }
1550  return;
1551}
1552
1553#undef EB_ADD
1554/******** Methods to create Element in Java of given record type /end ********/
1555
1556bool RSReflection::reflect(const char *OutputPackageName,
1557                           const std::string &InputFileName,
1558                           const std::string &OutputBCFileName) {
1559  Context *C = NULL;
1560  std::string ResourceId = "";
1561
1562  if (!GetClassNameFromFileName(OutputBCFileName, ResourceId))
1563    return false;
1564
1565  if (ResourceId.empty())
1566    ResourceId = "<Resource ID>";
1567
1568  if ((OutputPackageName == NULL) ||
1569      (*OutputPackageName == '\0') ||
1570      strcmp(OutputPackageName, "-") == 0)
1571    C = new Context(InputFileName, "<Package Name>", ResourceId, true);
1572  else
1573    C = new Context(InputFileName, OutputPackageName, ResourceId, false);
1574
1575  if (C != NULL) {
1576    std::string ErrorMsg, ScriptClassName;
1577    // class ScriptC_<ScriptName>
1578    if (!GetClassNameFromFileName(InputFileName, ScriptClassName))
1579      return false;
1580
1581    if (ScriptClassName.empty())
1582      ScriptClassName = "<Input Script Name>";
1583
1584    ScriptClassName.insert(0, RS_SCRIPT_CLASS_NAME_PREFIX);
1585
1586    if (mRSContext->getLicenseNote() != NULL) {
1587      C->setLicenseNote(*(mRSContext->getLicenseNote()));
1588    }
1589
1590    if (!genScriptClass(*C, ScriptClassName, ErrorMsg)) {
1591      std::cerr << "Failed to generate class " << ScriptClassName << " ("
1592                << ErrorMsg << ")" << std::endl;
1593      return false;
1594    }
1595
1596    // class ScriptField_<TypeName>
1597    for (RSContext::const_export_type_iterator TI =
1598             mRSContext->export_types_begin(),
1599             TE = mRSContext->export_types_end();
1600         TI != TE;
1601         TI++) {
1602      const RSExportType *ET = TI->getValue();
1603
1604      if (ET->getClass() == RSExportType::ExportClassRecord) {
1605        const RSExportRecordType *ERT =
1606            static_cast<const RSExportRecordType*>(ET);
1607
1608        if (!ERT->isArtificial() && !genTypeClass(*C, ERT, ErrorMsg)) {
1609          std::cerr << "Failed to generate type class for struct '"
1610                    << ERT->getName() << "' (" << ErrorMsg << ")" << std::endl;
1611          return false;
1612        }
1613      }
1614    }
1615  }
1616
1617  return true;
1618}
1619
1620/************************** RSReflection::Context **************************/
1621const char *const RSReflection::Context::ApacheLicenseNote =
1622    "/*\n"
1623    " * Copyright (C) 2010 The Android Open Source Project\n"
1624    " *\n"
1625    " * Licensed under the Apache License, Version 2.0 (the \"License\");\n"
1626    " * you may not use this file except in compliance with the License.\n"
1627    " * You may obtain a copy of the License at\n"
1628    " *\n"
1629    " *      http://www.apache.org/licenses/LICENSE-2.0\n"
1630    " *\n"
1631    " * Unless required by applicable law or agreed to in writing, software\n"
1632    " * distributed under the License is distributed on an \"AS IS\" BASIS,\n"
1633    " * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or "
1634    "implied.\n"
1635    " * See the License for the specific language governing permissions and\n"
1636    " * limitations under the License.\n"
1637    " */\n"
1638    "\n";
1639
1640const char *const RSReflection::Context::Import[] = {
1641  // RenderScript java class
1642  "android.renderscript.*",
1643  // Import R
1644  "android.content.res.Resources",
1645  // Import for debugging
1646  "android.util.Log",
1647};
1648
1649const char *RSReflection::Context::AccessModifierStr(AccessModifier AM) {
1650  switch (AM) {
1651    case AM_Public: return "public"; break;
1652    case AM_Protected: return "protected"; break;
1653    case AM_Private: return "private"; break;
1654    default: return ""; break;
1655  }
1656}
1657
1658bool RSReflection::Context::startClass(AccessModifier AM,
1659                                       bool IsStatic,
1660                                       const std::string &ClassName,
1661                                       const char *SuperClassName,
1662                                       std::string &ErrorMsg) {
1663  if (mVerbose)
1664    std::cout << "Generating " << ClassName << ".java ..." << std::endl;
1665
1666  // License
1667  out() << mLicenseNote;
1668
1669  // Notice of generated file
1670  out() << "/*" << std::endl;
1671  out() << " * This file is auto-generated. DO NOT MODIFY!" << std::endl;
1672  out() << " * The source RenderScript file: " << mInputRSFile << std::endl;
1673  out() << " */" << std::endl;
1674
1675  // Package
1676  if (!mPackageName.empty())
1677    out() << "package " << mPackageName << ";" << std::endl;
1678  out() << std::endl;
1679
1680  // Imports
1681  for (unsigned i = 0;i < (sizeof(Import) / sizeof(const char*)); i++)
1682    out() << "import " << Import[i] << ";" << std::endl;
1683  out() << std::endl;
1684
1685  // All reflected classes should be annotated as hidden, so that they won't
1686  // be exposed in SDK.
1687  out() << "/**" << std::endl;
1688  out() << " * @hide" << std::endl;
1689  out() << " */" << std::endl;
1690
1691  out() << AccessModifierStr(AM) << ((IsStatic) ? " static" : "") << " class "
1692        << ClassName;
1693  if (SuperClassName != NULL)
1694    out() << " extends " << SuperClassName;
1695
1696  startBlock();
1697
1698  mClassName = ClassName;
1699
1700  return true;
1701}
1702
1703void RSReflection::Context::endClass() {
1704  endBlock();
1705  if (!mUseStdout)
1706    mOF.close();
1707  clear();
1708  return;
1709}
1710
1711void RSReflection::Context::startBlock(bool ShouldIndent) {
1712  if (ShouldIndent)
1713    indent() << "{" << std::endl;
1714  else
1715    out() << " {" << std::endl;
1716  incIndentLevel();
1717  return;
1718}
1719
1720void RSReflection::Context::endBlock() {
1721  decIndentLevel();
1722  indent() << "}" << std::endl << std::endl;
1723  return;
1724}
1725
1726void RSReflection::Context::startTypeClass(const std::string &ClassName) {
1727  indent() << "public static class " << ClassName;
1728  startBlock();
1729  return;
1730}
1731
1732void RSReflection::Context::endTypeClass() {
1733  endBlock();
1734  return;
1735}
1736
1737void RSReflection::Context::startFunction(AccessModifier AM,
1738                                          bool IsStatic,
1739                                          const char *ReturnType,
1740                                          const std::string &FunctionName,
1741                                          int Argc, ...) {
1742  ArgTy Args;
1743  va_list vl;
1744  va_start(vl, Argc);
1745
1746  for (int i = 0; i < Argc; i++) {
1747    const char *ArgType = va_arg(vl, const char*);
1748    const char *ArgName = va_arg(vl, const char*);
1749
1750    Args.push_back(std::make_pair(ArgType, ArgName));
1751  }
1752  va_end(vl);
1753
1754  startFunction(AM, IsStatic, ReturnType, FunctionName, Args);
1755
1756  return;
1757}
1758
1759void RSReflection::Context::startFunction(AccessModifier AM,
1760                                          bool IsStatic,
1761                                          const char *ReturnType,
1762                                          const std::string &FunctionName,
1763                                          const ArgTy &Args) {
1764  indent() << AccessModifierStr(AM) << ((IsStatic) ? " static " : " ")
1765           << ((ReturnType) ? ReturnType : "") << " " << FunctionName << "(";
1766
1767  bool FirstArg = true;
1768  for (ArgTy::const_iterator I = Args.begin(), E = Args.end();
1769       I != E;
1770       I++) {
1771    if (!FirstArg)
1772      out() << ", ";
1773    else
1774      FirstArg = false;
1775
1776    out() << I->first << " " << I->second;
1777  }
1778
1779  out() << ")";
1780  startBlock();
1781
1782  return;
1783}
1784
1785void RSReflection::Context::endFunction() {
1786  endBlock();
1787  return;
1788}
1789