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;
34 // Keeps track of the warnings that we are ignoring
36 public Dictionary<int, bool> warning_ignore_table;
38 Dictionary<string, WarningRegions> warning_regions_table;
42 ReportPrinter printer;
44 int reporting_disabled;
47 /// List of symbols related to reported error/warning. You have to fill it before error/warning is reported.
49 List<string> extra_information = new List<string> ();
52 // IF YOU ADD A NEW WARNING YOU HAVE TO ADD ITS ID HERE
54 public static readonly int[] AllWarnings = new int[] {
56 105, 108, 109, 114, 162, 164, 168, 169, 183, 184, 197,
57 219, 251, 252, 253, 278, 282,
58 402, 414, 419, 420, 429, 436, 440, 458, 464, 465, 467, 469, 472,
59 612, 618, 626, 628, 642, 649, 652, 658, 659, 660, 661, 665, 672, 675, 693,
62 1522, 1570, 1571, 1572, 1573, 1574, 1580, 1581, 1584, 1587, 1589, 1590, 1591, 1592,
63 1616, 1633, 1634, 1635, 1685, 1690, 1691, 1692, 1699,
64 1700, 1717, 1718, 1720,
67 3000, 3001, 3002, 3003, 3005, 3006, 3007, 3008, 3009,
68 3010, 3011, 3012, 3013, 3014, 3015, 3016, 3017, 3018, 3019,
69 3021, 3022, 3023, 3024, 3026, 3027
74 // Just to be sure that binary search is working
75 Array.Sort (AllWarnings);
78 public Report (ReportPrinter printer)
81 throw new ArgumentNullException ("printer");
83 this.printer = printer;
87 public void DisableReporting ()
92 public void EnableReporting ()
97 public void FeatureIsNotAvailable (Location loc, string feature)
100 switch (RootContext.Version) {
101 case LanguageVersion.ISO_1:
104 case LanguageVersion.ISO_2:
107 case LanguageVersion.V_3:
111 throw new InternalErrorException ("Invalid feature version", RootContext.Version);
115 "Feature `{0}' cannot be used because it is not part of the C# {1} language specification",
119 public void FeatureIsNotSupported (Location loc, string feature)
122 "Feature `{0}' is not supported in Mono mcs1 compiler. Consider using the `gmcs' compiler instead",
126 static bool IsValidWarning (int code)
128 return Array.BinarySearch (AllWarnings, code) >= 0;
131 bool IsWarningEnabled (int code, int level, Location loc)
133 if (WarningLevel < level)
136 if (warning_ignore_table != null) {
137 if (warning_ignore_table.ContainsKey (code)) {
142 if (warning_regions_table == null || loc.IsNull)
145 WarningRegions regions;
146 if (!warning_regions_table.TryGetValue (loc.Name, out regions))
149 return regions.IsWarningEnabled (code, loc.Row);
152 bool IsWarningAsError (int code)
154 bool is_error = WarningsAreErrors;
156 // Check specific list
157 if (warnings_as_error != null)
158 is_error |= warnings_as_error.Contains (code);
160 // Ignore excluded warnings
161 if (warnings_only != null && warnings_only.Contains (code))
167 public void RuntimeMissingSupport (Location loc, string feature)
169 Error (-88, loc, "Your .NET Runtime does not support `{0}'. Please use the latest Mono runtime instead.", feature);
173 /// In most error cases is very useful to have information about symbol that caused the error.
174 /// Call this method before you call Report.Error when it makes sense.
176 public void SymbolRelatedToPreviousError (Location loc, string symbol)
178 SymbolRelatedToPreviousError (loc.ToString (), symbol);
181 public void SymbolRelatedToPreviousError (MemberSpec ms)
183 if (reporting_disabled > 0 || !printer.HasRelatedSymbolSupport)
186 var mc = ms.MemberDefinition as MemberCore;
187 while (ms is ElementTypeSpec) {
188 ms = ((ElementTypeSpec) ms).Element;
189 mc = ms.MemberDefinition as MemberCore;
193 SymbolRelatedToPreviousError (mc);
194 } else if (ms.MemberDefinition != null) {
195 SymbolRelatedToPreviousError (ms.MemberDefinition.Assembly.Location, "");
199 public void SymbolRelatedToPreviousError (MemberCore mc)
201 SymbolRelatedToPreviousError (mc.Location, mc.GetSignatureForError ());
204 void SymbolRelatedToPreviousError (string loc, string symbol)
206 string msg = String.Format ("{0} (Location of the symbol related to previous ", loc);
207 if (extra_information.Contains (msg))
210 extra_information.Add (msg);
213 public void AddWarningAsError (string warningId)
217 id = int.Parse (warningId);
222 if (!CheckWarningCode (id, warningId, Location.Null))
225 if (warnings_as_error == null)
226 warnings_as_error = new List<int> ();
228 warnings_as_error.Add (id);
231 public void RemoveWarningAsError (string warningId)
235 id = int.Parse (warningId);
240 if (!CheckWarningCode (id, warningId, Location.Null))
243 if (warnings_only == null)
244 warnings_only = new List<int> ();
246 warnings_only.Add (id);
249 public bool CheckWarningCode (int code, Location loc)
251 return CheckWarningCode (code, code.ToString (), loc);
254 public bool CheckWarningCode (int code, string scode, Location loc)
256 if (IsValidWarning (code))
259 Warning (1691, 1, loc, "`{0}' is not a valid warning number", scode);
263 public void ExtraInformation (Location loc, string msg)
265 extra_information.Add (String.Format ("{0} {1}", loc, msg));
268 public WarningRegions RegisterWarningRegion (Location location)
270 WarningRegions regions;
271 if (warning_regions_table == null) {
273 warning_regions_table = new Dictionary<string, WarningRegions> ();
275 warning_regions_table.TryGetValue (location.Name, out regions);
278 if (regions == null) {
279 regions = new WarningRegions ();
280 warning_regions_table.Add (location.Name, regions);
286 public void Warning (int code, int level, Location loc, string message)
288 if (reporting_disabled > 0)
291 if (!IsWarningEnabled (code, level, loc))
295 if (IsWarningAsError (code))
296 msg = new ErrorMessage (code, loc, message, extra_information);
298 msg = new WarningMessage (code, loc, message, extra_information);
300 extra_information.Clear ();
304 public void Warning (int code, int level, Location loc, string format, string arg)
306 Warning (code, level, loc, String.Format (format, arg));
309 public void Warning (int code, int level, Location loc, string format, string arg1, string arg2)
311 Warning (code, level, loc, String.Format (format, arg1, arg2));
314 public void Warning (int code, int level, Location loc, string format, params object[] args)
316 Warning (code, level, loc, String.Format (format, args));
319 public void Warning (int code, int level, string message)
321 Warning (code, level, Location.Null, message);
324 public void Warning (int code, int level, string format, string arg)
326 Warning (code, level, Location.Null, format, arg);
329 public void Warning (int code, int level, string format, string arg1, string arg2)
331 Warning (code, level, Location.Null, format, arg1, arg2);
334 public void Warning (int code, int level, string format, params string[] args)
336 Warning (code, level, Location.Null, String.Format (format, args));
340 // Warnings encountered so far
342 public int Warnings {
343 get { return printer.WarningsCount; }
346 public void Error (int code, Location loc, string error)
348 if (reporting_disabled > 0)
351 ErrorMessage msg = new ErrorMessage (code, loc, error, extra_information);
352 extra_information.Clear ();
357 public void Error (int code, Location loc, string format, string arg)
359 Error (code, loc, String.Format (format, arg));
362 public void Error (int code, Location loc, string format, string arg1, string arg2)
364 Error (code, loc, String.Format (format, arg1, arg2));
367 public void Error (int code, Location loc, string format, params string[] args)
369 Error (code, loc, String.Format (format, args));
372 public void Error (int code, string error)
374 Error (code, Location.Null, error);
377 public void Error (int code, string format, string arg)
379 Error (code, Location.Null, format, arg);
382 public void Error (int code, string format, string arg1, string arg2)
384 Error (code, Location.Null, format, arg1, arg2);
387 public void Error (int code, string format, params string[] args)
389 Error (code, Location.Null, String.Format (format, args));
393 // Errors encountered so far
396 get { return printer.ErrorsCount; }
399 public bool IsDisabled {
401 return reporting_disabled > 0;
405 public ReportPrinter Printer {
406 get { return printer; }
409 public void SetIgnoreWarning (int code)
411 if (warning_ignore_table == null)
412 warning_ignore_table = new Dictionary<int, bool> ();
414 warning_ignore_table [code] = true;
417 public ReportPrinter SetPrinter (ReportPrinter printer)
419 ReportPrinter old = this.printer;
420 this.printer = printer;
424 public int WarningLevel {
426 return warning_level;
429 warning_level = value;
433 [Conditional ("MCS_DEBUG")]
434 static public void Debug (string message, params object[] args)
436 Debug (4, message, args);
439 [Conditional ("MCS_DEBUG")]
440 static public void Debug (int category, string message, params object[] args)
442 if ((category & DebugFlags) == 0)
445 StringBuilder sb = new StringBuilder (message);
447 if ((args != null) && (args.Length > 0)) {
451 foreach (object arg in args) {
458 // else if (arg is ICollection)
459 // sb.Append (PrintCollection ((ICollection) arg));
465 Console.WriteLine (sb.ToString ());
468 static public string PrintCollection (ICollection collection)
470 StringBuilder sb = new StringBuilder ();
472 sb.Append (collection.GetType ());
476 foreach (object o in collection) {
485 return sb.ToString ();
490 public abstract class AbstractMessage
492 readonly string[] extra_info;
493 protected readonly int code;
494 protected readonly Location location;
495 readonly string message;
497 protected AbstractMessage (int code, Location loc, string msg, List<string> extraInfo)
501 this.code = 8000 - code;
505 if (extraInfo.Count != 0) {
506 this.extra_info = extraInfo.ToArray ();
510 protected AbstractMessage (AbstractMessage aMsg)
512 this.code = aMsg.code;
513 this.location = aMsg.location;
514 this.message = aMsg.message;
515 this.extra_info = aMsg.extra_info;
522 public override bool Equals (object obj)
524 AbstractMessage msg = obj as AbstractMessage;
528 return code == msg.code && location.Equals (msg.location) && message == msg.message;
531 public override int GetHashCode ()
533 return code.GetHashCode ();
536 public abstract bool IsWarning { get; }
538 public Location Location {
539 get { return location; }
542 public abstract string MessageType { get; }
544 public string[] RelatedSymbols {
545 get { return extra_info; }
549 get { return message; }
553 sealed class WarningMessage : AbstractMessage
555 public WarningMessage (int code, Location loc, string message, List<string> extra_info)
556 : base (code, loc, message, extra_info)
560 public override bool IsWarning {
564 public override string MessageType {
571 sealed class ErrorMessage : AbstractMessage
573 public ErrorMessage (int code, Location loc, string message, List<string> extraInfo)
574 : base (code, loc, message, extraInfo)
578 public ErrorMessage (AbstractMessage aMsg)
583 public override bool IsWarning {
584 get { return false; }
587 public override string MessageType {
595 // Generic base for any message writer
597 public abstract class ReportPrinter {
599 /// Whether to dump a stack trace on errors.
601 public bool Stacktrace;
603 int warnings, errors;
605 public int WarningsCount {
606 get { return warnings; }
609 public int ErrorsCount {
610 get { return errors; }
613 protected virtual string FormatText (string txt)
619 // When (symbols related to previous ...) can be used
621 public virtual bool HasRelatedSymbolSupport {
625 public virtual void Print (AbstractMessage msg)
633 protected void Print (AbstractMessage msg, TextWriter output)
635 StringBuilder txt = new StringBuilder ();
636 if (!msg.Location.IsNull) {
637 txt.Append (msg.Location.ToString ());
641 txt.AppendFormat ("{0} CS{1:0000}: {2}", msg.MessageType, msg.Code, msg.Text);
644 output.WriteLine (FormatText (txt.ToString ()));
646 output.WriteLine (txt.ToString ());
648 if (msg.RelatedSymbols != null) {
649 foreach (string s in msg.RelatedSymbols)
650 output.WriteLine (s + msg.MessageType + ")");
656 // Default message recorder, it uses two types of message groups.
657 // Common messages: messages reported in all sessions.
658 // Merged messages: union of all messages in all sessions.
660 // Used by the Lambda expressions to compile the code with various
661 // parameter values, or by attribute resolver
663 class SessionReportPrinter : ReportPrinter
665 List<AbstractMessage> session_messages;
667 // A collection of exactly same messages reported in all sessions
669 List<AbstractMessage> common_messages;
672 // A collection of unique messages reported in all sessions
674 List<AbstractMessage> merged_messages;
676 public override void Print (AbstractMessage msg)
679 // This line is useful when debugging recorded messages
681 // Console.WriteLine ("RECORDING: {0}", msg.ToString ());
683 if (session_messages == null)
684 session_messages = new List<AbstractMessage> ();
686 session_messages.Add (msg);
691 public void EndSession ()
693 if (session_messages == null)
697 // Handles the first session
699 if (common_messages == null) {
700 common_messages = new List<AbstractMessage> (session_messages);
701 merged_messages = session_messages;
702 session_messages = null;
707 // Store common messages if any
709 for (int i = 0; i < common_messages.Count; ++i) {
710 AbstractMessage cmsg = common_messages[i];
711 bool common_msg_found = false;
712 foreach (AbstractMessage msg in session_messages) {
713 if (cmsg.Equals (msg)) {
714 common_msg_found = true;
719 if (!common_msg_found)
720 common_messages.RemoveAt (i);
724 // Merge session and previous messages
726 for (int i = 0; i < session_messages.Count; ++i) {
727 AbstractMessage msg = session_messages[i];
728 bool msg_found = false;
729 for (int ii = 0; ii < merged_messages.Count; ++ii) {
730 if (msg.Equals (merged_messages[ii])) {
737 merged_messages.Add (msg);
741 public bool IsEmpty {
743 return merged_messages == null && common_messages == null;
748 // Prints collected messages, common messages have a priority
750 public bool Merge (ReportPrinter dest)
752 var messages_to_print = merged_messages;
753 if (common_messages != null && common_messages.Count > 0) {
754 messages_to_print = common_messages;
757 if (messages_to_print == null)
760 bool error_msg = false;
761 foreach (AbstractMessage msg in messages_to_print) {
763 error_msg |= !msg.IsWarning;
770 class StreamReportPrinter : ReportPrinter
772 readonly TextWriter writer;
774 public StreamReportPrinter (TextWriter writer)
776 this.writer = writer;
779 public override void Print (AbstractMessage msg)
786 class ConsoleReportPrinter : StreamReportPrinter
788 static readonly string prefix, postfix;
790 static ConsoleReportPrinter ()
792 string term = Environment.GetEnvironmentVariable ("TERM");
793 bool xterm_colors = false;
799 if (Environment.GetEnvironmentVariable ("COLORTERM") != null){
811 if (!(UnixUtils.isatty (1) && UnixUtils.isatty (2)))
814 string config = Environment.GetEnvironmentVariable ("MCS_COLORS");
816 config = "errors=red";
817 //config = "brightwhite,red";
820 if (config == "disable")
823 if (!config.StartsWith ("errors="))
826 config = config.Substring (7);
828 int p = config.IndexOf (",");
830 prefix = GetForeground (config);
832 prefix = GetBackground (config.Substring (p+1)) + GetForeground (config.Substring (0, p));
833 postfix = "\x001b[0m";
836 public ConsoleReportPrinter ()
837 : base (Console.Error)
841 public ConsoleReportPrinter (TextWriter writer)
846 public int Fatal { get; set; }
848 static int NameToCode (string s)
873 // maps a color name to its xterm color code
875 static string GetForeground (string s)
879 if (s.StartsWith ("bright")) {
885 return "\x001b[" + highcode + (30 + NameToCode (s)).ToString () + "m";
888 static string GetBackground (string s)
890 return "\x001b[" + (40 + NameToCode (s)).ToString () + "m";
893 protected override string FormatText (string txt)
896 return prefix + txt + postfix;
901 static string FriendlyStackTrace (StackTrace t)
903 StringBuilder sb = new StringBuilder ();
905 bool foundUserCode = false;
907 for (int i = 0; i < t.FrameCount; i++) {
908 StackFrame f = t.GetFrame (i);
909 MethodBase mb = f.GetMethod ();
911 if (!foundUserCode && mb.ReflectedType == typeof (Report))
914 foundUserCode = true;
918 if (f.GetFileLineNumber () > 0)
919 sb.AppendFormat ("(at {0}:{1}) ", f.GetFileName (), f.GetFileLineNumber ());
921 sb.AppendFormat ("{0}.{1} (", mb.ReflectedType.Name, mb.Name);
924 foreach (ParameterInfo pi in mb.GetParameters ()) {
929 sb.Append (pi.ParameterType.FullName);
934 return sb.ToString ();
938 public override void Print (AbstractMessage msg)
943 Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
945 if (++print_count == Fatal)
946 throw new Exception (msg.Text);
949 public static string FriendlyStackTrace (Exception e)
951 return FriendlyStackTrace (new StackTrace (e, true));
954 public static void StackTrace ()
956 Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
960 public enum TimerType {
970 public enum CounterType {
979 static DateTime[] timer_start;
980 static TimeSpan[] timers;
981 static long[] timer_counters;
982 static long[] counters;
986 timer_start = new DateTime [(int) TimerType.CountTimers];
987 timers = new TimeSpan [(int) TimerType.CountTimers];
988 timer_counters = new long [(int) TimerType.CountTimers];
989 counters = new long [(int) CounterType.CountCounters];
991 for (int i = 0; i < (int) TimerType.CountTimers; i++) {
992 timer_start [i] = DateTime.Now;
993 timers [i] = TimeSpan.Zero;
997 [Conditional("TIMER")]
998 static public void IncrementCounter (CounterType which)
1000 ++counters [(int) which];
1003 [Conditional("TIMER")]
1004 static public void StartTimer (TimerType which)
1006 timer_start [(int) which] = DateTime.Now;
1009 [Conditional("TIMER")]
1010 static public void StopTimer (TimerType which)
1012 timers [(int) which] += DateTime.Now - timer_start [(int) which];
1013 ++timer_counters [(int) which];
1016 [Conditional("TIMER")]
1017 static public void ShowTimers ()
1019 ShowTimer (TimerType.FindMembers, "- FindMembers timer");
1020 ShowTimer (TimerType.TcFindMembers, "- TypeContainer.FindMembers timer");
1021 ShowTimer (TimerType.MemberLookup, "- MemberLookup timer");
1022 ShowTimer (TimerType.CachedLookup, "- CachedLookup timer");
1023 ShowTimer (TimerType.CacheInit, "- Cache init");
1024 ShowTimer (TimerType.MiscTimer, "- Misc timer");
1026 ShowCounter (CounterType.FindMembers, "- Find members");
1027 ShowCounter (CounterType.MemberCache, "- Member cache");
1028 ShowCounter (CounterType.MiscCounter, "- Misc counter");
1031 static public void ShowCounter (CounterType which, string msg)
1033 Console.WriteLine ("{0} {1}", counters [(int) which], msg);
1036 static public void ShowTimer (TimerType which, string msg)
1039 "[{0:00}:{1:000}] {2} (used {3} times)",
1040 (int) timers [(int) which].TotalSeconds,
1041 timers [(int) which].Milliseconds, msg,
1042 timer_counters [(int) which]);
1046 public class InternalErrorException : Exception {
1047 public InternalErrorException (MemberCore mc, Exception e)
1048 : base (mc.Location + " " + mc.GetSignatureForError (), e)
1052 public InternalErrorException ()
1053 : base ("Internal error")
1057 public InternalErrorException (string message)
1062 public InternalErrorException (string message, params object[] args)
1063 : base (String.Format (message, args))
1067 public InternalErrorException (Exception exception, string message, params object[] args)
1068 : base (String.Format (message, args), exception)
1072 public InternalErrorException (Exception e, Location loc)
1073 : base (loc.ToString (), e)
1079 /// Handles #pragma warning
1081 public class WarningRegions {
1083 abstract class PragmaCmd
1087 protected PragmaCmd (int line)
1092 public abstract bool IsEnabled (int code, bool previous);
1095 class Disable : PragmaCmd
1098 public Disable (int line, int code)
1104 public override bool IsEnabled (int code, bool previous)
1106 return this.code == code ? false : previous;
1110 class DisableAll : PragmaCmd
1112 public DisableAll (int line)
1115 public override bool IsEnabled(int code, bool previous)
1121 class Enable : PragmaCmd
1124 public Enable (int line, int code)
1130 public override bool IsEnabled(int code, bool previous)
1132 return this.code == code ? true : previous;
1136 class EnableAll : PragmaCmd
1138 public EnableAll (int line)
1141 public override bool IsEnabled(int code, bool previous)
1148 List<PragmaCmd> regions = new List<PragmaCmd> ();
1150 public void WarningDisable (int line)
1152 regions.Add (new DisableAll (line));
1155 public void WarningDisable (Location location, int code, Report Report)
1157 if (Report.CheckWarningCode (code, location))
1158 regions.Add (new Disable (location.Row, code));
1161 public void WarningEnable (int line)
1163 regions.Add (new EnableAll (line));
1166 public void WarningEnable (Location location, int code, Report Report)
1168 if (Report.CheckWarningCode (code, location))
1169 regions.Add (new Enable (location.Row, code));
1172 public bool IsWarningEnabled (int code, int src_line)
1175 foreach (PragmaCmd pragma in regions) {
1176 if (src_line < pragma.Line)
1179 result = pragma.IsEnabled (code, result);