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;
188 while (ms is ElementTypeSpec) {
189 ms = ((ElementTypeSpec) ms).Element;
190 mc = ms.MemberDefinition as MemberCore;
194 SymbolRelatedToPreviousError (mc);
196 SymbolRelatedToPreviousError (ms.MemberDefinition.Assembly.Location, "");
200 public void SymbolRelatedToPreviousError (MemberCore mc)
202 SymbolRelatedToPreviousError (mc.Location, mc.GetSignatureForError ());
205 void SymbolRelatedToPreviousError (string loc, string symbol)
207 string msg = String.Format ("{0} (Location of the symbol related to previous ", loc);
208 if (extra_information.Contains (msg))
211 extra_information.Add (msg);
214 public void AddWarningAsError (string warningId)
218 id = int.Parse (warningId);
223 if (!CheckWarningCode (id, warningId, Location.Null))
226 if (warnings_as_error == null)
227 warnings_as_error = new List<int> ();
229 warnings_as_error.Add (id);
232 public void RemoveWarningAsError (string warningId)
236 id = int.Parse (warningId);
241 if (!CheckWarningCode (id, warningId, Location.Null))
244 if (warnings_only == null)
245 warnings_only = new List<int> ();
247 warnings_only.Add (id);
250 public bool CheckWarningCode (int code, Location loc)
252 return CheckWarningCode (code, code.ToString (), loc);
255 public bool CheckWarningCode (int code, string scode, Location loc)
257 if (IsValidWarning (code))
260 Warning (1691, 1, loc, "`{0}' is not a valid warning number", scode);
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<string, WarningRegions> ();
276 warning_regions_table.TryGetValue (location.Name, out regions);
279 if (regions == null) {
280 regions = new WarningRegions ();
281 warning_regions_table.Add (location.Name, 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 Dictionary<int, bool> ();
415 warning_ignore_table [code] = true;
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 foreach (AbstractMessage msg in messages_to_print)
768 class StreamReportPrinter : ReportPrinter
770 readonly TextWriter writer;
772 public StreamReportPrinter (TextWriter writer)
774 this.writer = writer;
777 public override void Print (AbstractMessage msg)
784 class ConsoleReportPrinter : StreamReportPrinter
786 static readonly string prefix, postfix;
788 static ConsoleReportPrinter ()
790 string term = Environment.GetEnvironmentVariable ("TERM");
791 bool xterm_colors = false;
797 if (Environment.GetEnvironmentVariable ("COLORTERM") != null){
809 if (!(UnixUtils.isatty (1) && UnixUtils.isatty (2)))
812 string config = Environment.GetEnvironmentVariable ("MCS_COLORS");
814 config = "errors=red";
815 //config = "brightwhite,red";
818 if (config == "disable")
821 if (!config.StartsWith ("errors="))
824 config = config.Substring (7);
826 int p = config.IndexOf (",");
828 prefix = GetForeground (config);
830 prefix = GetBackground (config.Substring (p+1)) + GetForeground (config.Substring (0, p));
831 postfix = "\x001b[0m";
834 public ConsoleReportPrinter ()
835 : base (Console.Error)
839 public ConsoleReportPrinter (TextWriter writer)
844 public int Fatal { get; set; }
846 static int NameToCode (string s)
871 // maps a color name to its xterm color code
873 static string GetForeground (string s)
877 if (s.StartsWith ("bright")) {
883 return "\x001b[" + highcode + (30 + NameToCode (s)).ToString () + "m";
886 static string GetBackground (string s)
888 return "\x001b[" + (40 + NameToCode (s)).ToString () + "m";
891 protected override string FormatText (string txt)
894 return prefix + txt + postfix;
899 static string FriendlyStackTrace (StackTrace t)
901 StringBuilder sb = new StringBuilder ();
903 bool foundUserCode = false;
905 for (int i = 0; i < t.FrameCount; i++) {
906 StackFrame f = t.GetFrame (i);
907 MethodBase mb = f.GetMethod ();
909 if (!foundUserCode && mb.ReflectedType == typeof (Report))
912 foundUserCode = true;
916 if (f.GetFileLineNumber () > 0)
917 sb.AppendFormat ("(at {0}:{1}) ", f.GetFileName (), f.GetFileLineNumber ());
919 sb.AppendFormat ("{0}.{1} (", mb.ReflectedType.Name, mb.Name);
922 foreach (ParameterInfo pi in mb.GetParameters ()) {
927 sb.Append (pi.ParameterType.FullName);
932 return sb.ToString ();
936 public override void Print (AbstractMessage msg)
941 Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
943 if (++print_count == Fatal)
944 throw new Exception (msg.Text);
947 public static string FriendlyStackTrace (Exception e)
949 return FriendlyStackTrace (new StackTrace (e, true));
952 public static void StackTrace ()
954 Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
958 public enum TimerType {
968 public enum CounterType {
977 static DateTime[] timer_start;
978 static TimeSpan[] timers;
979 static long[] timer_counters;
980 static long[] counters;
984 timer_start = new DateTime [(int) TimerType.CountTimers];
985 timers = new TimeSpan [(int) TimerType.CountTimers];
986 timer_counters = new long [(int) TimerType.CountTimers];
987 counters = new long [(int) CounterType.CountCounters];
989 for (int i = 0; i < (int) TimerType.CountTimers; i++) {
990 timer_start [i] = DateTime.Now;
991 timers [i] = TimeSpan.Zero;
995 [Conditional("TIMER")]
996 static public void IncrementCounter (CounterType which)
998 ++counters [(int) which];
1001 [Conditional("TIMER")]
1002 static public void StartTimer (TimerType which)
1004 timer_start [(int) which] = DateTime.Now;
1007 [Conditional("TIMER")]
1008 static public void StopTimer (TimerType which)
1010 timers [(int) which] += DateTime.Now - timer_start [(int) which];
1011 ++timer_counters [(int) which];
1014 [Conditional("TIMER")]
1015 static public void ShowTimers ()
1017 ShowTimer (TimerType.FindMembers, "- FindMembers timer");
1018 ShowTimer (TimerType.TcFindMembers, "- TypeContainer.FindMembers timer");
1019 ShowTimer (TimerType.MemberLookup, "- MemberLookup timer");
1020 ShowTimer (TimerType.CachedLookup, "- CachedLookup timer");
1021 ShowTimer (TimerType.CacheInit, "- Cache init");
1022 ShowTimer (TimerType.MiscTimer, "- Misc timer");
1024 ShowCounter (CounterType.FindMembers, "- Find members");
1025 ShowCounter (CounterType.MemberCache, "- Member cache");
1026 ShowCounter (CounterType.MiscCounter, "- Misc counter");
1029 static public void ShowCounter (CounterType which, string msg)
1031 Console.WriteLine ("{0} {1}", counters [(int) which], msg);
1034 static public void ShowTimer (TimerType which, string msg)
1037 "[{0:00}:{1:000}] {2} (used {3} times)",
1038 (int) timers [(int) which].TotalSeconds,
1039 timers [(int) which].Milliseconds, msg,
1040 timer_counters [(int) which]);
1044 public class InternalErrorException : Exception {
1045 public InternalErrorException (MemberCore mc, Exception e)
1046 : base (mc.Location + " " + mc.GetSignatureForError (), e)
1050 public InternalErrorException ()
1051 : base ("Internal error")
1055 public InternalErrorException (string message)
1060 public InternalErrorException (string message, params object[] args)
1061 : base (String.Format (message, args))
1065 public InternalErrorException (Exception exception, string message, params object[] args)
1066 : base (String.Format (message, args), exception)
1070 public InternalErrorException (Exception e, Location loc)
1071 : base (loc.ToString (), e)
1077 /// Handles #pragma warning
1079 public class WarningRegions {
1081 abstract class PragmaCmd
1085 protected PragmaCmd (int line)
1090 public abstract bool IsEnabled (int code, bool previous);
1093 class Disable : PragmaCmd
1096 public Disable (int line, int code)
1102 public override bool IsEnabled (int code, bool previous)
1104 return this.code == code ? false : previous;
1108 class DisableAll : PragmaCmd
1110 public DisableAll (int line)
1113 public override bool IsEnabled(int code, bool previous)
1119 class Enable : PragmaCmd
1122 public Enable (int line, int code)
1128 public override bool IsEnabled(int code, bool previous)
1130 return this.code == code ? true : previous;
1134 class EnableAll : PragmaCmd
1136 public EnableAll (int line)
1139 public override bool IsEnabled(int code, bool previous)
1146 List<PragmaCmd> regions = new List<PragmaCmd> ();
1148 public void WarningDisable (int line)
1150 regions.Add (new DisableAll (line));
1153 public void WarningDisable (Location location, int code, Report Report)
1155 if (Report.CheckWarningCode (code, location))
1156 regions.Add (new Disable (location.Row, code));
1159 public void WarningEnable (int line)
1161 regions.Add (new EnableAll (line));
1164 public void WarningEnable (Location location, int code, Report Report)
1166 if (Report.CheckWarningCode (code, location))
1167 regions.Add (new Enable (location.Row, code));
1170 public bool IsWarningEnabled (int code, int src_line)
1173 foreach (PragmaCmd pragma in regions) {
1174 if (src_line < pragma.Line)
1177 result = pragma.IsEnabled (code, result);