slang_rs_reflection.cpp revision db6dfdfcb7e8183f1c796475e5098ee4be80b5b8
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          slangAssert(false && "Unexpected type of value of initializer.");
819        }
820      }
821      break;
822    }
823    // TODO(zonr): Resolving initializer of a record (and matrix) type variable
824    // is complex. It cannot obtain by just simply evaluating the initializer
825    // expression.
826    case RSExportType::ExportClassMatrix:
827    case RSExportType::ExportClassConstantArray:
828    case RSExportType::ExportClassRecord: {
829#if 0
830      unsigned InitIndex = 0;
831      const RSExportRecordType *ERT =
832          static_cast<const RSExportRecordType*>(ET);
833
834      slangAssert((Val.getKind() == clang::APValue::Vector) &&
835          "Unexpected type of initializer for record type variable");
836
837      C.indent() << RS_EXPORT_VAR_PREFIX << VarName
838                 << " = new "RS_TYPE_CLASS_NAME_PREFIX << ERT->getName()
839                 <<  "."RS_TYPE_ITEM_CLASS_NAME"();" << std::endl;
840
841      for (RSExportRecordType::const_field_iterator I = ERT->fields_begin(),
842               E = ERT->fields_end();
843           I != E;
844           I++) {
845        const RSExportRecordType::Field *F = *I;
846        std::string FieldName = VarName + "." + F->getName();
847
848        if (InitIndex > Val.getVectorLength())
849          break;
850
851        genInitPrimitiveExportVariable(C,
852                                       FieldName,
853                                       Val.getVectorElt(InitIndex++));
854      }
855#endif
856      slangAssert(false && "Unsupported initializer for record/matrix/constant "
857                           "array type variable currently");
858      break;
859    }
860    default: {
861      slangAssert(false && "Unknown class of type");
862    }
863  }
864  return;
865}
866
867void RSReflection::genExportVariable(Context &C, const RSExportVar *EV) {
868  const RSExportType *ET = EV->getType();
869
870  C.indent() << "private final static int "RS_EXPORT_VAR_INDEX_PREFIX
871             << EV->getName() << " = " << C.getNextExportVarSlot() << ";"
872             << std::endl;
873
874  switch (ET->getClass()) {
875    case RSExportType::ExportClassPrimitive: {
876      genPrimitiveTypeExportVariable(C, EV);
877      break;
878    }
879    case RSExportType::ExportClassPointer: {
880      genPointerTypeExportVariable(C, EV);
881      break;
882    }
883    case RSExportType::ExportClassVector: {
884      genVectorTypeExportVariable(C, EV);
885      break;
886    }
887    case RSExportType::ExportClassMatrix: {
888      genMatrixTypeExportVariable(C, EV);
889      break;
890    }
891    case RSExportType::ExportClassConstantArray: {
892      genConstantArrayTypeExportVariable(C, EV);
893      break;
894    }
895    case RSExportType::ExportClassRecord: {
896      genRecordTypeExportVariable(C, EV);
897      break;
898    }
899    default: {
900      slangAssert(false && "Unknown class of type");
901    }
902  }
903
904  return;
905}
906
907void RSReflection::genExportFunction(Context &C, const RSExportFunc *EF) {
908  C.indent() << "private final static int "RS_EXPORT_FUNC_INDEX_PREFIX
909             << EF->getName() << " = " << C.getNextExportFuncSlot() << ";"
910             << std::endl;
911
912  // invoke_*()
913  Context::ArgTy Args;
914
915  if (EF->hasParam()) {
916    for (RSExportFunc::const_param_iterator I = EF->params_begin(),
917             E = EF->params_end();
918         I != E;
919         I++) {
920      Args.push_back(std::make_pair(GetTypeName((*I)->getType()),
921                                    (*I)->getName()));
922    }
923  }
924
925  C.startFunction(Context::AM_Public,
926                  false,
927                  "void",
928                  "invoke_" + EF->getName(/*Mangle=*/ false),
929                      // We are using un-mangled name since Java
930                      // supports method overloading.
931                  Args);
932
933  if (!EF->hasParam()) {
934    C.indent() << "invoke("RS_EXPORT_FUNC_INDEX_PREFIX << EF->getName() << ");"
935               << std::endl;
936  } else {
937    const RSExportRecordType *ERT = EF->getParamPacketType();
938    std::string FieldPackerName = EF->getName() + "_fp";
939
940    if (genCreateFieldPacker(C, ERT, FieldPackerName.c_str()))
941      genPackVarOfType(C, ERT, NULL, FieldPackerName.c_str());
942
943    C.indent() << "invoke("RS_EXPORT_FUNC_INDEX_PREFIX << EF->getName() << ", "
944               << FieldPackerName << ");" << std::endl;
945  }
946
947  C.endFunction();
948  return;
949}
950
951void RSReflection::genExportForEach(Context &C, const RSExportForEach *EF) {
952  C.indent() << "private final static int "RS_EXPORT_FOREACH_INDEX_PREFIX
953             << EF->getName() << " = " << C.getNextExportForEachSlot() << ";"
954             << std::endl;
955
956  // forEach_*()
957  Context::ArgTy Args;
958
959  slangAssert(EF->getNumParameters() > 0);
960
961  if (EF->hasIn())
962    Args.push_back(std::make_pair("Allocation", "ain"));
963  if (EF->hasOut())
964    Args.push_back(std::make_pair("Allocation", "aout"));
965
966  const RSExportRecordType *ERT = EF->getParamPacketType();
967  if (ERT) {
968    for (RSExportForEach::const_param_iterator I = EF->params_begin(),
969             E = EF->params_end();
970         I != E;
971         I++) {
972      Args.push_back(std::make_pair(GetTypeName((*I)->getType()),
973                                    (*I)->getName()));
974    }
975  }
976
977  C.startFunction(Context::AM_Public,
978                  false,
979                  "void",
980                  "forEach_" + EF->getName(),
981                  Args);
982
983  const RSExportType *IET = EF->getInType();
984  if (IET) {
985    genTypeCheck(C, IET, "ain");
986  }
987
988  const RSExportType *OET = EF->getOutType();
989  if (OET) {
990    genTypeCheck(C, OET, "aout");
991  }
992
993  if (EF->hasIn() && EF->hasOut()) {
994    C.indent() << "// Verify dimensions" << std::endl;
995    C.indent() << "Type tIn = ain.getType();" << std::endl;
996    C.indent() << "Type tOut = aout.getType();" << std::endl;
997    C.indent() << "if ((tIn.getCount() != tOut.getCount()) ||" << std::endl;
998    C.indent() << "    (tIn.getX() != tOut.getX()) ||" << std::endl;
999    C.indent() << "    (tIn.getY() != tOut.getY()) ||" << std::endl;
1000    C.indent() << "    (tIn.getZ() != tOut.getZ()) ||" << std::endl;
1001    C.indent() << "    (tIn.hasFaces() != tOut.hasFaces()) ||" << std::endl;
1002    C.indent() << "    (tIn.hasMipmaps() != tOut.hasMipmaps())) {" << std::endl;
1003    C.indent() << "    throw new RSRuntimeException(\"Dimension mismatch "
1004               << "between input and output parameters!\");";
1005    C.out()    << std::endl;
1006    C.indent() << "}" << std::endl;
1007  }
1008
1009  std::string FieldPackerName = EF->getName() + "_fp";
1010  if (ERT) {
1011    if (genCreateFieldPacker(C, ERT, FieldPackerName.c_str())) {
1012      genPackVarOfType(C, ERT, NULL, FieldPackerName.c_str());
1013    }
1014  }
1015  C.indent() << "forEach("RS_EXPORT_FOREACH_INDEX_PREFIX << EF->getName();
1016
1017  if (EF->hasIn())
1018    C.out() << ", ain";
1019  else
1020    C.out() << ", null";
1021
1022  if (EF->hasOut())
1023    C.out() << ", aout";
1024  else
1025    C.out() << ", null";
1026
1027  if (EF->hasUsrData())
1028    C.out() << ", " << FieldPackerName;
1029  else
1030    C.out() << ", null";
1031
1032  C.out() << ");" << std::endl;
1033
1034  C.endFunction();
1035  return;
1036}
1037
1038void RSReflection::genTypeInstance(Context &C,
1039                                   const RSExportType *ET) {
1040  if (ET->getClass() == RSExportType::ExportClassPointer) {
1041    const RSExportPointerType *EPT =
1042        static_cast<const RSExportPointerType*>(ET);
1043    ET = EPT->getPointeeType();
1044    switch (ET->getClass()) {
1045      case RSExportType::ExportClassPrimitive: {
1046        const RSExportPrimitiveType *EPT =
1047            static_cast<const RSExportPrimitiveType*>(ET);
1048        slangAssert(EPT);
1049
1050        switch (EPT->getKind()) {
1051          case RSExportPrimitiveType::DataKindPixelL:
1052          case RSExportPrimitiveType::DataKindPixelA:
1053          case RSExportPrimitiveType::DataKindPixelLA:
1054          case RSExportPrimitiveType::DataKindPixelRGB:
1055          case RSExportPrimitiveType::DataKindPixelRGBA: {
1056            break;
1057          }
1058
1059          case RSExportPrimitiveType::DataKindUser:
1060          default: {
1061            std::string TypeName = GetElementJavaTypeName(EPT->getType());
1062            if (C.mTypesToCheck.find(TypeName) == C.mTypesToCheck.end()) {
1063              C.indent() << "__" << TypeName << " = Element." << TypeName
1064                         << "(rs);" << std::endl;
1065              C.mTypesToCheck.insert(TypeName);
1066            }
1067            break;
1068          }
1069        }
1070        break;
1071      }
1072
1073      case RSExportType::ExportClassVector: {
1074        const RSExportVectorType *EVT =
1075            static_cast<const RSExportVectorType*>(ET);
1076        slangAssert(EVT);
1077
1078        const char *TypeName = GetVectorElementName(EVT);
1079        if (C.mTypesToCheck.find(TypeName) == C.mTypesToCheck.end()) {
1080          C.indent() << "__" << TypeName << " = Element." << TypeName
1081                     << "(rs);" << std::endl;
1082          C.mTypesToCheck.insert(TypeName);
1083        }
1084        break;
1085      }
1086
1087      case RSExportType::ExportClassRecord: {
1088        const RSExportRecordType *ERT =
1089            static_cast<const RSExportRecordType*>(ET);
1090        slangAssert(ERT);
1091
1092        std::string ClassName = RS_TYPE_CLASS_NAME_PREFIX + ERT->getName();
1093        if (C.mTypesToCheck.find(ClassName) == C.mTypesToCheck.end()) {
1094          C.indent() << "__" << ClassName << " = " << ClassName <<
1095                        ".createElement(rs);" << std::endl;
1096          C.mTypesToCheck.insert(ClassName);
1097        }
1098        break;
1099      }
1100
1101      default:
1102        break;
1103    }
1104  }
1105}
1106
1107void RSReflection::genTypeCheck(Context &C,
1108                                const RSExportType *ET,
1109                                const char *VarName) {
1110  C.indent() << "// check " << VarName << std::endl;
1111
1112  if (ET->getClass() == RSExportType::ExportClassPointer) {
1113    const RSExportPointerType *EPT =
1114        static_cast<const RSExportPointerType*>(ET);
1115    ET = EPT->getPointeeType();
1116  }
1117
1118  std::string TypeName;
1119
1120  switch (ET->getClass()) {
1121    case RSExportType::ExportClassPrimitive: {
1122      const RSExportPrimitiveType *EPT =
1123          static_cast<const RSExportPrimitiveType*>(ET);
1124      slangAssert(EPT);
1125
1126      if (EPT->getKind() == RSExportPrimitiveType::DataKindUser) {
1127        TypeName = GetElementJavaTypeName(EPT->getType());
1128      }
1129      break;
1130    }
1131
1132    case RSExportType::ExportClassVector: {
1133      const RSExportVectorType *EVT =
1134          static_cast<const RSExportVectorType*>(ET);
1135      slangAssert(EVT);
1136      TypeName = GetVectorElementName(EVT);
1137      break;
1138    }
1139
1140    case RSExportType::ExportClassRecord: {
1141      const RSExportRecordType *ERT =
1142          static_cast<const RSExportRecordType*>(ET);
1143      slangAssert(ERT);
1144      TypeName = RS_TYPE_CLASS_NAME_PREFIX + ERT->getName();
1145      break;
1146    }
1147
1148    default:
1149      break;
1150  }
1151
1152  if (!TypeName.empty()) {
1153    C.indent() << "if (!" << VarName
1154               << ".getType().getElement().isCompatible(__"
1155               << TypeName << ")) {" << std::endl;
1156    C.indent() << "    throw new RSRuntimeException(\"Type mismatch with "
1157               << TypeName << "!\");" << std::endl;
1158    C.indent() << "}" << std::endl;
1159  }
1160
1161  return;
1162}
1163
1164
1165void RSReflection::genPrimitiveTypeExportVariable(
1166    Context &C,
1167    const RSExportVar *EV) {
1168  slangAssert((EV->getType()->getClass() == RSExportType::ExportClassPrimitive)
1169              && "Variable should be type of primitive here");
1170
1171  const RSExportPrimitiveType *EPT =
1172      static_cast<const RSExportPrimitiveType*>(EV->getType());
1173  const char *TypeName = GetPrimitiveTypeName(EPT);
1174
1175  C.indent() << "private " << TypeName << " "RS_EXPORT_VAR_PREFIX
1176             << EV->getName() << ";" << std::endl;
1177
1178  // set_*()
1179  if (!EV->isConst()) {
1180    C.startFunction(Context::AM_Public,
1181                    false,
1182                    "void",
1183                    "set_" + EV->getName(),
1184                    1,
1185                    TypeName, "v");
1186    C.indent() << RS_EXPORT_VAR_PREFIX << EV->getName() << " = v;" << std::endl;
1187
1188    C.indent() << "setVar("RS_EXPORT_VAR_INDEX_PREFIX << EV->getName()
1189               << ", v);" << std::endl;
1190
1191    C.endFunction();
1192  }
1193
1194  genGetExportVariable(C, TypeName, EV->getName());
1195
1196  return;
1197}
1198
1199void RSReflection::genPointerTypeExportVariable(Context &C,
1200                                                const RSExportVar *EV) {
1201  const RSExportType *ET = EV->getType();
1202  const RSExportType *PointeeType;
1203  std::string TypeName;
1204
1205  slangAssert((ET->getClass() == RSExportType::ExportClassPointer) &&
1206              "Variable should be type of pointer here");
1207
1208  PointeeType = static_cast<const RSExportPointerType*>(ET)->getPointeeType();
1209  TypeName = GetTypeName(ET);
1210
1211  C.indent() << "private " << TypeName << " "RS_EXPORT_VAR_PREFIX
1212             << EV->getName() << ";" << std::endl;
1213
1214  // bind_*()
1215  C.startFunction(Context::AM_Public,
1216                  false,
1217                  "void",
1218                  "bind_" + EV->getName(),
1219                  1,
1220                  TypeName.c_str(), "v");
1221
1222  C.indent() << RS_EXPORT_VAR_PREFIX << EV->getName() << " = v;" << std::endl;
1223  C.indent() << "if (v == null) bindAllocation(null, "RS_EXPORT_VAR_INDEX_PREFIX
1224             << EV->getName() << ");" << std::endl;
1225
1226  if (PointeeType->getClass() == RSExportType::ExportClassRecord)
1227    C.indent() << "else bindAllocation(v.getAllocation(), "
1228        RS_EXPORT_VAR_INDEX_PREFIX << EV->getName() << ");"
1229               << std::endl;
1230  else
1231    C.indent() << "else bindAllocation(v, "RS_EXPORT_VAR_INDEX_PREFIX
1232               << EV->getName() << ");" << std::endl;
1233
1234  C.endFunction();
1235
1236  genGetExportVariable(C, TypeName, EV->getName());
1237
1238  return;
1239}
1240
1241void RSReflection::genVectorTypeExportVariable(Context &C,
1242                                               const RSExportVar *EV) {
1243  slangAssert((EV->getType()->getClass() == RSExportType::ExportClassVector) &&
1244              "Variable should be type of vector here");
1245
1246  const RSExportVectorType *EVT =
1247      static_cast<const RSExportVectorType*>(EV->getType());
1248  const char *TypeName = GetVectorTypeName(EVT);
1249  const char *FieldPackerName = "fp";
1250
1251  C.indent() << "private " << TypeName << " "RS_EXPORT_VAR_PREFIX
1252             << EV->getName() << ";" << std::endl;
1253
1254  // set_*()
1255  if (!EV->isConst()) {
1256    C.startFunction(Context::AM_Public,
1257                    false,
1258                    "void",
1259                    "set_" + EV->getName(),
1260                    1,
1261                    TypeName, "v");
1262    C.indent() << RS_EXPORT_VAR_PREFIX << EV->getName() << " = v;" << std::endl;
1263
1264    if (genCreateFieldPacker(C, EVT, FieldPackerName))
1265      genPackVarOfType(C, EVT, "v", FieldPackerName);
1266    C.indent() << "setVar("RS_EXPORT_VAR_INDEX_PREFIX << EV->getName() << ", "
1267               << FieldPackerName << ");" << std::endl;
1268
1269    C.endFunction();
1270  }
1271
1272  genGetExportVariable(C, TypeName, EV->getName());
1273  return;
1274}
1275
1276void RSReflection::genMatrixTypeExportVariable(Context &C,
1277                                               const RSExportVar *EV) {
1278  slangAssert((EV->getType()->getClass() == RSExportType::ExportClassMatrix) &&
1279              "Variable should be type of matrix here");
1280
1281  const RSExportMatrixType *EMT =
1282      static_cast<const RSExportMatrixType*>(EV->getType());
1283  const char *TypeName = GetMatrixTypeName(EMT);
1284  const char *FieldPackerName = "fp";
1285
1286  C.indent() << "private " << TypeName << " "RS_EXPORT_VAR_PREFIX
1287             << EV->getName() << ";" << std::endl;
1288
1289  // set_*()
1290  if (!EV->isConst()) {
1291    C.startFunction(Context::AM_Public,
1292                    false,
1293                    "void",
1294                    "set_" + EV->getName(),
1295                    1,
1296                    TypeName, "v");
1297    C.indent() << RS_EXPORT_VAR_PREFIX << EV->getName() << " = v;" << std::endl;
1298
1299    if (genCreateFieldPacker(C, EMT, FieldPackerName))
1300      genPackVarOfType(C, EMT, "v", FieldPackerName);
1301    C.indent() << "setVar("RS_EXPORT_VAR_INDEX_PREFIX << EV->getName() << ", "
1302               << FieldPackerName << ");" << std::endl;
1303
1304    C.endFunction();
1305  }
1306
1307  genGetExportVariable(C, TypeName, EV->getName());
1308  return;
1309}
1310
1311void RSReflection::genConstantArrayTypeExportVariable(
1312    Context &C,
1313    const RSExportVar *EV) {
1314  slangAssert((EV->getType()->getClass() ==
1315               RSExportType::ExportClassConstantArray) &&
1316              "Variable should be type of constant array here");
1317
1318  const RSExportConstantArrayType *ECAT =
1319      static_cast<const RSExportConstantArrayType*>(EV->getType());
1320  std::string TypeName = GetTypeName(ECAT);
1321  const char *FieldPackerName = "fp";
1322
1323  C.indent() << "private " << TypeName << " "RS_EXPORT_VAR_PREFIX
1324             << EV->getName() << ";" << std::endl;
1325
1326  // set_*()
1327  if (!EV->isConst()) {
1328    C.startFunction(Context::AM_Public,
1329                    false,
1330                    "void",
1331                    "set_" + EV->getName(),
1332                    1,
1333                    TypeName.c_str(), "v");
1334    C.indent() << RS_EXPORT_VAR_PREFIX << EV->getName() << " = v;" << std::endl;
1335
1336    if (genCreateFieldPacker(C, ECAT, FieldPackerName))
1337      genPackVarOfType(C, ECAT, "v", FieldPackerName);
1338    C.indent() << "setVar("RS_EXPORT_VAR_INDEX_PREFIX << EV->getName() << ", "
1339               << FieldPackerName << ");" << std::endl;
1340
1341    C.endFunction();
1342  }
1343
1344  genGetExportVariable(C, TypeName, EV->getName());
1345  return;
1346}
1347
1348void RSReflection::genRecordTypeExportVariable(Context &C,
1349                                               const RSExportVar *EV) {
1350  slangAssert((EV->getType()->getClass() == RSExportType::ExportClassRecord) &&
1351              "Variable should be type of struct here");
1352
1353  const RSExportRecordType *ERT =
1354      static_cast<const RSExportRecordType*>(EV->getType());
1355  std::string TypeName =
1356      RS_TYPE_CLASS_NAME_PREFIX + ERT->getName() + "."RS_TYPE_ITEM_CLASS_NAME;
1357  const char *FieldPackerName = "fp";
1358
1359  C.indent() << "private " << TypeName << " "RS_EXPORT_VAR_PREFIX
1360             << EV->getName() << ";" << std::endl;
1361
1362  // set_*()
1363  if (!EV->isConst()) {
1364    C.startFunction(Context::AM_Public,
1365                    false,
1366                    "void",
1367                    "set_" + EV->getName(),
1368                    1,
1369                    TypeName.c_str(), "v");
1370    C.indent() << RS_EXPORT_VAR_PREFIX << EV->getName() << " = v;" << std::endl;
1371
1372    if (genCreateFieldPacker(C, ERT, FieldPackerName))
1373      genPackVarOfType(C, ERT, "v", FieldPackerName);
1374    C.indent() << "setVar("RS_EXPORT_VAR_INDEX_PREFIX << EV->getName()
1375               << ", " << FieldPackerName << ");" << std::endl;
1376
1377    C.endFunction();
1378  }
1379
1380  genGetExportVariable(C, TypeName.c_str(), EV->getName());
1381  return;
1382}
1383
1384void RSReflection::genGetExportVariable(Context &C,
1385                                        const std::string &TypeName,
1386                                        const std::string &VarName) {
1387  C.startFunction(Context::AM_Public,
1388                  false,
1389                  TypeName.c_str(),
1390                  "get_" + VarName,
1391                  0);
1392
1393  C.indent() << "return "RS_EXPORT_VAR_PREFIX << VarName << ";" << std::endl;
1394
1395  C.endFunction();
1396  return;
1397}
1398
1399/******************* Methods to generate script class /end *******************/
1400
1401bool RSReflection::genCreateFieldPacker(Context &C,
1402                                        const RSExportType *ET,
1403                                        const char *FieldPackerName) {
1404  size_t AllocSize = RSExportType::GetTypeAllocSize(ET);
1405  if (AllocSize > 0)
1406    C.indent() << "FieldPacker " << FieldPackerName << " = new FieldPacker("
1407               << AllocSize << ");" << std::endl;
1408  else
1409    return false;
1410  return true;
1411}
1412
1413void RSReflection::genPackVarOfType(Context &C,
1414                                    const RSExportType *ET,
1415                                    const char *VarName,
1416                                    const char *FieldPackerName) {
1417  switch (ET->getClass()) {
1418    case RSExportType::ExportClassPrimitive:
1419    case RSExportType::ExportClassVector: {
1420      C.indent() << FieldPackerName << "."
1421                 << GetPackerAPIName(
1422                     static_cast<const RSExportPrimitiveType*>(ET))
1423                 << "(" << VarName << ");" << std::endl;
1424      break;
1425    }
1426    case RSExportType::ExportClassPointer: {
1427      // Must reflect as type Allocation in Java
1428      const RSExportType *PointeeType =
1429          static_cast<const RSExportPointerType*>(ET)->getPointeeType();
1430
1431      if (PointeeType->getClass() != RSExportType::ExportClassRecord)
1432        C.indent() << FieldPackerName << ".addI32(" << VarName
1433                   << ".getPtr());" << std::endl;
1434      else
1435        C.indent() << FieldPackerName << ".addI32(" << VarName
1436                   << ".getAllocation().getPtr());" << std::endl;
1437      break;
1438    }
1439    case RSExportType::ExportClassMatrix: {
1440      C.indent() << FieldPackerName << ".addMatrix(" << VarName << ");"
1441                 << std::endl;
1442      break;
1443    }
1444    case RSExportType::ExportClassConstantArray: {
1445      const RSExportConstantArrayType *ECAT =
1446          static_cast<const RSExportConstantArrayType *>(ET);
1447
1448      // TODO(zonr): more elegant way. Currently, we obtain the unique index
1449      //             variable (this method involves recursive call which means
1450      //             we may have more than one level loop, therefore we can't
1451      //             always use the same index variable name here) name given
1452      //             in the for-loop from counting the '.' in @VarName.
1453      unsigned Level = 0;
1454      size_t LastDotPos = 0;
1455      std::string ElementVarName(VarName);
1456
1457      while (LastDotPos != std::string::npos) {
1458        LastDotPos = ElementVarName.find_first_of('.', LastDotPos + 1);
1459        Level++;
1460      }
1461      std::string IndexVarName("ct");
1462      IndexVarName.append(llvm::utostr_32(Level));
1463
1464      C.indent() << "for (int " << IndexVarName << " = 0; " <<
1465                          IndexVarName << " < " << ECAT->getSize() << "; " <<
1466                          IndexVarName << "++)";
1467      C.startBlock();
1468
1469      ElementVarName.append("[" + IndexVarName + "]");
1470      genPackVarOfType(C, ECAT->getElementType(), ElementVarName.c_str(),
1471                       FieldPackerName);
1472
1473      C.endBlock();
1474      break;
1475    }
1476    case RSExportType::ExportClassRecord: {
1477      const RSExportRecordType *ERT =
1478          static_cast<const RSExportRecordType*>(ET);
1479      // Relative pos from now on in field packer
1480      unsigned Pos = 0;
1481
1482      for (RSExportRecordType::const_field_iterator I = ERT->fields_begin(),
1483               E = ERT->fields_end();
1484           I != E;
1485           I++) {
1486        const RSExportRecordType::Field *F = *I;
1487        std::string FieldName;
1488        size_t FieldOffset = F->getOffsetInParent();
1489        size_t FieldStoreSize = RSExportType::GetTypeStoreSize(F->getType());
1490        size_t FieldAllocSize = RSExportType::GetTypeAllocSize(F->getType());
1491
1492        if (VarName != NULL)
1493          FieldName = VarName + ("." + F->getName());
1494        else
1495          FieldName = F->getName();
1496
1497        if (FieldOffset > Pos)
1498          C.indent() << FieldPackerName << ".skip("
1499                     << (FieldOffset - Pos) << ");" << std::endl;
1500
1501        genPackVarOfType(C, F->getType(), FieldName.c_str(), FieldPackerName);
1502
1503        // There is padding in the field type
1504        if (FieldAllocSize > FieldStoreSize)
1505            C.indent() << FieldPackerName << ".skip("
1506                       << (FieldAllocSize - FieldStoreSize)
1507                       << ");" << std::endl;
1508
1509          Pos = FieldOffset + FieldAllocSize;
1510      }
1511
1512      // There maybe some padding after the struct
1513      if (RSExportType::GetTypeAllocSize(ERT) > Pos)
1514        C.indent() << FieldPackerName << ".skip("
1515                   << RSExportType::GetTypeAllocSize(ERT) - Pos << ");"
1516                   << std::endl;
1517      break;
1518    }
1519    default: {
1520      slangAssert(false && "Unknown class of type");
1521    }
1522  }
1523
1524  return;
1525}
1526
1527void RSReflection::genAllocateVarOfType(Context &C,
1528                                        const RSExportType *T,
1529                                        const std::string &VarName) {
1530  switch (T->getClass()) {
1531    case RSExportType::ExportClassPrimitive: {
1532      // Primitive type like int in Java has its own storage once it's declared.
1533      //
1534      // FIXME: Should we allocate storage for RS object?
1535      // if (static_cast<const RSExportPrimitiveType *>(T)->isRSObjectType())
1536      //  C.indent() << VarName << " = new " << GetTypeName(T) << "();"
1537      //             << std::endl;
1538      break;
1539    }
1540    case RSExportType::ExportClassPointer: {
1541      // Pointer type is an instance of Allocation or a TypeClass whose value is
1542      // expected to be assigned by programmer later in Java program. Therefore
1543      // we don't reflect things like [VarName] = new Allocation();
1544      C.indent() << VarName << " = null;" << std::endl;
1545      break;
1546    }
1547    case RSExportType::ExportClassConstantArray: {
1548      const RSExportConstantArrayType *ECAT =
1549          static_cast<const RSExportConstantArrayType *>(T);
1550      const RSExportType *ElementType = ECAT->getElementType();
1551
1552      C.indent() << VarName << " = new " << GetTypeName(ElementType)
1553                 << "[" << ECAT->getSize() << "];" << std::endl;
1554
1555      // Primitive type element doesn't need allocation code.
1556      if (ElementType->getClass() != RSExportType::ExportClassPrimitive) {
1557        C.indent() << "for (int $ct = 0; $ct < " << ECAT->getSize() << "; "
1558                            "$ct++)";
1559        C.startBlock();
1560
1561        std::string ElementVarName(VarName);
1562        ElementVarName.append("[$ct]");
1563        genAllocateVarOfType(C, ElementType, ElementVarName);
1564
1565        C.endBlock();
1566      }
1567      break;
1568    }
1569    case RSExportType::ExportClassVector:
1570    case RSExportType::ExportClassMatrix:
1571    case RSExportType::ExportClassRecord: {
1572      C.indent() << VarName << " = new " << GetTypeName(T) << "();"
1573                 << std::endl;
1574      break;
1575    }
1576  }
1577  return;
1578}
1579
1580void RSReflection::genNewItemBufferIfNull(Context &C,
1581                                          const char *Index) {
1582  C.indent() << "if (" RS_TYPE_ITEM_BUFFER_NAME " == null) "
1583                  RS_TYPE_ITEM_BUFFER_NAME " = "
1584                    "new " RS_TYPE_ITEM_CLASS_NAME
1585                      "[getType().getX() /* count */];"
1586             << std::endl;
1587  if (Index != NULL)
1588    C.indent() << "if ("RS_TYPE_ITEM_BUFFER_NAME"[" << Index << "] == null) "
1589                    RS_TYPE_ITEM_BUFFER_NAME"[" << Index << "] = "
1590                      "new "RS_TYPE_ITEM_CLASS_NAME"();" << std::endl;
1591  return;
1592}
1593
1594void RSReflection::genNewItemBufferPackerIfNull(Context &C) {
1595  C.indent() << "if (" RS_TYPE_ITEM_BUFFER_PACKER_NAME " == null) "
1596                  RS_TYPE_ITEM_BUFFER_PACKER_NAME " = "
1597                    "new FieldPacker(" RS_TYPE_ITEM_CLASS_NAME
1598                      ".sizeof * getType().getX()/* count */"
1599                        ");" << std::endl;
1600  return;
1601}
1602
1603/********************** Methods to generate type class  **********************/
1604bool RSReflection::genTypeClass(Context &C,
1605                                const RSExportRecordType *ERT,
1606                                std::string &ErrorMsg) {
1607  std::string ClassName = RS_TYPE_CLASS_NAME_PREFIX + ERT->getName();
1608
1609  if (!C.startClass(Context::AM_Public,
1610                    false,
1611                    ClassName,
1612                    RS_TYPE_CLASS_SUPER_CLASS_NAME,
1613                    ErrorMsg))
1614    return false;
1615
1616  mGeneratedFileNames->push_back(ClassName);
1617
1618  genTypeItemClass(C, ERT);
1619
1620  // Declare item buffer and item buffer packer
1621  C.indent() << "private "RS_TYPE_ITEM_CLASS_NAME" "RS_TYPE_ITEM_BUFFER_NAME"[]"
1622      ";" << std::endl;
1623  C.indent() << "private FieldPacker "RS_TYPE_ITEM_BUFFER_PACKER_NAME";"
1624             << std::endl;
1625
1626  genTypeClassConstructor(C, ERT);
1627  genTypeClassCopyToArrayLocal(C, ERT);
1628  genTypeClassCopyToArray(C, ERT);
1629  genTypeClassItemSetter(C, ERT);
1630  genTypeClassItemGetter(C, ERT);
1631  genTypeClassComponentSetter(C, ERT);
1632  genTypeClassComponentGetter(C, ERT);
1633  genTypeClassCopyAll(C, ERT);
1634  genTypeClassResize(C);
1635
1636  C.endClass();
1637
1638  C.resetFieldIndex();
1639  C.clearFieldIndexMap();
1640
1641  return true;
1642}
1643
1644void RSReflection::genTypeItemClass(Context &C,
1645                                    const RSExportRecordType *ERT) {
1646  C.indent() << "static public class "RS_TYPE_ITEM_CLASS_NAME;
1647  C.startBlock();
1648
1649  C.indent() << "public static final int sizeof = "
1650             << RSExportType::GetTypeAllocSize(ERT) << ";" << std::endl;
1651
1652  // Member elements
1653  C.out() << std::endl;
1654  for (RSExportRecordType::const_field_iterator FI = ERT->fields_begin(),
1655           FE = ERT->fields_end();
1656       FI != FE;
1657       FI++) {
1658    C.indent() << GetTypeName((*FI)->getType()) << " " << (*FI)->getName()
1659               << ";" << std::endl;
1660  }
1661
1662  // Constructor
1663  C.out() << std::endl;
1664  C.indent() << RS_TYPE_ITEM_CLASS_NAME"()";
1665  C.startBlock();
1666
1667  for (RSExportRecordType::const_field_iterator FI = ERT->fields_begin(),
1668           FE = ERT->fields_end();
1669       FI != FE;
1670       FI++) {
1671    const RSExportRecordType::Field *F = *FI;
1672    genAllocateVarOfType(C, F->getType(), F->getName());
1673  }
1674
1675  // end Constructor
1676  C.endBlock();
1677
1678  // end Item class
1679  C.endBlock();
1680
1681  return;
1682}
1683
1684void RSReflection::genTypeClassConstructor(Context &C,
1685                                           const RSExportRecordType *ERT) {
1686  const char *RenderScriptVar = "rs";
1687
1688  C.startFunction(Context::AM_Public,
1689                  true,
1690                  "Element",
1691                  "createElement",
1692                  1,
1693                  "RenderScript", RenderScriptVar);
1694  genBuildElement(C, "eb", ERT, RenderScriptVar, /* IsInline = */false);
1695  C.endFunction();
1696
1697  C.startFunction(Context::AM_Public,
1698                  false,
1699                  NULL,
1700                  C.getClassName(),
1701                  2,
1702                  "RenderScript", RenderScriptVar,
1703                  "int", "count");
1704
1705  C.indent() << RS_TYPE_ITEM_BUFFER_NAME" = null;" << std::endl;
1706  C.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME" = null;" << std::endl;
1707  C.indent() << "mElement = createElement(" << RenderScriptVar << ");"
1708             << std::endl;
1709  // Call init() in super class
1710  C.indent() << "init(" << RenderScriptVar << ", count);" << std::endl;
1711  C.endFunction();
1712
1713  C.startFunction(Context::AM_Public,
1714                  false,
1715                  NULL,
1716                  C.getClassName(),
1717                  3,
1718                  "RenderScript", RenderScriptVar,
1719                  "int", "count",
1720                  "int", "usages");
1721
1722  C.indent() << RS_TYPE_ITEM_BUFFER_NAME" = null;" << std::endl;
1723  C.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME" = null;" << std::endl;
1724  C.indent() << "mElement = createElement(" << RenderScriptVar << ");"
1725             << std::endl;
1726  // Call init() in super class
1727  C.indent() << "init(" << RenderScriptVar << ", count, usages);" << std::endl;
1728  C.endFunction();
1729
1730  return;
1731}
1732
1733void RSReflection::genTypeClassCopyToArray(Context &C,
1734                                           const RSExportRecordType *ERT) {
1735  C.startFunction(Context::AM_Private,
1736                  false,
1737                  "void",
1738                  "copyToArray",
1739                  2,
1740                  RS_TYPE_ITEM_CLASS_NAME, "i",
1741                  "int", "index");
1742
1743  genNewItemBufferPackerIfNull(C);
1744  C.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME
1745                ".reset(index * "RS_TYPE_ITEM_CLASS_NAME".sizeof);"
1746             << std::endl;
1747
1748  C.indent() << "copyToArrayLocal(i, " RS_TYPE_ITEM_BUFFER_PACKER_NAME
1749                ");" << std::endl;
1750
1751  C.endFunction();
1752  return;
1753}
1754
1755void RSReflection::genTypeClassCopyToArrayLocal(Context &C,
1756                                                const RSExportRecordType *ERT) {
1757  C.startFunction(Context::AM_Private,
1758                  false,
1759                  "void",
1760                  "copyToArrayLocal",
1761                  2,
1762                  RS_TYPE_ITEM_CLASS_NAME, "i",
1763                  "FieldPacker", "fp");
1764
1765  genPackVarOfType(C, ERT, "i", "fp");
1766
1767  C.endFunction();
1768  return;
1769}
1770
1771void RSReflection::genTypeClassItemSetter(Context &C,
1772                                          const RSExportRecordType *ERT) {
1773  C.startFunction(Context::AM_PublicSynchronized,
1774                  false,
1775                  "void",
1776                  "set",
1777                  3,
1778                  RS_TYPE_ITEM_CLASS_NAME, "i",
1779                  "int", "index",
1780                  "boolean", "copyNow");
1781  genNewItemBufferIfNull(C, NULL);
1782  C.indent() << RS_TYPE_ITEM_BUFFER_NAME"[index] = i;" << std::endl;
1783
1784  C.indent() << "if (copyNow) ";
1785  C.startBlock();
1786
1787  C.indent() << "copyToArray(i, index);" << std::endl;
1788  C.indent() << "FieldPacker fp = new FieldPacker(" RS_TYPE_ITEM_CLASS_NAME
1789                ".sizeof);" << std::endl;
1790  C.indent() << "copyToArrayLocal(i, fp);" << std::endl;
1791  C.indent() << "mAllocation.setFromFieldPacker(index, fp);" << std::endl;
1792
1793  // End of if (copyNow)
1794  C.endBlock();
1795
1796  C.endFunction();
1797  return;
1798}
1799
1800void RSReflection::genTypeClassItemGetter(Context &C,
1801                                          const RSExportRecordType *ERT) {
1802  C.startFunction(Context::AM_PublicSynchronized,
1803                  false,
1804                  RS_TYPE_ITEM_CLASS_NAME,
1805                  "get",
1806                  1,
1807                  "int", "index");
1808  C.indent() << "if ("RS_TYPE_ITEM_BUFFER_NAME" == null) return null;"
1809             << std::endl;
1810  C.indent() << "return "RS_TYPE_ITEM_BUFFER_NAME"[index];" << std::endl;
1811  C.endFunction();
1812  return;
1813}
1814
1815void RSReflection::genTypeClassComponentSetter(Context &C,
1816                                               const RSExportRecordType *ERT) {
1817  for (RSExportRecordType::const_field_iterator FI = ERT->fields_begin(),
1818           FE = ERT->fields_end();
1819       FI != FE;
1820       FI++) {
1821    const RSExportRecordType::Field *F = *FI;
1822    size_t FieldOffset = F->getOffsetInParent();
1823    size_t FieldStoreSize = RSExportType::GetTypeStoreSize(F->getType());
1824    unsigned FieldIndex = C.getFieldIndex(F);
1825
1826    C.startFunction(Context::AM_PublicSynchronized,
1827                    false,
1828                    "void",
1829                    "set_" + F->getName(), 3,
1830                    "int", "index",
1831                    GetTypeName(F->getType()).c_str(), "v",
1832                    "boolean", "copyNow");
1833    genNewItemBufferPackerIfNull(C);
1834    genNewItemBufferIfNull(C, "index");
1835    C.indent() << RS_TYPE_ITEM_BUFFER_NAME"[index]." << F->getName()
1836               << " = v;" << std::endl;
1837
1838    C.indent() << "if (copyNow) ";
1839    C.startBlock();
1840
1841    if (FieldOffset > 0)
1842      C.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME
1843                    ".reset(index * "RS_TYPE_ITEM_CLASS_NAME".sizeof + "
1844                 << FieldOffset << ");" << std::endl;
1845    else
1846      C.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME
1847                    ".reset(index * "RS_TYPE_ITEM_CLASS_NAME".sizeof);"
1848                 << std::endl;
1849    genPackVarOfType(C, F->getType(), "v", RS_TYPE_ITEM_BUFFER_PACKER_NAME);
1850
1851    C.indent() << "FieldPacker fp = new FieldPacker(" << FieldStoreSize << ");"
1852               << std::endl;
1853    genPackVarOfType(C, F->getType(), "v", "fp");
1854    C.indent() << "mAllocation.setFromFieldPacker(index, " << FieldIndex
1855               << ", fp);"
1856               << std::endl;
1857
1858    // End of if (copyNow)
1859    C.endBlock();
1860
1861    C.endFunction();
1862  }
1863  return;
1864}
1865
1866void RSReflection::genTypeClassComponentGetter(Context &C,
1867                                               const RSExportRecordType *ERT) {
1868  for (RSExportRecordType::const_field_iterator FI = ERT->fields_begin(),
1869           FE = ERT->fields_end();
1870       FI != FE;
1871       FI++) {
1872    const RSExportRecordType::Field *F = *FI;
1873    C.startFunction(Context::AM_PublicSynchronized,
1874                    false,
1875                    GetTypeName(F->getType()).c_str(),
1876                    "get_" + F->getName(),
1877                    1,
1878                    "int", "index");
1879    C.indent() << "if ("RS_TYPE_ITEM_BUFFER_NAME" == null) return "
1880               << GetTypeNullValue(F->getType()) << ";" << std::endl;
1881    C.indent() << "return "RS_TYPE_ITEM_BUFFER_NAME"[index]." << F->getName()
1882               << ";" << std::endl;
1883    C.endFunction();
1884  }
1885  return;
1886}
1887
1888void RSReflection::genTypeClassCopyAll(Context &C,
1889                                       const RSExportRecordType *ERT) {
1890  C.startFunction(Context::AM_PublicSynchronized, false, "void", "copyAll", 0);
1891
1892  C.indent() << "for (int ct = 0; ct < "RS_TYPE_ITEM_BUFFER_NAME".length; ct++)"
1893                  " copyToArray("RS_TYPE_ITEM_BUFFER_NAME"[ct], ct);"
1894             << std::endl;
1895  C.indent() << "mAllocation.setFromFieldPacker(0, "
1896                  RS_TYPE_ITEM_BUFFER_PACKER_NAME");"
1897             << std::endl;
1898
1899  C.endFunction();
1900  return;
1901}
1902
1903void RSReflection::genTypeClassResize(Context &C) {
1904  C.startFunction(Context::AM_PublicSynchronized,
1905                  false,
1906                  "void",
1907                  "resize",
1908                  1,
1909                  "int", "newSize");
1910
1911  C.indent() << "if (mItemArray != null) ";
1912  C.startBlock();
1913  C.indent() << "int oldSize = mItemArray.length;" << std::endl;
1914  C.indent() << "int copySize = Math.min(oldSize, newSize);" << std::endl;
1915  C.indent() << "if (newSize == oldSize) return;" << std::endl;
1916  C.indent() << "Item ni[] = new Item[newSize];" << std::endl;
1917  C.indent() << "System.arraycopy(mItemArray, 0, ni, 0, copySize);"
1918             << std::endl;
1919  C.indent() << "mItemArray = ni;" << std::endl;
1920  C.endBlock();
1921  C.indent() << "mAllocation.resize(newSize);" << std::endl;
1922
1923  C.indent() << "if (" RS_TYPE_ITEM_BUFFER_PACKER_NAME " != null) "
1924                  RS_TYPE_ITEM_BUFFER_PACKER_NAME " = "
1925                    "new FieldPacker(" RS_TYPE_ITEM_CLASS_NAME
1926                      ".sizeof * getType().getX()/* count */"
1927                        ");" << std::endl;
1928
1929  C.endFunction();
1930  return;
1931}
1932
1933/******************** Methods to generate type class /end ********************/
1934
1935/********** Methods to create Element in Java of given record type ***********/
1936void RSReflection::genBuildElement(Context &C,
1937                                   const char *ElementBuilderName,
1938                                   const RSExportRecordType *ERT,
1939                                   const char *RenderScriptVar,
1940                                   bool IsInline) {
1941  C.indent() << "Element.Builder " << ElementBuilderName << " = "
1942      "new Element.Builder(" << RenderScriptVar << ");" << std::endl;
1943
1944  // eb.add(...)
1945  genAddElementToElementBuilder(C,
1946                                ERT,
1947                                "",
1948                                ElementBuilderName,
1949                                RenderScriptVar,
1950                                /* ArraySize = */0);
1951
1952  if (!IsInline)
1953    C.indent() << "return " << ElementBuilderName << ".create();" << std::endl;
1954  return;
1955}
1956
1957#define EB_ADD(x) do {                                              \
1958  C.indent() << ElementBuilderName                                  \
1959             << ".add(" << x << ", \"" << VarName << "\"";  \
1960  if (ArraySize > 0)                                                \
1961    C.out() << ", " << ArraySize;                                   \
1962  C.out() << ");" << std::endl;                                     \
1963  C.incFieldIndex();                                                \
1964} while (false)
1965
1966void RSReflection::genAddElementToElementBuilder(Context &C,
1967                                                 const RSExportType *ET,
1968                                                 const std::string &VarName,
1969                                                 const char *ElementBuilderName,
1970                                                 const char *RenderScriptVar,
1971                                                 unsigned ArraySize) {
1972  const char *ElementConstruct = GetBuiltinElementConstruct(ET);
1973
1974  if (ElementConstruct != NULL) {
1975    EB_ADD(ElementConstruct << "(" << RenderScriptVar << ")");
1976  } else {
1977    if ((ET->getClass() == RSExportType::ExportClassPrimitive) ||
1978        (ET->getClass() == RSExportType::ExportClassVector)) {
1979      const RSExportPrimitiveType *EPT =
1980          static_cast<const RSExportPrimitiveType*>(ET);
1981      const char *DataKindName = GetElementDataKindName(EPT->getKind());
1982      const char *DataTypeName = GetElementDataTypeName(EPT->getType());
1983      int Size = (ET->getClass() == RSExportType::ExportClassVector) ?
1984          static_cast<const RSExportVectorType*>(ET)->getNumElement() :
1985          1;
1986
1987      switch (EPT->getKind()) {
1988        case RSExportPrimitiveType::DataKindPixelL:
1989        case RSExportPrimitiveType::DataKindPixelA:
1990        case RSExportPrimitiveType::DataKindPixelLA:
1991        case RSExportPrimitiveType::DataKindPixelRGB:
1992        case RSExportPrimitiveType::DataKindPixelRGBA: {
1993          // Element.createPixel()
1994          EB_ADD("Element.createPixel(" << RenderScriptVar << ", "
1995                                        << DataTypeName << ", "
1996                                        << DataKindName << ")");
1997          break;
1998        }
1999        case RSExportPrimitiveType::DataKindUser:
2000        default: {
2001          if (EPT->getClass() == RSExportType::ExportClassPrimitive) {
2002            // Element.createUser()
2003            EB_ADD("Element.createUser(" << RenderScriptVar << ", "
2004                                         << DataTypeName << ")");
2005          } else {
2006            slangAssert((ET->getClass() == RSExportType::ExportClassVector) &&
2007                        "Unexpected type.");
2008            EB_ADD("Element.createVector(" << RenderScriptVar << ", "
2009                                           << DataTypeName << ", "
2010                                           << Size << ")");
2011          }
2012          break;
2013        }
2014      }
2015#ifndef NDEBUG
2016    } else if (ET->getClass() == RSExportType::ExportClassPointer) {
2017      // Pointer type variable should be resolved in
2018      // GetBuiltinElementConstruct()
2019      slangAssert(false && "??");
2020    } else if (ET->getClass() == RSExportType::ExportClassMatrix) {
2021      // Matrix type variable should be resolved
2022      // in GetBuiltinElementConstruct()
2023      slangAssert(false && "??");
2024#endif
2025    } else if (ET->getClass() == RSExportType::ExportClassConstantArray) {
2026      const RSExportConstantArrayType *ECAT =
2027          static_cast<const RSExportConstantArrayType *>(ET);
2028
2029      const RSExportType *ElementType = ECAT->getElementType();
2030      if (ElementType->getClass() != RSExportType::ExportClassRecord) {
2031        genAddElementToElementBuilder(C,
2032                                      ECAT->getElementType(),
2033                                      VarName,
2034                                      ElementBuilderName,
2035                                      RenderScriptVar,
2036                                      ECAT->getSize());
2037      } else {
2038        std::string NewElementBuilderName(ElementBuilderName);
2039        NewElementBuilderName.append(1, '_');
2040
2041        genBuildElement(C,
2042                        NewElementBuilderName.c_str(),
2043                        static_cast<const RSExportRecordType*>(ElementType),
2044                        RenderScriptVar,
2045                        /* IsInline = */true);
2046        ArraySize = ECAT->getSize();
2047        EB_ADD(NewElementBuilderName << ".create()");
2048      }
2049    } else if (ET->getClass() == RSExportType::ExportClassRecord) {
2050      // Simalar to case of RSExportType::ExportClassRecord in genPackVarOfType.
2051      //
2052      // TODO(zonr): Generalize these two function such that there's no
2053      //             duplicated codes.
2054      const RSExportRecordType *ERT =
2055          static_cast<const RSExportRecordType*>(ET);
2056      int Pos = 0;    // relative pos from now on
2057
2058      for (RSExportRecordType::const_field_iterator I = ERT->fields_begin(),
2059               E = ERT->fields_end();
2060           I != E;
2061           I++) {
2062        const RSExportRecordType::Field *F = *I;
2063        std::string FieldName;
2064        int FieldOffset = F->getOffsetInParent();
2065        int FieldStoreSize = RSExportType::GetTypeStoreSize(F->getType());
2066        int FieldAllocSize = RSExportType::GetTypeAllocSize(F->getType());
2067
2068        if (!VarName.empty())
2069          FieldName = VarName + "." + F->getName();
2070        else
2071          FieldName = F->getName();
2072
2073        // Alignment
2074        genAddPaddingToElementBuiler(C,
2075                                     (FieldOffset - Pos),
2076                                     ElementBuilderName,
2077                                     RenderScriptVar);
2078
2079        // eb.add(...)
2080        C.addFieldIndexMapping(F);
2081        if (F->getType()->getClass() != RSExportType::ExportClassRecord) {
2082          genAddElementToElementBuilder(C,
2083                                        F->getType(),
2084                                        FieldName,
2085                                        ElementBuilderName,
2086                                        RenderScriptVar,
2087                                        0);
2088        } else {
2089          std::string NewElementBuilderName(ElementBuilderName);
2090          NewElementBuilderName.append(1, '_');
2091
2092          genBuildElement(C,
2093                          NewElementBuilderName.c_str(),
2094                          static_cast<const RSExportRecordType*>(F->getType()),
2095                          RenderScriptVar,
2096                          /* IsInline = */true);
2097
2098          const std::string &VarName = FieldName;  // Hack for EB_ADD macro
2099          EB_ADD(NewElementBuilderName << ".create()");
2100        }
2101
2102        // There is padding within the field type
2103        genAddPaddingToElementBuiler(C,
2104                                     (FieldAllocSize - FieldStoreSize),
2105                                     ElementBuilderName,
2106                                     RenderScriptVar);
2107
2108        Pos = FieldOffset + FieldAllocSize;
2109      }
2110
2111      // There maybe some padding after the struct
2112      size_t RecordAllocSize = RSExportType::GetTypeAllocSize(ERT);
2113
2114      genAddPaddingToElementBuiler(C,
2115                                   RecordAllocSize - Pos,
2116                                   ElementBuilderName,
2117                                   RenderScriptVar);
2118    } else {
2119      slangAssert(false && "Unknown class of type");
2120    }
2121  }
2122}
2123
2124void RSReflection::genAddPaddingToElementBuiler(Context &C,
2125                                                int PaddingSize,
2126                                                const char *ElementBuilderName,
2127                                                const char *RenderScriptVar) {
2128  unsigned ArraySize = 0;   // Hack the EB_ADD macro
2129  while (PaddingSize > 0) {
2130    const std::string &VarName = C.createPaddingField();
2131    if (PaddingSize >= 4) {
2132      EB_ADD("Element.U32(" << RenderScriptVar << ")");
2133      PaddingSize -= 4;
2134    } else if (PaddingSize >= 2) {
2135      EB_ADD("Element.U16(" << RenderScriptVar << ")");
2136      PaddingSize -= 2;
2137    } else if (PaddingSize >= 1) {
2138      EB_ADD("Element.U8(" << RenderScriptVar << ")");
2139      PaddingSize -= 1;
2140    }
2141  }
2142  return;
2143}
2144
2145#undef EB_ADD
2146/******** Methods to create Element in Java of given record type /end ********/
2147
2148bool RSReflection::reflect(const std::string &OutputPathBase,
2149                           const std::string &OutputPackageName,
2150                           const std::string &InputFileName,
2151                           const std::string &OutputBCFileName) {
2152  Context *C = NULL;
2153  std::string ResourceId = "";
2154
2155  if (!GetClassNameFromFileName(OutputBCFileName, ResourceId))
2156    return false;
2157
2158  if (ResourceId.empty())
2159    ResourceId = "<Resource ID>";
2160
2161  if (OutputPackageName.empty() || OutputPackageName == "-")
2162    C = new Context(OutputPathBase, InputFileName, "<Package Name>",
2163                    ResourceId, true);
2164  else
2165    C = new Context(OutputPathBase, InputFileName, OutputPackageName,
2166                    ResourceId, false);
2167
2168  if (C != NULL) {
2169    std::string ErrorMsg, ScriptClassName;
2170    // class ScriptC_<ScriptName>
2171    if (!GetClassNameFromFileName(InputFileName, ScriptClassName))
2172      return false;
2173
2174    if (ScriptClassName.empty())
2175      ScriptClassName = "<Input Script Name>";
2176
2177    ScriptClassName.insert(0, RS_SCRIPT_CLASS_NAME_PREFIX);
2178
2179    if (mRSContext->getLicenseNote() != NULL) {
2180      C->setLicenseNote(*(mRSContext->getLicenseNote()));
2181    }
2182
2183    if (!genScriptClass(*C, ScriptClassName, ErrorMsg)) {
2184      std::cerr << "Failed to generate class " << ScriptClassName << " ("
2185                << ErrorMsg << ")" << std::endl;
2186      return false;
2187    }
2188
2189    mGeneratedFileNames->push_back(ScriptClassName);
2190
2191    // class ScriptField_<TypeName>
2192    for (RSContext::const_export_type_iterator TI =
2193             mRSContext->export_types_begin(),
2194             TE = mRSContext->export_types_end();
2195         TI != TE;
2196         TI++) {
2197      const RSExportType *ET = TI->getValue();
2198
2199      if (ET->getClass() == RSExportType::ExportClassRecord) {
2200        const RSExportRecordType *ERT =
2201            static_cast<const RSExportRecordType*>(ET);
2202
2203        if (!ERT->isArtificial() && !genTypeClass(*C, ERT, ErrorMsg)) {
2204          std::cerr << "Failed to generate type class for struct '"
2205                    << ERT->getName() << "' (" << ErrorMsg << ")" << std::endl;
2206          return false;
2207        }
2208      }
2209    }
2210  }
2211
2212  return true;
2213}
2214
2215/************************** RSReflection::Context **************************/
2216const char *const RSReflection::Context::ApacheLicenseNote =
2217    "/*\n"
2218    " * Copyright (C) 2011 The Android Open Source Project\n"
2219    " *\n"
2220    " * Licensed under the Apache License, Version 2.0 (the \"License\");\n"
2221    " * you may not use this file except in compliance with the License.\n"
2222    " * You may obtain a copy of the License at\n"
2223    " *\n"
2224    " *      http://www.apache.org/licenses/LICENSE-2.0\n"
2225    " *\n"
2226    " * Unless required by applicable law or agreed to in writing, software\n"
2227    " * distributed under the License is distributed on an \"AS IS\" BASIS,\n"
2228    " * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or "
2229    "implied.\n"
2230    " * See the License for the specific language governing permissions and\n"
2231    " * limitations under the License.\n"
2232    " */\n"
2233    "\n";
2234
2235const char *const RSReflection::Context::Import[] = {
2236  // Renderscript java class
2237  "android.renderscript.*",
2238  // Import R
2239  "android.content.res.Resources",
2240  // Import for debugging
2241  // "android.util.Log",
2242};
2243
2244bool RSReflection::Context::openClassFile(const std::string &ClassName,
2245                                          std::string &ErrorMsg) {
2246  if (!mUseStdout) {
2247    mOF.clear();
2248    std::string Path =
2249        RSSlangReflectUtils::ComputePackagedPath(mOutputPathBase.c_str(),
2250                                                 mPackageName.c_str());
2251
2252    if (!SlangUtils::CreateDirectoryWithParents(Path, &ErrorMsg))
2253      return false;
2254
2255    std::string ClassFile = Path + OS_PATH_SEPARATOR_STR + ClassName + ".java";
2256
2257    mOF.open(ClassFile.c_str());
2258    if (!mOF.good()) {
2259      ErrorMsg = "failed to open file '" + ClassFile + "' for write";
2260      return false;
2261    }
2262  }
2263  return true;
2264}
2265
2266const char *RSReflection::Context::AccessModifierStr(AccessModifier AM) {
2267  switch (AM) {
2268    case AM_Public: return "public"; break;
2269    case AM_Protected: return "protected"; break;
2270    case AM_Private: return "private"; break;
2271    case AM_PublicSynchronized: return "public synchronized"; break;
2272    default: return ""; break;
2273  }
2274}
2275
2276bool RSReflection::Context::startClass(AccessModifier AM,
2277                                       bool IsStatic,
2278                                       const std::string &ClassName,
2279                                       const char *SuperClassName,
2280                                       std::string &ErrorMsg) {
2281  if (mVerbose)
2282    std::cout << "Generating " << ClassName << ".java ..." << std::endl;
2283
2284  // Open file for class
2285  if (!openClassFile(ClassName, ErrorMsg))
2286    return false;
2287
2288  // License
2289  out() << mLicenseNote;
2290
2291  // Notice of generated file
2292  out() << "/*" << std::endl;
2293  out() << " * This file is auto-generated. DO NOT MODIFY!" << std::endl;
2294  out() << " * The source Renderscript file: " << mInputRSFile << std::endl;
2295  out() << " */" << std::endl;
2296
2297  // Package
2298  if (!mPackageName.empty())
2299    out() << "package " << mPackageName << ";" << std::endl;
2300  out() << std::endl;
2301
2302  // Imports
2303  for (unsigned i = 0; i < (sizeof(Import) / sizeof(const char*)); i++)
2304    out() << "import " << Import[i] << ";" << std::endl;
2305  out() << std::endl;
2306
2307  // All reflected classes should be annotated as hidden, so that they won't
2308  // be exposed in SDK.
2309  out() << "/**" << std::endl;
2310  out() << " * @hide" << std::endl;
2311  out() << " */" << std::endl;
2312
2313  out() << AccessModifierStr(AM) << ((IsStatic) ? " static" : "") << " class "
2314        << ClassName;
2315  if (SuperClassName != NULL)
2316    out() << " extends " << SuperClassName;
2317
2318  startBlock();
2319
2320  mClassName = ClassName;
2321
2322  return true;
2323}
2324
2325void RSReflection::Context::endClass() {
2326  endBlock();
2327  if (!mUseStdout)
2328    mOF.close();
2329  clear();
2330  return;
2331}
2332
2333void RSReflection::Context::startBlock(bool ShouldIndent) {
2334  if (ShouldIndent)
2335    indent() << "{" << std::endl;
2336  else
2337    out() << " {" << std::endl;
2338  incIndentLevel();
2339  return;
2340}
2341
2342void RSReflection::Context::endBlock() {
2343  decIndentLevel();
2344  indent() << "}" << std::endl << std::endl;
2345  return;
2346}
2347
2348void RSReflection::Context::startTypeClass(const std::string &ClassName) {
2349  indent() << "public static class " << ClassName;
2350  startBlock();
2351  return;
2352}
2353
2354void RSReflection::Context::endTypeClass() {
2355  endBlock();
2356  return;
2357}
2358
2359void RSReflection::Context::startFunction(AccessModifier AM,
2360                                          bool IsStatic,
2361                                          const char *ReturnType,
2362                                          const std::string &FunctionName,
2363                                          int Argc, ...) {
2364  ArgTy Args;
2365  va_list vl;
2366  va_start(vl, Argc);
2367
2368  for (int i = 0; i < Argc; i++) {
2369    const char *ArgType = va_arg(vl, const char*);
2370    const char *ArgName = va_arg(vl, const char*);
2371
2372    Args.push_back(std::make_pair(ArgType, ArgName));
2373  }
2374  va_end(vl);
2375
2376  startFunction(AM, IsStatic, ReturnType, FunctionName, Args);
2377
2378  return;
2379}
2380
2381void RSReflection::Context::startFunction(AccessModifier AM,
2382                                          bool IsStatic,
2383                                          const char *ReturnType,
2384                                          const std::string &FunctionName,
2385                                          const ArgTy &Args) {
2386  indent() << AccessModifierStr(AM) << ((IsStatic) ? " static " : " ")
2387           << ((ReturnType) ? ReturnType : "") << " " << FunctionName << "(";
2388
2389  bool FirstArg = true;
2390  for (ArgTy::const_iterator I = Args.begin(), E = Args.end();
2391       I != E;
2392       I++) {
2393    if (!FirstArg)
2394      out() << ", ";
2395    else
2396      FirstArg = false;
2397
2398    out() << I->first << " " << I->second;
2399  }
2400
2401  out() << ")";
2402  startBlock();
2403
2404  return;
2405}
2406
2407void RSReflection::Context::endFunction() {
2408  endBlock();
2409  return;
2410}
2411
2412}  // namespace slang
2413