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.Generic;
14 using System.Diagnostics;
15 using System.Reflection;
17 namespace Mono.CSharp {
20 // Errors and warnings manager
25 /// Whether warnings should be considered errors
27 public bool WarningsAreErrors;
28 List<int> warnings_as_error;
29 List<int> warnings_only;
31 public static int DebugFlags = 0;
33 public const int RuntimeErrorId = 10000;
36 // Keeps track of the warnings that we are ignoring
38 HashSet<int> warning_ignore_table;
40 Dictionary<int, WarningRegions> warning_regions_table;
44 ReportPrinter printer;
46 int reporting_disabled;
49 /// List of symbols related to reported error/warning. You have to fill it before error/warning is reported.
51 List<string> extra_information = new List<string> ();
54 // IF YOU ADD A NEW WARNING YOU HAVE TO ADD ITS ID HERE
56 public static readonly int[] AllWarnings = new int[] {
58 105, 108, 109, 114, 162, 164, 168, 169, 183, 184, 197,
59 219, 251, 252, 253, 278, 282,
60 402, 414, 419, 420, 429, 436, 440, 458, 464, 465, 467, 469, 472,
61 612, 618, 626, 628, 642, 649, 652, 658, 659, 660, 661, 665, 672, 675, 693,
65 1522, 1570, 1571, 1572, 1573, 1574, 1580, 1581, 1584, 1587, 1589, 1590, 1591, 1592,
66 1616, 1633, 1634, 1635, 1685, 1690, 1691, 1692, 1695, 1696, 1699,
67 1700, 1709, 1717, 1718, 1720,
70 3000, 3001, 3002, 3003, 3005, 3006, 3007, 3008, 3009,
71 3010, 3011, 3012, 3013, 3014, 3015, 3016, 3017, 3018, 3019,
72 3021, 3022, 3023, 3024, 3026, 3027
75 static HashSet<int> AllWarningsHashSet;
77 public Report (ReportPrinter printer)
80 throw new ArgumentNullException ("printer");
82 this.printer = printer;
86 public void DisableReporting ()
91 public void EnableReporting ()
96 public void FeatureIsNotAvailable (Location loc, string feature)
99 switch (RootContext.Version) {
100 case LanguageVersion.ISO_1:
103 case LanguageVersion.ISO_2:
106 case LanguageVersion.V_3:
110 throw new InternalErrorException ("Invalid feature version", RootContext.Version);
114 "Feature `{0}' cannot be used because it is not part of the C# {1} language specification",
118 public void FeatureIsNotSupported (Location loc, string feature)
121 "Feature `{0}' is not supported in Mono mcs1 compiler. Consider using the `gmcs' compiler instead",
125 bool IsWarningEnabled (int code, int level, Location loc)
127 if (WarningLevel < level)
130 if (IsWarningDisabledGlobally (code))
133 if (warning_regions_table == null || loc.IsNull)
136 WarningRegions regions;
137 if (!warning_regions_table.TryGetValue (loc.File, out regions))
140 return regions.IsWarningEnabled (code, loc.Row);
143 public bool IsWarningDisabledGlobally (int code)
145 return warning_ignore_table != null && warning_ignore_table.Contains (code);
148 bool IsWarningAsError (int code)
150 bool is_error = WarningsAreErrors;
152 // Check specific list
153 if (warnings_as_error != null)
154 is_error |= warnings_as_error.Contains (code);
156 // Ignore excluded warnings
157 if (warnings_only != null && warnings_only.Contains (code))
163 public void RuntimeMissingSupport (Location loc, string feature)
165 Error (-88, loc, "Your .NET Runtime does not support `{0}'. Please use the latest Mono runtime instead.", feature);
169 /// In most error cases is very useful to have information about symbol that caused the error.
170 /// Call this method before you call Report.Error when it makes sense.
172 public void SymbolRelatedToPreviousError (Location loc, string symbol)
174 SymbolRelatedToPreviousError (loc.ToString (), symbol);
177 public void SymbolRelatedToPreviousError (MemberSpec ms)
179 if (reporting_disabled > 0 || !printer.HasRelatedSymbolSupport)
182 var mc = ms.MemberDefinition as MemberCore;
183 while (ms is ElementTypeSpec) {
184 ms = ((ElementTypeSpec) ms).Element;
185 mc = ms.MemberDefinition as MemberCore;
189 SymbolRelatedToPreviousError (mc);
190 } else if (ms.MemberDefinition != null) {
191 SymbolRelatedToPreviousError (ms.MemberDefinition.Assembly.Location, "");
195 public void SymbolRelatedToPreviousError (MemberCore mc)
197 SymbolRelatedToPreviousError (mc.Location, mc.GetSignatureForError ());
200 void SymbolRelatedToPreviousError (string loc, string symbol)
202 string msg = String.Format ("{0} (Location of the symbol related to previous ", loc);
203 if (extra_information.Contains (msg))
206 extra_information.Add (msg);
209 public void AddWarningAsError (string warningId)
213 id = int.Parse (warningId);
215 CheckWarningCode (warningId, Location.Null);
219 if (!CheckWarningCode (id, Location.Null))
222 if (warnings_as_error == null)
223 warnings_as_error = new List<int> ();
225 warnings_as_error.Add (id);
228 public void RemoveWarningAsError (string warningId)
232 id = int.Parse (warningId);
234 CheckWarningCode (warningId, Location.Null);
238 if (!CheckWarningCode (id, Location.Null))
241 if (warnings_only == null)
242 warnings_only = new List<int> ();
244 warnings_only.Add (id);
247 public bool CheckWarningCode (string code, Location loc)
249 Warning (1691, 1, loc, "`{0}' is not a valid warning number", code);
253 public bool CheckWarningCode (int code, Location loc)
255 if (AllWarningsHashSet == null)
256 AllWarningsHashSet = new HashSet<int> (AllWarnings);
258 if (AllWarningsHashSet.Contains (code))
261 return CheckWarningCode (code.ToString (), loc);
264 public void ExtraInformation (Location loc, string msg)
266 extra_information.Add (String.Format ("{0} {1}", loc, msg));
269 public WarningRegions RegisterWarningRegion (Location location)
271 WarningRegions regions;
272 if (warning_regions_table == null) {
274 warning_regions_table = new Dictionary<int, WarningRegions> ();
276 warning_regions_table.TryGetValue (location.File, out regions);
279 if (regions == null) {
280 regions = new WarningRegions ();
281 warning_regions_table.Add (location.File, regions);
287 public void Warning (int code, int level, Location loc, string message)
289 if (reporting_disabled > 0)
292 if (!IsWarningEnabled (code, level, loc))
296 if (IsWarningAsError (code))
297 msg = new ErrorMessage (code, loc, message, extra_information);
299 msg = new WarningMessage (code, loc, message, extra_information);
301 extra_information.Clear ();
305 public void Warning (int code, int level, Location loc, string format, string arg)
307 Warning (code, level, loc, String.Format (format, arg));
310 public void Warning (int code, int level, Location loc, string format, string arg1, string arg2)
312 Warning (code, level, loc, String.Format (format, arg1, arg2));
315 public void Warning (int code, int level, Location loc, string format, params object[] args)
317 Warning (code, level, loc, String.Format (format, args));
320 public void Warning (int code, int level, string message)
322 Warning (code, level, Location.Null, message);
325 public void Warning (int code, int level, string format, string arg)
327 Warning (code, level, Location.Null, format, arg);
330 public void Warning (int code, int level, string format, string arg1, string arg2)
332 Warning (code, level, Location.Null, format, arg1, arg2);
335 public void Warning (int code, int level, string format, params string[] args)
337 Warning (code, level, Location.Null, String.Format (format, args));
341 // Warnings encountered so far
343 public int Warnings {
344 get { return printer.WarningsCount; }
347 public void Error (int code, Location loc, string error)
349 if (reporting_disabled > 0)
352 ErrorMessage msg = new ErrorMessage (code, loc, error, extra_information);
353 extra_information.Clear ();
358 public void Error (int code, Location loc, string format, string arg)
360 Error (code, loc, String.Format (format, arg));
363 public void Error (int code, Location loc, string format, string arg1, string arg2)
365 Error (code, loc, String.Format (format, arg1, arg2));
368 public void Error (int code, Location loc, string format, params string[] args)
370 Error (code, loc, String.Format (format, args));
373 public void Error (int code, string error)
375 Error (code, Location.Null, error);
378 public void Error (int code, string format, string arg)
380 Error (code, Location.Null, format, arg);
383 public void Error (int code, string format, string arg1, string arg2)
385 Error (code, Location.Null, format, arg1, arg2);
388 public void Error (int code, string format, params string[] args)
390 Error (code, Location.Null, String.Format (format, args));
394 // Errors encountered so far
397 get { return printer.ErrorsCount; }
400 public bool IsDisabled {
402 return reporting_disabled > 0;
406 public ReportPrinter Printer {
407 get { return printer; }
410 public void SetIgnoreWarning (int code)
412 if (warning_ignore_table == null)
413 warning_ignore_table = new HashSet<int> ();
415 warning_ignore_table.Add (code);
418 public ReportPrinter SetPrinter (ReportPrinter printer)
420 ReportPrinter old = this.printer;
421 this.printer = printer;
425 public int WarningLevel {
427 return warning_level;
430 warning_level = value;
434 [Conditional ("MCS_DEBUG")]
435 static public void Debug (string message, params object[] args)
437 Debug (4, message, args);
440 [Conditional ("MCS_DEBUG")]
441 static public void Debug (int category, string message, params object[] args)
443 if ((category & DebugFlags) == 0)
446 StringBuilder sb = new StringBuilder (message);
448 if ((args != null) && (args.Length > 0)) {
452 foreach (object arg in args) {
459 // else if (arg is ICollection)
460 // sb.Append (PrintCollection ((ICollection) arg));
466 Console.WriteLine (sb.ToString ());
469 static public string PrintCollection (ICollection collection)
471 StringBuilder sb = new StringBuilder ();
473 sb.Append (collection.GetType ());
477 foreach (object o in collection) {
486 return sb.ToString ();
491 public abstract class AbstractMessage
493 readonly string[] extra_info;
494 protected readonly int code;
495 protected readonly Location location;
496 readonly string message;
498 protected AbstractMessage (int code, Location loc, string msg, List<string> extraInfo)
502 this.code = 8000 - code;
506 if (extraInfo.Count != 0) {
507 this.extra_info = extraInfo.ToArray ();
511 protected AbstractMessage (AbstractMessage aMsg)
513 this.code = aMsg.code;
514 this.location = aMsg.location;
515 this.message = aMsg.message;
516 this.extra_info = aMsg.extra_info;
523 public override bool Equals (object obj)
525 AbstractMessage msg = obj as AbstractMessage;
529 return code == msg.code && location.Equals (msg.location) && message == msg.message;
532 public override int GetHashCode ()
534 return code.GetHashCode ();
537 public abstract bool IsWarning { get; }
539 public Location Location {
540 get { return location; }
543 public abstract string MessageType { get; }
545 public string[] RelatedSymbols {
546 get { return extra_info; }
550 get { return message; }
554 sealed class WarningMessage : AbstractMessage
556 public WarningMessage (int code, Location loc, string message, List<string> extra_info)
557 : base (code, loc, message, extra_info)
561 public override bool IsWarning {
565 public override string MessageType {
572 sealed class ErrorMessage : AbstractMessage
574 public ErrorMessage (int code, Location loc, string message, List<string> extraInfo)
575 : base (code, loc, message, extraInfo)
579 public ErrorMessage (AbstractMessage aMsg)
584 public override bool IsWarning {
585 get { return false; }
588 public override string MessageType {
596 // Generic base for any message writer
598 public abstract class ReportPrinter {
600 /// Whether to dump a stack trace on errors.
602 public bool Stacktrace;
604 int warnings, errors;
606 public int WarningsCount {
607 get { return warnings; }
610 public int ErrorsCount {
611 get { return errors; }
614 protected virtual string FormatText (string txt)
620 // When (symbols related to previous ...) can be used
622 public virtual bool HasRelatedSymbolSupport {
626 public virtual void Print (AbstractMessage msg)
634 protected void Print (AbstractMessage msg, TextWriter output)
636 StringBuilder txt = new StringBuilder ();
637 if (!msg.Location.IsNull) {
638 txt.Append (msg.Location.ToString ());
642 txt.AppendFormat ("{0} CS{1:0000}: {2}", msg.MessageType, msg.Code, msg.Text);
645 output.WriteLine (FormatText (txt.ToString ()));
647 output.WriteLine (txt.ToString ());
649 if (msg.RelatedSymbols != null) {
650 foreach (string s in msg.RelatedSymbols)
651 output.WriteLine (s + msg.MessageType + ")");
657 // Default message recorder, it uses two types of message groups.
658 // Common messages: messages reported in all sessions.
659 // Merged messages: union of all messages in all sessions.
661 // Used by the Lambda expressions to compile the code with various
662 // parameter values, or by attribute resolver
664 class SessionReportPrinter : ReportPrinter
666 List<AbstractMessage> session_messages;
668 // A collection of exactly same messages reported in all sessions
670 List<AbstractMessage> common_messages;
673 // A collection of unique messages reported in all sessions
675 List<AbstractMessage> merged_messages;
677 public override void Print (AbstractMessage msg)
680 // This line is useful when debugging recorded messages
682 // Console.WriteLine ("RECORDING: {0}", msg.ToString ());
684 if (session_messages == null)
685 session_messages = new List<AbstractMessage> ();
687 session_messages.Add (msg);
692 public void EndSession ()
694 if (session_messages == null)
698 // Handles the first session
700 if (common_messages == null) {
701 common_messages = new List<AbstractMessage> (session_messages);
702 merged_messages = session_messages;
703 session_messages = null;
708 // Store common messages if any
710 for (int i = 0; i < common_messages.Count; ++i) {
711 AbstractMessage cmsg = common_messages[i];
712 bool common_msg_found = false;
713 foreach (AbstractMessage msg in session_messages) {
714 if (cmsg.Equals (msg)) {
715 common_msg_found = true;
720 if (!common_msg_found)
721 common_messages.RemoveAt (i);
725 // Merge session and previous messages
727 for (int i = 0; i < session_messages.Count; ++i) {
728 AbstractMessage msg = session_messages[i];
729 bool msg_found = false;
730 for (int ii = 0; ii < merged_messages.Count; ++ii) {
731 if (msg.Equals (merged_messages[ii])) {
738 merged_messages.Add (msg);
742 public bool IsEmpty {
744 return merged_messages == null && common_messages == null;
749 // Prints collected messages, common messages have a priority
751 public bool Merge (ReportPrinter dest)
753 var messages_to_print = merged_messages;
754 if (common_messages != null && common_messages.Count > 0) {
755 messages_to_print = common_messages;
758 if (messages_to_print == null)
761 bool error_msg = false;
762 foreach (AbstractMessage msg in messages_to_print) {
764 error_msg |= !msg.IsWarning;
771 class StreamReportPrinter : ReportPrinter
773 readonly TextWriter writer;
775 public StreamReportPrinter (TextWriter writer)
777 this.writer = writer;
780 public override void Print (AbstractMessage msg)
787 class ConsoleReportPrinter : StreamReportPrinter
789 static readonly string prefix, postfix;
791 static ConsoleReportPrinter ()
793 string term = Environment.GetEnvironmentVariable ("TERM");
794 bool xterm_colors = false;
800 if (Environment.GetEnvironmentVariable ("COLORTERM") != null){
812 if (!(UnixUtils.isatty (1) && UnixUtils.isatty (2)))
815 string config = Environment.GetEnvironmentVariable ("MCS_COLORS");
817 config = "errors=red";
818 //config = "brightwhite,red";
821 if (config == "disable")
824 if (!config.StartsWith ("errors="))
827 config = config.Substring (7);
829 int p = config.IndexOf (",");
831 prefix = GetForeground (config);
833 prefix = GetBackground (config.Substring (p+1)) + GetForeground (config.Substring (0, p));
834 postfix = "\x001b[0m";
837 public ConsoleReportPrinter ()
838 : base (Console.Error)
842 public ConsoleReportPrinter (TextWriter writer)
847 public int Fatal { get; set; }
849 static int NameToCode (string s)
874 // maps a color name to its xterm color code
876 static string GetForeground (string s)
880 if (s.StartsWith ("bright")) {
886 return "\x001b[" + highcode + (30 + NameToCode (s)).ToString () + "m";
889 static string GetBackground (string s)
891 return "\x001b[" + (40 + NameToCode (s)).ToString () + "m";
894 protected override string FormatText (string txt)
897 return prefix + txt + postfix;
902 static string FriendlyStackTrace (StackTrace t)
904 StringBuilder sb = new StringBuilder ();
906 bool foundUserCode = false;
908 for (int i = 0; i < t.FrameCount; i++) {
909 StackFrame f = t.GetFrame (i);
910 MethodBase mb = f.GetMethod ();
912 if (!foundUserCode && mb.ReflectedType == typeof (Report))
915 foundUserCode = true;
919 if (f.GetFileLineNumber () > 0)
920 sb.AppendFormat ("(at {0}:{1}) ", f.GetFileName (), f.GetFileLineNumber ());
922 sb.AppendFormat ("{0}.{1} (", mb.ReflectedType.Name, mb.Name);
925 foreach (ParameterInfo pi in mb.GetParameters ()) {
930 sb.Append (pi.ParameterType.FullName);
935 return sb.ToString ();
939 public override void Print (AbstractMessage msg)
944 Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
946 if (++print_count == Fatal)
947 throw new Exception (msg.Text);
950 public static string FriendlyStackTrace (Exception e)
952 return FriendlyStackTrace (new StackTrace (e, true));
955 public static void StackTrace ()
957 Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
961 public enum TimerType {
971 public enum CounterType {
980 static DateTime[] timer_start;
981 static TimeSpan[] timers;
982 static long[] timer_counters;
983 static long[] counters;
987 timer_start = new DateTime [(int) TimerType.CountTimers];
988 timers = new TimeSpan [(int) TimerType.CountTimers];
989 timer_counters = new long [(int) TimerType.CountTimers];
990 counters = new long [(int) CounterType.CountCounters];
992 for (int i = 0; i < (int) TimerType.CountTimers; i++) {
993 timer_start [i] = DateTime.Now;
994 timers [i] = TimeSpan.Zero;
998 [Conditional("TIMER")]
999 static public void IncrementCounter (CounterType which)
1001 ++counters [(int) which];
1004 [Conditional("TIMER")]
1005 static public void StartTimer (TimerType which)
1007 timer_start [(int) which] = DateTime.Now;
1010 [Conditional("TIMER")]
1011 static public void StopTimer (TimerType which)
1013 timers [(int) which] += DateTime.Now - timer_start [(int) which];
1014 ++timer_counters [(int) which];
1017 [Conditional("TIMER")]
1018 static public void ShowTimers ()
1020 ShowTimer (TimerType.FindMembers, "- FindMembers timer");
1021 ShowTimer (TimerType.TcFindMembers, "- TypeContainer.FindMembers timer");
1022 ShowTimer (TimerType.MemberLookup, "- MemberLookup timer");
1023 ShowTimer (TimerType.CachedLookup, "- CachedLookup timer");
1024 ShowTimer (TimerType.CacheInit, "- Cache init");
1025 ShowTimer (TimerType.MiscTimer, "- Misc timer");
1027 ShowCounter (CounterType.FindMembers, "- Find members");
1028 ShowCounter (CounterType.MemberCache, "- Member cache");
1029 ShowCounter (CounterType.MiscCounter, "- Misc counter");
1032 static public void ShowCounter (CounterType which, string msg)
1034 Console.WriteLine ("{0} {1}", counters [(int) which], msg);
1037 static public void ShowTimer (TimerType which, string msg)
1040 "[{0:00}:{1:000}] {2} (used {3} times)",
1041 (int) timers [(int) which].TotalSeconds,
1042 timers [(int) which].Milliseconds, msg,
1043 timer_counters [(int) which]);
1047 public class InternalErrorException : Exception {
1048 public InternalErrorException (MemberCore mc, Exception e)
1049 : base (mc.Location + " " + mc.GetSignatureForError (), e)
1053 public InternalErrorException ()
1054 : base ("Internal error")
1058 public InternalErrorException (string message)
1063 public InternalErrorException (string message, params object[] args)
1064 : base (String.Format (message, args))
1068 public InternalErrorException (Exception exception, string message, params object[] args)
1069 : base (String.Format (message, args), exception)
1073 public InternalErrorException (Exception e, Location loc)
1074 : base (loc.ToString (), e)
1080 /// Handles #pragma warning
1082 public class WarningRegions {
1084 abstract class PragmaCmd
1088 protected PragmaCmd (int line)
1093 public abstract bool IsEnabled (int code, bool previous);
1096 class Disable : PragmaCmd
1099 public Disable (int line, int code)
1105 public override bool IsEnabled (int code, bool previous)
1107 return this.code == code ? false : previous;
1111 class DisableAll : PragmaCmd
1113 public DisableAll (int line)
1116 public override bool IsEnabled(int code, bool previous)
1122 class Enable : PragmaCmd
1125 public Enable (int line, int code)
1131 public override bool IsEnabled(int code, bool previous)
1133 return this.code == code ? true : previous;
1137 class EnableAll : PragmaCmd
1139 public EnableAll (int line)
1142 public override bool IsEnabled(int code, bool previous)
1149 List<PragmaCmd> regions = new List<PragmaCmd> ();
1151 public void WarningDisable (int line)
1153 regions.Add (new DisableAll (line));
1156 public void WarningDisable (Location location, int code, Report Report)
1158 if (Report.CheckWarningCode (code, location))
1159 regions.Add (new Disable (location.Row, code));
1162 public void WarningEnable (int line)
1164 regions.Add (new EnableAll (line));
1167 public void WarningEnable (Location location, int code, Report Report)
1169 if (!Report.CheckWarningCode (code, location))
1172 if (Report.IsWarningDisabledGlobally (code))
1173 Report.Warning (1635, 1, location, "Cannot restore warning `CS{0:0000}' because it was disabled globally", code);
1175 regions.Add (new Enable (location.Row, code));
1178 public bool IsWarningEnabled (int code, int src_line)
1181 foreach (PragmaCmd pragma in regions) {
1182 if (src_line < pragma.Line)
1185 result = pragma.IsEnabled (code, result);