slang_rs_reflection.cpp revision 6e6578a360497f78a181e63d7783422a9c9bfb15
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  slangAssert(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      slangAssert(false && "RSReflection::genElementTypeName : Unsupported "
156                           "vector element data type");
157      break;
158    }
159  }
160
161  slangAssert((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  slangAssert(false && "GetMatrixTypeName : Unsupported matrix dimension");
180  return NULL;
181}
182
183static const char *GetVectorAccessor(unsigned Index) {
184  static const char *VectorAccessorMap[] = {
185    /* 0 */ "x",
186    /* 1 */ "y",
187    /* 2 */ "z",
188    /* 3 */ "w",
189  };
190
191  slangAssert((Index < (sizeof(VectorAccessorMap) / sizeof(const char*))) &&
192              "Out-of-bound index to access vector member");
193
194  return VectorAccessorMap[Index];
195}
196
197static const char *GetPackerAPIName(const RSExportPrimitiveType *EPT) {
198  static const char *PrimitiveTypePackerAPINameMap[] = {
199    "",         // RSExportPrimitiveType::DataTypeFloat16
200    "addF32",   // RSExportPrimitiveType::DataTypeFloat32
201    "addF64",   // RSExportPrimitiveType::DataTypeFloat64
202    "addI8",    // RSExportPrimitiveType::DataTypeSigned8
203    "addI16",   // RSExportPrimitiveType::DataTypeSigned16
204    "addI32",   // RSExportPrimitiveType::DataTypeSigned32
205    "addI64",   // RSExportPrimitiveType::DataTypeSigned64
206    "addU8",    // RSExportPrimitiveType::DataTypeUnsigned8
207    "addU16",   // RSExportPrimitiveType::DataTypeUnsigned16
208    "addU32",   // RSExportPrimitiveType::DataTypeUnsigned32
209    "addU64",   // RSExportPrimitiveType::DataTypeUnsigned64
210    "addBoolean",  // RSExportPrimitiveType::DataTypeBoolean
211
212    "addU16",   // RSExportPrimitiveType::DataTypeUnsigned565
213    "addU16",   // RSExportPrimitiveType::DataTypeUnsigned5551
214    "addU16",   // RSExportPrimitiveType::DataTypeUnsigned4444
215
216    "addMatrix",   // RSExportPrimitiveType::DataTypeRSMatrix2x2
217    "addMatrix",   // RSExportPrimitiveType::DataTypeRSMatrix3x3
218    "addMatrix",   // RSExportPrimitiveType::DataTypeRSMatrix4x4
219
220    "addObj",   // RSExportPrimitiveType::DataTypeRSElement
221    "addObj",   // RSExportPrimitiveType::DataTypeRSType
222    "addObj",   // RSExportPrimitiveType::DataTypeRSAllocation
223    "addObj",   // RSExportPrimitiveType::DataTypeRSSampler
224    "addObj",   // RSExportPrimitiveType::DataTypeRSScript
225    "addObj",   // RSExportPrimitiveType::DataTypeRSMesh
226    "addObj",   // RSExportPrimitiveType::DataTypeRSProgramFragment
227    "addObj",   // RSExportPrimitiveType::DataTypeRSProgramVertex
228    "addObj",   // RSExportPrimitiveType::DataTypeRSProgramRaster
229    "addObj",   // RSExportPrimitiveType::DataTypeRSProgramStore
230    "addObj",   // RSExportPrimitiveType::DataTypeRSFont
231  };
232  unsigned TypeId = EPT->getType();
233
234  if (TypeId < (sizeof(PrimitiveTypePackerAPINameMap) / sizeof(const char*)))
235    return PrimitiveTypePackerAPINameMap[ EPT->getType() ];
236
237  slangAssert(false && "GetPackerAPIName : Unknown primitive data type");
238  return NULL;
239}
240
241static std::string GetTypeName(const RSExportType *ET) {
242  switch (ET->getClass()) {
243    case RSExportType::ExportClassPrimitive: {
244      return GetPrimitiveTypeName(
245                static_cast<const RSExportPrimitiveType*>(ET));
246    }
247    case RSExportType::ExportClassPointer: {
248      const RSExportType *PointeeType =
249          static_cast<const RSExportPointerType*>(ET)->getPointeeType();
250
251      if (PointeeType->getClass() != RSExportType::ExportClassRecord)
252        return "Allocation";
253      else
254        return RS_TYPE_CLASS_NAME_PREFIX + PointeeType->getName();
255    }
256    case RSExportType::ExportClassVector: {
257      return GetVectorTypeName(static_cast<const RSExportVectorType*>(ET));
258    }
259    case RSExportType::ExportClassMatrix: {
260      return GetMatrixTypeName(static_cast<const RSExportMatrixType*>(ET));
261    }
262    case RSExportType::ExportClassConstantArray: {
263      const RSExportConstantArrayType* CAT =
264          static_cast<const RSExportConstantArrayType*>(ET);
265      std::string ElementTypeName = GetTypeName(CAT->getElementType());
266      ElementTypeName.append("[]");
267      return ElementTypeName;
268    }
269    case RSExportType::ExportClassRecord: {
270      return RS_TYPE_CLASS_NAME_PREFIX + ET->getName() +
271                 "."RS_TYPE_ITEM_CLASS_NAME;
272    }
273    default: {
274      slangAssert(false && "Unknown class of type");
275    }
276  }
277
278  return "";
279}
280
281static const char *GetTypeNullValue(const RSExportType *ET) {
282  switch (ET->getClass()) {
283    case RSExportType::ExportClassPrimitive: {
284      const RSExportPrimitiveType *EPT =
285          static_cast<const RSExportPrimitiveType*>(ET);
286      if (EPT->isRSObjectType())
287        return "null";
288      else if (EPT->getType() == RSExportPrimitiveType::DataTypeBoolean)
289        return "false";
290      else
291        return "0";
292      break;
293    }
294    case RSExportType::ExportClassPointer:
295    case RSExportType::ExportClassVector:
296    case RSExportType::ExportClassMatrix:
297    case RSExportType::ExportClassConstantArray:
298    case RSExportType::ExportClassRecord: {
299      return "null";
300      break;
301    }
302    default: {
303      slangAssert(false && "Unknown class of type");
304    }
305  }
306  return "";
307}
308
309static const char *GetBuiltinElementConstruct(const RSExportType *ET) {
310  if (ET->getClass() == RSExportType::ExportClassPrimitive) {
311    const RSExportPrimitiveType *EPT =
312        static_cast<const RSExportPrimitiveType*>(ET);
313    if (EPT->getKind() == RSExportPrimitiveType::DataKindUser) {
314      static const char *PrimitiveBuiltinElementConstructMap[] = {
315        NULL,               // RSExportPrimitiveType::DataTypeFloat16
316        "Element.F32",      // RSExportPrimitiveType::DataTypeFloat32
317        "Element.F64",      // RSExportPrimitiveType::DataTypeFloat64
318        "Element.I8",       // RSExportPrimitiveType::DataTypeSigned8
319        NULL,               // RSExportPrimitiveType::DataTypeSigned16
320        "Element.I32",      // RSExportPrimitiveType::DataTypeSigned32
321        "Element.I64",      // RSExportPrimitiveType::DataTypeSigned64
322        "Element.U8",       // RSExportPrimitiveType::DataTypeUnsigned8
323        NULL,               // RSExportPrimitiveType::DataTypeUnsigned16
324        "Element.U32",      // RSExportPrimitiveType::DataTypeUnsigned32
325        "Element.U64",      // RSExportPrimitiveType::DataTypeUnsigned64
326        "Element.BOOLEAN",  // RSExportPrimitiveType::DataTypeBoolean
327
328        NULL,   // RSExportPrimitiveType::DataTypeUnsigned565
329        NULL,   // RSExportPrimitiveType::DataTypeUnsigned5551
330        NULL,   // RSExportPrimitiveType::DataTypeUnsigned4444
331
332        NULL,   // (Dummy) RSExportPrimitiveType::DataTypeRSMatrix2x2
333        NULL,   // (Dummy) RSExportPrimitiveType::DataTypeRSMatrix3x3
334        NULL,   // (Dummy) RSExportPrimitiveType::DataTypeRSMatrix4x4
335
336        "Element.ELEMENT",      // RSExportPrimitiveType::DataTypeRSElement
337        "Element.TYPE",         // RSExportPrimitiveType::DataTypeRSType
338        "Element.ALLOCATION",   // RSExportPrimitiveType::DataTypeRSAllocation
339        "Element.SAMPLER",      // RSExportPrimitiveType::DataTypeRSSampler
340        "Element.SCRIPT",       // RSExportPrimitiveType::DataTypeRSScript
341        "Element.MESH",         // RSExportPrimitiveType::DataTypeRSMesh
342        "Element.PROGRAM_FRAGMENT",
343          // RSExportPrimitiveType::DataTypeRSProgramFragment
344        "Element.PROGRAM_VERTEX",
345          // RSExportPrimitiveType::DataTypeRSProgramVertex
346        "Element.PROGRAM_RASTER",
347          // RSExportPrimitiveType::DataTypeRSProgramRaster
348        "Element.PROGRAM_STORE",
349          // RSExportPrimitiveType::DataTypeRSProgramStore
350        "Element.FONT",
351          // RSExportPrimitiveType::DataTypeRSFont
352      };
353      unsigned TypeId = EPT->getType();
354
355      if (TypeId <
356          (sizeof(PrimitiveBuiltinElementConstructMap) / sizeof(const char*)))
357        return PrimitiveBuiltinElementConstructMap[ EPT->getType() ];
358    } else if (EPT->getKind() == RSExportPrimitiveType::DataKindPixelA) {
359      if (EPT->getType() == RSExportPrimitiveType::DataTypeUnsigned8)
360        return "Element.A_8";
361    } else if (EPT->getKind() == RSExportPrimitiveType::DataKindPixelRGB) {
362      if (EPT->getType() == RSExportPrimitiveType::DataTypeUnsigned565)
363        return "Element.RGB_565";
364      else if (EPT->getType() == RSExportPrimitiveType::DataTypeUnsigned8)
365        return "Element.RGB_888";
366    } else if (EPT->getKind() == RSExportPrimitiveType::DataKindPixelRGBA) {
367      if (EPT->getType() == RSExportPrimitiveType::DataTypeUnsigned5551)
368        return "Element.RGBA_5551";
369      else if (EPT->getType() == RSExportPrimitiveType::DataTypeUnsigned4444)
370        return "Element.RGBA_4444";
371      else if (EPT->getType() == RSExportPrimitiveType::DataTypeUnsigned8)
372        return "Element.RGBA_8888";
373    }
374  } else if (ET->getClass() == RSExportType::ExportClassVector) {
375    const RSExportVectorType *EVT = static_cast<const RSExportVectorType*>(ET);
376    if (EVT->getKind() == RSExportPrimitiveType::DataKindUser) {
377      if (EVT->getType() == RSExportPrimitiveType::DataTypeFloat32) {
378        if (EVT->getNumElement() == 2)
379          return "Element.F32_2";
380        else if (EVT->getNumElement() == 3)
381          return "Element.F32_3";
382        else if (EVT->getNumElement() == 4)
383          return "Element.F32_4";
384      } else if (EVT->getType() == RSExportPrimitiveType::DataTypeUnsigned8) {
385        if (EVT->getNumElement() == 4)
386          return "Element.U8_4";
387      }
388    }
389  } else if (ET->getClass() == RSExportType::ExportClassMatrix) {
390    const RSExportMatrixType *EMT = static_cast<const RSExportMatrixType *>(ET);
391    switch (EMT->getDim()) {
392      case 2: return "Element.MATRIX_2X2";
393      case 3: return "Element.MATRIX_3X3";
394      case 4: return "Element.MATRIX_4X4";
395      default: slangAssert(false && "Unsupported dimension of matrix");
396    }
397  } else if (ET->getClass() == RSExportType::ExportClassPointer) {
398    // Treat pointer type variable as unsigned int
399    // TODO(zonr): this is target dependent
400    return "Element.USER_I32";
401  }
402
403  return NULL;
404}
405
406static const char *GetElementDataKindName(RSExportPrimitiveType::DataKind DK) {
407  static const char *ElementDataKindNameMap[] = {
408    "Element.DataKind.USER",        // RSExportPrimitiveType::DataKindUser
409    "Element.DataKind.PIXEL_L",     // RSExportPrimitiveType::DataKindPixelL
410    "Element.DataKind.PIXEL_A",     // RSExportPrimitiveType::DataKindPixelA
411    "Element.DataKind.PIXEL_LA",    // RSExportPrimitiveType::DataKindPixelLA
412    "Element.DataKind.PIXEL_RGB",   // RSExportPrimitiveType::DataKindPixelRGB
413    "Element.DataKind.PIXEL_RGBA",  // RSExportPrimitiveType::DataKindPixelRGBA
414  };
415
416  if (static_cast<unsigned>(DK) <
417      (sizeof(ElementDataKindNameMap) / sizeof(const char*)))
418    return ElementDataKindNameMap[ DK ];
419  else
420    return NULL;
421}
422
423static const char *GetElementDataTypeName(RSExportPrimitiveType::DataType DT) {
424  static const char *ElementDataTypeNameMap[] = {
425    NULL,                            // RSExportPrimitiveType::DataTypeFloat16
426    "Element.DataType.FLOAT_32",     // RSExportPrimitiveType::DataTypeFloat32
427    "Element.DataType.FLOAT_64",     // RSExportPrimitiveType::DataTypeFloat64
428    "Element.DataType.SIGNED_8",     // RSExportPrimitiveType::DataTypeSigned8
429    "Element.DataType.SIGNED_16",    // RSExportPrimitiveType::DataTypeSigned16
430    "Element.DataType.SIGNED_32",    // RSExportPrimitiveType::DataTypeSigned32
431    "Element.DataType.SIGNED_64",    // RSExportPrimitiveType::DataTypeSigned64
432    "Element.DataType.UNSIGNED_8",   // RSExportPrimitiveType::DataTypeUnsigned8
433    "Element.DataType.UNSIGNED_16",
434      // RSExportPrimitiveType::DataTypeUnsigned16
435    "Element.DataType.UNSIGNED_32",
436      // RSExportPrimitiveType::DataTypeUnsigned32
437    "Element.DataType.UNSIGNED_64",
438      // RSExportPrimitiveType::DataTypeUnsigned64
439    "Element.DataType.BOOLEAN",
440      // RSExportPrimitiveType::DataTypeBoolean
441
442    // RSExportPrimitiveType::DataTypeUnsigned565
443    "Element.DataType.UNSIGNED_5_6_5",
444    // RSExportPrimitiveType::DataTypeUnsigned5551
445    "Element.DataType.UNSIGNED_5_5_5_1",
446    // RSExportPrimitiveType::DataTypeUnsigned4444
447    "Element.DataType.UNSIGNED_4_4_4_4",
448
449    // DataTypeRSMatrix* must have been resolved in GetBuiltinElementConstruct()
450    NULL,  // (Dummy) RSExportPrimitiveType::DataTypeRSMatrix2x2
451    NULL,  // (Dummy) RSExportPrimitiveType::DataTypeRSMatrix3x3
452    NULL,  // (Dummy) RSExportPrimitiveType::DataTypeRSMatrix4x4
453
454    "Element.DataType.RS_ELEMENT",  // RSExportPrimitiveType::DataTypeRSElement
455    "Element.DataType.RS_TYPE",     // RSExportPrimitiveType::DataTypeRSType
456      // RSExportPrimitiveType::DataTypeRSAllocation
457    "Element.DataType.RS_ALLOCATION",
458      // RSExportPrimitiveType::DataTypeRSSampler
459    "Element.DataType.RS_SAMPLER",
460      // RSExportPrimitiveType::DataTypeRSScript
461    "Element.DataType.RS_SCRIPT",
462      // RSExportPrimitiveType::DataTypeRSMesh
463    "Element.DataType.RS_MESH",
464      // RSExportPrimitiveType::DataTypeRSProgramFragment
465    "Element.DataType.RS_PROGRAM_FRAGMENT",
466      // RSExportPrimitiveType::DataTypeRSProgramVertex
467    "Element.DataType.RS_PROGRAM_VERTEX",
468      // RSExportPrimitiveType::DataTypeRSProgramRaster
469    "Element.DataType.RS_PROGRAM_RASTER",
470      // RSExportPrimitiveType::DataTypeRSProgramStore
471    "Element.DataType.RS_PROGRAM_STORE",
472      // RSExportPrimitiveType::DataTypeRSFont
473    "Element.DataType.RS_FONT",
474  };
475
476  if (static_cast<unsigned>(DT) <
477      (sizeof(ElementDataTypeNameMap) / sizeof(const char*)))
478    return ElementDataTypeNameMap[ DT ];
479  else
480    return NULL;
481}
482
483/********************** Methods to generate script class **********************/
484bool RSReflection::genScriptClass(Context &C,
485                                  const std::string &ClassName,
486                                  std::string &ErrorMsg) {
487  if (!C.startClass(Context::AM_Public,
488                    false,
489                    ClassName,
490                    RS_SCRIPT_CLASS_SUPER_CLASS_NAME,
491                    ErrorMsg))
492    return false;
493
494  genScriptClassConstructor(C);
495
496  // Reflect export variable
497  for (RSContext::const_export_var_iterator I = mRSContext->export_vars_begin(),
498           E = mRSContext->export_vars_end();
499       I != E;
500       I++)
501    genExportVariable(C, *I);
502
503  // Reflect export function
504  for (RSContext::const_export_func_iterator
505           I = mRSContext->export_funcs_begin(),
506           E = mRSContext->export_funcs_end();
507       I != E; I++)
508    genExportFunction(C, *I);
509
510  C.endClass();
511
512  return true;
513}
514
515void RSReflection::genScriptClassConstructor(Context &C) {
516  C.indent() << "// Constructor" << std::endl;
517  C.startFunction(Context::AM_Public,
518                  false,
519                  NULL,
520                  C.getClassName(),
521                  3,
522                  "RenderScript", "rs",
523                  "Resources", "resources",
524                  "int", "id");
525  // Call constructor of super class
526  C.indent() << "super(rs, resources, id);" << std::endl;
527
528  // If an exported variable has initial value, reflect it
529
530  for (RSContext::const_export_var_iterator I = mRSContext->export_vars_begin(),
531           E = mRSContext->export_vars_end();
532       I != E;
533       I++) {
534    const RSExportVar *EV = *I;
535    if (!EV->getInit().isUninit())
536      genInitExportVariable(C, EV->getType(), EV->getName(), EV->getInit());
537  }
538
539  C.endFunction();
540
541  return;
542}
543
544void RSReflection::genInitBoolExportVariable(Context &C,
545                                             const std::string &VarName,
546                                             const clang::APValue &Val) {
547  slangAssert(!Val.isUninit() && "Not a valid initializer");
548
549  C.indent() << RS_EXPORT_VAR_PREFIX << VarName << " = ";
550  slangAssert((Val.getKind() == clang::APValue::Int) &&
551              "Bool type has wrong initial APValue");
552
553  C.out() << ((Val.getInt().getSExtValue() == 0) ? "false" : "true")
554          << ";" << std::endl;
555
556  return;
557}
558
559void RSReflection::genInitPrimitiveExportVariable(
560      Context &C,
561      const std::string &VarName,
562      const clang::APValue &Val) {
563  slangAssert(!Val.isUninit() && "Not a valid initializer");
564
565  C.indent() << RS_EXPORT_VAR_PREFIX << VarName << " = ";
566  switch (Val.getKind()) {
567    case clang::APValue::Int: {
568      llvm::APInt api = Val.getInt();
569      C.out() << api.getSExtValue();
570      if (api.getBitWidth() > 32) {
571        C.out() << "L";
572      }
573      break;
574    }
575    case clang::APValue::Float: {
576      llvm::APFloat apf = Val.getFloat();
577      if (&apf.getSemantics() == &llvm::APFloat::IEEEsingle) {
578        C.out() << apf.convertToFloat() << "f";
579      } else {
580        C.out() << apf.convertToDouble();
581      }
582      break;
583    }
584
585    case clang::APValue::ComplexInt:
586    case clang::APValue::ComplexFloat:
587    case clang::APValue::LValue:
588    case clang::APValue::Vector: {
589      slangAssert(false &&
590                  "Primitive type cannot have such kind of initializer");
591      break;
592    }
593    default: {
594      slangAssert(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  slangAssert(!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          slangAssert(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      slangAssert((Val.getKind() == clang::APValue::Vector) &&
672          "Unexpected type of 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      slangAssert(false && "Unsupported initializer for record/matrix/constant "
694                           "array type variable currently");
695      break;
696    }
697    default: {
698      slangAssert(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      slangAssert(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  slangAssert((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  slangAssert((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  slangAssert((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  slangAssert((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  slangAssert((EV->getType()->getClass() ==
936               RSExportType::ExportClassConstantArray) &&
937              "Variable should be type of constant array here");
938
939  const RSExportConstantArrayType *ECAT =
940      static_cast<const RSExportConstantArrayType*>(EV->getType());
941  std::string TypeName = GetTypeName(ECAT);
942  const char *FieldPackerName = "fp";
943
944  C.indent() << "private " << TypeName << " "RS_EXPORT_VAR_PREFIX
945             << EV->getName() << ";" << std::endl;
946
947  // set_*()
948  if (!EV->isConst()) {
949    C.startFunction(Context::AM_Public,
950                    false,
951                    "void",
952                    "set_" + EV->getName(),
953                    1,
954                    TypeName.c_str(), "v");
955    C.indent() << RS_EXPORT_VAR_PREFIX << EV->getName() << " = v;" << std::endl;
956
957    if (genCreateFieldPacker(C, ECAT, FieldPackerName))
958      genPackVarOfType(C, ECAT, "v", FieldPackerName);
959    C.indent() << "setVar("RS_EXPORT_VAR_INDEX_PREFIX << EV->getName() << ", "
960               << FieldPackerName << ");" << std::endl;
961
962    C.endFunction();
963  }
964
965  genGetExportVariable(C, TypeName, EV->getName());
966  return;
967}
968
969void RSReflection::genRecordTypeExportVariable(Context &C,
970                                               const RSExportVar *EV) {
971  slangAssert((EV->getType()->getClass() == RSExportType::ExportClassRecord) &&
972              "Variable should be type of struct here");
973
974  const RSExportRecordType *ERT =
975      static_cast<const RSExportRecordType*>(EV->getType());
976  std::string TypeName =
977      RS_TYPE_CLASS_NAME_PREFIX + ERT->getName() + "."RS_TYPE_ITEM_CLASS_NAME;
978  const char *FieldPackerName = "fp";
979
980  C.indent() << "private " << TypeName << " "RS_EXPORT_VAR_PREFIX
981             << EV->getName() << ";" << std::endl;
982
983  // set_*()
984  if (!EV->isConst()) {
985    C.startFunction(Context::AM_Public,
986                    false,
987                    "void",
988                    "set_" + EV->getName(),
989                    1,
990                    TypeName.c_str(), "v");
991    C.indent() << RS_EXPORT_VAR_PREFIX << EV->getName() << " = v;" << std::endl;
992
993    if (genCreateFieldPacker(C, ERT, FieldPackerName))
994      genPackVarOfType(C, ERT, "v", FieldPackerName);
995    C.indent() << "setVar("RS_EXPORT_VAR_INDEX_PREFIX << EV->getName()
996               << ", " << FieldPackerName << ");" << std::endl;
997
998    C.endFunction();
999  }
1000
1001  genGetExportVariable(C, TypeName.c_str(), EV->getName());
1002  return;
1003}
1004
1005void RSReflection::genGetExportVariable(Context &C,
1006                                        const std::string &TypeName,
1007                                        const std::string &VarName) {
1008  C.startFunction(Context::AM_Public,
1009                  false,
1010                  TypeName.c_str(),
1011                  "get_" + VarName,
1012                  0);
1013
1014  C.indent() << "return "RS_EXPORT_VAR_PREFIX << VarName << ";" << std::endl;
1015
1016  C.endFunction();
1017  return;
1018}
1019
1020/******************* Methods to generate script class /end *******************/
1021
1022bool RSReflection::genCreateFieldPacker(Context &C,
1023                                        const RSExportType *ET,
1024                                        const char *FieldPackerName) {
1025  size_t AllocSize = RSExportType::GetTypeAllocSize(ET);
1026  if (AllocSize > 0)
1027    C.indent() << "FieldPacker " << FieldPackerName << " = new FieldPacker("
1028               << AllocSize << ");" << std::endl;
1029  else
1030    return false;
1031  return true;
1032}
1033
1034void RSReflection::genPackVarOfType(Context &C,
1035                                    const RSExportType *ET,
1036                                    const char *VarName,
1037                                    const char *FieldPackerName) {
1038  switch (ET->getClass()) {
1039    case RSExportType::ExportClassPrimitive:
1040    case RSExportType::ExportClassVector: {
1041      C.indent() << FieldPackerName << "."
1042                 << GetPackerAPIName(
1043                     static_cast<const RSExportPrimitiveType*>(ET))
1044                 << "(" << VarName << ");" << std::endl;
1045      break;
1046    }
1047    case RSExportType::ExportClassPointer: {
1048      // Must reflect as type Allocation in Java
1049      const RSExportType *PointeeType =
1050          static_cast<const RSExportPointerType*>(ET)->getPointeeType();
1051
1052      if (PointeeType->getClass() != RSExportType::ExportClassRecord)
1053        C.indent() << FieldPackerName << ".addI32(" << VarName
1054                   << ".getPtr());" << std::endl;
1055      else
1056        C.indent() << FieldPackerName << ".addI32(" << VarName
1057                   << ".getAllocation().getPtr());" << std::endl;
1058      break;
1059    }
1060    case RSExportType::ExportClassMatrix: {
1061      C.indent() << FieldPackerName << ".addMatrix(" << VarName << ");"
1062                 << std::endl;
1063      break;
1064    }
1065    case RSExportType::ExportClassConstantArray: {
1066      const RSExportConstantArrayType *ECAT =
1067          static_cast<const RSExportConstantArrayType *>(ET);
1068
1069      // TODO(zonr): more elegant way. Currently, we obtain the unique index
1070      //             variable (this method involves recursive call which means
1071      //             we may have more than one level loop, therefore we can't
1072      //             always use the same index variable name here) name given
1073      //             in the for-loop from counting the '.' in @VarName.
1074      unsigned Level = 0;
1075      size_t LastDotPos = 0;
1076      std::string ElementVarName(VarName);
1077
1078      while (LastDotPos != std::string::npos) {
1079        LastDotPos = ElementVarName.find_first_of('.', LastDotPos + 1);
1080        Level++;
1081      }
1082      std::string IndexVarName("ct");
1083      IndexVarName.append(llvm::utostr_32(Level));
1084
1085      C.indent() << "for (int " << IndexVarName << " = 0; " <<
1086                          IndexVarName << " < " << ECAT->getSize() << "; " <<
1087                          IndexVarName << "++)";
1088      C.startBlock();
1089
1090      ElementVarName.append("[" + IndexVarName + "]");
1091      genPackVarOfType(C, ECAT->getElementType(), ElementVarName.c_str(),
1092                       FieldPackerName);
1093
1094      C.endBlock();
1095      break;
1096    }
1097    case RSExportType::ExportClassRecord: {
1098      const RSExportRecordType *ERT =
1099          static_cast<const RSExportRecordType*>(ET);
1100      // Relative pos from now on in field packer
1101      unsigned Pos = 0;
1102
1103      for (RSExportRecordType::const_field_iterator I = ERT->fields_begin(),
1104               E = ERT->fields_end();
1105           I != E;
1106           I++) {
1107        const RSExportRecordType::Field *F = *I;
1108        std::string FieldName;
1109        size_t FieldOffset = F->getOffsetInParent();
1110        size_t FieldStoreSize = RSExportType::GetTypeStoreSize(F->getType());
1111        size_t FieldAllocSize = RSExportType::GetTypeAllocSize(F->getType());
1112
1113        if (VarName != NULL)
1114          FieldName = VarName + ("." + F->getName());
1115        else
1116          FieldName = F->getName();
1117
1118        if (FieldOffset > Pos)
1119          C.indent() << FieldPackerName << ".skip("
1120                     << (FieldOffset - Pos) << ");" << std::endl;
1121
1122        genPackVarOfType(C, F->getType(), FieldName.c_str(), FieldPackerName);
1123
1124        // There is padding in the field type
1125        if (FieldAllocSize > FieldStoreSize)
1126            C.indent() << FieldPackerName << ".skip("
1127                       << (FieldAllocSize - FieldStoreSize)
1128                       << ");" << std::endl;
1129
1130          Pos = FieldOffset + FieldAllocSize;
1131      }
1132
1133      // There maybe some padding after the struct
1134      size_t Padding = RSExportType::GetTypeAllocSize(ERT) - Pos;
1135      if (Padding > 0)
1136        C.indent() << FieldPackerName << ".skip(" << Padding << ");"
1137                   << std::endl;
1138      break;
1139    }
1140    default: {
1141      slangAssert(false && "Unknown class of type");
1142    }
1143  }
1144
1145  return;
1146}
1147
1148void RSReflection::genAllocateVarOfType(Context &C,
1149                                        const RSExportType *T,
1150                                        const std::string &VarName) {
1151  switch (T->getClass()) {
1152    case RSExportType::ExportClassPrimitive: {
1153      // Primitive type like int in Java has its own storage once it's declared.
1154      //
1155      // FIXME: Should we allocate storage for RS object?
1156      // if (static_cast<const RSExportPrimitiveType *>(T)->isRSObjectType())
1157      //  C.indent() << VarName << " = new " << GetTypeName(T) << "();"
1158      //             << std::endl;
1159      break;
1160    }
1161    case RSExportType::ExportClassPointer: {
1162      // Pointer type is an instance of Allocation or a TypeClass whose value is
1163      // expected to be assigned by programmer later in Java program. Therefore
1164      // we don't reflect things like [VarName] = new Allocation();
1165      C.indent() << VarName << " = null;" << std::endl;
1166      break;
1167    }
1168    case RSExportType::ExportClassConstantArray: {
1169      const RSExportConstantArrayType *ECAT =
1170          static_cast<const RSExportConstantArrayType *>(T);
1171      const RSExportType *ElementType = ECAT->getElementType();
1172
1173      C.indent() << VarName << " = new " << GetTypeName(ElementType)
1174                 << "[" << ECAT->getSize() << "];" << std::endl;
1175
1176      // Primitive type element doesn't need allocation code.
1177      if (ElementType->getClass() != RSExportType::ExportClassPrimitive) {
1178        C.indent() << "for (int $ct = 0; $ct < " << ECAT->getSize() << "; "
1179                            "$ct++)";
1180        C.startBlock();
1181
1182        std::string ElementVarName(VarName);
1183        ElementVarName.append("[$ct]");
1184        genAllocateVarOfType(C, ElementType, ElementVarName);
1185
1186        C.endBlock();
1187      }
1188      break;
1189    }
1190    case RSExportType::ExportClassVector:
1191    case RSExportType::ExportClassMatrix:
1192    case RSExportType::ExportClassRecord: {
1193      C.indent() << VarName << " = new " << GetTypeName(T) << "();"
1194                 << std::endl;
1195      break;
1196    }
1197  }
1198  return;
1199}
1200
1201void RSReflection::genNewItemBufferIfNull(Context &C,
1202                                          const char *Index) {
1203  C.indent() << "if (" RS_TYPE_ITEM_BUFFER_NAME " == null) "
1204                  RS_TYPE_ITEM_BUFFER_NAME " = "
1205                    "new " RS_TYPE_ITEM_CLASS_NAME
1206                      "[getType().getX() /* count */];"
1207             << std::endl;
1208  if (Index != NULL)
1209    C.indent() << "if ("RS_TYPE_ITEM_BUFFER_NAME"[" << Index << "] == null) "
1210                    RS_TYPE_ITEM_BUFFER_NAME"[" << Index << "] = "
1211                      "new "RS_TYPE_ITEM_CLASS_NAME"();" << std::endl;
1212  return;
1213}
1214
1215void RSReflection::genNewItemBufferPackerIfNull(Context &C) {
1216  C.indent() << "if (" RS_TYPE_ITEM_BUFFER_PACKER_NAME " == null) "
1217                  RS_TYPE_ITEM_BUFFER_PACKER_NAME " = "
1218                    "new FieldPacker(" RS_TYPE_ITEM_CLASS_NAME
1219                      ".sizeof * getType().getX()/* count */"
1220                        ");" << std::endl;
1221  return;
1222}
1223
1224/********************** Methods to generate type class  **********************/
1225bool RSReflection::genTypeClass(Context &C,
1226                                const RSExportRecordType *ERT,
1227                                std::string &ErrorMsg) {
1228  std::string ClassName = RS_TYPE_CLASS_NAME_PREFIX + ERT->getName();
1229
1230  if (!C.startClass(Context::AM_Public,
1231                    false,
1232                    ClassName,
1233                    RS_TYPE_CLASS_SUPER_CLASS_NAME,
1234                    ErrorMsg))
1235    return false;
1236
1237  mGeneratedFileNames->push_back(ClassName);
1238
1239  genTypeItemClass(C, ERT);
1240
1241  // Declare item buffer and item buffer packer
1242  C.indent() << "private "RS_TYPE_ITEM_CLASS_NAME" "RS_TYPE_ITEM_BUFFER_NAME"[]"
1243      ";" << std::endl;
1244  C.indent() << "private FieldPacker "RS_TYPE_ITEM_BUFFER_PACKER_NAME";"
1245             << std::endl;
1246
1247  genTypeClassConstructor(C, ERT);
1248  genTypeClassCopyToArray(C, ERT);
1249  genTypeClassItemSetter(C, ERT);
1250  genTypeClassItemGetter(C, ERT);
1251  genTypeClassComponentSetter(C, ERT);
1252  genTypeClassComponentGetter(C, ERT);
1253  genTypeClassCopyAll(C, ERT);
1254  genTypeClassResize(C);
1255
1256  C.endClass();
1257
1258  C.resetFieldIndex();
1259  C.clearFieldIndexMap();
1260
1261  return true;
1262}
1263
1264void RSReflection::genTypeItemClass(Context &C,
1265                                    const RSExportRecordType *ERT) {
1266  C.indent() << "static public class "RS_TYPE_ITEM_CLASS_NAME;
1267  C.startBlock();
1268
1269  C.indent() << "public static final int sizeof = "
1270             << RSExportType::GetTypeAllocSize(ERT) << ";" << std::endl;
1271
1272  // Member elements
1273  C.out() << std::endl;
1274  for (RSExportRecordType::const_field_iterator FI = ERT->fields_begin(),
1275           FE = ERT->fields_end();
1276       FI != FE;
1277       FI++) {
1278    C.indent() << GetTypeName((*FI)->getType()) << " " << (*FI)->getName()
1279               << ";" << std::endl;
1280  }
1281
1282  // Constructor
1283  C.out() << std::endl;
1284  C.indent() << RS_TYPE_ITEM_CLASS_NAME"()";
1285  C.startBlock();
1286
1287  for (RSExportRecordType::const_field_iterator FI = ERT->fields_begin(),
1288           FE = ERT->fields_end();
1289       FI != FE;
1290       FI++) {
1291    const RSExportRecordType::Field *F = *FI;
1292    genAllocateVarOfType(C, F->getType(), F->getName());
1293  }
1294
1295  // end Constructor
1296  C.endBlock();
1297
1298  // end Item class
1299  C.endBlock();
1300
1301  return;
1302}
1303
1304void RSReflection::genTypeClassConstructor(Context &C,
1305                                           const RSExportRecordType *ERT) {
1306  const char *RenderScriptVar = "rs";
1307
1308  C.startFunction(Context::AM_Public,
1309                  true,
1310                  "Element",
1311                  "createElement",
1312                  1,
1313                  "RenderScript", RenderScriptVar);
1314  genBuildElement(C, "eb", ERT, RenderScriptVar, /* IsInline = */false);
1315  C.endFunction();
1316
1317  C.startFunction(Context::AM_Public,
1318                  false,
1319                  NULL,
1320                  C.getClassName(),
1321                  2,
1322                  "RenderScript", RenderScriptVar,
1323                  "int", "count");
1324
1325  C.indent() << RS_TYPE_ITEM_BUFFER_NAME" = null;" << std::endl;
1326  C.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME" = null;" << std::endl;
1327  C.indent() << "mElement = createElement(" << RenderScriptVar << ");"
1328             << std::endl;
1329  // Call init() in super class
1330  C.indent() << "init(" << RenderScriptVar << ", count);" << std::endl;
1331  C.endFunction();
1332
1333  C.startFunction(Context::AM_Public,
1334                  false,
1335                  NULL,
1336                  C.getClassName(),
1337                  3,
1338                  "RenderScript", RenderScriptVar,
1339                  "int", "count",
1340                  "int", "usages");
1341
1342  C.indent() << RS_TYPE_ITEM_BUFFER_NAME" = null;" << std::endl;
1343  C.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME" = null;" << std::endl;
1344  C.indent() << "mElement = createElement(" << RenderScriptVar << ");"
1345             << std::endl;
1346  // Call init() in super class
1347  C.indent() << "init(" << RenderScriptVar << ", count, usages);" << std::endl;
1348  C.endFunction();
1349
1350  return;
1351}
1352
1353void RSReflection::genTypeClassCopyToArray(Context &C,
1354                                           const RSExportRecordType *ERT) {
1355  C.startFunction(Context::AM_Private,
1356                  false,
1357                  "void",
1358                  "copyToArray",
1359                  2,
1360                  RS_TYPE_ITEM_CLASS_NAME, "i",
1361                  "int", "index");
1362
1363  genNewItemBufferPackerIfNull(C);
1364  C.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME
1365                ".reset(index * "RS_TYPE_ITEM_CLASS_NAME".sizeof);"
1366             << std::endl;
1367
1368  genPackVarOfType(C, ERT, "i", RS_TYPE_ITEM_BUFFER_PACKER_NAME);
1369
1370  C.endFunction();
1371  return;
1372}
1373
1374void RSReflection::genTypeClassItemSetter(Context &C,
1375                                          const RSExportRecordType *ERT) {
1376  C.startFunction(Context::AM_Public,
1377                  false,
1378                  "void",
1379                  "set",
1380                  3,
1381                  RS_TYPE_ITEM_CLASS_NAME, "i",
1382                  "int", "index",
1383                  "boolean", "copyNow");
1384  genNewItemBufferIfNull(C, NULL);
1385  C.indent() << RS_TYPE_ITEM_BUFFER_NAME"[index] = i;" << std::endl;
1386
1387  C.indent() << "if (copyNow) ";
1388  C.startBlock();
1389
1390  C.indent() << "copyToArray(i, index);" << std::endl;
1391  C.indent() << "mAllocation.setFromFieldPacker(index, "
1392                  RS_TYPE_ITEM_BUFFER_PACKER_NAME");" << std::endl;
1393
1394  // End of if (copyNow)
1395  C.endBlock();
1396
1397  C.endFunction();
1398  return;
1399}
1400
1401void RSReflection::genTypeClassItemGetter(Context &C,
1402                                          const RSExportRecordType *ERT) {
1403  C.startFunction(Context::AM_Public,
1404                  false,
1405                  RS_TYPE_ITEM_CLASS_NAME,
1406                  "get",
1407                  1,
1408                  "int", "index");
1409  C.indent() << "if ("RS_TYPE_ITEM_BUFFER_NAME" == null) return null;"
1410             << std::endl;
1411  C.indent() << "return "RS_TYPE_ITEM_BUFFER_NAME"[index];" << std::endl;
1412  C.endFunction();
1413  return;
1414}
1415
1416void RSReflection::genTypeClassComponentSetter(Context &C,
1417                                               const RSExportRecordType *ERT) {
1418  for (RSExportRecordType::const_field_iterator FI = ERT->fields_begin(),
1419           FE = ERT->fields_end();
1420       FI != FE;
1421       FI++) {
1422    const RSExportRecordType::Field *F = *FI;
1423    size_t FieldOffset = F->getOffsetInParent();
1424    size_t FieldStoreSize = RSExportType::GetTypeStoreSize(F->getType());
1425    unsigned FieldIndex = C.getFieldIndex(F);
1426
1427    C.startFunction(Context::AM_Public,
1428                    false,
1429                    "void",
1430                    "set_" + F->getName(), 3,
1431                    "int", "index",
1432                    GetTypeName(F->getType()).c_str(), "v",
1433                    "boolean", "copyNow");
1434    genNewItemBufferPackerIfNull(C);
1435    genNewItemBufferIfNull(C, "index");
1436    C.indent() << RS_TYPE_ITEM_BUFFER_NAME"[index]." << F->getName()
1437               << " = v;" << std::endl;
1438
1439    C.indent() << "if (copyNow) ";
1440    C.startBlock();
1441
1442    if (FieldOffset > 0)
1443      C.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME
1444                    ".reset(index * "RS_TYPE_ITEM_CLASS_NAME".sizeof + "
1445                 << FieldOffset << ");" << std::endl;
1446    else
1447      C.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME
1448                    ".reset(index * "RS_TYPE_ITEM_CLASS_NAME".sizeof);"
1449                 << std::endl;
1450    genPackVarOfType(C, F->getType(), "v", RS_TYPE_ITEM_BUFFER_PACKER_NAME);
1451
1452    C.indent() << "FieldPacker fp = new FieldPacker(" << FieldStoreSize << ");"
1453               << std::endl;
1454    genPackVarOfType(C, F->getType(), "v", "fp");
1455    C.indent() << "mAllocation.setFromFieldPacker(index, " << FieldIndex
1456               << ", fp);"
1457               << std::endl;
1458
1459    // End of if (copyNow)
1460    C.endBlock();
1461
1462    C.endFunction();
1463  }
1464  return;
1465}
1466
1467void RSReflection::genTypeClassComponentGetter(Context &C,
1468                                               const RSExportRecordType *ERT) {
1469  for (RSExportRecordType::const_field_iterator FI = ERT->fields_begin(),
1470           FE = ERT->fields_end();
1471       FI != FE;
1472       FI++) {
1473    const RSExportRecordType::Field *F = *FI;
1474    C.startFunction(Context::AM_Public,
1475                    false,
1476                    GetTypeName(F->getType()).c_str(),
1477                    "get_" + F->getName(),
1478                    1,
1479                    "int", "index");
1480    C.indent() << "if ("RS_TYPE_ITEM_BUFFER_NAME" == null) return "
1481               << GetTypeNullValue(F->getType()) << ";" << std::endl;
1482    C.indent() << "return "RS_TYPE_ITEM_BUFFER_NAME"[index]." << F->getName()
1483               << ";" << std::endl;
1484    C.endFunction();
1485  }
1486  return;
1487}
1488
1489void RSReflection::genTypeClassCopyAll(Context &C,
1490                                       const RSExportRecordType *ERT) {
1491  C.startFunction(Context::AM_Public, false, "void", "copyAll", 0);
1492
1493  C.indent() << "for (int ct = 0; ct < "RS_TYPE_ITEM_BUFFER_NAME".length; ct++)"
1494                  " copyToArray("RS_TYPE_ITEM_BUFFER_NAME"[ct], ct);"
1495             << std::endl;
1496  C.indent() << "mAllocation.setFromFieldPacker(0, "
1497                  RS_TYPE_ITEM_BUFFER_PACKER_NAME");"
1498             << std::endl;
1499
1500  C.endFunction();
1501  return;
1502}
1503
1504void RSReflection::genTypeClassResize(Context &C) {
1505  C.startFunction(Context::AM_Public,
1506                  false,
1507                  "void",
1508                  "resize",
1509                  1,
1510                  "int", "newSize");
1511
1512  C.indent() << "if (mItemArray != null) ";
1513  C.startBlock();
1514  C.indent() << "int oldSize = mItemArray.length;" << std::endl;
1515  C.indent() << "int copySize = Math.min(oldSize, newSize);" << std::endl;
1516  C.indent() << "if (newSize == oldSize) return;" << std::endl;
1517  C.indent() << "Item ni[] = new Item[newSize];" << std::endl;
1518  C.indent() << "System.arraycopy(mItemArray, 0, ni, 0, copySize);"
1519             << std::endl;
1520  C.indent() << "mItemArray = ni;" << std::endl;
1521  C.endBlock();
1522  C.indent() << "mAllocation.resize(newSize);" << std::endl;
1523
1524  C.indent() << "if (" RS_TYPE_ITEM_BUFFER_PACKER_NAME " != null) "
1525                  RS_TYPE_ITEM_BUFFER_PACKER_NAME " = "
1526                    "new FieldPacker(" RS_TYPE_ITEM_CLASS_NAME
1527                      ".sizeof * getType().getX()/* count */"
1528                        ");" << std::endl;
1529
1530  C.endFunction();
1531  return;
1532}
1533
1534/******************** Methods to generate type class /end ********************/
1535
1536/********** Methods to create Element in Java of given record type ***********/
1537void RSReflection::genBuildElement(Context &C,
1538                                   const char *ElementBuilderName,
1539                                   const RSExportRecordType *ERT,
1540                                   const char *RenderScriptVar,
1541                                   bool IsInline) {
1542  C.indent() << "Element.Builder " << ElementBuilderName << " = "
1543      "new Element.Builder(" << RenderScriptVar << ");" << std::endl;
1544
1545  // eb.add(...)
1546  genAddElementToElementBuilder(C,
1547                                ERT,
1548                                "",
1549                                ElementBuilderName,
1550                                RenderScriptVar,
1551                                /* ArraySize = */0);
1552
1553  if (!IsInline)
1554    C.indent() << "return " << ElementBuilderName << ".create();" << std::endl;
1555  return;
1556}
1557
1558#define EB_ADD(x) do {                                              \
1559  C.indent() << ElementBuilderName                                  \
1560             << ".add(" << x << ", \"" << VarName << "\"";  \
1561  if (ArraySize > 0)                                                \
1562    C.out() << ", " << ArraySize;                                   \
1563  C.out() << ");" << std::endl;                                     \
1564  C.incFieldIndex();                                                \
1565} while (false)
1566
1567void RSReflection::genAddElementToElementBuilder(Context &C,
1568                                                 const RSExportType *ET,
1569                                                 const std::string &VarName,
1570                                                 const char *ElementBuilderName,
1571                                                 const char *RenderScriptVar,
1572                                                 unsigned ArraySize) {
1573  const char *ElementConstruct = GetBuiltinElementConstruct(ET);
1574
1575  if (ElementConstruct != NULL) {
1576    EB_ADD(ElementConstruct << "(" << RenderScriptVar << ")");
1577  } else {
1578    if ((ET->getClass() == RSExportType::ExportClassPrimitive) ||
1579        (ET->getClass() == RSExportType::ExportClassVector)) {
1580      const RSExportPrimitiveType *EPT =
1581          static_cast<const RSExportPrimitiveType*>(ET);
1582      const char *DataKindName = GetElementDataKindName(EPT->getKind());
1583      const char *DataTypeName = GetElementDataTypeName(EPT->getType());
1584      int Size = (ET->getClass() == RSExportType::ExportClassVector) ?
1585          static_cast<const RSExportVectorType*>(ET)->getNumElement() :
1586          1;
1587
1588      switch (EPT->getKind()) {
1589        case RSExportPrimitiveType::DataKindPixelL:
1590        case RSExportPrimitiveType::DataKindPixelA:
1591        case RSExportPrimitiveType::DataKindPixelLA:
1592        case RSExportPrimitiveType::DataKindPixelRGB:
1593        case RSExportPrimitiveType::DataKindPixelRGBA: {
1594          // Element.createPixel()
1595          EB_ADD("Element.createPixel(" << RenderScriptVar << ", "
1596                                        << DataTypeName << ", "
1597                                        << DataKindName << ")");
1598          break;
1599        }
1600        case RSExportPrimitiveType::DataKindUser:
1601        default: {
1602          if (EPT->getClass() == RSExportType::ExportClassPrimitive) {
1603            // Element.createUser()
1604            EB_ADD("Element.createUser(" << RenderScriptVar << ", "
1605                                         << DataTypeName << ")");
1606          } else {
1607            slangAssert((ET->getClass() == RSExportType::ExportClassVector) &&
1608                        "Unexpected type.");
1609            EB_ADD("Element.createVector(" << RenderScriptVar << ", "
1610                                           << DataTypeName << ", "
1611                                           << Size << ")");
1612          }
1613          break;
1614        }
1615      }
1616#ifndef NDEBUG
1617    } else if (ET->getClass() == RSExportType::ExportClassPointer) {
1618      // Pointer type variable should be resolved in
1619      // GetBuiltinElementConstruct()
1620      slangAssert(false && "??");
1621    } else if (ET->getClass() == RSExportType::ExportClassMatrix) {
1622      // Matrix type variable should be resolved
1623      // in GetBuiltinElementConstruct()
1624      slangAssert(false && "??");
1625#endif
1626    } else if (ET->getClass() == RSExportType::ExportClassConstantArray) {
1627      const RSExportConstantArrayType *ECAT =
1628          static_cast<const RSExportConstantArrayType *>(ET);
1629
1630      const RSExportType *ElementType = ECAT->getElementType();
1631      if (ElementType->getClass() != RSExportType::ExportClassRecord) {
1632        genAddElementToElementBuilder(C,
1633                                      ECAT->getElementType(),
1634                                      VarName,
1635                                      ElementBuilderName,
1636                                      RenderScriptVar,
1637                                      ECAT->getSize());
1638      } else {
1639        std::string NewElementBuilderName(ElementBuilderName);
1640        NewElementBuilderName.append(1, '_');
1641
1642        genBuildElement(C,
1643                        NewElementBuilderName.c_str(),
1644                        static_cast<const RSExportRecordType*>(ElementType),
1645                        RenderScriptVar,
1646                        /* IsInline = */true);
1647        ArraySize = ECAT->getSize();
1648        EB_ADD(NewElementBuilderName << ".create()");
1649      }
1650    } else if (ET->getClass() == RSExportType::ExportClassRecord) {
1651      // Simalar to case of RSExportType::ExportClassRecord in genPackVarOfType.
1652      //
1653      // TODO(zonr): Generalize these two function such that there's no
1654      //             duplicated codes.
1655      const RSExportRecordType *ERT =
1656          static_cast<const RSExportRecordType*>(ET);
1657      int Pos = 0;    // relative pos from now on
1658
1659      for (RSExportRecordType::const_field_iterator I = ERT->fields_begin(),
1660               E = ERT->fields_end();
1661           I != E;
1662           I++) {
1663        const RSExportRecordType::Field *F = *I;
1664        std::string FieldName;
1665        int FieldOffset = F->getOffsetInParent();
1666        int FieldStoreSize = RSExportType::GetTypeStoreSize(F->getType());
1667        int FieldAllocSize = RSExportType::GetTypeAllocSize(F->getType());
1668
1669        if (!VarName.empty())
1670          FieldName = VarName + "." + F->getName();
1671        else
1672          FieldName = F->getName();
1673
1674        // Alignment
1675        genAddPaddingToElementBuiler(C,
1676                                     (FieldOffset - Pos),
1677                                     ElementBuilderName,
1678                                     RenderScriptVar);
1679
1680        // eb.add(...)
1681        C.addFieldIndexMapping(F);
1682        if (F->getType()->getClass() != RSExportType::ExportClassRecord) {
1683          genAddElementToElementBuilder(C,
1684                                        F->getType(),
1685                                        FieldName,
1686                                        ElementBuilderName,
1687                                        RenderScriptVar,
1688                                        0);
1689        } else {
1690          std::string NewElementBuilderName(ElementBuilderName);
1691          NewElementBuilderName.append(1, '_');
1692
1693          genBuildElement(C,
1694                          NewElementBuilderName.c_str(),
1695                          static_cast<const RSExportRecordType*>(F->getType()),
1696                          RenderScriptVar,
1697                          /* IsInline = */true);
1698
1699          const std::string &VarName = FieldName;  // Hack for EB_ADD macro
1700          EB_ADD(NewElementBuilderName << ".create()");
1701        }
1702
1703        // There is padding within the field type
1704        genAddPaddingToElementBuiler(C,
1705                                     (FieldAllocSize - FieldStoreSize),
1706                                     ElementBuilderName,
1707                                     RenderScriptVar);
1708
1709        Pos = FieldOffset + FieldAllocSize;
1710      }
1711
1712      // There maybe some padding after the struct
1713      size_t RecordStoreSize = RSExportType::GetTypeStoreSize(ERT);
1714
1715      genAddPaddingToElementBuiler(C,
1716                                   RecordStoreSize - Pos,
1717                                   ElementBuilderName,
1718                                   RenderScriptVar);
1719    } else {
1720      slangAssert(false && "Unknown class of type");
1721    }
1722  }
1723}
1724
1725void RSReflection::genAddPaddingToElementBuiler(Context &C,
1726                                                int PaddingSize,
1727                                                const char *ElementBuilderName,
1728                                                const char *RenderScriptVar) {
1729  unsigned ArraySize = 0;   // Hack the EB_ADD macro
1730  while (PaddingSize > 0) {
1731    const std::string &VarName = C.createPaddingField();
1732    if (PaddingSize >= 4) {
1733      EB_ADD("Element.U32(" << RenderScriptVar << ")");
1734      PaddingSize -= 4;
1735    } else if (PaddingSize >= 2) {
1736      EB_ADD("Element.U16(" << RenderScriptVar << ")");
1737      PaddingSize -= 2;
1738    } else if (PaddingSize >= 1) {
1739      EB_ADD("Element.U8(" << RenderScriptVar << ")");
1740      PaddingSize -= 1;
1741    }
1742  }
1743  return;
1744}
1745
1746#undef EB_ADD
1747/******** Methods to create Element in Java of given record type /end ********/
1748
1749bool RSReflection::reflect(const std::string &OutputPathBase,
1750                           const std::string &OutputPackageName,
1751                           const std::string &InputFileName,
1752                           const std::string &OutputBCFileName) {
1753  Context *C = NULL;
1754  std::string ResourceId = "";
1755
1756  if (!GetClassNameFromFileName(OutputBCFileName, ResourceId))
1757    return false;
1758
1759  if (ResourceId.empty())
1760    ResourceId = "<Resource ID>";
1761
1762  if (OutputPackageName.empty() || OutputPackageName == "-")
1763    C = new Context(OutputPathBase, InputFileName, "<Package Name>",
1764                    ResourceId, true);
1765  else
1766    C = new Context(OutputPathBase, InputFileName, OutputPackageName,
1767                    ResourceId, false);
1768
1769  if (C != NULL) {
1770    std::string ErrorMsg, ScriptClassName;
1771    // class ScriptC_<ScriptName>
1772    if (!GetClassNameFromFileName(InputFileName, ScriptClassName))
1773      return false;
1774
1775    if (ScriptClassName.empty())
1776      ScriptClassName = "<Input Script Name>";
1777
1778    ScriptClassName.insert(0, RS_SCRIPT_CLASS_NAME_PREFIX);
1779
1780    if (mRSContext->getLicenseNote() != NULL) {
1781      C->setLicenseNote(*(mRSContext->getLicenseNote()));
1782    }
1783
1784    if (!genScriptClass(*C, ScriptClassName, ErrorMsg)) {
1785      std::cerr << "Failed to generate class " << ScriptClassName << " ("
1786                << ErrorMsg << ")" << std::endl;
1787      return false;
1788    }
1789
1790    mGeneratedFileNames->push_back(ScriptClassName);
1791
1792    // class ScriptField_<TypeName>
1793    for (RSContext::const_export_type_iterator TI =
1794             mRSContext->export_types_begin(),
1795             TE = mRSContext->export_types_end();
1796         TI != TE;
1797         TI++) {
1798      const RSExportType *ET = TI->getValue();
1799
1800      if (ET->getClass() == RSExportType::ExportClassRecord) {
1801        const RSExportRecordType *ERT =
1802            static_cast<const RSExportRecordType*>(ET);
1803
1804        if (!ERT->isArtificial() && !genTypeClass(*C, ERT, ErrorMsg)) {
1805          std::cerr << "Failed to generate type class for struct '"
1806                    << ERT->getName() << "' (" << ErrorMsg << ")" << std::endl;
1807          return false;
1808        }
1809      }
1810    }
1811  }
1812
1813  return true;
1814}
1815
1816/************************** RSReflection::Context **************************/
1817const char *const RSReflection::Context::ApacheLicenseNote =
1818    "/*\n"
1819    " * Copyright (C) 2011 The Android Open Source Project\n"
1820    " *\n"
1821    " * Licensed under the Apache License, Version 2.0 (the \"License\");\n"
1822    " * you may not use this file except in compliance with the License.\n"
1823    " * You may obtain a copy of the License at\n"
1824    " *\n"
1825    " *      http://www.apache.org/licenses/LICENSE-2.0\n"
1826    " *\n"
1827    " * Unless required by applicable law or agreed to in writing, software\n"
1828    " * distributed under the License is distributed on an \"AS IS\" BASIS,\n"
1829    " * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or "
1830    "implied.\n"
1831    " * See the License for the specific language governing permissions and\n"
1832    " * limitations under the License.\n"
1833    " */\n"
1834    "\n";
1835
1836const char *const RSReflection::Context::Import[] = {
1837  // RenderScript java class
1838  "android.renderscript.*",
1839  // Import R
1840  "android.content.res.Resources",
1841  // Import for debugging
1842  // "android.util.Log",
1843};
1844
1845bool RSReflection::Context::openClassFile(const std::string &ClassName,
1846                                          std::string &ErrorMsg) {
1847  if (!mUseStdout) {
1848    mOF.clear();
1849    std::string Path =
1850        RSSlangReflectUtils::ComputePackagedPath(mOutputPathBase.c_str(),
1851                                                 mPackageName.c_str());
1852
1853    if (!SlangUtils::CreateDirectoryWithParents(Path, &ErrorMsg))
1854      return false;
1855
1856    std::string ClassFile = Path + "/" + ClassName + ".java";
1857
1858    mOF.open(ClassFile.c_str());
1859    if (!mOF.good()) {
1860      ErrorMsg = "failed to open file '" + ClassFile + "' for write";
1861      return false;
1862    }
1863  }
1864  return true;
1865}
1866
1867const char *RSReflection::Context::AccessModifierStr(AccessModifier AM) {
1868  switch (AM) {
1869    case AM_Public: return "public"; break;
1870    case AM_Protected: return "protected"; break;
1871    case AM_Private: return "private"; break;
1872    default: return ""; break;
1873  }
1874}
1875
1876bool RSReflection::Context::startClass(AccessModifier AM,
1877                                       bool IsStatic,
1878                                       const std::string &ClassName,
1879                                       const char *SuperClassName,
1880                                       std::string &ErrorMsg) {
1881  if (mVerbose)
1882    std::cout << "Generating " << ClassName << ".java ..." << std::endl;
1883
1884  // Open file for class
1885  if (!openClassFile(ClassName, ErrorMsg))
1886    return false;
1887
1888  // License
1889  out() << mLicenseNote;
1890
1891  // Notice of generated file
1892  out() << "/*" << std::endl;
1893  out() << " * This file is auto-generated. DO NOT MODIFY!" << std::endl;
1894  out() << " * The source RenderScript file: " << mInputRSFile << std::endl;
1895  out() << " */" << std::endl;
1896
1897  // Package
1898  if (!mPackageName.empty())
1899    out() << "package " << mPackageName << ";" << std::endl;
1900  out() << std::endl;
1901
1902  // Imports
1903  for (unsigned i = 0; i < (sizeof(Import) / sizeof(const char*)); i++)
1904    out() << "import " << Import[i] << ";" << std::endl;
1905  out() << std::endl;
1906
1907  // All reflected classes should be annotated as hidden, so that they won't
1908  // be exposed in SDK.
1909  out() << "/**" << std::endl;
1910  out() << " * @hide" << std::endl;
1911  out() << " */" << std::endl;
1912
1913  out() << AccessModifierStr(AM) << ((IsStatic) ? " static" : "") << " class "
1914        << ClassName;
1915  if (SuperClassName != NULL)
1916    out() << " extends " << SuperClassName;
1917
1918  startBlock();
1919
1920  mClassName = ClassName;
1921
1922  return true;
1923}
1924
1925void RSReflection::Context::endClass() {
1926  endBlock();
1927  if (!mUseStdout)
1928    mOF.close();
1929  clear();
1930  return;
1931}
1932
1933void RSReflection::Context::startBlock(bool ShouldIndent) {
1934  if (ShouldIndent)
1935    indent() << "{" << std::endl;
1936  else
1937    out() << " {" << std::endl;
1938  incIndentLevel();
1939  return;
1940}
1941
1942void RSReflection::Context::endBlock() {
1943  decIndentLevel();
1944  indent() << "}" << std::endl << std::endl;
1945  return;
1946}
1947
1948void RSReflection::Context::startTypeClass(const std::string &ClassName) {
1949  indent() << "public static class " << ClassName;
1950  startBlock();
1951  return;
1952}
1953
1954void RSReflection::Context::endTypeClass() {
1955  endBlock();
1956  return;
1957}
1958
1959void RSReflection::Context::startFunction(AccessModifier AM,
1960                                          bool IsStatic,
1961                                          const char *ReturnType,
1962                                          const std::string &FunctionName,
1963                                          int Argc, ...) {
1964  ArgTy Args;
1965  va_list vl;
1966  va_start(vl, Argc);
1967
1968  for (int i = 0; i < Argc; i++) {
1969    const char *ArgType = va_arg(vl, const char*);
1970    const char *ArgName = va_arg(vl, const char*);
1971
1972    Args.push_back(std::make_pair(ArgType, ArgName));
1973  }
1974  va_end(vl);
1975
1976  startFunction(AM, IsStatic, ReturnType, FunctionName, Args);
1977
1978  return;
1979}
1980
1981void RSReflection::Context::startFunction(AccessModifier AM,
1982                                          bool IsStatic,
1983                                          const char *ReturnType,
1984                                          const std::string &FunctionName,
1985                                          const ArgTy &Args) {
1986  indent() << AccessModifierStr(AM) << ((IsStatic) ? " static " : " ")
1987           << ((ReturnType) ? ReturnType : "") << " " << FunctionName << "(";
1988
1989  bool FirstArg = true;
1990  for (ArgTy::const_iterator I = Args.begin(), E = Args.end();
1991       I != E;
1992       I++) {
1993    if (!FirstArg)
1994      out() << ", ";
1995    else
1996      FirstArg = false;
1997
1998    out() << I->first << " " << I->second;
1999  }
2000
2001  out() << ")";
2002  startBlock();
2003
2004  return;
2005}
2006
2007void RSReflection::Context::endFunction() {
2008  endBlock();
2009  return;
2010}
2011
2012}  // namespace slang
2013