/
HierarchyEmitter.n
1380 lines (1167 loc) · 45.8 KB
/
HierarchyEmitter.n
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) 2003-2008 The University of Wroclaw.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the University may not be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
* NO EVENT SHALL THE UNIVERSITY BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using Nemerle.Compiler.Typedtree;
using Nemerle.Collections;
using Nemerle.Imperative;
using Nemerle.Utility;
using System.Reflection;
using System.IO;
using System.Diagnostics.SymbolStore;
using System.Diagnostics;
using System.Security;
using NC = Nemerle.Compiler;
using SRE = System.Reflection.Emit;
using NC = Nemerle.Compiler;
namespace Nemerle.Compiler
{
/**
* This part of TypesManages is responsible for generation of System.Reflection.Emit structures
* composing program hierarchy. It executes emission of all classes and their members.
*/
[ManagerAccess]
public partial class TypesManager : System.IDisposable
{
/* -- PUBLIC CONSTRUCTORS ---------------------------------------------- */
// workaround MS.NET bugs with some specific value / generic types hierarchy
private resolve_hack (_ : object, _ : System.ResolveEventArgs) : Assembly
{
//Message.Debug ($ "resolve_hack: $(args.Name)");
_assembly_builder
}
public this (man : ManagerClass)
{
Manager = man;
_OutputFileName = Manager.Options.OutputFileName;
unless (Manager.Options.TargetIsLibrary)
{
_need_entry_point = true;
_entry_point = None ();
}
unless (Manager.IsIntelliSenseMode)
System.AppDomain.CurrentDomain.TypeResolve += resolve_hack;
}
public Dispose () : void
{
unless (Manager.IsIntelliSenseMode)
System.AppDomain.CurrentDomain.TypeResolve -= resolve_hack;
}
public CreateAssembly () : void
{
// we need to process global assembly attributes before creating assembly name
_assembly_name = CreateAssemblyName ();
_assembly_name.Name = Path.GetFileNameWithoutExtension (_OutputFileName);
def assembly_requirements =
if (Manager.Options.CompileToMemory)
Emit.AssemblyBuilderAccess.Run
else
Emit.AssemblyBuilderAccess.Save;
def dir = Path.GetDirectoryName(Path.GetFullPath (_OutputFileName));
unless (Directory.Exists (dir))
Message.FatalError ($"specified output directory `$dir' does not exist");
#pragma warning disable 618
mutable required : PermissionSet;
mutable optional : PermissionSet;
mutable refused : PermissionSet;
foreach ((action, perm_set) in Manager.AttributeCompiler.GetPermissionSets (assembly_attributes)) {
match (action) {
| Permissions.SecurityAction.RequestMinimum => required = perm_set
| Permissions.SecurityAction.RequestOptional => optional = perm_set
| Permissions.SecurityAction.RequestRefuse => refused = perm_set
| _ => Message.FatalError ($"$action is not valid here")
}
}
/* define a dynamic assembly */
this._assembly_builder =
System.AppDomain.CurrentDomain.DefineDynamicAssembly
(this._assembly_name,
assembly_requirements,
dir, required, optional, refused);
GetInformationalAssemblyAttributes().Iter(this._assembly_builder.SetCustomAttribute);
#pragma warning restore 618
when (_assembly_name.Name == "") Message.FatalError ("name of output assembly cannot be empty");
/* create a dynamic module */
this._module_builder =
if (Manager.Options.CompileToMemory)
// we cannot give output filename if we are compiling only to Run
this._assembly_builder.DefineDynamicModule (_assembly_name.Name, Manager.Options.EmitDebug);
else
this._assembly_builder.DefineDynamicModule (_assembly_name.Name,
Path.GetFileName (_OutputFileName),
Manager.Options.EmitDebug);
when (Manager.Options.EmitDebug) _debug_emit = _module_builder.GetSymWriter ();
}
public IsEmitting : bool {
get { _assembly_builder != null }
}
add_resources_to_assembly () : void
{
def escape_resource (x : string) {
def cp = x.IndexOf (',');
if (cp != -1)
(x.Substring (0, cp), x.Substring (cp + 1))
else
// change name from /bar/bar/file.png to file.png namespace
(x, Path.GetFileName (x));
}
/* we can embed resources only on mono or .NET 2.0 */
foreach (element in Manager.Options.EmbeddedResources) {
def (file, name) = escape_resource (element);
try {
if (File.Exists (file)) {
def fs = File.OpenRead (file);
def meth = _module_builder.GetType ().GetMethod ("DefineManifestResource");
if (meth == null) {
try {
def res = array (fs.Length :> int);
def loop (pos) {
if (res.Length == pos) {}
else
loop (pos + fs.Read(res, pos, res.Length - pos));
}
loop (0);
def meth = _assembly_builder.GetType ()
.GetMethod ("EmbedResource", BindingFlags.NonPublic|BindingFlags.Instance);
if (meth == null)
Message.Error ("cannot find API for saving resources");
else
_ = meth.Invoke (_assembly_builder, array [name : object, res,
ResourceAttributes.Public]);
}
finally {
fs.Dispose ();
}
}
else {
// this method does the Dispose for us
_ = meth.Invoke (_module_builder, array [name : object,
fs, ResourceAttributes.Public])
}
}
else
Message.Error ("Could not find resource " + file);
}
catch {
| e => Message.Error ("Could not embed resource: " + e.Message);
}
}
foreach (element in Manager.Options.LinkedResources) {
def (file, name) = escape_resource (element);
try {
_assembly_builder.AddResourceFile (name, file);
}
catch {
| _ is FileNotFoundException =>
Message.Error ("Could not find resource " + file);
| e is System.ArgumentException =>
Message.Error ("Could not link resource: " + e.Message);
}
}
def uresource = Manager.Options.UnmanagedResource;
if(uresource != null) {
try {
_module_builder.DefineUnmanagedResource(uresource);
}
catch {
| _ is FileNotFoundException =>
Message.Error("Could not find resource" + uresource);
| e is System.ArgumentException =>
Message.Error($"Could not embed unmanaged resource $uresource: $(e.Message)");
}
}
else
{
this._assembly_builder.DefineVersionInfoResource();
}
}
/**
*
*/
public EmitAuxDecls () : void
{
compile_all_tyinfos (true)
}
/**
*
*/
public EmitDecls () : void
{
Manager.Solver.Enqueue (fun () {
compile_all_tyinfos (false);
foreach ((attr, shouldEmit) when shouldEmit in Manager.AttributeCompiler.GetCompiledAssemblyAttributes (assembly_attributes))
_assembly_builder.SetCustomAttribute (attr);
// emit debug attributes
when (Manager.Options.EmitDebug) {
def attr = Manager.AttributeCompiler.MakeEmittedAttribute (SystemTypeCache.DebuggableAttribute, array [SystemTypeCache.DebuggableAttribute_DebuggingModes],
DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.Default);
_assembly_builder.SetCustomAttribute (attr);
}
// do not require string literals interning
def attr = Manager.AttributeCompiler.MakeEmittedAttribute (SystemTypeCache.CompilationRelaxationsAttribute, 8);
_assembly_builder.SetCustomAttribute (attr);
// wrap non exception throws
/* uncomment it after we get dependency upon mono 1.1.10, since mono 1.1.9.x do not support this attribute
def (_, attr) = AttributeCompiler.CompileAttribute (GlobalEnv.Core, null, <[ System.Runtime.CompilerServices.RuntimeCompatibilityAttribute (WrapNonExceptionThrows=true) ]>);
_assembly_builder.SetCustomAttribute (attr);
*/
})
}
/**
* Returns generated assembly for runtime instantations of its types
*/
public GeneratedAssembly : Assembly
{
get { _assembly_builder }
}
/**
* Saves the constructed assembly to a file
*/
public SaveAssembly () : void
{
add_resources_to_assembly ();
// if there are some nemerle specific metadata encoded in attributes
when (contains_nemerle_specifics) {
def attr = Manager.AttributeCompiler.MakeEmittedAttribute (SystemTypeCache.Reflection_AssemblyConfigurationAttribute, "ContainsNemerleTypes");
this._assembly_builder.SetCustomAttribute (attr);
}
// set the entry point
match ((_need_entry_point, _entry_point))
{
| (true, Some (entry_point_method_info)) =>
_assembly_builder.SetEntryPoint (entry_point_method_info,
if (Manager.Options.TargetIsWinexe)
Emit.PEFileKinds.WindowApplication
else
Emit.PEFileKinds.ConsoleApplication)
| (true, None) =>
Message.Error ("no suitable entry point (Main function) found")
| _ => ()
}
// save the assembly
try
{
def (portableExecutableKind, imageFileMachine) = make_platform_flags (Manager.Options.Platform);
_assembly_builder.Save (Path.GetFileName (_OutputFileName), portableExecutableKind, imageFileMachine);
//when (_debug_emit != null) _debug_emit.Close ();
}
catch
{
| e is System.UnauthorizedAccessException =>
Message.Error ($"could not write to output file `$(this._OutputFileName)'"
" -- `$(e.Message)'")
| e is IOException =>
Message.Error ($"could not write to output file `$(this._OutputFileName)'"
" -- `$(e.Message)'")
| e is System.Runtime.InteropServices.COMException =>
Message.Error($"Problems saving assembly: $(e.Message)");
| e is System.ApplicationException =>
Message.Error (e.Message);
}
}
/* -- PRIVATE METHODS -------------------------------------------------- */
/**
* - create S.R.E.TypeBuilders for entire hierarchy of program
* - add members to those TypeBuilders (only stubs for methods)
* - emit bodies of methods
* - finalize value types
* - finalize all types
*/
protected virtual compile_all_tyinfos (aux_phase : bool) : void
{
def allow_it(ti : TypeBuilder)
{
!ti.IsFinalized && is_aux_decl(ti) == aux_phase
}
def create_type_emit_builder(ti : TypeBuilder)
{
when (allow_it (ti))
{
//Message.Debug ("make type builder for " + ti.FullName);
ti.CreateEmitBuilder ();
when (ti.Attributes %&& NemerleModifiers.Macro)
{
def attr = Manager.AttributeCompiler.MakeEmittedAttribute (SystemTypeCache.ContainsMacroAttribute, ti.GetTypeBuilder ().FullName);
_assembly_builder.SetCustomAttribute (attr);
}
}
}
// create members' declarations in SRE.TypeBuilders
def emit_decls (ti : TypeBuilder)
{
when (allow_it(ti))
{
// Message.Debug ("generating declarations " + ti.FullName);
ti.CreateEmitDeclarations()
}
}
def emit_impl(ti : TypeBuilder)
{
when (allow_it(ti))
{
//Message.Debug ("generating code for " + ti.FullName);
Manager.MarkTypeBuilderCompiled();
ti.EmitImplementation()
}
}
when (!aux_phase)
_cgil_phase = 1;
Iter(create_type_emit_builder);
Iter(tb => when (allow_it(tb))
tb.UpdateEmittedInheritance());
when (!aux_phase)
_cgil_phase = 2;
// first emit fields of enum types as it is required to compute their sizes,
// when they are used as fields
IterConditionally(emit_decls, (x : TypeBuilder) => x.IsEnum);
IterConditionally(emit_decls, (x : TypeBuilder) => !x.IsEnum);
when (!aux_phase)
_cgil_phase = 3;
// we first finalize value types, because MS.NET runtime requires so
IterConditionally(emit_impl,
(x : TypeBuilder) => x.IsValueType && x.DeclaringType == null);
// now we can finalize everything else
Iter(emit_impl);
// MaybeBailout inteferes with the Code Completion Engine
//unless (Manager.IsIntelliSenseMode)
// Message.MaybeBailout ();
when (!aux_phase)
_cgil_phase = 4;
}
internal EnsureEmitProgress (ti : TypeBuilder) : void
{
// Message.Debug ($"ma: $ti -> $mem ");
when (_cgil_phase >= 1)
{
ti.CreateEmitBuilder ();
ti.UpdateEmittedInheritance ();
}
}
internal MaybeCompile (ti : TypeBuilder, mem : MemberBuilder) : void
{
mem.CreateEmitBuilder (ti.GetTypeBuilder ());
when (_cgil_phase >= 3)
ti.DoBeforeFinalization(() => mem.Compile())
}
/**
* Check if declaration is auxiliary, used internally etc.
*/
private static is_aux_decl (ti : TypeBuilder) : bool
{
ti.FullName.StartsWith("Nemerle.Internal.")
}
private static make_platform_flags (platform : string) : PortableExecutableKinds * ImageFileMachine
{
| "x86" =>
(PortableExecutableKinds.ILOnly | PortableExecutableKinds.Required32Bit
, ImageFileMachine.I386)
| "x64" =>
(PortableExecutableKinds.ILOnly | PortableExecutableKinds.PE32Plus
, ImageFileMachine.AMD64)
| ""
| "anycpu" =>
(PortableExecutableKinds.ILOnly
, ImageFileMachine.I386)
| "ia64" =>
(PortableExecutableKinds.ILOnly | PortableExecutableKinds.PE32Plus
, ImageFileMachine.IA64)
| _ =>
assert(false)
}
/* -- PRIVATE FIELDS --------------------------------------------------- */
private mutable _assembly_name : System.Reflection.AssemblyName;
private mutable _assembly_builder : Emit.AssemblyBuilder;
internal mutable _module_builder : Emit.ModuleBuilder;
public mutable _debug_emit : ISymbolWriter;
internal mutable contains_nemerle_specifics : bool = false;
internal _need_entry_point : bool;
/** updated when method with static Main signature is met */
internal mutable _entry_point : option[MethodInfo];
private _OutputFileName : string;
private mutable _cgil_phase : int;
}
public partial class TypeBuilder : NC.TypeInfo
{
/**
* This method makes a skeleton of a class -- the class partial type and
* partial types for the nested classes are created. The parent class and
* the interfaces being implemented are assumed to have been processed
* before constructing a dependant class. All the declarations and method
* implementations will be created successively in subsequent passes.
*/
internal CreateEmitBuilder () : void
{
when (system_type == null) {
/* create optional custom attributes for this type */
def custom_attribute =
match (tydecl)
{
| TypeDeclaration.Variant (decls) =>
make_nemerle_variant_attribute (decls)
| TypeDeclaration.VariantOption =>
def has_co_ctor = GetConstantObject () != null;
make_nemerle_variant_option_attribute (has_co_ctor)
| TypeDeclaration.Alias (t) =>
make_nemerle_type_alias_attribute (t)
| _ => null
};
/* decide the new type attributes */
def is_nested = DeclaringType != null;
def type_kind_attrs =
match (tydecl)
{
| TypeDeclaration.Variant
| TypeDeclaration.VariantOption
| TypeDeclaration.Class => TypeAttributes.Class
| TypeDeclaration.Alias // we pretend type alias is an interface
| TypeDeclaration.Interface => TypeAttributes.Interface %| TypeAttributes.Abstract
| TypeDeclaration.Enum => TypeAttributes.Sealed %| TypeAttributes.Class
};
mutable attrs = make_type_attributes (Attributes, is_nested, IsStruct) %| type_kind_attrs;
mutable typarms_len = TyparmsCount;
when (is_nested)
typarms_len -= DeclaringType.TyparmsCount;
def generic_mark_suffix =
match (typarms_len) {
| 0 => ""
| l => "`" + l.ToString ()
}
def empty_struct = IsStruct && GetFields (BindingFlags.Instance %|
BindingFlags.Public %|
BindingFlags.NonPublic).IsEmpty;
def no_static_ctor = GetConstructors (BindingFlags.Static %|
BindingFlags.Public %|
BindingFlags.NonPublic).IsEmpty;
when (no_static_ctor)
attrs = attrs %| TypeAttributes.BeforeFieldInit; /* [DF] mimick mcs behaviour */
/* create the type builder for a top-level or nested class declaration */
type_builder =
if (!is_nested)
if(empty_struct)
TyManager._module_builder.DefineType (FullName + generic_mark_suffix, attrs, null, SRE.PackingSize.Unspecified, 1)
else
TyManager._module_builder.DefineType (FullName + generic_mark_suffix, attrs)
else
{
def containing_builder = (DeclaringType :> TypeBuilder).GetTypeBuilder ();
if(empty_struct)
containing_builder.DefineNestedType (Name + generic_mark_suffix, attrs, null, 1) // cannot specify both PackingSize and type size
else
containing_builder.DefineNestedType (Name + generic_mark_suffix, attrs)
};
// creates and store generic parameters in our StaticTyVars
unless (typarms.IsEmpty) {
def names = typarms.MapToArray (fun (x) { x.Name });
def generic_parms = type_builder.DefineGenericParameters (names);
typarms.IterI (0, fun (idx, x) {
x.SetGenericBuilder (generic_parms [idx]);
});
}
when (custom_attribute != null) {
TyManager.contains_nemerle_specifics = true;
type_builder.SetCustomAttribute (custom_attribute);
}
when (extension_patterns.Count > 0)
TyManager.contains_nemerle_specifics = true;
Manager.AttributeCompiler.GetPermissionSets(GlobalEnv, modifiers.custom_attrs)
.Iter(type_builder.AddDeclarativeSecurity);
system_type = type_builder;
}
}
/**
* Builds a Nemerle variant attribute
*/
private make_nemerle_variant_attribute (decls : list [NC.TypeInfo]) : Emit.CustomAttributeBuilder
{
def names = decls.Map (fun (decl) { decl.FullName });
Manager.AttributeCompiler.MakeEmittedAttribute (SystemTypeCache.VariantAttribute, NString.Concat (",", names))
}
/**
* Builds a Nemerle type alias
*/
private make_nemerle_type_alias_attribute (t : FixedType) : Emit.CustomAttributeBuilder
{
Manager.AttributeCompiler.MakeEmittedAttribute (SystemTypeCache.TypeAliasAttribute, TyCodec.EncodeType (t))
}
/**
* Builds a Nemerle variant option attribute
*/
private make_nemerle_variant_option_attribute (is_const : bool) : Emit.CustomAttributeBuilder
{
Manager.AttributeCompiler.MakeEmittedAttribute (if (is_const)
SystemTypeCache.ConstantVariantOptionAttribute
else
SystemTypeCache.VariantOptionAttribute)
}
/**
* Converts Nemerle modifiers to the Framework type attributes.
*/
private static make_type_attributes (attrs : NemerleModifiers, is_nested : bool, is_struct : bool = false) : TypeAttributes
{
mutable result =
if (is_struct)
TypeAttributes.SequentialLayout /* [DF] default struct layout is sequential */
else
TypeAttributes.AutoLayout;
when (attrs %&& NemerleModifiers.Public)
if (is_nested) result |= TypeAttributes.NestedPublic
else result |= TypeAttributes.Public;
when (attrs %&& NemerleModifiers.Private)
if (is_nested) result |= TypeAttributes.NestedPrivate
else Message.Error ("Private is not allowed for top level types");
when (attrs %&& NemerleModifiers.Protected)
if (is_nested) result |= TypeAttributes.NestedFamily
else Message.Error ("Protected is not allowed for top level types");
when (attrs %&& NemerleModifiers.Internal && is_nested)
result |= TypeAttributes.NestedFamORAssem;
when (attrs %&& NemerleModifiers.Abstract) result |= TypeAttributes.Abstract;
when (attrs %&& NemerleModifiers.Sealed) result |= TypeAttributes.Sealed;
when (attrs %&& NemerleModifiers.SpecialName) result |= TypeAttributes.SpecialName;
when (attrs %&& NemerleModifiers.Static) result |= TypeAttributes.Abstract | TypeAttributes.Sealed;
result
}
/**
* Set up custom attributes on members of this TypeBuilder. Compile method's bodies.
*/
internal EmitImplementation() : void
{
unless (IsFinalized)
{
IsFinalized = true;
foreach (m is MemberBuilder in member_list)
m.Compile();
unless (modifiers.IsEmpty)
{
modifiers.SaveCustomAttributes(this,
fun (target, a, shouldEmit)
{
def valid = target %&& System.AttributeTargets.Class
|| type_builder.IsEnum && target %&& System.AttributeTargets.Enum
|| type_builder.IsInterface && target %&& System.AttributeTargets.Interface;
if (valid)
{
when(shouldEmit)
type_builder.SetCustomAttribute (a);
null
}
else if (a != null)
"type " + ToString()
else
null
})
}
//Message.Debug ("finalizing " + FullName);
unless (Message.SeenError)
this.FinalizeType();
//Message.Debug ("finalized " + FullName);
}
}
/**
* This methods walks the class and adds field and method declarations.
* The method implementation will be filled in a separate pass.
*/
internal CreateEmitDeclarations() : void
{
// nested types are skipped here
foreach (m is MemberBuilder in member_list)
{
// Message.Debug ($ "emit $m from $type_builder");
m.CreateEmitBuilder (type_builder);
}
}
/**
* Reads the inheritance list of a class and retrieves the base
* type and builds the array of interfaces implemented by the class.
*/
determine_inheritance() : (System.Type * array[System.Type])
{
match (tydecl)
{
| TypeDeclaration.Enum => (SystemTypeCache.Enum, array[])
| _ =>
def interfaces = InterfacesToImplement().MapToArray(i => i.GetSystemType());
if (parent_type != null)
(parent_type.GetSystemType(), interfaces)
else
(null, interfaces)
}
}
internal UpdateEmittedInheritance () : void
{
when (! reflection_inheritance_emitted) {
reflection_inheritance_emitted = true;
/* determine the inheritance relation for this type
generic builders are now properly stored */
def (extends_class, implements_interfaces) = determine_inheritance ();
// save inheritance information in our type builder
when (extends_class != null) {
if (FullName.StartsWith ("Nemerle.Builtins.Array"))
type_builder.SetParent (SystemTypeCache.Object);
else
type_builder.SetParent (extends_class);
}
foreach (inter in implements_interfaces)
type_builder.AddInterfaceImplementation (inter);
foreach (gp in typarms) gp.UpdateConstraints ();
}
}
}
public partial class MethodBuilder : MemberBuilder
{
internal override CreateEmitBuilder (tb : Emit.TypeBuilder) : void
{
when (SkipEmiting)
return;
if (MemberKind == MemberKinds.Constructor)
CreateConstructorBuilder (tb)
else
CreateMethodBuilder (tb)
}
/**
* Emits a method's body
*/
internal CompileAfterTyping () : void
{
when (SkipEmiting)
return;
def setup_method (emitter) {
// make sure type is not finalized
def type_builder = declaring_type.GetTypeBuilder ();
assert(type_builder != null);
def mb = GetMethodInfo ();
Util.cassert (mb != null, $"method builder is null for $this");
/* update the entry point settings, if necessary */
when (emitter._need_entry_point && Name == "Main"
&& (Manager.Options.MainClass == null
|| declaring_type.FullName == Manager.Options.MainClass
|| Manager.Options.IsMainClassAutogenerated))
{
def has_correct_signature ()
{
mb.IsStatic &&
(ReturnType.Equals (InternalType.Int32) ||
ReturnType.Equals (InternalType.Void)) &&
match (fun_header.Parameters)
{
// workaround bug in MS PEVerify
| [fp] =>
fp.ty.Fix ().Equals (FixedType.Array (InternalType.String, 1))
| [] => true
| _ => false
}
}
if (has_correct_signature ()) {
if (declaring_type.TyparmsCount > 0 || !Header.TypeParameters.IsEmpty)
Message.Warning (402, this.ToString () + ": an entry point cannot be generic or in a generic type");
else
match (emitter._entry_point) {
| Some (exist) =>
Message.Error ($ "more than one entry point (Main function) "
"found, e.g. types $(exist.DeclaringType) and $(mb.DeclaringType)");
Message.Hint ("you can use -main TypeName switch to disambiguate selection");
| None =>
when (DeclaringType.TyManager._debug_emit != null)
DeclaringType.TyManager._debug_emit.SetUserEntryPoint (SymbolToken (1));
emitter._entry_point = Some (mb : MethodInfo)
}
}
else
Message.Warning (28, $"$this has the wrong signature to be an entry point");
}
// update the overriding relationships
foreach ((overriddenType, overridden) in ImplementedMethods)
{
// Message.Debug("override " + method_info.Name + " " + overridden_info.Name + " in " + type_builder.FullName);
when (!mb.IsPublic || Name != overridden.Name)
{
// VladD2: Возможно вместо declaring_type.GetMemType() надо использовать
def overridden_info = ILEmitter.GetMethodInfo(overriddenType, overridden);
type_builder.DefineMethodOverride(mb, overridden_info)
}
}
}
// Message.Debug (this.ToString ());
match (fun_header.body)
{
| FunBody.ILed => {}
| _ =>
// maybe create additional method for implementing interface method
// (in case of co/contravariant methods)
CreateImplementsWrapper();
// Message.Debug (Location, $ "compile: $this");
Util.locate(Location,
{
match (fun_header.body)
{
| FunBody.ILed | FunBody.Parsed => Util.ice (fun_header.body.GetType().ToString ())
| FunBody.Typed when Message.SeenError =>
// just skip it
fun_header.body = FunBody.ILed ()
| FunBody.Typed =>
assign_parameter_indexes(GetMethodBase().IsStatic);
emit_parameter_attributes();
unless (declaring_type.IsDelegate)
{
unless (MemberKind == MemberKinds.Constructor)
setup_method(declaring_type.TyManager);
declaring_type.DoBeforeFinalization2 (
fun()
{
// Message.Debug ($"making il generator for $meth");
def gen = ILEmitter (this);
when (Manager.Options.EmitDebug)
gen.SetDocument(Location);
gen.Run ();
});
}
| FunBody.Abstract => emit_parameter_attributes();
}
});
when (Manager.Options.EarlyExit)
Message.MaybeBailout ();
}
}
static parameter_attributes (fp : TParameter) : ParameterAttributes
{
(match (fp.kind)
{
| ParmKind.Out => ParameterAttributes.Out
| ParmKind.Ref
| ParmKind.Normal => ParameterAttributes.None
}
)
|
(if (fp.default_value.IsSome)
ParameterAttributes.HasDefault | ParameterAttributes.Optional
else
ParameterAttributes.None)
}
emit_parameter_attributes() : void
{
foreach (parm in fun_header.Parameters)
{
parm.modifiers.SaveCustomAttributes (declaring_type,
fun(target, attr, shouldEmit)
{
if (target %&& System.AttributeTargets.Parameter)
{
when(shouldEmit)
parm.builder.SetCustomAttribute (attr);
null
}
else
"parameter " + parm.name
})
}
}
/**
* Assigns an ordinal index to each of a method's parameter
*/
assign_parameter_indexes (is_static : bool) : void
{
mutable index = if (is_static) 0 else 1;
foreach (parm in fun_header.Parameters)
{
parm.decl.SetParmIndex(index, is_by_ref = parm.kind != ParmKind.Normal);
index++;
}
}
/* build the parameter types array */
param_types () : array [System.Type]
{
GetParameters ().MapToArray (fun (parm) { parm.GetSystemType() });
}
/**
* Converts Nemerle modifiers to the CLI method attributes.
*/
static make_method_attributes (attrs : NemerleModifiers) : MethodAttributes
{
mutable result = MethodAttributes.HideBySig;
when (attrs %&& NemerleModifiers.Public)
result |= MethodAttributes.Public;
when (attrs %&& NemerleModifiers.Private)
result |= MethodAttributes.Private;
if (attrs %&& NemerleModifiers.Protected)
if (attrs %&& NemerleModifiers.Internal)
result |= MethodAttributes.FamORAssem;
else
result |= MethodAttributes.Family;
else when (attrs %&& NemerleModifiers.Internal)
result |= MethodAttributes.Assembly;
when (attrs %&& NemerleModifiers.Static)
result |= MethodAttributes.Static;
when (attrs %&& NemerleModifiers.Override)
result |= MethodAttributes.Virtual %| MethodAttributes.ReuseSlot;
// when method is static, then new is only for compile-time information
when (!(attrs %&& NemerleModifiers.Static) && attrs %&& NemerleModifiers.New && attrs %&& NemerleModifiers.Virtual)
result |= MethodAttributes.NewSlot | MethodAttributes.Virtual;
when (attrs %&& NemerleModifiers.Abstract)
result |= MethodAttributes.Virtual %| MethodAttributes.Abstract;
when (attrs %&& NemerleModifiers.Virtual)
result |= MethodAttributes.Virtual;
when (attrs %&& NemerleModifiers.Sealed)
result |= MethodAttributes.Final %| MethodAttributes.Virtual;
when (attrs %&& NemerleModifiers.SpecialName)
result |= MethodAttributes.SpecialName;
result
}
/**
* Adds a method builder to a type builder
*/
CreateMethodBuilder (tb : Emit.TypeBuilder) : void
{
when (SkipEmiting)
return;
// Message.Debug ($"-- AddMethodBuilder: $meth $(Attributes) ");
/* update the modifiers list */
unless (ImplementedMethods.IsEmpty)
Attributes |= NemerleModifiers.Virtual;
def attrs = make_method_attributes (Attributes);