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;
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);
337 if (Stderr == Console.Error)
338 Stderr.WriteLine (ColorFormat (msg.ToString ()));
340 Stderr.WriteLine (msg.ToString ());
342 if (extra_info != null) {
343 foreach (string s in extra_info)
344 Stderr.WriteLine (s + MessageType + ")");
348 Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
351 if (!IsWarning || WarningsAreErrors)
352 throw new Exception (message);
358 public virtual string ColorFormat (string s)
364 sealed class WarningMessage : AbstractMessage
368 public WarningMessage (int code, int level, Location loc, string message, ArrayList extra_info)
369 : base (code, loc, message, extra_info)
374 public override bool IsWarning {
380 if (WarningLevel < Level)
383 if (warning_ignore_table != null) {
384 if (warning_ignore_table.Contains (code)) {
389 if (warning_regions_table == null || location.IsNull)
392 WarningRegions regions = (WarningRegions)warning_regions_table [location.Name];
396 return regions.IsWarningEnabled (code, location.Row);
399 public override void Print ()
404 if (WarningsAreErrors) {
405 new ErrorMessage (this).Print ();
413 public override string MessageType {
420 static int NameToCode (string s)
445 // maps a color name to its xterm color code
447 static string GetForeground (string s)
451 if (s.StartsWith ("bright")){
457 return "\x001b[" + highcode + (30 + NameToCode (s)).ToString () + "m";
460 static string GetBackground (string s)
462 return "\x001b[" + (40 + NameToCode (s)).ToString () + "m";
465 sealed class ErrorMessage : AbstractMessage
467 static string prefix, postfix;
469 [System.Runtime.InteropServices.DllImport ("libc", EntryPoint="isatty")]
470 extern static int _isatty (int fd);
472 static bool isatty (int fd)
475 return _isatty (fd) == 1;
481 static ErrorMessage ()
483 string term = Environment.GetEnvironmentVariable ("TERM");
484 bool xterm_colors = false;
490 if (Environment.GetEnvironmentVariable ("COLORTERM") != null){
502 if (!(isatty (1) && isatty (2)))
505 string config = Environment.GetEnvironmentVariable ("MCS_COLORS");
507 config = "errors=red";
508 //config = "brightwhite,red";
511 if (config == "disable")
514 if (!config.StartsWith ("errors="))
517 config = config.Substring (7);
519 int p = config.IndexOf (",");
521 prefix = GetForeground (config);
523 prefix = GetBackground (config.Substring (p+1)) + GetForeground (config.Substring (0, p));
524 postfix = "\x001b[0m";
527 public ErrorMessage (int code, Location loc, string message, ArrayList extraInfo)
528 : base (code, loc, message, extraInfo)
532 public ErrorMessage (AbstractMessage aMsg)
537 public override string ColorFormat (string s)
540 return prefix + s + postfix;
544 public override void Print()
550 public override bool IsWarning {
551 get { return false; }
554 public override string MessageType {
561 public static void FeatureIsNotAvailable (Location loc, string feature)
564 switch (RootContext.Version) {
565 case LanguageVersion.ISO_1:
568 case LanguageVersion.ISO_2:
571 case LanguageVersion.Default_MCS:
572 Report.Error (1644, loc, "Feature `{0}' is not available in Mono mcs compiler. Consider using Mono gmcs compiler instead",
576 throw new InternalErrorException ("Invalid feature version", RootContext.Version);
579 Report.Error (1644, loc,
580 "Feature `{0}' cannot be used because it is not part of the C# {1} language specification",
584 public static string FriendlyStackTrace (Exception e)
586 return FriendlyStackTrace (new StackTrace (e, true));
589 static string FriendlyStackTrace (StackTrace t)
591 StringBuilder sb = new StringBuilder ();
593 bool foundUserCode = false;
595 for (int i = 0; i < t.FrameCount; i++) {
596 StackFrame f = t.GetFrame (i);
597 MethodBase mb = f.GetMethod ();
599 if (!foundUserCode && mb.ReflectedType == typeof (Report))
602 foundUserCode = true;
606 if (f.GetFileLineNumber () > 0)
607 sb.AppendFormat ("(at {0}:{1}) ", f.GetFileName (), f.GetFileLineNumber ());
609 sb.AppendFormat ("{0}.{1} (", mb.ReflectedType.Name, mb.Name);
612 foreach (ParameterInfo pi in mb.GetParameters ()) {
617 sb.Append (TypeManager.CSharpName (pi.ParameterType));
622 return sb.ToString ();
625 public static void StackTrace ()
627 Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
630 public static bool IsValidWarning (int code)
632 return Array.BinarySearch (AllWarnings, code) >= 0;
635 static public void RuntimeMissingSupport (Location loc, string feature)
637 Report.Error (-88, loc, "Your .NET Runtime does not support `{0}'. Please use the latest Mono runtime instead.", feature);
641 /// In most error cases is very useful to have information about symbol that caused the error.
642 /// Call this method before you call Report.Error when it makes sense.
644 static public void SymbolRelatedToPreviousError (Location loc, string symbol)
646 SymbolRelatedToPreviousError (loc.ToString (), symbol);
649 static public void SymbolRelatedToPreviousError (MemberInfo mi)
651 if (reporting_disabled)
654 Type dt = TypeManager.DropGenericTypeArguments (mi.DeclaringType);
655 if (TypeManager.IsDelegateType (dt)) {
656 SymbolRelatedToPreviousError (dt);
660 DeclSpace temp_ds = TypeManager.LookupDeclSpace (dt);
661 if (temp_ds == null) {
662 SymbolRelatedToPreviousError (dt.Assembly.Location, TypeManager.GetFullNameSignature (mi));
664 MethodBase mb = mi as MethodBase;
666 mb = TypeManager.DropGenericMethodArguments (mb);
667 IMethodData md = TypeManager.GetMethod (mb);
668 SymbolRelatedToPreviousError (md.Location, md.GetSignatureForError ());
672 MemberCore mc = temp_ds.GetDefinition (mi.Name);
673 SymbolRelatedToPreviousError (mc);
677 static public void SymbolRelatedToPreviousError (MemberCore mc)
679 SymbolRelatedToPreviousError (mc.Location, mc.GetSignatureForError ());
682 static public void SymbolRelatedToPreviousError (Type type)
684 if (reporting_disabled)
687 type = TypeManager.DropGenericTypeArguments (type);
689 if (TypeManager.IsGenericParameter (type)) {
690 TypeParameter tp = TypeManager.LookupTypeParameter (type);
692 SymbolRelatedToPreviousError (tp.Location, "");
697 if (type is TypeBuilder) {
698 DeclSpace temp_ds = TypeManager.LookupDeclSpace (type);
699 SymbolRelatedToPreviousError (temp_ds.Location, TypeManager.CSharpName (type));
700 } else if (type.HasElementType) {
701 SymbolRelatedToPreviousError (type.GetElementType ());
703 SymbolRelatedToPreviousError (type.Assembly.Location, TypeManager.CSharpName (type));
707 static void SymbolRelatedToPreviousError (string loc, string symbol)
709 extra_information.Add (String.Format ("{0} (Location of the symbol related to previous ", loc));
712 public static void ExtraInformation (Location loc, string msg)
714 extra_information.Add (String.Format ("{0} {1}", loc, msg));
717 public static WarningRegions RegisterWarningRegion (Location location)
719 if (warning_regions_table == null)
720 warning_regions_table = new Hashtable ();
722 WarningRegions regions = (WarningRegions)warning_regions_table [location.Name];
723 if (regions == null) {
724 regions = new WarningRegions ();
725 warning_regions_table.Add (location.Name, regions);
730 static public void Warning (int code, int level, Location loc, string message)
732 WarningMessage w = new WarningMessage (code, level, loc, message, extra_information);
733 extra_information.Clear ();
737 static public void Warning (int code, int level, Location loc, string format, string arg)
739 WarningMessage w = new WarningMessage (code, level, loc, String.Format (format, arg), extra_information);
740 extra_information.Clear ();
744 static public void Warning (int code, int level, Location loc, string format, string arg1, string arg2)
746 WarningMessage w = new WarningMessage (code, level, loc, String.Format (format, arg1, arg2), extra_information);
747 extra_information.Clear ();
751 static public void Warning (int code, int level, Location loc, string format, params object[] args)
753 WarningMessage w = new WarningMessage (code, level, loc, String.Format (format, args), extra_information);
754 extra_information.Clear ();
758 static public void Warning (int code, int level, string message)
760 Warning (code, level, Location.Null, message);
763 static public void Warning (int code, int level, string format, string arg)
765 Warning (code, level, Location.Null, format, arg);
768 static public void Warning (int code, int level, string format, string arg1, string arg2)
770 Warning (code, level, Location.Null, format, arg1, arg2);
773 static public void Warning (int code, int level, string format, params string[] args)
775 Warning (code, level, Location.Null, String.Format (format, args));
778 static public void Error (int code, Location loc, string error)
780 new ErrorMessage (code, loc, error, extra_information).Print ();
781 extra_information.Clear ();
784 static public void Error (int code, Location loc, string format, string arg)
786 new ErrorMessage (code, loc, String.Format (format, arg), extra_information).Print ();
787 extra_information.Clear ();
790 static public void Error (int code, Location loc, string format, string arg1, string arg2)
792 new ErrorMessage (code, loc, String.Format (format, arg1, arg2), extra_information).Print ();
793 extra_information.Clear ();
796 static public void Error (int code, Location loc, string format, params object[] args)
798 Error (code, loc, String.Format (format, args));
801 static public void Error (int code, string error)
803 Error (code, Location.Null, error);
806 static public void Error (int code, string format, string arg)
808 Error (code, Location.Null, format, arg);
811 static public void Error (int code, string format, string arg1, string arg2)
813 Error (code, Location.Null, format, arg1, arg2);
816 static public void Error (int code, string format, params string[] args)
818 Error (code, Location.Null, String.Format (format, args));
821 static public void SetIgnoreWarning (int code)
823 if (warning_ignore_table == null)
824 warning_ignore_table = new Hashtable ();
826 warning_ignore_table [code] = true;
829 static public int ExpectedError {
831 expected_error = value;
834 return expected_error;
838 public static int WarningLevel {
840 return warning_level;
843 warning_level = value;
847 public static int DebugFlags = 0;
849 [Conditional ("MCS_DEBUG")]
850 static public void Debug (string message, params object[] args)
852 Debug (4, message, args);
855 [Conditional ("MCS_DEBUG")]
856 static public void Debug (int category, string message, params object[] args)
858 if ((category & DebugFlags) == 0)
861 StringBuilder sb = new StringBuilder (message);
863 if ((args != null) && (args.Length > 0)) {
867 foreach (object arg in args) {
874 else if (arg is ICollection)
875 sb.Append (PrintCollection ((ICollection) arg));
881 Console.WriteLine (sb.ToString ());
884 static public string PrintCollection (ICollection collection)
886 StringBuilder sb = new StringBuilder ();
888 sb.Append (collection.GetType ());
892 foreach (object o in collection) {
901 return sb.ToString ();
905 public enum TimerType {
915 public enum CounterType {
924 static DateTime[] timer_start;
925 static TimeSpan[] timers;
926 static long[] timer_counters;
927 static long[] counters;
931 timer_start = new DateTime [(int) TimerType.CountTimers];
932 timers = new TimeSpan [(int) TimerType.CountTimers];
933 timer_counters = new long [(int) TimerType.CountTimers];
934 counters = new long [(int) CounterType.CountCounters];
936 for (int i = 0; i < (int) TimerType.CountTimers; i++) {
937 timer_start [i] = DateTime.Now;
938 timers [i] = TimeSpan.Zero;
942 [Conditional("TIMER")]
943 static public void IncrementCounter (CounterType which)
945 ++counters [(int) which];
948 [Conditional("TIMER")]
949 static public void StartTimer (TimerType which)
951 timer_start [(int) which] = DateTime.Now;
954 [Conditional("TIMER")]
955 static public void StopTimer (TimerType which)
957 timers [(int) which] += DateTime.Now - timer_start [(int) which];
958 ++timer_counters [(int) which];
961 [Conditional("TIMER")]
962 static public void ShowTimers ()
964 ShowTimer (TimerType.FindMembers, "- FindMembers timer");
965 ShowTimer (TimerType.TcFindMembers, "- TypeContainer.FindMembers timer");
966 ShowTimer (TimerType.MemberLookup, "- MemberLookup timer");
967 ShowTimer (TimerType.CachedLookup, "- CachedLookup timer");
968 ShowTimer (TimerType.CacheInit, "- Cache init");
969 ShowTimer (TimerType.MiscTimer, "- Misc timer");
971 ShowCounter (CounterType.FindMembers, "- Find members");
972 ShowCounter (CounterType.MemberCache, "- Member cache");
973 ShowCounter (CounterType.MiscCounter, "- Misc counter");
976 static public void ShowCounter (CounterType which, string msg)
978 Console.WriteLine ("{0} {1}", counters [(int) which], msg);
981 static public void ShowTimer (TimerType which, string msg)
984 "[{0:00}:{1:000}] {2} (used {3} times)",
985 (int) timers [(int) which].TotalSeconds,
986 timers [(int) which].Milliseconds, msg,
987 timer_counters [(int) which]);
991 public class InternalErrorException : Exception {
992 public InternalErrorException (MemberCore mc, Exception e)
993 : base (mc.Location + " " + mc.GetSignatureForError (), e)
997 public InternalErrorException ()
998 : base ("Internal error")
1002 public InternalErrorException (string message)
1007 public InternalErrorException (string message, params object[] args)
1008 : base (String.Format (message, args))
1011 public InternalErrorException (Exception e, Location loc)
1012 : base (loc.ToString (), e)
1018 /// Handles #pragma warning
1020 public class WarningRegions {
1022 abstract class PragmaCmd
1026 protected PragmaCmd (int line)
1031 public abstract bool IsEnabled (int code, bool previous);
1034 class Disable : PragmaCmd
1037 public Disable (int line, int code)
1043 public override bool IsEnabled (int code, bool previous)
1045 return this.code == code ? false : previous;
1049 class DisableAll : PragmaCmd
1051 public DisableAll (int line)
1054 public override bool IsEnabled(int code, bool previous)
1060 class Enable : PragmaCmd
1063 public Enable (int line, int code)
1069 public override bool IsEnabled(int code, bool previous)
1071 return this.code == code ? true : previous;
1075 class EnableAll : PragmaCmd
1077 public EnableAll (int line)
1080 public override bool IsEnabled(int code, bool previous)
1087 ArrayList regions = new ArrayList ();
1089 public void WarningDisable (int line)
1091 regions.Add (new DisableAll (line));
1094 public void WarningDisable (Location location, int code)
1096 if (CheckWarningCode (code, location))
1097 regions.Add (new Disable (location.Row, code));
1100 public void WarningEnable (int line)
1102 regions.Add (new EnableAll (line));
1105 public void WarningEnable (Location location, int code)
1107 if (CheckWarningCode (code, location))
1108 regions.Add (new Enable (location.Row, code));
1111 public bool IsWarningEnabled (int code, int src_line)
1114 foreach (PragmaCmd pragma in regions) {
1115 if (src_line < pragma.Line)
1118 result = pragma.IsEnabled (code, result);
1123 static bool CheckWarningCode (int code, Location loc)
1125 if (Report.IsValidWarning (code))
1128 Report.Warning (1691, 1, loc, "`{0}' is not a valid warning number", code.ToString ());