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,
62 static HashSet<int> AllWarningsHashSet;
64 public Report (CompilerContext context, ReportPrinter printer)
67 throw new ArgumentNullException ("settings");
69 throw new ArgumentNullException ("printer");
71 this.settings = context.Settings;
72 this.printer = printer;
75 public void DisableReporting ()
80 public void EnableReporting ()
85 public void FeatureIsNotAvailable (CompilerContext compiler, Location loc, string feature)
88 switch (compiler.Settings.Version) {
89 case LanguageVersion.ISO_1:
92 case LanguageVersion.ISO_2:
95 case LanguageVersion.V_3:
98 case LanguageVersion.V_4:
101 case LanguageVersion.V_5:
105 throw new InternalErrorException ("Invalid feature version", compiler.Settings.Version);
109 "Feature `{0}' cannot be used because it is not part of the C# {1} language specification",
113 public void FeatureIsNotSupported (Location loc, string feature)
116 "Feature `{0}' is not supported in Mono mcs1 compiler. Consider using the `gmcs' compiler instead",
120 public void RuntimeMissingSupport (Location loc, string feature)
122 Error (-88, loc, "Your .NET Runtime does not support `{0}'. Please use the latest Mono runtime instead.", feature);
126 /// In most error cases is very useful to have information about symbol that caused the error.
127 /// Call this method before you call Report.Error when it makes sense.
129 public void SymbolRelatedToPreviousError (Location loc, string symbol)
131 SymbolRelatedToPreviousError (loc.ToString ());
134 public void SymbolRelatedToPreviousError (MemberSpec ms)
136 if (reporting_disabled > 0 || !printer.HasRelatedSymbolSupport)
139 var mc = ms.MemberDefinition as MemberCore;
140 while (ms is ElementTypeSpec) {
141 ms = ((ElementTypeSpec) ms).Element;
142 mc = ms.MemberDefinition as MemberCore;
146 SymbolRelatedToPreviousError (mc);
148 if (ms.DeclaringType != null)
149 ms = ms.DeclaringType;
151 var imported_type = ms.MemberDefinition as ImportedTypeDefinition;
152 if (imported_type != null) {
153 var iad = imported_type.DeclaringAssembly as ImportedAssemblyDefinition;
154 SymbolRelatedToPreviousError (iad.Location);
159 public void SymbolRelatedToPreviousError (MemberCore mc)
161 SymbolRelatedToPreviousError (mc.Location, mc.GetSignatureForError ());
164 public void SymbolRelatedToPreviousError (string loc)
166 string msg = String.Format ("{0} (Location of the symbol related to previous ", loc);
167 if (extra_information.Contains (msg))
170 extra_information.Add (msg);
173 public bool CheckWarningCode (int code, Location loc)
175 if (AllWarningsHashSet == null)
176 AllWarningsHashSet = new HashSet<int> (AllWarnings);
178 if (AllWarningsHashSet.Contains (code))
181 Warning (1691, 1, loc, "`{0}' is not a valid warning number", code);
185 public void ExtraInformation (Location loc, string msg)
187 extra_information.Add (String.Format ("{0} {1}", loc, msg));
190 public WarningRegions RegisterWarningRegion (Location location)
192 WarningRegions regions;
193 if (warning_regions_table == null) {
195 warning_regions_table = new Dictionary<int, WarningRegions> ();
197 warning_regions_table.TryGetValue (location.File, out regions);
200 if (regions == null) {
201 regions = new WarningRegions ();
202 warning_regions_table.Add (location.File, regions);
208 public void Warning (int code, int level, Location loc, string message)
210 if (reporting_disabled > 0)
213 if (!settings.IsWarningEnabled (code, level))
216 if (warning_regions_table != null && !loc.IsNull) {
217 WarningRegions regions;
218 if (warning_regions_table.TryGetValue (loc.File, out regions) && !regions.IsWarningEnabled (code, loc.Row))
223 if (settings.IsWarningAsError (code)) {
224 message = "Warning as Error: " + message;
225 msg = new ErrorMessage (code, loc, message, extra_information);
227 msg = new WarningMessage (code, loc, message, extra_information);
230 extra_information.Clear ();
231 printer.Print (msg, settings.ShowFullPaths);
234 public void Warning (int code, int level, Location loc, string format, string arg)
236 Warning (code, level, loc, String.Format (format, arg));
239 public void Warning (int code, int level, Location loc, string format, string arg1, string arg2)
241 Warning (code, level, loc, String.Format (format, arg1, arg2));
244 public void Warning (int code, int level, Location loc, string format, params object[] args)
246 Warning (code, level, loc, String.Format (format, args));
249 public void Warning (int code, int level, string message)
251 Warning (code, level, Location.Null, message);
254 public void Warning (int code, int level, string format, string arg)
256 Warning (code, level, Location.Null, format, arg);
259 public void Warning (int code, int level, string format, string arg1, string arg2)
261 Warning (code, level, Location.Null, format, arg1, arg2);
264 public void Warning (int code, int level, string format, params string[] args)
266 Warning (code, level, Location.Null, String.Format (format, args));
270 // Warnings encountered so far
272 public int Warnings {
273 get { return printer.WarningsCount; }
276 public void Error (int code, Location loc, string error)
278 if (reporting_disabled > 0)
281 ErrorMessage msg = new ErrorMessage (code, loc, error, extra_information);
282 extra_information.Clear ();
284 printer.Print (msg, settings.ShowFullPaths);
286 if (settings.Stacktrace)
287 Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
289 if (printer.ErrorsCount == settings.FatalCounter)
290 throw new FatalException (msg.Text);
293 public void Error (int code, Location loc, string format, string arg)
295 Error (code, loc, String.Format (format, arg));
298 public void Error (int code, Location loc, string format, string arg1, string arg2)
300 Error (code, loc, String.Format (format, arg1, arg2));
303 public void Error (int code, Location loc, string format, params string[] args)
305 Error (code, loc, String.Format (format, args));
308 public void Error (int code, string error)
310 Error (code, Location.Null, error);
313 public void Error (int code, string format, string arg)
315 Error (code, Location.Null, format, arg);
318 public void Error (int code, string format, string arg1, string arg2)
320 Error (code, Location.Null, format, arg1, arg2);
323 public void Error (int code, string format, params string[] args)
325 Error (code, Location.Null, String.Format (format, args));
329 // Errors encountered so far
332 get { return printer.ErrorsCount; }
335 public bool IsDisabled {
337 return reporting_disabled > 0;
341 public ReportPrinter Printer {
342 get { return printer; }
345 public ReportPrinter SetPrinter (ReportPrinter printer)
347 ReportPrinter old = this.printer;
348 this.printer = printer;
352 [Conditional ("MCS_DEBUG")]
353 static public void Debug (string message, params object[] args)
355 Debug (4, message, args);
358 [Conditional ("MCS_DEBUG")]
359 static public void Debug (int category, string message, params object[] args)
361 // if ((category & DebugFlags) == 0)
364 StringBuilder sb = new StringBuilder (message);
366 if ((args != null) && (args.Length > 0)) {
370 foreach (object arg in args) {
377 // else if (arg is ICollection)
378 // sb.Append (PrintCollection ((ICollection) arg));
384 Console.WriteLine (sb.ToString ());
387 static public string PrintCollection (ICollection collection)
389 StringBuilder sb = new StringBuilder ();
391 sb.Append (collection.GetType ());
395 foreach (object o in collection) {
404 return sb.ToString ();
407 static string FriendlyStackTrace (StackTrace t)
409 StringBuilder sb = new StringBuilder ();
411 bool foundUserCode = false;
413 for (int i = 0; i < t.FrameCount; i++) {
414 StackFrame f = t.GetFrame (i);
415 var mb = f.GetMethod ();
417 if (!foundUserCode && mb.ReflectedType == typeof (Report))
420 foundUserCode = true;
424 if (f.GetFileLineNumber () > 0)
425 sb.AppendFormat ("(at {0}:{1}) ", f.GetFileName (), f.GetFileLineNumber ());
427 sb.AppendFormat ("{0}.{1} (", mb.ReflectedType.Name, mb.Name);
430 foreach (var pi in mb.GetParameters ()) {
435 sb.Append (pi.ParameterType.FullName);
440 return sb.ToString ();
444 public abstract class AbstractMessage
446 readonly string[] extra_info;
447 protected readonly int code;
448 protected readonly Location location;
449 readonly string message;
451 protected AbstractMessage (int code, Location loc, string msg, List<string> extraInfo)
455 this.code = 8000 - code;
459 if (extraInfo.Count != 0) {
460 this.extra_info = extraInfo.ToArray ();
464 protected AbstractMessage (AbstractMessage aMsg)
466 this.code = aMsg.code;
467 this.location = aMsg.location;
468 this.message = aMsg.message;
469 this.extra_info = aMsg.extra_info;
476 public override bool Equals (object obj)
478 AbstractMessage msg = obj as AbstractMessage;
482 return code == msg.code && location.Equals (msg.location) && message == msg.message;
485 public override int GetHashCode ()
487 return code.GetHashCode ();
490 public abstract bool IsWarning { get; }
492 public Location Location {
493 get { return location; }
496 public abstract string MessageType { get; }
498 public string[] RelatedSymbols {
499 get { return extra_info; }
503 get { return message; }
507 sealed class WarningMessage : AbstractMessage
509 public WarningMessage (int code, Location loc, string message, List<string> extra_info)
510 : base (code, loc, message, extra_info)
514 public override bool IsWarning {
518 public override string MessageType {
525 sealed class ErrorMessage : AbstractMessage
527 public ErrorMessage (int code, Location loc, string message, List<string> extraInfo)
528 : base (code, loc, message, extraInfo)
532 public ErrorMessage (AbstractMessage aMsg)
537 public override bool IsWarning {
538 get { return false; }
541 public override string MessageType {
549 // Generic base for any message writer
551 public abstract class ReportPrinter
553 protected HashSet<ITypeDefinition> reported_missing_definitions;
557 public int ErrorsCount { get; protected set; }
559 public int WarningsCount { get; private set; }
562 // When (symbols related to previous ...) can be used
564 public virtual bool HasRelatedSymbolSupport {
571 protected virtual string FormatText (string txt)
576 public virtual void Print (AbstractMessage msg, bool showFullPath)
585 protected void Print (AbstractMessage msg, TextWriter output, bool showFullPath)
587 StringBuilder txt = new StringBuilder ();
588 if (!msg.Location.IsNull) {
590 txt.Append (msg.Location.ToStringFullName ());
592 txt.Append (msg.Location.ToString ());
597 txt.AppendFormat ("{0} CS{1:0000}: {2}", msg.MessageType, msg.Code, msg.Text);
600 output.WriteLine (FormatText (txt.ToString ()));
602 output.WriteLine (txt.ToString ());
604 if (msg.RelatedSymbols != null) {
605 foreach (string s in msg.RelatedSymbols)
606 output.WriteLine (s + msg.MessageType + ")");
611 // Tracks reported missing types. It needs to be session specific
612 // because we can run in probing mode
614 public bool MissingTypeReported (ITypeDefinition typeDefinition)
616 if (reported_missing_definitions == null)
617 reported_missing_definitions = new HashSet<ITypeDefinition> ();
619 if (reported_missing_definitions.Contains (typeDefinition))
622 reported_missing_definitions.Add (typeDefinition);
628 // HACK: Temporary hack for broken repl flow
629 ErrorsCount = WarningsCount = 0;
633 sealed class NullReportPrinter : ReportPrinter
638 // Default message recorder, it uses two types of message groups.
639 // Common messages: messages reported in all sessions.
640 // Merged messages: union of all messages in all sessions.
642 // Used by the Lambda expressions to compile the code with various
643 // parameter values, or by attribute resolver
645 class SessionReportPrinter : ReportPrinter
647 List<AbstractMessage> session_messages;
649 // A collection of exactly same messages reported in all sessions
651 List<AbstractMessage> common_messages;
654 // A collection of unique messages reported in all sessions
656 List<AbstractMessage> merged_messages;
660 public void ClearSession ()
662 session_messages = null;
665 public override void Print (AbstractMessage msg, bool showFullPath)
668 // This line is useful when debugging recorded messages
670 // Console.WriteLine ("RECORDING: {0}", msg.Text);
672 if (session_messages == null)
673 session_messages = new List<AbstractMessage> ();
675 session_messages.Add (msg);
677 this.showFullPaths = showFullPath;
678 base.Print (msg, showFullPath);
681 public void EndSession ()
683 if (session_messages == null)
687 // Handles the first session
689 if (common_messages == null) {
690 common_messages = new List<AbstractMessage> (session_messages);
691 merged_messages = session_messages;
692 session_messages = null;
697 // Store common messages if any
699 for (int i = 0; i < common_messages.Count; ++i) {
700 AbstractMessage cmsg = common_messages[i];
701 bool common_msg_found = false;
702 foreach (AbstractMessage msg in session_messages) {
703 if (cmsg.Equals (msg)) {
704 common_msg_found = true;
709 if (!common_msg_found)
710 common_messages.RemoveAt (i);
714 // Merge session and previous messages
716 for (int i = 0; i < session_messages.Count; ++i) {
717 AbstractMessage msg = session_messages[i];
718 bool msg_found = false;
719 for (int ii = 0; ii < merged_messages.Count; ++ii) {
720 if (msg.Equals (merged_messages[ii])) {
727 merged_messages.Add (msg);
731 public bool IsEmpty {
733 return merged_messages == null && common_messages == null;
738 // Prints collected messages, common messages have a priority
740 public bool Merge (ReportPrinter dest)
742 var messages_to_print = merged_messages;
743 if (common_messages != null && common_messages.Count > 0) {
744 messages_to_print = common_messages;
747 if (messages_to_print == null)
750 bool error_msg = false;
751 foreach (AbstractMessage msg in messages_to_print) {
752 dest.Print (msg, showFullPaths);
753 error_msg |= !msg.IsWarning;
756 if (reported_missing_definitions != null) {
757 foreach (var missing in reported_missing_definitions)
758 dest.MissingTypeReported (missing);
765 public class StreamReportPrinter : ReportPrinter
767 readonly TextWriter writer;
769 public StreamReportPrinter (TextWriter writer)
771 this.writer = writer;
774 public override void Print (AbstractMessage msg, bool showFullPath)
776 Print (msg, writer, showFullPath);
777 base.Print (msg, showFullPath);
781 public class ConsoleReportPrinter : StreamReportPrinter
783 static readonly string prefix, postfix;
785 static ConsoleReportPrinter ()
787 string term = Environment.GetEnvironmentVariable ("TERM");
788 bool xterm_colors = false;
794 if (Environment.GetEnvironmentVariable ("COLORTERM") != null){
800 case "xterm-256color":
807 if (!(UnixUtils.isatty (1) && UnixUtils.isatty (2)))
810 string config = Environment.GetEnvironmentVariable ("MCS_COLORS");
812 config = "errors=red";
813 //config = "brightwhite,red";
816 if (config == "disable")
819 if (!config.StartsWith ("errors="))
822 config = config.Substring (7);
824 int p = config.IndexOf (",");
826 prefix = GetForeground (config);
828 prefix = GetBackground (config.Substring (p+1)) + GetForeground (config.Substring (0, p));
829 postfix = "\x001b[0m";
832 public ConsoleReportPrinter ()
833 : base (Console.Error)
837 public ConsoleReportPrinter (TextWriter writer)
842 static int NameToCode (string s)
867 // maps a color name to its xterm color code
869 static string GetForeground (string s)
873 if (s.StartsWith ("bright")) {
879 return "\x001b[" + highcode + (30 + NameToCode (s)).ToString () + "m";
882 static string GetBackground (string s)
884 return "\x001b[" + (40 + NameToCode (s)).ToString () + "m";
887 protected override string FormatText (string txt)
890 return prefix + txt + postfix;
898 public enum TimerType
901 AssemblyBuilderSetup,
906 ModuleDefinitionTotal,
914 readonly Stopwatch[] timers;
917 public TimeReporter (bool enabled)
922 timers = new Stopwatch[System.Enum.GetValues(typeof (TimerType)).Length];
925 public void Start (TimerType type)
927 if (timers != null) {
928 var sw = new Stopwatch ();
929 timers[(int) type] = sw;
934 public void StartTotal ()
936 total = new Stopwatch ();
940 public void Stop (TimerType type)
942 if (timers != null) {
943 timers[(int) type].Stop ();
947 public void StopTotal ()
952 public void ShowStats ()
957 Dictionary<TimerType, string> timer_names = new Dictionary<TimerType,string> () {
958 { TimerType.ParseTotal, "Parsing source files" },
959 { TimerType.AssemblyBuilderSetup, "Assembly builder setup" },
960 { TimerType.CreateTypeTotal, "Compiled types created" },
961 { TimerType.ReferencesLoading, "Referenced assemblies loading" },
962 { TimerType.ReferencesImporting, "Referenced assemblies importing" },
963 { TimerType.PredefinedTypesInit, "Predefined types initialization" },
964 { TimerType.ModuleDefinitionTotal, "Module definition" },
965 { TimerType.EmitTotal, "Resolving and emitting members blocks" },
966 { TimerType.CloseTypes, "Module types closed" },
967 { TimerType.Resouces, "Embedding resources" },
968 { TimerType.OutputSave, "Writing output file" },
969 { TimerType.DebugSave, "Writing debug symbols file" },
973 double percentage = (double) total.ElapsedMilliseconds / 100;
974 long subtotal = total.ElapsedMilliseconds;
975 foreach (var timer in timers) {
976 string msg = timer_names[(TimerType) counter++];
977 var ms = timer == null ? 0 : timer.ElapsedMilliseconds;
978 Console.WriteLine ("{0,4:0.0}% {1,5}ms {2}", ms / percentage, ms, msg);
982 Console.WriteLine ("{0,4:0.0}% {1,5}ms Other tasks", subtotal / percentage, subtotal);
983 Console.WriteLine ();
984 Console.WriteLine ("Total elapsed time: {0}", total.Elapsed);
988 public class InternalErrorException : Exception {
989 public InternalErrorException (MemberCore mc, Exception e)
990 : base (mc.Location + " " + mc.GetSignatureForError (), e)
994 public InternalErrorException ()
995 : base ("Internal error")
999 public InternalErrorException (string message)
1004 public InternalErrorException (string message, params object[] args)
1005 : base (String.Format (message, args))
1009 public InternalErrorException (Exception exception, string message, params object[] args)
1010 : base (String.Format (message, args), exception)
1014 public InternalErrorException (Exception e, Location loc)
1015 : base (loc.ToString (), e)
1020 class FatalException : Exception
1022 public FatalException (string message)
1029 /// Handles #pragma warning
1031 public class WarningRegions {
1033 abstract class PragmaCmd
1037 protected PragmaCmd (int line)
1042 public abstract bool IsEnabled (int code, bool previous);
1045 class Disable : PragmaCmd
1048 public Disable (int line, int code)
1054 public override bool IsEnabled (int code, bool previous)
1056 return this.code == code ? false : previous;
1060 class DisableAll : PragmaCmd
1062 public DisableAll (int line)
1065 public override bool IsEnabled(int code, bool previous)
1071 class Enable : PragmaCmd
1074 public Enable (int line, int code)
1080 public override bool IsEnabled(int code, bool previous)
1082 return this.code == code ? true : previous;
1086 class EnableAll : PragmaCmd
1088 public EnableAll (int line)
1091 public override bool IsEnabled(int code, bool previous)
1098 List<PragmaCmd> regions = new List<PragmaCmd> ();
1100 public void WarningDisable (int line)
1102 regions.Add (new DisableAll (line));
1105 public void WarningDisable (Location location, int code, Report Report)
1107 if (Report.CheckWarningCode (code, location))
1108 regions.Add (new Disable (location.Row, code));
1111 public void WarningEnable (int line)
1113 regions.Add (new EnableAll (line));
1116 public void WarningEnable (Location location, int code, CompilerContext context)
1118 if (!context.Report.CheckWarningCode (code, location))
1121 if (context.Settings.IsWarningDisabledGlobally (code))
1122 context.Report.Warning (1635, 1, location, "Cannot restore warning `CS{0:0000}' because it was disabled globally", code);
1124 regions.Add (new Enable (location.Row, code));
1127 public bool IsWarningEnabled (int code, int src_line)
1130 foreach (PragmaCmd pragma in regions) {
1131 if (src_line < pragma.Line)
1134 result = pragma.IsEnabled (code, result);