-
Notifications
You must be signed in to change notification settings - Fork 117
Expand file tree
/
Copy pathContextMethodMapper.cs
More file actions
297 lines (243 loc) · 11.5 KB
/
ContextMethodMapper.cs
File metadata and controls
297 lines (243 loc) · 11.5 KB
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
/*----------------------------------------------------------
This Source Code Form is subject to the terms of the
Mozilla Public License, v.2.0. If a copy of the MPL
was not distributed with this file, You can obtain one
at http://mozilla.org/MPL/2.0/.
----------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using OneScript.Contexts;
using OneScript.Exceptions;
using OneScript.Execution;
using OneScript.Language;
namespace ScriptEngine.Machine.Contexts
{
public delegate IValue ContextCallableDelegate<TInstance>(TInstance instance, IValue[] args, IBslProcess process);
public class ContextMethodsMapper<TInstance>
{
private List<InternalMethInfo> _methodPtrs;
private IdentifiersTrie<int> _methodNumbers;
private readonly object _locker = new object();
private void Init()
{
if (_methodPtrs == null)
{
lock (_locker)
{
if (_methodPtrs == null)
{
var localPtrs = MapType(typeof(TInstance));
_methodNumbers = new IdentifiersTrie<int>();
for (int idx = 0; idx < localPtrs.Count; ++idx)
{
var methinfo = localPtrs[idx].MethodSignature;
_methodNumbers.Add(methinfo.Name, idx);
if (methinfo.Alias != null)
_methodNumbers.Add(methinfo.Alias, idx);
}
_methodPtrs = localPtrs;
}
}
}
}
public ContextCallableDelegate<TInstance> GetCallableDelegate(int number)
{
Init();
return _methodPtrs[number].Method;
}
public BslMethodInfo GetRuntimeMethod(int number)
{
Init();
return _methodPtrs[number].ClrMethod;
}
public IEnumerable<BslMethodInfo> GetMethods()
{
Init();
return _methodPtrs.Select(x => x.ClrMethod);
}
public int FindMethod(string name)
{
Init();
if (!_methodNumbers.TryGetValue(name, out var idx))
throw RuntimeException.MethodNotFoundException(name);
return idx;
}
public int Count
{
get
{
Init();
return _methodPtrs.Count;
}
}
private List<InternalMethInfo> MapType(Type type)
{
return type.GetMethods()
.SelectMany(method => method.GetCustomAttributes(typeof(ContextMethodAttribute), false)
.Select(attr => new InternalMethInfo(method, (ContextMethodAttribute)attr)) )
.ToList();
}
private class InternalMethInfo
{
private readonly Lazy<ContextCallableDelegate<TInstance>> _method;
private readonly ContextMethodInfo _clrMethod;
public MethodSignature MethodSignature { get; }
public BslMethodInfo ClrMethod => _clrMethod;
public InternalMethInfo(MethodInfo target, ContextMethodAttribute binding)
{
_clrMethod = new ContextMethodInfo(target, binding);
MethodSignature = CreateMetadata(target, binding, _clrMethod.InjectsProcess);
_method = new Lazy<ContextCallableDelegate<TInstance>>(() =>
{
var isFunc = target.ReturnType != typeof(void);
return isFunc ? CreateFunction(_clrMethod) : CreateProcedure(_clrMethod);
});
}
public ContextCallableDelegate<TInstance> Method => _method.Value;
private static MethodSignature CreateMetadata(MethodInfo target, ContextMethodAttribute binding, bool hasProcessParam)
{
var parameters = target.GetParameters();
var isFunc = target.ReturnType != typeof(void);
var (startIndex, argNum) = hasProcessParam ? (1, parameters.Length - 1) : (0, parameters.Length);
var paramDefs = new ParameterDefinition[argNum];
for (int i = 0, j = startIndex; i < argNum; i++, j++)
{
var pd = new ParameterDefinition();
if (parameters[j].GetCustomAttributes(typeof(ByRefAttribute), false).Length != 0)
{
if (parameters[j].ParameterType != typeof(IVariable))
{
throw new InvalidOperationException("Attribute ByRef can be applied only on IVariable parameters");
}
pd.IsByValue = false;
}
else
{
pd.IsByValue = true;
}
if (parameters[j].IsOptional)
{
pd.HasDefaultValue = true;
pd.DefaultValueIndex = ParameterDefinition.UNDEFINED_VALUE_INDEX;
}
paramDefs[i] = pd;
}
var scriptMethInfo = new MethodSignature
{
IsFunction = isFunc,
IsExport = true,
IsDeprecated = binding.IsDeprecated,
ThrowOnUseDeprecated = binding.ThrowOnUse,
Name = binding.Name,
Alias = binding.Alias,
Params = paramDefs
};
return scriptMethInfo;
}
private static ContextCallableDelegate<TInstance> CreateFunction(ContextMethodInfo target)
{
var methodCall = MethodCallExpression(target, out var instParam, out var argsParam, out var processParam);
var convertReturnCall = target.ConverterType switch
{
null => Expression.Call(
ContextValuesMarshaller.BslReturnValueGenericConverter.MakeGenericMethod(target.ReturnType),
methodCall),
_ => Expression.Call(
Expression.New(target.ConverterType),
target.ConverterType.GetMethod("ToIValue")!,
methodCall)
};
var body = convertReturnCall;
var l = Expression.Lambda<ContextCallableDelegate<TInstance>>(body, instParam, argsParam, processParam);
return l.Compile();
}
private static ContextCallableDelegate<TInstance> CreateProcedure(ContextMethodInfo target)
{
var methodCall = MethodCallExpression(target, out var instParam, out var argsParam, out var processParam);
var returnLabel = Expression.Label(typeof(IValue));
var defaultValue = Expression.Constant(null, typeof(IValue));
var returnExpr = Expression.Return(
returnLabel,
defaultValue,
typeof(IValue)
);
var body = Expression.Block(
methodCall,
returnExpr,
Expression.Label(returnLabel, defaultValue)
);
var l = Expression.Lambda<ContextCallableDelegate<TInstance>>(body, instParam, argsParam, processParam);
return l.Compile();
}
private static InvocationExpression MethodCallExpression(
ContextMethodInfo contextMethod,
out ParameterExpression instParam,
out ParameterExpression argsParam,
out ParameterExpression processParam)
{
// For those who dare:
// Код ниже формирует следующую лямбду с 2-мя замыканиями realMethodDelegate и defaults:
// (inst, args) =>
// {
// realMethodDelegate(inst,
// ConvertParam<TypeOfArg1>(args[i], defaults[i]),
// ...
// ConvertParam<TypeOfArgN>(args[i], defaults[i]));
// }
var target = contextMethod.GetWrappedMethod();
var methodClojure = CreateDelegateExpr(target);
instParam = Expression.Parameter(typeof(TInstance), "inst");
argsParam = Expression.Parameter(typeof(IValue[]), "args");
processParam = Expression.Parameter(typeof(IBslProcess), "process");
var parameters = target.GetParameters();
var (clrIndexStart, argsLen) = contextMethod.InjectsProcess ? (1, parameters.Length - 1) : (0, parameters.Length);
var argsPass = new List<Expression> { instParam };
if (contextMethod.InjectsProcess)
argsPass.Add(processParam);
for (int bslIndex = 0,clrIndex = clrIndexStart; bslIndex < argsLen; bslIndex++, clrIndex++)
{
var targetType = parameters[clrIndex].ParameterType;
Expression defaultArg;
if (parameters[clrIndex].HasDefaultValue)
defaultArg = Expression.Constant(parameters[clrIndex].DefaultValue, targetType);
else
defaultArg = ContextValuesMarshaller.GetDefaultBslValueConstant(targetType);
var indexedArg = Expression.ArrayIndex(argsParam, Expression.Constant(bslIndex));
var convertMethod = ContextValuesMarshaller.BslGenericParameterConverter.MakeGenericMethod(targetType);
var conversionCall = Expression.Call(convertMethod,
indexedArg,
defaultArg,
processParam);
argsPass.Add(Expression.Convert(conversionCall, targetType));
}
var methodCall = Expression.Invoke(methodClojure, argsPass);
return methodCall;
}
private static Expression CreateDelegateExpr(MethodInfo target)
{
var types = new List<Type>();
types.Add(target.DeclaringType);
types.AddRange(target.GetParameters().Select(x => x.ParameterType));
Type delegateType;
if (target.ReturnType == typeof(void))
{
delegateType = Expression.GetActionType(types.ToArray());
}
else
{
types.Add(target.ReturnType);
delegateType = Expression.GetFuncType(types.ToArray());
}
var deleg = target.CreateDelegate(delegateType);
var delegateExpr = Expression.Constant(deleg);
var conversion = Expression.Convert(delegateExpr, delegateType);
var delegateCreator = Expression.Lambda(conversion).Compile();
var methodClojure = Expression.Constant(delegateCreator.DynamicInvoke());
return methodClojure;
}
}
}
}