예제 #1
0
    static void CopyBehaviour(MonoBehaviour behaviour, JSSerializer serizlizer)
    {
        lstAnalyze.Clear();
        lstString.Clear();
        lstObjs.Clear();

        // GameObject go = behaviour.gameObject;
        //Type type = behaviour.GetType();

        // 1) Fields
        FieldInfo[] fields = GetMonoBehaviourSerializedFields(behaviour);
        foreach (FieldInfo field in fields)
        {
            AddAnalyze(field.FieldType, field.Name, field.GetValue(behaviour));
        }

        // 2) Properties
        PropertyInfo[] properties = GetTypeSerializedProperties(behaviour.GetType());
        foreach (PropertyInfo pro in properties)
        {
            AddAnalyze(pro.PropertyType, "#" + pro.Name, pro.GetValue(behaviour, null));
        }

        TraverseAnalyze();

        for (var i = 0; i < lstAnalyze.Count; i++)
        {
            lstAnalyze[i].Alloc(serizlizer);
        }
        serizlizer.jsClassName = JSNameMgr.GetTypeFullName(behaviour.GetType());
        serizlizer.arrString   = lstString.ToArray();
        serizlizer.arrObject   = lstObjs.ToArray();
    }
예제 #2
0
    /// <summary>
    ///     获取当前类型继承关系信息
    /// </summary>
    /// <returns></returns>
    public static StringBuilder GetJsTypeInheritInfo(Type type)
    {
        var sb = new StringBuilder();
        //生成BaseType信息
        string baseTypeName = JSNameMgr.GetJSTypeFullName(type.BaseType);

        if (!string.IsNullOrEmpty(baseTypeName))
        {
            sb.Append("\n    baseTypeName: '" + baseTypeName + "',");
        }
        //生成Interface信息
        var interfaces = type.GetInterfaces();

        if (interfaces.Length > 0)
        {
            sb.Append("\n    interfaceNames: [");
            for (int i = 0; i < interfaces.Length; i++)
            {
                var iType = interfaces[i];
                if (iType.IsPublic || iType.IsNestedPublic)
                {
                    sb.Append("'" + JSNameMgr.GetJSTypeFullName(interfaces[i]) + "'");
                    if (i < interfaces.Length - 1)
                    {
                        sb.Append(", ");
                    }
                }
            }
            sb.Append("],");
        }
        return(sb);
    }
예제 #3
0
    static void GenerateEnum()
    {
        string fullName   = JSNameMgr.GetTypeFullName(type);
        string jsTypeName = fullName.Replace('.', '$');

        var sbValues = new StringBuilder();
        {
            FieldInfo[] fields   = type.GetFields(BindingFlags.GetField | BindingFlags.Public | BindingFlags.Static);
            string      fmtField = "        {0}: {1}{2}\n";
            for (int i = 0; i < fields.Length; i++)
            {
                sbValues.AppendFormat(fmtField, fields[i].Name, (int)fields[i].GetValue(null),
                                      i == fields.Length - 1 ? "" : ",");
            }
        }

        var sbDef = new StringBuilder();

        sbDef.AppendFormat(@"
jst_pushOrReplace([[
    fullname: '{1}',
    staticDefinition: [[
{2}    ]],
    Kind: 'Enum'
]]);
",
                           jsTypeName, fullName, sbValues);

        HandleStringFormat(sbDef);
        W.Write(sbDef.ToString());
    }
예제 #4
0
    private static void GenerateMono2JsComConfig()
    {
        var mono2JsCom = new Dictionary <string, string>();

        Assembly logicCodeLib = Assembly.Load("Assembly-CSharp");

        if (logicCodeLib != null)
        {
            var types = logicCodeLib.GetExportedTypes();
            foreach (var t in types)
            {
                if (t.IsSubclassOf(typeof(MonoBehaviour)))
                {
                    if (WillTypeBeTranslatedToJavaScript(t))
                    {
                        string jsComponentName = JSComponentGenerator.GetJSComponentClassName(t);
                        mono2JsCom.Add(JSNameMgr.GetTypeFullName(t, false), jsComponentName);
                    }
                }
            }
        }
        else
        {
            Debug.LogError("Load Assembly-CSharp.dll failed");
        }

        string filePath = JSPathSettings.Mono2JsComConfig;

        File.WriteAllText(filePath, JsonMapper.ToJson(mono2JsCom));
        Debug.Log(string.Format("Mono2JsCom:{0}\nOK. File: {1}", mono2JsCom.Count, filePath));
    }
예제 #5
0
    public static string GetMethodArg_DelegateFuncionName(Type classType, string methodName, int methodTag, int argIndex)
    {
        // append Method Index if still conflicts
        var sb = new StringBuilder();

        sb.AppendFormat("{0}_{1}_GetDelegate_member{2}_arg{3}", classType.Name, methodName, methodTag, argIndex);
        return(JSNameMgr.HandleFunctionName(sb.ToString()));
    }
예제 #6
0
    public static StringBuilder Build_DelegateFunction(Type classType, MemberInfo memberInfo, Type delType, int methodTag, int argIndex)
    {
        // building a closure
        // a function having a up-value: jsFunction

        string getDelFunctionName = GetMethodArg_DelegateFuncionName(classType, memberInfo.Name, methodTag, argIndex);

        var        sb        = new StringBuilder();
        MethodInfo delInvoke = delType.GetMethod("Invoke");

        ParameterInfo[] ps         = delInvoke.GetParameters();
        Type            returnType = delType.GetMethod("Invoke").ReturnType;

        var argsParam = new cg.args();

        for (int i = 0; i < ps.Length; i++)
        {
            argsParam.Add(ps[i].Name);
        }

        // format as <t,u,v>
        string stringTOfMethod = string.Empty;

        if (delType.ContainsGenericParameters)
        {
            var arg = new cg.args();
            foreach (var t in delType.GetGenericArguments())
            {
                arg.Add(t.Name);
            }
            stringTOfMethod = arg.Format(cg.args.ArgsFormat.GenericT);
        }

        // this function name is used in BuildFields, don't change
        sb.AppendFormat("public static {0} {1}{2}(CSRepresentedObject objFunction)\n[[\n",
                        JSNameMgr.GetTypeFullName(delType, true), // [0]
                        getDelFunctionName,                       // [2]
                        stringTOfMethod                           // [1]
                        );
        sb.Append("    if (objFunction == null || objFunction.jsObjID == 0)\n");
        sb.Append("    [[\n        return null;\n    ]]\n");

        sb.AppendFormat("    {0} action = ({1}) => \n", JSNameMgr.GetTypeFullName(delType, true), argsParam.Format(cg.args.ArgsFormat.OnlyList));
        sb.AppendFormat("    [[\n");
        sb.AppendFormat("        JSMgr.vCall.CallJSFunctionValue(0, objFunction.jsObjID{0}{1});\n", (argsParam.Count > 0) ? ", " : "", argsParam);

        if (returnType != typeof(void))
        {
            sb.Append("        return (" + JSNameMgr.GetTypeFullName(returnType) + ")" + JSDataExchangeEditor.Get_GetJSReturn(returnType) + ";\n");
        }

        sb.AppendFormat("    ]];\n");
        sb.Append("    JSMgr.addJSFunCSDelegateRel(objFunction.jsObjID, action);\n");
        sb.Append("    return action;\n");
        sb.AppendFormat("]]\n");

        return(sb);
    }
예제 #7
0
 public static string Build_GetDelegate(string getDelegateFunctionName, Type delType)
 {
     return(new StringBuilder()
            .AppendFormat("JSDataExchangeMgr.GetJSArg<{0}>(()=>[[\n", JSNameMgr.GetTypeFullName(delType))
            .AppendFormat("    if (JSApi.isFunctionS((int)JSApi.GetType.Arg))\n")
            .AppendFormat("        return {0}(JSApi.getFunctionS((int)JSApi.GetType.Arg));\n", getDelegateFunctionName)
            .Append("    else\n")
            .AppendFormat("        return ({0})JSMgr.datax.getObject((int)JSApi.GetType.Arg);\n", JSNameMgr.GetTypeFullName(delType))
            .Append("]])\n")
            .ToString());
 }
예제 #8
0
    public string Get_GetParam(Type t)
    {
        elementType = t.GetElementType();
        if (elementType.IsArray)
        {
            //...error
        }
        StringBuilder sb     = new StringBuilder();
        string        getVal = JSDataExchangeMgr.GetMetatypeKeyword(elementType);

        var arrayFullName   = string.Empty;
        var elementFullName = string.Empty;

        if (elementType.IsGenericParameter)
        {
            arrayFullName   = "object[]";
            elementFullName = "object";
        }
        else
        {
            arrayFullName   = JSNameMgr.GetTypeFullName(t);
            elementFullName = JSNameMgr.GetTypeFullName(elementType);
        }
        sb.AppendFormat("JSDataExchangeMgr.GetJSArg<{0}>(() =>\n", arrayFullName)
        .Append("    [[\n")
        .AppendFormat("    int jsObjID = JSApi.getObject((int)JSApi.GetType.Arg);\n")
        .AppendFormat("    int length = JSApi.getArrayLength(jsObjID);\n")
        .AppendFormat("    var ret = new {0}[length];\n", elementFullName)
        .AppendFormat("    for (var i = 0; i < length; i++) [[\n")
        .AppendFormat("        JSApi.getElement(jsObjID, i);\n")
        .AppendFormat("        ret[i] = ({0}){1}((int)JSApi.GetType.SaveAndRemove);\n", elementFullName, getVal)
        .AppendFormat("    ]]\n")
        .AppendFormat("    return ret;\n")
        .AppendFormat("]])\n");

//         sb.AppendFormat("JSDataExchangeMgr.GetJSArg<{0}>(() => [[\n", arrayFullName)
//         .AppendFormat("    IntPtr jsObj = JSApi.JSh_ArgvObject(JSMgr.cx, vc.vp, vc.currIndex++);\n")
//         .AppendFormat("    int length = JSApi.JSh_GetArrayLength(JSMgr.cx, jsObj);\n")
//         .AppendFormat("    var ret = new {0}[length];\n", elementFullName)
//         .AppendFormat("    for (var i = 0; i < length; i++) [[\n")
//         .AppendFormat("        JSApi.JSh_GetElement(JSMgr.cx, jsObj, (uint)i, ref vc.valTemp);\n")
//         .AppendFormat("        ret[i] = ({0}){1}((int)JSApi.GetType.Jsval);\n", elementFullName, getVal)
//         .AppendFormat("    ]]\n")
//         .AppendFormat("    return ret;\n")
//         .AppendFormat("]])\n");

        sb.Replace("[[", "{");
        sb.Replace("]]", "}");

        return(sb.ToString());
    }
예제 #9
0
    public static void GenerateClass(Type type, out List <string> memberNames)
    {
        memberNames = new List <string>();

        GeneratorHelp.ATypeInfo ti;
        int    slot      = GeneratorHelp.AddTypeInfo(type, out ti);
        string jsDefName = GetJsTypeDefinition(type);

        var sbClass = new StringBuilder();

        var sbDefinition       = new StringBuilder();
        var sbStaticDefinition = new StringBuilder();

        BuildConstructors(type, ti.constructors, slot, sbDefinition, memberNames);
        BuildProperties(type, ti.properties, slot, sbDefinition, sbStaticDefinition, memberNames);
        BuildMethods(type, ti.methods, slot, sbDefinition, sbStaticDefinition, memberNames);
        var sbAllDefinition = new StringBuilder();

        if (sbStaticDefinition.Length > 0)
        {
            sbAllDefinition.AppendFormat(@"
    staticDefinition: [[{0}
    ]],", sbStaticDefinition);
        }

        if (sbDefinition.Length > 0)
        {
            sbAllDefinition.AppendFormat(@"
    definition: [[{0}
    ]],", sbDefinition);
        }

        sbClass.AppendFormat(@"
// {0}
var {1} = 
[[
    assemblyName: '{2}',
    fullname: '{3}',
    Kind: '{4}',{5}{6}{7}
]];
jsb_ReplaceOrPushJsType({1});
", type.FullName, jsDefName, type.Assembly.FullName, JSNameMgr.GetJSTypeFullName(type),
                             GetJsTypeKind(type),
                             GetJsTypeInheritInfo(type),
                             BuildFields(type, ti.fields, slot, memberNames),
                             sbAllDefinition);
        HandleStringFormat(sbClass);

        _streamWriter.Write(sbClass.ToString());
    }
        static string typefn(Type tType, string eraseNs, CsNameOption opt = CsNameOption.Compilable)
        {
            string fn = JSNameMgr.CsFullName(tType, opt);

            if (eraseNs == "no-namespace")
            {
                int dot = fn.LastIndexOf('.');
                if (dot >= 0)
                {
                    fn = fn.Substring(dot + 1);
                }
            }
            else if (!string.IsNullOrEmpty(eraseNs) &&
                     fn.StartsWith(eraseNs + "."))
            {
                fn = fn.Substring(eraseNs.Length + 1);
            }
            return(fn);
        }
예제 #11
0
    public static void GenerateJsTypeBindings(HashSet <Type> exportTypes, HashSet <Type> exportEnums, Type[] otherExportTypes)
    {
        OnBegin();

        // <typeName,members>
        var allExportInfoDic = new Dictionary <string, List <string> >();

        // classes
        foreach (var type in exportTypes)
        {
            List <string> memberNames;
            GenerateClass(type, out memberNames);
            allExportInfoDic.Add(JSNameMgr.GetJSTypeFullName(type), memberNames);
        }
        foreach (var type in otherExportTypes)
        {
            List <string> memberNames;
            GenerateClass(type, out memberNames);
            allExportInfoDic.Add(JSNameMgr.GetJSTypeFullName(type), memberNames);
        }

        foreach (var type in exportEnums)
        {
            GenerateEnum(type);
        }

        OnEnd();

        var sb = new StringBuilder();

        foreach (var item in allExportInfoDic)
        {
            sb.AppendFormat("[{0}]\r\n", item.Key);

            var lst = item.Value;
            foreach (string l in lst)
            {
                sb.AppendFormat("    {0}\r\n", l);
            }
            sb.Append("\r\n");
        }
        File.WriteAllText(JsExternalTools.GetAllExportedMembersFile(), sb.ToString());
    }
예제 #12
0
    public static string Get_Return(Type type, string expVar)
    {
        if (type == typeof(void))
        {
            return(expVar + ";");
        }

        if (type.IsArray)
        {
            arrayExchange.elementType = type.GetElementType();
            if (arrayExchange.elementType.IsArray)
            {
                Debug.LogError("Return [][] not supported");
                return(string.Empty);
            }
//            else if (arrayExchange.elementType.ContainsGenericParameters)
//            {
//                Debug.LogError(" Return T[] not supported");
//                return "/* Return T[] is not supported */";
//            }

            return(arrayExchange.Get_Return(expVar));
        }
        var    sb      = new StringBuilder();
        string keyword = SetMetatypeKeyword(type);

        if (type.IsPrimitive)
        {
            sb.AppendFormat("        {0}((int)JSApi.SetType.Rval, ({1})({2}));", keyword,
                            JSNameMgr.GetTypeFullName(type),
                            expVar);
        }
        else if (type.IsEnum)
        {
            sb.AppendFormat("        {0}((int)JSApi.SetType.Rval, (int){1});", keyword, expVar);
        }
        else
        {
            sb.AppendFormat("        {0}((int)JSApi.SetType.Rval, {1});", keyword, expVar);
        }
        return(sb.ToString());
    }
예제 #13
0
    public string Get_GetParam(Type t)
    {
        elementType = t.GetElementType();
        if (elementType.IsArray)
        {
            //...error
        }
        var    sb     = new StringBuilder();
        string getVal = JSDataExchangeEditor.GetMetatypeKeyword(elementType);

        string arrayFullName   = string.Empty;
        string elementFullName = string.Empty;

        if (elementType.IsGenericParameter)
        {
            arrayFullName   = "object[]";
            elementFullName = "object";
        }
        else
        {
            arrayFullName   = JSNameMgr.GetTypeFullName(t);
            elementFullName = JSNameMgr.GetTypeFullName(elementType);
        }
        sb.AppendFormat("JSDataExchangeMgr.GetJSArg<{0}>(() =>\n", arrayFullName)
        .Append("        [[\n")
        .AppendFormat("            int jsObjID = JSApi.getObject((int)JSApi.GetType.Arg);\n")
        .AppendFormat("            int length = JSApi.getArrayLength(jsObjID);\n")
        .AppendFormat("            var ret = new {0}[length];\n", elementFullName)
        .AppendFormat("            for (var i = 0; i < length; i++) [[\n")
        .AppendFormat("                JSApi.getElement(jsObjID, i);\n")
        .AppendFormat("                ret[i] = ({0}){1}((int)JSApi.GetType.SaveAndRemove);\n", elementFullName,
                      getVal)
        .AppendFormat("            ]]\n")
        .AppendFormat("            return ret;\n")
        .AppendFormat("        ]])");

        sb.Replace("[[", "{");
        sb.Replace("]]", "}");

        return(sb.ToString());
    }
예제 #14
0
    public string Get_Return(string expVar)
    {
        if (elementType == null)
        {
            Debug.LogError("JSDataExchange_Arr elementType == null !!");
            return("");
        }

        StringBuilder sb           = new StringBuilder();
        string        getValMethod = JSDataExchangeMgr.GetMetatypeKeyword(elementType).Replace("get", "set");

        // 2015.Sep.2
        // +ÅжÏarrRetΪnullµÄÇé¿ö
        if (elementType.ContainsGenericParameters)
        {
            sb.AppendFormat("    var arrRet = (Array){0};\n", expVar)
            .AppendFormat("    for (int i = 0; arrRet != null && i < arrRet.Length; i++)\n")
            .Append("    [[\n")
            .AppendFormat("        {0}((int)JSApi.SetType.SaveAndTempTrace, arrRet.GetValue(i));\n", getValMethod)
            .AppendFormat("        JSApi.moveSaveID2Arr(i);\n")
            .AppendFormat("    ]]\n")
            .AppendFormat("    JSApi.setArrayS((int)JSApi.SetType.Rval, (arrRet != null ? arrRet.Length : 0), true);");
        }
        else
        {
            sb.AppendFormat("    var arrRet = ({0}[]){1};\n", JSNameMgr.GetTypeFullName(elementType), expVar)
            .AppendFormat("    for (int i = 0; arrRet != null && i < arrRet.Length; i++)\n")
            .Append("    [[\n")
            .AppendFormat("        {0}((int)JSApi.SetType.SaveAndTempTrace, {1}arrRet[i]);\n", getValMethod, elementType.IsEnum ? "(int)" : "")
            .AppendFormat("        JSApi.moveSaveID2Arr(i);\n")
            .AppendFormat("    ]]\n")
            .AppendFormat("    JSApi.setArrayS((int)JSApi.SetType.Rval, (arrRet != null ? arrRet.Length : 0), true);");
        }

        sb.Replace("[[", "{");
        sb.Replace("]]", "}");

        return(sb.ToString());
    }
예제 #15
0
//    public string RecursivelyGetParam(Type type)
//    {
//        if (type.IsByRef)
//        {
//            return RecursivelyGetParam(type.GetElementType());
//        }
//        if (!type.IsArray)
//        {
//
//        }
//    }
    // Editor only
    public static ParamHandler Get_ParamHandler(Type type, int paramIndex, bool isRef, bool isOut)
    {
        var ph = new ParamHandler();

        ph.argName = "arg" + paramIndex;

        if (IsDelegateDerived(type))
        {
            Debug.LogError("Delegate derived class should not get here");
            return(ph);
        }

        bool bTOrContainsT = type.IsGenericParameter || type.ContainsGenericParameters;

        string typeFullName;

        if (bTOrContainsT)
        {
            typeFullName = "object";
        }
        else
        {
            typeFullName = JSNameMgr.GetTypeFullName(type);
        }

        if (type.IsArray)
        {
            ph.getter = new StringBuilder()
                        .AppendFormat("{0} {1} = {2};", typeFullName, ph.argName, arrayExchange.Get_GetParam(type))
                        .ToString();
        }
        else
        {
            if (isRef || isOut)
            {
                type = type.GetElementType();
            }
            string keyword = GetMetatypeKeyword(type);
            if (keyword == string.Empty)
            {
                Debug.LogError("keyword is empty: " + type.Name);
                return(ph);
            }

            if (isOut)
            {
                ph.getter = new StringBuilder()
                            .AppendFormat("int r_arg{0} = JSApi.incArgIndex();\n", paramIndex)
                            .AppendFormat("        {0} {1}{2};", typeFullName, ph.argName, bTOrContainsT ? " = null" : "")
                            .ToString();
            }
            else if (isRef)
            {
                ph.getter = new StringBuilder()
                            .AppendFormat("int r_arg{0} = JSApi.getArgIndex();\n", paramIndex)
                            .AppendFormat("{0} {1} = ({0}){2}((int)JSApi.GetType.ArgRef);", typeFullName, ph.argName, keyword)
                            .ToString();
            }
            else
            {
                ph.getter = new StringBuilder()
                            .AppendFormat("{0} {1} = ({0}){2}((int)JSApi.GetType.Arg);", typeFullName, ph.argName, keyword)
                            .ToString();
            }

            if (isOut || isRef)
            {
                var _sb = new StringBuilder();
                if (bTOrContainsT)
                {
                    // TODO
                    // sorry, 'arr_t' is written in CSGenerator2.cs
                    _sb.AppendFormat("        {0} = arr_t[{1}];\n", ph.argName, paramIndex);
                }

                ph.updater = _sb.AppendFormat("        JSApi.setArgIndex(r_arg{0});\n", paramIndex)
                             .AppendFormat("        {0}((int)JSApi.SetType.ArgRef, {1});\n", keyword.Replace("get", "set"),
                                           ph.argName)
                             .ToString();
            }
        }
        return(ph);
    }
예제 #16
0
    public static void OutputAllTypesWithJsTypeAttribute()
    {
        //var sb = new StringBuilder();
        var sb2 = new StringBuilder();

//        sb.Append(@"/* Generated by JSBinding Menu : JSB | Generate SharpKit JsType file CS.require list
//* see JSAnalyzer.cs / OutputAllTypesWithJsTypeAttribute() function
//* better not modify manually.
//*/
//
//");
        sb2.Append(@"/* Generated by JSBinding Menu : JSB | Generate MonoBehaviour to JSComponent_XX
* see JSAnalyzer.cs / OutputAllTypesWithJsTypeAttribute() function
* better not modify manually.
*/

");
        sb2.AppendLine("var MonoBehaviour2JSComponentName =").AppendLine("[");

        foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
        {
            Type[] types = a.GetTypes();
            foreach (Type t in types)
            {
                if (JSSerializerEditor.WillTypeBeTranslatedToJavaScript(t))
                {
                    System.Object[] attrs      = t.GetCustomAttributes(typeof(JsTypeAttribute), false);
                    JsTypeAttribute jsTypeAttr = (JsTypeAttribute)attrs[0];
                    if (jsTypeAttr.Filename != null)
                    {
                        //Debug.Log(jsTypeAttr.filename);

                        string mustBegin = "StreamingAssets/JavaScript/";
                        //string mustBegin = JSBindingSettings.sharpKitGenFileDir;
                        int index = 0;
                        if ((index = jsTypeAttr.Filename.IndexOf(mustBegin)) >= 0)
                        {
                            //sb.AppendFormat("CS.require(\"{0}\");\n", jsTypeAttr.Filename.Substring(index + mustBegin.Length));
                        }
                        else
                        {
                            Debug.LogError(JSNameMgr.GetTypeFullName(t) + " is ignored because JsType.filename doesn't contain \"" + mustBegin + "\"");
                        }
                    }

                    /////
                    if (t.IsSubclassOf(typeof(MonoBehaviour)))
                    {
                        string jsComponentName = JSComponentGenerator.GetJSComponentClassName(t);
                        sb2.AppendFormat("    \"{0}|{1}\",\n", JSNameMgr.GetTypeFullName(t, false), jsComponentName);
                    }
                }
            }
        }
        sb2.AppendLine("];");
        sb2.Append(@"

var GetMonoBehaviourJSComponentName = function (i)
{
    if (i < MonoBehaviour2JSComponentName.length)
    {
        return MonoBehaviour2JSComponentName[i];
    }
    return """"; // returning empty string when end
}
");

        //Debug.Log(sb);

        string path = JSBindingSettings.sharpkitGeneratedFiles;

        // 现在不需要这个
//        File.WriteAllText(path, sb.ToString());
//        Debug.Log("OK. File: " + path);
        // AssetDatabase.Refresh();

        path = JSBindingSettings.monoBehaviour2JSComponentName;
        File.WriteAllText(path, sb2.ToString());
        Debug.Log("OK. File: " + path);
    }
예제 #17
0
    //
    // arg: a,b,c
    //
    public static string BuildCallString(Type classType, MemberInfo memberInfo, string argList, MemberFeature features,
                                         string newValue = "")
    {
        bool   bGenericT    = classType.IsGenericTypeDefinition;
        string memberName   = memberInfo.Name;
        bool   bIndexer     = (features & MemberFeature.Indexer) > 0;
        bool   bStatic      = (features & MemberFeature.Static) > 0;
        bool   bStruct      = classType.IsValueType;
        string typeFullName = JSNameMgr.GetTypeFullName(classType);
        bool   bField       = memberInfo is FieldInfo;
        bool   bProperty    = memberInfo is PropertyInfo;
        bool   bGet         = (features & MemberFeature.Get) > 0;
        bool   bSet         = (features & MemberFeature.Set) > 0;

        if ((bGet && bSet) || (!bGet && !bSet))
        {
            return(">>>> sorry >>>>");
        }

        var sb = new StringBuilder();

        if (bField || bProperty)
        {
            if (!bGenericT)
            {
                string strThis = typeFullName;
                if (!bStatic)
                {
                    strThis = "_this";
                    sb.AppendFormat("        {0} _this = ({0})vc.csObj;\n", typeFullName);
                }

                string result = string.Empty;
                if (bGet)
                {
                    // convention: name 'result'
                    result = "var result = ";
                }

                if (bIndexer)
                {
                    sb.AppendFormat("        {2}{0}[{1}]", strThis, argList, result);
                }
                else
                {
                    sb.AppendFormat("        {2}{0}.{1}", strThis, memberName, result);
                }

                if (bGet)
                {
                    sb.Append(";\n");
                }
                else
                {
                    sb.AppendFormat(" = {0};\n", newValue);
                    if (!bStatic && bStruct)
                    {
                        sb.Append("        JSMgr.changeJSObj(vc.jsObjID, _this);\n");
                    }
                }
            }
            else
            {
                // convention: name 'member'
                if (bIndexer || !bIndexer) // both indexer and not indexer enters
                {
                    if (bProperty)
                    {
                        sb.AppendFormat("        {4}member.{0}({1}, {2}new object[][[{3}]]);\n",
                                        bGet ? "GetValue" : "SetValue",
                                        bStatic ? "null" : "vc.csObj",
                                        bSet ? newValue + ", " : "",
                                        argList,
                                        bGet ? "var result = " : "");
                    }
                    else
                    {
                        sb.AppendFormat("        {3}member.{0}({1}{2});\n",
                                        bGet ? "GetValue" : "SetValue",
                                        bStatic ? "null" : "vc.csObj",
                                        bSet ? ", " + newValue : "",
                                        bGet ? "var result = " : "");
                    }
                }
            }
        }
        return(sb.ToString());
    }
예제 #18
0
 public static string SharpKitClassName(Type type)
 {
     return(JSNameMgr.GetJSTypeFullName(type));
 }
예제 #19
0
    public static StringBuilder BuildHeader(Type type)
    {
        string fmt        = @"// {0}
_jstype = jst_pushOrReplace([[
    definition: [[]],
    staticDefinition: [[]],
    fields: [[]],
    staticFields: [[]],
    assemblyName: '{1}',
    Kind: '{2}',
    fullname: '{3}', {4}
    {5}
]]);
";
        string jsTypeName = JSNameMgr.GetTypeFullName(type);

        jsTypeName = jsTypeName.Replace('.', '$');

        string assemblyName = "";
        string Kind         = "unknown";

        if (type.IsClass)
        {
            Kind = "Class";
        }
        else if (type.IsEnum)
        {
            Kind = "Enum";
        }
        else if (type.IsValueType)
        {
            Kind = "Struct";
        }
        else if (type.IsInterface)
        {
            Kind = "Interface";
        }

        string fullname     = SharpKitClassName(type);
        string baseTypeName = SharpKitClassName(type.BaseType);

        Type[]        interfaces = type.GetInterfaces();
        StringBuilder sbI        = new StringBuilder();

        if (interfaces != null && interfaces.Length > 0)
        {
            sbI.Append("\n    interfaceNames: [");
            for (int i = 0; i < interfaces.Length; i++)
            {
                sbI.AppendFormat("\'{0}\'", SharpKitClassName(interfaces[i]));
                if (i < interfaces.Length - 1)
                {
                    sbI.Append(", ");
                }
            }
            sbI.Append("],");
        }

        StringBuilder sb = new StringBuilder();

        sb.AppendFormat(fmt,
                        jsTypeName,                                                             // [0]
                        assemblyName,                                                           // [1]
                        Kind,                                                                   // [2]
                        fullname,                                                               // [3] full name
                        sbI.ToString(),                                                         // [4] interfaceNames
                        baseTypeName.Length > 0 ? "baseTypeName: '" + baseTypeName + "'" : ""); // [5] baseTypeName

        return(sb);
    }
예제 #20
0
    // CheckClassBindings: check 'classes' array
    // 1 skip something unnecessary or unsupported
    // 2 auto add base classes & interfaces
    public static Type[] CheckClassBindings()
    {
        HashSet <Type> skips = new HashSet <Type>();
        {
            //
            // these types are defined in clrlibrary.javascript
            //
            skips.Add(typeof(System.Object));
            skips.Add(typeof(System.Exception));
            skips.Add(typeof(System.SystemException));
            skips.Add(typeof(System.ValueType));
        }

        HashSet <Type> wanted = new HashSet <Type>();
        var            sb     = new StringBuilder();
        bool           ret    = true;

        foreach (var type in classes)
        {
            // delegate is not allowed
            if (typeof(System.Delegate).IsAssignableFrom(type))
            {
                sb.AppendFormat("Delegate \"{0}\" can not be exported.\n",
                                JSNameMgr.GetTypeFullName(type));
                ret = false;
            }

            // generic type but not generic type definition is not allowed
            if (type.IsGenericType && !type.IsGenericTypeDefinition)
            {
                sb.AppendFormat("\"{0}\" is not allowed. Try \"{1}\".\n",
                                JSNameMgr.GetTypeFullName(type), JSNameMgr.GetTypeFullName(type.GetGenericTypeDefinition()));
                ret = false;
            }

            // interfaces should not be in this array, they are auto-added
            if (type.IsInterface)
            {
                sb.AppendFormat("Interface \"{0}\" should not be in JSBindingSettings.classes.\n",
                                JSNameMgr.GetTypeFullName(type));
                ret = false;
            }

            // duplicated type is not allowed
            if (wanted.Contains(type))
            {
                sb.AppendFormat("There are more than 1 \"{0}\" in JSBindingSettings.classes.\n",
                                JSNameMgr.GetTypeFullName(type));
                ret = false;
            }
            else if (!skips.Contains(type))
            {
                wanted.Add(type);
            }
        }

        // add base types
        foreach (var typeb in wanted.ToArray())
        {
            Type type = typeb;

            // add base types
            Type baseType = type.BaseType;
            while (baseType != null)
            {
                if (!skips.Contains(baseType) && !wanted.Contains(baseType) &&
                    !(baseType.IsGenericType && !baseType.IsGenericTypeDefinition) &&
                    !IsDiscardType(baseType))
                {
                    wanted.Add(baseType);
                }
                baseType = baseType.BaseType;
            }
        }

        // add interfaces
        foreach (var typeb in wanted.ToArray())
        {
            Type   type       = typeb;
            Type[] interfaces = type.GetInterfaces();
            for (int i = 0; i < interfaces.Length; i++)
            {
                Type   ti         = interfaces[i];
                string tiFullName = JSNameMgr.GetTypeFullName(ti);

                // some intefaces's name has <>, skip them
                if (!tiFullName.Contains("<") && !tiFullName.Contains(">") &&
                    !skips.Contains(ti) && !wanted.Contains(ti) &&
                    !IsDiscardType(ti))
                {
                    wanted.Add(ti);
                }
            }
        }

        Type[] arr = null;
        if (!ret)
        {
            Debug.LogError(sb);
        }
        else
        {
            arr = new Type[wanted.Count];
            wanted.CopyTo(arr);

            // output final types to be exported
            sb.Remove(0, sb.Length);
            sb.AppendLine("Classes to export:");
            foreach (var t in arr)
            {
                sb.AppendLine(JSNameMgr.GetTypeFullName(t));
            }
            Debug.Log(sb.ToString());
        }
        return(arr);
    }
예제 #21
0
        public void Alloc(JSSerializer serializer)
        {
            eSerialize = SerializeType.String;
            switch (analyzeType)
            {
            case JSSerializer.AnalyzeType.ArrayBegin:
                AllocString("ArrayBegin/" + this.Name + "/");
                break;

            case JSSerializer.AnalyzeType.ArrayEnd:
                AllocString("ArrayEnd/" + this.Name + "/");
                break;

            case JSSerializer.AnalyzeType.StructBegin:
                AllocString("StructBegin/" + this.Name + "/" + JSNameMgr.GetTypeFullName(this.type));
                break;

            case JSSerializer.AnalyzeType.StructEnd:
                AllocString("StructEnd/" + this.Name + "/" + JSNameMgr.GetTypeFullName(this.type));
                break;

            case JSSerializer.AnalyzeType.ListBegin:
                AllocString("ListBegin/" + this.Name + "/" + JSNameMgr.GetTypeFullName(typeof(List <>)));
                break;

            case JSSerializer.AnalyzeType.ListEnd:
                AllocString("ListEnd/" + this.Name + "/" + JSNameMgr.GetTypeFullName(typeof(List <>)));
                break;

            case JSSerializer.AnalyzeType.Unit:
            {
                var sb = new StringBuilder();

                // this.value could be null
                Type declaredType = this.type;
                Type valueType    = (this.value != null ? this.value.GetType() : declaredType);

                if (this.unitType == JSSerializer.UnitType.ST_JavaScriptMonoBehaviour ||
                    this.unitType == JSSerializer.UnitType.ST_UnityEngineObject)
                {
                    eSerialize = SerializeType.Object;

                    if (this.unitType == JSSerializer.UnitType.ST_JavaScriptMonoBehaviour)
                    {
                        if (!typeof(UnityEngine.MonoBehaviour).IsAssignableFrom(valueType) ||
                            !WillTypeBeTranslatedToJavaScript(valueType))
                        {
                            Debug.LogError("unitType is ST_JavaScriptMonoBehaviour, but valueType is not MonoBehaviour or doesn't JsType attribute.");
                        }

                        // if a monobehaviour is referenced
                        // and this monobehaviour will be translated to js later
                        //  ST_MonoBehaviour

                        // add game object
                        // this.value can be null
                        int index;
                        if (this.value == null)
                        {
                            index = AllocObject(null);
                        }
                        else
                        {
                            index = AllocObject(((MonoBehaviour)this.value).gameObject);
                        }

                        // UnitType / Name / object Index / MonoBehaviour Name
                        sb.AppendFormat("{0}/{1}/{2}/{3}", (int)this.unitType, this.Name, index, JSNameMgr.GetTypeFullName(valueType));
                        AllocString(sb.ToString());
                    }
                    else
                    {
                        // UnitType / Name / object Index
                        sb.AppendFormat("{0}/{1}/{2}", (int)this.unitType, this.Name, AllocObject((UnityEngine.Object) this.value));
                        AllocString(sb.ToString());
                    }
                }
                else
                {
                    sb.AppendFormat("{0}/{1}/{2}", (int)this.unitType, this.Name,
                                    ValueToString(this.value, this.type));
                    AllocString(sb.ToString());
                }
            }
            break;
            }
        }