少年修仙传客户端基础资源
client_Wu Xijin
2018-10-31 6efd4c3b791d7aac3b0b5b5e2867f533457a7f2b
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
/*
 * 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.
*/
 
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLua.LuaDLL.lua_CSFunction;
#endif
 
using System;
using System.Linq;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using XLua;
 
namespace XLua.TemplateEngine
{
    public enum TokenType
    {
        Code, Eval, Text
    }
 
    public class Chunk
    {
        public TokenType Type {get; private set;}
        public string Text { get; private set; }
        public Chunk(TokenType type, string text)
        {
            Type = type;
            Text = text;
        }
    }
 
    class TemplateFormatException : Exception
    {
        public TemplateFormatException(string message)
        {
        }
    }
 
    public class Parser
    {
        public static string RegexString
        {
            get;
            private set;
        }
 
        static Parser()
        {
            RegexString = GetRegexString();
        }
 
        /// <summary>
        /// Replaces special characters with their literal representation.
        /// </summary>
        /// <returns>Resulting string.</returns>
        /// <param name="input">Input string.</param>
        static string EscapeString(string input)
        {
            var output = input
                .Replace("\\", @"\\")
                    .Replace("\'", @"\'")
                    .Replace("\"", @"\""")
                    .Replace("\n", @"\n")
                    .Replace("\t", @"\t")
                    .Replace("\r", @"\r")
                    .Replace("\b", @"\b")
                    .Replace("\f", @"\f")
                    .Replace("\a", @"\a")
                    .Replace("\v", @"\v")
                    .Replace("\0", @"\0");
            /*          var surrogateMin = (char)0xD800;
            var surrogateMax = (char)0xDFFF;
            for (char sur = surrogateMin; sur <= surrogateMax; sur++)
                output.Replace(sur, '\uFFFD');*/
            return output;
        }
 
        static string GetRegexString()
        {
            string regexBadUnopened = @"(?<error>((?!<%).)*%>)";
            string regexText = @"(?<text>((?!<%).)+)";
            string regexNoCode = @"(?<nocode><%=?%>)";
            string regexCode = @"<%(?<code>[^=]((?!<%|%>).)*)%>";
            string regexEval = @"<%=(?<eval>((?!<%|%>).)*)%>";
            string regexBadUnclosed = @"(?<error><%.*)";
            string regexBadEmpty = @"(?<error>^$)";
 
            return '(' + regexBadUnopened
                + '|' + regexText
                + '|' + regexNoCode
                + '|' + regexCode
                + '|' + regexEval
                + '|' + regexBadUnclosed
                + '|' + regexBadEmpty
                + ")*";
        }
 
        /// <summary>
        /// Parses the string into regex groups, 
        /// stores group:value pairs in List of Chunk
        /// <returns>List of group:value pairs.</returns>;
        /// </summary>
        public static List<Chunk> Parse(string snippet)
        {
            Regex templateRegex = new Regex(
                RegexString,
                RegexOptions.ExplicitCapture | RegexOptions.Singleline
            );
            Match matches = templateRegex.Match(snippet);
 
            if (matches.Groups["error"].Length > 0)
            {
                throw new TemplateFormatException("Messed up brackets");
            }
 
            List<Chunk> Chunks = matches.Groups["code"].Captures
                .Cast<Capture>()
                .Select(p => new { Type = TokenType.Code, p.Value, p.Index })
                .Concat(matches.Groups["text"].Captures
                .Cast<Capture>()
                .Select(p => new { Type = TokenType.Text, Value = EscapeString(p.Value), p.Index }))
                .Concat(matches.Groups["eval"].Captures
                .Cast<Capture>()
                .Select(p => new { Type = TokenType.Eval, p.Value, p.Index }))
                .OrderBy(p => p.Index)
                .Select(m => new Chunk(m.Type, m.Value))
                .ToList();
 
            if (Chunks.Count == 0)
            {
                throw new TemplateFormatException("Empty template");
            }
            return Chunks;
        }
    }
 
    public class LuaTemplate
    {
        public static string ComposeCode(List<Chunk> chunks)
        {
            StringBuilder code = new StringBuilder();
 
            code.Append("local __text_gen = {}\r\n");
            foreach (var chunk in chunks)
            {
                switch (chunk.Type)
                {
                    case TokenType.Text:
                        code.Append("table.insert(__text_gen, \"" + chunk.Text + "\")\r\n");
                        break;
                    case TokenType.Eval:
                        code.Append("table.insert(__text_gen, tostring(" + chunk.Text + "))\r\n");
                        break;
                    case TokenType.Code:
                        code.Append(chunk.Text + "\r\n");
                        break;
                }
            }
 
            code.Append("return table.concat(__text_gen)\r\n");
            //UnityEngine.Debug.Log("code compose:"+code.ToString());
            return code.ToString();
        }
 
        public static LuaFunction Compile(LuaEnv luaenv, string snippet)
        {
            return luaenv.LoadString(ComposeCode(Parser.Parse(snippet)), "luatemplate");
        }
 
        public static string Execute(LuaFunction compiledTemplate, LuaTable parameters)
        {
            compiledTemplate.SetEnv(parameters);
            object[] result = compiledTemplate.Call();
            System.Diagnostics.Debug.Assert(result.Length == 1);
            return result[0].ToString();
        }
 
        public static string Execute(LuaFunction compiledTemplate)
        {
            object[] result = compiledTemplate.Call();
            System.Diagnostics.Debug.Assert(result.Length == 1);
            return result[0].ToString();
        }
 
        [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
        public static int Compile(RealStatePtr L)
        {
            string snippet = LuaAPI.lua_tostring(L, 1);
            
            string code;
            try
            {
                code = ComposeCode(Parser.Parse(snippet));
            }
            catch (Exception e)
            {
                return LuaAPI.luaL_error(L, String.Format("template compile error:{0}\r\n", e.Message));
            }
            //UnityEngine.Debug.Log("code=" + code);
            if (LuaAPI.luaL_loadbuffer(L, code, "luatemplate") != 0)
            {
                return LuaAPI.lua_error(L);
            }
            return 1;
        }
 
        [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
        public static int Execute(RealStatePtr L)
        {
            if (!LuaAPI.lua_isfunction(L, 1))
            {
                return LuaAPI.luaL_error(L, "invalid compiled template, function needed!\r\n");
            }
            if (LuaAPI.lua_istable(L, 2))
            {
                LuaAPI.lua_setfenv(L, 1);
            }
            LuaAPI.lua_pcall(L, 0, 1, 0);
            return 1;
        }
 
        static LuaCSFunction templateCompileFunction = Compile;
        static LuaCSFunction templateExecuteFunction = Execute;
 
        public static void OpenLib(RealStatePtr L)
        {
            LuaAPI.lua_newtable(L);
            LuaAPI.xlua_pushasciistring(L, "compile");
            LuaAPI.lua_pushstdcallcfunction(L, templateCompileFunction);
            LuaAPI.lua_rawset(L, -3);
            LuaAPI.xlua_pushasciistring(L, "execute");
            LuaAPI.lua_pushstdcallcfunction(L, templateExecuteFunction);
            LuaAPI.lua_rawset(L, -3);
            if (0 != LuaAPI.xlua_setglobal(L, "template"))
            {
                throw new Exception("call xlua_setglobal fail!");
            }
        }
    }
}