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;
44 static ArrayList warnings_as_error;
45 static ArrayList warnings_only;
48 /// Whether to dump a stack trace on errors.
50 static public bool Stacktrace;
52 static public TextWriter Stderr = Console.Error;
55 // If the 'expected' error code is reported then the
56 // compilation succeeds.
58 // Used for the test suite to excercise the error codes
60 static int expected_error = 0;
63 // Keeps track of the warnings that we are ignoring
65 public static Hashtable warning_ignore_table;
67 static Hashtable warning_regions_table;
70 // This is used to save/restore the error state. When the
71 // error stack contains elements, warnings and errors are not
72 // reported to the user. This is used by the Lambda expression
73 // support to compile the code with various parameter values.
74 // A stack because of `Report.Errors == errors;'
76 static Stack error_stack;
77 static Stack warning_stack;
78 static bool reporting_disabled;
80 static int warning_level;
83 /// List of symbols related to reported error/warning. You have to fill it before error/warning is reported.
85 static ArrayList extra_information = new ArrayList ();
88 // IF YOU ADD A NEW WARNING YOU HAVE TO ADD ITS ID HERE
90 public static readonly int[] AllWarnings = new int[] {
92 105, 108, 109, 114, 162, 164, 168, 169, 183, 184, 197,
93 219, 251, 252, 253, 278, 282,
94 419, 420, 429, 436, 440, 465, 467, 469, 472,
95 612, 618, 626, 628, 642, 649, 652, 658, 659, 660, 661, 665, 672, 675,
98 1522, 1570, 1571, 1572, 1573, 1574, 1580, 1581, 1584, 1587, 1589, 1590, 1591, 1592,
99 1616, 1633, 1634, 1635, 1685, 1690, 1691, 1692,
103 3000, 3001, 3002, 3003, 3005, 3006, 3007, 3008, 3009,
104 3010, 3011, 3012, 3013, 3014, 3015, 3016, 3017, 3018, 3019,
105 3021, 3022, 3023, 3026, 3027,
107 414, // Non ISO-1 warnings
109 402, 458, 464, 693, 1058, 1700, 3024
115 // Just to be sure that binary search is working
116 Array.Sort (AllWarnings);
119 public static void Reset ()
121 Errors = Warnings = 0;
122 WarningsAreErrors = false;
123 warning_ignore_table = null;
124 warning_regions_table = null;
125 reporting_disabled = false;
126 error_stack = warning_stack = null;
127 warnings_as_error = null;
128 warnings_only = null;
131 public static void DisableReporting ()
133 if (error_stack == null)
134 error_stack = new Stack ();
135 error_stack.Push (Errors);
138 if (warning_stack == null)
139 warning_stack = new Stack ();
140 warning_stack.Push (Warnings);
143 reporting_disabled = true;
146 public static void EnableReporting ()
148 if (warning_stack != null && warning_stack.Count > 0)
149 Warnings = (int) warning_stack.Pop ();
153 Errors = (int) error_stack.Pop ();
154 if (error_stack.Count == 0) {
155 reporting_disabled = false;
159 public static IMessageRecorder msg_recorder;
161 public static IMessageRecorder SetMessageRecorder (IMessageRecorder recorder)
163 IMessageRecorder previous = msg_recorder;
164 msg_recorder = recorder;
168 public interface IMessageRecorder
170 bool IsEmpty { get; }
172 void AddMessage (AbstractMessage msg);
173 bool PrintMessages ();
177 // Default message recorder, it uses two types of message groups.
178 // Common messages: messages reported in all sessions.
179 // Merged messages: union of all messages in all sessions.
181 public struct MessageRecorder : IMessageRecorder
183 ArrayList session_messages;
185 // A collection of exactly same messages reported in all sessions
187 ArrayList common_messages;
190 // A collection of unique messages reported in all sessions
192 ArrayList merged_messages;
194 public void EndSession ()
196 if (session_messages == null)
200 // Handles the first session
202 if (common_messages == null) {
203 common_messages = new ArrayList (session_messages);
204 merged_messages = session_messages;
205 session_messages = null;
210 // Store common messages if any
212 for (int i = 0; i < common_messages.Count; ++i) {
213 AbstractMessage cmsg = (AbstractMessage) common_messages [i];
214 bool common_msg_found = false;
215 foreach (AbstractMessage msg in session_messages) {
216 if (cmsg.Equals (msg)) {
217 common_msg_found = true;
222 if (!common_msg_found)
223 common_messages.RemoveAt (i);
227 // Merge session and previous messages
229 for (int i = 0; i < session_messages.Count; ++i) {
230 AbstractMessage msg = (AbstractMessage) session_messages [i];
231 bool msg_found = false;
232 for (int ii = 0; ii < merged_messages.Count; ++ii) {
233 if (msg.Equals (merged_messages [ii])) {
240 merged_messages.Add (msg);
244 public void AddMessage (AbstractMessage msg)
246 if (session_messages == null)
247 session_messages = new ArrayList ();
249 session_messages.Add (msg);
252 public bool IsEmpty {
254 return merged_messages == null && common_messages == null;
259 // Prints collected messages, common messages have a priority
261 public bool PrintMessages ()
263 ArrayList messages_to_print = merged_messages;
264 if (common_messages != null && common_messages.Count > 0) {
265 messages_to_print = common_messages;
268 if (messages_to_print == null)
271 foreach (AbstractMessage msg in messages_to_print)
278 public abstract class AbstractMessage
280 readonly string[] extra_info;
281 protected readonly int code;
282 protected readonly Location location;
283 readonly string message;
285 protected AbstractMessage (int code, Location loc, string msg, ArrayList extraInfo)
289 this.code = 8000 - code;
293 if (extraInfo.Count != 0) {
294 this.extra_info = (string[])extraInfo.ToArray (typeof (string));
298 protected AbstractMessage (AbstractMessage aMsg)
300 this.code = aMsg.code;
301 this.location = aMsg.location;
302 this.message = aMsg.message;
303 this.extra_info = aMsg.extra_info;
306 static void Check (int code)
308 if (code == expected_error) {
309 Environment.Exit (0);
313 public override bool Equals (object obj)
315 AbstractMessage msg = obj as AbstractMessage;
319 return code == msg.code && location.Equals (msg.location) && message == msg.message;
322 public override int GetHashCode ()
324 return code.GetHashCode ();
327 public abstract bool IsWarning { get; }
329 public abstract string MessageType { get; }
331 public virtual void Print ()
333 if (msg_recorder != null) {
335 // This line is useful when debugging messages recorder
337 // Console.WriteLine ("RECORDING: {0} {1} {2}", code, location, message);
338 msg_recorder.AddMessage (this);
342 if (reporting_disabled)
345 StringBuilder msg = new StringBuilder ();
346 if (!location.IsNull) {
347 msg.Append (location.ToString ());
350 msg.AppendFormat ("{0} CS{1:0000}: {2}", MessageType, code, message);
354 if (Stderr == Console.Error)
355 Stderr.WriteLine (ColorFormat (msg.ToString ()));
357 Stderr.WriteLine (msg.ToString ());
359 if (extra_info != null) {
360 foreach (string s in extra_info)
361 Stderr.WriteLine (s + MessageType + ")");
365 Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
367 if (Fatal && !IsWarning)
368 throw new Exception (message);
373 protected virtual string ColorFormat (string s)
379 sealed class WarningMessage : AbstractMessage
383 public WarningMessage (int code, int level, Location loc, string message, ArrayList extra_info)
384 : base (code, loc, message, extra_info)
389 public override bool IsWarning {
395 if (WarningLevel < Level)
398 if (warning_ignore_table != null) {
399 if (warning_ignore_table.Contains (code)) {
404 if (warning_regions_table == null || location.IsNull)
407 WarningRegions regions = (WarningRegions)warning_regions_table [location.Name];
411 return regions.IsWarningEnabled (code, location.Row);
414 bool IsErrorWarning {
416 bool is_error = WarningsAreErrors;
418 // Check specific list
419 if (warnings_as_error != null)
420 is_error |= warnings_as_error.Contains (code);
422 // Ignore excluded warnings
423 if (warnings_only != null && warnings_only.Contains (code))
430 public override void Print ()
435 if (IsErrorWarning) {
436 new ErrorMessage (this).Print ();
444 public override string MessageType {
451 static int NameToCode (string s)
476 // maps a color name to its xterm color code
478 static string GetForeground (string s)
482 if (s.StartsWith ("bright")){
488 return "\x001b[" + highcode + (30 + NameToCode (s)).ToString () + "m";
491 static string GetBackground (string s)
493 return "\x001b[" + (40 + NameToCode (s)).ToString () + "m";
496 sealed class ErrorMessage : AbstractMessage
498 static string prefix, postfix;
500 static ErrorMessage ()
502 string term = Environment.GetEnvironmentVariable ("TERM");
503 bool xterm_colors = false;
509 if (Environment.GetEnvironmentVariable ("COLORTERM") != null){
521 if (!(UnixUtils.isatty (1) && UnixUtils.isatty (2)))
524 string config = Environment.GetEnvironmentVariable ("MCS_COLORS");
526 config = "errors=red";
527 //config = "brightwhite,red";
530 if (config == "disable")
533 if (!config.StartsWith ("errors="))
536 config = config.Substring (7);
538 int p = config.IndexOf (",");
540 prefix = GetForeground (config);
542 prefix = GetBackground (config.Substring (p+1)) + GetForeground (config.Substring (0, p));
543 postfix = "\x001b[0m";
546 public ErrorMessage (int code, Location loc, string message, ArrayList extraInfo)
547 : base (code, loc, message, extraInfo)
551 public ErrorMessage (AbstractMessage aMsg)
556 protected override string ColorFormat (string s)
559 return prefix + s + postfix;
563 public override void Print()
569 public override bool IsWarning {
570 get { return false; }
573 public override string MessageType {
580 public static void FeatureIsNotAvailable (Location loc, string feature)
583 switch (RootContext.Version) {
584 case LanguageVersion.ISO_1:
587 case LanguageVersion.ISO_2:
590 case LanguageVersion.V_3:
594 throw new InternalErrorException ("Invalid feature version", RootContext.Version);
597 Report.Error (1644, loc,
598 "Feature `{0}' cannot be used because it is not part of the C# {1} language specification",
602 public static void FeatureIsNotSupported (Location loc, string feature)
604 Report.Error (1644, loc,
605 "Feature `{0}' is not supported in Mono mcs1 compiler. Consider using the `gmcs' compiler instead",
609 public static string FriendlyStackTrace (Exception e)
611 return FriendlyStackTrace (new StackTrace (e, true));
614 static string FriendlyStackTrace (StackTrace t)
616 StringBuilder sb = new StringBuilder ();
618 bool foundUserCode = false;
620 for (int i = 0; i < t.FrameCount; i++) {
621 StackFrame f = t.GetFrame (i);
622 MethodBase mb = f.GetMethod ();
624 if (!foundUserCode && mb.ReflectedType == typeof (Report))
627 foundUserCode = true;
631 if (f.GetFileLineNumber () > 0)
632 sb.AppendFormat ("(at {0}:{1}) ", f.GetFileName (), f.GetFileLineNumber ());
634 sb.AppendFormat ("{0}.{1} (", mb.ReflectedType.Name, mb.Name);
637 foreach (ParameterInfo pi in mb.GetParameters ()) {
642 sb.Append (TypeManager.CSharpName (pi.ParameterType));
647 return sb.ToString ();
650 public static void StackTrace ()
652 Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
655 static bool IsValidWarning (int code)
657 return Array.BinarySearch (AllWarnings, code) >= 0;
660 static public void RuntimeMissingSupport (Location loc, string feature)
662 Report.Error (-88, loc, "Your .NET Runtime does not support `{0}'. Please use the latest Mono runtime instead.", feature);
666 /// In most error cases is very useful to have information about symbol that caused the error.
667 /// Call this method before you call Report.Error when it makes sense.
669 static public void SymbolRelatedToPreviousError (Location loc, string symbol)
671 SymbolRelatedToPreviousError (loc.ToString (), symbol);
674 static public void SymbolRelatedToPreviousError (MemberInfo mi)
676 if (reporting_disabled)
679 Type dt = TypeManager.DropGenericTypeArguments (mi.DeclaringType);
680 if (TypeManager.IsDelegateType (dt)) {
681 SymbolRelatedToPreviousError (dt);
685 DeclSpace temp_ds = TypeManager.LookupDeclSpace (dt);
686 if (temp_ds == null) {
687 SymbolRelatedToPreviousError (dt.Assembly.Location, TypeManager.GetFullNameSignature (mi));
689 MethodBase mb = mi as MethodBase;
691 mb = TypeManager.DropGenericMethodArguments (mb);
692 IMethodData md = TypeManager.GetMethod (mb);
694 SymbolRelatedToPreviousError (md.Location, md.GetSignatureForError ());
699 // FIXME: Completely wrong, it has to use FindMembers
700 MemberCore mc = temp_ds.GetDefinition (mi.Name);
702 SymbolRelatedToPreviousError (mc);
706 static public void SymbolRelatedToPreviousError (MemberCore mc)
708 SymbolRelatedToPreviousError (mc.Location, mc.GetSignatureForError ());
711 static public void SymbolRelatedToPreviousError (Type type)
713 if (reporting_disabled)
716 type = TypeManager.DropGenericTypeArguments (type);
718 if (TypeManager.IsGenericParameter (type)) {
719 TypeParameter tp = TypeManager.LookupTypeParameter (type);
721 SymbolRelatedToPreviousError (tp.Location, "");
726 if (type is TypeBuilder) {
727 DeclSpace temp_ds = TypeManager.LookupDeclSpace (type);
728 SymbolRelatedToPreviousError (temp_ds.Location, TypeManager.CSharpName (type));
729 } else if (TypeManager.HasElementType (type)) {
730 SymbolRelatedToPreviousError (TypeManager.GetElementType (type));
732 SymbolRelatedToPreviousError (type.Assembly.Location, TypeManager.CSharpName (type));
736 static void SymbolRelatedToPreviousError (string loc, string symbol)
738 string msg = String.Format ("{0} (Location of the symbol related to previous ", loc);
739 if (extra_information.Contains (msg))
742 extra_information.Add (msg);
745 public static void AddWarningAsError (string warningId)
749 id = int.Parse (warningId);
754 if (!CheckWarningCode (id, warningId, Location.Null))
757 if (warnings_as_error == null)
758 warnings_as_error = new ArrayList ();
760 warnings_as_error.Add (id);
763 public static void RemoveWarningAsError (string warningId)
767 id = int.Parse (warningId);
772 if (!CheckWarningCode (id, warningId, Location.Null))
775 if (warnings_only == null)
776 warnings_only = new ArrayList ();
778 warnings_only.Add (id);
781 public static bool CheckWarningCode (int code, Location loc)
783 return CheckWarningCode (code, code.ToString (), loc);
786 public static bool CheckWarningCode (int code, string scode, Location loc)
788 if (IsValidWarning (code))
791 Report.Warning (1691, 1, loc, "`{0}' is not a valid warning number", scode);
795 public static void ExtraInformation (Location loc, string msg)
797 extra_information.Add (String.Format ("{0} {1}", loc, msg));
800 public static WarningRegions RegisterWarningRegion (Location location)
802 if (warning_regions_table == null)
803 warning_regions_table = new Hashtable ();
805 WarningRegions regions = (WarningRegions)warning_regions_table [location.Name];
806 if (regions == null) {
807 regions = new WarningRegions ();
808 warning_regions_table.Add (location.Name, regions);
813 static public void Warning (int code, int level, Location loc, string message)
815 WarningMessage w = new WarningMessage (code, level, loc, message, extra_information);
816 extra_information.Clear ();
820 static public void Warning (int code, int level, Location loc, string format, string arg)
822 WarningMessage w = new WarningMessage (code, level, loc, String.Format (format, arg), extra_information);
823 extra_information.Clear ();
827 static public void Warning (int code, int level, Location loc, string format, string arg1, string arg2)
829 WarningMessage w = new WarningMessage (code, level, loc, String.Format (format, arg1, arg2), extra_information);
830 extra_information.Clear ();
834 static public void Warning (int code, int level, Location loc, string format, params object[] args)
836 WarningMessage w = new WarningMessage (code, level, loc, String.Format (format, args), extra_information);
837 extra_information.Clear ();
841 static public void Warning (int code, int level, string message)
843 Warning (code, level, Location.Null, message);
846 static public void Warning (int code, int level, string format, string arg)
848 Warning (code, level, Location.Null, format, arg);
851 static public void Warning (int code, int level, string format, string arg1, string arg2)
853 Warning (code, level, Location.Null, format, arg1, arg2);
856 static public void Warning (int code, int level, string format, params string[] args)
858 Warning (code, level, Location.Null, String.Format (format, args));
861 static public void Error (int code, Location loc, string error)
863 new ErrorMessage (code, loc, error, extra_information).Print ();
864 extra_information.Clear ();
867 static public void Error (int code, Location loc, string format, string arg)
869 new ErrorMessage (code, loc, String.Format (format, arg), extra_information).Print ();
870 extra_information.Clear ();
873 static public void Error (int code, Location loc, string format, string arg1, string arg2)
875 new ErrorMessage (code, loc, String.Format (format, arg1, arg2), extra_information).Print ();
876 extra_information.Clear ();
879 static public void Error (int code, Location loc, string format, params object[] args)
881 Error (code, loc, String.Format (format, args));
884 static public void Error (int code, string error)
886 Error (code, Location.Null, error);
889 static public void Error (int code, string format, string arg)
891 Error (code, Location.Null, format, arg);
894 static public void Error (int code, string format, string arg1, string arg2)
896 Error (code, Location.Null, format, arg1, arg2);
899 static public void Error (int code, string format, params string[] args)
901 Error (code, Location.Null, String.Format (format, args));
904 static public void SetIgnoreWarning (int code)
906 if (warning_ignore_table == null)
907 warning_ignore_table = new Hashtable ();
909 warning_ignore_table [code] = true;
912 static public int ExpectedError {
914 expected_error = value;
917 return expected_error;
921 public static int WarningLevel {
923 return warning_level;
926 warning_level = value;
930 public static int DebugFlags = 0;
932 [Conditional ("MCS_DEBUG")]
933 static public void Debug (string message, params object[] args)
935 Debug (4, message, args);
938 [Conditional ("MCS_DEBUG")]
939 static public void Debug (int category, string message, params object[] args)
941 if ((category & DebugFlags) == 0)
944 StringBuilder sb = new StringBuilder (message);
946 if ((args != null) && (args.Length > 0)) {
950 foreach (object arg in args) {
957 else if (arg is ICollection)
958 sb.Append (PrintCollection ((ICollection) arg));
964 Console.WriteLine (sb.ToString ());
967 static public string PrintCollection (ICollection collection)
969 StringBuilder sb = new StringBuilder ();
971 sb.Append (collection.GetType ());
975 foreach (object o in collection) {
984 return sb.ToString ();
988 public enum TimerType {
998 public enum CounterType {
1007 static DateTime[] timer_start;
1008 static TimeSpan[] timers;
1009 static long[] timer_counters;
1010 static long[] counters;
1014 timer_start = new DateTime [(int) TimerType.CountTimers];
1015 timers = new TimeSpan [(int) TimerType.CountTimers];
1016 timer_counters = new long [(int) TimerType.CountTimers];
1017 counters = new long [(int) CounterType.CountCounters];
1019 for (int i = 0; i < (int) TimerType.CountTimers; i++) {
1020 timer_start [i] = DateTime.Now;
1021 timers [i] = TimeSpan.Zero;
1025 [Conditional("TIMER")]
1026 static public void IncrementCounter (CounterType which)
1028 ++counters [(int) which];
1031 [Conditional("TIMER")]
1032 static public void StartTimer (TimerType which)
1034 timer_start [(int) which] = DateTime.Now;
1037 [Conditional("TIMER")]
1038 static public void StopTimer (TimerType which)
1040 timers [(int) which] += DateTime.Now - timer_start [(int) which];
1041 ++timer_counters [(int) which];
1044 [Conditional("TIMER")]
1045 static public void ShowTimers ()
1047 ShowTimer (TimerType.FindMembers, "- FindMembers timer");
1048 ShowTimer (TimerType.TcFindMembers, "- TypeContainer.FindMembers timer");
1049 ShowTimer (TimerType.MemberLookup, "- MemberLookup timer");
1050 ShowTimer (TimerType.CachedLookup, "- CachedLookup timer");
1051 ShowTimer (TimerType.CacheInit, "- Cache init");
1052 ShowTimer (TimerType.MiscTimer, "- Misc timer");
1054 ShowCounter (CounterType.FindMembers, "- Find members");
1055 ShowCounter (CounterType.MemberCache, "- Member cache");
1056 ShowCounter (CounterType.MiscCounter, "- Misc counter");
1059 static public void ShowCounter (CounterType which, string msg)
1061 Console.WriteLine ("{0} {1}", counters [(int) which], msg);
1064 static public void ShowTimer (TimerType which, string msg)
1067 "[{0:00}:{1:000}] {2} (used {3} times)",
1068 (int) timers [(int) which].TotalSeconds,
1069 timers [(int) which].Milliseconds, msg,
1070 timer_counters [(int) which]);
1074 public class InternalErrorException : Exception {
1075 public InternalErrorException (MemberCore mc, Exception e)
1076 : base (mc.Location + " " + mc.GetSignatureForError (), e)
1080 public InternalErrorException ()
1081 : base ("Internal error")
1085 public InternalErrorException (string message)
1090 public InternalErrorException (string message, params object[] args)
1091 : base (String.Format (message, args))
1094 public InternalErrorException (Exception e, Location loc)
1095 : base (loc.ToString (), e)
1101 /// Handles #pragma warning
1103 public class WarningRegions {
1105 abstract class PragmaCmd
1109 protected PragmaCmd (int line)
1114 public abstract bool IsEnabled (int code, bool previous);
1117 class Disable : PragmaCmd
1120 public Disable (int line, int code)
1126 public override bool IsEnabled (int code, bool previous)
1128 return this.code == code ? false : previous;
1132 class DisableAll : PragmaCmd
1134 public DisableAll (int line)
1137 public override bool IsEnabled(int code, bool previous)
1143 class Enable : PragmaCmd
1146 public Enable (int line, int code)
1152 public override bool IsEnabled(int code, bool previous)
1154 return this.code == code ? true : previous;
1158 class EnableAll : PragmaCmd
1160 public EnableAll (int line)
1163 public override bool IsEnabled(int code, bool previous)
1170 ArrayList regions = new ArrayList ();
1172 public void WarningDisable (int line)
1174 regions.Add (new DisableAll (line));
1177 public void WarningDisable (Location location, int code)
1179 if (Report.CheckWarningCode (code, location))
1180 regions.Add (new Disable (location.Row, code));
1183 public void WarningEnable (int line)
1185 regions.Add (new EnableAll (line));
1188 public void WarningEnable (Location location, int code)
1190 if (Report.CheckWarningCode (code, location))
1191 regions.Add (new Enable (location.Row, code));
1194 public bool IsWarningEnabled (int code, int src_line)
1197 foreach (PragmaCmd pragma in regions) {
1198 if (src_line < pragma.Line)
1201 result = pragma.IsEnabled (code, result);