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 && warning_stack.Count > 0)
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
163 bool IsEmpty { get; }
165 void AddMessage (AbstractMessage msg);
166 bool PrintMessages ();
170 // Default message recorder, it uses two types of message groups.
171 // Common messages: messages reported in all sessions.
172 // Merged messages: union of all messages in all sessions.
174 public struct MessageRecorder : IMessageRecorder
176 ArrayList session_messages;
178 // A collection of exactly same messages reported in all sessions
180 ArrayList common_messages;
183 // A collection of unique messages reported in all sessions
185 ArrayList merged_messages;
187 public void EndSession ()
189 if (session_messages == null)
193 // Handles the first session
195 if (common_messages == null) {
196 common_messages = new ArrayList (session_messages);
197 merged_messages = session_messages;
198 session_messages = null;
203 // Store common messages if any
205 for (int i = 0; i < common_messages.Count; ++i) {
206 AbstractMessage cmsg = (AbstractMessage) common_messages [i];
207 bool common_msg_found = false;
208 foreach (AbstractMessage msg in session_messages) {
209 if (cmsg.Equals (msg)) {
210 common_msg_found = true;
215 if (!common_msg_found)
216 common_messages.RemoveAt (i);
220 // Merge session and previous messages
222 for (int i = 0; i < session_messages.Count; ++i) {
223 AbstractMessage msg = (AbstractMessage) session_messages [i];
224 bool msg_found = false;
225 for (int ii = 0; ii < merged_messages.Count; ++ii) {
226 if (msg.Equals (merged_messages [ii])) {
233 merged_messages.Add (msg);
237 public void AddMessage (AbstractMessage msg)
239 if (session_messages == null)
240 session_messages = new ArrayList ();
242 session_messages.Add (msg);
245 public bool IsEmpty {
247 return merged_messages == null && common_messages == null;
252 // Prints collected messages, common messages have a priority
254 public bool PrintMessages ()
256 ArrayList messages_to_print = merged_messages;
257 if (common_messages != null && common_messages.Count > 0) {
258 messages_to_print = common_messages;
261 if (messages_to_print == null)
264 foreach (AbstractMessage msg in messages_to_print)
271 public abstract class AbstractMessage
273 readonly string[] extra_info;
274 protected readonly int code;
275 protected readonly Location location;
276 readonly string message;
278 protected AbstractMessage (int code, Location loc, string msg, ArrayList extraInfo)
282 this.code = 8000 - code;
286 if (extraInfo.Count != 0) {
287 this.extra_info = (string[])extraInfo.ToArray (typeof (string));
291 protected AbstractMessage (AbstractMessage aMsg)
293 this.code = aMsg.code;
294 this.location = aMsg.location;
295 this.message = aMsg.message;
296 this.extra_info = aMsg.extra_info;
299 static void Check (int code)
301 if (code == expected_error) {
302 Environment.Exit (0);
306 public override bool Equals (object obj)
308 AbstractMessage msg = obj as AbstractMessage;
312 return code == msg.code && location.Equals (msg.location) && message == msg.message;
315 public override int GetHashCode ()
317 return code.GetHashCode ();
320 public abstract bool IsWarning { get; }
322 public abstract string MessageType { get; }
324 public virtual void Print ()
326 if (msg_recorder != null) {
328 // This line is useful when debugging messages recorder
330 // Console.WriteLine ("RECORDING: {0} {1} {2}", code, location, message);
331 msg_recorder.AddMessage (this);
335 if (reporting_disabled)
338 StringBuilder msg = new StringBuilder ();
339 if (!location.IsNull) {
340 msg.Append (location.ToString ());
343 msg.AppendFormat ("{0} CS{1:0000}: {2}", MessageType, code, message);
347 if (Stderr == Console.Error)
348 Stderr.WriteLine (ColorFormat (msg.ToString ()));
350 Stderr.WriteLine (msg.ToString ());
352 if (extra_info != null) {
353 foreach (string s in extra_info)
354 Stderr.WriteLine (s + MessageType + ")");
358 Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
361 if (!IsWarning || WarningsAreErrors)
362 throw new Exception (message);
368 protected virtual string ColorFormat (string s)
374 sealed class WarningMessage : AbstractMessage
378 public WarningMessage (int code, int level, Location loc, string message, ArrayList extra_info)
379 : base (code, loc, message, extra_info)
384 public override bool IsWarning {
390 if (WarningLevel < Level)
393 if (warning_ignore_table != null) {
394 if (warning_ignore_table.Contains (code)) {
399 if (warning_regions_table == null || location.IsNull)
402 WarningRegions regions = (WarningRegions)warning_regions_table [location.Name];
406 return regions.IsWarningEnabled (code, location.Row);
409 public override void Print ()
414 if (WarningsAreErrors) {
415 new ErrorMessage (this).Print ();
423 public override string MessageType {
430 static int NameToCode (string s)
455 // maps a color name to its xterm color code
457 static string GetForeground (string s)
461 if (s.StartsWith ("bright")){
467 return "\x001b[" + highcode + (30 + NameToCode (s)).ToString () + "m";
470 static string GetBackground (string s)
472 return "\x001b[" + (40 + NameToCode (s)).ToString () + "m";
475 sealed class ErrorMessage : AbstractMessage
477 static string prefix, postfix;
479 [System.Runtime.InteropServices.DllImport ("libc", EntryPoint="isatty")]
480 extern static int _isatty (int fd);
482 static bool isatty (int fd)
485 return _isatty (fd) == 1;
491 static ErrorMessage ()
493 string term = Environment.GetEnvironmentVariable ("TERM");
494 bool xterm_colors = false;
500 if (Environment.GetEnvironmentVariable ("COLORTERM") != null){
512 if (!(isatty (1) && isatty (2)))
515 string config = Environment.GetEnvironmentVariable ("MCS_COLORS");
517 config = "errors=red";
518 //config = "brightwhite,red";
521 if (config == "disable")
524 if (!config.StartsWith ("errors="))
527 config = config.Substring (7);
529 int p = config.IndexOf (",");
531 prefix = GetForeground (config);
533 prefix = GetBackground (config.Substring (p+1)) + GetForeground (config.Substring (0, p));
534 postfix = "\x001b[0m";
537 public ErrorMessage (int code, Location loc, string message, ArrayList extraInfo)
538 : base (code, loc, message, extraInfo)
542 public ErrorMessage (AbstractMessage aMsg)
547 protected override string ColorFormat (string s)
550 return prefix + s + postfix;
554 public override void Print()
560 public override bool IsWarning {
561 get { return false; }
564 public override string MessageType {
571 public static void FeatureIsNotAvailable (Location loc, string feature)
574 switch (RootContext.Version) {
575 case LanguageVersion.ISO_1:
578 case LanguageVersion.ISO_2:
581 case LanguageVersion.Default_MCS:
582 Report.Error (1644, loc, "Feature `{0}' is not available in Mono mcs1 compiler. Consider using the `gmcs' compiler instead",
586 throw new InternalErrorException ("Invalid feature version", RootContext.Version);
589 Report.Error (1644, loc,
590 "Feature `{0}' cannot be used because it is not part of the C# {1} language specification",
594 public static string FriendlyStackTrace (Exception e)
596 return FriendlyStackTrace (new StackTrace (e, true));
599 static string FriendlyStackTrace (StackTrace t)
601 StringBuilder sb = new StringBuilder ();
603 bool foundUserCode = false;
605 for (int i = 0; i < t.FrameCount; i++) {
606 StackFrame f = t.GetFrame (i);
607 MethodBase mb = f.GetMethod ();
609 if (!foundUserCode && mb.ReflectedType == typeof (Report))
612 foundUserCode = true;
616 if (f.GetFileLineNumber () > 0)
617 sb.AppendFormat ("(at {0}:{1}) ", f.GetFileName (), f.GetFileLineNumber ());
619 sb.AppendFormat ("{0}.{1} (", mb.ReflectedType.Name, mb.Name);
622 foreach (ParameterInfo pi in mb.GetParameters ()) {
627 sb.Append (TypeManager.CSharpName (pi.ParameterType));
632 return sb.ToString ();
635 public static void StackTrace ()
637 Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
640 public static bool IsValidWarning (int code)
642 return Array.BinarySearch (AllWarnings, code) >= 0;
645 static public void RuntimeMissingSupport (Location loc, string feature)
647 Report.Error (-88, loc, "Your .NET Runtime does not support `{0}'. Please use the latest Mono runtime instead.", feature);
651 /// In most error cases is very useful to have information about symbol that caused the error.
652 /// Call this method before you call Report.Error when it makes sense.
654 static public void SymbolRelatedToPreviousError (Location loc, string symbol)
656 SymbolRelatedToPreviousError (loc.ToString (), symbol);
659 static public void SymbolRelatedToPreviousError (MemberInfo mi)
661 if (reporting_disabled)
664 Type dt = TypeManager.DropGenericTypeArguments (mi.DeclaringType);
665 if (TypeManager.IsDelegateType (dt)) {
666 SymbolRelatedToPreviousError (dt);
670 DeclSpace temp_ds = TypeManager.LookupDeclSpace (dt);
671 if (temp_ds == null) {
672 SymbolRelatedToPreviousError (dt.Assembly.Location, TypeManager.GetFullNameSignature (mi));
674 MethodBase mb = mi as MethodBase;
676 mb = TypeManager.DropGenericMethodArguments (mb);
677 IMethodData md = TypeManager.GetMethod (mb);
678 SymbolRelatedToPreviousError (md.Location, md.GetSignatureForError ());
682 MemberCore mc = temp_ds.GetDefinition (mi.Name);
683 SymbolRelatedToPreviousError (mc);
687 static public void SymbolRelatedToPreviousError (MemberCore mc)
689 SymbolRelatedToPreviousError (mc.Location, mc.GetSignatureForError ());
692 static public void SymbolRelatedToPreviousError (Type type)
694 if (reporting_disabled)
697 type = TypeManager.DropGenericTypeArguments (type);
699 if (TypeManager.IsGenericParameter (type)) {
700 TypeParameter tp = TypeManager.LookupTypeParameter (type);
702 SymbolRelatedToPreviousError (tp.Location, "");
707 if (type is TypeBuilder) {
708 DeclSpace temp_ds = TypeManager.LookupDeclSpace (type);
709 SymbolRelatedToPreviousError (temp_ds.Location, TypeManager.CSharpName (type));
710 } else if (TypeManager.HasElementType (type)) {
711 SymbolRelatedToPreviousError (type.GetElementType ());
713 SymbolRelatedToPreviousError (type.Assembly.Location, TypeManager.CSharpName (type));
717 static void SymbolRelatedToPreviousError (string loc, string symbol)
719 extra_information.Add (String.Format ("{0} (Location of the symbol related to previous ", loc));
722 public static void ExtraInformation (Location loc, string msg)
724 extra_information.Add (String.Format ("{0} {1}", loc, msg));
727 public static WarningRegions RegisterWarningRegion (Location location)
729 if (warning_regions_table == null)
730 warning_regions_table = new Hashtable ();
732 WarningRegions regions = (WarningRegions)warning_regions_table [location.Name];
733 if (regions == null) {
734 regions = new WarningRegions ();
735 warning_regions_table.Add (location.Name, regions);
740 static public void Warning (int code, int level, Location loc, string message)
742 WarningMessage w = new WarningMessage (code, level, loc, message, extra_information);
743 extra_information.Clear ();
747 static public void Warning (int code, int level, Location loc, string format, string arg)
749 WarningMessage w = new WarningMessage (code, level, loc, String.Format (format, arg), extra_information);
750 extra_information.Clear ();
754 static public void Warning (int code, int level, Location loc, string format, string arg1, string arg2)
756 WarningMessage w = new WarningMessage (code, level, loc, String.Format (format, arg1, arg2), extra_information);
757 extra_information.Clear ();
761 static public void Warning (int code, int level, Location loc, string format, params object[] args)
763 WarningMessage w = new WarningMessage (code, level, loc, String.Format (format, args), extra_information);
764 extra_information.Clear ();
768 static public void Warning (int code, int level, string message)
770 Warning (code, level, Location.Null, message);
773 static public void Warning (int code, int level, string format, string arg)
775 Warning (code, level, Location.Null, format, arg);
778 static public void Warning (int code, int level, string format, string arg1, string arg2)
780 Warning (code, level, Location.Null, format, arg1, arg2);
783 static public void Warning (int code, int level, string format, params string[] args)
785 Warning (code, level, Location.Null, String.Format (format, args));
788 static public void Error (int code, Location loc, string error)
790 new ErrorMessage (code, loc, error, extra_information).Print ();
791 extra_information.Clear ();
794 static public void Error (int code, Location loc, string format, string arg)
796 new ErrorMessage (code, loc, String.Format (format, arg), extra_information).Print ();
797 extra_information.Clear ();
800 static public void Error (int code, Location loc, string format, string arg1, string arg2)
802 new ErrorMessage (code, loc, String.Format (format, arg1, arg2), extra_information).Print ();
803 extra_information.Clear ();
806 static public void Error (int code, Location loc, string format, params object[] args)
808 Error (code, loc, String.Format (format, args));
811 static public void Error (int code, string error)
813 Error (code, Location.Null, error);
816 static public void Error (int code, string format, string arg)
818 Error (code, Location.Null, format, arg);
821 static public void Error (int code, string format, string arg1, string arg2)
823 Error (code, Location.Null, format, arg1, arg2);
826 static public void Error (int code, string format, params string[] args)
828 Error (code, Location.Null, String.Format (format, args));
831 static public void SetIgnoreWarning (int code)
833 if (warning_ignore_table == null)
834 warning_ignore_table = new Hashtable ();
836 warning_ignore_table [code] = true;
839 static public int ExpectedError {
841 expected_error = value;
844 return expected_error;
848 public static int WarningLevel {
850 return warning_level;
853 warning_level = value;
857 public static int DebugFlags = 0;
859 [Conditional ("MCS_DEBUG")]
860 static public void Debug (string message, params object[] args)
862 Debug (4, message, args);
865 [Conditional ("MCS_DEBUG")]
866 static public void Debug (int category, string message, params object[] args)
868 if ((category & DebugFlags) == 0)
871 StringBuilder sb = new StringBuilder (message);
873 if ((args != null) && (args.Length > 0)) {
877 foreach (object arg in args) {
884 else if (arg is ICollection)
885 sb.Append (PrintCollection ((ICollection) arg));
891 Console.WriteLine (sb.ToString ());
894 static public string PrintCollection (ICollection collection)
896 StringBuilder sb = new StringBuilder ();
898 sb.Append (collection.GetType ());
902 foreach (object o in collection) {
911 return sb.ToString ();
915 public enum TimerType {
925 public enum CounterType {
934 static DateTime[] timer_start;
935 static TimeSpan[] timers;
936 static long[] timer_counters;
937 static long[] counters;
941 timer_start = new DateTime [(int) TimerType.CountTimers];
942 timers = new TimeSpan [(int) TimerType.CountTimers];
943 timer_counters = new long [(int) TimerType.CountTimers];
944 counters = new long [(int) CounterType.CountCounters];
946 for (int i = 0; i < (int) TimerType.CountTimers; i++) {
947 timer_start [i] = DateTime.Now;
948 timers [i] = TimeSpan.Zero;
952 [Conditional("TIMER")]
953 static public void IncrementCounter (CounterType which)
955 ++counters [(int) which];
958 [Conditional("TIMER")]
959 static public void StartTimer (TimerType which)
961 timer_start [(int) which] = DateTime.Now;
964 [Conditional("TIMER")]
965 static public void StopTimer (TimerType which)
967 timers [(int) which] += DateTime.Now - timer_start [(int) which];
968 ++timer_counters [(int) which];
971 [Conditional("TIMER")]
972 static public void ShowTimers ()
974 ShowTimer (TimerType.FindMembers, "- FindMembers timer");
975 ShowTimer (TimerType.TcFindMembers, "- TypeContainer.FindMembers timer");
976 ShowTimer (TimerType.MemberLookup, "- MemberLookup timer");
977 ShowTimer (TimerType.CachedLookup, "- CachedLookup timer");
978 ShowTimer (TimerType.CacheInit, "- Cache init");
979 ShowTimer (TimerType.MiscTimer, "- Misc timer");
981 ShowCounter (CounterType.FindMembers, "- Find members");
982 ShowCounter (CounterType.MemberCache, "- Member cache");
983 ShowCounter (CounterType.MiscCounter, "- Misc counter");
986 static public void ShowCounter (CounterType which, string msg)
988 Console.WriteLine ("{0} {1}", counters [(int) which], msg);
991 static public void ShowTimer (TimerType which, string msg)
994 "[{0:00}:{1:000}] {2} (used {3} times)",
995 (int) timers [(int) which].TotalSeconds,
996 timers [(int) which].Milliseconds, msg,
997 timer_counters [(int) which]);
1001 public class InternalErrorException : Exception {
1002 public InternalErrorException (MemberCore mc, Exception e)
1003 : base (mc.Location + " " + mc.GetSignatureForError (), e)
1007 public InternalErrorException ()
1008 : base ("Internal error")
1012 public InternalErrorException (string message)
1017 public InternalErrorException (string message, params object[] args)
1018 : base (String.Format (message, args))
1021 public InternalErrorException (Exception e, Location loc)
1022 : base (loc.ToString (), e)
1028 /// Handles #pragma warning
1030 public class WarningRegions {
1032 abstract class PragmaCmd
1036 protected PragmaCmd (int line)
1041 public abstract bool IsEnabled (int code, bool previous);
1044 class Disable : PragmaCmd
1047 public Disable (int line, int code)
1053 public override bool IsEnabled (int code, bool previous)
1055 return this.code == code ? false : previous;
1059 class DisableAll : PragmaCmd
1061 public DisableAll (int line)
1064 public override bool IsEnabled(int code, bool previous)
1070 class Enable : PragmaCmd
1073 public Enable (int line, int code)
1079 public override bool IsEnabled(int code, bool previous)
1081 return this.code == code ? true : previous;
1085 class EnableAll : PragmaCmd
1087 public EnableAll (int line)
1090 public override bool IsEnabled(int code, bool previous)
1097 ArrayList regions = new ArrayList ();
1099 public void WarningDisable (int line)
1101 regions.Add (new DisableAll (line));
1104 public void WarningDisable (Location location, int code)
1106 if (CheckWarningCode (code, location))
1107 regions.Add (new Disable (location.Row, code));
1110 public void WarningEnable (int line)
1112 regions.Add (new EnableAll (line));
1115 public void WarningEnable (Location location, int code)
1117 if (CheckWarningCode (code, location))
1118 regions.Add (new Enable (location.Row, code));
1121 public bool IsWarningEnabled (int code, int src_line)
1124 foreach (PragmaCmd pragma in regions) {
1125 if (src_line < pragma.Line)
1128 result = pragma.IsEnabled (code, result);
1133 static bool CheckWarningCode (int code, Location loc)
1135 if (Report.IsValidWarning (code))
1138 Report.Warning (1691, 1, loc, "`{0}' is not a valid warning number", code.ToString ());