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 static ErrorMessage ()
471 string term = Environment.GetEnvironmentVariable ("TERM");
472 bool xterm_colors = false;
478 if (Environment.GetEnvironmentVariable ("COLORTERM") != null){
487 string config = Environment.GetEnvironmentVariable ("MCS_COLORS");
489 config = "errors=red";
490 //config = "brightwhite,red";
493 if (config == "disable")
496 if (!config.StartsWith ("errors="))
499 config = config.Substring (7);
504 int p = config.IndexOf (",");
506 prefix = GetForeground (config);
508 prefix = GetBackground (config.Substring (p+1)) + GetForeground (config.Substring (0, p));
509 postfix = "\x001b[0m";
512 public ErrorMessage (int code, Location loc, string message, ArrayList extraInfo)
513 : base (code, loc, message, extraInfo)
517 public ErrorMessage (AbstractMessage aMsg)
522 public override string ColorFormat (string s)
525 return prefix + s + postfix;
529 public override void Print()
535 public override bool IsWarning {
536 get { return false; }
539 public override string MessageType {
546 public static void FeatureIsNotAvailable (Location loc, string feature)
549 switch (RootContext.Version) {
550 case LanguageVersion.ISO_1:
553 case LanguageVersion.ISO_2:
556 case LanguageVersion.Default_MCS:
557 Report.Error (1644, loc, "Feature `{0}' is not available in Mono mcs compiler. Consider using Mono gmcs compiler instead",
561 throw new InternalErrorException ("Invalid feature version", RootContext.Version);
564 Report.Error (1644, loc,
565 "Feature `{0}' cannot be used because it is not part of the C# {1} language specification",
569 public static string FriendlyStackTrace (Exception e)
571 return FriendlyStackTrace (new StackTrace (e, true));
574 static string FriendlyStackTrace (StackTrace t)
576 StringBuilder sb = new StringBuilder ();
578 bool foundUserCode = false;
580 for (int i = 0; i < t.FrameCount; i++) {
581 StackFrame f = t.GetFrame (i);
582 MethodBase mb = f.GetMethod ();
584 if (!foundUserCode && mb.ReflectedType == typeof (Report))
587 foundUserCode = true;
591 if (f.GetFileLineNumber () > 0)
592 sb.AppendFormat ("(at {0}:{1}) ", f.GetFileName (), f.GetFileLineNumber ());
594 sb.AppendFormat ("{0}.{1} (", mb.ReflectedType.Name, mb.Name);
597 foreach (ParameterInfo pi in mb.GetParameters ()) {
602 sb.Append (TypeManager.CSharpName (pi.ParameterType));
607 return sb.ToString ();
610 public static void StackTrace ()
612 Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
615 public static bool IsValidWarning (int code)
617 return Array.BinarySearch (AllWarnings, code) >= 0;
620 static public void RuntimeMissingSupport (Location loc, string feature)
622 Report.Error (-88, loc, "Your .NET Runtime does not support `{0}'. Please use the latest Mono runtime instead.", feature);
626 /// In most error cases is very useful to have information about symbol that caused the error.
627 /// Call this method before you call Report.Error when it makes sense.
629 static public void SymbolRelatedToPreviousError (Location loc, string symbol)
631 SymbolRelatedToPreviousError (loc.ToString (), symbol);
634 static public void SymbolRelatedToPreviousError (MemberInfo mi)
636 if (reporting_disabled)
639 Type dt = TypeManager.DropGenericTypeArguments (mi.DeclaringType);
640 if (TypeManager.IsDelegateType (dt)) {
641 SymbolRelatedToPreviousError (dt);
645 DeclSpace temp_ds = TypeManager.LookupDeclSpace (dt);
646 if (temp_ds == null) {
647 SymbolRelatedToPreviousError (dt.Assembly.Location, TypeManager.GetFullNameSignature (mi));
649 MethodBase mb = mi as MethodBase;
651 mb = TypeManager.DropGenericMethodArguments (mb);
652 IMethodData md = TypeManager.GetMethod (mb);
653 SymbolRelatedToPreviousError (md.Location, md.GetSignatureForError ());
657 MemberCore mc = temp_ds.GetDefinition (mi.Name);
658 SymbolRelatedToPreviousError (mc);
662 static public void SymbolRelatedToPreviousError (MemberCore mc)
664 SymbolRelatedToPreviousError (mc.Location, mc.GetSignatureForError ());
667 static public void SymbolRelatedToPreviousError (Type type)
669 if (reporting_disabled)
672 type = TypeManager.DropGenericTypeArguments (type);
674 if (TypeManager.IsGenericParameter (type)) {
675 TypeParameter tp = TypeManager.LookupTypeParameter (type);
677 SymbolRelatedToPreviousError (tp.Location, "");
682 if (type is TypeBuilder) {
683 DeclSpace temp_ds = TypeManager.LookupDeclSpace (type);
684 SymbolRelatedToPreviousError (temp_ds.Location, TypeManager.CSharpName (type));
685 } else if (type.HasElementType) {
686 SymbolRelatedToPreviousError (type.GetElementType ());
688 SymbolRelatedToPreviousError (type.Assembly.Location, TypeManager.CSharpName (type));
692 static void SymbolRelatedToPreviousError (string loc, string symbol)
694 extra_information.Add (String.Format ("{0} (Location of the symbol related to previous ", loc));
697 public static void ExtraInformation (Location loc, string msg)
699 extra_information.Add (String.Format ("{0} {1}", loc, msg));
702 public static WarningRegions RegisterWarningRegion (Location location)
704 if (warning_regions_table == null)
705 warning_regions_table = new Hashtable ();
707 WarningRegions regions = (WarningRegions)warning_regions_table [location.Name];
708 if (regions == null) {
709 regions = new WarningRegions ();
710 warning_regions_table.Add (location.Name, regions);
715 static public void Warning (int code, int level, Location loc, string message)
717 WarningMessage w = new WarningMessage (code, level, loc, message, extra_information);
718 extra_information.Clear ();
722 static public void Warning (int code, int level, Location loc, string format, string arg)
724 WarningMessage w = new WarningMessage (code, level, loc, String.Format (format, arg), extra_information);
725 extra_information.Clear ();
729 static public void Warning (int code, int level, Location loc, string format, string arg1, string arg2)
731 WarningMessage w = new WarningMessage (code, level, loc, String.Format (format, arg1, arg2), extra_information);
732 extra_information.Clear ();
736 static public void Warning (int code, int level, Location loc, string format, params object[] args)
738 WarningMessage w = new WarningMessage (code, level, loc, String.Format (format, args), extra_information);
739 extra_information.Clear ();
743 static public void Warning (int code, int level, string message)
745 Warning (code, level, Location.Null, message);
748 static public void Warning (int code, int level, string format, string arg)
750 Warning (code, level, Location.Null, format, arg);
753 static public void Warning (int code, int level, string format, string arg1, string arg2)
755 Warning (code, level, Location.Null, format, arg1, arg2);
758 static public void Warning (int code, int level, string format, params string[] args)
760 Warning (code, level, Location.Null, String.Format (format, args));
763 static public void Error (int code, Location loc, string error)
765 new ErrorMessage (code, loc, error, extra_information).Print ();
766 extra_information.Clear ();
769 static public void Error (int code, Location loc, string format, string arg)
771 new ErrorMessage (code, loc, String.Format (format, arg), extra_information).Print ();
772 extra_information.Clear ();
775 static public void Error (int code, Location loc, string format, string arg1, string arg2)
777 new ErrorMessage (code, loc, String.Format (format, arg1, arg2), extra_information).Print ();
778 extra_information.Clear ();
781 static public void Error (int code, Location loc, string format, params object[] args)
783 Error (code, loc, String.Format (format, args));
786 static public void Error (int code, string error)
788 Error (code, Location.Null, error);
791 static public void Error (int code, string format, string arg)
793 Error (code, Location.Null, format, arg);
796 static public void Error (int code, string format, string arg1, string arg2)
798 Error (code, Location.Null, format, arg1, arg2);
801 static public void Error (int code, string format, params string[] args)
803 Error (code, Location.Null, String.Format (format, args));
806 static public void SetIgnoreWarning (int code)
808 if (warning_ignore_table == null)
809 warning_ignore_table = new Hashtable ();
811 warning_ignore_table [code] = true;
814 static public int ExpectedError {
816 expected_error = value;
819 return expected_error;
823 public static int WarningLevel {
825 return warning_level;
828 warning_level = value;
832 public static int DebugFlags = 0;
834 [Conditional ("MCS_DEBUG")]
835 static public void Debug (string message, params object[] args)
837 Debug (4, message, args);
840 [Conditional ("MCS_DEBUG")]
841 static public void Debug (int category, string message, params object[] args)
843 if ((category & DebugFlags) == 0)
846 StringBuilder sb = new StringBuilder (message);
848 if ((args != null) && (args.Length > 0)) {
852 foreach (object arg in args) {
859 else if (arg is ICollection)
860 sb.Append (PrintCollection ((ICollection) arg));
866 Console.WriteLine (sb.ToString ());
869 static public string PrintCollection (ICollection collection)
871 StringBuilder sb = new StringBuilder ();
873 sb.Append (collection.GetType ());
877 foreach (object o in collection) {
886 return sb.ToString ();
890 public enum TimerType {
900 public enum CounterType {
909 static DateTime[] timer_start;
910 static TimeSpan[] timers;
911 static long[] timer_counters;
912 static long[] counters;
916 timer_start = new DateTime [(int) TimerType.CountTimers];
917 timers = new TimeSpan [(int) TimerType.CountTimers];
918 timer_counters = new long [(int) TimerType.CountTimers];
919 counters = new long [(int) CounterType.CountCounters];
921 for (int i = 0; i < (int) TimerType.CountTimers; i++) {
922 timer_start [i] = DateTime.Now;
923 timers [i] = TimeSpan.Zero;
927 [Conditional("TIMER")]
928 static public void IncrementCounter (CounterType which)
930 ++counters [(int) which];
933 [Conditional("TIMER")]
934 static public void StartTimer (TimerType which)
936 timer_start [(int) which] = DateTime.Now;
939 [Conditional("TIMER")]
940 static public void StopTimer (TimerType which)
942 timers [(int) which] += DateTime.Now - timer_start [(int) which];
943 ++timer_counters [(int) which];
946 [Conditional("TIMER")]
947 static public void ShowTimers ()
949 ShowTimer (TimerType.FindMembers, "- FindMembers timer");
950 ShowTimer (TimerType.TcFindMembers, "- TypeContainer.FindMembers timer");
951 ShowTimer (TimerType.MemberLookup, "- MemberLookup timer");
952 ShowTimer (TimerType.CachedLookup, "- CachedLookup timer");
953 ShowTimer (TimerType.CacheInit, "- Cache init");
954 ShowTimer (TimerType.MiscTimer, "- Misc timer");
956 ShowCounter (CounterType.FindMembers, "- Find members");
957 ShowCounter (CounterType.MemberCache, "- Member cache");
958 ShowCounter (CounterType.MiscCounter, "- Misc counter");
961 static public void ShowCounter (CounterType which, string msg)
963 Console.WriteLine ("{0} {1}", counters [(int) which], msg);
966 static public void ShowTimer (TimerType which, string msg)
969 "[{0:00}:{1:000}] {2} (used {3} times)",
970 (int) timers [(int) which].TotalSeconds,
971 timers [(int) which].Milliseconds, msg,
972 timer_counters [(int) which]);
976 public class InternalErrorException : Exception {
977 public InternalErrorException (MemberCore mc, Exception e)
978 : base (mc.Location + " " + mc.GetSignatureForError (), e)
982 public InternalErrorException ()
983 : base ("Internal error")
987 public InternalErrorException (string message)
992 public InternalErrorException (string message, params object[] args)
993 : base (String.Format (message, args))
996 public InternalErrorException (Exception e, Location loc)
997 : base (loc.ToString (), e)
1003 /// Handles #pragma warning
1005 public class WarningRegions {
1007 abstract class PragmaCmd
1011 protected PragmaCmd (int line)
1016 public abstract bool IsEnabled (int code, bool previous);
1019 class Disable : PragmaCmd
1022 public Disable (int line, int code)
1028 public override bool IsEnabled (int code, bool previous)
1030 return this.code == code ? false : previous;
1034 class DisableAll : PragmaCmd
1036 public DisableAll (int line)
1039 public override bool IsEnabled(int code, bool previous)
1045 class Enable : PragmaCmd
1048 public Enable (int line, int code)
1054 public override bool IsEnabled(int code, bool previous)
1056 return this.code == code ? true : previous;
1060 class EnableAll : PragmaCmd
1062 public EnableAll (int line)
1065 public override bool IsEnabled(int code, bool previous)
1072 ArrayList regions = new ArrayList ();
1074 public void WarningDisable (int line)
1076 regions.Add (new DisableAll (line));
1079 public void WarningDisable (Location location, int code)
1081 if (CheckWarningCode (code, location))
1082 regions.Add (new Disable (location.Row, code));
1085 public void WarningEnable (int line)
1087 regions.Add (new EnableAll (line));
1090 public void WarningEnable (Location location, int code)
1092 if (CheckWarningCode (code, location))
1093 regions.Add (new Enable (location.Row, code));
1096 public bool IsWarningEnabled (int code, int src_line)
1099 foreach (PragmaCmd pragma in regions) {
1100 if (src_line < pragma.Line)
1103 result = pragma.IsEnabled (code, result);
1108 static bool CheckWarningCode (int code, Location loc)
1110 if (Report.IsValidWarning (code))
1113 Report.Warning (1691, 1, loc, "`{0}' is not a valid warning number", code.ToString ());