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