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 static int DebugFlags = 0;
32 public const int RuntimeErrorId = 10000;
35 // Keeps track of the warnings that we are ignoring
37 HashSet<int> warning_ignore_table;
39 Dictionary<int, 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,
64 1522, 1570, 1571, 1572, 1573, 1574, 1580, 1581, 1584, 1587, 1589, 1590, 1591, 1592,
65 1607, 1616, 1633, 1634, 1635, 1685, 1690, 1691, 1692, 1695, 1696, 1699,
66 1700, 1701, 1702, 1709, 1717, 1718, 1720,
69 3000, 3001, 3002, 3003, 3005, 3006, 3007, 3008, 3009,
70 3010, 3011, 3012, 3013, 3014, 3015, 3016, 3017, 3018, 3019,
71 3021, 3022, 3023, 3024, 3026, 3027
74 static HashSet<int> AllWarningsHashSet;
76 public Report (ReportPrinter printer)
79 throw new ArgumentNullException ("printer");
81 this.printer = printer;
85 public void DisableReporting ()
90 public void EnableReporting ()
95 public void FeatureIsNotAvailable (CompilerContext compiler, Location loc, string feature)
98 switch (compiler.Settings.Version) {
99 case LanguageVersion.ISO_1:
102 case LanguageVersion.ISO_2:
105 case LanguageVersion.V_3:
109 throw new InternalErrorException ("Invalid feature version", compiler.Settings.Version);
113 "Feature `{0}' cannot be used because it is not part of the C# {1} language specification",
117 public void FeatureIsNotSupported (Location loc, string feature)
120 "Feature `{0}' is not supported in Mono mcs1 compiler. Consider using the `gmcs' compiler instead",
124 bool IsWarningEnabled (int code, int level, Location loc)
126 if (WarningLevel < level)
129 if (IsWarningDisabledGlobally (code))
132 if (warning_regions_table == null || loc.IsNull)
135 WarningRegions regions;
136 if (!warning_regions_table.TryGetValue (loc.File, out regions))
139 return regions.IsWarningEnabled (code, loc.Row);
142 public bool IsWarningDisabledGlobally (int code)
144 return warning_ignore_table != null && warning_ignore_table.Contains (code);
147 bool IsWarningAsError (int code)
149 bool is_error = WarningsAreErrors;
151 // Check specific list
152 if (warnings_as_error != null)
153 is_error |= warnings_as_error.Contains (code);
155 // Ignore excluded warnings
156 if (warnings_only != null && warnings_only.Contains (code))
162 public void RuntimeMissingSupport (Location loc, string feature)
164 Error (-88, loc, "Your .NET Runtime does not support `{0}'. Please use the latest Mono runtime instead.", feature);
168 /// In most error cases is very useful to have information about symbol that caused the error.
169 /// Call this method before you call Report.Error when it makes sense.
171 public void SymbolRelatedToPreviousError (Location loc, string symbol)
173 SymbolRelatedToPreviousError (loc.ToString ());
176 public void SymbolRelatedToPreviousError (MemberSpec ms)
178 if (reporting_disabled > 0 || !printer.HasRelatedSymbolSupport)
181 var mc = ms.MemberDefinition as MemberCore;
182 while (ms is ElementTypeSpec) {
183 ms = ((ElementTypeSpec) ms).Element;
184 mc = ms.MemberDefinition as MemberCore;
188 SymbolRelatedToPreviousError (mc);
190 if (ms.DeclaringType != null)
191 ms = ms.DeclaringType;
193 var imported_type = ms.MemberDefinition as ImportedTypeDefinition;
194 if (imported_type != null) {
195 var iad = imported_type.DeclaringAssembly as ImportedAssemblyDefinition;
196 SymbolRelatedToPreviousError (iad.Location);
201 public void SymbolRelatedToPreviousError (MemberCore mc)
203 SymbolRelatedToPreviousError (mc.Location, mc.GetSignatureForError ());
206 public void SymbolRelatedToPreviousError (string loc)
208 string msg = String.Format ("{0} (Location of the symbol related to previous ", loc);
209 if (extra_information.Contains (msg))
212 extra_information.Add (msg);
215 public void AddWarningAsError (string warningId)
219 id = int.Parse (warningId);
221 CheckWarningCode (warningId, Location.Null);
225 if (!CheckWarningCode (id, Location.Null))
228 if (warnings_as_error == null)
229 warnings_as_error = new List<int> ();
231 warnings_as_error.Add (id);
234 public void RemoveWarningAsError (string warningId)
238 id = int.Parse (warningId);
240 CheckWarningCode (warningId, Location.Null);
244 if (!CheckWarningCode (id, Location.Null))
247 if (warnings_only == null)
248 warnings_only = new List<int> ();
250 warnings_only.Add (id);
253 public bool CheckWarningCode (string code, Location loc)
255 Warning (1691, 1, loc, "`{0}' is not a valid warning number", code);
259 public bool CheckWarningCode (int code, Location loc)
261 if (AllWarningsHashSet == null)
262 AllWarningsHashSet = new HashSet<int> (AllWarnings);
264 if (AllWarningsHashSet.Contains (code))
267 return CheckWarningCode (code.ToString (), loc);
270 public void ExtraInformation (Location loc, string msg)
272 extra_information.Add (String.Format ("{0} {1}", loc, msg));
275 public WarningRegions RegisterWarningRegion (Location location)
277 WarningRegions regions;
278 if (warning_regions_table == null) {
280 warning_regions_table = new Dictionary<int, WarningRegions> ();
282 warning_regions_table.TryGetValue (location.File, out regions);
285 if (regions == null) {
286 regions = new WarningRegions ();
287 warning_regions_table.Add (location.File, regions);
293 public void Warning (int code, int level, Location loc, string message)
295 if (reporting_disabled > 0)
298 if (!IsWarningEnabled (code, level, loc))
302 if (IsWarningAsError (code))
303 msg = new ErrorMessage (code, loc, message, extra_information);
305 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;
681 // Default message recorder, it uses two types of message groups.
682 // Common messages: messages reported in all sessions.
683 // Merged messages: union of all messages in all sessions.
685 // Used by the Lambda expressions to compile the code with various
686 // parameter values, or by attribute resolver
688 class SessionReportPrinter : ReportPrinter
690 List<AbstractMessage> session_messages;
692 // A collection of exactly same messages reported in all sessions
694 List<AbstractMessage> common_messages;
697 // A collection of unique messages reported in all sessions
699 List<AbstractMessage> merged_messages;
701 public override void Print (AbstractMessage msg)
704 // This line is useful when debugging recorded messages
706 // Console.WriteLine ("RECORDING: {0}", msg.ToString ());
708 if (session_messages == null)
709 session_messages = new List<AbstractMessage> ();
711 session_messages.Add (msg);
716 public void EndSession ()
718 if (session_messages == null)
722 // Handles the first session
724 if (common_messages == null) {
725 common_messages = new List<AbstractMessage> (session_messages);
726 merged_messages = session_messages;
727 session_messages = null;
732 // Store common messages if any
734 for (int i = 0; i < common_messages.Count; ++i) {
735 AbstractMessage cmsg = common_messages[i];
736 bool common_msg_found = false;
737 foreach (AbstractMessage msg in session_messages) {
738 if (cmsg.Equals (msg)) {
739 common_msg_found = true;
744 if (!common_msg_found)
745 common_messages.RemoveAt (i);
749 // Merge session and previous messages
751 for (int i = 0; i < session_messages.Count; ++i) {
752 AbstractMessage msg = session_messages[i];
753 bool msg_found = false;
754 for (int ii = 0; ii < merged_messages.Count; ++ii) {
755 if (msg.Equals (merged_messages[ii])) {
762 merged_messages.Add (msg);
766 public bool IsEmpty {
768 return merged_messages == null && common_messages == null;
773 // Prints collected messages, common messages have a priority
775 public bool Merge (ReportPrinter dest)
777 var messages_to_print = merged_messages;
778 if (common_messages != null && common_messages.Count > 0) {
779 messages_to_print = common_messages;
782 if (messages_to_print == null)
785 bool error_msg = false;
786 foreach (AbstractMessage msg in messages_to_print) {
788 error_msg |= !msg.IsWarning;
795 class StreamReportPrinter : ReportPrinter
797 readonly TextWriter writer;
799 public StreamReportPrinter (TextWriter writer)
801 this.writer = writer;
804 public override void Print (AbstractMessage msg)
811 class ConsoleReportPrinter : StreamReportPrinter
813 static readonly string prefix, postfix;
815 static ConsoleReportPrinter ()
817 string term = Environment.GetEnvironmentVariable ("TERM");
818 bool xterm_colors = false;
824 if (Environment.GetEnvironmentVariable ("COLORTERM") != null){
836 if (!(UnixUtils.isatty (1) && UnixUtils.isatty (2)))
839 string config = Environment.GetEnvironmentVariable ("MCS_COLORS");
841 config = "errors=red";
842 //config = "brightwhite,red";
845 if (config == "disable")
848 if (!config.StartsWith ("errors="))
851 config = config.Substring (7);
853 int p = config.IndexOf (",");
855 prefix = GetForeground (config);
857 prefix = GetBackground (config.Substring (p+1)) + GetForeground (config.Substring (0, p));
858 postfix = "\x001b[0m";
861 public ConsoleReportPrinter ()
862 : base (Console.Error)
866 public ConsoleReportPrinter (TextWriter writer)
871 static int NameToCode (string s)
896 // maps a color name to its xterm color code
898 static string GetForeground (string s)
902 if (s.StartsWith ("bright")) {
908 return "\x001b[" + highcode + (30 + NameToCode (s)).ToString () + "m";
911 static string GetBackground (string s)
913 return "\x001b[" + (40 + NameToCode (s)).ToString () + "m";
916 protected override string FormatText (string txt)
919 return prefix + txt + postfix;
924 static string FriendlyStackTrace (StackTrace t)
926 StringBuilder sb = new StringBuilder ();
928 bool foundUserCode = false;
930 for (int i = 0; i < t.FrameCount; i++) {
931 StackFrame f = t.GetFrame (i);
932 var mb = f.GetMethod ();
934 if (!foundUserCode && mb.ReflectedType == typeof (Report))
937 foundUserCode = true;
941 if (f.GetFileLineNumber () > 0)
942 sb.AppendFormat ("(at {0}:{1}) ", f.GetFileName (), f.GetFileLineNumber ());
944 sb.AppendFormat ("{0}.{1} (", mb.ReflectedType.Name, mb.Name);
947 foreach (var pi in mb.GetParameters ()) {
952 sb.Append (pi.ParameterType.FullName);
957 return sb.ToString ();
960 public override void Print (AbstractMessage msg)
965 Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
968 public static string FriendlyStackTrace (Exception e)
970 return FriendlyStackTrace (new StackTrace (e, true));
973 public static void StackTrace ()
975 Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
981 public enum TimerType
984 AssemblyBuilderSetup,
989 ModuleDefinitionTotal,
998 readonly Stopwatch[] timers;
1001 public TimeReporter (bool enabled)
1006 timers = new Stopwatch[System.Enum.GetValues(typeof (TimerType)).Length];
1009 public void Start (TimerType type)
1011 if (timers != null) {
1012 var sw = new Stopwatch ();
1013 timers[(int) type] = sw;
1018 public void StartTotal ()
1020 total = new Stopwatch ();
1024 public void Stop (TimerType type)
1026 if (timers != null) {
1027 timers[(int) type].Stop ();
1031 public void StopTotal ()
1036 public void ShowStats ()
1041 Dictionary<TimerType, string> timer_names = new Dictionary<TimerType,string> () {
1042 { TimerType.ParseTotal, "Parsing source files" },
1043 { TimerType.AssemblyBuilderSetup, "Assembly builder setup" },
1044 { TimerType.CreateTypeTotal, "Compiled types created" },
1045 { TimerType.ReferencesLoading, "Referenced assemblies loading" },
1046 { TimerType.ReferencesImporting, "Referenced assemblies importing" },
1047 { TimerType.PredefinedTypesInit, "Predefined types initialization" },
1048 { TimerType.ModuleDefinitionTotal, "Module definition" },
1049 { TimerType.UsingVerification, "Usings verification" },
1050 { TimerType.EmitTotal, "Resolving and emitting members blocks" },
1051 { TimerType.CloseTypes, "Module types closed" },
1052 { TimerType.Resouces, "Embedding resources" },
1053 { TimerType.OutputSave, "Writing output file" },
1054 { TimerType.DebugSave, "Writing debug symbols file" },
1058 double percentage = total.ElapsedMilliseconds / 100;
1059 long subtotal = total.ElapsedMilliseconds;
1060 foreach (var timer in timers) {
1061 string msg = timer_names[(TimerType) counter++];
1062 var ms = timer == null ? 0 : timer.ElapsedMilliseconds;
1063 Console.WriteLine ("{0,4:0.0}% {1,5}ms {2}", ms / percentage, ms, msg);
1067 Console.WriteLine ("{0,4:0.0}% {1,5}ms Other tasks", subtotal / percentage, subtotal);
1068 Console.WriteLine ();
1069 Console.WriteLine ("Total elapsed time: {0}", total.Elapsed);
1073 public class InternalErrorException : Exception {
1074 public InternalErrorException (MemberCore mc, Exception e)
1075 : base (mc.Location + " " + mc.GetSignatureForError (), e)
1079 public InternalErrorException ()
1080 : base ("Internal error")
1084 public InternalErrorException (string message)
1089 public InternalErrorException (string message, params object[] args)
1090 : base (String.Format (message, args))
1094 public InternalErrorException (Exception exception, string message, params object[] args)
1095 : base (String.Format (message, args), exception)
1099 public InternalErrorException (Exception e, Location loc)
1100 : base (loc.ToString (), e)
1106 /// Handles #pragma warning
1108 public class WarningRegions {
1110 abstract class PragmaCmd
1114 protected PragmaCmd (int line)
1119 public abstract bool IsEnabled (int code, bool previous);
1122 class Disable : PragmaCmd
1125 public Disable (int line, int code)
1131 public override bool IsEnabled (int code, bool previous)
1133 return this.code == code ? false : previous;
1137 class DisableAll : PragmaCmd
1139 public DisableAll (int line)
1142 public override bool IsEnabled(int code, bool previous)
1148 class Enable : PragmaCmd
1151 public Enable (int line, int code)
1157 public override bool IsEnabled(int code, bool previous)
1159 return this.code == code ? true : previous;
1163 class EnableAll : PragmaCmd
1165 public EnableAll (int line)
1168 public override bool IsEnabled(int code, bool previous)
1175 List<PragmaCmd> regions = new List<PragmaCmd> ();
1177 public void WarningDisable (int line)
1179 regions.Add (new DisableAll (line));
1182 public void WarningDisable (Location location, int code, Report Report)
1184 if (Report.CheckWarningCode (code, location))
1185 regions.Add (new Disable (location.Row, code));
1188 public void WarningEnable (int line)
1190 regions.Add (new EnableAll (line));
1193 public void WarningEnable (Location location, int code, Report Report)
1195 if (!Report.CheckWarningCode (code, location))
1198 if (Report.IsWarningDisabledGlobally (code))
1199 Report.Warning (1635, 1, location, "Cannot restore warning `CS{0:0000}' because it was disabled globally", code);
1201 regions.Add (new Enable (location.Row, code));
1204 public bool IsWarningEnabled (int code, int src_line)
1207 foreach (PragmaCmd pragma in regions) {
1208 if (src_line < pragma.Line)
1211 result = pragma.IsEnabled (code, result);