2 // codegen.cs: The code generator
5 // Miguel de Icaza (miguel@ximian.com)
7 // Copyright 2001, 2002, 2003 Ximian, Inc.
8 // Copyright 2004 Novell, Inc.
12 // Please leave this defined on SVN: The idea is that when we ship the
13 // compiler to end users, if the compiler crashes, they have a chance
14 // to narrow down the problem.
16 // Only remove it if you need to debug locally on your tree.
22 using System
.Collections
;
23 using System
.Collections
.Specialized
;
24 using System
.Globalization
;
25 using System
.Reflection
;
26 using System
.Reflection
.Emit
;
27 using System
.Runtime
.InteropServices
;
28 using System
.Security
;
29 using System
.Security
.Cryptography
;
30 using System
.Security
.Permissions
;
32 using Mono
.Security
.Cryptography
;
34 namespace Mono
.CSharp
{
37 /// Code generator class.
39 public class CodeGen
{
40 static AppDomain current_domain
;
42 public static AssemblyClass Assembly
;
43 public static ModuleClass Module
;
50 public static void Reset ()
52 Assembly
= new AssemblyClass ();
53 Module
= new ModuleClass (RootContext
.Unsafe
);
56 public static string Basename (string name
)
58 int pos
= name
.LastIndexOf ('/');
61 return name
.Substring (pos
+ 1);
63 pos
= name
.LastIndexOf ('\\');
65 return name
.Substring (pos
+ 1);
70 public static string Dirname (string name
)
72 int pos
= name
.LastIndexOf ('/');
75 return name
.Substring (0, pos
);
77 pos
= name
.LastIndexOf ('\\');
79 return name
.Substring (0, pos
);
84 static public string FileName
;
87 const AssemblyBuilderAccess COMPILER_ACCESS
= 0;
89 /* Keep this in sync with System.Reflection.Emit.AssemblyBuilder */
90 const AssemblyBuilderAccess COMPILER_ACCESS
= (AssemblyBuilderAccess
) 0x800;
94 // Initializes the code generator variables for interactive use (repl)
96 static public void InitDynamic (string name
)
98 current_domain
= AppDomain
.CurrentDomain
;
99 AssemblyName an
= Assembly
.GetAssemblyName (name
, name
);
101 Assembly
.Builder
= current_domain
.DefineDynamicAssembly (an
, AssemblyBuilderAccess
.Run
| COMPILER_ACCESS
);
102 Module
.Builder
= Assembly
.Builder
.DefineDynamicModule (Basename (name
), false);
104 Assembly
.Name
= Assembly
.Builder
.GetName ();
109 // Initializes the code generator variables
111 static public bool Init (string name
, string output
, bool want_debugging_support
)
114 AssemblyName an
= Assembly
.GetAssemblyName (name
, output
);
118 if (an
.KeyPair
!= null) {
119 // If we are going to strong name our assembly make
120 // sure all its refs are strong named
121 foreach (Assembly a
in RootNamespace
.Global
.Assemblies
) {
122 AssemblyName ref_name
= a
.GetName ();
123 byte [] b
= ref_name
.GetPublicKeyToken ();
124 if (b
== null || b
.Length
== 0) {
125 Report
.Error (1577, "Assembly generation failed " +
126 "-- Referenced assembly '" +
128 "' does not have a strong name.");
129 //Environment.Exit (1);
134 current_domain
= AppDomain
.CurrentDomain
;
137 Assembly
.Builder
= current_domain
.DefineDynamicAssembly (an
,
138 AssemblyBuilderAccess
.RunAndSave
| COMPILER_ACCESS
, Dirname (name
));
140 catch (ArgumentException
) {
141 // specified key may not be exportable outside it's container
142 if (RootContext
.StrongNameKeyContainer
!= null) {
143 Report
.Error (1548, "Could not access the key inside the container `" +
144 RootContext
.StrongNameKeyContainer
+ "'.");
145 Environment
.Exit (1);
149 catch (CryptographicException
) {
150 if ((RootContext
.StrongNameKeyContainer
!= null) || (RootContext
.StrongNameKeyFile
!= null)) {
151 Report
.Error (1548, "Could not use the specified key to strongname the assembly.");
152 Environment
.Exit (1);
158 // Get the complete AssemblyName from the builder
159 // (We need to get the public key and token)
160 Assembly
.Name
= Assembly
.Builder
.GetName ();
164 // Pass a path-less name to DefineDynamicModule. Wonder how
165 // this copes with output in different directories then.
166 // FIXME: figure out how this copes with --output /tmp/blah
168 // If the third argument is true, the ModuleBuilder will dynamically
169 // load the default symbol writer.
172 Module
.Builder
= Assembly
.Builder
.DefineDynamicModule (
173 Basename (name
), Basename (output
), want_debugging_support
);
176 // TODO: We should use SymbolWriter from DefineDynamicModule
177 if (want_debugging_support
&& !SymbolWriter
.Initialize (Module
.Builder
, output
)) {
178 Report
.Error (40, "Unexpected debug information initialization error `{0}'",
179 "Could not find the symbol writer assembly (Mono.CompilerServices.SymbolWriter.dll)");
183 } catch (ExecutionEngineException e
) {
184 Report
.Error (40, "Unexpected debug information initialization error `{0}'",
192 static public void Save (string name
, bool saveDebugInfo
)
195 Assembly
.Builder
.Save (Basename (name
));
197 catch (COMException
) {
198 if ((RootContext
.StrongNameKeyFile
== null) || (!RootContext
.StrongNameDelaySign
))
201 // FIXME: it seems Microsoft AssemblyBuilder doesn't like to delay sign assemblies
202 Report
.Error (1548, "Couldn't delay-sign the assembly with the '" +
203 RootContext
.StrongNameKeyFile
+
204 "', Use MCS with the Mono runtime or CSC to compile this assembly.");
206 catch (System
.IO
.IOException io
) {
207 Report
.Error (16, "Could not write to file `"+name
+"', cause: " + io
.Message
);
210 catch (System
.UnauthorizedAccessException ua
) {
211 Report
.Error (16, "Could not write to file `"+name
+"', cause: " + ua
.Message
);
216 // Write debuger symbol file
219 SymbolWriter
.WriteSymbolFile ();
225 /// An interface to hold all the information needed in the resolving phase.
227 public interface IResolveContext
229 DeclSpace DeclContainer { get; }
230 bool IsInObsoleteScope { get; }
231 bool IsInUnsafeScope { get; }
233 // the declcontainer to lookup for type-parameters. Should only use LookupGeneric on it.
235 // FIXME: This is somewhat of a hack. We don't need a full DeclSpace for this. We just need the
236 // current type parameters in scope. IUIC, that will require us to rewrite GenericMethod.
237 // Maybe we can replace this with a 'LookupGeneric (string)' instead, but we'll have to
238 // handle generic method overrides differently
239 DeclSpace GenericDeclContainer { get; }
243 /// An Emit Context is created for each body of code (from methods,
244 /// properties bodies, indexer bodies or constructor bodies)
246 public class EmitContext
: IResolveContext
{
249 // Holds a varible used during collection or object initialization.
251 public Expression CurrentInitializerVariable
;
253 DeclSpace decl_space
;
255 public DeclSpace TypeContainer
;
256 public ILGenerator ig
;
259 public enum Flags
: int {
261 /// This flag tracks the `checked' state of the compilation,
262 /// it controls whether we should generate code that does overflow
263 /// checking, or if we generate code that ignores overflows.
265 /// The default setting comes from the command line option to generate
266 /// checked or unchecked code plus any source code changes using the
267 /// checked/unchecked statements or expressions. Contrast this with
268 /// the ConstantCheckState flag.
273 /// The constant check state is always set to `true' and cant be changed
274 /// from the command line. The source code can change this setting with
275 /// the `checked' and `unchecked' statements and expressions.
277 ConstantCheckState
= 1 << 1,
279 AllCheckStateFlags
= CheckState
| ConstantCheckState
,
282 /// Whether we are inside an unsafe block
290 /// Whether control flow analysis is enabled
292 DoFlowAnalysis
= 1 << 5,
295 /// Whether control flow analysis is disabled on structs
296 /// (only meaningful when DoFlowAnalysis is set)
298 OmitStructFlowAnalysis
= 1 << 6,
301 /// Indicates the current context is in probing mode, no errors are reported.
303 ProbingMode
= 1 << 7,
306 // Inside field intializer expression
308 InFieldInitializer
= 1 << 8,
310 InferReturnType
= 1 << 9,
312 InCompoundAssignment
= 1 << 10,
314 OmitDebuggingInfo
= 1 << 11
320 /// Whether we are emitting code inside a static or instance method
322 public bool IsStatic
;
325 /// Whether the actual created method is static or instance method.
326 /// Althoug the method might be declared as `static', if an anonymous
327 /// method is involved, we might turn this into an instance method.
329 /// So this reflects the low-level staticness of the method, while
330 /// IsStatic represents the semantic, high-level staticness.
332 //public bool MethodIsStatic;
335 /// The value that is allowed to be returned or NULL if there is no
341 /// Points to the Type (extracted from the TypeContainer) that
342 /// declares this body of code
344 public readonly Type ContainerType
;
347 /// Whether this is generating code for a constructor
349 public bool IsConstructor
;
352 /// Keeps track of the Type to LocalBuilder temporary storage created
353 /// to store structures (used to compute the address of the structure
354 /// value on structure method invocations)
356 public Hashtable temporary_storage
;
358 public Block CurrentBlock
;
360 public int CurrentFile
;
363 /// The location where we store the return value.
365 LocalBuilder return_value
;
368 /// The location where return has to jump to return the
371 public Label ReturnLabel
;
374 /// If we already defined the ReturnLabel
376 public bool HasReturnLabel
;
379 /// Whether we are in a `fixed' initialization
381 public bool InFixedInitializer
;
384 /// Whether we are inside an anonymous method.
386 public AnonymousExpression CurrentAnonymousMethod
;
389 /// Location for this EmitContext
394 /// Inside an enum definition, we do not resolve enumeration values
395 /// to their enumerations, but rather to the underlying type/value
396 /// This is so EnumVal + EnumValB can be evaluated.
398 /// There is no "E operator + (E x, E y)", so during an enum evaluation
399 /// we relax the rules
401 public bool InEnumContext
;
403 public readonly IResolveContext ResolveContext
;
406 /// The current iterator
408 public Iterator CurrentIterator
{
409 get { return CurrentAnonymousMethod as Iterator; }
413 /// Whether we are in the resolving stage or not
421 bool isAnonymousMethodAllowed
= true;
424 FlowBranching current_flow_branching
;
426 static int next_id
= 0;
429 public override string ToString ()
431 return String
.Format ("EmitContext ({0}:{1})", id
,
432 CurrentAnonymousMethod
, loc
);
435 public EmitContext (IResolveContext rc
, DeclSpace parent
, DeclSpace ds
, Location l
, ILGenerator ig
,
436 Type return_type
, int code_flags
, bool is_constructor
)
438 this.ResolveContext
= rc
;
441 TypeContainer
= parent
;
442 this.decl_space
= ds
;
443 if (RootContext
.Checked
)
444 flags
|= Flags
.CheckState
;
445 flags
|= Flags
.ConstantCheckState
;
447 if (return_type
== null)
448 throw new ArgumentNullException ("return_type");
450 if ((return_type
is TypeBuilder
) && return_type
.IsGenericTypeDefinition
)
451 throw new InternalErrorException ();
454 IsStatic
= (code_flags
& Modifiers
.STATIC
) != 0;
455 ReturnType
= return_type
;
456 IsConstructor
= is_constructor
;
459 current_phase
= Phase
.Created
;
462 // Can only be null for the ResolveType contexts.
463 ContainerType
= parent
.TypeBuilder
;
464 if (rc
.IsInUnsafeScope
)
465 flags
|= Flags
.InUnsafe
;
470 public EmitContext (IResolveContext rc
, DeclSpace ds
, Location l
, ILGenerator ig
,
471 Type return_type
, int code_flags
, bool is_constructor
)
472 : this (rc
, ds
, ds
, l
, ig
, return_type
, code_flags
, is_constructor
)
476 public EmitContext (IResolveContext rc
, DeclSpace ds
, Location l
, ILGenerator ig
,
477 Type return_type
, int code_flags
)
478 : this (rc
, ds
, ds
, l
, ig
, return_type
, code_flags
, false)
482 // IResolveContext.DeclContainer
483 public DeclSpace DeclContainer
{
484 get { return decl_space; }
485 set { decl_space = value; }
488 // IResolveContext.GenericDeclContainer
489 public DeclSpace GenericDeclContainer
{
490 get { return DeclContainer; }
493 public bool CheckState
{
494 get { return (flags & Flags.CheckState) != 0; }
497 public bool ConstantCheckState
{
498 get { return (flags & Flags.ConstantCheckState) != 0; }
501 public bool InUnsafe
{
502 get { return (flags & Flags.InUnsafe) != 0; }
505 public bool InCatch
{
506 get { return (flags & Flags.InCatch) != 0; }
509 public bool InFinally
{
510 get { return (flags & Flags.InFinally) != 0; }
513 public bool DoFlowAnalysis
{
514 get { return (flags & Flags.DoFlowAnalysis) != 0; }
517 public bool OmitStructFlowAnalysis
{
518 get { return (flags & Flags.OmitStructFlowAnalysis) != 0; }
521 // utility helper for CheckExpr, UnCheckExpr, Checked and Unchecked statements
522 // it's public so that we can use a struct at the callsite
523 public struct FlagsHandle
: IDisposable
526 readonly Flags invmask
, oldval
;
528 public FlagsHandle (EmitContext ec
, Flags flagsToSet
)
529 : this (ec
, flagsToSet
, flagsToSet
)
533 internal FlagsHandle (EmitContext ec
, Flags mask
, Flags val
)
537 oldval
= ec
.flags
& mask
;
538 ec
.flags
= (ec
.flags
& invmask
) | (val
& mask
);
540 if ((mask
& Flags
.ProbingMode
) != 0)
541 Report
.DisableReporting ();
544 public void Dispose ()
546 if ((invmask
& Flags
.ProbingMode
) == 0)
547 Report
.EnableReporting ();
549 ec
.flags
= (ec
.flags
& invmask
) | oldval
;
553 // Temporarily set all the given flags to the given value. Should be used in an 'using' statement
554 public FlagsHandle
Set (Flags flagsToSet
)
556 return new FlagsHandle (this, flagsToSet
);
559 public FlagsHandle
With (Flags bits
, bool enable
)
561 return new FlagsHandle (this, bits
, enable
? bits
: 0);
564 public FlagsHandle
WithFlowAnalysis (bool do_flow_analysis
, bool omit_struct_analysis
)
567 (do_flow_analysis
? Flags
.DoFlowAnalysis
: 0) |
568 (omit_struct_analysis
? Flags
.OmitStructFlowAnalysis
: 0);
569 return new FlagsHandle (this, Flags
.DoFlowAnalysis
| Flags
.OmitStructFlowAnalysis
, newflags
);
573 /// If this is true, then Return and ContextualReturn statements
574 /// will set the ReturnType value based on the expression types
575 /// of each return statement instead of the method return type
576 /// (which is initially null).
578 public bool InferReturnType
{
579 get { return (flags & Flags.InferReturnType) != 0; }
582 // IResolveContext.IsInObsoleteScope
583 public bool IsInObsoleteScope
{
585 // Disables obsolete checks when probing is on
586 return IsInProbingMode
|| ResolveContext
.IsInObsoleteScope
;
590 public bool IsInProbingMode
{
591 get { return (flags & Flags.ProbingMode) != 0; }
594 // IResolveContext.IsInUnsafeScope
595 public bool IsInUnsafeScope
{
596 get { return InUnsafe || ResolveContext.IsInUnsafeScope; }
599 public bool IsAnonymousMethodAllowed
{
600 get { return isAnonymousMethodAllowed; }
601 set { isAnonymousMethodAllowed = value; }
604 public bool IsInFieldInitializer
{
605 get { return (flags & Flags.InFieldInitializer) != 0; }
608 public bool IsInCompoundAssignment
{
609 get { return (flags & Flags.InCompoundAssignment) != 0; }
612 public bool IsVariableCapturingRequired
{
614 return !IsInProbingMode
&& (CurrentBranching
== null || !CurrentBranching
.CurrentUsageVector
.IsUnreachable
);
618 public FlowBranching CurrentBranching
{
619 get { return current_flow_branching; }
622 public bool OmitDebuggingInfo
{
623 get { return (flags & Flags.OmitDebuggingInfo) != 0; }
626 flags
|= Flags
.OmitDebuggingInfo
;
628 flags
&= ~Flags
.OmitDebuggingInfo
;
633 // Starts a new code branching. This inherits the state of all local
634 // variables and parameters from the current branching.
636 public FlowBranching
StartFlowBranching (FlowBranching
.BranchingType type
, Location loc
)
638 current_flow_branching
= FlowBranching
.CreateBranching (CurrentBranching
, type
, null, loc
);
639 return current_flow_branching
;
643 // Starts a new code branching for block `block'.
645 public FlowBranching
StartFlowBranching (Block block
)
647 flags
|= Flags
.DoFlowAnalysis
;
649 current_flow_branching
= FlowBranching
.CreateBranching (
650 CurrentBranching
, FlowBranching
.BranchingType
.Block
, block
, block
.StartLocation
);
651 return current_flow_branching
;
654 public FlowBranchingTryCatch
StartFlowBranching (TryCatch stmt
)
656 FlowBranchingTryCatch branching
= new FlowBranchingTryCatch (CurrentBranching
, stmt
);
657 current_flow_branching
= branching
;
661 public FlowBranchingException
StartFlowBranching (ExceptionStatement stmt
)
663 FlowBranchingException branching
= new FlowBranchingException (CurrentBranching
, stmt
);
664 current_flow_branching
= branching
;
668 public FlowBranchingLabeled
StartFlowBranching (LabeledStatement stmt
)
670 FlowBranchingLabeled branching
= new FlowBranchingLabeled (CurrentBranching
, stmt
);
671 current_flow_branching
= branching
;
675 public FlowBranchingIterator
StartFlowBranching (Iterator iterator
)
677 FlowBranchingIterator branching
= new FlowBranchingIterator (CurrentBranching
, iterator
);
678 current_flow_branching
= branching
;
682 public FlowBranchingToplevel
StartFlowBranching (ToplevelBlock stmt
)
684 FlowBranchingToplevel branching
= new FlowBranchingToplevel (CurrentBranching
, stmt
);
685 current_flow_branching
= branching
;
690 // Ends a code branching. Merges the state of locals and parameters
691 // from all the children of the ending branching.
693 public bool EndFlowBranching ()
695 FlowBranching old
= current_flow_branching
;
696 current_flow_branching
= current_flow_branching
.Parent
;
698 FlowBranching
.UsageVector vector
= current_flow_branching
.MergeChild (old
);
699 return vector
.IsUnreachable
;
703 // Kills the current code branching. This throws away any changed state
704 // information and should only be used in case of an error.
706 // FIXME: this is evil
707 public void KillFlowBranching ()
709 current_flow_branching
= current_flow_branching
.Parent
;
712 public bool MustCaptureVariable (LocalInfo local
)
714 if (CurrentAnonymousMethod
== null)
717 // FIXME: IsIterator is too aggressive, we should capture only if child
718 // block contains yield
719 if (CurrentAnonymousMethod
.IsIterator
)
722 return local
.Block
.Toplevel
!= CurrentBlock
.Toplevel
;
725 public void EmitMeta (ToplevelBlock b
)
730 ReturnLabel
= ig
.DefineLabel ();
734 // Here until we can fix the problem with Mono.CSharp.Switch, which
735 // currently can not cope with ig == null during resolve (which must
736 // be fixed for switch statements to work on anonymous methods).
738 public void EmitTopBlock (IMethodData md
, ToplevelBlock block
)
745 if (ResolveTopBlock (null, block
, md
.ParameterInfo
, md
, out unreachable
)){
746 if (Report
.Errors
> 0)
751 current_phase
= Phase
.Emitting
;
755 EmitResolvedTopBlock (block
, unreachable
);
757 } catch (Exception e
){
758 Console
.WriteLine ("Exception caught by the compiler while emitting:");
759 Console
.WriteLine (" Block that caused the problem begin at: " + block
.loc
);
761 Console
.WriteLine (e
.GetType ().FullName
+ ": " + e
.Message
);
771 public bool ResolveTopBlock (EmitContext anonymous_method_host
, ToplevelBlock block
,
772 ParametersCompiled ip
, IMethodData md
, out bool unreachable
)
775 unreachable
= this.unreachable
;
779 current_phase
= Phase
.Resolving
;
783 CurrentFile
= loc
.File
;
788 if (!block
.ResolveMeta (this, ip
))
791 using (this.With (EmitContext
.Flags
.DoFlowAnalysis
, true)) {
792 FlowBranchingToplevel top_level
;
793 if (anonymous_method_host
!= null)
794 top_level
= new FlowBranchingToplevel (anonymous_method_host
.CurrentBranching
, block
);
796 top_level
= block
.TopLevelBranching
;
798 current_flow_branching
= top_level
;
799 bool ok
= block
.Resolve (this);
800 current_flow_branching
= null;
805 bool flow_unreachable
= top_level
.End ();
806 if (flow_unreachable
)
807 this.unreachable
= unreachable
= true;
810 } catch (Exception e
) {
811 Console
.WriteLine ("Exception caught by the compiler while compiling:");
812 Console
.WriteLine (" Block that caused the problem begin at: " + loc
);
814 if (CurrentBlock
!= null){
815 Console
.WriteLine (" Block being compiled: [{0},{1}]",
816 CurrentBlock
.StartLocation
, CurrentBlock
.EndLocation
);
818 Console
.WriteLine (e
.GetType ().FullName
+ ": " + e
.Message
);
823 if (return_type
!= TypeManager
.void_type
&& !unreachable
) {
824 if (CurrentAnonymousMethod
== null) {
825 Report
.Error (161, md
.Location
, "`{0}': not all code paths return a value", md
.GetSignatureForError ());
827 } else if (!CurrentAnonymousMethod
.IsIterator
) {
828 Report
.Error (1643, CurrentAnonymousMethod
.Location
, "Not all code paths return a value in anonymous method of type `{0}'",
829 CurrentAnonymousMethod
.GetSignatureForError ());
838 public Type ReturnType
{
847 public void EmitResolvedTopBlock (ToplevelBlock block
, bool unreachable
)
853 ig
.MarkLabel (ReturnLabel
);
855 if (return_value
!= null){
856 ig
.Emit (OpCodes
.Ldloc
, return_value
);
857 ig
.Emit (OpCodes
.Ret
);
860 // If `HasReturnLabel' is set, then we already emitted a
861 // jump to the end of the method, so we must emit a `ret'
864 // Unfortunately, System.Reflection.Emit automatically emits
865 // a leave to the end of a finally block. This is a problem
866 // if no code is following the try/finally block since we may
867 // jump to a point after the end of the method.
868 // As a workaround, we're always creating a return label in
872 if (HasReturnLabel
|| !unreachable
) {
873 if (return_type
!= TypeManager
.void_type
)
874 ig
.Emit (OpCodes
.Ldloc
, TemporaryReturn ());
875 ig
.Emit (OpCodes
.Ret
);
881 /// This is called immediately before emitting an IL opcode to tell the symbol
882 /// writer to which source line this opcode belongs.
884 public void Mark (Location loc
)
886 if (!SymbolWriter
.HasSymbolWriter
|| OmitDebuggingInfo
|| loc
.IsNull
)
889 SymbolWriter
.MarkSequencePoint (ig
, loc
);
892 public void DefineLocalVariable (string name
, LocalBuilder builder
)
894 SymbolWriter
.DefineLocalVariable (name
, builder
);
897 public void BeginScope ()
900 SymbolWriter
.OpenScope(ig
);
903 public void EndScope ()
906 SymbolWriter
.CloseScope(ig
);
910 /// Returns a temporary storage for a variable of type t as
911 /// a local variable in the current body.
913 public LocalBuilder
GetTemporaryLocal (Type t
)
915 if (temporary_storage
!= null) {
916 object o
= temporary_storage
[t
];
920 o
= s
.Count
== 0 ? null : s
.Pop ();
922 temporary_storage
.Remove (t
);
926 return (LocalBuilder
) o
;
928 return ig
.DeclareLocal (t
);
931 public void FreeTemporaryLocal (LocalBuilder b
, Type t
)
933 if (temporary_storage
== null) {
934 temporary_storage
= new Hashtable ();
935 temporary_storage
[t
] = b
;
938 object o
= temporary_storage
[t
];
940 temporary_storage
[t
] = b
;
943 Stack s
= o
as Stack
;
947 temporary_storage
[t
] = s
;
953 /// Current loop begin and end labels.
955 public Label LoopBegin
, LoopEnd
;
958 /// Default target in a switch statement. Only valid if
961 public Label DefaultTarget
;
964 /// If this is non-null, points to the current switch statement
966 public Switch Switch
;
969 /// ReturnValue creates on demand the LocalBuilder for the
970 /// return value from the function. By default this is not
971 /// used. This is only required when returns are found inside
972 /// Try or Catch statements.
974 /// This method is typically invoked from the Emit phase, so
975 /// we allow the creation of a return label if it was not
976 /// requested during the resolution phase. Could be cleaned
977 /// up, but it would replicate a lot of logic in the Emit phase
978 /// of the code that uses it.
980 public LocalBuilder
TemporaryReturn ()
982 if (return_value
== null){
983 return_value
= ig
.DeclareLocal (return_type
);
984 if (!HasReturnLabel
){
985 ReturnLabel
= ig
.DefineLabel ();
986 HasReturnLabel
= true;
994 /// This method is used during the Resolution phase to flag the
995 /// need to define the ReturnLabel
997 public void NeedReturnLabel ()
999 if (current_phase
!= Phase
.Resolving
){
1001 // The reason is that the `ReturnLabel' is declared between
1002 // resolution and emission
1004 throw new Exception ("NeedReturnLabel called from Emit phase, should only be called during Resolve");
1007 if (!HasReturnLabel
)
1008 HasReturnLabel
= true;
1012 public Expression
GetThis (Location loc
)
1015 if (CurrentBlock
!= null)
1016 my_this
= new This (CurrentBlock
, loc
);
1018 my_this
= new This (loc
);
1020 if (!my_this
.ResolveBase (this))
1028 public abstract class CommonAssemblyModulClass
: Attributable
, IResolveContext
{
1030 protected CommonAssemblyModulClass ():
1035 public void AddAttributes (ArrayList attrs
)
1037 foreach (Attribute a
in attrs
)
1040 if (attributes
== null) {
1041 attributes
= new Attributes (attrs
);
1044 attributes
.AddAttributes (attrs
);
1047 public virtual void Emit (TypeContainer tc
)
1049 if (OptAttributes
== null)
1052 OptAttributes
.Emit ();
1055 protected Attribute
ResolveAttribute (Type a_type
)
1057 Attribute a
= OptAttributes
.Search (a_type
);
1064 public override IResolveContext ResolveContext
{
1065 get { return this; }
1068 #region IResolveContext Members
1070 public DeclSpace DeclContainer
{
1071 get { return RootContext.ToplevelTypes; }
1074 public DeclSpace GenericDeclContainer
{
1075 get { return DeclContainer; }
1078 public bool IsInObsoleteScope
{
1079 get { return false; }
1082 public bool IsInUnsafeScope
{
1083 get { return false; }
1089 public class AssemblyClass
: CommonAssemblyModulClass
{
1090 // TODO: make it private and move all builder based methods here
1091 public AssemblyBuilder Builder
;
1092 bool is_cls_compliant
;
1093 bool wrap_non_exception_throws
;
1094 Type runtime_compatibility_attr_type
;
1096 public Attribute ClsCompliantAttribute
;
1098 ListDictionary declarative_security
;
1100 bool has_extension_method
;
1101 public AssemblyName Name
;
1102 MethodInfo add_type_forwarder
;
1103 ListDictionary emitted_forwarders
;
1106 // Module is here just because of error messages
1107 static string[] attribute_targets
= new string [] { "assembly", "module" }
;
1109 public AssemblyClass (): base ()
1112 wrap_non_exception_throws
= true;
1116 public bool HasExtensionMethods
{
1119 has_extension_method
= value;
1124 public bool IsClsCompliant
{
1126 return is_cls_compliant
;
1130 public bool WrapNonExceptionThrows
{
1132 return wrap_non_exception_throws
;
1136 public override AttributeTargets AttributeTargets
{
1138 return AttributeTargets
.Assembly
;
1142 public override bool IsClsComplianceRequired ()
1144 return is_cls_compliant
;
1147 public void Resolve ()
1149 runtime_compatibility_attr_type
= TypeManager
.CoreLookupType (
1150 "System.Runtime.CompilerServices", "RuntimeCompatibilityAttribute", Kind
.Class
, false);
1152 if (RootContext
.Unsafe
) {
1154 // Emits [assembly: SecurityPermissionAttribute (SecurityAction.RequestMinimum, SkipVerification = true)]
1155 // when -unsafe option was specified
1158 Location loc
= Location
.Null
;
1160 MemberAccess system_security_permissions
= new MemberAccess (new MemberAccess (
1161 new QualifiedAliasMember (QualifiedAliasMember
.GlobalAlias
, "System", loc
), "Security", loc
), "Permissions", loc
);
1163 ArrayList pos
= new ArrayList (1);
1164 pos
.Add (new Argument (new MemberAccess (new MemberAccess (system_security_permissions
, "SecurityAction", loc
), "RequestMinimum")));
1166 ArrayList named
= new ArrayList (1);
1167 named
.Add (new DictionaryEntry ("SkipVerification", new Argument (new BoolLiteral (true, loc
))));
1169 GlobalAttribute g
= new GlobalAttribute (new NamespaceEntry (null, null, null), "assembly", system_security_permissions
,
1170 "SecurityPermissionAttribute", new object[] { pos, named }
, loc
, false);
1173 if (g
.Resolve () != null) {
1174 declarative_security
= new ListDictionary ();
1175 g
.ExtractSecurityPermissionSet (declarative_security
);
1179 if (OptAttributes
== null)
1182 // Ensure that we only have GlobalAttributes, since the Search isn't safe with other types.
1183 if (!OptAttributes
.CheckTargets())
1186 if (TypeManager
.cls_compliant_attribute_type
!= null)
1187 ClsCompliantAttribute
= ResolveAttribute (TypeManager
.cls_compliant_attribute_type
);
1189 if (ClsCompliantAttribute
!= null) {
1190 is_cls_compliant
= ClsCompliantAttribute
.GetClsCompliantAttributeValue ();
1193 if (runtime_compatibility_attr_type
!= null) {
1194 Attribute a
= ResolveAttribute (runtime_compatibility_attr_type
);
1196 object val
= a
.GetPropertyValue ("WrapNonExceptionThrows");
1198 wrap_non_exception_throws
= (bool) val
;
1204 private void SetPublicKey (AssemblyName an
, byte[] strongNameBlob
)
1207 // check for possible ECMA key
1208 if (strongNameBlob
.Length
== 16) {
1209 // will be rejected if not "the" ECMA key
1210 an
.SetPublicKey (strongNameBlob
);
1213 // take it, with or without, a private key
1214 RSA rsa
= CryptoConvert
.FromCapiKeyBlob (strongNameBlob
);
1215 // and make sure we only feed the public part to Sys.Ref
1216 byte[] publickey
= CryptoConvert
.ToCapiPublicKeyBlob (rsa
);
1218 // AssemblyName.SetPublicKey requires an additional header
1219 byte[] publicKeyHeader
= new byte [12] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00 }
;
1221 byte[] encodedPublicKey
= new byte [12 + publickey
.Length
];
1222 Buffer
.BlockCopy (publicKeyHeader
, 0, encodedPublicKey
, 0, 12);
1223 Buffer
.BlockCopy (publickey
, 0, encodedPublicKey
, 12, publickey
.Length
);
1224 an
.SetPublicKey (encodedPublicKey
);
1228 Error_AssemblySigning ("The specified file `" + RootContext
.StrongNameKeyFile
+ "' is incorrectly encoded");
1229 Environment
.Exit (1);
1233 // TODO: rewrite this code (to kill N bugs and make it faster) and use standard ApplyAttribute way.
1234 public AssemblyName
GetAssemblyName (string name
, string output
)
1236 if (OptAttributes
!= null) {
1237 foreach (Attribute a
in OptAttributes
.Attrs
) {
1238 // cannot rely on any resolve-based members before you call Resolve
1239 if (a
.ExplicitTarget
== null || a
.ExplicitTarget
!= "assembly")
1242 // TODO: This code is buggy: comparing Attribute name without resolving is wrong.
1243 // However, this is invoked by CodeGen.Init, when none of the namespaces
1245 // TODO: Does not handle quoted attributes properly
1247 case "AssemblyKeyFile":
1248 case "AssemblyKeyFileAttribute":
1249 case "System.Reflection.AssemblyKeyFileAttribute":
1250 if (RootContext
.StrongNameKeyFile
!= null) {
1251 Report
.SymbolRelatedToPreviousError (a
.Location
, a
.Name
);
1252 Report
.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
1253 "keyfile", "System.Reflection.AssemblyKeyFileAttribute");
1255 string value = a
.GetString ();
1256 if (value.Length
!= 0)
1257 RootContext
.StrongNameKeyFile
= value;
1260 case "AssemblyKeyName":
1261 case "AssemblyKeyNameAttribute":
1262 case "System.Reflection.AssemblyKeyNameAttribute":
1263 if (RootContext
.StrongNameKeyContainer
!= null) {
1264 Report
.SymbolRelatedToPreviousError (a
.Location
, a
.Name
);
1265 Report
.Warning (1616, 1, "Option `{0}' overrides attribute `{1}' given in a source file or added module",
1266 "keycontainer", "System.Reflection.AssemblyKeyNameAttribute");
1268 string value = a
.GetString ();
1269 if (value.Length
!= 0)
1270 RootContext
.StrongNameKeyContainer
= value;
1273 case "AssemblyDelaySign":
1274 case "AssemblyDelaySignAttribute":
1275 case "System.Reflection.AssemblyDelaySignAttribute":
1276 RootContext
.StrongNameDelaySign
= a
.GetBoolean ();
1282 AssemblyName an
= new AssemblyName ();
1283 an
.Name
= Path
.GetFileNameWithoutExtension (name
);
1285 // note: delay doesn't apply when using a key container
1286 if (RootContext
.StrongNameKeyContainer
!= null) {
1287 an
.KeyPair
= new StrongNameKeyPair (RootContext
.StrongNameKeyContainer
);
1291 // strongname is optional
1292 if (RootContext
.StrongNameKeyFile
== null)
1295 string AssemblyDir
= Path
.GetDirectoryName (output
);
1297 // the StrongName key file may be relative to (a) the compiled
1298 // file or (b) to the output assembly. See bugzilla #55320
1299 // http://bugzilla.ximian.com/show_bug.cgi?id=55320
1301 // (a) relative to the compiled file
1302 string filename
= Path
.GetFullPath (RootContext
.StrongNameKeyFile
);
1303 bool exist
= File
.Exists (filename
);
1304 if ((!exist
) && (AssemblyDir
!= null) && (AssemblyDir
!= String
.Empty
)) {
1305 // (b) relative to the outputed assembly
1306 filename
= Path
.GetFullPath (Path
.Combine (AssemblyDir
, RootContext
.StrongNameKeyFile
));
1307 exist
= File
.Exists (filename
);
1311 using (FileStream fs
= new FileStream (filename
, FileMode
.Open
, FileAccess
.Read
)) {
1312 byte[] snkeypair
= new byte [fs
.Length
];
1313 fs
.Read (snkeypair
, 0, snkeypair
.Length
);
1315 if (RootContext
.StrongNameDelaySign
) {
1316 // delayed signing - DO NOT include private key
1317 SetPublicKey (an
, snkeypair
);
1320 // no delay so we make sure we have the private key
1322 CryptoConvert
.FromCapiPrivateKeyBlob (snkeypair
);
1323 an
.KeyPair
= new StrongNameKeyPair (snkeypair
);
1325 catch (CryptographicException
) {
1326 if (snkeypair
.Length
== 16) {
1327 // error # is different for ECMA key
1328 Report
.Error (1606, "Could not sign the assembly. " +
1329 "ECMA key can only be used to delay-sign assemblies");
1332 Error_AssemblySigning ("The specified file `" + RootContext
.StrongNameKeyFile
+ "' does not have a private key");
1340 Error_AssemblySigning ("The specified file `" + RootContext
.StrongNameKeyFile
+ "' does not exist");
1346 void Error_AssemblySigning (string text
)
1348 Report
.Error (1548, "Error during assembly signing. " + text
);
1352 bool CheckInternalsVisibleAttribute (Attribute a
)
1354 string assembly_name
= a
.GetString ();
1355 if (assembly_name
.Length
== 0)
1358 AssemblyName aname
= null;
1360 aname
= new AssemblyName (assembly_name
);
1361 } catch (FileLoadException
) {
1362 } catch (ArgumentException
) {
1365 // Bad assembly name format
1367 Report
.Warning (1700, 3, a
.Location
, "Assembly reference `" + assembly_name
+ "' is invalid and cannot be resolved");
1368 // Report error if we have defined Version or Culture
1369 else if (aname
.Version
!= null || aname
.CultureInfo
!= null)
1370 throw new Exception ("Friend assembly `" + a
.GetString () +
1371 "' is invalid. InternalsVisibleTo cannot have version or culture specified.");
1372 else if (aname
.GetPublicKey () == null && Name
.GetPublicKey () != null && Name
.GetPublicKey ().Length
!= 0) {
1373 Report
.Error (1726, a
.Location
, "Friend assembly reference `" + aname
.FullName
+ "' is invalid." +
1374 " Strong named assemblies must specify a public key in their InternalsVisibleTo declarations");
1382 static bool IsValidAssemblyVersion (string version
)
1386 v
= new Version (version
);
1389 int major
= int.Parse (version
, CultureInfo
.InvariantCulture
);
1390 v
= new Version (major
, 0);
1396 foreach (int candidate
in new int [] { v.Major, v.Minor, v.Build, v.Revision }
) {
1397 if (candidate
> ushort.MaxValue
)
1404 public override void ApplyAttributeBuilder (Attribute a
, CustomAttributeBuilder customBuilder
)
1406 if (a
.IsValidSecurityAttribute ()) {
1407 if (declarative_security
== null)
1408 declarative_security
= new ListDictionary ();
1410 a
.ExtractSecurityPermissionSet (declarative_security
);
1414 if (a
.Type
== TypeManager
.assembly_culture_attribute_type
) {
1415 string value = a
.GetString ();
1416 if (value == null || value.Length
== 0)
1419 if (RootContext
.Target
== Target
.Exe
) {
1420 a
.Error_AttributeEmitError ("The executables cannot be satelite assemblies, remove the attribute or keep it empty");
1425 if (a
.Type
== TypeManager
.assembly_version_attribute_type
) {
1426 string value = a
.GetString ();
1427 if (value == null || value.Length
== 0)
1430 value = value.Replace ('*', '0');
1432 if (!IsValidAssemblyVersion (value)) {
1433 a
.Error_AttributeEmitError (string.Format ("Specified version `{0}' is not valid", value));
1439 if (a
.Type
== TypeManager
.internals_visible_attr_type
&& !CheckInternalsVisibleAttribute (a
))
1442 if (a
.Type
== TypeManager
.type_forwarder_attr_type
) {
1443 Type t
= a
.GetArgumentType ();
1444 if (t
== null || TypeManager
.HasElementType (t
)) {
1445 Report
.Error (735, a
.Location
, "Invalid type specified as an argument for TypeForwardedTo attribute");
1449 if (emitted_forwarders
== null) {
1450 emitted_forwarders
= new ListDictionary();
1451 } else if (emitted_forwarders
.Contains(t
)) {
1452 Report
.SymbolRelatedToPreviousError(((Attribute
)emitted_forwarders
[t
]).Location
, null);
1453 Report
.Error(739, a
.Location
, "A duplicate type forward of type `{0}'",
1454 TypeManager
.CSharpName(t
));
1458 emitted_forwarders
.Add(t
, a
);
1460 if (TypeManager
.LookupDeclSpace (t
) != null) {
1461 Report
.SymbolRelatedToPreviousError (t
);
1462 Report
.Error (729, a
.Location
, "Cannot forward type `{0}' because it is defined in this assembly",
1463 TypeManager
.CSharpName (t
));
1468 Report
.Error (730, a
.Location
, "Cannot forward type `{0}' because it is a nested type",
1469 TypeManager
.CSharpName (t
));
1473 if (t
.IsGenericType
) {
1474 Report
.Error (733, a
.Location
, "Cannot forward generic type `{0}'", TypeManager
.CSharpName (t
));
1478 if (add_type_forwarder
== null) {
1479 add_type_forwarder
= typeof (AssemblyBuilder
).GetMethod ("AddTypeForwarder",
1480 BindingFlags
.NonPublic
| BindingFlags
.Instance
);
1482 if (add_type_forwarder
== null) {
1483 Report
.RuntimeMissingSupport (a
.Location
, "TypeForwardedTo attribute");
1488 add_type_forwarder
.Invoke (Builder
, new object[] { t }
);
1492 if (a
.Type
== TypeManager
.extension_attribute_type
) {
1493 a
.Error_MisusedExtensionAttribute ();
1497 Builder
.SetCustomAttribute (customBuilder
);
1500 public override void Emit (TypeContainer tc
)
1505 if (has_extension_method
)
1506 Builder
.SetCustomAttribute (TypeManager
.extension_attribute_attr
);
1509 if (runtime_compatibility_attr_type
!= null) {
1510 // FIXME: Does this belong inside SRE.AssemblyBuilder instead?
1511 if (OptAttributes
== null || !OptAttributes
.Contains (runtime_compatibility_attr_type
)) {
1512 ConstructorInfo ci
= TypeManager
.GetPredefinedConstructor (
1513 runtime_compatibility_attr_type
, Location
.Null
, Type
.EmptyTypes
);
1514 PropertyInfo
[] pis
= new PropertyInfo
[1];
1515 pis
[0] = TypeManager
.GetPredefinedProperty (runtime_compatibility_attr_type
,
1516 "WrapNonExceptionThrows", Location
.Null
, TypeManager
.bool_type
);
1517 object [] pargs
= new object [1];
1519 Builder
.SetCustomAttribute (new CustomAttributeBuilder (ci
, new object [0], pis
, pargs
));
1523 if (declarative_security
!= null) {
1525 MethodInfo add_permission
= typeof (AssemblyBuilder
).GetMethod ("AddPermissionRequests", BindingFlags
.Instance
| BindingFlags
.NonPublic
);
1526 object builder_instance
= Builder
;
1529 // Microsoft runtime hacking
1530 if (add_permission
== null) {
1531 Type assembly_builder
= typeof (AssemblyBuilder
).Assembly
.GetType ("System.Reflection.Emit.AssemblyBuilderData");
1532 add_permission
= assembly_builder
.GetMethod ("AddPermissionRequests", BindingFlags
.Instance
| BindingFlags
.NonPublic
);
1534 FieldInfo fi
= typeof (AssemblyBuilder
).GetField ("m_assemblyData", BindingFlags
.Instance
| BindingFlags
.NonPublic
| BindingFlags
.GetField
);
1535 builder_instance
= fi
.GetValue (Builder
);
1538 object[] args
= new object [] { declarative_security
[SecurityAction
.RequestMinimum
],
1539 declarative_security
[SecurityAction
.RequestOptional
],
1540 declarative_security
[SecurityAction
.RequestRefuse
] };
1541 add_permission
.Invoke (builder_instance
, args
);
1544 Report
.RuntimeMissingSupport (Location
.Null
, "assembly permission setting");
1549 public override string[] ValidAttributeTargets
{
1551 return attribute_targets
;
1555 // Wrapper for AssemblyBuilder.AddModule
1556 static MethodInfo adder_method
;
1557 static public MethodInfo AddModule_Method
{
1559 if (adder_method
== null)
1560 adder_method
= typeof (AssemblyBuilder
).GetMethod ("AddModule", BindingFlags
.Instance
|BindingFlags
.NonPublic
);
1561 return adder_method
;
1564 public Module
AddModule (string module
)
1566 MethodInfo m
= AddModule_Method
;
1568 Report
.RuntimeMissingSupport (Location
.Null
, "/addmodule");
1569 Environment
.Exit (1);
1573 return (Module
) m
.Invoke (Builder
, new object [] { module }
);
1574 } catch (TargetInvocationException ex
) {
1575 throw ex
.InnerException
;
1580 public class ModuleClass
: CommonAssemblyModulClass
{
1581 // TODO: make it private and move all builder based methods here
1582 public ModuleBuilder Builder
;
1583 bool m_module_is_unsafe
;
1585 bool has_default_charset
;
1588 public CharSet DefaultCharSet
= CharSet
.Ansi
;
1589 public TypeAttributes DefaultCharSetType
= TypeAttributes
.AnsiClass
;
1591 static string[] attribute_targets
= new string [] { "module" }
;
1593 public ModuleClass (bool is_unsafe
)
1595 m_module_is_unsafe
= is_unsafe
;
1598 public override AttributeTargets AttributeTargets
{
1600 return AttributeTargets
.Module
;
1604 public override bool IsClsComplianceRequired ()
1606 return CodeGen
.Assembly
.IsClsCompliant
;
1609 public override void Emit (TypeContainer tc
)
1613 if (m_module_is_unsafe
) {
1614 Type t
= TypeManager
.CoreLookupType ("System.Security", "UnverifiableCodeAttribute", Kind
.Class
, true);
1616 ConstructorInfo unverifiable_code_ctor
= TypeManager
.GetPredefinedConstructor (t
, Location
.Null
, Type
.EmptyTypes
);
1617 if (unverifiable_code_ctor
!= null)
1618 Builder
.SetCustomAttribute (new CustomAttributeBuilder (unverifiable_code_ctor
, new object [0]));
1623 public override void ApplyAttributeBuilder (Attribute a
, CustomAttributeBuilder customBuilder
)
1625 if (a
.Type
== TypeManager
.cls_compliant_attribute_type
) {
1626 if (CodeGen
.Assembly
.ClsCompliantAttribute
== null) {
1627 Report
.Warning (3012, 1, a
.Location
, "You must specify the CLSCompliant attribute on the assembly, not the module, to enable CLS compliance checking");
1629 else if (CodeGen
.Assembly
.IsClsCompliant
!= a
.GetBoolean ()) {
1630 Report
.SymbolRelatedToPreviousError (CodeGen
.Assembly
.ClsCompliantAttribute
.Location
, CodeGen
.Assembly
.ClsCompliantAttribute
.GetSignatureForError ());
1631 Report
.Warning (3017, 1, a
.Location
, "You cannot specify the CLSCompliant attribute on a module that differs from the CLSCompliant attribute on the assembly");
1636 Builder
.SetCustomAttribute (customBuilder
);
1639 public bool HasDefaultCharSet
{
1642 return has_default_charset
;
1650 /// It is called very early therefore can resolve only predefined attributes
1652 public void Resolve ()
1655 if (OptAttributes
== null)
1658 if (!OptAttributes
.CheckTargets())
1661 if (TypeManager
.default_charset_type
== null)
1664 Attribute a
= ResolveAttribute (TypeManager
.default_charset_type
);
1666 has_default_charset
= true;
1667 DefaultCharSet
= a
.GetCharSetValue ();
1668 switch (DefaultCharSet
) {
1673 DefaultCharSetType
= TypeAttributes
.AutoClass
;
1675 case CharSet
.Unicode
:
1676 DefaultCharSetType
= TypeAttributes
.UnicodeClass
;
1679 Report
.Error (1724, a
.Location
, "Value specified for the argument to 'System.Runtime.InteropServices.DefaultCharSetAttribute' is not valid");
1686 public override string[] ValidAttributeTargets
{
1688 return attribute_targets
;