少年修仙传客户端代码仓库
client_Wu Xijin
2019-02-20 a87120c155c48fa45b20a97c1a58bdbeb77318b7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
-- Tencent is pleased to support the open source community by making xLua available.
-- Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
-- Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
-- http://opensource.org/licenses/MIT
-- Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
 
local friendlyNameMap = {
    ["System.Object"] = "object",
    ["System.String"] = "string",
    ["System.Boolean"] = "bool",
    ["System.Byte"] = "byte",
    ["System.Char"] = "char",
    ["System.Decimal"] = "decimal",
    ["System.Double"] = "double",
    ["System.Int16"] = "short",
    ["System.Int32"] = "int",
    ["System.Int64"] = "long",
    ["System.SByte"] = "sbyte",
    ["System.Single"] = "float",
    ["System.UInt16"] = "ushort",
    ["System.UInt32"] = "uint",
    ["System.UInt64"] = "ulong",
    ["System.Void"] = "void",
}
 
local csKeywords = {
"abstract", "as", "base", "bool",
"break", "byte", "case", "catch",
"char", "checked", "class", "const",
"continue", "decimal", "default", "delegate",
"do", "double", "else", "enum",
"event", "explicit", "extern", "false",
"finally", "fixed", "float", "for",
"foreach", "goto", "if", "implicit",
"in", "int", "interface",
"internal", "is", "lock", "long",
"namespace", "new", "null", "object",
"operator", "out", "override",
"params", "private", "protected", "public",
"readonly", "ref", "return", "sbyte",
"sealed", "short", "sizeof", "stackalloc",
"static", "string", "struct", "switch",
"this", "throw", "true", "try",
"typeof", "uint", "ulong", "unchecked",
"unsafe", "ushort", "using", "virtual",
"void", "volatile", "while"
}
 
for _, kw in ipairs(csKeywords) do
    csKeywords[kw] = '@'..kw
end
for i = 1, #csKeywords do
    csKeywords[i] = nil
end
 
function UnK(symbol)
    return csKeywords[symbol] or symbol
end
 
local fixChecker = {
    --["System.String"] = "LuaAPI.lua_isstring",
    ["System.Boolean"] = "LuaTypes.LUA_TBOOLEAN == LuaAPI.lua_type",
    ["System.Byte"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type",
    ["System.Char"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type",
    --["System.Decimal"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type",
    ["System.Double"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type",
    ["System.Int16"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type",
    ["System.Int32"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type",
    --["System.Int64"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type",
    ["System.SByte"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type",
    ["System.Single"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type",
    ["System.UInt16"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type",
    ["System.UInt32"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type",
    --["System.UInt64"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type",
    ["System.IntPtr"] = "LuaTypes.LUA_TLIGHTUSERDATA == LuaAPI.lua_type",
}
 
local typedCaster = {
    ["System.Byte"] = "LuaAPI.xlua_tointeger",
    ["System.Char"] = "LuaAPI.xlua_tointeger",
    ["System.Int16"] = "LuaAPI.xlua_tointeger",
    ["System.SByte"] = "LuaAPI.xlua_tointeger",
    ["System.Single"] = "LuaAPI.lua_tonumber",
    ["System.UInt16"] = "LuaAPI.xlua_tointeger",
}
 
local fixCaster = {
    ["System.Double"] = "LuaAPI.lua_tonumber",
    ["System.String"] = "LuaAPI.lua_tostring",
    ["System.Boolean"] = "LuaAPI.lua_toboolean",
    ["System.Byte[]"] = "LuaAPI.lua_tobytes",
    ["System.IntPtr"] = "LuaAPI.lua_touserdata",
    ["System.UInt32"] = "LuaAPI.xlua_touint",
    ["System.UInt64"] = "LuaAPI.lua_touint64",
    ["System.Int32"] = "LuaAPI.xlua_tointeger",
    ["System.Int64"] = "LuaAPI.lua_toint64",
}
 
local fixPush = {
    ["System.Byte"] = "LuaAPI.xlua_pushinteger",
    ["System.Char"] = "LuaAPI.xlua_pushinteger",
    ["System.Int16"] = "LuaAPI.xlua_pushinteger",
    ["System.Int32"] = "LuaAPI.xlua_pushinteger",
    ["System.Int64"] = "LuaAPI.lua_pushint64",
    ["System.SByte"] = "LuaAPI.xlua_pushinteger",
    ["System.Single"] = "LuaAPI.lua_pushnumber",
    ["System.UInt16"] = "LuaAPI.xlua_pushinteger",
    ["System.UInt32"] = "LuaAPI.xlua_pushuint",
    ["System.UInt64"] = "LuaAPI.lua_pushuint64",
    ["System.Single"] = "LuaAPI.lua_pushnumber",
    ["System.Double"] = "LuaAPI.lua_pushnumber",
    ["System.String"] = "LuaAPI.lua_pushstring",
    ["System.Byte[]"] = "LuaAPI.lua_pushstring",
    ["System.Boolean"] = "LuaAPI.lua_pushboolean",
    ["System.IntPtr"] = "LuaAPI.lua_pushlightuserdata",
    ["System.Decimal"] = "translator.PushDecimal",
    ["System.Object"] = "translator.PushAny",
}
 
local notranslator = {
    ["System.Byte"] = true,
    ["System.Char"] = true,
    ["System.Int16"] = true,
    ["System.Int32"] = true,
    ["System.Int64"] = true,
    ["System.SByte"] = true,
    ["System.Single"] = true,
    ["System.UInt16"] = true,
    ["System.UInt32"] = true,
    ["System.UInt64"] = true,
    ["System.Double"] = true,
    ["System.String"] = true,
    ["System.Boolean"] = true,
    ["System.Void"] = true,
    ["System.IntPtr"] = true,
    ["System.Byte[]"] = true,
}
 
function ForEachCsList(...)
    local list_count = select('#', ...) - 1
    local callback = select(list_count + 1, ...)
    for i = 1, list_count do
        local list = select(i, ...)
        for i = 0, (list.Count or list.Length) - 1 do 
            callback(list[i], i)
        end
    end
end
 
function CalcCsList(list, predicate)
    local count = 0
    for i = 0, (list.Count or list.Length) - 1 do 
        if predicate(list[i], i) then count = count + 1 end
    end
    return count
end
 
function IfAny(list, predicate)
    for i = 0, (list.Count or list.Length) - 1 do 
        if predicate(list[i], i) then return true end
    end
    return false
end
 
local genPushAndUpdateTypes
 
function SetGenPushAndUpdateTypes(list)
    genPushAndUpdateTypes = {}
    ForEachCsList(list, function(t)
        genPushAndUpdateTypes[t] = true
    end)
end
 
local xLuaClasses
function SetXLuaClasses(list)
    xLuaClasses = {}
    ForEachCsList(list, function(t)
        xLuaClasses[t.Name] = true
    end)
end
 
local objType = typeof(CS.System.Object)
local valueType = typeof(CS.System.ValueType)
 
local function _CsFullTypeName(t)
    if t.IsArray then
        local element_name, element_is_array = _CsFullTypeName(t:GetElementType())
        if element_is_array then
            local bracket_pos = element_name:find('%[')
            return element_name:sub(1, bracket_pos - 1) .. '[' .. string.rep(',', t:GetArrayRank() - 1) .. ']' .. element_name:sub(bracket_pos, -1), true
        else
            return element_name .. '[' .. string.rep(',', t:GetArrayRank() - 1) .. ']', true
        end
    elseif t.IsByRef then
        return _CsFullTypeName(t:GetElementType())
    elseif t.IsGenericParameter then
        return (t.BaseType == objType or t.BaseType == valueType) and t.Name or _CsFullTypeName(t.BaseType) --TODO:应该判断是否类型约束
    end
 
    local name = t.FullName:gsub("&", ""):gsub("%+", ".") 
    if not t.IsGenericType then 
        return friendlyNameMap[name] or name
    end
    local genericParameter = ""
    ForEachCsList(t:GetGenericArguments(), function(at, ati)
        if ati ~= 0 then  genericParameter = genericParameter .. ', ' end
        genericParameter = genericParameter .. _CsFullTypeName(at)
    end)
    return name:gsub("`%d+", '<' .. genericParameter .. '>'):gsub("%[[^,%]].*", ""), false
end
 
function CsFullTypeName(t)
    local name = _CsFullTypeName(t)
    return xLuaClasses[name] and ("global::" .. name) or name
end
 
function CSVariableName(t)
    if t.IsArray then
        return CSVariableName(t:GetElementType()) .. '_'.. t:GetArrayRank() ..'_'
    end
    return t:ToString():gsub("&", ""):gsub("%+", ""):gsub("`", "_"):gsub("%.", ""):gsub("%[", "_"):gsub("%]", "_"):gsub(",", "")
end
 
local function getSafeFullName(t)
    if t == nil then
        return ""
    end
 
    if t.IsGenericParameter then
        return t.BaseType == objType and t.Name or getSafeFullName(t.BaseType)
    end
    
    if not t.FullName then return "" end
 
    return t.FullName:gsub("&", "")
end
 
function GetCheckStatement(t, idx, is_v_params)
    local cond_start = is_v_params and "(LuaTypes.LUA_TNONE == LuaAPI.lua_type(L, ".. idx ..") || " or ""
    local cond_end = is_v_params and ")" or ""
    local testname = getSafeFullName(t)
    if testname ==  "System.String" or testname == "System.Byte[]" then
        return cond_start .. "(LuaAPI.lua_isnil(L, " .. idx .. ") || LuaAPI.lua_type(L, ".. idx ..") == LuaTypes.LUA_TSTRING)" .. cond_end
    elseif testname == "System.Int64" then
        return cond_start .. "(LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, ".. idx ..") || LuaAPI.lua_isint64(L, ".. idx .."))" .. cond_end
    elseif testname == "System.UInt64" then
        return cond_start .. "(LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, ".. idx ..") || LuaAPI.lua_isuint64(L, ".. idx .."))" .. cond_end
    elseif testname == "System.Decimal" then
        return cond_start .. "(LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, ".. idx ..") || translator.IsDecimal(L, ".. idx .."))" .. cond_end
    elseif testname == "XLua.LuaTable" then
        return cond_start .. "(LuaAPI.lua_isnil(L, " .. idx .. ") || LuaAPI.lua_type(L, ".. idx ..") == LuaTypes.LUA_TTABLE)" .. cond_end
    elseif testname == "XLua.LuaFunction" then
        return cond_start .. "(LuaAPI.lua_isnil(L, " .. idx .. ") || LuaAPI.lua_type(L, ".. idx ..") == LuaTypes.LUA_TFUNCTION)" .. cond_end
    end
    return cond_start .. (fixChecker[testname] or ("translator.Assignable<" .. CsFullTypeName(t).. ">")) .. "(L, ".. idx ..")" .. cond_end
end
 
local delegateType = typeof(CS.System.Delegate)
local ExtensionAttribute = typeof(CS.System.Runtime.CompilerServices.ExtensionAttribute)
function MethodParameters(method)
    if not method:IsDefined(ExtensionAttribute, false) then
        return method:GetParameters()
    else
        local parameters = method:GetParameters()
        if parameters[0].ParameterType.IsInterface then
            return parameters
        end
        local ret = {}
        for i = 1, parameters.Length - 1 do 
            ret[i - 1] = parameters[i]
        end
        ret.Length = parameters.Length - 1
        return ret
    end
end
 
function IsStruct(t)
    if t.IsByRef then t = t:GetElementType() end
    return t.IsValueType and not t.IsPrimitive
end
 
function NeedUpdate(t)
    if t.IsByRef then t = t:GetElementType() end
    return t.IsValueType and not t.IsPrimitive and not t.IsEnum and t ~= typeof(CS.System.Decimal)
end
 
function GetCasterStatement(t, idx, var_name, need_declare, is_v_params)
    local testname = getSafeFullName(t)
    local statement = ""
    local is_struct = IsStruct(t)
    
    if need_declare then
        statement = CsFullTypeName(t) .. " " .. var_name
        if is_struct and not typedCaster[testname] and not fixCaster[testname] then
            statement = statement .. ";"
        else
            statement = statement .. " = "
        end
    elseif not is_struct then
        statement = var_name .. " = "
    end
    
    if is_v_params then
        return statement .. "translator.GetParams<" .. CsFullTypeName(t:GetElementType()).. ">" .. "(L, ".. idx ..")" 
    elseif typedCaster[testname] then
        return statement .. "(" .. CsFullTypeName(t) .. ")" ..typedCaster[testname] .. "(L, ".. idx ..")" 
    elseif delegateType:IsAssignableFrom(t) then
        return statement .. "translator.GetDelegate<" .. CsFullTypeName(t).. ">" .. "(L, ".. idx ..")" 
    elseif fixCaster[testname] then
        return statement .. fixCaster[testname] .. "(L, ".. idx ..")" 
    elseif testname == "System.Object" then
        return statement .. "translator.GetObject(L, ".. idx ..", typeof(" .. CsFullTypeName(t) .."))"
    elseif is_struct then
        return statement .. "translator.Get(L, ".. idx ..", out " .. var_name .. ")"
    elseif t.IsGenericParameter and not t.DeclaringMethod then
        return statement .. "translator.GetByType<"..t.Name..">(L, ".. idx ..")" 
    else
        return statement .. "("..CsFullTypeName(t)..")translator.GetObject(L, ".. idx ..", typeof(" .. CsFullTypeName(t) .."))" 
    end
end
 
local paramsAttriType = typeof(CS.System.ParamArrayAttribute)
function IsParams(pi)
    if (not pi.IsDefined) then
        return pi.IsParamArray
    end
    return pi:IsDefined(paramsAttriType, false)
end
 
local obsoluteAttriType = typeof(CS.System.ObsoleteAttribute)
function IsObsolute(f)
    return f:IsDefined(obsoluteAttriType, false)
end
 
local objectType = typeof(CS.System.Object)
function GetSelfStatement(t)
    local fulltypename = CsFullTypeName(t)
    local is_struct = IsStruct(t)
    if is_struct then
        return fulltypename .. " gen_to_be_invoked;translator.Get(L, 1, out gen_to_be_invoked)"
    else
        if t == objectType then
            return "object gen_to_be_invoked = translator.FastGetCSObj(L, 1)"
        else
            return fulltypename .. " gen_to_be_invoked = (" .. fulltypename .. ")translator.FastGetCSObj(L, 1)"
        end
    end
    
end
 
local GetNullableUnderlyingType = CS.System.Nullable.GetUnderlyingType
 
function GetPushStatement(t, variable, is_v_params)
    if is_v_params then
        local item_push = GetPushStatement(t:GetElementType(), variable..'[__gen_i]')
        return 'if ('.. variable ..' != null)  { for (int __gen_i = 0; __gen_i < ' .. variable .. '.Length; ++__gen_i) ' .. item_push .. '; }'
    end
    if t.IsByRef then t = t:GetElementType() end
    local testname = getSafeFullName(t)
    if fixPush[testname] then
        return fixPush[testname] .. "(L, ".. variable ..")" 
    elseif genPushAndUpdateTypes[t] then
        return "translator.Push".. CSVariableName(t) .."(L, "..variable..")"
    elseif t.IsGenericParameter and not t.DeclaringMethod then
        return "translator.PushByType(L, "..variable..")"
    elseif t.IsInterface or GetNullableUnderlyingType(t) then
        return "translator.PushAny(L, "..variable..")"
    else
        return "translator.Push(L, "..variable..")"
    end
end
 
function GetUpdateStatement(t, idx, variable)
    if t.IsByRef then t = t:GetElementType() end
    if typeof(CS.System.Decimal) == t then error('Decimal not update!') end
    if genPushAndUpdateTypes[t] then
        return "translator.Update".. CSVariableName(t) .."(L, ".. idx ..", "..variable..")"
    else
        return "translator.Update(L, ".. idx ..", "..variable..")"
    end
end
 
function JustLuaType(t)
    return notranslator[getSafeFullName(t)]
end
 
function CallNeedTranslator(overload, isdelegate)
    if not overload.IsStatic and not isdelegate then return true end
    local ret_type_name = getSafeFullName(overload.ReturnType)
    if not notranslator[ret_type_name] then return true end 
    local parameters = overload:GetParameters()
    return IfAny(overload:GetParameters(), function(parameter) 
        return IsParams(parameter) or (not notranslator[getSafeFullName(parameter.ParameterType)])
    end)
end
 
function MethodCallNeedTranslator(method)
    return IfAny(method.Overloads, function(overload) return CallNeedTranslator(overload) end)
end
 
function AccessorNeedTranslator(accessor)
    return not accessor.IsStatic or not JustLuaType(accessor.Type)
end
 
local GenericParameterAttributes = CS.System.Reflection.GenericParameterAttributes
local enum_and_op = debug.getmetatable(CS.System.Reflection.BindingFlags.Public).__band
local has_generic_flag = function(f1, f2)
    return (f1 ~= GenericParameterAttributes.None) and (enum_and_op(f1, f2) == f2)
end
 
function GenericArgumentList(type)
    local generic_arg_list = ""
    local type_constraints = ""
    if type.IsGenericTypeDefinition then
        generic_arg_list = "<"
        
        local constraints = {}
        
        ForEachCsList(type:GetGenericArguments(), function(generic_arg, gai)
            local constraint = {}
            if gai ~= 0 then generic_arg_list = generic_arg_list .. ", " end
            
            generic_arg_list = generic_arg_list .. generic_arg.Name
            
            if has_generic_flag(generic_arg.GenericParameterAttributes, GenericParameterAttributes.ReferenceTypeConstraint) then
                table.insert(constraint, 'class')
            end
            if has_generic_flag(generic_arg.GenericParameterAttributes, GenericParameterAttributes.NotNullableValueTypeConstraint) then
                table.insert(constraint, 'struct')
            end
            ForEachCsList(generic_arg:GetGenericParameterConstraints(), function(gpc)
                if gpc ~= typeof(CS.System.ValueType) or not has_generic_flag(generic_arg.GenericParameterAttributes, GenericParameterAttributes.NotNullableValueTypeConstraint) then
                    table.insert(constraint, CsFullTypeName(gpc))
                end
            end)
            if not has_generic_flag(generic_arg.GenericParameterAttributes, GenericParameterAttributes.NotNullableValueTypeConstraint) and has_generic_flag(generic_arg.GenericParameterAttributes, GenericParameterAttributes.DefaultConstructorConstraint) then
                table.insert(constraint, 'new()')
            end
            if #constraint > 0 then
                table.insert(constraints, 'where ' .. generic_arg.Name .. ' : ' .. table.concat(constraint, ','))
            end
        end)
        generic_arg_list = generic_arg_list .. ">"
        if #constraints > 0 then
            type_constraints = table.concat(constraints, ',')
        end
    end
    return generic_arg_list, type_constraints
end
 
function LocalName(name)
    return "_" .. name
end