2 // report.cs: report errors and warnings.
4 // Author: Miguel de Icaza (miguel@ximian.com)
5 // Marek Safar (marek.safar@gmail.com)
7 // Copyright 2001 Ximian, Inc. (http://www.ximian.com)
8 // Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
14 using System.Collections.Generic;
15 using System.Diagnostics;
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 const int RuntimeErrorId = 10000;
34 // Keeps track of the warnings that we are ignoring
36 HashSet<int> warning_ignore_table;
38 Dictionary<int, 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, 437, 440, 458, 464, 465, 467, 469, 472, 473,
59 612, 618, 626, 628, 642, 649, 652, 657, 658, 659, 660, 661, 665, 672, 675, 693,
62 1030, 1058, 1060, 1066,
63 1522, 1570, 1571, 1572, 1573, 1574, 1580, 1581, 1584, 1587, 1589, 1590, 1591, 1592,
64 1607, 1616, 1633, 1634, 1635, 1685, 1690, 1691, 1692, 1695, 1696, 1699,
65 1700, 1701, 1702, 1709, 1711, 1717, 1718, 1720, 1735,
66 1901, 1956, 1981, 1998,
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
73 static HashSet<int> AllWarningsHashSet;
75 public Report (ReportPrinter printer)
78 throw new ArgumentNullException ("printer");
80 this.printer = printer;
84 public void DisableReporting ()
89 public void EnableReporting ()
94 public void FeatureIsNotAvailable (CompilerContext compiler, Location loc, string feature)
97 switch (compiler.Settings.Version) {
98 case LanguageVersion.ISO_1:
101 case LanguageVersion.ISO_2:
104 case LanguageVersion.V_3:
107 case LanguageVersion.V_4:
110 case LanguageVersion.V_5:
114 throw new InternalErrorException ("Invalid feature version", compiler.Settings.Version);
118 "Feature `{0}' cannot be used because it is not part of the C# {1} language specification",
122 public void FeatureIsNotSupported (Location loc, string feature)
125 "Feature `{0}' is not supported in Mono mcs1 compiler. Consider using the `gmcs' compiler instead",
129 bool IsWarningEnabled (int code, int level, Location loc)
131 if (WarningLevel < level)
134 if (IsWarningDisabledGlobally (code))
137 if (warning_regions_table == null || loc.IsNull)
140 WarningRegions regions;
141 if (!warning_regions_table.TryGetValue (loc.File, out regions))
144 return regions.IsWarningEnabled (code, loc.Row);
147 public bool IsWarningDisabledGlobally (int code)
149 return warning_ignore_table != null && warning_ignore_table.Contains (code);
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 ());
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);
195 if (ms.DeclaringType != null)
196 ms = ms.DeclaringType;
198 var imported_type = ms.MemberDefinition as ImportedTypeDefinition;
199 if (imported_type != null) {
200 var iad = imported_type.DeclaringAssembly as ImportedAssemblyDefinition;
201 SymbolRelatedToPreviousError (iad.Location);
206 public void SymbolRelatedToPreviousError (MemberCore mc)
208 SymbolRelatedToPreviousError (mc.Location, mc.GetSignatureForError ());
211 public void SymbolRelatedToPreviousError (string loc)
213 string msg = String.Format ("{0} (Location of the symbol related to previous ", loc);
214 if (extra_information.Contains (msg))
217 extra_information.Add (msg);
220 public void AddWarningAsError (string warningId)
224 id = int.Parse (warningId);
226 CheckWarningCode (warningId, Location.Null);
230 if (!CheckWarningCode (id, Location.Null))
233 if (warnings_as_error == null)
234 warnings_as_error = new List<int> ();
236 warnings_as_error.Add (id);
239 public void RemoveWarningAsError (string warningId)
243 id = int.Parse (warningId);
245 CheckWarningCode (warningId, Location.Null);
249 if (!CheckWarningCode (id, Location.Null))
252 if (warnings_only == null)
253 warnings_only = new List<int> ();
255 warnings_only.Add (id);
258 public bool CheckWarningCode (string code, Location loc)
260 Warning (1691, 1, loc, "`{0}' is not a valid warning number", code);
264 public bool CheckWarningCode (int code, Location loc)
266 if (AllWarningsHashSet == null)
267 AllWarningsHashSet = new HashSet<int> (AllWarnings);
269 if (AllWarningsHashSet.Contains (code))
272 return CheckWarningCode (code.ToString (), loc);
275 public void ExtraInformation (Location loc, string msg)
277 extra_information.Add (String.Format ("{0} {1}", loc, msg));
280 public WarningRegions RegisterWarningRegion (Location location)
282 WarningRegions regions;
283 if (warning_regions_table == null) {
285 warning_regions_table = new Dictionary<int, WarningRegions> ();
287 warning_regions_table.TryGetValue (location.File, out regions);
290 if (regions == null) {
291 regions = new WarningRegions ();
292 warning_regions_table.Add (location.File, regions);
298 public void Warning (int code, int level, Location loc, string message)
300 if (reporting_disabled > 0)
303 if (!IsWarningEnabled (code, level, loc))
307 if (IsWarningAsError (code)) {
308 message = "Warning as Error: " + message;
309 msg = new ErrorMessage (code, loc, message, extra_information);
311 msg = new WarningMessage (code, loc, message, extra_information);
314 extra_information.Clear ();
318 public void Warning (int code, int level, Location loc, string format, string arg)
320 Warning (code, level, loc, String.Format (format, arg));
323 public void Warning (int code, int level, Location loc, string format, string arg1, string arg2)
325 Warning (code, level, loc, String.Format (format, arg1, arg2));
328 public void Warning (int code, int level, Location loc, string format, params object[] args)
330 Warning (code, level, loc, String.Format (format, args));
333 public void Warning (int code, int level, string message)
335 Warning (code, level, Location.Null, message);
338 public void Warning (int code, int level, string format, string arg)
340 Warning (code, level, Location.Null, format, arg);
343 public void Warning (int code, int level, string format, string arg1, string arg2)
345 Warning (code, level, Location.Null, format, arg1, arg2);
348 public void Warning (int code, int level, string format, params string[] args)
350 Warning (code, level, Location.Null, String.Format (format, args));
354 // Warnings encountered so far
356 public int Warnings {
357 get { return printer.WarningsCount; }
360 public void Error (int code, Location loc, string error)
362 if (reporting_disabled > 0)
365 ErrorMessage msg = new ErrorMessage (code, loc, error, extra_information);
366 extra_information.Clear ();
371 public void Error (int code, Location loc, string format, string arg)
373 Error (code, loc, String.Format (format, arg));
376 public void Error (int code, Location loc, string format, string arg1, string arg2)
378 Error (code, loc, String.Format (format, arg1, arg2));
381 public void Error (int code, Location loc, string format, params string[] args)
383 Error (code, loc, String.Format (format, args));
386 public void Error (int code, string error)
388 Error (code, Location.Null, error);
391 public void Error (int code, string format, string arg)
393 Error (code, Location.Null, format, arg);
396 public void Error (int code, string format, string arg1, string arg2)
398 Error (code, Location.Null, format, arg1, arg2);
401 public void Error (int code, string format, params string[] args)
403 Error (code, Location.Null, String.Format (format, args));
407 // Errors encountered so far
410 get { return printer.ErrorsCount; }
413 public bool IsDisabled {
415 return reporting_disabled > 0;
419 public ReportPrinter Printer {
420 get { return printer; }
423 public void SetIgnoreWarning (int code)
425 if (warning_ignore_table == null)
426 warning_ignore_table = new HashSet<int> ();
428 warning_ignore_table.Add (code);
431 public ReportPrinter SetPrinter (ReportPrinter printer)
433 ReportPrinter old = this.printer;
434 this.printer = printer;
438 public int WarningLevel {
440 return warning_level;
443 warning_level = value;
447 [Conditional ("MCS_DEBUG")]
448 static public void Debug (string message, params object[] args)
450 Debug (4, message, args);
453 [Conditional ("MCS_DEBUG")]
454 static public void Debug (int category, string message, params object[] args)
456 // if ((category & DebugFlags) == 0)
459 StringBuilder sb = new StringBuilder (message);
461 if ((args != null) && (args.Length > 0)) {
465 foreach (object arg in args) {
472 // else if (arg is ICollection)
473 // sb.Append (PrintCollection ((ICollection) arg));
479 Console.WriteLine (sb.ToString ());
482 static public string PrintCollection (ICollection collection)
484 StringBuilder sb = new StringBuilder ();
486 sb.Append (collection.GetType ());
490 foreach (object o in collection) {
499 return sb.ToString ();
504 public abstract class AbstractMessage
506 readonly string[] extra_info;
507 protected readonly int code;
508 protected readonly Location location;
509 readonly string message;
511 protected AbstractMessage (int code, Location loc, string msg, List<string> extraInfo)
515 this.code = 8000 - code;
519 if (extraInfo.Count != 0) {
520 this.extra_info = extraInfo.ToArray ();
524 protected AbstractMessage (AbstractMessage aMsg)
526 this.code = aMsg.code;
527 this.location = aMsg.location;
528 this.message = aMsg.message;
529 this.extra_info = aMsg.extra_info;
536 public override bool Equals (object obj)
538 AbstractMessage msg = obj as AbstractMessage;
542 return code == msg.code && location.Equals (msg.location) && message == msg.message;
545 public override int GetHashCode ()
547 return code.GetHashCode ();
550 public abstract bool IsWarning { get; }
552 public Location Location {
553 get { return location; }
556 public abstract string MessageType { get; }
558 public string[] RelatedSymbols {
559 get { return extra_info; }
563 get { return message; }
567 sealed class WarningMessage : AbstractMessage
569 public WarningMessage (int code, Location loc, string message, List<string> extra_info)
570 : base (code, loc, message, extra_info)
574 public override bool IsWarning {
578 public override string MessageType {
585 sealed class ErrorMessage : AbstractMessage
587 public ErrorMessage (int code, Location loc, string message, List<string> extraInfo)
588 : base (code, loc, message, extraInfo)
592 public ErrorMessage (AbstractMessage aMsg)
597 public override bool IsWarning {
598 get { return false; }
601 public override string MessageType {
609 // Generic base for any message writer
611 public abstract class ReportPrinter
615 public int FatalCounter { get; set; }
617 public int ErrorsCount { get; protected set; }
619 public bool ShowFullPaths { get; set; }
622 // Whether to dump a stack trace on errors.
624 public bool Stacktrace { get; set; }
626 public int WarningsCount { get; private set; }
629 // When (symbols related to previous ...) can be used
631 public virtual bool HasRelatedSymbolSupport {
638 protected virtual string FormatText (string txt)
643 public virtual void Print (AbstractMessage msg)
650 if (ErrorsCount == FatalCounter)
651 throw new Exception (msg.Text);
655 protected void Print (AbstractMessage msg, TextWriter output)
657 StringBuilder txt = new StringBuilder ();
658 if (!msg.Location.IsNull) {
660 txt.Append (msg.Location.ToStringFullName ());
662 txt.Append (msg.Location.ToString ());
667 txt.AppendFormat ("{0} CS{1:0000}: {2}", msg.MessageType, msg.Code, msg.Text);
670 output.WriteLine (FormatText (txt.ToString ()));
672 output.WriteLine (txt.ToString ());
674 if (msg.RelatedSymbols != null) {
675 foreach (string s in msg.RelatedSymbols)
676 output.WriteLine (s + msg.MessageType + ")");
682 // HACK: Temporary hack for broken repl flow
683 ErrorsCount = WarningsCount = 0;
687 sealed class NullReportPrinter : ReportPrinter
692 // Default message recorder, it uses two types of message groups.
693 // Common messages: messages reported in all sessions.
694 // Merged messages: union of all messages in all sessions.
696 // Used by the Lambda expressions to compile the code with various
697 // parameter values, or by attribute resolver
699 class SessionReportPrinter : ReportPrinter
701 List<AbstractMessage> session_messages;
703 // A collection of exactly same messages reported in all sessions
705 List<AbstractMessage> common_messages;
708 // A collection of unique messages reported in all sessions
710 List<AbstractMessage> merged_messages;
712 public override void Print (AbstractMessage msg)
715 // This line is useful when debugging recorded messages
717 // Console.WriteLine ("RECORDING: {0}", msg.ToString ());
719 if (session_messages == null)
720 session_messages = new List<AbstractMessage> ();
722 session_messages.Add (msg);
727 public void EndSession ()
729 if (session_messages == null)
733 // Handles the first session
735 if (common_messages == null) {
736 common_messages = new List<AbstractMessage> (session_messages);
737 merged_messages = session_messages;
738 session_messages = null;
743 // Store common messages if any
745 for (int i = 0; i < common_messages.Count; ++i) {
746 AbstractMessage cmsg = common_messages[i];
747 bool common_msg_found = false;
748 foreach (AbstractMessage msg in session_messages) {
749 if (cmsg.Equals (msg)) {
750 common_msg_found = true;
755 if (!common_msg_found)
756 common_messages.RemoveAt (i);
760 // Merge session and previous messages
762 for (int i = 0; i < session_messages.Count; ++i) {
763 AbstractMessage msg = session_messages[i];
764 bool msg_found = false;
765 for (int ii = 0; ii < merged_messages.Count; ++ii) {
766 if (msg.Equals (merged_messages[ii])) {
773 merged_messages.Add (msg);
777 public bool IsEmpty {
779 return merged_messages == null && common_messages == null;
784 // Prints collected messages, common messages have a priority
786 public bool Merge (ReportPrinter dest)
788 var messages_to_print = merged_messages;
789 if (common_messages != null && common_messages.Count > 0) {
790 messages_to_print = common_messages;
793 if (messages_to_print == null)
796 bool error_msg = false;
797 foreach (AbstractMessage msg in messages_to_print) {
799 error_msg |= !msg.IsWarning;
806 public class StreamReportPrinter : ReportPrinter
808 readonly TextWriter writer;
810 public StreamReportPrinter (TextWriter writer)
812 this.writer = writer;
815 public override void Print (AbstractMessage msg)
822 public class ConsoleReportPrinter : StreamReportPrinter
824 static readonly string prefix, postfix;
826 static ConsoleReportPrinter ()
828 string term = Environment.GetEnvironmentVariable ("TERM");
829 bool xterm_colors = false;
835 if (Environment.GetEnvironmentVariable ("COLORTERM") != null){
841 case "xterm-256color":
848 if (!(UnixUtils.isatty (1) && UnixUtils.isatty (2)))
851 string config = Environment.GetEnvironmentVariable ("MCS_COLORS");
853 config = "errors=red";
854 //config = "brightwhite,red";
857 if (config == "disable")
860 if (!config.StartsWith ("errors="))
863 config = config.Substring (7);
865 int p = config.IndexOf (",");
867 prefix = GetForeground (config);
869 prefix = GetBackground (config.Substring (p+1)) + GetForeground (config.Substring (0, p));
870 postfix = "\x001b[0m";
873 public ConsoleReportPrinter ()
874 : base (Console.Error)
878 public ConsoleReportPrinter (TextWriter writer)
883 static int NameToCode (string s)
908 // maps a color name to its xterm color code
910 static string GetForeground (string s)
914 if (s.StartsWith ("bright")) {
920 return "\x001b[" + highcode + (30 + NameToCode (s)).ToString () + "m";
923 static string GetBackground (string s)
925 return "\x001b[" + (40 + NameToCode (s)).ToString () + "m";
928 protected override string FormatText (string txt)
931 return prefix + txt + postfix;
936 static string FriendlyStackTrace (StackTrace t)
938 StringBuilder sb = new StringBuilder ();
940 bool foundUserCode = false;
942 for (int i = 0; i < t.FrameCount; i++) {
943 StackFrame f = t.GetFrame (i);
944 var mb = f.GetMethod ();
946 if (!foundUserCode && mb.ReflectedType == typeof (Report))
949 foundUserCode = true;
953 if (f.GetFileLineNumber () > 0)
954 sb.AppendFormat ("(at {0}:{1}) ", f.GetFileName (), f.GetFileLineNumber ());
956 sb.AppendFormat ("{0}.{1} (", mb.ReflectedType.Name, mb.Name);
959 foreach (var pi in mb.GetParameters ()) {
964 sb.Append (pi.ParameterType.FullName);
969 return sb.ToString ();
972 public override void Print (AbstractMessage msg)
977 Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
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)));
993 public enum TimerType
996 AssemblyBuilderSetup,
1000 PredefinedTypesInit,
1001 ModuleDefinitionTotal,
1009 readonly Stopwatch[] timers;
1012 public TimeReporter (bool enabled)
1017 timers = new Stopwatch[System.Enum.GetValues(typeof (TimerType)).Length];
1020 public void Start (TimerType type)
1022 if (timers != null) {
1023 var sw = new Stopwatch ();
1024 timers[(int) type] = sw;
1029 public void StartTotal ()
1031 total = new Stopwatch ();
1035 public void Stop (TimerType type)
1037 if (timers != null) {
1038 timers[(int) type].Stop ();
1042 public void StopTotal ()
1047 public void ShowStats ()
1052 Dictionary<TimerType, string> timer_names = new Dictionary<TimerType,string> () {
1053 { TimerType.ParseTotal, "Parsing source files" },
1054 { TimerType.AssemblyBuilderSetup, "Assembly builder setup" },
1055 { TimerType.CreateTypeTotal, "Compiled types created" },
1056 { TimerType.ReferencesLoading, "Referenced assemblies loading" },
1057 { TimerType.ReferencesImporting, "Referenced assemblies importing" },
1058 { TimerType.PredefinedTypesInit, "Predefined types initialization" },
1059 { TimerType.ModuleDefinitionTotal, "Module definition" },
1060 { TimerType.EmitTotal, "Resolving and emitting members blocks" },
1061 { TimerType.CloseTypes, "Module types closed" },
1062 { TimerType.Resouces, "Embedding resources" },
1063 { TimerType.OutputSave, "Writing output file" },
1064 { TimerType.DebugSave, "Writing debug symbols file" },
1068 double percentage = (double) total.ElapsedMilliseconds / 100;
1069 long subtotal = total.ElapsedMilliseconds;
1070 foreach (var timer in timers) {
1071 string msg = timer_names[(TimerType) counter++];
1072 var ms = timer == null ? 0 : timer.ElapsedMilliseconds;
1073 Console.WriteLine ("{0,4:0.0}% {1,5}ms {2}", ms / percentage, ms, msg);
1077 Console.WriteLine ("{0,4:0.0}% {1,5}ms Other tasks", subtotal / percentage, subtotal);
1078 Console.WriteLine ();
1079 Console.WriteLine ("Total elapsed time: {0}", total.Elapsed);
1083 public class InternalErrorException : Exception {
1084 public InternalErrorException (MemberCore mc, Exception e)
1085 : base (mc.Location + " " + mc.GetSignatureForError (), e)
1089 public InternalErrorException ()
1090 : base ("Internal error")
1094 public InternalErrorException (string message)
1099 public InternalErrorException (string message, params object[] args)
1100 : base (String.Format (message, args))
1104 public InternalErrorException (Exception exception, string message, params object[] args)
1105 : base (String.Format (message, args), exception)
1109 public InternalErrorException (Exception e, Location loc)
1110 : base (loc.ToString (), e)
1116 /// Handles #pragma warning
1118 public class WarningRegions {
1120 abstract class PragmaCmd
1124 protected PragmaCmd (int line)
1129 public abstract bool IsEnabled (int code, bool previous);
1132 class Disable : PragmaCmd
1135 public Disable (int line, int code)
1141 public override bool IsEnabled (int code, bool previous)
1143 return this.code == code ? false : previous;
1147 class DisableAll : PragmaCmd
1149 public DisableAll (int line)
1152 public override bool IsEnabled(int code, bool previous)
1158 class Enable : PragmaCmd
1161 public Enable (int line, int code)
1167 public override bool IsEnabled(int code, bool previous)
1169 return this.code == code ? true : previous;
1173 class EnableAll : PragmaCmd
1175 public EnableAll (int line)
1178 public override bool IsEnabled(int code, bool previous)
1185 List<PragmaCmd> regions = new List<PragmaCmd> ();
1187 public void WarningDisable (int line)
1189 regions.Add (new DisableAll (line));
1192 public void WarningDisable (Location location, int code, Report Report)
1194 if (Report.CheckWarningCode (code, location))
1195 regions.Add (new Disable (location.Row, code));
1198 public void WarningEnable (int line)
1200 regions.Add (new EnableAll (line));
1203 public void WarningEnable (Location location, int code, Report Report)
1205 if (!Report.CheckWarningCode (code, location))
1208 if (Report.IsWarningDisabledGlobally (code))
1209 Report.Warning (1635, 1, location, "Cannot restore warning `CS{0:0000}' because it was disabled globally", code);
1211 regions.Add (new Enable (location.Row, code));
1214 public bool IsWarningEnabled (int code, int src_line)
1217 foreach (PragmaCmd pragma in regions) {
1218 if (src_line < pragma.Line)
1221 result = pragma.IsEnabled (code, result);