2 // report.cs: report errors and warnings.
4 // Author: Miguel de Icaza (miguel@ximian.com)
5 // Marek Safar (marek.safar@seznam.cz)
7 // Copyright 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, 458, 464, 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;
121 error_stack = warning_stack = null;
124 public static void DisableReporting ()
126 if (error_stack == null)
127 error_stack = new Stack ();
128 error_stack.Push (Errors);
131 if (warning_stack == null)
132 warning_stack = new Stack ();
133 warning_stack.Push (Warnings);
136 reporting_disabled = true;
139 public static void EnableReporting ()
141 if (warning_stack != null)
142 Warnings = (int) warning_stack.Pop ();
146 Errors = (int) error_stack.Pop ();
147 if (error_stack.Count == 0) {
148 reporting_disabled = false;
152 public static IMessageRecorder msg_recorder;
154 public static IMessageRecorder SetMessageRecorder (IMessageRecorder recorder)
156 IMessageRecorder previous = msg_recorder;
157 msg_recorder = recorder;
161 public interface IMessageRecorder
164 void AddMessage (AbstractMessage msg);
165 bool PrintMessages ();
169 // Default message recorder, it uses two types of message groups.
170 // Common messages: messages reported in all sessions.
171 // Merged messages: union of all messages in all sessions.
173 public struct MessageRecorder : IMessageRecorder
175 ArrayList session_messages;
177 // A collection of exactly same messages reported in all sessions
179 ArrayList common_messages;
182 // A collection of unique messages reported in all sessions
184 ArrayList merged_messages;
186 public void EndSession ()
188 if (session_messages == null)
192 // Handles the first session
194 if (common_messages == null) {
195 common_messages = new ArrayList (session_messages);
196 merged_messages = session_messages;
197 session_messages = null;
202 // Store common messages if any
204 for (int i = 0; i < common_messages.Count; ++i) {
205 AbstractMessage cmsg = (AbstractMessage) common_messages [i];
206 bool common_msg_found = false;
207 foreach (AbstractMessage msg in session_messages) {
208 if (cmsg.Equals (msg)) {
209 common_msg_found = true;
214 if (!common_msg_found)
215 common_messages.RemoveAt (i);
219 // Merge session and previous messages
221 for (int i = 0; i < session_messages.Count; ++i) {
222 AbstractMessage msg = (AbstractMessage) session_messages [i];
223 bool msg_found = false;
224 for (int ii = 0; ii < merged_messages.Count; ++ii) {
225 if (msg.Equals (merged_messages [ii])) {
232 merged_messages.Add (msg);
236 public void AddMessage (AbstractMessage msg)
238 if (session_messages == null)
239 session_messages = new ArrayList ();
241 session_messages.Add (msg);
245 // Prints collected messages, common messages have a priority
247 public bool PrintMessages ()
249 ArrayList messages_to_print = merged_messages;
250 if (common_messages != null && common_messages.Count > 0) {
251 messages_to_print = common_messages;
254 if (messages_to_print == null)
257 foreach (AbstractMessage msg in messages_to_print)
264 public abstract class AbstractMessage
266 readonly string[] extra_info;
267 protected readonly int code;
268 protected readonly Location location;
269 readonly string message;
271 protected AbstractMessage (int code, Location loc, string msg, ArrayList extraInfo)
275 this.code = 8000 - code;
279 if (extraInfo.Count != 0) {
280 this.extra_info = (string[])extraInfo.ToArray (typeof (string));
284 protected AbstractMessage (AbstractMessage aMsg)
286 this.code = aMsg.code;
287 this.location = aMsg.location;
288 this.message = aMsg.message;
289 this.extra_info = aMsg.extra_info;
292 static void Check (int code)
294 if (code == expected_error) {
295 Environment.Exit (0);
299 public override bool Equals (object obj)
301 AbstractMessage msg = obj as AbstractMessage;
305 return code == msg.code && location.Equals (msg.location) && message == msg.message;
308 public override int GetHashCode ()
310 return code.GetHashCode ();
313 public abstract bool IsWarning { get; }
315 public abstract string MessageType { get; }
317 public virtual void Print ()
319 if (msg_recorder != null) {
321 // This line is useful when debugging messages recorder
323 // Console.WriteLine ("RECORDING: {0} {1} {2}", code, location, message);
324 msg_recorder.AddMessage (this);
328 if (reporting_disabled)
331 StringBuilder msg = new StringBuilder ();
332 if (!location.IsNull) {
333 msg.Append (location.ToString ());
336 msg.AppendFormat ("{0} CS{1:0000}: {2}", MessageType, code, message);
340 if (Stderr == Console.Error)
341 Stderr.WriteLine (ColorFormat (msg.ToString ()));
343 Stderr.WriteLine (msg.ToString ());
345 if (extra_info != null) {
346 foreach (string s in extra_info)
347 Stderr.WriteLine (s + MessageType + ")");
351 Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
354 if (!IsWarning || WarningsAreErrors)
355 throw new Exception (message);
361 protected virtual string ColorFormat (string s)
367 sealed class WarningMessage : AbstractMessage
371 public WarningMessage (int code, int level, Location loc, string message, ArrayList extra_info)
372 : base (code, loc, message, extra_info)
377 public override bool IsWarning {
383 if (WarningLevel < Level)
386 if (warning_ignore_table != null) {
387 if (warning_ignore_table.Contains (code)) {
392 if (warning_regions_table == null || location.IsNull)
395 WarningRegions regions = (WarningRegions)warning_regions_table [location.Name];
399 return regions.IsWarningEnabled (code, location.Row);
402 public override void Print ()
407 if (WarningsAreErrors) {
408 new ErrorMessage (this).Print ();
416 public override string MessageType {
423 static int NameToCode (string s)
448 // maps a color name to its xterm color code
450 static string GetForeground (string s)
454 if (s.StartsWith ("bright")){
460 return "\x001b[" + highcode + (30 + NameToCode (s)).ToString () + "m";
463 static string GetBackground (string s)
465 return "\x001b[" + (40 + NameToCode (s)).ToString () + "m";
468 sealed class ErrorMessage : AbstractMessage
470 static string prefix, postfix;
472 [System.Runtime.InteropServices.DllImport ("libc", EntryPoint="isatty")]
473 extern static int _isatty (int fd);
475 static bool isatty (int fd)
478 return _isatty (fd) == 1;
484 static ErrorMessage ()
486 string term = Environment.GetEnvironmentVariable ("TERM");
487 bool xterm_colors = false;
493 if (Environment.GetEnvironmentVariable ("COLORTERM") != null){
505 if (!(isatty (1) && isatty (2)))
508 string config = Environment.GetEnvironmentVariable ("MCS_COLORS");
510 config = "errors=red";
511 //config = "brightwhite,red";
514 if (config == "disable")
517 if (!config.StartsWith ("errors="))
520 config = config.Substring (7);
522 int p = config.IndexOf (",");
524 prefix = GetForeground (config);
526 prefix = GetBackground (config.Substring (p+1)) + GetForeground (config.Substring (0, p));
527 postfix = "\x001b[0m";
530 public ErrorMessage (int code, Location loc, string message, ArrayList extraInfo)
531 : base (code, loc, message, extraInfo)
535 public ErrorMessage (AbstractMessage aMsg)
540 protected override string ColorFormat (string s)
543 return prefix + s + postfix;
547 public override void Print()
553 public override bool IsWarning {
554 get { return false; }
557 public override string MessageType {
564 public static void FeatureIsNotAvailable (Location loc, string feature)
567 switch (RootContext.Version) {
568 case LanguageVersion.ISO_1:
571 case LanguageVersion.ISO_2:
574 case LanguageVersion.Default_MCS:
575 Report.Error (1644, loc, "Feature `{0}' is not available in Mono mcs1 compiler. Consider using the `gmcs' compiler instead",
579 throw new InternalErrorException ("Invalid feature version", RootContext.Version);
582 Report.Error (1644, loc,
583 "Feature `{0}' cannot be used because it is not part of the C# {1} language specification",
587 public static string FriendlyStackTrace (Exception e)
589 return FriendlyStackTrace (new StackTrace (e, true));
592 static string FriendlyStackTrace (StackTrace t)
594 StringBuilder sb = new StringBuilder ();
596 bool foundUserCode = false;
598 for (int i = 0; i < t.FrameCount; i++) {
599 StackFrame f = t.GetFrame (i);
600 MethodBase mb = f.GetMethod ();
602 if (!foundUserCode && mb.ReflectedType == typeof (Report))
605 foundUserCode = true;
609 if (f.GetFileLineNumber () > 0)
610 sb.AppendFormat ("(at {0}:{1}) ", f.GetFileName (), f.GetFileLineNumber ());
612 sb.AppendFormat ("{0}.{1} (", mb.ReflectedType.Name, mb.Name);
615 foreach (ParameterInfo pi in mb.GetParameters ()) {
620 sb.Append (TypeManager.CSharpName (pi.ParameterType));
625 return sb.ToString ();
628 public static void StackTrace ()
630 Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
633 public static bool IsValidWarning (int code)
635 return Array.BinarySearch (AllWarnings, code) >= 0;
638 static public void RuntimeMissingSupport (Location loc, string feature)
640 Report.Error (-88, loc, "Your .NET Runtime does not support `{0}'. Please use the latest Mono runtime instead.", feature);
644 /// In most error cases is very useful to have information about symbol that caused the error.
645 /// Call this method before you call Report.Error when it makes sense.
647 static public void SymbolRelatedToPreviousError (Location loc, string symbol)
649 SymbolRelatedToPreviousError (loc.ToString (), symbol);
652 static public void SymbolRelatedToPreviousError (MemberInfo mi)
654 if (reporting_disabled)
657 Type dt = TypeManager.DropGenericTypeArguments (mi.DeclaringType);
658 if (TypeManager.IsDelegateType (dt)) {
659 SymbolRelatedToPreviousError (dt);
663 DeclSpace temp_ds = TypeManager.LookupDeclSpace (dt);
664 if (temp_ds == null) {
665 SymbolRelatedToPreviousError (dt.Assembly.Location, TypeManager.GetFullNameSignature (mi));
667 MethodBase mb = mi as MethodBase;
669 mb = TypeManager.DropGenericMethodArguments (mb);
670 IMethodData md = TypeManager.GetMethod (mb);
671 SymbolRelatedToPreviousError (md.Location, md.GetSignatureForError ());
675 MemberCore mc = temp_ds.GetDefinition (mi.Name);
676 SymbolRelatedToPreviousError (mc);
680 static public void SymbolRelatedToPreviousError (MemberCore mc)
682 SymbolRelatedToPreviousError (mc.Location, mc.GetSignatureForError ());
685 static public void SymbolRelatedToPreviousError (Type type)
687 if (reporting_disabled)
690 type = TypeManager.DropGenericTypeArguments (type);
692 if (TypeManager.IsGenericParameter (type)) {
693 TypeParameter tp = TypeManager.LookupTypeParameter (type);
695 SymbolRelatedToPreviousError (tp.Location, "");
700 if (type is TypeBuilder) {
701 DeclSpace temp_ds = TypeManager.LookupDeclSpace (type);
702 SymbolRelatedToPreviousError (temp_ds.Location, TypeManager.CSharpName (type));
703 } else if (TypeManager.HasElementType (type)) {
704 SymbolRelatedToPreviousError (type.GetElementType ());
706 SymbolRelatedToPreviousError (type.Assembly.Location, TypeManager.CSharpName (type));
710 static void SymbolRelatedToPreviousError (string loc, string symbol)
712 extra_information.Add (String.Format ("{0} (Location of the symbol related to previous ", loc));
715 public static void ExtraInformation (Location loc, string msg)
717 extra_information.Add (String.Format ("{0} {1}", loc, msg));
720 public static WarningRegions RegisterWarningRegion (Location location)
722 if (warning_regions_table == null)
723 warning_regions_table = new Hashtable ();
725 WarningRegions regions = (WarningRegions)warning_regions_table [location.Name];
726 if (regions == null) {
727 regions = new WarningRegions ();
728 warning_regions_table.Add (location.Name, regions);
733 static public void Warning (int code, int level, Location loc, string message)
735 WarningMessage w = new WarningMessage (code, level, loc, message, extra_information);
736 extra_information.Clear ();
740 static public void Warning (int code, int level, Location loc, string format, string arg)
742 WarningMessage w = new WarningMessage (code, level, loc, String.Format (format, arg), extra_information);
743 extra_information.Clear ();
747 static public void Warning (int code, int level, Location loc, string format, string arg1, string arg2)
749 WarningMessage w = new WarningMessage (code, level, loc, String.Format (format, arg1, arg2), extra_information);
750 extra_information.Clear ();
754 static public void Warning (int code, int level, Location loc, string format, params object[] args)
756 WarningMessage w = new WarningMessage (code, level, loc, String.Format (format, args), extra_information);
757 extra_information.Clear ();
761 static public void Warning (int code, int level, string message)
763 Warning (code, level, Location.Null, message);
766 static public void Warning (int code, int level, string format, string arg)
768 Warning (code, level, Location.Null, format, arg);
771 static public void Warning (int code, int level, string format, string arg1, string arg2)
773 Warning (code, level, Location.Null, format, arg1, arg2);
776 static public void Warning (int code, int level, string format, params string[] args)
778 Warning (code, level, Location.Null, String.Format (format, args));
781 static public void Error (int code, Location loc, string error)
783 new ErrorMessage (code, loc, error, extra_information).Print ();
784 extra_information.Clear ();
787 static public void Error (int code, Location loc, string format, string arg)
789 new ErrorMessage (code, loc, String.Format (format, arg), extra_information).Print ();
790 extra_information.Clear ();
793 static public void Error (int code, Location loc, string format, string arg1, string arg2)
795 new ErrorMessage (code, loc, String.Format (format, arg1, arg2), extra_information).Print ();
796 extra_information.Clear ();
799 static public void Error (int code, Location loc, string format, params object[] args)
801 Error (code, loc, String.Format (format, args));
804 static public void Error (int code, string error)
806 Error (code, Location.Null, error);
809 static public void Error (int code, string format, string arg)
811 Error (code, Location.Null, format, arg);
814 static public void Error (int code, string format, string arg1, string arg2)
816 Error (code, Location.Null, format, arg1, arg2);
819 static public void Error (int code, string format, params string[] args)
821 Error (code, Location.Null, String.Format (format, args));
824 static public void SetIgnoreWarning (int code)
826 if (warning_ignore_table == null)
827 warning_ignore_table = new Hashtable ();
829 warning_ignore_table [code] = true;
832 static public int ExpectedError {
834 expected_error = value;
837 return expected_error;
841 public static int WarningLevel {
843 return warning_level;
846 warning_level = value;
850 public static int DebugFlags = 0;
852 [Conditional ("MCS_DEBUG")]
853 static public void Debug (string message, params object[] args)
855 Debug (4, message, args);
858 [Conditional ("MCS_DEBUG")]
859 static public void Debug (int category, string message, params object[] args)
861 if ((category & DebugFlags) == 0)
864 StringBuilder sb = new StringBuilder (message);
866 if ((args != null) && (args.Length > 0)) {
870 foreach (object arg in args) {
877 else if (arg is ICollection)
878 sb.Append (PrintCollection ((ICollection) arg));
884 Console.WriteLine (sb.ToString ());
887 static public string PrintCollection (ICollection collection)
889 StringBuilder sb = new StringBuilder ();
891 sb.Append (collection.GetType ());
895 foreach (object o in collection) {
904 return sb.ToString ();
908 public enum TimerType {
918 public enum CounterType {
927 static DateTime[] timer_start;
928 static TimeSpan[] timers;
929 static long[] timer_counters;
930 static long[] counters;
934 timer_start = new DateTime [(int) TimerType.CountTimers];
935 timers = new TimeSpan [(int) TimerType.CountTimers];
936 timer_counters = new long [(int) TimerType.CountTimers];
937 counters = new long [(int) CounterType.CountCounters];
939 for (int i = 0; i < (int) TimerType.CountTimers; i++) {
940 timer_start [i] = DateTime.Now;
941 timers [i] = TimeSpan.Zero;
945 [Conditional("TIMER")]
946 static public void IncrementCounter (CounterType which)
948 ++counters [(int) which];
951 [Conditional("TIMER")]
952 static public void StartTimer (TimerType which)
954 timer_start [(int) which] = DateTime.Now;
957 [Conditional("TIMER")]
958 static public void StopTimer (TimerType which)
960 timers [(int) which] += DateTime.Now - timer_start [(int) which];
961 ++timer_counters [(int) which];
964 [Conditional("TIMER")]
965 static public void ShowTimers ()
967 ShowTimer (TimerType.FindMembers, "- FindMembers timer");
968 ShowTimer (TimerType.TcFindMembers, "- TypeContainer.FindMembers timer");
969 ShowTimer (TimerType.MemberLookup, "- MemberLookup timer");
970 ShowTimer (TimerType.CachedLookup, "- CachedLookup timer");
971 ShowTimer (TimerType.CacheInit, "- Cache init");
972 ShowTimer (TimerType.MiscTimer, "- Misc timer");
974 ShowCounter (CounterType.FindMembers, "- Find members");
975 ShowCounter (CounterType.MemberCache, "- Member cache");
976 ShowCounter (CounterType.MiscCounter, "- Misc counter");
979 static public void ShowCounter (CounterType which, string msg)
981 Console.WriteLine ("{0} {1}", counters [(int) which], msg);
984 static public void ShowTimer (TimerType which, string msg)
987 "[{0:00}:{1:000}] {2} (used {3} times)",
988 (int) timers [(int) which].TotalSeconds,
989 timers [(int) which].Milliseconds, msg,
990 timer_counters [(int) which]);
994 public class InternalErrorException : Exception {
995 public InternalErrorException (MemberCore mc, Exception e)
996 : base (mc.Location + " " + mc.GetSignatureForError (), e)
1000 public InternalErrorException ()
1001 : base ("Internal error")
1005 public InternalErrorException (string message)
1010 public InternalErrorException (string message, params object[] args)
1011 : base (String.Format (message, args))
1014 public InternalErrorException (Exception e, Location loc)
1015 : base (loc.ToString (), e)
1021 /// Handles #pragma warning
1023 public class WarningRegions {
1025 abstract class PragmaCmd
1029 protected PragmaCmd (int line)
1034 public abstract bool IsEnabled (int code, bool previous);
1037 class Disable : PragmaCmd
1040 public Disable (int line, int code)
1046 public override bool IsEnabled (int code, bool previous)
1048 return this.code == code ? false : previous;
1052 class DisableAll : PragmaCmd
1054 public DisableAll (int line)
1057 public override bool IsEnabled(int code, bool previous)
1063 class Enable : PragmaCmd
1066 public Enable (int line, int code)
1072 public override bool IsEnabled(int code, bool previous)
1074 return this.code == code ? true : previous;
1078 class EnableAll : PragmaCmd
1080 public EnableAll (int line)
1083 public override bool IsEnabled(int code, bool previous)
1090 ArrayList regions = new ArrayList ();
1092 public void WarningDisable (int line)
1094 regions.Add (new DisableAll (line));
1097 public void WarningDisable (Location location, int code)
1099 if (CheckWarningCode (code, location))
1100 regions.Add (new Disable (location.Row, code));
1103 public void WarningEnable (int line)
1105 regions.Add (new EnableAll (line));
1108 public void WarningEnable (Location location, int code)
1110 if (CheckWarningCode (code, location))
1111 regions.Add (new Enable (location.Row, code));
1114 public bool IsWarningEnabled (int code, int src_line)
1117 foreach (PragmaCmd pragma in regions) {
1118 if (src_line < pragma.Line)
1121 result = pragma.IsEnabled (code, result);
1126 static bool CheckWarningCode (int code, Location loc)
1128 if (Report.IsValidWarning (code))
1131 Report.Warning (1691, 1, loc, "`{0}' is not a valid warning number", code.ToString ());