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;
16 using System.Reflection.Emit;
18 namespace Mono.CSharp {
21 // Errors and warnings manager
26 /// Whether warnings should be considered errors
28 public bool WarningsAreErrors;
29 List<int> warnings_as_error;
30 List<int> warnings_only;
32 public static int DebugFlags = 0;
35 // Keeps track of the warnings that we are ignoring
37 public Dictionary<int, bool> warning_ignore_table;
39 Dictionary<string, WarningRegions> warning_regions_table;
43 ReportPrinter printer;
45 int reporting_disabled;
48 /// List of symbols related to reported error/warning. You have to fill it before error/warning is reported.
50 List<string> extra_information = new List<string> ();
53 // IF YOU ADD A NEW WARNING YOU HAVE TO ADD ITS ID HERE
55 public static readonly int[] AllWarnings = new int[] {
57 105, 108, 109, 114, 162, 164, 168, 169, 183, 184, 197,
58 219, 251, 252, 253, 278, 282,
59 402, 414, 419, 420, 429, 436, 440, 458, 464, 465, 467, 469, 472,
60 612, 618, 626, 628, 642, 649, 652, 658, 659, 660, 661, 665, 672, 675, 693,
63 1522, 1570, 1571, 1572, 1573, 1574, 1580, 1581, 1584, 1587, 1589, 1590, 1591, 1592,
64 1616, 1633, 1634, 1635, 1685, 1690, 1691, 1692,
65 1700, 1717, 1718, 1720,
68 3000, 3001, 3002, 3003, 3005, 3006, 3007, 3008, 3009,
69 3010, 3011, 3012, 3013, 3014, 3015, 3016, 3017, 3018, 3019,
70 3021, 3022, 3023, 3024, 3026, 3027
75 // Just to be sure that binary search is working
76 Array.Sort (AllWarnings);
79 public Report (ReportPrinter printer)
82 throw new ArgumentNullException ("printer");
84 this.printer = printer;
88 public void DisableReporting ()
93 public void EnableReporting ()
98 public void FeatureIsNotAvailable (Location loc, string feature)
101 switch (RootContext.Version) {
102 case LanguageVersion.ISO_1:
105 case LanguageVersion.ISO_2:
108 case LanguageVersion.V_3:
112 throw new InternalErrorException ("Invalid feature version", RootContext.Version);
116 "Feature `{0}' cannot be used because it is not part of the C# {1} language specification",
120 public void FeatureIsNotSupported (Location loc, string feature)
123 "Feature `{0}' is not supported in Mono mcs1 compiler. Consider using the `gmcs' compiler instead",
127 static bool IsValidWarning (int code)
129 return Array.BinarySearch (AllWarnings, code) >= 0;
132 bool IsWarningEnabled (int code, int level, Location loc)
134 if (WarningLevel < level)
137 if (warning_ignore_table != null) {
138 if (warning_ignore_table.ContainsKey (code)) {
143 if (warning_regions_table == null || loc.IsNull)
146 WarningRegions regions;
147 if (!warning_regions_table.TryGetValue (loc.Name, out regions))
150 return regions.IsWarningEnabled (code, loc.Row);
153 bool IsWarningAsError (int code)
155 bool is_error = WarningsAreErrors;
157 // Check specific list
158 if (warnings_as_error != null)
159 is_error |= warnings_as_error.Contains (code);
161 // Ignore excluded warnings
162 if (warnings_only != null && warnings_only.Contains (code))
168 public void RuntimeMissingSupport (Location loc, string feature)
170 Error (-88, loc, "Your .NET Runtime does not support `{0}'. Please use the latest Mono runtime instead.", feature);
174 /// In most error cases is very useful to have information about symbol that caused the error.
175 /// Call this method before you call Report.Error when it makes sense.
177 public void SymbolRelatedToPreviousError (Location loc, string symbol)
179 SymbolRelatedToPreviousError (loc.ToString (), symbol);
182 public void SymbolRelatedToPreviousError (MemberSpec ms)
184 if (reporting_disabled > 0 || !printer.HasRelatedSymbolSupport)
187 var mc = ms.MemberDefinition as MemberCore;
189 SymbolRelatedToPreviousError (mc);
191 var im = ms.MemberDefinition as ImportedMemberDefinition;
192 SymbolRelatedToPreviousError (im.Assembly.Location, "");
196 public void SymbolRelatedToPreviousError (MemberCore mc)
198 SymbolRelatedToPreviousError (mc.Location, mc.GetSignatureForError ());
201 void SymbolRelatedToPreviousError (string loc, string symbol)
203 string msg = String.Format ("{0} (Location of the symbol related to previous ", loc);
204 if (extra_information.Contains (msg))
207 extra_information.Add (msg);
210 public void AddWarningAsError (string warningId)
214 id = int.Parse (warningId);
219 if (!CheckWarningCode (id, warningId, 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);
237 if (!CheckWarningCode (id, warningId, Location.Null))
240 if (warnings_only == null)
241 warnings_only = new List<int> ();
243 warnings_only.Add (id);
246 public bool CheckWarningCode (int code, Location loc)
248 return CheckWarningCode (code, code.ToString (), loc);
251 public bool CheckWarningCode (int code, string scode, Location loc)
253 if (IsValidWarning (code))
256 Warning (1691, 1, loc, "`{0}' is not a valid warning number", scode);
260 public void ExtraInformation (Location loc, string msg)
262 extra_information.Add (String.Format ("{0} {1}", loc, msg));
265 public WarningRegions RegisterWarningRegion (Location location)
267 WarningRegions regions;
268 if (warning_regions_table == null) {
270 warning_regions_table = new Dictionary<string, WarningRegions> ();
272 warning_regions_table.TryGetValue (location.Name, out regions);
275 if (regions == null) {
276 regions = new WarningRegions ();
277 warning_regions_table.Add (location.Name, regions);
283 public void Warning (int code, int level, Location loc, string message)
285 if (reporting_disabled > 0)
288 if (!IsWarningEnabled (code, level, loc))
292 if (IsWarningAsError (code))
293 msg = new ErrorMessage (code, loc, message, extra_information);
295 msg = new WarningMessage (code, loc, message, extra_information);
297 extra_information.Clear ();
301 public void Warning (int code, int level, Location loc, string format, string arg)
303 Warning (code, level, loc, String.Format (format, arg));
306 public void Warning (int code, int level, Location loc, string format, string arg1, string arg2)
308 Warning (code, level, loc, String.Format (format, arg1, arg2));
311 public void Warning (int code, int level, Location loc, string format, params object[] args)
313 Warning (code, level, loc, String.Format (format, args));
316 public void Warning (int code, int level, string message)
318 Warning (code, level, Location.Null, message);
321 public void Warning (int code, int level, string format, string arg)
323 Warning (code, level, Location.Null, format, arg);
326 public void Warning (int code, int level, string format, string arg1, string arg2)
328 Warning (code, level, Location.Null, format, arg1, arg2);
331 public void Warning (int code, int level, string format, params string[] args)
333 Warning (code, level, Location.Null, String.Format (format, args));
337 // Warnings encountered so far
339 public int Warnings {
340 get { return printer.WarningsCount; }
343 public void Error (int code, Location loc, string error)
345 if (reporting_disabled > 0)
348 ErrorMessage msg = new ErrorMessage (code, loc, error, extra_information);
349 extra_information.Clear ();
354 public void Error (int code, Location loc, string format, string arg)
356 Error (code, loc, String.Format (format, arg));
359 public void Error (int code, Location loc, string format, string arg1, string arg2)
361 Error (code, loc, String.Format (format, arg1, arg2));
364 public void Error (int code, Location loc, string format, params string[] args)
366 Error (code, loc, String.Format (format, args));
369 public void Error (int code, string error)
371 Error (code, Location.Null, error);
374 public void Error (int code, string format, string arg)
376 Error (code, Location.Null, format, arg);
379 public void Error (int code, string format, string arg1, string arg2)
381 Error (code, Location.Null, format, arg1, arg2);
384 public void Error (int code, string format, params string[] args)
386 Error (code, Location.Null, String.Format (format, args));
390 // Errors encountered so far
393 get { return printer.ErrorsCount; }
396 public ReportPrinter Printer {
397 get { return printer; }
400 public void SetIgnoreWarning (int code)
402 if (warning_ignore_table == null)
403 warning_ignore_table = new Dictionary<int, bool> ();
405 warning_ignore_table [code] = true;
408 public ReportPrinter SetPrinter (ReportPrinter printer)
410 ReportPrinter old = this.printer;
411 this.printer = printer;
415 public int WarningLevel {
417 return warning_level;
420 warning_level = value;
424 [Conditional ("MCS_DEBUG")]
425 static public void Debug (string message, params object[] args)
427 Debug (4, message, args);
430 [Conditional ("MCS_DEBUG")]
431 static public void Debug (int category, string message, params object[] args)
433 if ((category & DebugFlags) == 0)
436 StringBuilder sb = new StringBuilder (message);
438 if ((args != null) && (args.Length > 0)) {
442 foreach (object arg in args) {
449 // else if (arg is ICollection)
450 // sb.Append (PrintCollection ((ICollection) arg));
456 Console.WriteLine (sb.ToString ());
459 static public string PrintCollection (ICollection collection)
461 StringBuilder sb = new StringBuilder ();
463 sb.Append (collection.GetType ());
467 foreach (object o in collection) {
476 return sb.ToString ();
481 public abstract class AbstractMessage
483 readonly string[] extra_info;
484 protected readonly int code;
485 protected readonly Location location;
486 readonly string message;
488 protected AbstractMessage (int code, Location loc, string msg, List<string> extraInfo)
492 this.code = 8000 - code;
496 if (extraInfo.Count != 0) {
497 this.extra_info = extraInfo.ToArray ();
501 protected AbstractMessage (AbstractMessage aMsg)
503 this.code = aMsg.code;
504 this.location = aMsg.location;
505 this.message = aMsg.message;
506 this.extra_info = aMsg.extra_info;
513 public override bool Equals (object obj)
515 AbstractMessage msg = obj as AbstractMessage;
519 return code == msg.code && location.Equals (msg.location) && message == msg.message;
522 public override int GetHashCode ()
524 return code.GetHashCode ();
527 public abstract bool IsWarning { get; }
529 public Location Location {
530 get { return location; }
533 public abstract string MessageType { get; }
535 public string[] RelatedSymbols {
536 get { return extra_info; }
540 get { return message; }
544 sealed class WarningMessage : AbstractMessage
546 public WarningMessage (int code, Location loc, string message, List<string> extra_info)
547 : base (code, loc, message, extra_info)
551 public override bool IsWarning {
555 public override string MessageType {
562 sealed class ErrorMessage : AbstractMessage
564 public ErrorMessage (int code, Location loc, string message, List<string> extraInfo)
565 : base (code, loc, message, extraInfo)
569 public ErrorMessage (AbstractMessage aMsg)
574 public override bool IsWarning {
575 get { return false; }
578 public override string MessageType {
586 // Generic base for any message writer
588 public abstract class ReportPrinter {
590 /// Whether to dump a stack trace on errors.
592 public bool Stacktrace;
594 int warnings, errors;
596 public int WarningsCount {
597 get { return warnings; }
600 public int ErrorsCount {
601 get { return errors; }
604 protected virtual string FormatText (string txt)
610 // When (symbols related to previous ...) can be used
612 public virtual bool HasRelatedSymbolSupport {
616 public virtual void Print (AbstractMessage msg)
624 protected void Print (AbstractMessage msg, TextWriter output)
626 StringBuilder txt = new StringBuilder ();
627 if (!msg.Location.IsNull) {
628 txt.Append (msg.Location.ToString ());
632 txt.AppendFormat ("{0} CS{1:0000}: {2}", msg.MessageType, msg.Code, msg.Text);
635 output.WriteLine (FormatText (txt.ToString ()));
637 output.WriteLine (txt.ToString ());
639 if (msg.RelatedSymbols != null) {
640 foreach (string s in msg.RelatedSymbols)
641 output.WriteLine (s + msg.MessageType + ")");
647 // Default message recorder, it uses two types of message groups.
648 // Common messages: messages reported in all sessions.
649 // Merged messages: union of all messages in all sessions.
651 // Used by the Lambda expressions to compile the code with various
652 // parameter values, or by attribute resolver
654 class SessionReportPrinter : ReportPrinter
656 List<AbstractMessage> session_messages;
658 // A collection of exactly same messages reported in all sessions
660 List<AbstractMessage> common_messages;
663 // A collection of unique messages reported in all sessions
665 List<AbstractMessage> merged_messages;
667 public override void Print (AbstractMessage msg)
670 // This line is useful when debugging recorded messages
672 // Console.WriteLine ("RECORDING: {0} {1} {2}", code, location, message);
674 if (session_messages == null)
675 session_messages = new List<AbstractMessage> ();
677 session_messages.Add (msg);
682 public void EndSession ()
684 if (session_messages == null)
688 // Handles the first session
690 if (common_messages == null) {
691 common_messages = new List<AbstractMessage> (session_messages);
692 merged_messages = session_messages;
693 session_messages = null;
698 // Store common messages if any
700 for (int i = 0; i < common_messages.Count; ++i) {
701 AbstractMessage cmsg = (AbstractMessage) common_messages[i];
702 bool common_msg_found = false;
703 foreach (AbstractMessage msg in session_messages) {
704 if (cmsg.Equals (msg)) {
705 common_msg_found = true;
710 if (!common_msg_found)
711 common_messages.RemoveAt (i);
715 // Merge session and previous messages
717 for (int i = 0; i < session_messages.Count; ++i) {
718 AbstractMessage msg = (AbstractMessage) session_messages[i];
719 bool msg_found = false;
720 for (int ii = 0; ii < merged_messages.Count; ++ii) {
721 if (msg.Equals (merged_messages[ii])) {
728 merged_messages.Add (msg);
732 public bool IsEmpty {
734 return merged_messages == null && common_messages == null;
739 // Prints collected messages, common messages have a priority
741 public bool Merge (ReportPrinter dest)
743 var messages_to_print = merged_messages;
744 if (common_messages != null && common_messages.Count > 0) {
745 messages_to_print = common_messages;
748 if (messages_to_print == null)
751 foreach (AbstractMessage msg in messages_to_print)
758 class StreamReportPrinter : ReportPrinter
760 readonly TextWriter writer;
762 public StreamReportPrinter (TextWriter writer)
764 this.writer = writer;
767 public override void Print (AbstractMessage msg)
774 class ConsoleReportPrinter : StreamReportPrinter
776 static readonly string prefix, postfix;
778 static ConsoleReportPrinter ()
780 string term = Environment.GetEnvironmentVariable ("TERM");
781 bool xterm_colors = false;
787 if (Environment.GetEnvironmentVariable ("COLORTERM") != null){
799 if (!(UnixUtils.isatty (1) && UnixUtils.isatty (2)))
802 string config = Environment.GetEnvironmentVariable ("MCS_COLORS");
804 config = "errors=red";
805 //config = "brightwhite,red";
808 if (config == "disable")
811 if (!config.StartsWith ("errors="))
814 config = config.Substring (7);
816 int p = config.IndexOf (",");
818 prefix = GetForeground (config);
820 prefix = GetBackground (config.Substring (p+1)) + GetForeground (config.Substring (0, p));
821 postfix = "\x001b[0m";
824 public ConsoleReportPrinter ()
825 : base (Console.Error)
829 public ConsoleReportPrinter (TextWriter writer)
834 public int Fatal { get; set; }
836 static int NameToCode (string s)
861 // maps a color name to its xterm color code
863 static string GetForeground (string s)
867 if (s.StartsWith ("bright")) {
873 return "\x001b[" + highcode + (30 + NameToCode (s)).ToString () + "m";
876 static string GetBackground (string s)
878 return "\x001b[" + (40 + NameToCode (s)).ToString () + "m";
881 protected override string FormatText (string txt)
884 return prefix + txt + postfix;
889 static string FriendlyStackTrace (StackTrace t)
891 StringBuilder sb = new StringBuilder ();
893 bool foundUserCode = false;
895 for (int i = 0; i < t.FrameCount; i++) {
896 StackFrame f = t.GetFrame (i);
897 MethodBase mb = f.GetMethod ();
899 if (!foundUserCode && mb.ReflectedType == typeof (Report))
902 foundUserCode = true;
906 if (f.GetFileLineNumber () > 0)
907 sb.AppendFormat ("(at {0}:{1}) ", f.GetFileName (), f.GetFileLineNumber ());
909 sb.AppendFormat ("{0}.{1} (", mb.ReflectedType.Name, mb.Name);
912 foreach (ParameterInfo pi in mb.GetParameters ()) {
917 sb.Append (pi.ParameterType.FullName);
922 return sb.ToString ();
926 public override void Print (AbstractMessage msg)
931 Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
933 if (++print_count == Fatal)
934 throw new Exception (msg.Text);
937 public static string FriendlyStackTrace (Exception e)
939 return FriendlyStackTrace (new StackTrace (e, true));
942 public static void StackTrace ()
944 Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
948 public enum TimerType {
958 public enum CounterType {
967 static DateTime[] timer_start;
968 static TimeSpan[] timers;
969 static long[] timer_counters;
970 static long[] counters;
974 timer_start = new DateTime [(int) TimerType.CountTimers];
975 timers = new TimeSpan [(int) TimerType.CountTimers];
976 timer_counters = new long [(int) TimerType.CountTimers];
977 counters = new long [(int) CounterType.CountCounters];
979 for (int i = 0; i < (int) TimerType.CountTimers; i++) {
980 timer_start [i] = DateTime.Now;
981 timers [i] = TimeSpan.Zero;
985 [Conditional("TIMER")]
986 static public void IncrementCounter (CounterType which)
988 ++counters [(int) which];
991 [Conditional("TIMER")]
992 static public void StartTimer (TimerType which)
994 timer_start [(int) which] = DateTime.Now;
997 [Conditional("TIMER")]
998 static public void StopTimer (TimerType which)
1000 timers [(int) which] += DateTime.Now - timer_start [(int) which];
1001 ++timer_counters [(int) which];
1004 [Conditional("TIMER")]
1005 static public void ShowTimers ()
1007 ShowTimer (TimerType.FindMembers, "- FindMembers timer");
1008 ShowTimer (TimerType.TcFindMembers, "- TypeContainer.FindMembers timer");
1009 ShowTimer (TimerType.MemberLookup, "- MemberLookup timer");
1010 ShowTimer (TimerType.CachedLookup, "- CachedLookup timer");
1011 ShowTimer (TimerType.CacheInit, "- Cache init");
1012 ShowTimer (TimerType.MiscTimer, "- Misc timer");
1014 ShowCounter (CounterType.FindMembers, "- Find members");
1015 ShowCounter (CounterType.MemberCache, "- Member cache");
1016 ShowCounter (CounterType.MiscCounter, "- Misc counter");
1019 static public void ShowCounter (CounterType which, string msg)
1021 Console.WriteLine ("{0} {1}", counters [(int) which], msg);
1024 static public void ShowTimer (TimerType which, string msg)
1027 "[{0:00}:{1:000}] {2} (used {3} times)",
1028 (int) timers [(int) which].TotalSeconds,
1029 timers [(int) which].Milliseconds, msg,
1030 timer_counters [(int) which]);
1034 public class InternalErrorException : Exception {
1035 public InternalErrorException (MemberCore mc, Exception e)
1036 : base (mc.Location + " " + mc.GetSignatureForError (), e)
1040 public InternalErrorException ()
1041 : base ("Internal error")
1045 public InternalErrorException (string message)
1050 public InternalErrorException (string message, params object[] args)
1051 : base (String.Format (message, args))
1054 public InternalErrorException (Exception e, Location loc)
1055 : base (loc.ToString (), e)
1061 /// Handles #pragma warning
1063 public class WarningRegions {
1065 abstract class PragmaCmd
1069 protected PragmaCmd (int line)
1074 public abstract bool IsEnabled (int code, bool previous);
1077 class Disable : PragmaCmd
1080 public Disable (int line, int code)
1086 public override bool IsEnabled (int code, bool previous)
1088 return this.code == code ? false : previous;
1092 class DisableAll : PragmaCmd
1094 public DisableAll (int line)
1097 public override bool IsEnabled(int code, bool previous)
1103 class Enable : PragmaCmd
1106 public Enable (int line, int code)
1112 public override bool IsEnabled(int code, bool previous)
1114 return this.code == code ? true : previous;
1118 class EnableAll : PragmaCmd
1120 public EnableAll (int line)
1123 public override bool IsEnabled(int code, bool previous)
1130 List<PragmaCmd> regions = new List<PragmaCmd> ();
1132 public void WarningDisable (int line)
1134 regions.Add (new DisableAll (line));
1137 public void WarningDisable (Location location, int code, Report Report)
1139 if (Report.CheckWarningCode (code, location))
1140 regions.Add (new Disable (location.Row, code));
1143 public void WarningEnable (int line)
1145 regions.Add (new EnableAll (line));
1148 public void WarningEnable (Location location, int code, Report Report)
1150 if (Report.CheckWarningCode (code, location))
1151 regions.Add (new Enable (location.Row, code));
1154 public bool IsWarningEnabled (int code, int src_line)
1157 foreach (PragmaCmd pragma in regions) {
1158 if (src_line < pragma.Line)
1161 result = pragma.IsEnabled (code, result);