2 // report.cs: report errors and warnings.
4 // Author: Miguel de Icaza (miguel@ximian.com)
5 // Marek Safar (marek.safar@seznam.cz)
7 // (C) 2001 Ximian, Inc. (http://www.ximian.com)
13 using System.Collections;
14 using System.Collections.Specialized;
15 using System.Diagnostics;
16 using System.Reflection;
17 using System.Reflection.Emit;
19 namespace Mono.CSharp {
22 /// This class is used to report errors and warnings t te user.
26 /// Errors encountered so far
28 static public int Errors;
31 /// Warnings encountered so far
33 static public int Warnings;
36 /// Whether errors should be throw an exception
38 static public bool Fatal;
41 /// Whether warnings should be considered errors
43 static public bool WarningsAreErrors;
47 /// Whether to dump a stack trace on errors.
49 static public bool Stacktrace;
51 static public TextWriter Stderr = Console.Error;
54 // If the 'expected' error code is reported then the
55 // compilation succeeds.
57 // Used for the test suite to excercise the error codes
59 static int expected_error = 0;
62 // Keeps track of the warnings that we are ignoring
64 public static Hashtable warning_ignore_table;
66 static Hashtable warning_regions_table;
69 // This is used to save/restore the error state. When the
70 // error stack contains elements, warnings and errors are not
71 // reported to the user. This is used by the Lambda expression
72 // support to compile the code with various parameter values.
73 // A stack because of `Report.Errors == errors;'
75 static Stack error_stack;
76 static Stack warning_stack;
77 static bool reporting_disabled;
79 static int warning_level;
82 /// List of symbols related to reported error/warning. You have to fill it before error/warning is reported.
84 static ArrayList extra_information = new ArrayList ();
87 // IF YOU ADD A NEW WARNING YOU HAVE TO ADD ITS ID HERE
89 public static readonly int[] AllWarnings = new int[] {
91 105, 108, 109, 114, 162, 164, 168, 169, 183, 184, 197,
92 219, 251, 252, 253, 278, 282,
93 419, 420, 429, 436, 440, 465, 467, 469, 472,
94 612, 618, 626, 628, 642, 649, 652, 658, 659, 660, 661, 665, 672, 675,
97 1522, 1570, 1571, 1572, 1573, 1574, 1580, 1581, 1584, 1587, 1589, 1590, 1591, 1592,
98 1616, 1633, 1634, 1635, 1685, 1690, 1691, 1692,
102 3005, 3012, 3018, 3019, 3021, 3022, 3023, 3026, 3027,
104 402, 414, 693, 1058, 1700, 3024
110 // Just to be sure that binary search is working
111 Array.Sort (AllWarnings);
114 public static void Reset ()
116 Errors = Warnings = 0;
117 WarningsAreErrors = false;
118 warning_ignore_table = null;
119 warning_regions_table = null;
120 reporting_disabled = false;
123 public static void DisableReporting ()
125 if (error_stack == null)
126 error_stack = new Stack ();
127 error_stack.Push (Errors);
130 if (warning_stack == null)
131 warning_stack = new Stack ();
132 warning_stack.Push (Warnings);
135 reporting_disabled = true;
138 public static void EnableReporting ()
140 if (warning_stack != null)
141 Warnings = (int) warning_stack.Pop ();
143 Errors = (int) error_stack.Pop ();
144 if (error_stack.Count == 0) {
145 reporting_disabled = false;
149 public static IMessageRecorder msg_recorder;
151 public static IMessageRecorder SetMessageRecorder (IMessageRecorder recorder)
153 IMessageRecorder previous = msg_recorder;
154 msg_recorder = recorder;
158 public interface IMessageRecorder
161 void AddMessage (AbstractMessage msg);
162 bool PrintMessages ();
166 // Default message recorder, it uses two types of message groups.
167 // Common messages: messages reported in all sessions.
168 // Merged messages: union of all messages in all sessions.
170 public struct MessageRecorder : IMessageRecorder
172 ArrayList session_messages;
174 // A collection of exactly same messages reported in all sessions
176 ArrayList common_messages;
179 // A collection of unique messages reported in all sessions
181 ArrayList merged_messages;
183 public void EndSession ()
185 if (session_messages == null)
189 // Handles the first session
191 if (common_messages == null) {
192 common_messages = new ArrayList (session_messages);
193 merged_messages = session_messages;
194 session_messages = null;
199 // Store common messages if any
201 for (int i = 0; i < common_messages.Count; ++i) {
202 AbstractMessage cmsg = (AbstractMessage) common_messages [i];
203 bool common_msg_found = false;
204 foreach (AbstractMessage msg in session_messages) {
205 if (cmsg.Equals (msg)) {
206 common_msg_found = true;
211 if (!common_msg_found)
212 common_messages.RemoveAt (i);
216 // Merge session and previous messages
218 for (int i = 0; i < session_messages.Count; ++i) {
219 AbstractMessage msg = (AbstractMessage) session_messages [i];
220 bool msg_found = false;
221 for (int ii = 0; ii < merged_messages.Count; ++ii) {
222 if (msg.Equals (merged_messages [ii])) {
229 merged_messages.Add (msg);
233 public void AddMessage (AbstractMessage msg)
235 if (session_messages == null)
236 session_messages = new ArrayList ();
238 session_messages.Add (msg);
242 // Prints collected messages, common messages have a priority
244 public bool PrintMessages ()
246 ArrayList messages_to_print = merged_messages;
247 if (common_messages != null && common_messages.Count > 0) {
248 messages_to_print = common_messages;
251 if (messages_to_print == null)
254 foreach (AbstractMessage msg in messages_to_print)
261 public abstract class AbstractMessage
263 readonly string[] extra_info;
264 protected readonly int code;
265 protected readonly Location location;
266 readonly string message;
268 protected AbstractMessage (int code, Location loc, string msg, ArrayList extraInfo)
272 this.code = 8000 - code;
276 if (extraInfo.Count != 0) {
277 this.extra_info = (string[])extraInfo.ToArray (typeof (string));
281 protected AbstractMessage (AbstractMessage aMsg)
283 this.code = aMsg.code;
284 this.location = aMsg.location;
285 this.message = aMsg.message;
286 this.extra_info = aMsg.extra_info;
289 static void Check (int code)
291 if (code == expected_error) {
292 Environment.Exit (0);
296 public override bool Equals (object obj)
298 AbstractMessage msg = obj as AbstractMessage;
302 return code == msg.code && location.Equals (msg.location) && message == msg.message;
305 public override int GetHashCode ()
307 return code.GetHashCode ();
310 public abstract bool IsWarning { get; }
312 public abstract string MessageType { get; }
314 public virtual void Print ()
316 if (msg_recorder != null) {
318 // This line is useful when debugging messages recorder
320 // Console.WriteLine ("RECORDING: {0} {1} {2}", code, location, message);
321 msg_recorder.AddMessage (this);
325 if (reporting_disabled)
328 StringBuilder msg = new StringBuilder ();
329 if (!location.IsNull) {
330 msg.Append (location.ToString ());
333 msg.AppendFormat ("{0} CS{1:0000}: {2}", MessageType, code, message);
334 Stderr.WriteLine (msg.ToString ());
336 if (extra_info != null) {
337 foreach (string s in extra_info)
338 Stderr.WriteLine (s + MessageType + ")");
342 Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
345 if (!IsWarning || WarningsAreErrors)
346 throw new Exception (message);
353 sealed class WarningMessage : AbstractMessage
357 public WarningMessage (int code, int level, Location loc, string message, ArrayList extra_info)
358 : base (code, loc, message, extra_info)
363 public override bool IsWarning {
369 if (WarningLevel < Level)
372 if (warning_ignore_table != null) {
373 if (warning_ignore_table.Contains (code)) {
378 if (warning_regions_table == null || location.IsNull)
381 WarningRegions regions = (WarningRegions)warning_regions_table [location.Name];
385 return regions.IsWarningEnabled (code, location.Row);
388 public override void Print ()
393 if (WarningsAreErrors) {
394 new ErrorMessage (this).Print ();
402 public override string MessageType {
409 sealed class ErrorMessage : AbstractMessage
411 public ErrorMessage (int code, Location loc, string message, ArrayList extraInfo)
412 : base (code, loc, message, extraInfo)
416 public ErrorMessage (AbstractMessage aMsg)
421 public override void Print()
427 public override bool IsWarning {
428 get { return false; }
431 public override string MessageType {
438 public static void FeatureIsNotAvailable (Location loc, string feature)
441 if (RootContext.Version == LanguageVersion.ISO_1)
443 else if (RootContext.Version == LanguageVersion.ISO_2)
446 throw new InternalErrorException ("Invalid feature version", RootContext.Version);
448 Report.Error (1644, loc,
449 "Feature `{0}' cannot be used because it is not part of the C# {1} language specification",
453 public static string FriendlyStackTrace (Exception e)
455 return FriendlyStackTrace (new StackTrace (e, true));
458 static string FriendlyStackTrace (StackTrace t)
460 StringBuilder sb = new StringBuilder ();
462 bool foundUserCode = false;
464 for (int i = 0; i < t.FrameCount; i++) {
465 StackFrame f = t.GetFrame (i);
466 MethodBase mb = f.GetMethod ();
468 if (!foundUserCode && mb.ReflectedType == typeof (Report))
471 foundUserCode = true;
475 if (f.GetFileLineNumber () > 0)
476 sb.AppendFormat ("(at {0}:{1}) ", f.GetFileName (), f.GetFileLineNumber ());
478 sb.AppendFormat ("{0}.{1} (", mb.ReflectedType.Name, mb.Name);
481 foreach (ParameterInfo pi in mb.GetParameters ()) {
486 sb.Append (TypeManager.CSharpName (pi.ParameterType));
491 return sb.ToString ();
494 public static void StackTrace ()
496 Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
499 public static bool IsValidWarning (int code)
501 return Array.BinarySearch (AllWarnings, code) >= 0;
504 static public void RuntimeMissingSupport (Location loc, string feature)
506 Report.Error (-88, loc, "Your .NET Runtime does not support `{0}'. Please use the latest Mono runtime instead.", feature);
510 /// In most error cases is very useful to have information about symbol that caused the error.
511 /// Call this method before you call Report.Error when it makes sense.
513 static public void SymbolRelatedToPreviousError (Location loc, string symbol)
515 SymbolRelatedToPreviousError (loc.ToString (), symbol);
518 static public void SymbolRelatedToPreviousError (MemberInfo mi)
520 if (reporting_disabled)
523 Type dt = TypeManager.DropGenericTypeArguments (mi.DeclaringType);
524 if (TypeManager.IsDelegateType (dt)) {
525 SymbolRelatedToPreviousError (dt);
529 DeclSpace temp_ds = TypeManager.LookupDeclSpace (dt);
530 if (temp_ds == null) {
531 SymbolRelatedToPreviousError (dt.Assembly.Location, TypeManager.GetFullNameSignature (mi));
533 MethodBase mb = mi as MethodBase;
535 mb = TypeManager.DropGenericMethodArguments (mb);
536 IMethodData md = TypeManager.GetMethod (mb);
537 SymbolRelatedToPreviousError (md.Location, md.GetSignatureForError ());
541 MemberCore mc = temp_ds.GetDefinition (mi.Name);
542 SymbolRelatedToPreviousError (mc);
546 static public void SymbolRelatedToPreviousError (MemberCore mc)
548 SymbolRelatedToPreviousError (mc.Location, mc.GetSignatureForError ());
551 static public void SymbolRelatedToPreviousError (Type type)
553 if (reporting_disabled)
556 type = TypeManager.DropGenericTypeArguments (type);
558 if (TypeManager.IsGenericParameter (type)) {
559 TypeParameter tp = TypeManager.LookupTypeParameter (type);
561 SymbolRelatedToPreviousError (tp.Location, "");
566 if (type is TypeBuilder) {
567 DeclSpace temp_ds = TypeManager.LookupDeclSpace (type);
568 SymbolRelatedToPreviousError (temp_ds.Location, TypeManager.CSharpName (type));
569 } else if (type.HasElementType) {
570 SymbolRelatedToPreviousError (type.GetElementType ());
572 SymbolRelatedToPreviousError (type.Assembly.Location, TypeManager.CSharpName (type));
576 static void SymbolRelatedToPreviousError (string loc, string symbol)
578 extra_information.Add (String.Format ("{0} (Location of the symbol related to previous ", loc));
581 public static void ExtraInformation (Location loc, string msg)
583 extra_information.Add (String.Format ("{0} {1}", loc, msg));
586 public static WarningRegions RegisterWarningRegion (Location location)
588 if (warning_regions_table == null)
589 warning_regions_table = new Hashtable ();
591 WarningRegions regions = (WarningRegions)warning_regions_table [location.Name];
592 if (regions == null) {
593 regions = new WarningRegions ();
594 warning_regions_table.Add (location.Name, regions);
599 static public void Warning (int code, int level, Location loc, string message)
601 WarningMessage w = new WarningMessage (code, level, loc, message, extra_information);
602 extra_information.Clear ();
606 static public void Warning (int code, int level, Location loc, string format, string arg)
608 WarningMessage w = new WarningMessage (code, level, loc, String.Format (format, arg), extra_information);
609 extra_information.Clear ();
613 static public void Warning (int code, int level, Location loc, string format, string arg1, string arg2)
615 WarningMessage w = new WarningMessage (code, level, loc, String.Format (format, arg1, arg2), extra_information);
616 extra_information.Clear ();
620 static public void Warning (int code, int level, Location loc, string format, params object[] args)
622 WarningMessage w = new WarningMessage (code, level, loc, String.Format (format, args), extra_information);
623 extra_information.Clear ();
627 static public void Warning (int code, int level, string message)
629 Warning (code, level, Location.Null, message);
632 static public void Warning (int code, int level, string format, string arg)
634 Warning (code, level, Location.Null, format, arg);
637 static public void Warning (int code, int level, string format, string arg1, string arg2)
639 Warning (code, level, Location.Null, format, arg1, arg2);
642 static public void Warning (int code, int level, string format, params string[] args)
644 Warning (code, level, Location.Null, String.Format (format, args));
647 static public void Error (int code, Location loc, string error)
649 new ErrorMessage (code, loc, error, extra_information).Print ();
650 extra_information.Clear ();
653 static public void Error (int code, Location loc, string format, string arg)
655 new ErrorMessage (code, loc, String.Format (format, arg), extra_information).Print ();
656 extra_information.Clear ();
659 static public void Error (int code, Location loc, string format, string arg1, string arg2)
661 new ErrorMessage (code, loc, String.Format (format, arg1, arg2), extra_information).Print ();
662 extra_information.Clear ();
665 static public void Error (int code, Location loc, string format, params object[] args)
667 Error (code, loc, String.Format (format, args));
670 static public void Error (int code, string error)
672 Error (code, Location.Null, error);
675 static public void Error (int code, string format, string arg)
677 Error (code, Location.Null, format, arg);
680 static public void Error (int code, string format, string arg1, string arg2)
682 Error (code, Location.Null, format, arg1, arg2);
685 static public void Error (int code, string format, params string[] args)
687 Error (code, Location.Null, String.Format (format, args));
690 static public void SetIgnoreWarning (int code)
692 if (warning_ignore_table == null)
693 warning_ignore_table = new Hashtable ();
695 warning_ignore_table [code] = true;
698 static public int ExpectedError {
700 expected_error = value;
703 return expected_error;
707 public static int WarningLevel {
709 return warning_level;
712 warning_level = value;
716 public static int DebugFlags = 0;
718 [Conditional ("MCS_DEBUG")]
719 static public void Debug (string message, params object[] args)
721 Debug (4, message, args);
724 [Conditional ("MCS_DEBUG")]
725 static public void Debug (int category, string message, params object[] args)
727 if ((category & DebugFlags) == 0)
730 StringBuilder sb = new StringBuilder (message);
732 if ((args != null) && (args.Length > 0)) {
736 foreach (object arg in args) {
743 else if (arg is ICollection)
744 sb.Append (PrintCollection ((ICollection) arg));
750 Console.WriteLine (sb.ToString ());
753 static public string PrintCollection (ICollection collection)
755 StringBuilder sb = new StringBuilder ();
757 sb.Append (collection.GetType ());
761 foreach (object o in collection) {
770 return sb.ToString ();
774 public enum TimerType {
784 public enum CounterType {
793 static DateTime[] timer_start;
794 static TimeSpan[] timers;
795 static long[] timer_counters;
796 static long[] counters;
800 timer_start = new DateTime [(int) TimerType.CountTimers];
801 timers = new TimeSpan [(int) TimerType.CountTimers];
802 timer_counters = new long [(int) TimerType.CountTimers];
803 counters = new long [(int) CounterType.CountCounters];
805 for (int i = 0; i < (int) TimerType.CountTimers; i++) {
806 timer_start [i] = DateTime.Now;
807 timers [i] = TimeSpan.Zero;
811 [Conditional("TIMER")]
812 static public void IncrementCounter (CounterType which)
814 ++counters [(int) which];
817 [Conditional("TIMER")]
818 static public void StartTimer (TimerType which)
820 timer_start [(int) which] = DateTime.Now;
823 [Conditional("TIMER")]
824 static public void StopTimer (TimerType which)
826 timers [(int) which] += DateTime.Now - timer_start [(int) which];
827 ++timer_counters [(int) which];
830 [Conditional("TIMER")]
831 static public void ShowTimers ()
833 ShowTimer (TimerType.FindMembers, "- FindMembers timer");
834 ShowTimer (TimerType.TcFindMembers, "- TypeContainer.FindMembers timer");
835 ShowTimer (TimerType.MemberLookup, "- MemberLookup timer");
836 ShowTimer (TimerType.CachedLookup, "- CachedLookup timer");
837 ShowTimer (TimerType.CacheInit, "- Cache init");
838 ShowTimer (TimerType.MiscTimer, "- Misc timer");
840 ShowCounter (CounterType.FindMembers, "- Find members");
841 ShowCounter (CounterType.MemberCache, "- Member cache");
842 ShowCounter (CounterType.MiscCounter, "- Misc counter");
845 static public void ShowCounter (CounterType which, string msg)
847 Console.WriteLine ("{0} {1}", counters [(int) which], msg);
850 static public void ShowTimer (TimerType which, string msg)
853 "[{0:00}:{1:000}] {2} (used {3} times)",
854 (int) timers [(int) which].TotalSeconds,
855 timers [(int) which].Milliseconds, msg,
856 timer_counters [(int) which]);
860 public class InternalErrorException : Exception {
861 public InternalErrorException (MemberCore mc, Exception e)
862 : base (mc.Location + " " + mc.GetSignatureForError (), e)
866 public InternalErrorException ()
867 : base ("Internal error")
871 public InternalErrorException (string message)
876 public InternalErrorException (string message, params object[] args)
877 : base (String.Format (message, args))
880 public InternalErrorException (Exception e, Location loc)
881 : base (loc.ToString (), e)
887 /// Handles #pragma warning
889 public class WarningRegions {
891 abstract class PragmaCmd
895 protected PragmaCmd (int line)
900 public abstract bool IsEnabled (int code, bool previous);
903 class Disable : PragmaCmd
906 public Disable (int line, int code)
912 public override bool IsEnabled (int code, bool previous)
914 return this.code == code ? false : previous;
918 class DisableAll : PragmaCmd
920 public DisableAll (int line)
923 public override bool IsEnabled(int code, bool previous)
929 class Enable : PragmaCmd
932 public Enable (int line, int code)
938 public override bool IsEnabled(int code, bool previous)
940 return this.code == code ? true : previous;
944 class EnableAll : PragmaCmd
946 public EnableAll (int line)
949 public override bool IsEnabled(int code, bool previous)
956 ArrayList regions = new ArrayList ();
958 public void WarningDisable (int line)
960 regions.Add (new DisableAll (line));
963 public void WarningDisable (Location location, int code)
965 if (CheckWarningCode (code, location))
966 regions.Add (new Disable (location.Row, code));
969 public void WarningEnable (int line)
971 regions.Add (new EnableAll (line));
974 public void WarningEnable (Location location, int code)
976 if (CheckWarningCode (code, location))
977 regions.Add (new Enable (location.Row, code));
980 public bool IsWarningEnabled (int code, int src_line)
983 foreach (PragmaCmd pragma in regions) {
984 if (src_line < pragma.Line)
987 result = pragma.IsEnabled (code, result);
992 static bool CheckWarningCode (int code, Location loc)
994 if (Report.IsValidWarning (code))
997 Report.Warning (1691, 1, loc, "`{0}' is not a valid warning number", code.ToString ());