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
24 public const int RuntimeErrorId = 10000;
26 Dictionary<int, WarningRegions> warning_regions_table;
28 ReportPrinter printer;
30 int reporting_disabled;
32 readonly CompilerSettings settings;
35 /// List of symbols related to reported error/warning. You have to fill it before error/warning is reported.
37 List<string> extra_information = new List<string> ();
40 // IF YOU ADD A NEW WARNING YOU HAVE TO ADD ITS ID HERE
42 public static readonly int[] AllWarnings = new int[] {
44 105, 108, 109, 114, 162, 164, 168, 169, 183, 184, 197,
45 219, 251, 252, 253, 278, 282,
46 402, 414, 419, 420, 429, 436, 437, 440, 458, 464, 465, 467, 469, 472, 473,
47 612, 618, 626, 628, 642, 649, 652, 657, 658, 659, 660, 661, 665, 672, 675, 693,
50 1030, 1058, 1060, 1066,
51 1522, 1570, 1571, 1572, 1573, 1574, 1580, 1581, 1584, 1587, 1589, 1590, 1591, 1592,
52 1607, 1616, 1633, 1634, 1635, 1685, 1690, 1691, 1692, 1695, 1696, 1697, 1699,
53 1700, 1701, 1702, 1709, 1711, 1717, 1718, 1720, 1735,
54 1901, 1956, 1981, 1998,
56 3000, 3001, 3002, 3003, 3005, 3006, 3007, 3008, 3009,
57 3010, 3011, 3012, 3013, 3014, 3015, 3016, 3017, 3018, 3019,
58 3021, 3022, 3023, 3024, 3026, 3027,
59 4014, 4024, 4025, 4026,
60 7035, 7080, 7081, 7082, 7095,
64 static HashSet<int> AllWarningsHashSet;
66 public Report (CompilerContext context, ReportPrinter printer)
69 throw new ArgumentNullException ("settings");
71 throw new ArgumentNullException ("printer");
73 this.settings = context.Settings;
74 this.printer = printer;
77 public void DisableReporting ()
82 public void EnableReporting ()
87 public void FeatureIsNotAvailable (CompilerContext compiler, Location loc, string feature)
90 switch (compiler.Settings.Version) {
91 case LanguageVersion.ISO_1:
94 case LanguageVersion.ISO_2:
97 case LanguageVersion.V_3:
100 case LanguageVersion.V_4:
103 case LanguageVersion.V_5:
106 case LanguageVersion.V_6:
110 throw new InternalErrorException ("Invalid feature version", compiler.Settings.Version);
114 "Feature `{0}' cannot be used because it is not part of the C# {1} language specification",
118 public void FeatureIsNotSupported (Location loc, string feature)
121 "Feature `{0}' is not supported in Mono mcs1 compiler. Consider using the `gmcs' compiler instead",
125 public void RuntimeMissingSupport (Location loc, string feature)
127 Error (-88, loc, "Your .NET Runtime does not support `{0}'. Please use the latest Mono runtime instead.", feature);
131 /// In most error cases is very useful to have information about symbol that caused the error.
132 /// Call this method before you call Report.Error when it makes sense.
134 public void SymbolRelatedToPreviousError (Location loc, string symbol)
136 SymbolRelatedToPreviousError (loc.ToString ());
139 public void SymbolRelatedToPreviousError (MemberSpec ms)
141 if (reporting_disabled > 0 || !printer.HasRelatedSymbolSupport)
144 var mc = ms.MemberDefinition as MemberCore;
145 while (ms is ElementTypeSpec) {
146 ms = ((ElementTypeSpec) ms).Element;
147 mc = ms.MemberDefinition as MemberCore;
151 SymbolRelatedToPreviousError (mc);
153 if (ms.DeclaringType != null)
154 ms = ms.DeclaringType;
156 var imported_type = ms.MemberDefinition as ImportedTypeDefinition;
157 if (imported_type != null) {
158 var iad = imported_type.DeclaringAssembly as ImportedAssemblyDefinition;
159 SymbolRelatedToPreviousError (iad.Location);
164 public void SymbolRelatedToPreviousError (MemberCore mc)
166 SymbolRelatedToPreviousError (mc.Location, mc.GetSignatureForError ());
169 public void SymbolRelatedToPreviousError (string loc)
171 string msg = String.Format ("{0} (Location of the symbol related to previous ", loc);
172 if (extra_information.Contains (msg))
175 extra_information.Add (msg);
178 public bool CheckWarningCode (int code, Location loc)
180 if (AllWarningsHashSet == null)
181 AllWarningsHashSet = new HashSet<int> (AllWarnings);
183 if (AllWarningsHashSet.Contains (code))
186 Warning (1691, 1, loc, "`{0}' is not a valid warning number", code);
190 public void ExtraInformation (Location loc, string msg)
192 extra_information.Add (String.Format ("{0} {1}", loc, msg));
195 public WarningRegions RegisterWarningRegion (Location location)
197 WarningRegions regions;
198 if (warning_regions_table == null) {
200 warning_regions_table = new Dictionary<int, WarningRegions> ();
202 warning_regions_table.TryGetValue (location.File, out regions);
205 if (regions == null) {
206 regions = new WarningRegions ();
207 warning_regions_table.Add (location.File, regions);
213 public void Warning (int code, int level, Location loc, string message)
215 if (reporting_disabled > 0)
218 if (!settings.IsWarningEnabled (code, level))
221 if (warning_regions_table != null && !loc.IsNull) {
222 WarningRegions regions;
223 if (warning_regions_table.TryGetValue (loc.File, out regions) && !regions.IsWarningEnabled (code, loc.Row))
228 if (settings.IsWarningAsError (code)) {
229 message = "Warning as Error: " + message;
230 msg = new ErrorMessage (code, loc, message, extra_information);
232 msg = new WarningMessage (code, loc, message, extra_information);
235 extra_information.Clear ();
236 printer.Print (msg, settings.ShowFullPaths);
239 public void Warning (int code, int level, Location loc, string format, string arg)
241 Warning (code, level, loc, String.Format (format, arg));
244 public void Warning (int code, int level, Location loc, string format, string arg1, string arg2)
246 Warning (code, level, loc, String.Format (format, arg1, arg2));
249 public void Warning (int code, int level, Location loc, string format, params object[] args)
251 Warning (code, level, loc, String.Format (format, args));
254 public void Warning (int code, int level, string message)
256 Warning (code, level, Location.Null, message);
259 public void Warning (int code, int level, string format, string arg)
261 Warning (code, level, Location.Null, format, arg);
264 public void Warning (int code, int level, string format, string arg1, string arg2)
266 Warning (code, level, Location.Null, format, arg1, arg2);
269 public void Warning (int code, int level, string format, params string[] args)
271 Warning (code, level, Location.Null, String.Format (format, args));
275 // Warnings encountered so far
277 public int Warnings {
278 get { return printer.WarningsCount; }
281 public void Error (int code, Location loc, string error)
283 if (reporting_disabled > 0)
286 ErrorMessage msg = new ErrorMessage (code, loc, error, extra_information);
287 extra_information.Clear ();
289 printer.Print (msg, settings.ShowFullPaths);
291 if (settings.Stacktrace)
292 Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
294 if (printer.ErrorsCount == settings.FatalCounter)
295 throw new FatalException (msg.Text);
298 public void Error (int code, Location loc, string format, string arg)
300 Error (code, loc, String.Format (format, arg));
303 public void Error (int code, Location loc, string format, string arg1, string arg2)
305 Error (code, loc, String.Format (format, arg1, arg2));
308 public void Error (int code, Location loc, string format, params string[] args)
310 Error (code, loc, String.Format (format, args));
313 public void Error (int code, string error)
315 Error (code, Location.Null, error);
318 public void Error (int code, string format, string arg)
320 Error (code, Location.Null, format, arg);
323 public void Error (int code, string format, string arg1, string arg2)
325 Error (code, Location.Null, format, arg1, arg2);
328 public void Error (int code, string format, params string[] args)
330 Error (code, Location.Null, String.Format (format, args));
334 // Errors encountered so far
337 get { return printer.ErrorsCount; }
340 public bool IsDisabled {
342 return reporting_disabled > 0;
346 public ReportPrinter Printer {
347 get { return printer; }
350 public ReportPrinter SetPrinter (ReportPrinter printer)
352 ReportPrinter old = this.printer;
353 this.printer = printer;
357 [Conditional ("MCS_DEBUG")]
358 static public void Debug (string message, params object[] args)
360 Debug (4, message, args);
363 [Conditional ("MCS_DEBUG")]
364 static public void Debug (int category, string message, params object[] args)
366 // if ((category & DebugFlags) == 0)
369 StringBuilder sb = new StringBuilder (message);
371 if ((args != null) && (args.Length > 0)) {
375 foreach (object arg in args) {
382 // else if (arg is ICollection)
383 // sb.Append (PrintCollection ((ICollection) arg));
389 Console.WriteLine (sb.ToString ());
392 static public string PrintCollection (ICollection collection)
394 StringBuilder sb = new StringBuilder ();
396 sb.Append (collection.GetType ());
400 foreach (object o in collection) {
409 return sb.ToString ();
412 static string FriendlyStackTrace (StackTrace t)
414 StringBuilder sb = new StringBuilder ();
416 bool foundUserCode = false;
418 for (int i = 0; i < t.FrameCount; i++) {
419 StackFrame f = t.GetFrame (i);
420 var mb = f.GetMethod ();
422 if (!foundUserCode && mb.ReflectedType == typeof (Report))
425 foundUserCode = true;
429 if (f.GetFileLineNumber () > 0)
430 sb.AppendFormat ("(at {0}:{1}) ", f.GetFileName (), f.GetFileLineNumber ());
432 sb.AppendFormat ("{0}.{1} (", mb.ReflectedType.Name, mb.Name);
435 foreach (var pi in mb.GetParameters ()) {
440 sb.Append (pi.ParameterType.FullName);
445 return sb.ToString ();
449 public abstract class AbstractMessage
451 readonly string[] extra_info;
452 protected readonly int code;
453 protected readonly Location location;
454 readonly string message;
456 protected AbstractMessage (int code, Location loc, string msg, List<string> extraInfo)
460 this.code = 8000 - code;
464 if (extraInfo.Count != 0) {
465 this.extra_info = extraInfo.ToArray ();
469 protected AbstractMessage (AbstractMessage aMsg)
471 this.code = aMsg.code;
472 this.location = aMsg.location;
473 this.message = aMsg.message;
474 this.extra_info = aMsg.extra_info;
481 public override bool Equals (object obj)
483 AbstractMessage msg = obj as AbstractMessage;
487 return code == msg.code && location.Equals (msg.location) && message == msg.message;
490 public override int GetHashCode ()
492 return code.GetHashCode ();
495 public abstract bool IsWarning { get; }
497 public Location Location {
498 get { return location; }
501 public abstract string MessageType { get; }
503 public string[] RelatedSymbols {
504 get { return extra_info; }
508 get { return message; }
512 sealed class WarningMessage : AbstractMessage
514 public WarningMessage (int code, Location loc, string message, List<string> extra_info)
515 : base (code, loc, message, extra_info)
519 public override bool IsWarning {
523 public override string MessageType {
530 sealed class ErrorMessage : AbstractMessage
532 public ErrorMessage (int code, Location loc, string message, List<string> extraInfo)
533 : base (code, loc, message, extraInfo)
537 public ErrorMessage (AbstractMessage aMsg)
542 public override bool IsWarning {
543 get { return false; }
546 public override string MessageType {
554 // Generic base for any message writer
556 public abstract class ReportPrinter
558 protected HashSet<ITypeDefinition> reported_missing_definitions;
562 public int ErrorsCount { get; protected set; }
564 public int WarningsCount { get; private set; }
567 // When (symbols related to previous ...) can be used
569 public virtual bool HasRelatedSymbolSupport {
576 protected virtual string FormatText (string txt)
581 public virtual void Print (AbstractMessage msg, bool showFullPath)
590 protected void Print (AbstractMessage msg, TextWriter output, bool showFullPath)
592 StringBuilder txt = new StringBuilder ();
593 if (!msg.Location.IsNull) {
595 txt.Append (msg.Location.ToStringFullName ());
597 txt.Append (msg.Location.ToString ());
602 txt.AppendFormat ("{0} CS{1:0000}: {2}", msg.MessageType, msg.Code, msg.Text);
605 output.WriteLine (FormatText (txt.ToString ()));
607 output.WriteLine (txt.ToString ());
609 if (msg.RelatedSymbols != null) {
610 foreach (string s in msg.RelatedSymbols)
611 output.WriteLine (s + msg.MessageType + ")");
616 // Tracks reported missing types. It needs to be session specific
617 // because we can run in probing mode
619 public bool MissingTypeReported (ITypeDefinition typeDefinition)
621 if (reported_missing_definitions == null)
622 reported_missing_definitions = new HashSet<ITypeDefinition> ();
624 if (reported_missing_definitions.Contains (typeDefinition))
627 reported_missing_definitions.Add (typeDefinition);
633 // HACK: Temporary hack for broken repl flow
634 ErrorsCount = WarningsCount = 0;
638 sealed class NullReportPrinter : ReportPrinter
643 // Default message recorder, it uses two types of message groups.
644 // Common messages: messages reported in all sessions.
645 // Merged messages: union of all messages in all sessions.
647 // Used by the Lambda expressions to compile the code with various
648 // parameter values, or by attribute resolver
650 class SessionReportPrinter : ReportPrinter
652 List<AbstractMessage> session_messages;
654 // A collection of exactly same messages reported in all sessions
656 List<AbstractMessage> common_messages;
659 // A collection of unique messages reported in all sessions
661 List<AbstractMessage> merged_messages;
665 public void ClearSession ()
667 session_messages = null;
670 public override void Print (AbstractMessage msg, bool showFullPath)
673 // This line is useful when debugging recorded messages
675 // Console.WriteLine ("RECORDING: {0}", msg.Text);
677 if (session_messages == null)
678 session_messages = new List<AbstractMessage> ();
680 session_messages.Add (msg);
682 this.showFullPaths = showFullPath;
683 base.Print (msg, showFullPath);
686 public void EndSession ()
688 if (session_messages == null)
692 // Handles the first session
694 if (common_messages == null) {
695 common_messages = new List<AbstractMessage> (session_messages);
696 merged_messages = session_messages;
697 session_messages = null;
702 // Store common messages if any
704 for (int i = 0; i < common_messages.Count; ++i) {
705 AbstractMessage cmsg = common_messages[i];
706 bool common_msg_found = false;
707 foreach (AbstractMessage msg in session_messages) {
708 if (cmsg.Equals (msg)) {
709 common_msg_found = true;
714 if (!common_msg_found)
715 common_messages.RemoveAt (i);
719 // Merge session and previous messages
721 for (int i = 0; i < session_messages.Count; ++i) {
722 AbstractMessage msg = session_messages[i];
723 bool msg_found = false;
724 for (int ii = 0; ii < merged_messages.Count; ++ii) {
725 if (msg.Equals (merged_messages[ii])) {
732 merged_messages.Add (msg);
736 public bool IsEmpty {
738 return merged_messages == null && common_messages == null;
743 // Prints collected messages, common messages have a priority
745 public bool Merge (ReportPrinter dest)
747 var messages_to_print = merged_messages;
748 if (common_messages != null && common_messages.Count > 0) {
749 messages_to_print = common_messages;
752 if (messages_to_print == null)
755 bool error_msg = false;
756 foreach (AbstractMessage msg in messages_to_print) {
757 dest.Print (msg, showFullPaths);
758 error_msg |= !msg.IsWarning;
761 if (reported_missing_definitions != null) {
762 foreach (var missing in reported_missing_definitions)
763 dest.MissingTypeReported (missing);
770 public class StreamReportPrinter : ReportPrinter
772 readonly TextWriter writer;
774 public StreamReportPrinter (TextWriter writer)
776 this.writer = writer;
779 public override void Print (AbstractMessage msg, bool showFullPath)
781 Print (msg, writer, showFullPath);
782 base.Print (msg, showFullPath);
786 public 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){
805 case "xterm-256color":
812 if (!(UnixUtils.isatty (1) && UnixUtils.isatty (2)))
815 string config = Environment.GetEnvironmentVariable ("MCS_COLORS");
817 config = "errors=red";
818 //config = "brightwhite,red";
821 if (config == "disable")
824 if (!config.StartsWith ("errors="))
827 config = config.Substring (7);
829 int p = config.IndexOf (",");
831 prefix = GetForeground (config);
833 prefix = GetBackground (config.Substring (p+1)) + GetForeground (config.Substring (0, p));
834 postfix = "\x001b[0m";
837 public ConsoleReportPrinter ()
838 : base (Console.Error)
842 public ConsoleReportPrinter (TextWriter writer)
847 static int NameToCode (string s)
872 // maps a color name to its xterm color code
874 static string GetForeground (string s)
878 if (s.StartsWith ("bright")) {
884 return "\x001b[" + highcode + (30 + NameToCode (s)).ToString () + "m";
887 static string GetBackground (string s)
889 return "\x001b[" + (40 + NameToCode (s)).ToString () + "m";
892 protected override string FormatText (string txt)
895 return prefix + txt + postfix;
903 public enum TimerType
906 AssemblyBuilderSetup,
911 ModuleDefinitionTotal,
919 readonly Stopwatch[] timers;
922 public TimeReporter (bool enabled)
927 timers = new Stopwatch[System.Enum.GetValues(typeof (TimerType)).Length];
930 public void Start (TimerType type)
932 if (timers != null) {
933 var sw = new Stopwatch ();
934 timers[(int) type] = sw;
939 public void StartTotal ()
941 total = new Stopwatch ();
945 public void Stop (TimerType type)
947 if (timers != null) {
948 timers[(int) type].Stop ();
952 public void StopTotal ()
957 public void ShowStats ()
962 Dictionary<TimerType, string> timer_names = new Dictionary<TimerType,string> {
963 { TimerType.ParseTotal, "Parsing source files" },
964 { TimerType.AssemblyBuilderSetup, "Assembly builder setup" },
965 { TimerType.CreateTypeTotal, "Compiled types created" },
966 { TimerType.ReferencesLoading, "Referenced assemblies loading" },
967 { TimerType.ReferencesImporting, "Referenced assemblies importing" },
968 { TimerType.PredefinedTypesInit, "Predefined types initialization" },
969 { TimerType.ModuleDefinitionTotal, "Module definition" },
970 { TimerType.EmitTotal, "Resolving and emitting members blocks" },
971 { TimerType.CloseTypes, "Module types closed" },
972 { TimerType.Resouces, "Embedding resources" },
973 { TimerType.OutputSave, "Writing output file" },
974 { TimerType.DebugSave, "Writing debug symbols file" },
978 double percentage = (double) total.ElapsedMilliseconds / 100;
979 long subtotal = total.ElapsedMilliseconds;
980 foreach (var timer in timers) {
981 string msg = timer_names[(TimerType) counter++];
982 var ms = timer == null ? 0 : timer.ElapsedMilliseconds;
983 Console.WriteLine ("{0,4:0.0}% {1,5}ms {2}", ms / percentage, ms, msg);
987 Console.WriteLine ("{0,4:0.0}% {1,5}ms Other tasks", subtotal / percentage, subtotal);
988 Console.WriteLine ();
989 Console.WriteLine ("Total elapsed time: {0}", total.Elapsed);
993 public class InternalErrorException : Exception {
994 public InternalErrorException (MemberCore mc, Exception e)
995 : base (mc.Location + " " + mc.GetSignatureForError (), e)
999 public InternalErrorException ()
1000 : base ("Internal error")
1004 public InternalErrorException (string message)
1009 public InternalErrorException (string message, params object[] args)
1010 : base (String.Format (message, args))
1014 public InternalErrorException (Exception exception, string message, params object[] args)
1015 : base (String.Format (message, args), exception)
1019 public InternalErrorException (Exception e, Location loc)
1020 : base (loc.ToString (), e)
1025 class FatalException : Exception
1027 public FatalException (string message)
1034 /// Handles #pragma warning
1036 public class WarningRegions {
1038 abstract class PragmaCmd
1042 protected PragmaCmd (int line)
1047 public abstract bool IsEnabled (int code, bool previous);
1050 class Disable : PragmaCmd
1053 public Disable (int line, int code)
1059 public override bool IsEnabled (int code, bool previous)
1061 return this.code != code && previous;
1065 class DisableAll : PragmaCmd
1067 public DisableAll (int line)
1070 public override bool IsEnabled(int code, bool previous)
1076 class Enable : PragmaCmd
1079 public Enable (int line, int code)
1085 public override bool IsEnabled(int code, bool previous)
1087 return this.code == code || previous;
1091 class EnableAll : PragmaCmd
1093 public EnableAll (int line)
1096 public override bool IsEnabled(int code, bool previous)
1103 List<PragmaCmd> regions = new List<PragmaCmd> ();
1105 public void WarningDisable (int line)
1107 regions.Add (new DisableAll (line));
1110 public void WarningDisable (Location location, int code, Report Report)
1112 if (Report.CheckWarningCode (code, location))
1113 regions.Add (new Disable (location.Row, code));
1116 public void WarningEnable (int line)
1118 regions.Add (new EnableAll (line));
1121 public void WarningEnable (Location location, int code, CompilerContext context)
1123 if (!context.Report.CheckWarningCode (code, location))
1126 if (context.Settings.IsWarningDisabledGlobally (code))
1127 context.Report.Warning (1635, 1, location, "Cannot restore warning `CS{0:0000}' because it was disabled globally", code);
1129 regions.Add (new Enable (location.Row, code));
1132 public bool IsWarningEnabled (int code, int src_line)
1135 foreach (PragmaCmd pragma in regions) {
1136 if (src_line < pragma.Line)
1139 result = pragma.IsEnabled (code, result);