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;
16 namespace Mono.CSharp {
19 // Errors and warnings manager
24 /// Whether warnings should be considered errors
26 public bool WarningsAreErrors;
27 List<int> warnings_as_error;
28 List<int> warnings_only;
30 public const int RuntimeErrorId = 10000;
33 // Keeps track of the warnings that we are ignoring
35 HashSet<int> warning_ignore_table;
37 Dictionary<int, WarningRegions> warning_regions_table;
41 ReportPrinter printer;
43 int reporting_disabled;
46 /// List of symbols related to reported error/warning. You have to fill it before error/warning is reported.
48 List<string> extra_information = new List<string> ();
51 // IF YOU ADD A NEW WARNING YOU HAVE TO ADD ITS ID HERE
53 public static readonly int[] AllWarnings = new int[] {
55 105, 108, 109, 114, 162, 164, 168, 169, 183, 184, 197,
56 219, 251, 252, 253, 278, 282,
57 402, 414, 419, 420, 429, 436, 437, 440, 458, 464, 465, 467, 469, 472, 473,
58 612, 618, 626, 628, 642, 649, 652, 657, 658, 659, 660, 661, 665, 672, 675, 693,
62 1522, 1570, 1571, 1572, 1573, 1574, 1580, 1581, 1584, 1587, 1589, 1590, 1591, 1592,
63 1607, 1616, 1633, 1634, 1635, 1685, 1690, 1691, 1692, 1695, 1696, 1699,
64 1700, 1701, 1702, 1709, 1711, 1717, 1718, 1720, 1735,
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
72 static HashSet<int> AllWarningsHashSet;
74 public Report (ReportPrinter printer)
77 throw new ArgumentNullException ("printer");
79 this.printer = printer;
83 public void DisableReporting ()
88 public void EnableReporting ()
93 public void FeatureIsNotAvailable (CompilerContext compiler, Location loc, string feature)
96 switch (compiler.Settings.Version) {
97 case LanguageVersion.ISO_1:
100 case LanguageVersion.ISO_2:
103 case LanguageVersion.V_3:
107 throw new InternalErrorException ("Invalid feature version", compiler.Settings.Version);
111 "Feature `{0}' cannot be used because it is not part of the C# {1} language specification",
115 public void FeatureIsNotSupported (Location loc, string feature)
118 "Feature `{0}' is not supported in Mono mcs1 compiler. Consider using the `gmcs' compiler instead",
122 bool IsWarningEnabled (int code, int level, Location loc)
124 if (WarningLevel < level)
127 if (IsWarningDisabledGlobally (code))
130 if (warning_regions_table == null || loc.IsNull)
133 WarningRegions regions;
134 if (!warning_regions_table.TryGetValue (loc.File, out regions))
137 return regions.IsWarningEnabled (code, loc.Row);
140 public bool IsWarningDisabledGlobally (int code)
142 return warning_ignore_table != null && warning_ignore_table.Contains (code);
145 bool IsWarningAsError (int code)
147 bool is_error = WarningsAreErrors;
149 // Check specific list
150 if (warnings_as_error != null)
151 is_error |= warnings_as_error.Contains (code);
153 // Ignore excluded warnings
154 if (warnings_only != null && warnings_only.Contains (code))
160 public void RuntimeMissingSupport (Location loc, string feature)
162 Error (-88, loc, "Your .NET Runtime does not support `{0}'. Please use the latest Mono runtime instead.", feature);
166 /// In most error cases is very useful to have information about symbol that caused the error.
167 /// Call this method before you call Report.Error when it makes sense.
169 public void SymbolRelatedToPreviousError (Location loc, string symbol)
171 SymbolRelatedToPreviousError (loc.ToString ());
174 public void SymbolRelatedToPreviousError (MemberSpec ms)
176 if (reporting_disabled > 0 || !printer.HasRelatedSymbolSupport)
179 var mc = ms.MemberDefinition as MemberCore;
180 while (ms is ElementTypeSpec) {
181 ms = ((ElementTypeSpec) ms).Element;
182 mc = ms.MemberDefinition as MemberCore;
186 SymbolRelatedToPreviousError (mc);
188 if (ms.DeclaringType != null)
189 ms = ms.DeclaringType;
191 var imported_type = ms.MemberDefinition as ImportedTypeDefinition;
192 if (imported_type != null) {
193 var iad = imported_type.DeclaringAssembly as ImportedAssemblyDefinition;
194 SymbolRelatedToPreviousError (iad.Location);
199 public void SymbolRelatedToPreviousError (MemberCore mc)
201 SymbolRelatedToPreviousError (mc.Location, mc.GetSignatureForError ());
204 public void SymbolRelatedToPreviousError (string loc)
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);
219 CheckWarningCode (warningId, Location.Null);
223 if (!CheckWarningCode (id, 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);
238 CheckWarningCode (warningId, Location.Null);
242 if (!CheckWarningCode (id, Location.Null))
245 if (warnings_only == null)
246 warnings_only = new List<int> ();
248 warnings_only.Add (id);
251 public bool CheckWarningCode (string code, Location loc)
253 Warning (1691, 1, loc, "`{0}' is not a valid warning number", code);
257 public bool CheckWarningCode (int code, Location loc)
259 if (AllWarningsHashSet == null)
260 AllWarningsHashSet = new HashSet<int> (AllWarnings);
262 if (AllWarningsHashSet.Contains (code))
265 return CheckWarningCode (code.ToString (), loc);
268 public void ExtraInformation (Location loc, string msg)
270 extra_information.Add (String.Format ("{0} {1}", loc, msg));
273 public WarningRegions RegisterWarningRegion (Location location)
275 WarningRegions regions;
276 if (warning_regions_table == null) {
278 warning_regions_table = new Dictionary<int, WarningRegions> ();
280 warning_regions_table.TryGetValue (location.File, out regions);
283 if (regions == null) {
284 regions = new WarningRegions ();
285 warning_regions_table.Add (location.File, regions);
291 public void Warning (int code, int level, Location loc, string message)
293 if (reporting_disabled > 0)
296 if (!IsWarningEnabled (code, level, loc))
300 if (IsWarningAsError (code)) {
301 message = "Warning as Error: " + message;
302 msg = new ErrorMessage (code, loc, message, extra_information);
304 msg = new WarningMessage (code, loc, message, extra_information);
307 extra_information.Clear ();
311 public void Warning (int code, int level, Location loc, string format, string arg)
313 Warning (code, level, loc, String.Format (format, arg));
316 public void Warning (int code, int level, Location loc, string format, string arg1, string arg2)
318 Warning (code, level, loc, String.Format (format, arg1, arg2));
321 public void Warning (int code, int level, Location loc, string format, params object[] args)
323 Warning (code, level, loc, String.Format (format, args));
326 public void Warning (int code, int level, string message)
328 Warning (code, level, Location.Null, message);
331 public void Warning (int code, int level, string format, string arg)
333 Warning (code, level, Location.Null, format, arg);
336 public void Warning (int code, int level, string format, string arg1, string arg2)
338 Warning (code, level, Location.Null, format, arg1, arg2);
341 public void Warning (int code, int level, string format, params string[] args)
343 Warning (code, level, Location.Null, String.Format (format, args));
347 // Warnings encountered so far
349 public int Warnings {
350 get { return printer.WarningsCount; }
353 public void Error (int code, Location loc, string error)
355 if (reporting_disabled > 0)
358 ErrorMessage msg = new ErrorMessage (code, loc, error, extra_information);
359 extra_information.Clear ();
364 public void Error (int code, Location loc, string format, string arg)
366 Error (code, loc, String.Format (format, arg));
369 public void Error (int code, Location loc, string format, string arg1, string arg2)
371 Error (code, loc, String.Format (format, arg1, arg2));
374 public void Error (int code, Location loc, string format, params string[] args)
376 Error (code, loc, String.Format (format, args));
379 public void Error (int code, string error)
381 Error (code, Location.Null, error);
384 public void Error (int code, string format, string arg)
386 Error (code, Location.Null, format, arg);
389 public void Error (int code, string format, string arg1, string arg2)
391 Error (code, Location.Null, format, arg1, arg2);
394 public void Error (int code, string format, params string[] args)
396 Error (code, Location.Null, String.Format (format, args));
400 // Errors encountered so far
403 get { return printer.ErrorsCount; }
406 public bool IsDisabled {
408 return reporting_disabled > 0;
412 public ReportPrinter Printer {
413 get { return printer; }
416 public void SetIgnoreWarning (int code)
418 if (warning_ignore_table == null)
419 warning_ignore_table = new HashSet<int> ();
421 warning_ignore_table.Add (code);
424 public ReportPrinter SetPrinter (ReportPrinter printer)
426 ReportPrinter old = this.printer;
427 this.printer = printer;
431 public int WarningLevel {
433 return warning_level;
436 warning_level = value;
440 [Conditional ("MCS_DEBUG")]
441 static public void Debug (string message, params object[] args)
443 Debug (4, message, args);
446 [Conditional ("MCS_DEBUG")]
447 static public void Debug (int category, string message, params object[] args)
449 // if ((category & DebugFlags) == 0)
452 StringBuilder sb = new StringBuilder (message);
454 if ((args != null) && (args.Length > 0)) {
458 foreach (object arg in args) {
465 // else if (arg is ICollection)
466 // sb.Append (PrintCollection ((ICollection) arg));
472 Console.WriteLine (sb.ToString ());
475 static public string PrintCollection (ICollection collection)
477 StringBuilder sb = new StringBuilder ();
479 sb.Append (collection.GetType ());
483 foreach (object o in collection) {
492 return sb.ToString ();
497 public abstract class AbstractMessage
499 readonly string[] extra_info;
500 protected readonly int code;
501 protected readonly Location location;
502 readonly string message;
504 protected AbstractMessage (int code, Location loc, string msg, List<string> extraInfo)
508 this.code = 8000 - code;
512 if (extraInfo.Count != 0) {
513 this.extra_info = extraInfo.ToArray ();
517 protected AbstractMessage (AbstractMessage aMsg)
519 this.code = aMsg.code;
520 this.location = aMsg.location;
521 this.message = aMsg.message;
522 this.extra_info = aMsg.extra_info;
529 public override bool Equals (object obj)
531 AbstractMessage msg = obj as AbstractMessage;
535 return code == msg.code && location.Equals (msg.location) && message == msg.message;
538 public override int GetHashCode ()
540 return code.GetHashCode ();
543 public abstract bool IsWarning { get; }
545 public Location Location {
546 get { return location; }
549 public abstract string MessageType { get; }
551 public string[] RelatedSymbols {
552 get { return extra_info; }
556 get { return message; }
560 sealed class WarningMessage : AbstractMessage
562 public WarningMessage (int code, Location loc, string message, List<string> extra_info)
563 : base (code, loc, message, extra_info)
567 public override bool IsWarning {
571 public override string MessageType {
578 sealed class ErrorMessage : AbstractMessage
580 public ErrorMessage (int code, Location loc, string message, List<string> extraInfo)
581 : base (code, loc, message, extraInfo)
585 public ErrorMessage (AbstractMessage aMsg)
590 public override bool IsWarning {
591 get { return false; }
594 public override string MessageType {
602 // Generic base for any message writer
604 public abstract class ReportPrinter
608 public int FatalCounter { get; set; }
610 public int ErrorsCount { get; protected set; }
612 public bool ShowFullPaths { get; set; }
615 // Whether to dump a stack trace on errors.
617 public bool Stacktrace { get; set; }
619 public int WarningsCount { get; private set; }
622 // When (symbols related to previous ...) can be used
624 public virtual bool HasRelatedSymbolSupport {
631 protected virtual string FormatText (string txt)
636 public virtual void Print (AbstractMessage msg)
643 if (ErrorsCount == FatalCounter)
644 throw new Exception (msg.Text);
648 protected void Print (AbstractMessage msg, TextWriter output)
650 StringBuilder txt = new StringBuilder ();
651 if (!msg.Location.IsNull) {
653 txt.Append (msg.Location.ToStringFullName ());
655 txt.Append (msg.Location.ToString ());
660 txt.AppendFormat ("{0} CS{1:0000}: {2}", msg.MessageType, msg.Code, msg.Text);
663 output.WriteLine (FormatText (txt.ToString ()));
665 output.WriteLine (txt.ToString ());
667 if (msg.RelatedSymbols != null) {
668 foreach (string s in msg.RelatedSymbols)
669 output.WriteLine (s + msg.MessageType + ")");
675 // HACK: Temporary hack for broken repl flow
676 ErrorsCount = WarningsCount = 0;
680 sealed class NullReportPrinter : ReportPrinter
685 // Default message recorder, it uses two types of message groups.
686 // Common messages: messages reported in all sessions.
687 // Merged messages: union of all messages in all sessions.
689 // Used by the Lambda expressions to compile the code with various
690 // parameter values, or by attribute resolver
692 class SessionReportPrinter : ReportPrinter
694 List<AbstractMessage> session_messages;
696 // A collection of exactly same messages reported in all sessions
698 List<AbstractMessage> common_messages;
701 // A collection of unique messages reported in all sessions
703 List<AbstractMessage> merged_messages;
705 public override void Print (AbstractMessage msg)
708 // This line is useful when debugging recorded messages
710 // Console.WriteLine ("RECORDING: {0}", msg.ToString ());
712 if (session_messages == null)
713 session_messages = new List<AbstractMessage> ();
715 session_messages.Add (msg);
720 public void EndSession ()
722 if (session_messages == null)
726 // Handles the first session
728 if (common_messages == null) {
729 common_messages = new List<AbstractMessage> (session_messages);
730 merged_messages = session_messages;
731 session_messages = null;
736 // Store common messages if any
738 for (int i = 0; i < common_messages.Count; ++i) {
739 AbstractMessage cmsg = common_messages[i];
740 bool common_msg_found = false;
741 foreach (AbstractMessage msg in session_messages) {
742 if (cmsg.Equals (msg)) {
743 common_msg_found = true;
748 if (!common_msg_found)
749 common_messages.RemoveAt (i);
753 // Merge session and previous messages
755 for (int i = 0; i < session_messages.Count; ++i) {
756 AbstractMessage msg = session_messages[i];
757 bool msg_found = false;
758 for (int ii = 0; ii < merged_messages.Count; ++ii) {
759 if (msg.Equals (merged_messages[ii])) {
766 merged_messages.Add (msg);
770 public bool IsEmpty {
772 return merged_messages == null && common_messages == null;
777 // Prints collected messages, common messages have a priority
779 public bool Merge (ReportPrinter dest)
781 var messages_to_print = merged_messages;
782 if (common_messages != null && common_messages.Count > 0) {
783 messages_to_print = common_messages;
786 if (messages_to_print == null)
789 bool error_msg = false;
790 foreach (AbstractMessage msg in messages_to_print) {
792 error_msg |= !msg.IsWarning;
799 public class StreamReportPrinter : ReportPrinter
801 readonly TextWriter writer;
803 public StreamReportPrinter (TextWriter writer)
805 this.writer = writer;
808 public override void Print (AbstractMessage msg)
815 public class ConsoleReportPrinter : StreamReportPrinter
817 static readonly string prefix, postfix;
819 static ConsoleReportPrinter ()
821 string term = Environment.GetEnvironmentVariable ("TERM");
822 bool xterm_colors = false;
828 if (Environment.GetEnvironmentVariable ("COLORTERM") != null){
834 case "xterm-256color":
841 if (!(UnixUtils.isatty (1) && UnixUtils.isatty (2)))
844 string config = Environment.GetEnvironmentVariable ("MCS_COLORS");
846 config = "errors=red";
847 //config = "brightwhite,red";
850 if (config == "disable")
853 if (!config.StartsWith ("errors="))
856 config = config.Substring (7);
858 int p = config.IndexOf (",");
860 prefix = GetForeground (config);
862 prefix = GetBackground (config.Substring (p+1)) + GetForeground (config.Substring (0, p));
863 postfix = "\x001b[0m";
866 public ConsoleReportPrinter ()
867 : base (Console.Error)
871 public ConsoleReportPrinter (TextWriter writer)
876 static int NameToCode (string s)
901 // maps a color name to its xterm color code
903 static string GetForeground (string s)
907 if (s.StartsWith ("bright")) {
913 return "\x001b[" + highcode + (30 + NameToCode (s)).ToString () + "m";
916 static string GetBackground (string s)
918 return "\x001b[" + (40 + NameToCode (s)).ToString () + "m";
921 protected override string FormatText (string txt)
924 return prefix + txt + postfix;
929 static string FriendlyStackTrace (StackTrace t)
931 StringBuilder sb = new StringBuilder ();
933 bool foundUserCode = false;
935 for (int i = 0; i < t.FrameCount; i++) {
936 StackFrame f = t.GetFrame (i);
937 var mb = f.GetMethod ();
939 if (!foundUserCode && mb.ReflectedType == typeof (Report))
942 foundUserCode = true;
946 if (f.GetFileLineNumber () > 0)
947 sb.AppendFormat ("(at {0}:{1}) ", f.GetFileName (), f.GetFileLineNumber ());
949 sb.AppendFormat ("{0}.{1} (", mb.ReflectedType.Name, mb.Name);
952 foreach (var pi in mb.GetParameters ()) {
957 sb.Append (pi.ParameterType.FullName);
962 return sb.ToString ();
965 public override void Print (AbstractMessage msg)
970 Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
973 public static string FriendlyStackTrace (Exception e)
975 return FriendlyStackTrace (new StackTrace (e, true));
978 public static void StackTrace ()
980 Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
986 public enum TimerType
989 AssemblyBuilderSetup,
994 ModuleDefinitionTotal,
1003 readonly Stopwatch[] timers;
1006 public TimeReporter (bool enabled)
1011 timers = new Stopwatch[System.Enum.GetValues(typeof (TimerType)).Length];
1014 public void Start (TimerType type)
1016 if (timers != null) {
1017 var sw = new Stopwatch ();
1018 timers[(int) type] = sw;
1023 public void StartTotal ()
1025 total = new Stopwatch ();
1029 public void Stop (TimerType type)
1031 if (timers != null) {
1032 timers[(int) type].Stop ();
1036 public void StopTotal ()
1041 public void ShowStats ()
1046 Dictionary<TimerType, string> timer_names = new Dictionary<TimerType,string> () {
1047 { TimerType.ParseTotal, "Parsing source files" },
1048 { TimerType.AssemblyBuilderSetup, "Assembly builder setup" },
1049 { TimerType.CreateTypeTotal, "Compiled types created" },
1050 { TimerType.ReferencesLoading, "Referenced assemblies loading" },
1051 { TimerType.ReferencesImporting, "Referenced assemblies importing" },
1052 { TimerType.PredefinedTypesInit, "Predefined types initialization" },
1053 { TimerType.ModuleDefinitionTotal, "Module definition" },
1054 { TimerType.UsingResolve, "Top-level usings resolve" },
1055 { TimerType.EmitTotal, "Resolving and emitting members blocks" },
1056 { TimerType.CloseTypes, "Module types closed" },
1057 { TimerType.Resouces, "Embedding resources" },
1058 { TimerType.OutputSave, "Writing output file" },
1059 { TimerType.DebugSave, "Writing debug symbols file" },
1063 double percentage = (double) total.ElapsedMilliseconds / 100;
1064 long subtotal = total.ElapsedMilliseconds;
1065 foreach (var timer in timers) {
1066 string msg = timer_names[(TimerType) counter++];
1067 var ms = timer == null ? 0 : timer.ElapsedMilliseconds;
1068 Console.WriteLine ("{0,4:0.0}% {1,5}ms {2}", ms / percentage, ms, msg);
1072 Console.WriteLine ("{0,4:0.0}% {1,5}ms Other tasks", subtotal / percentage, subtotal);
1073 Console.WriteLine ();
1074 Console.WriteLine ("Total elapsed time: {0}", total.Elapsed);
1078 public class InternalErrorException : Exception {
1079 public InternalErrorException (MemberCore mc, Exception e)
1080 : base (mc.Location + " " + mc.GetSignatureForError (), e)
1084 public InternalErrorException ()
1085 : base ("Internal error")
1089 public InternalErrorException (string message)
1094 public InternalErrorException (string message, params object[] args)
1095 : base (String.Format (message, args))
1099 public InternalErrorException (Exception exception, string message, params object[] args)
1100 : base (String.Format (message, args), exception)
1104 public InternalErrorException (Exception e, Location loc)
1105 : base (loc.ToString (), e)
1111 /// Handles #pragma warning
1113 public class WarningRegions {
1115 abstract class PragmaCmd
1119 protected PragmaCmd (int line)
1124 public abstract bool IsEnabled (int code, bool previous);
1127 class Disable : PragmaCmd
1130 public Disable (int line, int code)
1136 public override bool IsEnabled (int code, bool previous)
1138 return this.code == code ? false : previous;
1142 class DisableAll : PragmaCmd
1144 public DisableAll (int line)
1147 public override bool IsEnabled(int code, bool previous)
1153 class Enable : PragmaCmd
1156 public Enable (int line, int code)
1162 public override bool IsEnabled(int code, bool previous)
1164 return this.code == code ? true : previous;
1168 class EnableAll : PragmaCmd
1170 public EnableAll (int line)
1173 public override bool IsEnabled(int code, bool previous)
1180 List<PragmaCmd> regions = new List<PragmaCmd> ();
1182 public void WarningDisable (int line)
1184 regions.Add (new DisableAll (line));
1187 public void WarningDisable (Location location, int code, Report Report)
1189 if (Report.CheckWarningCode (code, location))
1190 regions.Add (new Disable (location.Row, code));
1193 public void WarningEnable (int line)
1195 regions.Add (new EnableAll (line));
1198 public void WarningEnable (Location location, int code, Report Report)
1200 if (!Report.CheckWarningCode (code, location))
1203 if (Report.IsWarningDisabledGlobally (code))
1204 Report.Warning (1635, 1, location, "Cannot restore warning `CS{0:0000}' because it was disabled globally", code);
1206 regions.Add (new Enable (location.Row, code));
1209 public bool IsWarningEnabled (int code, int src_line)
1212 foreach (PragmaCmd pragma in regions) {
1213 if (src_line < pragma.Line)
1216 result = pragma.IsEnabled (code, result);