2009-02-20 Zoltan Varga <vargaz@gmail.com>
[mcs.git] / mcs / codegen.cs
blob68ab895b42d0bcb5c7ada6da2f6e6733fb2cfb40
1 //
2 // codegen.cs: The code generator
3 //
4 // Author:
5 // Miguel de Icaza (miguel@ximian.com)
6 //
7 // Copyright 2001, 2002, 2003 Ximian, Inc.
8 // Copyright 2004 Novell, Inc.
9 //
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.
18 #define PRODUCTION
20 using System;
21 using System.IO;
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 {
36 /// <summary>
37 /// Code generator class.
38 /// </summary>
39 public class CodeGen {
40 static AppDomain current_domain;
42 public static AssemblyClass Assembly;
43 public static ModuleClass Module;
45 static CodeGen ()
47 Reset ();
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 ('/');
60 if (pos != -1)
61 return name.Substring (pos + 1);
63 pos = name.LastIndexOf ('\\');
64 if (pos != -1)
65 return name.Substring (pos + 1);
67 return name;
70 public static string Dirname (string name)
72 int pos = name.LastIndexOf ('/');
74 if (pos != -1)
75 return name.Substring (0, pos);
77 pos = name.LastIndexOf ('\\');
78 if (pos != -1)
79 return name.Substring (0, pos);
81 return ".";
84 static public string FileName;
86 #if MS_COMPATIBLE
87 const AssemblyBuilderAccess COMPILER_ACCESS = 0;
88 #else
89 /* Keep this in sync with System.Reflection.Emit.AssemblyBuilder */
90 const AssemblyBuilderAccess COMPILER_ACCESS = (AssemblyBuilderAccess) 0x800;
91 #endif
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);
103 #if GMCS_SOURCE
104 Assembly.Name = Assembly.Builder.GetName ();
105 #endif
109 // Initializes the code generator variables
111 static public bool Init (string name, string output, bool want_debugging_support)
113 FileName = output;
114 AssemblyName an = Assembly.GetAssemblyName (name, output);
115 if (an == null)
116 return false;
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 '" +
127 ref_name.Name +
128 "' does not have a strong name.");
129 //Environment.Exit (1);
134 current_domain = AppDomain.CurrentDomain;
136 try {
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);
147 throw;
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);
154 return false;
157 #if GMCS_SOURCE
158 // Get the complete AssemblyName from the builder
159 // (We need to get the public key and token)
160 Assembly.Name = Assembly.Builder.GetName ();
161 #endif
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.
171 try {
172 Module.Builder = Assembly.Builder.DefineDynamicModule (
173 Basename (name), Basename (output), want_debugging_support);
175 #if !MS_COMPATIBLE
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)");
180 return false;
182 #endif
183 } catch (ExecutionEngineException e) {
184 Report.Error (40, "Unexpected debug information initialization error `{0}'",
185 e.Message);
186 return false;
189 return true;
192 static public void Save (string name, bool saveDebugInfo)
194 try {
195 Assembly.Builder.Save (Basename (name));
197 catch (COMException) {
198 if ((RootContext.StrongNameKeyFile == null) || (!RootContext.StrongNameDelaySign))
199 throw;
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);
208 return;
210 catch (System.UnauthorizedAccessException ua) {
211 Report.Error (16, "Could not write to file `"+name+"', cause: " + ua.Message);
212 return;
216 // Write debuger symbol file
218 if (saveDebugInfo)
219 SymbolWriter.WriteSymbolFile ();
224 /// <summary>
225 /// An interface to hold all the information needed in the resolving phase.
226 /// </summary>
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; }
242 /// <summary>
243 /// An Emit Context is created for each body of code (from methods,
244 /// properties bodies, indexer bodies or constructor bodies)
245 /// </summary>
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;
258 [Flags]
259 public enum Flags : int {
260 /// <summary>
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.
269 /// </summary>
270 CheckState = 1 << 0,
272 /// <summary>
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.
276 /// </summary>
277 ConstantCheckState = 1 << 1,
279 AllCheckStateFlags = CheckState | ConstantCheckState,
281 /// <summary>
282 /// Whether we are inside an unsafe block
283 /// </summary>
284 InUnsafe = 1 << 2,
286 InCatch = 1 << 3,
287 InFinally = 1 << 4,
289 /// <summary>
290 /// Whether control flow analysis is enabled
291 /// </summary>
292 DoFlowAnalysis = 1 << 5,
294 /// <summary>
295 /// Whether control flow analysis is disabled on structs
296 /// (only meaningful when DoFlowAnalysis is set)
297 /// </summary>
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
317 Flags flags;
319 /// <summary>
320 /// Whether we are emitting code inside a static or instance method
321 /// </summary>
322 public bool IsStatic;
324 /// <summary>
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.
331 /// </summary>
332 //public bool MethodIsStatic;
334 /// <summary>
335 /// The value that is allowed to be returned or NULL if there is no
336 /// return type.
337 /// </summary>
338 Type return_type;
340 /// <summary>
341 /// Points to the Type (extracted from the TypeContainer) that
342 /// declares this body of code
343 /// </summary>
344 public readonly Type ContainerType;
346 /// <summary>
347 /// Whether this is generating code for a constructor
348 /// </summary>
349 public bool IsConstructor;
351 /// <summary>
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)
355 /// </summary>
356 public Hashtable temporary_storage;
358 public Block CurrentBlock;
360 public int CurrentFile;
362 /// <summary>
363 /// The location where we store the return value.
364 /// </summary>
365 LocalBuilder return_value;
367 /// <summary>
368 /// The location where return has to jump to return the
369 /// value
370 /// </summary>
371 public Label ReturnLabel;
373 /// <summary>
374 /// If we already defined the ReturnLabel
375 /// </summary>
376 public bool HasReturnLabel;
378 /// <summary>
379 /// Whether we are in a `fixed' initialization
380 /// </summary>
381 public bool InFixedInitializer;
383 /// <summary>
384 /// Whether we are inside an anonymous method.
385 /// </summary>
386 public AnonymousExpression CurrentAnonymousMethod;
388 /// <summary>
389 /// Location for this EmitContext
390 /// </summary>
391 public Location loc;
393 /// <summary>
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
400 /// </summary>
401 public bool InEnumContext;
403 public readonly IResolveContext ResolveContext;
405 /// <summary>
406 /// The current iterator
407 /// </summary>
408 public Iterator CurrentIterator {
409 get { return CurrentAnonymousMethod as Iterator; }
412 /// <summary>
413 /// Whether we are in the resolving stage or not
414 /// </summary>
415 enum Phase {
416 Created,
417 Resolving,
418 Emitting
421 bool isAnonymousMethodAllowed = true;
423 Phase current_phase;
424 FlowBranching current_flow_branching;
426 static int next_id = 0;
427 int id = ++next_id;
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;
439 this.ig = ig;
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");
449 #if GMCS_SOURCE
450 if ((return_type is TypeBuilder) && return_type.IsGenericTypeDefinition)
451 throw new InternalErrorException ();
452 #endif
454 IsStatic = (code_flags & Modifiers.STATIC) != 0;
455 ReturnType = return_type;
456 IsConstructor = is_constructor;
457 CurrentBlock = null;
458 CurrentFile = 0;
459 current_phase = Phase.Created;
461 if (parent != null){
462 // Can only be null for the ResolveType contexts.
463 ContainerType = parent.TypeBuilder;
464 if (rc.IsInUnsafeScope)
465 flags |= Flags.InUnsafe;
467 loc = l;
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
525 EmitContext ec;
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)
535 this.ec = ec;
536 invmask = ~mask;
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)
566 Flags newflags =
567 (do_flow_analysis ? Flags.DoFlowAnalysis : 0) |
568 (omit_struct_analysis ? Flags.OmitStructFlowAnalysis : 0);
569 return new FlagsHandle (this, Flags.DoFlowAnalysis | Flags.OmitStructFlowAnalysis, newflags);
572 /// <summary>
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).
577 /// </summary>
578 public bool InferReturnType {
579 get { return (flags & Flags.InferReturnType) != 0; }
582 // IResolveContext.IsInObsoleteScope
583 public bool IsInObsoleteScope {
584 get {
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 {
613 get {
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; }
624 set {
625 if (value)
626 flags |= Flags.OmitDebuggingInfo;
627 else
628 flags &= ~Flags.OmitDebuggingInfo;
632 // <summary>
633 // Starts a new code branching. This inherits the state of all local
634 // variables and parameters from the current branching.
635 // </summary>
636 public FlowBranching StartFlowBranching (FlowBranching.BranchingType type, Location loc)
638 current_flow_branching = FlowBranching.CreateBranching (CurrentBranching, type, null, loc);
639 return current_flow_branching;
642 // <summary>
643 // Starts a new code branching for block `block'.
644 // </summary>
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;
658 return branching;
661 public FlowBranchingException StartFlowBranching (ExceptionStatement stmt)
663 FlowBranchingException branching = new FlowBranchingException (CurrentBranching, stmt);
664 current_flow_branching = branching;
665 return branching;
668 public FlowBranchingLabeled StartFlowBranching (LabeledStatement stmt)
670 FlowBranchingLabeled branching = new FlowBranchingLabeled (CurrentBranching, stmt);
671 current_flow_branching = branching;
672 return branching;
675 public FlowBranchingIterator StartFlowBranching (Iterator iterator)
677 FlowBranchingIterator branching = new FlowBranchingIterator (CurrentBranching, iterator);
678 current_flow_branching = branching;
679 return branching;
682 public FlowBranchingToplevel StartFlowBranching (ToplevelBlock stmt)
684 FlowBranchingToplevel branching = new FlowBranchingToplevel (CurrentBranching, stmt);
685 current_flow_branching = branching;
686 return branching;
689 // <summary>
690 // Ends a code branching. Merges the state of locals and parameters
691 // from all the children of the ending branching.
692 // </summary>
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;
702 // <summary>
703 // Kills the current code branching. This throws away any changed state
704 // information and should only be used in case of an error.
705 // </summary>
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)
715 return false;
717 // FIXME: IsIterator is too aggressive, we should capture only if child
718 // block contains yield
719 if (CurrentAnonymousMethod.IsIterator)
720 return true;
722 return local.Block.Toplevel != CurrentBlock.Toplevel;
725 public void EmitMeta (ToplevelBlock b)
727 b.EmitMeta (this);
729 if (HasReturnLabel)
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)
740 if (block == null)
741 return;
743 bool unreachable;
745 if (ResolveTopBlock (null, block, md.ParameterInfo, md, out unreachable)){
746 if (Report.Errors > 0)
747 return;
749 EmitMeta (block);
751 current_phase = Phase.Emitting;
752 #if PRODUCTION
753 try {
754 #endif
755 EmitResolvedTopBlock (block, unreachable);
756 #if PRODUCTION
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);
762 throw;
764 #endif
768 bool resolved;
769 bool unreachable;
771 public bool ResolveTopBlock (EmitContext anonymous_method_host, ToplevelBlock block,
772 ParametersCompiled ip, IMethodData md, out bool unreachable)
774 if (resolved) {
775 unreachable = this.unreachable;
776 return true;
779 current_phase = Phase.Resolving;
780 unreachable = false;
782 if (!loc.IsNull)
783 CurrentFile = loc.File;
785 #if PRODUCTION
786 try {
787 #endif
788 if (!block.ResolveMeta (this, ip))
789 return false;
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);
795 else
796 top_level = block.TopLevelBranching;
798 current_flow_branching = top_level;
799 bool ok = block.Resolve (this);
800 current_flow_branching = null;
802 if (!ok)
803 return false;
805 bool flow_unreachable = top_level.End ();
806 if (flow_unreachable)
807 this.unreachable = unreachable = true;
809 #if PRODUCTION
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);
819 throw;
821 #endif
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 ());
826 return false;
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 ());
830 return false;
834 resolved = true;
835 return true;
838 public Type ReturnType {
839 set {
840 return_type = value;
842 get {
843 return return_type;
847 public void EmitResolvedTopBlock (ToplevelBlock block, bool unreachable)
849 if (block != null)
850 block.Emit (this);
852 if (HasReturnLabel)
853 ig.MarkLabel (ReturnLabel);
855 if (return_value != null){
856 ig.Emit (OpCodes.Ldloc, return_value);
857 ig.Emit (OpCodes.Ret);
858 } else {
860 // If `HasReturnLabel' is set, then we already emitted a
861 // jump to the end of the method, so we must emit a `ret'
862 // there.
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
869 // this case.
872 if (HasReturnLabel || !unreachable) {
873 if (return_type != TypeManager.void_type)
874 ig.Emit (OpCodes.Ldloc, TemporaryReturn ());
875 ig.Emit (OpCodes.Ret);
880 /// <summary>
881 /// This is called immediately before emitting an IL opcode to tell the symbol
882 /// writer to which source line this opcode belongs.
883 /// </summary>
884 public void Mark (Location loc)
886 if (!SymbolWriter.HasSymbolWriter || OmitDebuggingInfo || loc.IsNull)
887 return;
889 SymbolWriter.MarkSequencePoint (ig, loc);
892 public void DefineLocalVariable (string name, LocalBuilder builder)
894 SymbolWriter.DefineLocalVariable (name, builder);
897 public void BeginScope ()
899 ig.BeginScope();
900 SymbolWriter.OpenScope(ig);
903 public void EndScope ()
905 ig.EndScope();
906 SymbolWriter.CloseScope(ig);
909 /// <summary>
910 /// Returns a temporary storage for a variable of type t as
911 /// a local variable in the current body.
912 /// </summary>
913 public LocalBuilder GetTemporaryLocal (Type t)
915 if (temporary_storage != null) {
916 object o = temporary_storage [t];
917 if (o != null) {
918 if (o is Stack) {
919 Stack s = (Stack) o;
920 o = s.Count == 0 ? null : s.Pop ();
921 } else {
922 temporary_storage.Remove (t);
925 if (o != null)
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;
936 return;
938 object o = temporary_storage [t];
939 if (o == null) {
940 temporary_storage [t] = b;
941 return;
943 Stack s = o as Stack;
944 if (s == null) {
945 s = new Stack ();
946 s.Push (o);
947 temporary_storage [t] = s;
949 s.Push (b);
952 /// <summary>
953 /// Current loop begin and end labels.
954 /// </summary>
955 public Label LoopBegin, LoopEnd;
957 /// <summary>
958 /// Default target in a switch statement. Only valid if
959 /// InSwitch is true
960 /// </summary>
961 public Label DefaultTarget;
963 /// <summary>
964 /// If this is non-null, points to the current switch statement
965 /// </summary>
966 public Switch Switch;
968 /// <summary>
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.
979 /// </summary>
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;
990 return return_value;
993 /// <summary>
994 /// This method is used during the Resolution phase to flag the
995 /// need to define the ReturnLabel
996 /// </summary>
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)
1014 This my_this;
1015 if (CurrentBlock != null)
1016 my_this = new This (CurrentBlock, loc);
1017 else
1018 my_this = new This (loc);
1020 if (!my_this.ResolveBase (this))
1021 my_this = null;
1023 return my_this;
1028 public abstract class CommonAssemblyModulClass : Attributable, IResolveContext {
1030 protected CommonAssemblyModulClass ():
1031 base (null)
1035 public void AddAttributes (ArrayList attrs)
1037 foreach (Attribute a in attrs)
1038 a.AttachTo (this);
1040 if (attributes == null) {
1041 attributes = new Attributes (attrs);
1042 return;
1044 attributes.AddAttributes (attrs);
1047 public virtual void Emit (TypeContainer tc)
1049 if (OptAttributes == null)
1050 return;
1052 OptAttributes.Emit ();
1055 protected Attribute ResolveAttribute (Type a_type)
1057 Attribute a = OptAttributes.Search (a_type);
1058 if (a != null) {
1059 a.Resolve ();
1061 return a;
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; }
1086 #endregion
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;
1099 #if GMCS_SOURCE
1100 bool has_extension_method;
1101 public AssemblyName Name;
1102 MethodInfo add_type_forwarder;
1103 ListDictionary emitted_forwarders;
1104 #endif
1106 // Module is here just because of error messages
1107 static string[] attribute_targets = new string [] { "assembly", "module" };
1109 public AssemblyClass (): base ()
1111 #if GMCS_SOURCE
1112 wrap_non_exception_throws = true;
1113 #endif
1116 public bool HasExtensionMethods {
1117 set {
1118 #if GMCS_SOURCE
1119 has_extension_method = value;
1120 #endif
1124 public bool IsClsCompliant {
1125 get {
1126 return is_cls_compliant;
1130 public bool WrapNonExceptionThrows {
1131 get {
1132 return wrap_non_exception_throws;
1136 public override AttributeTargets AttributeTargets {
1137 get {
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);
1171 g.AttachTo (this);
1173 if (g.Resolve () != null) {
1174 declarative_security = new ListDictionary ();
1175 g.ExtractSecurityPermissionSet (declarative_security);
1179 if (OptAttributes == null)
1180 return;
1182 // Ensure that we only have GlobalAttributes, since the Search isn't safe with other types.
1183 if (!OptAttributes.CheckTargets())
1184 return;
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);
1195 if (a != null) {
1196 object val = a.GetPropertyValue ("WrapNonExceptionThrows");
1197 if (val != null)
1198 wrap_non_exception_throws = (bool) val;
1203 // fix bug #56621
1204 private void SetPublicKey (AssemblyName an, byte[] strongNameBlob)
1206 try {
1207 // check for possible ECMA key
1208 if (strongNameBlob.Length == 16) {
1209 // will be rejected if not "the" ECMA key
1210 an.SetPublicKey (strongNameBlob);
1212 else {
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);
1227 catch (Exception) {
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")
1240 continue;
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
1244 // are loaded yet.
1245 // TODO: Does not handle quoted attributes properly
1246 switch (a.Name) {
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");
1254 } else {
1255 string value = a.GetString ();
1256 if (value.Length != 0)
1257 RootContext.StrongNameKeyFile = value;
1259 break;
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");
1267 } else {
1268 string value = a.GetString ();
1269 if (value.Length != 0)
1270 RootContext.StrongNameKeyContainer = value;
1272 break;
1273 case "AssemblyDelaySign":
1274 case "AssemblyDelaySignAttribute":
1275 case "System.Reflection.AssemblyDelaySignAttribute":
1276 RootContext.StrongNameDelaySign = a.GetBoolean ();
1277 break;
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);
1288 return an;
1291 // strongname is optional
1292 if (RootContext.StrongNameKeyFile == null)
1293 return an;
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);
1310 if (exist) {
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);
1319 else {
1320 // no delay so we make sure we have the private key
1321 try {
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");
1331 else {
1332 Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' does not have a private key");
1334 return null;
1339 else {
1340 Error_AssemblySigning ("The specified file `" + RootContext.StrongNameKeyFile + "' does not exist");
1341 return null;
1343 return an;
1346 void Error_AssemblySigning (string text)
1348 Report.Error (1548, "Error during assembly signing. " + text);
1351 #if GMCS_SOURCE
1352 bool CheckInternalsVisibleAttribute (Attribute a)
1354 string assembly_name = a.GetString ();
1355 if (assembly_name.Length == 0)
1356 return false;
1358 AssemblyName aname = null;
1359 try {
1360 aname = new AssemblyName (assembly_name);
1361 } catch (FileLoadException) {
1362 } catch (ArgumentException) {
1365 // Bad assembly name format
1366 if (aname == null)
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");
1375 return false;
1378 return true;
1380 #endif
1382 static bool IsValidAssemblyVersion (string version)
1384 Version v;
1385 try {
1386 v = new Version (version);
1387 } catch {
1388 try {
1389 int major = int.Parse (version, CultureInfo.InvariantCulture);
1390 v = new Version (major, 0);
1391 } catch {
1392 return false;
1396 foreach (int candidate in new int [] { v.Major, v.Minor, v.Build, v.Revision }) {
1397 if (candidate > ushort.MaxValue)
1398 return false;
1401 return true;
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);
1411 return;
1414 if (a.Type == TypeManager.assembly_culture_attribute_type) {
1415 string value = a.GetString ();
1416 if (value == null || value.Length == 0)
1417 return;
1419 if (RootContext.Target == Target.Exe) {
1420 a.Error_AttributeEmitError ("The executables cannot be satelite assemblies, remove the attribute or keep it empty");
1421 return;
1425 if (a.Type == TypeManager.assembly_version_attribute_type) {
1426 string value = a.GetString ();
1427 if (value == null || value.Length == 0)
1428 return;
1430 value = value.Replace ('*', '0');
1432 if (!IsValidAssemblyVersion (value)) {
1433 a.Error_AttributeEmitError (string.Format ("Specified version `{0}' is not valid", value));
1434 return;
1438 #if GMCS_SOURCE
1439 if (a.Type == TypeManager.internals_visible_attr_type && !CheckInternalsVisibleAttribute (a))
1440 return;
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");
1446 return;
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));
1455 return;
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));
1464 return;
1467 if (t.IsNested) {
1468 Report.Error (730, a.Location, "Cannot forward type `{0}' because it is a nested type",
1469 TypeManager.CSharpName (t));
1470 return;
1473 if (t.IsGenericType) {
1474 Report.Error (733, a.Location, "Cannot forward generic type `{0}'", TypeManager.CSharpName (t));
1475 return;
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");
1484 return;
1488 add_type_forwarder.Invoke (Builder, new object[] { t });
1489 return;
1492 if (a.Type == TypeManager.extension_attribute_type) {
1493 a.Error_MisusedExtensionAttribute ();
1494 return;
1496 #endif
1497 Builder.SetCustomAttribute (customBuilder);
1500 public override void Emit (TypeContainer tc)
1502 base.Emit (tc);
1504 #if GMCS_SOURCE
1505 if (has_extension_method)
1506 Builder.SetCustomAttribute (TypeManager.extension_attribute_attr);
1507 #endif
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];
1518 pargs [0] = true;
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;
1528 try {
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);
1543 catch {
1544 Report.RuntimeMissingSupport (Location.Null, "assembly permission setting");
1549 public override string[] ValidAttributeTargets {
1550 get {
1551 return attribute_targets;
1555 // Wrapper for AssemblyBuilder.AddModule
1556 static MethodInfo adder_method;
1557 static public MethodInfo AddModule_Method {
1558 get {
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;
1567 if (m == null) {
1568 Report.RuntimeMissingSupport (Location.Null, "/addmodule");
1569 Environment.Exit (1);
1572 try {
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;
1584 #if GMCS_SOURCE
1585 bool has_default_charset;
1586 #endif
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 {
1599 get {
1600 return AttributeTargets.Module;
1604 public override bool IsClsComplianceRequired ()
1606 return CodeGen.Assembly.IsClsCompliant;
1609 public override void Emit (TypeContainer tc)
1611 base.Emit (tc);
1613 if (m_module_is_unsafe) {
1614 Type t = TypeManager.CoreLookupType ("System.Security", "UnverifiableCodeAttribute", Kind.Class, true);
1615 if (t != null) {
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");
1632 return;
1636 Builder.SetCustomAttribute (customBuilder);
1639 public bool HasDefaultCharSet {
1640 get {
1641 #if GMCS_SOURCE
1642 return has_default_charset;
1643 #else
1644 return false;
1645 #endif
1649 /// <summary>
1650 /// It is called very early therefore can resolve only predefined attributes
1651 /// </summary>
1652 public void Resolve ()
1654 #if GMCS_SOURCE
1655 if (OptAttributes == null)
1656 return;
1658 if (!OptAttributes.CheckTargets())
1659 return;
1661 if (TypeManager.default_charset_type == null)
1662 return;
1664 Attribute a = ResolveAttribute (TypeManager.default_charset_type);
1665 if (a != null) {
1666 has_default_charset = true;
1667 DefaultCharSet = a.GetCharSetValue ();
1668 switch (DefaultCharSet) {
1669 case CharSet.Ansi:
1670 case CharSet.None:
1671 break;
1672 case CharSet.Auto:
1673 DefaultCharSetType = TypeAttributes.AutoClass;
1674 break;
1675 case CharSet.Unicode:
1676 DefaultCharSetType = TypeAttributes.UnicodeClass;
1677 break;
1678 default:
1679 Report.Error (1724, a.Location, "Value specified for the argument to 'System.Runtime.InteropServices.DefaultCharSetAttribute' is not valid");
1680 break;
1683 #endif
1686 public override string[] ValidAttributeTargets {
1687 get {
1688 return attribute_targets;