slang_rs_reflection.cpp revision 60c985d5a07b76b34e5113fbd166bf73ba16b7d0
1#include "slang_rs_context.hpp"
2#include "slang_rs_export_var.hpp"
3#include "slang_rs_reflection.hpp"
4#include "slang_rs_export_func.hpp"
5
6#include <ctype.h>
7
8#include <utility>
9#include <cstdarg>
10
11using std::make_pair;
12using std::endl;
13
14
15#define RS_SCRIPT_CLASS_NAME_PREFIX         "ScriptC_"
16#define RS_SCRIPT_CLASS_SUPER_CLASS_NAME    "ScriptC"
17
18#define RS_TYPE_CLASS_NAME_PREFIX           "ScriptField_"
19#define RS_TYPE_CLASS_SUPER_CLASS_NAME      "android.renderscript.Script.FieldBase"
20
21#define RS_TYPE_ITEM_CLASS_NAME             "Item"
22
23#define RS_TYPE_ITEM_BUFFER_NAME            "mItemArray"
24#define RS_TYPE_ITEM_BUFFER_PACKER_NAME     "mIOBuffer"
25
26#define RS_EXPORT_VAR_INDEX_PREFIX          "mExportVarIdx_"
27#define RS_EXPORT_VAR_PREFIX                "mExportVar_"
28
29#define RS_EXPORT_FUNC_INDEX_PREFIX         "mExportFuncIdx_"
30
31#define RS_EXPORT_VAR_ALLOCATION_PREFIX     "mAlloction_"
32#define RS_EXPORT_VAR_DATA_STORAGE_PREFIX   "mData_"
33
34namespace slang {
35
36/* Some utility function using internal in RSReflection */
37static bool GetFileNameWithoutExtension(const std::string& FileName, std::string& OutFileName) {
38    OutFileName.clear();
39
40    if(FileName.empty() || (FileName == "-"))
41        return true;
42
43    /* find last component in given path */
44    size_t SlashPos = FileName.find_last_of("/\\");
45
46    if((SlashPos != std::string::npos) && ((SlashPos + 1) < FileName.length()))
47        OutFileName = FileName.substr(SlashPos + 1);
48    else
49        OutFileName = FileName;
50
51    size_t DotPos = OutFileName.find_first_of('.');
52    if(DotPos != std::string::npos)
53        OutFileName.erase(DotPos);
54
55    return true;
56}
57
58static const char* GetPrimitiveTypeName(const RSExportPrimitiveType* EPT) {
59    static const char* PrimitiveTypeJavaNameMap[] = {
60        "",
61        "",
62        "float",    /* RSExportPrimitiveType::DataTypeFloat32 */
63        "double",   /* RSExportPrimitiveType::DataTypeFloat64 */
64        "byte",     /* RSExportPrimitiveType::DataTypeSigned8 */
65        "short",    /* RSExportPrimitiveType::DataTypeSigned16 */
66        "int",      /* RSExportPrimitiveType::DataTypeSigned32 */
67        "long",     /* RSExportPrimitiveType::DataTypeSigned64 */
68        "short",    /* RSExportPrimitiveType::DataTypeUnsigned8 */
69        "int",      /* RSExportPrimitiveType::DataTypeUnsigned16 */
70        "long",     /* RSExportPrimitiveType::DataTypeUnsigned32 */
71        "long",     /* RSExportPrimitiveType::DataTypeUnsigned64 */
72
73        "int",      /* RSExportPrimitiveType::DataTypeUnsigned565 */
74        "int",      /* RSExportPrimitiveType::DataTypeUnsigned5551 */
75        "int",      /* RSExportPrimitiveType::DataTypeUnsigned4444 */
76
77        "Element",  /* RSExportPrimitiveType::DataTypeRSElement */
78        "Type",     /* RSExportPrimitiveType::DataTypeRSType */
79        "Allocation",   /* RSExportPrimitiveType::DataTypeRSAllocation */
80        "Sampler",  /* RSExportPrimitiveType::DataTypeRSSampler */
81        "Script",   /* RSExportPrimitiveType::DataTypeRSScript */
82        "SimpleMesh",       /* RSExportPrimitiveType::DataTypeRSSimpleMesh */
83        "ProgramFragment",  /* RSExportPrimitiveType::DataTypeRSProgramFragment */
84        "ProgramVertex",    /* RSExportPrimitiveType::DataTypeRSProgramVertex */
85        "ProgramRaster",    /* RSExportPrimitiveType::DataTypeRSProgramRaster */
86        "ProgramStore",     /* RSExportPrimitiveType::DataTypeRSProgramStore */
87    };
88
89    if((EPT->getType() >= 0) && (EPT->getType() < (sizeof(PrimitiveTypeJavaNameMap) / sizeof(const char*))))
90        return PrimitiveTypeJavaNameMap[ EPT->getType() ];
91
92    assert(false && "GetPrimitiveTypeName : Unknown primitive data type");
93    return NULL;
94}
95
96static const char* GetVectorTypeName(const RSExportVectorType* EVT) {
97    static const char* VectorTypeJavaNameMap[][3] = {
98        /* 0 */ { "Byte2",  "Byte3",    "Byte4" },
99        /* 1 */ { "Short2", "Short3",   "Short4" },
100        /* 2 */ { "Int2",   "Int3",     "Int4" },
101        /* 3 */ { "Long2",  "Long3",    "Long4" },
102        /* 4 */ { "Float2", "Float3",   "Float4" },
103    };
104
105    const char** BaseElement;
106
107    switch(EVT->getType()) {
108        case RSExportPrimitiveType::DataTypeSigned8:
109            BaseElement = VectorTypeJavaNameMap[0];
110        break;
111
112        case RSExportPrimitiveType::DataTypeSigned16:
113        case RSExportPrimitiveType::DataTypeUnsigned8:
114            BaseElement = VectorTypeJavaNameMap[1];
115        break;
116
117        case RSExportPrimitiveType::DataTypeSigned32:
118        case RSExportPrimitiveType::DataTypeUnsigned16:
119            BaseElement = VectorTypeJavaNameMap[2];
120        break;
121
122        case RSExportPrimitiveType::DataTypeUnsigned32:
123            BaseElement = VectorTypeJavaNameMap[3];
124        break;
125
126        case RSExportPrimitiveType::DataTypeFloat32:
127            BaseElement = VectorTypeJavaNameMap[4];
128        break;
129
130        default:
131            assert(false && "RSReflection::genElementTypeName : Unsupported vector element data type");
132        break;
133    }
134
135    assert((EVT->getNumElement() > 1) && (EVT->getNumElement() <= 4) && "Number of element in vector type is invalid");
136
137    return BaseElement[EVT->getNumElement() - 2];
138}
139
140static const char* GetPackerAPIName(const RSExportPrimitiveType* EPT) {
141    static const char* PrimitiveTypePackerAPINameMap[] = {
142        "",
143        "",
144        "addF32",   /* RSExportPrimitiveType::DataTypeFloat32 */
145        "addF64",   /* RSExportPrimitiveType::DataTypeFloat64 */
146        "addI8",    /* RSExportPrimitiveType::DataTypeSigned8 */
147        "addI16",   /* RSExportPrimitiveType::DataTypeSigned16 */
148        "addI32",   /* RSExportPrimitiveType::DataTypeSigned32 */
149        "addI64",   /* RSExportPrimitiveType::DataTypeSigned64 */
150        "addU8",    /* RSExportPrimitiveType::DataTypeUnsigned8 */
151        "addU16",   /* RSExportPrimitiveType::DataTypeUnsigned16 */
152        "addU32",   /* RSExportPrimitiveType::DataTypeUnsigned32 */
153        "addU64",   /* RSExportPrimitiveType::DataTypeUnsigned64 */
154
155        "addU16",   /* RSExportPrimitiveType::DataTypeUnsigned565 */
156        "addU16",   /* RSExportPrimitiveType::DataTypeUnsigned5551 */
157        "addU16",   /* RSExportPrimitiveType::DataTypeUnsigned4444 */
158
159        "addObj",   /* RSExportPrimitiveType::DataTypeRSElement */
160        "addObj",   /* RSExportPrimitiveType::DataTypeRSType */
161        "addObj",   /* RSExportPrimitiveType::DataTypeRSAllocation */
162        "addObj",   /* RSExportPrimitiveType::DataTypeRSSampler */
163        "addObj",   /* RSExportPrimitiveType::DataTypeRSScript */
164        "addObj",   /* RSExportPrimitiveType::DataTypeRSSimpleMesh */
165        "addObj",   /* RSExportPrimitiveType::DataTypeRSProgramFragment */
166        "addObj",   /* RSExportPrimitiveType::DataTypeRSProgramVertex */
167        "addObj",   /* RSExportPrimitiveType::DataTypeRSProgramRaster */
168        "addObj",   /* RSExportPrimitiveType::DataTypeRSProgramStore */
169    };
170
171    if((EPT->getType() >= 0) && (EPT->getType() < (sizeof(PrimitiveTypePackerAPINameMap) / sizeof(const char*))))
172        return PrimitiveTypePackerAPINameMap[ EPT->getType() ];
173
174    assert(false && "GetPackerAPIName : Unknown primitive data type");
175    return NULL;
176}
177
178static std::string GetTypeName(const RSExportType* ET) {
179    switch(ET->getClass()) {
180        case RSExportType::ExportClassPrimitive:
181            return GetPrimitiveTypeName(static_cast<const RSExportPrimitiveType*>(ET));
182        break;
183
184        case RSExportType::ExportClassPointer:
185        {
186            const RSExportType* PointeeType = static_cast<const RSExportPointerType*>(ET)->getPointeeType();
187
188            if(PointeeType->getClass() != RSExportType::ExportClassRecord)
189                return "Allocation";
190            else
191                return RS_TYPE_CLASS_NAME_PREFIX + PointeeType->getName();
192        }
193        break;
194
195        case RSExportType::ExportClassVector:
196            return GetVectorTypeName(static_cast<const RSExportVectorType*>(ET));
197        break;
198
199        case RSExportType::ExportClassRecord:
200            return RS_TYPE_CLASS_NAME_PREFIX + ET->getName() + "."RS_TYPE_ITEM_CLASS_NAME;
201        break;
202
203        default:
204            assert(false && "Unknown class of type");
205        break;
206    }
207
208    return "";
209}
210
211static const char* GetBuiltinElementConstruct(const RSExportType* ET) {
212    if(ET->getClass() == RSExportType::ExportClassPrimitive) {
213        const RSExportPrimitiveType* EPT = static_cast<const RSExportPrimitiveType*>(ET);
214        if(EPT->getKind() == RSExportPrimitiveType::DataKindUser) {
215            static const char* PrimitiveBuiltinElementConstructMap[] = {
216                NULL,
217                NULL,
218                "USER_F32", /* RSExportPrimitiveType::DataTypeFloat32 */
219                NULL,       /* RSExportPrimitiveType::DataTypeFloat64 */
220                "USER_I8",  /* RSExportPrimitiveType::DataTypeSigned8 */
221                NULL,       /* RSExportPrimitiveType::DataTypeSigned16 */
222                "USER_I32", /* RSExportPrimitiveType::DataTypeSigned32 */
223                NULL,       /* RSExportPrimitiveType::DataTypeSigned64 */
224                "USER_U8",  /* RSExportPrimitiveType::DataTypeUnsigned8 */
225                NULL,       /* RSExportPrimitiveType::DataTypeUnsigned16 */
226                "USER_U32", /* RSExportPrimitiveType::DataTypeUnsigned32 */
227                NULL,       /* RSExportPrimitiveType::DataTypeUnsigned64 */
228
229                NULL,   /* RSExportPrimitiveType::DataTypeUnsigned565 */
230                NULL,   /* RSExportPrimitiveType::DataTypeUnsigned5551 */
231                NULL,   /* RSExportPrimitiveType::DataTypeUnsigned4444 */
232
233                "USER_ELEMENT", /* RSExportPrimitiveType::DataTypeRSElement */
234                "USER_TYPE",    /* RSExportPrimitiveType::DataTypeRSType */
235                "USER_ALLOCATION",  /* RSExportPrimitiveType::DataTypeRSAllocation */
236                "USER_SAMPLER",     /* RSExportPrimitiveType::DataTypeRSSampler */
237                "USER_SCRIPT",      /* RSExportPrimitiveType::DataTypeRSScript */
238                "USER_MESH",        /* RSExportPrimitiveType::DataTypeRSSimpleMesh */
239                "USER_PROGRAM_FRAGMENT",    /* RSExportPrimitiveType::DataTypeRSProgramFragment */
240                "USER_PROGRAM_VERTEX",      /* RSExportPrimitiveType::DataTypeRSProgramVertex */
241                "USER_PROGRAM_RASTER",      /* RSExportPrimitiveType::DataTypeRSProgramRaster */
242                "USER_PROGRAM_STORE",       /* RSExportPrimitiveType::DataTypeRSProgramStore */
243            };
244
245            if((EPT->getType() >= 0) && (EPT->getType() < (sizeof(PrimitiveBuiltinElementConstructMap) / sizeof(const char*))))
246                return PrimitiveBuiltinElementConstructMap[ EPT->getType() ];
247        } else if(EPT->getKind() == RSExportPrimitiveType::DataKindPixelA) {
248            if(EPT->getType() == RSExportPrimitiveType::DataTypeUnsigned8)
249                return "A_8";
250        } else if(EPT->getKind() == RSExportPrimitiveType::DataKindPixelRGB) {
251            if(EPT->getType() == RSExportPrimitiveType::DataTypeUnsigned565)
252                return "RGB_565";
253            else if(EPT->getType() == RSExportPrimitiveType::DataTypeUnsigned8)
254                return "RGB_888";
255        } else if(EPT->getKind() == RSExportPrimitiveType::DataKindPixelRGBA) {
256            if(EPT->getType() == RSExportPrimitiveType::DataTypeUnsigned5551)
257                return "RGB_5551";
258            else if(EPT->getType() == RSExportPrimitiveType::DataTypeUnsigned4444)
259                return "RGB_4444";
260            else if(EPT->getType() == RSExportPrimitiveType::DataTypeUnsigned8)
261                return "RGB_8888";
262        } else if(EPT->getKind() == RSExportPrimitiveType::DataKindIndex) {
263            if(EPT->getType() == RSExportPrimitiveType::DataTypeUnsigned16)
264                return "INDEX_16";
265        }
266    } else if(ET->getClass() == RSExportType::ExportClassVector) {
267        const RSExportVectorType* EVT = static_cast<const RSExportVectorType*>(ET);
268        if(EVT->getKind() == RSExportPrimitiveType::DataKindPosition) {
269            if(EVT->getType() == RSExportPrimitiveType::DataTypeFloat32) {
270                if(EVT->getNumElement() == 2)
271                    return "ATTRIB_POSITION_2";
272                else if(EVT->getNumElement() == 3)
273                    return "ATTRIB_POSITION_3";
274            }
275        } else if(EVT->getKind() == RSExportPrimitiveType::DataKindTexture) {
276            if(EVT->getType() == RSExportPrimitiveType::DataTypeFloat32) {
277                if(EVT->getNumElement() == 2)
278                    return "ATTRIB_TEXTURE_2";
279            }
280        } else if(EVT->getKind() == RSExportPrimitiveType::DataKindNormal) {
281            if(EVT->getType() == RSExportPrimitiveType::DataTypeFloat32) {
282                if(EVT->getNumElement() == 3)
283                    return "ATTRIB_NORMAL_3";
284            }
285        } else if(EVT->getKind() == RSExportPrimitiveType::DataKindColor) {
286            if(EVT->getType() == RSExportPrimitiveType::DataTypeFloat32) {
287                if(EVT->getNumElement() == 4)
288                    return "ATTRIB_COLOR_F32_4";
289            } else if(EVT->getType() == RSExportPrimitiveType::DataTypeUnsigned8) {
290                if(EVT->getNumElement() == 4)
291                    return "ATTRIB_COLOR_U8_4";
292            }
293        }
294    } else if(ET->getClass() == RSExportType::ExportClassPointer) {
295        return "USER_I32";  /* tread pointer type variable as unsigned int (TODO: this is target dependent) */
296    }
297
298    return NULL;
299}
300
301static const char* GetElementDataKindName(RSExportPrimitiveType::DataKind DK) {
302    static const char* ElementDataKindNameMap[] = {
303        "Element.DataKind.USER",        /* RSExportPrimitiveType::DataKindUser */
304        "Element.DataKind.COLOR",       /* RSExportPrimitiveType::DataKindColor */
305        "Element.DataKind.POSITION",    /* RSExportPrimitiveType::DataKindPosition */
306        "Element.DataKind.TEXTURE",     /* RSExportPrimitiveType::DataKindTexture */
307        "Element.DataKind.NORMAL",      /* RSExportPrimitiveType::DataKindNormal */
308        "Element.DataKind.INDEX",       /* RSExportPrimitiveType::DataKindIndex */
309        "Element.DataKind.POINT_SIZE",  /* RSExportPrimitiveType::DataKindPointSize */
310        "Element.DataKind.PIXEL_L",     /* RSExportPrimitiveType::DataKindPixelL */
311        "Element.DataKind.PIXEL_A",     /* RSExportPrimitiveType::DataKindPixelA */
312        "Element.DataKind.PIXEL_LA",    /* RSExportPrimitiveType::DataKindPixelLA */
313        "Element.DataKind.PIXEL_RGB",   /* RSExportPrimitiveType::DataKindPixelRGB */
314        "Element.DataKind.PIXEL_RGBA",  /* RSExportPrimitiveType::DataKindPixelRGBA */
315    };
316
317    if((DK >= 0) && (DK < (sizeof(ElementDataKindNameMap) / sizeof(const char*))))
318        return ElementDataKindNameMap[ DK ];
319    else
320        return NULL;
321}
322
323static const char* GetElementDataTypeName(RSExportPrimitiveType::DataType DT) {
324    static const char* ElementDataTypeNameMap[] = {
325        NULL,
326        NULL,
327        "Element.DataType.FLOAT_32",    /* RSExportPrimitiveType::DataTypeFloat32 */
328        NULL,                           /* RSExportPrimitiveType::DataTypeFloat64 */
329        "Element.DataType.SIGNED_8",    /* RSExportPrimitiveType::DataTypeSigned8 */
330        "Element.DataType.SIGNED_16",   /* RSExportPrimitiveType::DataTypeSigned16 */
331        "Element.DataType.SIGNED_32",   /* RSExportPrimitiveType::DataTypeSigned32 */
332        NULL,                           /* RSExportPrimitiveType::DataTypeSigned64 */
333        "Element.DataType.UNSIGNED_8",  /* RSExportPrimitiveType::DataTypeUnsigned8 */
334        "Element.DataType.UNSIGNED_16", /* RSExportPrimitiveType::DataTypeUnsigned16 */
335        "Element.DataType.UNSIGNED_32", /* RSExportPrimitiveType::DataTypeUnsigned32 */
336        NULL,                           /* RSExportPrimitiveType::DataTypeUnsigned64 */
337
338        "Element.DataType.UNSIGNED_5_6_5",   /* RSExportPrimitiveType::DataTypeUnsigned565 */
339        "Element.DataType.UNSIGNED_5_5_5_1", /* RSExportPrimitiveType::DataTypeUnsigned5551 */
340        "Element.DataType.UNSIGNED_4_4_4_4", /* RSExportPrimitiveType::DataTypeUnsigned4444 */
341
342        "Element.DataType.RS_ELEMENT",  /* RSExportPrimitiveType::DataTypeRSElement */
343        "Element.DataType.RS_TYPE",     /* RSExportPrimitiveType::DataTypeRSType */
344        "Element.DataType.RS_ALLOCATION",   /* RSExportPrimitiveType::DataTypeRSAllocation */
345        "Element.DataType.RS_SAMPLER",      /* RSExportPrimitiveType::DataTypeRSSampler */
346        "Element.DataType.RS_SCRIPT",       /* RSExportPrimitiveType::DataTypeRSScript */
347        "Element.DataType.RS_MESH",         /* RSExportPrimitiveType::DataTypeRSSimpleMesh */
348        "Element.DataType.RS_PROGRAM_FRAGMENT", /* RSExportPrimitiveType::DataTypeRSProgramFragment */
349        "Element.DataType.RS_PROGRAM_VERTEX",   /* RSExportPrimitiveType::DataTypeRSProgramVertex */
350        "Element.DataType.RS_PROGRAM_RASTER",   /* RSExportPrimitiveType::DataTypeRSProgramRaster */
351        "Element.DataType.RS_PROGRAM_STORE",    /* RSExportPrimitiveType::DataTypeRSProgramStore */
352    };
353
354    if((DT >= 0) && (DT < (sizeof(ElementDataTypeNameMap) / sizeof(const char*))))
355        return ElementDataTypeNameMap[ DT ];
356    else
357        return NULL;
358}
359
360/****************************** Methods to generate script class ******************************/
361bool RSReflection::genScriptClass(Context& C, const std::string& ClassName, std::string& ErrorMsg) {
362    if(!C.startClass(Context::AM_Public, false, ClassName, RS_SCRIPT_CLASS_SUPER_CLASS_NAME, ErrorMsg))
363        return false;
364
365    genScriptClassConstructor(C);
366
367    /* Reflect export variable */
368    for(RSContext::const_export_var_iterator I = mRSContext->export_vars_begin();
369        I != mRSContext->export_vars_end();
370        I++)
371        genExportVariable(C, *I);
372
373    /* Reflect export function */
374    for(RSContext::const_export_func_iterator I = mRSContext->export_funcs_begin();
375        I != mRSContext->export_funcs_end();
376        I++)
377        genExportFunction(C, *I);
378
379    C.endClass();
380
381    return true;
382}
383
384void RSReflection::genScriptClassConstructor(Context& C) {
385    C.indent() << "// Constructor" << endl;
386    C.startFunction(Context::AM_Public, false, NULL, C.getClassName(), 4, "RenderScript", "rs",
387                                                                          "Resources", "resources",
388                                                                          "int", "id",
389                                                                          "boolean", "isRoot");
390    /* Call constructor of super class */
391    C.indent() << "super(rs, resources, id, isRoot);" << endl;
392    C.endFunction();
393    return;
394}
395
396void RSReflection::genExportVariable(Context& C, const RSExportVar* EV) {
397    const RSExportType* ET = EV->getType();
398
399    C.indent() << "private final static int "RS_EXPORT_VAR_INDEX_PREFIX << EV->getName() << " = " << C.getNextExportVarSlot() << ";" << endl;
400
401    switch(ET->getClass()) {
402        case RSExportType::ExportClassPrimitive:
403            genPrimitiveTypeExportVariable(C, EV);
404        break;
405
406        case RSExportType::ExportClassPointer:
407            genPointerTypeExportVariable(C, EV);
408        break;
409
410        case RSExportType::ExportClassVector:
411            genVectorTypeExportVariable(C, EV);
412        break;
413
414        case RSExportType::ExportClassRecord:
415            genRecordTypeExportVariable(C, EV);
416        break;
417
418        default:
419            assert(false && "Unknown class of type");
420        break;
421    }
422
423    return;
424}
425
426void RSReflection::genExportFunction(Context& C, const RSExportFunc* EF) {
427    C.indent() << "private final static int "RS_EXPORT_FUNC_INDEX_PREFIX << EF->getName() << " = " << C.getNextExportFuncSlot() << ";" << endl;
428
429    /* invoke_*() */
430    Context::ArgTy Args;
431
432    for(RSExportFunc::const_param_iterator I = EF->params_begin();
433        I != EF->params_end();
434        I++)
435    {
436        const RSExportFunc::Parameter* P = *I;
437        Args.push_back( make_pair(GetTypeName(P->getType()), P->getName()) );
438    }
439
440    C.startFunction(Context::AM_Public, false, "void", "invoke_" + EF->getName(), Args);
441
442    if(!EF->hasParam()) {
443        C.indent() << "invoke("RS_EXPORT_FUNC_INDEX_PREFIX << EF->getName() << ");" << endl;
444    } else {
445        const RSExportRecordType* ERT = EF->getParamPacketType();
446        std::string FieldPackerName = EF->getName() + "_fp";
447
448        if(genCreateFieldPacker(C, ERT, FieldPackerName.c_str()))
449            genPackVarOfType(C, ERT, NULL, FieldPackerName.c_str());
450
451        C.indent() << "invoke("RS_EXPORT_FUNC_INDEX_PREFIX << EF->getName() << ", " << FieldPackerName << ");" << endl;
452    }
453
454    C.endFunction();
455    return;
456}
457
458void RSReflection::genPrimitiveTypeExportVariable(Context& C, const RSExportVar* EV) {
459    assert((EV->getType()->getClass() == RSExportType::ExportClassPrimitive) && "Variable should be type of primitive here");
460
461    const RSExportPrimitiveType* EPT = static_cast<const RSExportPrimitiveType*>(EV->getType());
462    const char* TypeName = GetPrimitiveTypeName(EPT);
463
464    C.indent() << "private " << TypeName << " "RS_EXPORT_VAR_PREFIX << EV->getName() << ";" << endl;
465
466    /* set_*() */
467    C.startFunction(Context::AM_Public, false, "void", "set_" + EV->getName(), 1, TypeName, "v");
468    C.indent() << RS_EXPORT_VAR_PREFIX << EV->getName() << " = v;" << endl;
469
470    if(EPT->isRSObjectType())
471        C.indent() << "setVar("RS_EXPORT_VAR_INDEX_PREFIX << EV->getName() << ", (v == null) ? 0 : v.getID());" << endl;
472    else
473        C.indent() << "setVar("RS_EXPORT_VAR_INDEX_PREFIX << EV->getName() << ", v);" << endl;
474
475    C.endFunction();
476
477    genGetExportVariable(C, TypeName, EV->getName());
478
479    return;
480}
481
482void RSReflection::genPointerTypeExportVariable(Context& C, const RSExportVar* EV) {
483    const RSExportType* ET = EV->getType();
484    const RSExportType* PointeeType;
485    std::string TypeName;
486
487    assert((ET->getClass() == RSExportType::ExportClassPointer) && "Variable should be type of pointer here");
488
489    PointeeType = static_cast<const RSExportPointerType*>(ET)->getPointeeType();
490    TypeName = GetTypeName(ET);
491
492    /* bind_*() */
493    C.indent() << "private " << TypeName << " "RS_EXPORT_VAR_PREFIX << EV->getName() << ";" << endl;
494
495    C.startFunction(Context::AM_Public, false, "void", "bind_" + EV->getName(), 1, TypeName.c_str(), "v");
496
497    C.indent() << RS_EXPORT_VAR_PREFIX << EV->getName() << " = v;" << endl;
498    C.indent() << "if(v == null) bindAllocation(null, "RS_EXPORT_VAR_INDEX_PREFIX << EV->getName() << ");" << endl;
499
500    if(PointeeType->getClass() == RSExportType::ExportClassRecord)
501        C.indent() << "else bindAllocation(v.getAllocation(), "RS_EXPORT_VAR_INDEX_PREFIX << EV->getName() << ");" << endl;
502    else
503        C.indent() << "else bindAllocation(v, "RS_EXPORT_VAR_INDEX_PREFIX << EV->getName() << ");" << endl;
504
505    C.endFunction();
506
507    genGetExportVariable(C, TypeName, EV->getName());
508
509    return;
510}
511
512void RSReflection::genVectorTypeExportVariable(Context& C, const RSExportVar* EV) {
513    assert((EV->getType()->getClass() == RSExportType::ExportClassVector) && "Variable should be type of vector here");
514
515    const RSExportVectorType* EVT = static_cast<const RSExportVectorType*>(EV->getType());
516    const char* TypeName = GetVectorTypeName(EVT);
517    const char* FieldPackerName = "fp";
518
519    C.indent() << "private " << TypeName << " "RS_EXPORT_VAR_PREFIX << EV->getName() << ";" << endl;
520
521    /* set_*() */
522    C.startFunction(Context::AM_Public, false, "void", "set_" + EV->getName(), 1, TypeName, "v");
523    C.indent() << RS_EXPORT_VAR_PREFIX << EV->getName() << " = v;" << endl;
524
525    if(genCreateFieldPacker(C, EVT, FieldPackerName))
526        genPackVarOfType(C, EVT, "v", FieldPackerName);
527    C.indent() << "setVar("RS_EXPORT_VAR_INDEX_PREFIX << EV->getName() << ", " << FieldPackerName << ");" << endl;
528
529    C.endFunction();
530
531    genGetExportVariable(C, TypeName, EV->getName());
532    return;
533}
534
535void RSReflection::genRecordTypeExportVariable(Context& C, const RSExportVar* EV) {
536    assert((EV->getType()->getClass() == RSExportType::ExportClassRecord) && "Variable should be type of struct here");
537
538    const RSExportRecordType* ERT = static_cast<const RSExportRecordType*>(EV->getType());
539    std::string TypeName = RS_TYPE_CLASS_NAME_PREFIX + ERT->getName() + "."RS_TYPE_ITEM_CLASS_NAME;
540    const char* FieldPackerName = "fp";
541
542    C.indent() << "private " << TypeName << " "RS_EXPORT_VAR_PREFIX << EV->getName() << ";" << endl;
543
544    /* set_*() */
545    C.startFunction(Context::AM_Public, false, "void", "set_" + EV->getName(), 1, TypeName.c_str(), "v");
546    C.indent() << RS_EXPORT_VAR_PREFIX << EV->getName() << " = v;" << endl;
547
548    if(genCreateFieldPacker(C, ERT, FieldPackerName))
549        genPackVarOfType(C, ERT, "v", FieldPackerName);
550    C.indent() << "setVar("RS_EXPORT_VAR_INDEX_PREFIX << EV->getName() << ", " << FieldPackerName << ");" << endl;
551
552    C.endFunction();
553
554    genGetExportVariable(C, TypeName.c_str(), EV->getName());
555    return;
556}
557
558void RSReflection::genGetExportVariable(Context& C, const std::string& TypeName, const std::string& VarName) {
559    C.startFunction(Context::AM_Public, false, TypeName.c_str(), "get_" + VarName, 0);
560
561    C.indent() << "return "RS_EXPORT_VAR_PREFIX << VarName << ";" << endl;
562
563    C.endFunction();
564    return;
565}
566
567/****************************** Methods to generate script class /end ******************************/
568
569bool RSReflection::genCreateFieldPacker(Context& C, const RSExportType* ET, const char* FieldPackerName) {
570    size_t AllocSize = RSExportType::GetTypeAllocSize(ET);
571    if(AllocSize > 0)
572        C.indent() << "FieldPacker " << FieldPackerName << " = new FieldPacker(" << AllocSize << ");" << endl;
573    else
574        return false;
575    return true;
576}
577
578void RSReflection::genPackVarOfType(Context& C, const RSExportType* ET, const char* VarName, const char* FieldPackerName) {
579    switch(ET->getClass()) {
580        case RSExportType::ExportClassPrimitive:
581        case RSExportType::ExportClassVector:
582            C.indent() << FieldPackerName << "." << GetPackerAPIName(static_cast<const RSExportPrimitiveType*>(ET)) << "(" << VarName << ");" << endl;
583        break;
584
585        case RSExportType::ExportClassPointer:
586        {
587            /* Must reflect as type Allocation in Java */
588            const RSExportType* PointeeType = static_cast<const RSExportPointerType*>(ET)->getPointeeType();
589
590            if(PointeeType->getClass() != RSExportType::ExportClassRecord)
591                C.indent() << FieldPackerName << ".addI32(" << VarName << ".getPtr());" << endl;
592            else
593                C.indent() << FieldPackerName << ".addI32(" << VarName << ".getAllocation().getPtr());" << endl;
594        }
595        break;
596
597        case RSExportType::ExportClassRecord:
598        {
599            const RSExportRecordType* ERT = static_cast<const RSExportRecordType*>(ET);
600            int Pos = 0;    /* relative pos from now on in field packer */
601
602            for(RSExportRecordType::const_field_iterator I = ERT->fields_begin();
603                I != ERT->fields_end();
604                I++)
605            {
606                const RSExportRecordType::Field* F = *I;
607                std::string FieldName;
608                size_t FieldOffset = F->getOffsetInParent();
609                size_t FieldStoreSize = RSExportType::GetTypeStoreSize(F->getType());
610                size_t FieldAllocSize = RSExportType::GetTypeAllocSize(F->getType());
611
612                if(VarName != NULL)
613                    FieldName = VarName + ("." + F->getName());
614                else
615                    FieldName = F->getName();
616
617                if(FieldOffset > Pos)
618                    C.indent() << FieldPackerName << ".skip(" << (FieldOffset - Pos) << ");" << endl;
619
620                genPackVarOfType(C, F->getType(), FieldName.c_str(), FieldPackerName);
621
622                if(FieldAllocSize > FieldStoreSize)  /* there's padding in the field type */
623                    C.indent() << FieldPackerName << ".skip(" << (FieldAllocSize - FieldStoreSize) << ");" << endl;
624
625                Pos = FieldOffset + FieldAllocSize;
626            }
627
628            /* There maybe some padding after the struct */
629            size_t Padding = RSExportType::GetTypeAllocSize(ERT) - Pos;
630            if(Padding > 0)
631                C.indent() << FieldPackerName << ".skip(" << Padding << ");" << endl;
632        }
633        break;
634
635        default:
636            assert(false && "Unknown class of type");
637        break;
638    }
639
640    return;
641}
642
643/****************************** Methods to generate type class  ******************************/
644bool RSReflection::genTypeClass(Context& C, const RSExportRecordType* ERT, std::string& ErrorMsg) {
645    std::string ClassName = RS_TYPE_CLASS_NAME_PREFIX + ERT->getName();
646
647    if(!C.startClass(Context::AM_Public, false, ClassName, RS_TYPE_CLASS_SUPER_CLASS_NAME, ErrorMsg))
648        return false;
649
650    if(!genTypeItemClass(C, ERT, ErrorMsg))
651        return false;
652
653    /* Declare item buffer and item buffer packer */
654    C.indent() << "private "RS_TYPE_ITEM_CLASS_NAME" "RS_TYPE_ITEM_BUFFER_NAME"[];" << endl;
655    C.indent() << "private FieldPacker "RS_TYPE_ITEM_BUFFER_PACKER_NAME";" << endl;
656
657    genTypeClassConstructor(C, ERT);
658    genTypeClassCopyToArray(C, ERT);
659    genTypeClasSet(C, ERT);
660    genTypeClasCopyAll(C, ERT);
661
662    C.endClass();
663
664    return true;
665}
666
667bool RSReflection::genTypeItemClass(Context& C, const RSExportRecordType* ERT, std::string& ErrorMsg) {
668    C.indent() << "static public class "RS_TYPE_ITEM_CLASS_NAME;
669    C.startBlock();
670
671    C.indent() << "public static final int sizeof = " << RSExportType::GetTypeAllocSize(ERT) << ";" << endl;
672
673    /* Member elements */
674    C.out() << endl;
675    for(RSExportRecordType::const_field_iterator FI = ERT->fields_begin();
676        FI != ERT->fields_end();
677        FI++)
678        C.indent() << GetTypeName((*FI)->getType()) << " " << (*FI)->getName() << ";" << endl;
679
680    /* Constructor */
681    C.out() << endl;
682    C.indent() << RS_TYPE_ITEM_CLASS_NAME"()";
683    C.startBlock();
684
685    for(RSExportRecordType::const_field_iterator FI = ERT->fields_begin();
686        FI != ERT->fields_end();
687        FI++)
688    {
689        const RSExportRecordType::Field* F = *FI;
690        if((F->getType()->getClass() == RSExportType::ExportClassVector) || (F->getType()->getClass() == RSExportType::ExportClassRecord))
691        C.indent() << F->getName() << " = new " << GetTypeName(F->getType()) << "();" << endl;
692    }
693
694    C.endBlock();   /* end Constructor */
695
696    C.endBlock();   /* end Item class */
697
698
699    return true;
700}
701
702void RSReflection::genTypeClassConstructor(Context& C, const RSExportRecordType* ERT) {
703    const char* RenderScriptVar = "rs";
704
705    C.startFunction(Context::AM_Public, false, NULL, C.getClassName(), 2, "RenderScript", RenderScriptVar,
706                                                                          "int", "count");
707
708    C.indent() << RS_TYPE_ITEM_BUFFER_NAME" = null;" << endl;
709    C.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME" = null;" << endl;
710
711    genBuildElement(C, ERT, "mElement", RenderScriptVar);
712    /* Call init() in super class */
713    C.indent() << "init(" << RenderScriptVar << ", count);" << endl;
714    C.endFunction();
715
716    return;
717}
718
719void RSReflection::genTypeClassCopyToArray(Context& C, const RSExportRecordType* ERT) {
720    C.startFunction(Context::AM_Private, false, "void", "copyToArray", 2, RS_TYPE_ITEM_CLASS_NAME, "i",
721                                                                          "int", "index");
722
723    C.indent() << "if ("RS_TYPE_ITEM_BUFFER_PACKER_NAME" == null) "RS_TYPE_ITEM_BUFFER_PACKER_NAME" = new FieldPacker("RS_TYPE_ITEM_CLASS_NAME".sizeof * mType.getX() /* count */);" << endl;
724    C.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME".reset(index * "RS_TYPE_ITEM_CLASS_NAME".sizeof);" << endl;
725
726    genPackVarOfType(C, ERT, "i", RS_TYPE_ITEM_BUFFER_PACKER_NAME);
727
728    C.endFunction();
729    return;
730}
731
732void RSReflection::genTypeClasSet(Context& C, const RSExportRecordType* ERT) {
733    C.startFunction(Context::AM_Public, false, "void", "set", 3, RS_TYPE_ITEM_CLASS_NAME, "i",
734                                                                 "int", "index",
735                                                                 "boolean", "copyNow");
736    C.indent() << "if ("RS_TYPE_ITEM_BUFFER_NAME" == null) "RS_TYPE_ITEM_BUFFER_NAME" = new "RS_TYPE_ITEM_CLASS_NAME"[mType.getX() /* count */];" << endl;
737    C.indent() << RS_TYPE_ITEM_BUFFER_NAME"[index] = i;" << endl;
738
739    C.indent() << "if (copyNow) ";
740    C.startBlock();
741
742    C.indent() << "copyToArray(i, index);" << endl;
743    C.indent() << "mAllocation.subData1D(index * "RS_TYPE_ITEM_CLASS_NAME".sizeof, "RS_TYPE_ITEM_CLASS_NAME".sizeof, "RS_TYPE_ITEM_BUFFER_PACKER_NAME".getData());" << endl;
744
745    C.endBlock();   /* end if (copyNow) */
746
747    C.endFunction();
748    return;
749}
750
751void RSReflection::genTypeClasCopyAll(Context& C, const RSExportRecordType* ERT) {
752    C.startFunction(Context::AM_Public, false, "void", "copyAll", 0);
753
754    C.indent() << "for (int ct=0; ct < "RS_TYPE_ITEM_BUFFER_NAME".length; ct++) copyToArray("RS_TYPE_ITEM_BUFFER_NAME"[ct], ct);" << endl;
755    C.indent() << "mAllocation.data("RS_TYPE_ITEM_BUFFER_PACKER_NAME".getData());" << endl;
756
757    C.endFunction();
758    return;
759}
760
761/****************************** Methods to generate type class /end ******************************/
762
763/******************** Methods to create Element in Java of given record type ********************/
764void RSReflection::genBuildElement(Context& C, const RSExportRecordType* ERT, const char* ElementName, const char* RenderScriptVar) {
765    const char* ElementBuilderName = "eb";
766
767    /* Create element builder */
768    C.startBlock(true);
769
770    C.indent() << "Element.Builder " << ElementBuilderName << " = new Element.Builder(" << RenderScriptVar << ");" << endl;
771
772    /* eb.add(...) */
773    genAddElementToElementBuilder(C, ERT, "", ElementBuilderName, RenderScriptVar);
774
775    C.indent() << ElementName << " = " << ElementBuilderName << ".create();" << endl;
776
777    C.endBlock();
778    return;
779}
780
781#define EB_ADD(x, ...)  \
782        C.indent() << ElementBuilderName << ".add(Element." << x ##__VA_ARGS__ ", \"" << VarName << "\");" << endl
783void RSReflection::genAddElementToElementBuilder(Context& C, const RSExportType* ET, const std::string& VarName, const char* ElementBuilderName, const char* RenderScriptVar) {
784        const char* ElementConstruct = GetBuiltinElementConstruct(ET);
785        if(ElementConstruct != NULL) {
786            EB_ADD(ElementConstruct << "(" << RenderScriptVar << ")");
787        } else {
788            if((ET->getClass() == RSExportType::ExportClassPrimitive) || (ET->getClass() == RSExportType::ExportClassVector)) {
789                const RSExportPrimitiveType* EPT = static_cast<const RSExportPrimitiveType*>(ET);
790                const char* DataKindName = GetElementDataKindName(EPT->getKind());
791                const char* DataTypeName = GetElementDataTypeName(EPT->getType());
792                int Size = (ET->getClass() == RSExportType::ExportClassVector) ? static_cast<const RSExportVectorType*>(ET)->getNumElement() : 1;
793
794                switch(EPT->getKind()) {
795                    case RSExportPrimitiveType::DataKindColor:
796                    case RSExportPrimitiveType::DataKindPosition:
797                    case RSExportPrimitiveType::DataKindTexture:
798                    case RSExportPrimitiveType::DataKindNormal:
799                    case RSExportPrimitiveType::DataKindPointSize:
800                        /* Element.createAttrib() */
801                        EB_ADD("createAttrib(" << RenderScriptVar << ", " << DataTypeName << ", " << DataKindName << ", " << Size << ")");
802                    break;
803
804                    case RSExportPrimitiveType::DataKindIndex:
805                        /* Element.createIndex() */
806                        EB_ADD("createAttrib(" << RenderScriptVar << ")");
807                    break;
808
809                    case RSExportPrimitiveType::DataKindPixelL:
810                    case RSExportPrimitiveType::DataKindPixelA:
811                    case RSExportPrimitiveType::DataKindPixelLA:
812                    case RSExportPrimitiveType::DataKindPixelRGB:
813                    case RSExportPrimitiveType::DataKindPixelRGBA:
814                        /* Element.createPixel() */
815                        EB_ADD("createVector(" << RenderScriptVar << ", " << DataTypeName << ", " << DataKindName << ")");
816                    break;
817
818                    case RSExportPrimitiveType::DataKindUser:
819                    default:
820                        if(EPT->getClass() == RSExportType::ExportClassPrimitive)
821                            /* Element.createUser() */
822                            EB_ADD("createUser(" << RenderScriptVar << ", " << DataTypeName << ")");
823                        else /* (ET->getClass() == RSExportType::ExportClassVector) must hold here */
824                            /* Element.createVector() */
825                            EB_ADD("createVector(" << RenderScriptVar << ", " << DataTypeName << ", " << Size << ")");
826                    break;
827                }
828            } else if(ET->getClass() == RSExportType::ExportClassPointer) {
829                /* Pointer type variable should be resolved in GetBuiltinElementConstruct()  */
830                assert(false && "??");
831            } else if(ET->getClass() == RSExportType::ExportClassRecord) {
832                /*
833                 * Simalar to genPackVarOfType.
834                 *
835                 * TODO: Generalize these two function such that there's no duplicated codes.
836                 */
837                const RSExportRecordType* ERT = static_cast<const RSExportRecordType*>(ET);
838                int Pos = 0;    /* relative pos from now on */
839
840                for(RSExportRecordType::const_field_iterator I = ERT->fields_begin();
841                    I != ERT->fields_end();
842                    I++)
843                {
844                    const RSExportRecordType::Field* F = *I;
845                    std::string FieldName;
846                    size_t FieldOffset = F->getOffsetInParent();
847                    size_t FieldStoreSize = RSExportType::GetTypeStoreSize(F->getType());
848                    size_t FieldAllocSize = RSExportType::GetTypeAllocSize(F->getType());
849
850                    if(!VarName.empty())
851                        FieldName = VarName + "." + F->getName();
852                    else
853                        FieldName = F->getName();
854
855                    /* alignment */
856                    genAddPaddingToElementBuiler(C, (FieldOffset - Pos), ElementBuilderName, RenderScriptVar);
857
858                    /* eb.add(...) */
859                    genAddElementToElementBuilder(C, (*I)->getType(), FieldName, ElementBuilderName, RenderScriptVar);
860
861                    /* there's padding within the field type */
862                    genAddPaddingToElementBuiler(C, (FieldAllocSize - FieldStoreSize), ElementBuilderName, RenderScriptVar);
863
864                    Pos = FieldOffset + FieldAllocSize;
865                }
866
867                /* There maybe some padding after the struct */
868                genAddPaddingToElementBuiler(C, (RSExportType::GetTypeAllocSize(ERT) - Pos), ElementBuilderName, RenderScriptVar);
869            } else {
870                assert(false && "Unknown class of type");
871            }
872        }
873}
874
875void RSReflection::genAddPaddingToElementBuiler(Context& C, size_t PaddingSize, const char* ElementBuilderName, const char* RenderScriptVar) {
876    while(PaddingSize > 0) {
877        const std::string& VarName = C.createPaddingField();
878        if(PaddingSize >= 4) {
879            EB_ADD("USER_U32(" << RenderScriptVar << ")");
880            PaddingSize -= 4;
881        } else if(PaddingSize >= 2) {
882            EB_ADD("USER_U16(" << RenderScriptVar << ")");
883            PaddingSize -= 2;
884        } else if(PaddingSize >= 1) {
885            EB_ADD("USER_U8(" << RenderScriptVar << ")");
886            PaddingSize -= 1;
887        }
888    }
889    return;
890}
891
892#undef EB_ADD
893/******************** Methods to create Element in Java of given record type /end ********************/
894
895bool RSReflection::reflect(const char* OutputPackageName, const std::string& InputFileName, const std::string& OutputBCFileName) {
896    Context *C = NULL;
897    std::string ResourceId = "";
898
899    if(!GetFileNameWithoutExtension(OutputBCFileName, ResourceId))
900        return false;
901
902    if(ResourceId.empty())
903        ResourceId = "<Resource ID>";
904
905    if((OutputPackageName == NULL) || (*OutputPackageName == '\0') || strcmp(OutputPackageName, "-") == 0)
906        C = new Context("<Package Name>", ResourceId, true);
907    else
908        C = new Context(OutputPackageName, ResourceId, false);
909
910    if(C != NULL) {
911        std::string ErrorMsg, ScriptClassName;
912        /* class ScriptC_<ScriptName> */
913        if(!GetFileNameWithoutExtension(InputFileName, ScriptClassName))
914            return false;
915
916        if(ScriptClassName.empty())
917            ScriptClassName = "<Input Script Name>";
918
919        ScriptClassName.at(0) = toupper(ScriptClassName.at(0));
920        ScriptClassName.insert(0, RS_SCRIPT_CLASS_NAME_PREFIX);
921
922        if(!genScriptClass(*C, ScriptClassName, ErrorMsg)) {
923            std::cerr << "Failed to generate class " << ScriptClassName << " (" << ErrorMsg << ")" << endl;
924            return false;
925        }
926
927        /* class ScriptField_<TypeName> */
928        for(RSContext::const_export_type_iterator TI = mRSContext->export_types_begin();
929            TI != mRSContext->export_types_end();
930            TI++)
931        {
932            const RSExportType* ET = TI->getValue();
933
934            if(ET->getClass() == RSExportType::ExportClassRecord) {
935                const RSExportRecordType* ERT = static_cast<const RSExportRecordType*>(ET);
936
937                if(!ERT->isArtificial() && !genTypeClass(*C, ERT, ErrorMsg)) {
938                    std::cerr << "Failed to generate type class for struct '" << ERT->getName() << "' (" << ErrorMsg << ")" << endl;
939                    return false;
940                }
941            }
942        }
943    }
944
945    return true;
946}
947
948/****************************** RSReflection::Context ******************************/
949const char* const RSReflection::Context::LicenseNote =
950    "/*\n"
951	" * Copyright (C) 2010 The Android Open Source Project\n"
952	" *\n"
953	" * Licensed under the Apache License, Version 2.0 (the \"License\");\n"
954	" * you may not use this file except in compliance with the License.\n"
955	" * You may obtain a copy of the License at\n"
956	" *\n"
957	" *      http://www.apache.org/licenses/LICENSE-2.0\n"
958	" *\n"
959	" * Unless required by applicable law or agreed to in writing, software\n"
960	" * distributed under the License is distributed on an \"AS IS\" BASIS,\n"
961	" * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n"
962	" * See the License for the specific language governing permissions and\n"
963	" * limitations under the License.\n"
964	" */\n";
965
966const char* const RSReflection::Context::Import[] = {
967    /* RenderScript java class */
968    "android.renderscript.*",
969    /* Import R */
970    "android.content.res.Resources",
971    /* Import for debugging */
972    "android.util.Log",
973};
974
975const char* RSReflection::Context::AccessModifierStr(AccessModifier AM) {
976    switch(AM) {
977        case AM_Public: return "public"; break;
978        case AM_Protected: return "protected"; break;
979        case AM_Private: return "private"; break;
980        default: return ""; break;
981    }
982}
983
984bool RSReflection::Context::startClass(AccessModifier AM, bool IsStatic, const std::string& ClassName, const char* SuperClassName, std::string& ErrorMsg) {
985    if(mVerbose)
986        std::cout << "Generating " << ClassName << ".java ..." << endl;
987
988    /* Open the file */
989    if(!mUseStdout) {
990        mOF.clear();
991        mOF.open((ClassName + ".java").c_str());
992        if(!mOF.good()) {
993            ErrorMsg = "failed to open file '" + ClassName + ".java' for write";
994            return false;
995        }
996    }
997
998    /* License */
999    out() << LicenseNote << endl;
1000
1001    /* Package */
1002    if(!mPackageName.empty())
1003        out() << "package " << mPackageName << ";" << endl;
1004    out() << endl;
1005
1006    /* Imports */
1007    for(int i=0;i<(sizeof(Import)/sizeof(const char*));i++)
1008        out() << "import " << Import[i] << ";" << endl;
1009    out() << endl;
1010
1011    out() << AccessModifierStr(AM) << ((IsStatic) ? " static" : "") << " class " << ClassName;
1012    if(SuperClassName != NULL)
1013        out() << " extends " << SuperClassName;
1014
1015    startBlock();
1016
1017    mClassName = ClassName;
1018
1019    return true;
1020}
1021
1022void RSReflection::Context::endClass() {
1023    endBlock();
1024    if(!mUseStdout)
1025        mOF.close();
1026    clear();
1027    return;
1028}
1029
1030void RSReflection::Context::startBlock(bool ShouldIndent) {
1031    if(ShouldIndent)
1032        indent() << "{" << endl;
1033    else
1034        out() << " {" << endl;
1035    incIndentLevel();
1036    return;
1037}
1038
1039void RSReflection::Context::endBlock() {
1040    decIndentLevel();
1041    indent() << "}" << endl << endl;
1042    return;
1043}
1044
1045void RSReflection::Context::startTypeClass(const std::string& ClassName) {
1046    indent() << "public static class " << ClassName;
1047    startBlock();
1048    return;
1049}
1050
1051void RSReflection::Context::endTypeClass() {
1052    endBlock();
1053    return;
1054}
1055
1056void RSReflection::Context::startFunction(AccessModifier AM, bool IsStatic, const char* ReturnType, const std::string& FunctionName, int Argc, ...) {
1057    ArgTy Args;
1058    va_list vl;
1059    va_start(vl, Argc);
1060
1061    for(int i=0;i<Argc;i++) {
1062        const char* ArgType = va_arg(vl, const char*);
1063        const char* ArgName = va_arg(vl, const char*);
1064
1065        Args.push_back( make_pair(ArgType, ArgName) );
1066    }
1067    va_end(vl);
1068
1069    startFunction(AM, IsStatic, ReturnType, FunctionName, Args);
1070
1071    return;
1072}
1073
1074void RSReflection::Context::startFunction(AccessModifier AM,
1075                                          bool IsStatic,
1076                                          const char* ReturnType,
1077                                          const std::string& FunctionName,
1078                                          const ArgTy& Args)
1079{
1080    indent() << AccessModifierStr(AM) << ((IsStatic) ? " static " : " ") << ((ReturnType) ? ReturnType : "") << " " << FunctionName << "(";
1081
1082    bool FirstArg = true;
1083    for(ArgTy::const_iterator I = Args.begin();
1084        I != Args.end();
1085        I++)
1086    {
1087        if(!FirstArg)
1088            out() << ", ";
1089        else
1090            FirstArg = false;
1091
1092        out() << I->first << " " << I->second;
1093    }
1094
1095    out() << ")";
1096    startBlock();
1097
1098    return;
1099}
1100
1101void RSReflection::Context::endFunction() {
1102    endBlock();
1103    return;
1104}
1105
1106}   /* namespace slang */
1107