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, 458, 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 ();
144 Errors = (int) error_stack.Pop ();
145 if (error_stack.Count == 0) {
146 reporting_disabled = false;
150 public static IMessageRecorder msg_recorder;
152 public static IMessageRecorder SetMessageRecorder (IMessageRecorder recorder)
154 IMessageRecorder previous = msg_recorder;
155 msg_recorder = recorder;
159 public interface IMessageRecorder
162 void AddMessage (AbstractMessage msg);
163 bool PrintMessages ();
167 // Default message recorder, it uses two types of message groups.
168 // Common messages: messages reported in all sessions.
169 // Merged messages: union of all messages in all sessions.
171 public struct MessageRecorder : IMessageRecorder
173 ArrayList session_messages;
175 // A collection of exactly same messages reported in all sessions
177 ArrayList common_messages;
180 // A collection of unique messages reported in all sessions
182 ArrayList merged_messages;
184 public void EndSession ()
186 if (session_messages == null)
190 // Handles the first session
192 if (common_messages == null) {
193 common_messages = new ArrayList (session_messages);
194 merged_messages = session_messages;
195 session_messages = null;
200 // Store common messages if any
202 for (int i = 0; i < common_messages.Count; ++i) {
203 AbstractMessage cmsg = (AbstractMessage) common_messages [i];
204 bool common_msg_found = false;
205 foreach (AbstractMessage msg in session_messages) {
206 if (cmsg.Equals (msg)) {
207 common_msg_found = true;
212 if (!common_msg_found)
213 common_messages.RemoveAt (i);
217 // Merge session and previous messages
219 for (int i = 0; i < session_messages.Count; ++i) {
220 AbstractMessage msg = (AbstractMessage) session_messages [i];
221 bool msg_found = false;
222 for (int ii = 0; ii < merged_messages.Count; ++ii) {
223 if (msg.Equals (merged_messages [ii])) {
230 merged_messages.Add (msg);
234 public void AddMessage (AbstractMessage msg)
236 if (session_messages == null)
237 session_messages = new ArrayList ();
239 session_messages.Add (msg);
243 // Prints collected messages, common messages have a priority
245 public bool PrintMessages ()
247 ArrayList messages_to_print = merged_messages;
248 if (common_messages != null && common_messages.Count > 0) {
249 messages_to_print = common_messages;
252 if (messages_to_print == null)
255 foreach (AbstractMessage msg in messages_to_print)
262 public abstract class AbstractMessage
264 readonly string[] extra_info;
265 protected readonly int code;
266 protected readonly Location location;
267 readonly string message;
269 protected AbstractMessage (int code, Location loc, string msg, ArrayList extraInfo)
273 this.code = 8000 - code;
277 if (extraInfo.Count != 0) {
278 this.extra_info = (string[])extraInfo.ToArray (typeof (string));
282 protected AbstractMessage (AbstractMessage aMsg)
284 this.code = aMsg.code;
285 this.location = aMsg.location;
286 this.message = aMsg.message;
287 this.extra_info = aMsg.extra_info;
290 static void Check (int code)
292 if (code == expected_error) {
293 Environment.Exit (0);
297 public override bool Equals (object obj)
299 AbstractMessage msg = obj as AbstractMessage;
303 return code == msg.code && location.Equals (msg.location) && message == msg.message;
306 public override int GetHashCode ()
308 return code.GetHashCode ();
311 public abstract bool IsWarning { get; }
313 public abstract string MessageType { get; }
315 public virtual void Print ()
317 if (msg_recorder != null) {
319 // This line is useful when debugging messages recorder
321 // Console.WriteLine ("RECORDING: {0} {1} {2}", code, location, message);
322 msg_recorder.AddMessage (this);
326 if (reporting_disabled)
329 StringBuilder msg = new StringBuilder ();
330 if (!location.IsNull) {
331 msg.Append (location.ToString ());
334 msg.AppendFormat ("{0} CS{1:0000}: {2}", MessageType, code, message);
338 if (Stderr == Console.Error)
339 Stderr.WriteLine (ColorFormat (msg.ToString ()));
341 Stderr.WriteLine (msg.ToString ());
343 if (extra_info != null) {
344 foreach (string s in extra_info)
345 Stderr.WriteLine (s + MessageType + ")");
349 Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
352 if (!IsWarning || WarningsAreErrors)
353 throw new Exception (message);
359 public virtual string ColorFormat (string s)
365 sealed class WarningMessage : AbstractMessage
369 public WarningMessage (int code, int level, Location loc, string message, ArrayList extra_info)
370 : base (code, loc, message, extra_info)
375 public override bool IsWarning {
381 if (WarningLevel < Level)
384 if (warning_ignore_table != null) {
385 if (warning_ignore_table.Contains (code)) {
390 if (warning_regions_table == null || location.IsNull)
393 WarningRegions regions = (WarningRegions)warning_regions_table [location.Name];
397 return regions.IsWarningEnabled (code, location.Row);
400 public override void Print ()
405 if (WarningsAreErrors) {
406 new ErrorMessage (this).Print ();
414 public override string MessageType {
421 static int NameToCode (string s)
446 // maps a color name to its xterm color code
448 static string GetForeground (string s)
452 if (s.StartsWith ("bright")){
458 return "\x001b[" + highcode + (30 + NameToCode (s)).ToString () + "m";
461 static string GetBackground (string s)
463 return "\x001b[" + (40 + NameToCode (s)).ToString () + "m";
466 sealed class ErrorMessage : AbstractMessage
468 static string prefix, postfix;
470 [System.Runtime.InteropServices.DllImport ("libc", EntryPoint="isatty")]
471 extern static int _isatty (int fd);
473 static bool isatty (int fd)
476 return _isatty (fd) == 1;
482 static ErrorMessage ()
484 string term = Environment.GetEnvironmentVariable ("TERM");
485 bool xterm_colors = false;
491 if (Environment.GetEnvironmentVariable ("COLORTERM") != null){
503 if (!(isatty (1) && isatty (2)))
506 string config = Environment.GetEnvironmentVariable ("MCS_COLORS");
508 config = "errors=red";
509 //config = "brightwhite,red";
512 if (config == "disable")
515 if (!config.StartsWith ("errors="))
518 config = config.Substring (7);
520 int p = config.IndexOf (",");
522 prefix = GetForeground (config);
524 prefix = GetBackground (config.Substring (p+1)) + GetForeground (config.Substring (0, p));
525 postfix = "\x001b[0m";
528 public ErrorMessage (int code, Location loc, string message, ArrayList extraInfo)
529 : base (code, loc, message, extraInfo)
533 public ErrorMessage (AbstractMessage aMsg)
538 public override string ColorFormat (string s)
541 return prefix + s + postfix;
545 public override void Print()
551 public override bool IsWarning {
552 get { return false; }
555 public override string MessageType {
562 public static void FeatureIsNotAvailable (Location loc, string feature)
565 switch (RootContext.Version) {
566 case LanguageVersion.ISO_1:
569 case LanguageVersion.ISO_2:
572 case LanguageVersion.Default_MCS:
573 Report.Error (1644, loc, "Feature `{0}' is not available in Mono mcs compiler. Consider using Mono gmcs compiler instead",
577 throw new InternalErrorException ("Invalid feature version", RootContext.Version);
580 Report.Error (1644, loc,
581 "Feature `{0}' cannot be used because it is not part of the C# {1} language specification",
585 public static string FriendlyStackTrace (Exception e)
587 return FriendlyStackTrace (new StackTrace (e, true));
590 static string FriendlyStackTrace (StackTrace t)
592 StringBuilder sb = new StringBuilder ();
594 bool foundUserCode = false;
596 for (int i = 0; i < t.FrameCount; i++) {
597 StackFrame f = t.GetFrame (i);
598 MethodBase mb = f.GetMethod ();
600 if (!foundUserCode && mb.ReflectedType == typeof (Report))
603 foundUserCode = true;
607 if (f.GetFileLineNumber () > 0)
608 sb.AppendFormat ("(at {0}:{1}) ", f.GetFileName (), f.GetFileLineNumber ());
610 sb.AppendFormat ("{0}.{1} (", mb.ReflectedType.Name, mb.Name);
613 foreach (ParameterInfo pi in mb.GetParameters ()) {
618 sb.Append (TypeManager.CSharpName (pi.ParameterType));
623 return sb.ToString ();
626 public static void StackTrace ()
628 Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
631 public static bool IsValidWarning (int code)
633 return Array.BinarySearch (AllWarnings, code) >= 0;
636 static public void RuntimeMissingSupport (Location loc, string feature)
638 Report.Error (-88, loc, "Your .NET Runtime does not support `{0}'. Please use the latest Mono runtime instead.", feature);
642 /// In most error cases is very useful to have information about symbol that caused the error.
643 /// Call this method before you call Report.Error when it makes sense.
645 static public void SymbolRelatedToPreviousError (Location loc, string symbol)
647 SymbolRelatedToPreviousError (loc.ToString (), symbol);
650 static public void SymbolRelatedToPreviousError (MemberInfo mi)
652 if (reporting_disabled)
655 Type dt = TypeManager.DropGenericTypeArguments (mi.DeclaringType);
656 if (TypeManager.IsDelegateType (dt)) {
657 SymbolRelatedToPreviousError (dt);
661 DeclSpace temp_ds = TypeManager.LookupDeclSpace (dt);
662 if (temp_ds == null) {
663 SymbolRelatedToPreviousError (dt.Assembly.Location, TypeManager.GetFullNameSignature (mi));
665 MethodBase mb = mi as MethodBase;
667 mb = TypeManager.DropGenericMethodArguments (mb);
668 IMethodData md = TypeManager.GetMethod (mb);
669 SymbolRelatedToPreviousError (md.Location, md.GetSignatureForError ());
673 MemberCore mc = temp_ds.GetDefinition (mi.Name);
674 SymbolRelatedToPreviousError (mc);
678 static public void SymbolRelatedToPreviousError (MemberCore mc)
680 SymbolRelatedToPreviousError (mc.Location, mc.GetSignatureForError ());
683 static public void SymbolRelatedToPreviousError (Type type)
685 if (reporting_disabled)
688 type = TypeManager.DropGenericTypeArguments (type);
690 if (TypeManager.IsGenericParameter (type)) {
691 TypeParameter tp = TypeManager.LookupTypeParameter (type);
693 SymbolRelatedToPreviousError (tp.Location, "");
698 if (type is TypeBuilder) {
699 DeclSpace temp_ds = TypeManager.LookupDeclSpace (type);
700 SymbolRelatedToPreviousError (temp_ds.Location, TypeManager.CSharpName (type));
701 } else if (type.HasElementType) {
702 SymbolRelatedToPreviousError (type.GetElementType ());
704 SymbolRelatedToPreviousError (type.Assembly.Location, TypeManager.CSharpName (type));
708 static void SymbolRelatedToPreviousError (string loc, string symbol)
710 extra_information.Add (String.Format ("{0} (Location of the symbol related to previous ", loc));
713 public static void ExtraInformation (Location loc, string msg)
715 extra_information.Add (String.Format ("{0} {1}", loc, msg));
718 public static WarningRegions RegisterWarningRegion (Location location)
720 if (warning_regions_table == null)
721 warning_regions_table = new Hashtable ();
723 WarningRegions regions = (WarningRegions)warning_regions_table [location.Name];
724 if (regions == null) {
725 regions = new WarningRegions ();
726 warning_regions_table.Add (location.Name, regions);
731 static public void Warning (int code, int level, Location loc, string message)
733 WarningMessage w = new WarningMessage (code, level, loc, message, extra_information);
734 extra_information.Clear ();
738 static public void Warning (int code, int level, Location loc, string format, string arg)
740 WarningMessage w = new WarningMessage (code, level, loc, String.Format (format, arg), extra_information);
741 extra_information.Clear ();
745 static public void Warning (int code, int level, Location loc, string format, string arg1, string arg2)
747 WarningMessage w = new WarningMessage (code, level, loc, String.Format (format, arg1, arg2), extra_information);
748 extra_information.Clear ();
752 static public void Warning (int code, int level, Location loc, string format, params object[] args)
754 WarningMessage w = new WarningMessage (code, level, loc, String.Format (format, args), extra_information);
755 extra_information.Clear ();
759 static public void Warning (int code, int level, string message)
761 Warning (code, level, Location.Null, message);
764 static public void Warning (int code, int level, string format, string arg)
766 Warning (code, level, Location.Null, format, arg);
769 static public void Warning (int code, int level, string format, string arg1, string arg2)
771 Warning (code, level, Location.Null, format, arg1, arg2);
774 static public void Warning (int code, int level, string format, params string[] args)
776 Warning (code, level, Location.Null, String.Format (format, args));
779 static public void Error (int code, Location loc, string error)
781 new ErrorMessage (code, loc, error, extra_information).Print ();
782 extra_information.Clear ();
785 static public void Error (int code, Location loc, string format, string arg)
787 new ErrorMessage (code, loc, String.Format (format, arg), extra_information).Print ();
788 extra_information.Clear ();
791 static public void Error (int code, Location loc, string format, string arg1, string arg2)
793 new ErrorMessage (code, loc, String.Format (format, arg1, arg2), extra_information).Print ();
794 extra_information.Clear ();
797 static public void Error (int code, Location loc, string format, params object[] args)
799 Error (code, loc, String.Format (format, args));
802 static public void Error (int code, string error)
804 Error (code, Location.Null, error);
807 static public void Error (int code, string format, string arg)
809 Error (code, Location.Null, format, arg);
812 static public void Error (int code, string format, string arg1, string arg2)
814 Error (code, Location.Null, format, arg1, arg2);
817 static public void Error (int code, string format, params string[] args)
819 Error (code, Location.Null, String.Format (format, args));
822 static public void SetIgnoreWarning (int code)
824 if (warning_ignore_table == null)
825 warning_ignore_table = new Hashtable ();
827 warning_ignore_table [code] = true;
830 static public int ExpectedError {
832 expected_error = value;
835 return expected_error;
839 public static int WarningLevel {
841 return warning_level;
844 warning_level = value;
848 public static int DebugFlags = 0;
850 [Conditional ("MCS_DEBUG")]
851 static public void Debug (string message, params object[] args)
853 Debug (4, message, args);
856 [Conditional ("MCS_DEBUG")]
857 static public void Debug (int category, string message, params object[] args)
859 if ((category & DebugFlags) == 0)
862 StringBuilder sb = new StringBuilder (message);
864 if ((args != null) && (args.Length > 0)) {
868 foreach (object arg in args) {
875 else if (arg is ICollection)
876 sb.Append (PrintCollection ((ICollection) arg));
882 Console.WriteLine (sb.ToString ());
885 static public string PrintCollection (ICollection collection)
887 StringBuilder sb = new StringBuilder ();
889 sb.Append (collection.GetType ());
893 foreach (object o in collection) {
902 return sb.ToString ();
906 public enum TimerType {
916 public enum CounterType {
925 static DateTime[] timer_start;
926 static TimeSpan[] timers;
927 static long[] timer_counters;
928 static long[] counters;
932 timer_start = new DateTime [(int) TimerType.CountTimers];
933 timers = new TimeSpan [(int) TimerType.CountTimers];
934 timer_counters = new long [(int) TimerType.CountTimers];
935 counters = new long [(int) CounterType.CountCounters];
937 for (int i = 0; i < (int) TimerType.CountTimers; i++) {
938 timer_start [i] = DateTime.Now;
939 timers [i] = TimeSpan.Zero;
943 [Conditional("TIMER")]
944 static public void IncrementCounter (CounterType which)
946 ++counters [(int) which];
949 [Conditional("TIMER")]
950 static public void StartTimer (TimerType which)
952 timer_start [(int) which] = DateTime.Now;
955 [Conditional("TIMER")]
956 static public void StopTimer (TimerType which)
958 timers [(int) which] += DateTime.Now - timer_start [(int) which];
959 ++timer_counters [(int) which];
962 [Conditional("TIMER")]
963 static public void ShowTimers ()
965 ShowTimer (TimerType.FindMembers, "- FindMembers timer");
966 ShowTimer (TimerType.TcFindMembers, "- TypeContainer.FindMembers timer");
967 ShowTimer (TimerType.MemberLookup, "- MemberLookup timer");
968 ShowTimer (TimerType.CachedLookup, "- CachedLookup timer");
969 ShowTimer (TimerType.CacheInit, "- Cache init");
970 ShowTimer (TimerType.MiscTimer, "- Misc timer");
972 ShowCounter (CounterType.FindMembers, "- Find members");
973 ShowCounter (CounterType.MemberCache, "- Member cache");
974 ShowCounter (CounterType.MiscCounter, "- Misc counter");
977 static public void ShowCounter (CounterType which, string msg)
979 Console.WriteLine ("{0} {1}", counters [(int) which], msg);
982 static public void ShowTimer (TimerType which, string msg)
985 "[{0:00}:{1:000}] {2} (used {3} times)",
986 (int) timers [(int) which].TotalSeconds,
987 timers [(int) which].Milliseconds, msg,
988 timer_counters [(int) which]);
992 public class InternalErrorException : Exception {
993 public InternalErrorException (MemberCore mc, Exception e)
994 : base (mc.Location + " " + mc.GetSignatureForError (), e)
998 public InternalErrorException ()
999 : base ("Internal error")
1003 public InternalErrorException (string message)
1008 public InternalErrorException (string message, params object[] args)
1009 : base (String.Format (message, args))
1012 public InternalErrorException (Exception e, Location loc)
1013 : base (loc.ToString (), e)
1019 /// Handles #pragma warning
1021 public class WarningRegions {
1023 abstract class PragmaCmd
1027 protected PragmaCmd (int line)
1032 public abstract bool IsEnabled (int code, bool previous);
1035 class Disable : PragmaCmd
1038 public Disable (int line, int code)
1044 public override bool IsEnabled (int code, bool previous)
1046 return this.code == code ? false : previous;
1050 class DisableAll : PragmaCmd
1052 public DisableAll (int line)
1055 public override bool IsEnabled(int code, bool previous)
1061 class Enable : PragmaCmd
1064 public Enable (int line, int code)
1070 public override bool IsEnabled(int code, bool previous)
1072 return this.code == code ? true : previous;
1076 class EnableAll : PragmaCmd
1078 public EnableAll (int line)
1081 public override bool IsEnabled(int code, bool previous)
1088 ArrayList regions = new ArrayList ();
1090 public void WarningDisable (int line)
1092 regions.Add (new DisableAll (line));
1095 public void WarningDisable (Location location, int code)
1097 if (CheckWarningCode (code, location))
1098 regions.Add (new Disable (location.Row, code));
1101 public void WarningEnable (int line)
1103 regions.Add (new EnableAll (line));
1106 public void WarningEnable (Location location, int code)
1108 if (CheckWarningCode (code, location))
1109 regions.Add (new Enable (location.Row, code));
1112 public bool IsWarningEnabled (int code, int src_line)
1115 foreach (PragmaCmd pragma in regions) {
1116 if (src_line < pragma.Line)
1119 result = pragma.IsEnabled (code, result);
1124 static bool CheckWarningCode (int code, Location loc)
1126 if (Report.IsValidWarning (code))
1129 Report.Warning (1691, 1, loc, "`{0}' is not a valid warning number", code.ToString ());