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 (MemberInfo mi)
184 if (reporting_disabled > 0 || !printer.HasRelatedSymbolSupport)
187 Type dt = TypeManager.DropGenericTypeArguments (mi.DeclaringType);
188 if (TypeManager.IsDelegateType (dt)) {
189 SymbolRelatedToPreviousError (dt);
193 DeclSpace temp_ds = TypeManager.LookupDeclSpace (dt);
194 if (temp_ds == null) {
195 SymbolRelatedToPreviousError (dt.Assembly.Location, TypeManager.GetFullNameSignature (mi));
197 MethodBase mb = mi as MethodBase;
199 mb = TypeManager.DropGenericMethodArguments (mb);
200 IMethodData md = TypeManager.GetMethod (mb);
202 SymbolRelatedToPreviousError (md.Location, md.GetSignatureForError ());
207 // FIXME: Completely wrong, it has to use FindMembers
208 MemberCore mc = temp_ds.GetDefinition (mi.Name);
210 SymbolRelatedToPreviousError (mc);
214 public void SymbolRelatedToPreviousError (MemberCore mc)
216 SymbolRelatedToPreviousError (mc.Location, mc.GetSignatureForError ());
219 public void SymbolRelatedToPreviousError (Type type)
221 if (reporting_disabled > 0 || !printer.HasRelatedSymbolSupport)
224 type = TypeManager.DropGenericTypeArguments (type);
226 if (TypeManager.IsGenericParameter (type)) {
227 TypeParameter tp = TypeManager.LookupTypeParameter (type);
229 SymbolRelatedToPreviousError (tp.Location, "");
234 if (type is TypeBuilder) {
235 DeclSpace temp_ds = TypeManager.LookupDeclSpace (type);
236 SymbolRelatedToPreviousError (temp_ds.Location, TypeManager.CSharpName (type));
237 } else if (TypeManager.HasElementType (type)) {
238 SymbolRelatedToPreviousError (TypeManager.GetElementType (type));
240 SymbolRelatedToPreviousError (type.Assembly.Location, TypeManager.CSharpName (type));
244 void SymbolRelatedToPreviousError (string loc, string symbol)
246 string msg = String.Format ("{0} (Location of the symbol related to previous ", loc);
247 if (extra_information.Contains (msg))
250 extra_information.Add (msg);
253 public void AddWarningAsError (string warningId)
257 id = int.Parse (warningId);
262 if (!CheckWarningCode (id, warningId, Location.Null))
265 if (warnings_as_error == null)
266 warnings_as_error = new List<int> ();
268 warnings_as_error.Add (id);
271 public void RemoveWarningAsError (string warningId)
275 id = int.Parse (warningId);
280 if (!CheckWarningCode (id, warningId, Location.Null))
283 if (warnings_only == null)
284 warnings_only = new List<int> ();
286 warnings_only.Add (id);
289 public bool CheckWarningCode (int code, Location loc)
291 return CheckWarningCode (code, code.ToString (), loc);
294 public bool CheckWarningCode (int code, string scode, Location loc)
296 if (IsValidWarning (code))
299 Warning (1691, 1, loc, "`{0}' is not a valid warning number", scode);
303 public void ExtraInformation (Location loc, string msg)
305 extra_information.Add (String.Format ("{0} {1}", loc, msg));
308 public WarningRegions RegisterWarningRegion (Location location)
310 WarningRegions regions;
311 if (warning_regions_table == null) {
313 warning_regions_table = new Dictionary<string, WarningRegions> ();
315 warning_regions_table.TryGetValue (location.Name, out regions);
318 if (regions == null) {
319 regions = new WarningRegions ();
320 warning_regions_table.Add (location.Name, regions);
326 public void Warning (int code, int level, Location loc, string message)
328 if (reporting_disabled > 0)
331 if (!IsWarningEnabled (code, level, loc))
335 if (IsWarningAsError (code))
336 msg = new ErrorMessage (code, loc, message, extra_information);
338 msg = new WarningMessage (code, loc, message, extra_information);
340 extra_information.Clear ();
344 public void Warning (int code, int level, Location loc, string format, string arg)
346 Warning (code, level, loc, String.Format (format, arg));
349 public void Warning (int code, int level, Location loc, string format, string arg1, string arg2)
351 Warning (code, level, loc, String.Format (format, arg1, arg2));
354 public void Warning (int code, int level, Location loc, string format, params object[] args)
356 Warning (code, level, loc, String.Format (format, args));
359 public void Warning (int code, int level, string message)
361 Warning (code, level, Location.Null, message);
364 public void Warning (int code, int level, string format, string arg)
366 Warning (code, level, Location.Null, format, arg);
369 public void Warning (int code, int level, string format, string arg1, string arg2)
371 Warning (code, level, Location.Null, format, arg1, arg2);
374 public void Warning (int code, int level, string format, params string[] args)
376 Warning (code, level, Location.Null, String.Format (format, args));
380 // Warnings encountered so far
382 public int Warnings {
383 get { return printer.WarningsCount; }
386 public void Error (int code, Location loc, string error)
388 if (reporting_disabled > 0)
391 ErrorMessage msg = new ErrorMessage (code, loc, error, extra_information);
392 extra_information.Clear ();
397 public void Error (int code, Location loc, string format, string arg)
399 Error (code, loc, String.Format (format, arg));
402 public void Error (int code, Location loc, string format, string arg1, string arg2)
404 Error (code, loc, String.Format (format, arg1, arg2));
407 public void Error (int code, Location loc, string format, params object[] args)
409 Error (code, loc, String.Format (format, args));
412 public void Error (int code, string error)
414 Error (code, Location.Null, error);
417 public void Error (int code, string format, string arg)
419 Error (code, Location.Null, format, arg);
422 public void Error (int code, string format, string arg1, string arg2)
424 Error (code, Location.Null, format, arg1, arg2);
427 public void Error (int code, string format, params string[] args)
429 Error (code, Location.Null, String.Format (format, args));
433 // Errors encountered so far
436 get { return printer.ErrorsCount; }
439 public ReportPrinter Printer {
440 get { return printer; }
443 public void SetIgnoreWarning (int code)
445 if (warning_ignore_table == null)
446 warning_ignore_table = new Dictionary<int, bool> ();
448 warning_ignore_table [code] = true;
451 public ReportPrinter SetPrinter (ReportPrinter printer)
453 ReportPrinter old = this.printer;
454 this.printer = printer;
458 public int WarningLevel {
460 return warning_level;
463 warning_level = value;
467 [Conditional ("MCS_DEBUG")]
468 static public void Debug (string message, params object[] args)
470 Debug (4, message, args);
473 [Conditional ("MCS_DEBUG")]
474 static public void Debug (int category, string message, params object[] args)
476 if ((category & DebugFlags) == 0)
479 StringBuilder sb = new StringBuilder (message);
481 if ((args != null) && (args.Length > 0)) {
485 foreach (object arg in args) {
492 // else if (arg is ICollection)
493 // sb.Append (PrintCollection ((ICollection) arg));
499 Console.WriteLine (sb.ToString ());
502 static public string PrintCollection (ICollection collection)
504 StringBuilder sb = new StringBuilder ();
506 sb.Append (collection.GetType ());
510 foreach (object o in collection) {
519 return sb.ToString ();
524 public abstract class AbstractMessage
526 readonly string[] extra_info;
527 protected readonly int code;
528 protected readonly Location location;
529 readonly string message;
531 protected AbstractMessage (int code, Location loc, string msg, List<string> extraInfo)
535 this.code = 8000 - code;
539 if (extraInfo.Count != 0) {
540 this.extra_info = extraInfo.ToArray ();
544 protected AbstractMessage (AbstractMessage aMsg)
546 this.code = aMsg.code;
547 this.location = aMsg.location;
548 this.message = aMsg.message;
549 this.extra_info = aMsg.extra_info;
556 public override bool Equals (object obj)
558 AbstractMessage msg = obj as AbstractMessage;
562 return code == msg.code && location.Equals (msg.location) && message == msg.message;
565 public override int GetHashCode ()
567 return code.GetHashCode ();
570 public abstract bool IsWarning { get; }
572 public Location Location {
573 get { return location; }
576 public abstract string MessageType { get; }
578 public string[] RelatedSymbols {
579 get { return extra_info; }
583 get { return message; }
587 sealed class WarningMessage : AbstractMessage
589 public WarningMessage (int code, Location loc, string message, List<string> extra_info)
590 : base (code, loc, message, extra_info)
594 public override bool IsWarning {
598 public override string MessageType {
605 sealed class ErrorMessage : AbstractMessage
607 public ErrorMessage (int code, Location loc, string message, List<string> extraInfo)
608 : base (code, loc, message, extraInfo)
612 public ErrorMessage (AbstractMessage aMsg)
617 public override bool IsWarning {
618 get { return false; }
621 public override string MessageType {
629 // Generic base for any message writer
631 public abstract class ReportPrinter {
633 /// Whether to dump a stack trace on errors.
635 public bool Stacktrace;
637 int warnings, errors;
639 public int WarningsCount {
640 get { return warnings; }
643 public int ErrorsCount {
644 get { return errors; }
647 protected virtual string FormatText (string txt)
653 // When (symbols related to previous ...) can be used
655 public virtual bool HasRelatedSymbolSupport {
659 public virtual void Print (AbstractMessage msg)
667 protected void Print (AbstractMessage msg, TextWriter output)
669 StringBuilder txt = new StringBuilder ();
670 if (!msg.Location.IsNull) {
671 txt.Append (msg.Location.ToString ());
675 txt.AppendFormat ("{0} CS{1:0000}: {2}", msg.MessageType, msg.Code, msg.Text);
678 output.WriteLine (FormatText (txt.ToString ()));
680 output.WriteLine (txt.ToString ());
682 if (msg.RelatedSymbols != null) {
683 foreach (string s in msg.RelatedSymbols)
684 output.WriteLine (s + msg.MessageType + ")");
690 // Default message recorder, it uses two types of message groups.
691 // Common messages: messages reported in all sessions.
692 // Merged messages: union of all messages in all sessions.
694 // Used by the Lambda expressions to compile the code with various
695 // parameter values, or by attribute resolver
697 class SessionReportPrinter : ReportPrinter
699 List<AbstractMessage> session_messages;
701 // A collection of exactly same messages reported in all sessions
703 List<AbstractMessage> common_messages;
706 // A collection of unique messages reported in all sessions
708 List<AbstractMessage> merged_messages;
710 public override void Print (AbstractMessage msg)
713 // This line is useful when debugging recorded messages
715 // Console.WriteLine ("RECORDING: {0} {1} {2}", code, location, message);
717 if (session_messages == null)
718 session_messages = new List<AbstractMessage> ();
720 session_messages.Add (msg);
725 public void EndSession ()
727 if (session_messages == null)
731 // Handles the first session
733 if (common_messages == null) {
734 common_messages = new List<AbstractMessage> (session_messages);
735 merged_messages = session_messages;
736 session_messages = null;
741 // Store common messages if any
743 for (int i = 0; i < common_messages.Count; ++i) {
744 AbstractMessage cmsg = (AbstractMessage) common_messages[i];
745 bool common_msg_found = false;
746 foreach (AbstractMessage msg in session_messages) {
747 if (cmsg.Equals (msg)) {
748 common_msg_found = true;
753 if (!common_msg_found)
754 common_messages.RemoveAt (i);
758 // Merge session and previous messages
760 for (int i = 0; i < session_messages.Count; ++i) {
761 AbstractMessage msg = (AbstractMessage) session_messages[i];
762 bool msg_found = false;
763 for (int ii = 0; ii < merged_messages.Count; ++ii) {
764 if (msg.Equals (merged_messages[ii])) {
771 merged_messages.Add (msg);
775 public bool IsEmpty {
777 return merged_messages == null && common_messages == null;
782 // Prints collected messages, common messages have a priority
784 public bool Merge (ReportPrinter dest)
786 var messages_to_print = merged_messages;
787 if (common_messages != null && common_messages.Count > 0) {
788 messages_to_print = common_messages;
791 if (messages_to_print == null)
794 foreach (AbstractMessage msg in messages_to_print)
801 class StreamReportPrinter : ReportPrinter
803 readonly TextWriter writer;
805 public StreamReportPrinter (TextWriter writer)
807 this.writer = writer;
810 public override void Print (AbstractMessage msg)
817 class ConsoleReportPrinter : StreamReportPrinter
819 static readonly string prefix, postfix;
821 static ConsoleReportPrinter ()
823 string term = Environment.GetEnvironmentVariable ("TERM");
824 bool xterm_colors = false;
830 if (Environment.GetEnvironmentVariable ("COLORTERM") != null){
842 if (!(UnixUtils.isatty (1) && UnixUtils.isatty (2)))
845 string config = Environment.GetEnvironmentVariable ("MCS_COLORS");
847 config = "errors=red";
848 //config = "brightwhite,red";
851 if (config == "disable")
854 if (!config.StartsWith ("errors="))
857 config = config.Substring (7);
859 int p = config.IndexOf (",");
861 prefix = GetForeground (config);
863 prefix = GetBackground (config.Substring (p+1)) + GetForeground (config.Substring (0, p));
864 postfix = "\x001b[0m";
867 public ConsoleReportPrinter ()
868 : base (Console.Error)
872 public ConsoleReportPrinter (TextWriter writer)
877 public int Fatal { get; set; }
879 static int NameToCode (string s)
904 // maps a color name to its xterm color code
906 static string GetForeground (string s)
910 if (s.StartsWith ("bright")) {
916 return "\x001b[" + highcode + (30 + NameToCode (s)).ToString () + "m";
919 static string GetBackground (string s)
921 return "\x001b[" + (40 + NameToCode (s)).ToString () + "m";
924 protected override string FormatText (string txt)
927 return prefix + txt + postfix;
932 static string FriendlyStackTrace (StackTrace t)
934 StringBuilder sb = new StringBuilder ();
936 bool foundUserCode = false;
938 for (int i = 0; i < t.FrameCount; i++) {
939 StackFrame f = t.GetFrame (i);
940 MethodBase mb = f.GetMethod ();
942 if (!foundUserCode && mb.ReflectedType == typeof (Report))
945 foundUserCode = true;
949 if (f.GetFileLineNumber () > 0)
950 sb.AppendFormat ("(at {0}:{1}) ", f.GetFileName (), f.GetFileLineNumber ());
952 sb.AppendFormat ("{0}.{1} (", mb.ReflectedType.Name, mb.Name);
955 foreach (ParameterInfo pi in mb.GetParameters ()) {
960 sb.Append (TypeManager.CSharpName (pi.ParameterType));
965 return sb.ToString ();
969 public override void Print (AbstractMessage msg)
974 Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
976 if (++print_count == Fatal)
977 throw new Exception (msg.Text);
980 public static string FriendlyStackTrace (Exception e)
982 return FriendlyStackTrace (new StackTrace (e, true));
985 public static void StackTrace ()
987 Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
991 public enum TimerType {
1001 public enum CounterType {
1010 static DateTime[] timer_start;
1011 static TimeSpan[] timers;
1012 static long[] timer_counters;
1013 static long[] counters;
1017 timer_start = new DateTime [(int) TimerType.CountTimers];
1018 timers = new TimeSpan [(int) TimerType.CountTimers];
1019 timer_counters = new long [(int) TimerType.CountTimers];
1020 counters = new long [(int) CounterType.CountCounters];
1022 for (int i = 0; i < (int) TimerType.CountTimers; i++) {
1023 timer_start [i] = DateTime.Now;
1024 timers [i] = TimeSpan.Zero;
1028 [Conditional("TIMER")]
1029 static public void IncrementCounter (CounterType which)
1031 ++counters [(int) which];
1034 [Conditional("TIMER")]
1035 static public void StartTimer (TimerType which)
1037 timer_start [(int) which] = DateTime.Now;
1040 [Conditional("TIMER")]
1041 static public void StopTimer (TimerType which)
1043 timers [(int) which] += DateTime.Now - timer_start [(int) which];
1044 ++timer_counters [(int) which];
1047 [Conditional("TIMER")]
1048 static public void ShowTimers ()
1050 ShowTimer (TimerType.FindMembers, "- FindMembers timer");
1051 ShowTimer (TimerType.TcFindMembers, "- TypeContainer.FindMembers timer");
1052 ShowTimer (TimerType.MemberLookup, "- MemberLookup timer");
1053 ShowTimer (TimerType.CachedLookup, "- CachedLookup timer");
1054 ShowTimer (TimerType.CacheInit, "- Cache init");
1055 ShowTimer (TimerType.MiscTimer, "- Misc timer");
1057 ShowCounter (CounterType.FindMembers, "- Find members");
1058 ShowCounter (CounterType.MemberCache, "- Member cache");
1059 ShowCounter (CounterType.MiscCounter, "- Misc counter");
1062 static public void ShowCounter (CounterType which, string msg)
1064 Console.WriteLine ("{0} {1}", counters [(int) which], msg);
1067 static public void ShowTimer (TimerType which, string msg)
1070 "[{0:00}:{1:000}] {2} (used {3} times)",
1071 (int) timers [(int) which].TotalSeconds,
1072 timers [(int) which].Milliseconds, msg,
1073 timer_counters [(int) which]);
1077 public class InternalErrorException : Exception {
1078 public InternalErrorException (MemberCore mc, Exception e)
1079 : base (mc.Location + " " + mc.GetSignatureForError (), e)
1083 public InternalErrorException ()
1084 : base ("Internal error")
1088 public InternalErrorException (string message)
1093 public InternalErrorException (string message, params object[] args)
1094 : base (String.Format (message, args))
1097 public InternalErrorException (Exception e, Location loc)
1098 : base (loc.ToString (), e)
1104 /// Handles #pragma warning
1106 public class WarningRegions {
1108 abstract class PragmaCmd
1112 protected PragmaCmd (int line)
1117 public abstract bool IsEnabled (int code, bool previous);
1120 class Disable : PragmaCmd
1123 public Disable (int line, int code)
1129 public override bool IsEnabled (int code, bool previous)
1131 return this.code == code ? false : previous;
1135 class DisableAll : PragmaCmd
1137 public DisableAll (int line)
1140 public override bool IsEnabled(int code, bool previous)
1146 class Enable : PragmaCmd
1149 public Enable (int line, int code)
1155 public override bool IsEnabled(int code, bool previous)
1157 return this.code == code ? true : previous;
1161 class EnableAll : PragmaCmd
1163 public EnableAll (int line)
1166 public override bool IsEnabled(int code, bool previous)
1173 List<PragmaCmd> regions = new List<PragmaCmd> ();
1175 public void WarningDisable (int line)
1177 regions.Add (new DisableAll (line));
1180 public void WarningDisable (Location location, int code, Report Report)
1182 if (Report.CheckWarningCode (code, location))
1183 regions.Add (new Disable (location.Row, code));
1186 public void WarningEnable (int line)
1188 regions.Add (new EnableAll (line));
1191 public void WarningEnable (Location location, int code, Report Report)
1193 if (Report.CheckWarningCode (code, location))
1194 regions.Add (new Enable (location.Row, code));
1197 public bool IsWarningEnabled (int code, int src_line)
1200 foreach (PragmaCmd pragma in regions) {
1201 if (src_line < pragma.Line)
1204 result = pragma.IsEnabled (code, result);