-
Notifications
You must be signed in to change notification settings - Fork 77
Expand file tree
/
Copy pathJSMarshaller.cs
More file actions
3942 lines (3632 loc) · 166 KB
/
JSMarshaller.cs
File metadata and controls
3942 lines (3632 loc) · 166 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
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Numerics;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.JavaScript.NodeApi.Interop;
namespace Microsoft.JavaScript.NodeApi.DotNetHost;
/// <summary>
/// Generates expressions and delegates that support marshaling between .NET and JS.
/// </summary>
/// <remarks>
/// Most marshaling logic is generated in the form of lambda expressions. The expressions
/// can then be compiled into delegates at runtime, or written out as source code by a
/// compile time source-generator to support faster startup and AOT compiled binaries.
/// <para/>
/// All methods on this class are thread-safe.
/// </remarks>
public class JSMarshaller
{
/// <summary>
/// Prefix applied to the name of out parameters when building expressions. Expressions
/// do not distinguish between ref and out parameters, but the source generator needs to use
/// the correct keyword.
/// </summary>
public const string OutParameterPrefix = "__out_";
/// <summary>
/// When a method has `ref` and/or `out` parameters, the results are returned as an object
/// with properties for each of the `ref`/`out` parameters along with a `result` property
/// for the actual return value (if not void).
/// </summary>
public const string ResultPropertyName = "result";
/// <summary>
/// Keeps track of the names of all generated lambda expressions in order to automatically
/// avoid collisions, which can occur with overloaded methods.
/// </summary>
private readonly HashSet<string> _expressionNames = new();
[ThreadStatic]
private static JSMarshaller? s_current;
public static JSMarshaller Current
{
get => s_current ??
throw new InvalidOperationException("No current JSMarshaller instance.");
internal set => s_current = value;
}
public JSMarshaller()
{
_interfaceMarshaller = new(() => new JSInterfaceMarshaller(),
LazyThreadSafetyMode.ExecutionAndPublication);
_delegates = new(() => new JSMarshallerDelegates(),
LazyThreadSafetyMode.ExecutionAndPublication);
}
private readonly Lazy<JSInterfaceMarshaller> _interfaceMarshaller;
private readonly Lazy<JSMarshallerDelegates> _delegates;
private readonly ConcurrentDictionary<Type, Delegate> _fromJSDelegates = new();
private readonly ConcurrentDictionary<Type, Delegate> _toJSDelegates = new();
private readonly ConcurrentDictionary<Type, LambdaExpression> _fromJSExpressions = new();
private readonly ConcurrentDictionary<Type, LambdaExpression> _toJSExpressions = new();
private readonly ConcurrentDictionary<MethodInfo, Delegate> _jsMethodDelegates = new();
private static readonly ParameterExpression s_argsParameter =
Expression.Parameter(typeof(JSCallbackArgs), "__args");
private static readonly IEnumerable<ParameterExpression> s_argsArray =
new[] { s_argsParameter };
// Cache some reflected members that are frequently referenced in expressions.
private static readonly PropertyInfo s_context =
typeof(JSRuntimeContext).GetStaticProperty(nameof(JSRuntimeContext.Current))
?? throw new NotImplementedException("JSRuntimeContext.Current");
private static readonly PropertyInfo s_moduleContext =
typeof(JSModuleContext).GetStaticProperty(nameof(JSModuleContext.Current))
?? throw new NotImplementedException("JSModuleContext.Current");
private static readonly PropertyInfo s_valueItem =
typeof(JSValue).GetIndexer(typeof(string))
?? throw new NotImplementedException("JSValue[string]");
private static readonly MethodInfo s_isNullOrUndefined =
typeof(JSValue).GetMethod(nameof(JSValue.IsNullOrUndefined))
?? throw new NotImplementedException("JSValue.IsNullOrUndefined");
private static readonly PropertyInfo s_thisArgProperty =
typeof(JSCallbackArgs).GetProperty(nameof(JSCallbackArgs.ThisArg))
?? throw new NotImplementedException("JSCallbackArgs.ThisArg");
private static readonly PropertyInfo s_argsIndexer =
typeof(JSCallbackArgs).GetIndexer(typeof(int))
?? throw new NotImplementedException("JSCallbackArgs[int]");
private static readonly MethodInfo s_unwrap =
typeof(JSValue).GetMethod(nameof(JSValue.Unwrap))
?? throw new NotImplementedException("JSValue.Unwrap");
private static readonly MethodInfo s_tryUnwrap =
typeof(JSValue).GetMethod(nameof(JSValue.TryUnwrap))
?? throw new NotImplementedException("JSValue.TryUnwrap");
private static readonly MethodInfo s_getOrCreateObjectWrapper =
typeof(JSRuntimeContext).GetInstanceMethod(
nameof(JSRuntimeContext.GetOrCreateObjectWrapper));
private static readonly MethodInfo s_asVoidPromise =
typeof(TaskExtensions).GetStaticMethod(
nameof(TaskExtensions.AsPromise), new[] { typeof(Task) });
/// <summary>
/// Gets or sets a value indicating whether the marshaller automatically converts
/// casing between TitleCase .NET member names and camelCase JavaScript member names.
/// </summary>
public bool AutoCamelCase { get; set; }
public static string ToCamelCase(string name)
{
if (name.Length == 0)
{
return name;
}
// Skip leading underscores.
int firstLetterIndex = 0;
while (name[firstLetterIndex] == '_')
{
firstLetterIndex++;
if (firstLetterIndex == name.Length)
{
// Only underscores.
return name;
}
}
// Only convert if it looks like title-case. (Avoid converting ALLCAPS.)
if (char.IsUpper(name[firstLetterIndex]))
{
for (int i = firstLetterIndex + 1; i < name.Length; i++)
{
if (char.IsLower(name[i]))
{
// Found at least one lowercase letter. Convert to camel-case and return.
char[] chars = name.ToCharArray();
chars[firstLetterIndex] = char.ToLower(name[firstLetterIndex]);
return new string(chars);
}
}
}
return name;
}
private UnaryExpression JSMemberNameExpression(MemberInfo member)
{
string name = member.Name;
int lastDotIndex = name.LastIndexOf('.');
if (lastDotIndex > 0)
{
// For explicit interface implementations, use the simple name.
name = name.Substring(lastDotIndex + 1);
}
string jsName = AutoCamelCase ? ToCamelCase(name) : name;
return Expression.Convert(
Expression.Constant(jsName),
typeof(JSValue),
typeof(JSValue).GetImplicitConversion(typeof(string), typeof(JSValue)));
}
/// <summary>
/// Checks whether a type is converted to a JavaScript built-in type.
/// </summary>
internal static bool IsConvertedType(Type type)
{
if (type.IsPrimitive ||
type == typeof(string) ||
type == typeof(Array) ||
type == typeof(Task) ||
type == typeof(ValueTask) ||
type == typeof(CancellationToken) ||
type == typeof(DateTime) ||
type == typeof(TimeSpan) ||
type == typeof(Guid) ||
type == typeof(BigInteger))
{
return true;
}
if (type.IsGenericType)
{
type = type.GetGenericTypeDefinition();
}
if (type.IsGenericTypeDefinition &&
(type == typeof(Task<>) ||
type == typeof(ValueTask<>) ||
type == typeof(IEnumerable<>) ||
type == typeof(IAsyncEnumerable<>) ||
type == typeof(ICollection<>) ||
type == typeof(IReadOnlyCollection<>) ||
type == typeof(ISet<>) ||
#if READONLY_SET
type == typeof(IReadOnlySet<>) ||
#else
// TODO: Support IReadOnlySet on .NET Framework / .NET Standard 2.0.
#endif
type == typeof(IList<>) ||
type == typeof(IReadOnlyList<>) ||
type == typeof(IDictionary<,>) ||
type == typeof(IReadOnlyDictionary<,>) ||
type == typeof(List<>) ||
type == typeof(Stack<>) ||
type == typeof(Queue<>) ||
type == typeof(HashSet<>) ||
type == typeof(SortedSet<>) ||
type == typeof(Dictionary<,>) ||
type == typeof(SortedDictionary<,>) ||
type == typeof(Collection<>) ||
type == typeof(ReadOnlyCollection<>) ||
type == typeof(ReadOnlyDictionary<,>)))
{
return true;
}
return false;
}
/// <summary>
/// Converts from a JS value to a specified type.
/// </summary>
/// <typeparam name="T">The type the value will be converted to.</typeparam>
/// <param name="value">The JavaScript value to be converted.</param>
/// <exception cref="NotSupportedException">The type cannot be converted.</exception>
public T FromJS<T>(JSValue value) => GetFromJSValueDelegate<T>()(value);
/// <summary>
/// Converts from a JS value to a specified type.
/// </summary>
/// <param name="type">The type the value will be converted to.</param>
/// <param name="value">The JavaScript value to be converted.</param>
/// <exception cref="NotSupportedException">The type cannot be converted.</exception>
public object FromJS(Type type, JSValue value) =>
GetFromJSValueDelegate(type).DynamicInvoke(value)!;
/// <summary>
/// Converts from a specified type to a JS value.
/// </summary>
/// <typeparam name="T">The type the value will be converted from.</typeparam>
/// <exception cref="NotSupportedException">The type cannot be converted.</exception>
public JSValue ToJS<T>(T value) => GetToJSValueDelegate<T>()(value);
/// <summary>
/// Converts from a specified type to a JS value.
/// </summary>
/// <param name="type">The type the value will be converted from.</param>
/// <param name="value">The value to be converted. Must be an instance (or subtype of) the
/// <paramref name="type"/>.</param>
/// <exception cref="NotSupportedException">The type cannot be converted.</exception>
public JSValue ToJS(Type type, object value) =>
(JSValue)GetToJSValueDelegate(type).DynamicInvoke(value)!;
/// <summary>
/// Gets a delegate that converts from a JS value to a specified type.
/// </summary>
/// <typeparam name="T">The type the value will be converted to.</typeparam>
/// <exception cref="NotSupportedException">The type cannot be converted.</exception>
/// <remarks>
/// Type conversion delegates are built on created and then cached, so it is efficient
/// to call this method multiple times for the same type.
/// </remarks>
public JSValue.To<T> GetFromJSValueDelegate<T>()
{
return (JSValue.To<T>)GetFromJSValueDelegate(typeof(T));
}
/// <summary>
/// Gets a delegate that converts from a JS value to a specified type.
/// </summary>
/// <param name="type">The type the value will be converted to.</param>
/// <exception cref="NotSupportedException">The type cannot be converted.</exception>
/// <remarks>
/// Type conversion delegates are built on created and then cached, so it is efficient
/// to call this method multiple times for the same type.
/// </remarks>
public Delegate GetFromJSValueDelegate(Type type)
{
return _fromJSDelegates.GetOrAdd(type, (toType) =>
{
LambdaExpression fromJSExpression = GetFromJSValueExpression(toType);
return fromJSExpression.Compile();
});
}
/// <summary>
/// Gets a delegate that converts from a specified type to a JS value.
/// </summary>
/// <typeparam name="T">The type the value will be converted from.</typeparam>
/// <exception cref="NotSupportedException">The type cannot be converted.</exception>
/// <remarks>
/// Type conversion delegates are built on demand and then cached, so it is efficient
/// to call this method multiple times for the same type.
/// </remarks>
public JSValue.From<T> GetToJSValueDelegate<T>()
{
return (JSValue.From<T>)GetToJSValueDelegate(typeof(T));
}
/// <summary>
/// Gets a delegate that converts from a specified type to a JS value.
/// </summary>
/// <param name="type">The type the value will be converted from.</param>
/// <exception cref="NotSupportedException">The type cannot be converted.</exception>
/// <remarks>
/// Type conversion delegates are built on demand and then cached, so it is efficient
/// to call this method multiple times for the same type.
/// </remarks>
public Delegate GetToJSValueDelegate(Type type)
{
return _toJSDelegates.GetOrAdd(type, (fromType) =>
{
LambdaExpression toJSExpression = GetToJSValueExpression(fromType);
return toJSExpression.Compile();
});
}
/// <summary>
/// Gets a delegate for a .NET adapter to a JS method. When invoked, the adapter will
/// marshal the arguments to JS, invoke the JS method, then marshal the return value
/// (or exception) back to .NET.
/// </summary>
/// <remarks>
/// The delegate has an extra initial argument of type <see cref="JSValue"/> that is
/// the JS object on which the method will be invoked.
/// </remarks>
public Delegate GetToJSMethodDelegate(MethodInfo method)
{
return _jsMethodDelegates.GetOrAdd(method, (method) =>
{
LambdaExpression jsMethodExpression = BuildToJSMethodExpression(method);
return jsMethodExpression.Compile();
});
}
/// <summary>
/// Gets a delegate for a .NET adapter to a JS method, using the current thread
/// JS marshaller instance.
/// </summary>
public static Delegate StaticGetToJSMethodDelegate(MethodInfo method)
=> Current.GetToJSMethodDelegate(method);
/// <summary>
/// Gets a lambda expression that converts from a JS value to a specified type.
/// </summary>
/// <param name="toType">The type the value will be converted to.</param>
/// <exception cref="NotSupportedException">The type cannot be converted.</exception>
/// <remarks>
/// Type conversion expressions are built on demand and then cached, so it is efficient
/// to call this method multiple times for the same type.
/// </remarks>
public LambdaExpression GetFromJSValueExpression(Type toType)
{
if (toType is null) throw new ArgumentNullException(nameof(toType));
try
{
if (toType == typeof(Task) || toType == typeof(ValueTask) ||
(toType.IsGenericType && toType.GetGenericTypeDefinition() == typeof(Task<>)) ||
(toType.IsGenericType && toType.GetGenericTypeDefinition() == typeof(ValueTask<>)))
{
return _fromJSExpressions.GetOrAdd(toType, BuildConvertFromJSPromiseExpression);
}
else
{
return _fromJSExpressions.GetOrAdd(toType, BuildConvertFromJSValueExpression);
}
}
catch (Exception ex)
{
throw new JSMarshallerException(
"Failed to build expression for conversion from JS value.", toType, ex);
}
}
/// <summary>
/// Gets a lambda expression that converts from a specified type to a JS value.
/// </summary>
/// <param name="fromType">The type the value will be converted from.</param>
/// <exception cref="NotSupportedException">The type cannot be converted.</exception>
/// <remarks>
/// Type conversion expressions are built on demand and then cached, so it is efficient
/// to call this method multiple times for the same type.
/// </remarks>
public LambdaExpression GetToJSValueExpression(Type fromType)
{
if (fromType is null) throw new ArgumentNullException(nameof(fromType));
try
{
if (fromType == typeof(Task) || fromType == typeof(ValueTask) ||
(fromType.IsGenericType && fromType.GetGenericTypeDefinition() == typeof(Task<>)) ||
(fromType.IsGenericType &&
fromType.GetGenericTypeDefinition() == typeof(ValueTask<>)))
{
return _toJSExpressions.GetOrAdd(fromType, BuildConvertToJSPromiseExpression);
}
else
{
return _toJSExpressions.GetOrAdd(fromType, BuildConvertToJSValueExpression);
}
}
catch (Exception ex)
{
throw new JSMarshallerException(
"Failed to build expression for conversion to JS value.", fromType, ex);
}
}
/// <summary>
/// Builds a lambda expression for a JS callback adapter that constructs an instance of
/// a .NET class or struct. When invoked, the expression will marshal the constructor arguments
/// from JS, invoke the constructor, then return the new instance either as a wrapped
/// .NET class or a JS object marshalled from the struct.
/// </summary>
/// <remarks>
/// The returned expression takes a <see cref="JSCallbackArgs"/> parameter and returns a JS
/// value for the constructed instance. The lambda expression may be converted to a delegate
/// with <see cref="LambdaExpression.Compile()"/>, and used as the constructor callback
/// parameter for a <see cref="JSClassBuilder{T}"/>.
/// </remarks>
#pragma warning disable CA1822 // Mark members as static
public Expression<JSCallback> BuildFromJSConstructorExpression(ConstructorInfo constructor)
{
if (constructor is null) throw new ArgumentNullException(nameof(constructor));
/*
* ConstructorClass(JSCallbackArgs __args)
* {
* var param0Name = (Param0Type)__args[0];
* ...
* var __result = new ConstructorClass(param0, ...);
* return JSValue.CreateExternal(__result);
* }
*/
ParameterInfo[] parameters = constructor.GetParameters();
ParameterExpression[] argVariables = new ParameterExpression[parameters.Length];
List<ParameterExpression> variables;
List<Expression> statements = new(parameters.Length + 2);
for (int i = 0; i < parameters.Length; i++)
{
argVariables[i] = Variable(parameters[i]);
statements.Add(Expression.Assign(argVariables[i],
BuildArgumentExpression(i, parameters[i])));
}
ParameterExpression resultVariable = Expression.Variable(
constructor.DeclaringType!, "__result");
variables = [.. argVariables.Append(resultVariable)];
statements.Add(Expression.Assign(resultVariable,
Expression.New(constructor, argVariables)));
if (constructor.DeclaringType!.IsValueType)
{
// For structs, use the object from __args.ThisArg and marshal the result struct
// to a JS object (by value).
Expression thisExpression = Expression.Property(
s_argsParameter, nameof(JSCallbackArgs.ThisArg));
statements.AddRange(BuildToJSFromStructExpressions(
constructor.DeclaringType!, variables, resultVariable, thisExpression));
}
else
{
MethodInfo createExternalMethod = typeof(JSValue)
.GetStaticMethod(nameof(JSValue.CreateExternal));
statements.Add(Expression.Call(
createExternalMethod, resultVariable));
}
return Expression.Lambda<JSCallback>(
body: Expression.Block(typeof(JSValue), variables, statements),
name: "new_" + FullTypeName(constructor.DeclaringType!),
parameters: s_argsArray);
}
#pragma warning restore CA1822 // Mark members as static
/// <summary>
/// Builds a lambda expression for a JS callback adapter to a .NET method. When invoked,
/// the expression will marshal the arguments from JS, invoke the method, then marshal the
/// return value (or exception) back to JS.
/// </summary>
/// <param name="method">The reflected method info.</param>
/// <param name="asExtensionMethod">True to treat a static .NET extension method as an
/// instance method call on the target JS object.</param>
/// <remarks>
/// The returned expression takes a single <see cref="JSCallbackArgs"/> parameter and
/// returns a <see cref="JSValue"/>. For instance methods, the `this` argument for the JS
/// callback args must be a JS object that wraps a .NET object matching the method's
/// declaring type. The lambda expression may be converted to a <see cref="JSCallback"/>
/// delegate with <see cref="LambdaExpression.Compile()"/>.
/// </remarks>
public Expression<JSCallback> BuildFromJSMethodExpression(
MethodInfo method,
bool asExtensionMethod = false)
{
if (method is null) throw new ArgumentNullException(nameof(method));
else if (method.IsGenericMethodDefinition) throw new ArgumentException(
"Construct a generic method definition from the method first.", nameof(method));
try
{
return method.IsStatic && !asExtensionMethod
? BuildFromJSStaticMethodExpression(method)
: BuildFromJSInstanceMethodExpression(method);
}
catch (Exception ex)
{
throw new JSMarshallerException(
"Failed to build JS callback adapter expression for .NET method.", method, ex);
}
}
/// <summary>
/// Builds a lambda expression for a JS callback adapter to a .NET property getter. When
/// invoked, the expression will get the property value and marshal it back to JS.
/// </summary>
/// <remarks>
/// The returned expression takes a single <see cref="JSCallbackArgs"/> parameter and
/// returns a <see cref="JSValue"/>. For instance methods, the `this` argument for the JS
/// callback args must be a JS object that wraps a .NET object matching the property's
/// declaring type. The lambda expression may be converted to a <see cref="JSCallback"/>
/// delegate with <see cref="LambdaExpression.Compile()"/>.
/// </remarks>
public Expression<JSCallback> BuildFromJSPropertyGetExpression(PropertyInfo property)
{
if (property is null) throw new ArgumentNullException(nameof(property));
MethodInfo? getMethod = property.GetMethod ??
throw new ArgumentException("Property does not have a get method.");
try
{
return getMethod.IsStatic
? BuildFromJSStaticPropertyGetExpression(property)
: BuildFromJSInstancePropertyGetExpression(property);
}
catch (Exception ex)
{
throw new JSMarshallerException(
"Failed to build JS callback adapter for .NET property getter.", property, ex);
}
}
/// <summary>
/// Builds a lambda expression for a JS callback adapter to a .NET property setter. When
/// invoked, the delegate will marshal the value from JS and set the property.
/// </summary>
/// <remarks>
/// The returned expression takes a single <see cref="JSCallbackArgs"/> parameter and
/// returns a <see cref="JSValue"/>. For instance methods, the `this` argument for the JS
/// callback args must be a JS object that wraps a .NET object matching the property's
/// declaring type. The lambda expression may be converted to a <see cref="JSCallback"/>
/// delegate with <see cref="LambdaExpression.Compile()"/>.
/// </remarks>
public Expression<JSCallback> BuildFromJSPropertySetExpression(PropertyInfo property)
{
if (property is null) throw new ArgumentNullException(nameof(property));
MethodInfo? setMethod = property.SetMethod ??
throw new ArgumentException("Property does not have a set method.");
try
{
return setMethod.IsStatic
? BuildFromJSStaticPropertySetExpression(property)
: BuildFromJSInstancePropertySetExpression(property);
}
catch (Exception ex)
{
throw new JSMarshallerException(
"Failed to build JS callback adapter for .NET property setter.", property, ex);
}
}
/// <summary>
/// Builds a lambda expression for a .NET adapter to a JS method. When invoked, the
/// delegate will marshal the arguments to JS, invoke the method on the JS class or
/// instance, then marshal the return value (or exception) back to .NET.
/// </summary>
/// <remarks>
/// The expression has an extra initial argument of type <see cref="JSValue"/> that is
/// the JS object on which the method will be invoked. For static methods that is the
/// JS class object; for instance methods it is the JS instance. The lambda expression
/// may be converted to a delegate with <see cref="LambdaExpression.Compile()"/>.
/// </remarks>
public LambdaExpression BuildToJSMethodExpression(MethodInfo method)
{
if (method is null) throw new ArgumentNullException(nameof(method));
else if (method.IsGenericMethodDefinition) throw new ArgumentException(
"Construct a generic method definition from the method first.", nameof(method));
try
{
string name = method.Name;
if (method.DeclaringType!.IsInterface)
{
string nsPrefix = method.DeclaringType.Namespace != null ?
method.DeclaringType.Namespace + '.' : string.Empty;
name = nsPrefix + method.DeclaringType.Name + '.' + name;
}
ParameterInfo[] allMethodParameters = method.GetParameters();
ParameterInfo[] methodParameters = allMethodParameters
.Where((p) => !(p.IsOut && !p.IsIn)).ToArray(); // Exclude out-only parameters
ParameterExpression[] parameters =
new ParameterExpression[allMethodParameters.Length + 1];
ParameterExpression thisParameter = Expression.Parameter(typeof(JSValue), "__this");
parameters[0] = thisParameter;
for (int i = 0; i < allMethodParameters.Length; i++)
{
parameters[i + 1] = Parameter(allMethodParameters[i]);
}
/*
* ReturnType MethodName(JSValue __this, Arg0Type arg0, ...)
* {
* JSValue __result = __this.CallMethod("methodName", (JSValue)arg0, ...);
* return (ReturnType)__result;
* }
*/
Expression methodName = JSMemberNameExpression(method);
Expression ParameterToJSValue(int index) => InlineOrInvoke(
GetToJSValueExpression(methodParameters[index].ParameterType),
parameters[index + 1],
nameof(BuildToJSMethodExpression));
// Switch on parameter count to avoid allocating an array if < 4 parameters.
// (Expression trees don't support stackalloc.)
Expression callExpression;
if (methodParameters.Length == 0)
{
callExpression = Expression.Call(
thisParameter,
typeof(JSValue).GetMethod(nameof(JSValue.CallMethod),
new[] { typeof(JSValue) })
?? throw new NotImplementedException("JSValue.CallMethod(JSValue)"),
methodName);
}
else if (methodParameters.Length == 1)
{
callExpression = Expression.Call(
thisParameter,
typeof(JSValue).GetMethod(nameof(JSValue.CallMethod),
new[] { typeof(JSValue), typeof(JSValue) })
?? throw new NotImplementedException(
"JSValue.CallMethod(JSValue, JSValue)"),
methodName,
ParameterToJSValue(0));
}
else if (methodParameters.Length == 2)
{
callExpression = Expression.Call(
thisParameter,
typeof(JSValue).GetMethod(nameof(JSValue.CallMethod),
new[] { typeof(JSValue), typeof(JSValue), typeof(JSValue) })
?? throw new NotImplementedException(
"JSValue.CallMethod(JSValue, JSValue, JSValue)"),
methodName,
ParameterToJSValue(0),
ParameterToJSValue(1));
}
else if (methodParameters.Length == 3)
{
callExpression = Expression.Call(
thisParameter,
typeof(JSValue).GetMethod(nameof(JSValue.CallMethod),
new[] { typeof(JSValue), typeof(JSValue), typeof(JSValue),
typeof(JSValue) })
?? throw new NotImplementedException(
"JSValue.CallMethod(JSValue, JSValue, JSValue, JSValue)"),
methodName,
ParameterToJSValue(0),
ParameterToJSValue(1),
ParameterToJSValue(2));
}
else
{
callExpression = Expression.Call(
thisParameter,
typeof(JSValue).GetMethod(nameof(JSValue.CallMethod),
new[] { typeof(JSValue), typeof(JSValue[]) })
?? throw new NotImplementedException("JSValue.CallMethod(JSValue, JSValue[])"),
new Expression[]
{
methodName,
Expression.NewArrayInit(
typeof(JSValue),
methodParameters.Select((_, i) => ParameterToJSValue(i))),
});
}
ParameterExpression resultVariable = Expression.Parameter(typeof(JSValue), "__result");
List<Expression> statements = new();
if (allMethodParameters.Any((p) => p.IsOut))
{
statements.Add(Expression.Assign(resultVariable, callExpression));
foreach (ParameterInfo outParameter in allMethodParameters.Where((p) => p.IsOut))
{
// Convert and assign values to out parameters.
string? outParameterName = Parameter(outParameter).Name;
statements.Add(Expression.Assign(
parameters.Single((p) => p.Name == outParameterName),
InlineOrInvoke(
GetFromJSValueExpression(outParameter.ParameterType),
Expression.Property(
resultVariable,
s_valueItem,
Expression.Constant(outParameter.Name)),
nameof(BuildToJSMethodExpression))));
}
string resultName = ResultPropertyName;
if (allMethodParameters.Any(
(p) => p.Name == resultName && (p.IsOut || p.ParameterType.IsByRef)))
{
resultName = '_' + resultName;
}
if (method.ReturnType != typeof(void))
{
// Get the return value from the results object.
statements.Add(Expression.Assign(resultVariable, Expression.Property(
resultVariable, s_valueItem, Expression.Constant(resultName))));
statements.Add(InlineOrInvoke(
GetFromJSValueExpression(method.ReturnType),
resultVariable,
nameof(BuildToJSMethodExpression)));
}
}
else if (method.ReturnType == typeof(void))
{
statements.Add(callExpression);
}
else
{
statements.Add(Expression.Assign(resultVariable, callExpression));
statements.Add(InlineOrInvoke(
GetFromJSValueExpression(method.ReturnType),
resultVariable,
nameof(BuildToJSMethodExpression)));
}
return Expression.Lambda(
_delegates.Value.GetToJSDelegateType(method.ReturnType, parameters),
Expression.Block(method.ReturnType, new[] { resultVariable }, statements),
name,
parameters);
}
catch (Exception ex)
{
throw new JSMarshallerException(
"Failed to build .NET adapter for JS method.", method, ex);
}
}
/// <summary>
/// Builds a lambda expression for a .NET adapter to a JS function that is callable
/// as a .NET delegate. When invoked, the adapter will marshal the arguments to JS, invoke
/// the JS function, then marshal the return value (or exception) back to .NET.
/// </summary>
/// <remarks>
/// The expression has an extra initial argument of type <see cref="JSValue"/> that is
/// the JS function that will be invoked. The lambda expression may be converted to a
/// delegate with <see cref="LambdaExpression.Compile()"/>.
/// </remarks>
public LambdaExpression BuildToJSFunctionExpression(MethodInfo method)
{
if (method is null) throw new ArgumentNullException(nameof(method));
else if (method.IsGenericMethodDefinition) throw new ArgumentException(
"Construct a generic method definition from the method first.", nameof(method));
try
{
ParameterInfo[] methodParameters = method.GetParameters();
ParameterExpression[] parameters = new ParameterExpression[methodParameters.Length + 1];
ParameterExpression thisParameter = Expression.Parameter(typeof(JSValue), "__this");
parameters[0] = thisParameter;
for (int i = 0; i < methodParameters.Length; i++)
{
parameters[i + 1] = Parameter(methodParameters[i]);
}
ParameterExpression resultVariable = Expression.Parameter(typeof(JSValue), "__result");
/*
* ReturnType DelegateName(JSValue __this, Arg0Type arg0, ...)
* {
* JSValue __result = __this.Call(thisArg: default(JSValue), (JSValue)arg0, ...);
* return (ReturnType)__result;
* }
*/
Expression ParameterToJSValue(int index) => InlineOrInvoke(
GetToJSValueExpression(methodParameters[index].ParameterType),
parameters[index + 1],
nameof(BuildToJSMethodExpression));
// Switch on parameter count to avoid allocating an array if < 4 parameters.
// (Expression trees don't support stackalloc.)
Expression callExpression;
if (methodParameters.Length == 0)
{
callExpression = Expression.Call(
thisParameter,
typeof(JSValue).GetMethod(nameof(JSValue.Call),
new[] { typeof(JSValue) })
?? throw new NotImplementedException("JSValue.Call(JSValue)"),
Expression.Default(typeof(JSValue)));
}
else if (methodParameters.Length == 1)
{
callExpression = Expression.Call(
thisParameter,
typeof(JSValue).GetMethod(nameof(JSValue.Call),
new[] { typeof(JSValue), typeof(JSValue) })
?? throw new NotImplementedException("JSValue.Call(JSValue, JSValue)"),
Expression.Default(typeof(JSValue)),
ParameterToJSValue(0));
}
else if (methodParameters.Length == 2)
{
callExpression = Expression.Call(
thisParameter,
typeof(JSValue).GetMethod(nameof(JSValue.Call),
new[] { typeof(JSValue), typeof(JSValue), typeof(JSValue) })
?? throw new NotImplementedException(
"JSValue.Call(JSValue, JSValue, JSValue)"),
Expression.Default(typeof(JSValue)),
ParameterToJSValue(0),
ParameterToJSValue(1));
}
else if (methodParameters.Length == 3)
{
callExpression = Expression.Call(
thisParameter,
typeof(JSValue).GetMethod(nameof(JSValue.Call),
new[] { typeof(JSValue), typeof(JSValue), typeof(JSValue),
typeof(JSValue) })
?? throw new NotImplementedException(
"JSValue.Call(JSValue, JSValue, JSValue, JSValue)"),
Expression.Default(typeof(JSValue)),
ParameterToJSValue(0),
ParameterToJSValue(1),
ParameterToJSValue(2));
}
else
{
callExpression = Expression.Call(
thisParameter,
typeof(JSValue).GetMethod(nameof(JSValue.Call),
new[] { typeof(JSValue), typeof(JSValue[]) })
?? throw new NotImplementedException(
"JSValue.Call(JSValue, JSValue[])"),
new Expression[]
{
Expression.Default(typeof(JSValue)),
Expression.NewArrayInit(
typeof(JSValue),
methodParameters.Select((_, i) => ParameterToJSValue(i))),
});
}
Expression[] statements;
if (method.ReturnType == typeof(void))
{
statements = new[] { callExpression };
}
else
{
statements = new[]
{
Expression.Assign(resultVariable, callExpression),
InlineOrInvoke(
GetFromJSValueExpression(method.ReturnType),
resultVariable,
nameof(BuildToJSMethodExpression)),
};
}
return Expression.Lambda(
_delegates.Value.GetToJSDelegateType(method.ReturnType, parameters),
Expression.Block(method.ReturnType, new[] { resultVariable }, statements),
FullMethodName(method, "to_"),
parameters);
}
catch (Exception ex)
{
throw new JSMarshallerException(
"Failed to build .NET adapter to JS delegate.", method.DeclaringType!, ex);
}
}
/// <summary>
/// Builds a lambda expression for a .NET adapter from a JS function that calls a
/// .NET delegate. When invoked, the adapter will marshal the arguments from JS, invoke
/// the .NET delegate, then marshal the return value (or exception) back to JS.
/// </summary>
/// <remarks>
/// The expression has an extra initial argument of the .NET delegate type that is
/// the delegate that will be invoked. The lambda expression may be converted to a
/// delegate with <see cref="LambdaExpression.Compile()"/>.
/// </remarks>
public LambdaExpression BuildFromJSFunctionExpression(MethodInfo method)
{
try
{
ParameterExpression thisParameter = Expression.Parameter(
method.DeclaringType!, "__this");
List<ParameterExpression> argVariables = new();
IEnumerable<ParameterExpression> variables;
ParameterInfo[] parameters = method.GetParameters();
List<Expression> statements = new(parameters.Length + 2);
/*
* JSValue DelegateName(DelegateType __this, JSCallbackArgs __args)
* {
* var param0Name = (Param0Type)__args[0];
* ...
* var __result = __this.Invoke(param0, ...);
* return (JSValue)__result;
* }
*/
for (int i = 0; i < parameters.Length; i++)
{
argVariables.Add(Expression.Variable(
parameters[i].ParameterType, parameters[i].Name));
statements.Add(Expression.Assign(argVariables[i],
BuildArgumentExpression(i, parameters[i])));
}
if (method.ReturnType == typeof(void))
{
variables = argVariables;
statements.Add(Expression.Call(thisParameter, method, argVariables));
statements.Add(Expression.Default(typeof(JSValue)));
}
else
{
ParameterExpression resultVariable = Expression.Variable(
method.ReturnType, "__result");
variables = argVariables.Append(resultVariable);
statements.Add(Expression.Assign(resultVariable,
Expression.Call(thisParameter, method, argVariables)));
statements.Add(BuildResultExpression(resultVariable, method.ReturnType));
}
return Expression.Lambda(
JSMarshallerDelegates.GetFromJSDelegateType(method.DeclaringType!),
body: Expression.Block(typeof(JSValue), variables, statements),
FullMethodName(method, "from_"),
parameters: new[] { thisParameter, s_argsParameter });
}
catch (Exception ex)
{
throw new JSMarshallerException(
"Failed to build .NET adapter from JS delegate.", method.DeclaringType!, ex);
}
}
private LambdaExpression BuildToJSFunctionExpression(Type delegateType)
{
MethodInfo invokeMethod = delegateType.GetMethod(nameof(Action.Invoke))!;
LambdaExpression methodExpression = BuildToJSFunctionExpression(invokeMethod);