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:
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 public void RuntimeMissingSupport (Location loc, string feature)
124 Error (-88, loc, "Your .NET Runtime does not support `{0}'. Please use the latest Mono runtime instead.", feature);
128 /// In most error cases is very useful to have information about symbol that caused the error.
129 /// Call this method before you call Report.Error when it makes sense.
131 public void SymbolRelatedToPreviousError (Location loc, string symbol)
133 SymbolRelatedToPreviousError (loc.ToString ());
136 public void SymbolRelatedToPreviousError (MemberSpec ms)
138 if (reporting_disabled > 0 || !printer.HasRelatedSymbolSupport)
141 var mc = ms.MemberDefinition as MemberCore;
142 while (ms is ElementTypeSpec) {
143 ms = ((ElementTypeSpec) ms).Element;
144 mc = ms.MemberDefinition as MemberCore;
148 SymbolRelatedToPreviousError (mc);
150 if (ms.DeclaringType != null)
151 ms = ms.DeclaringType;
153 var imported_type = ms.MemberDefinition as ImportedTypeDefinition;
154 if (imported_type != null) {
155 var iad = imported_type.DeclaringAssembly as ImportedAssemblyDefinition;
156 SymbolRelatedToPreviousError (iad.Location);
161 public void SymbolRelatedToPreviousError (MemberCore mc)
163 SymbolRelatedToPreviousError (mc.Location, mc.GetSignatureForError ());
166 public void SymbolRelatedToPreviousError (string loc)
168 string msg = String.Format ("{0} (Location of the symbol related to previous ", loc);
169 if (extra_information.Contains (msg))
172 extra_information.Add (msg);
175 public bool CheckWarningCode (int code, Location loc)
177 if (AllWarningsHashSet == null)
178 AllWarningsHashSet = new HashSet<int> (AllWarnings);
180 if (AllWarningsHashSet.Contains (code))
183 Warning (1691, 1, loc, "`{0}' is not a valid warning number", code);
187 public void ExtraInformation (Location loc, string msg)
189 extra_information.Add (String.Format ("{0} {1}", loc, msg));
192 public WarningRegions RegisterWarningRegion (Location location)
194 WarningRegions regions;
195 if (warning_regions_table == null) {
197 warning_regions_table = new Dictionary<int, WarningRegions> ();
199 warning_regions_table.TryGetValue (location.File, out regions);
202 if (regions == null) {
203 regions = new WarningRegions ();
204 warning_regions_table.Add (location.File, regions);
210 public void Warning (int code, int level, Location loc, string message)
212 if (reporting_disabled > 0)
215 if (!settings.IsWarningEnabled (code, level))
218 if (warning_regions_table != null && !loc.IsNull) {
219 WarningRegions regions;
220 if (warning_regions_table.TryGetValue (loc.File, out regions) && !regions.IsWarningEnabled (code, loc.Row))
225 if (settings.IsWarningAsError (code)) {
226 message = "Warning as Error: " + message;
227 msg = new ErrorMessage (code, loc, message, extra_information);
229 msg = new WarningMessage (code, loc, message, extra_information);
232 extra_information.Clear ();
233 printer.Print (msg, settings.ShowFullPaths);
236 public void Warning (int code, int level, Location loc, string format, string arg)
238 Warning (code, level, loc, String.Format (format, arg));
241 public void Warning (int code, int level, Location loc, string format, string arg1, string arg2)
243 Warning (code, level, loc, String.Format (format, arg1, arg2));
246 public void Warning (int code, int level, Location loc, string format, params object[] args)
248 Warning (code, level, loc, String.Format (format, args));
251 public void Warning (int code, int level, string message)
253 Warning (code, level, Location.Null, message);
256 public void Warning (int code, int level, string format, string arg)
258 Warning (code, level, Location.Null, format, arg);
261 public void Warning (int code, int level, string format, string arg1, string arg2)
263 Warning (code, level, Location.Null, format, arg1, arg2);
266 public void Warning (int code, int level, string format, params string[] args)
268 Warning (code, level, Location.Null, String.Format (format, args));
272 // Warnings encountered so far
274 public int Warnings {
275 get { return printer.WarningsCount; }
278 public void Error (int code, Location loc, string error)
280 if (reporting_disabled > 0)
283 ErrorMessage msg = new ErrorMessage (code, loc, error, extra_information);
284 extra_information.Clear ();
286 printer.Print (msg, settings.ShowFullPaths);
288 if (settings.Stacktrace)
289 Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
291 if (printer.ErrorsCount == settings.FatalCounter)
292 throw new FatalException (msg.Text);
295 public void Error (int code, Location loc, string format, string arg)
297 Error (code, loc, String.Format (format, arg));
300 public void Error (int code, Location loc, string format, string arg1, string arg2)
302 Error (code, loc, String.Format (format, arg1, arg2));
305 public void Error (int code, Location loc, string format, params string[] args)
307 Error (code, loc, String.Format (format, args));
310 public void Error (int code, string error)
312 Error (code, Location.Null, error);
315 public void Error (int code, string format, string arg)
317 Error (code, Location.Null, format, arg);
320 public void Error (int code, string format, string arg1, string arg2)
322 Error (code, Location.Null, format, arg1, arg2);
325 public void Error (int code, string format, params string[] args)
327 Error (code, Location.Null, String.Format (format, args));
331 // Errors encountered so far
334 get { return printer.ErrorsCount; }
337 public bool IsDisabled {
339 return reporting_disabled > 0;
343 public ReportPrinter Printer {
344 get { return printer; }
347 public ReportPrinter SetPrinter (ReportPrinter printer)
349 ReportPrinter old = this.printer;
350 this.printer = printer;
354 [Conditional ("MCS_DEBUG")]
355 static public void Debug (string message, params object[] args)
357 Debug (4, message, args);
360 [Conditional ("MCS_DEBUG")]
361 static public void Debug (int category, string message, params object[] args)
363 // if ((category & DebugFlags) == 0)
366 StringBuilder sb = new StringBuilder (message);
368 if ((args != null) && (args.Length > 0)) {
372 foreach (object arg in args) {
379 // else if (arg is ICollection)
380 // sb.Append (PrintCollection ((ICollection) arg));
386 Console.WriteLine (sb.ToString ());
389 static public string PrintCollection (ICollection collection)
391 StringBuilder sb = new StringBuilder ();
393 sb.Append (collection.GetType ());
397 foreach (object o in collection) {
406 return sb.ToString ();
409 static string FriendlyStackTrace (StackTrace t)
411 StringBuilder sb = new StringBuilder ();
413 bool foundUserCode = false;
415 for (int i = 0; i < t.FrameCount; i++) {
416 StackFrame f = t.GetFrame (i);
417 var mb = f.GetMethod ();
419 if (!foundUserCode && mb.ReflectedType == typeof (Report))
422 foundUserCode = true;
426 if (f.GetFileLineNumber () > 0)
427 sb.AppendFormat ("(at {0}:{1}) ", f.GetFileName (), f.GetFileLineNumber ());
429 sb.AppendFormat ("{0}.{1} (", mb.ReflectedType.Name, mb.Name);
432 foreach (var pi in mb.GetParameters ()) {
437 sb.Append (pi.ParameterType.FullName);
442 return sb.ToString ();
446 public abstract class AbstractMessage
448 readonly string[] extra_info;
449 protected readonly int code;
450 protected readonly Location location;
451 readonly string message;
453 protected AbstractMessage (int code, Location loc, string msg, List<string> extraInfo)
457 this.code = 8000 - code;
461 if (extraInfo.Count != 0) {
462 this.extra_info = extraInfo.ToArray ();
466 protected AbstractMessage (AbstractMessage aMsg)
468 this.code = aMsg.code;
469 this.location = aMsg.location;
470 this.message = aMsg.message;
471 this.extra_info = aMsg.extra_info;
478 public override bool Equals (object obj)
480 AbstractMessage msg = obj as AbstractMessage;
484 return code == msg.code && location.Equals (msg.location) && message == msg.message;
487 public override int GetHashCode ()
489 return code.GetHashCode ();
492 public abstract bool IsWarning { get; }
494 public Location Location {
495 get { return location; }
498 public abstract string MessageType { get; }
500 public string[] RelatedSymbols {
501 get { return extra_info; }
505 get { return message; }
509 sealed class WarningMessage : AbstractMessage
511 public WarningMessage (int code, Location loc, string message, List<string> extra_info)
512 : base (code, loc, message, extra_info)
516 public override bool IsWarning {
520 public override string MessageType {
527 sealed class ErrorMessage : AbstractMessage
529 public ErrorMessage (int code, Location loc, string message, List<string> extraInfo)
530 : base (code, loc, message, extraInfo)
534 public ErrorMessage (AbstractMessage aMsg)
539 public override bool IsWarning {
540 get { return false; }
543 public override string MessageType {
551 // Generic base for any message writer
553 public abstract class ReportPrinter
555 protected HashSet<ITypeDefinition> reported_missing_definitions;
559 public int ErrorsCount { get; protected set; }
561 public int WarningsCount { get; private set; }
564 // When (symbols related to previous ...) can be used
566 public virtual bool HasRelatedSymbolSupport {
573 protected virtual string FormatText (string txt)
578 public virtual void Print (AbstractMessage msg, bool showFullPath)
587 protected void Print (AbstractMessage msg, TextWriter output, bool showFullPath)
589 StringBuilder txt = new StringBuilder ();
590 if (!msg.Location.IsNull) {
592 txt.Append (msg.Location.ToStringFullName ());
594 txt.Append (msg.Location.ToString ());
599 txt.AppendFormat ("{0} CS{1:0000}: {2}", msg.MessageType, msg.Code, msg.Text);
602 output.WriteLine (FormatText (txt.ToString ()));
604 output.WriteLine (txt.ToString ());
606 if (msg.RelatedSymbols != null) {
607 foreach (string s in msg.RelatedSymbols)
608 output.WriteLine (s + msg.MessageType + ")");
613 // Tracks reported missing types. It needs to be session specific
614 // because we can run in probing mode
616 public bool MissingTypeReported (ITypeDefinition typeDefinition)
618 if (reported_missing_definitions == null)
619 reported_missing_definitions = new HashSet<ITypeDefinition> ();
621 if (reported_missing_definitions.Contains (typeDefinition))
624 reported_missing_definitions.Add (typeDefinition);
630 // HACK: Temporary hack for broken repl flow
631 ErrorsCount = WarningsCount = 0;
635 sealed class NullReportPrinter : ReportPrinter
640 // Default message recorder, it uses two types of message groups.
641 // Common messages: messages reported in all sessions.
642 // Merged messages: union of all messages in all sessions.
644 // Used by the Lambda expressions to compile the code with various
645 // parameter values, or by attribute resolver
647 class SessionReportPrinter : ReportPrinter
649 List<AbstractMessage> session_messages;
651 // A collection of exactly same messages reported in all sessions
653 List<AbstractMessage> common_messages;
656 // A collection of unique messages reported in all sessions
658 List<AbstractMessage> merged_messages;
662 public void ClearSession ()
664 session_messages = null;
667 public override void Print (AbstractMessage msg, bool showFullPath)
670 // This line is useful when debugging recorded messages
672 // Console.WriteLine ("RECORDING: {0}", msg.Text);
674 if (session_messages == null)
675 session_messages = new List<AbstractMessage> ();
677 session_messages.Add (msg);
679 this.showFullPaths = showFullPath;
680 base.Print (msg, showFullPath);
683 public void EndSession ()
685 if (session_messages == null)
689 // Handles the first session
691 if (common_messages == null) {
692 common_messages = new List<AbstractMessage> (session_messages);
693 merged_messages = session_messages;
694 session_messages = null;
699 // Store common messages if any
701 for (int i = 0; i < common_messages.Count; ++i) {
702 AbstractMessage cmsg = common_messages[i];
703 bool common_msg_found = false;
704 foreach (AbstractMessage msg in session_messages) {
705 if (cmsg.Equals (msg)) {
706 common_msg_found = true;
711 if (!common_msg_found)
712 common_messages.RemoveAt (i);
716 // Merge session and previous messages
718 for (int i = 0; i < session_messages.Count; ++i) {
719 AbstractMessage msg = session_messages[i];
720 bool msg_found = false;
721 for (int ii = 0; ii < merged_messages.Count; ++ii) {
722 if (msg.Equals (merged_messages[ii])) {
729 merged_messages.Add (msg);
733 public bool IsEmpty {
735 return merged_messages == null && common_messages == null;
740 // Prints collected messages, common messages have a priority
742 public bool Merge (ReportPrinter dest)
744 var messages_to_print = merged_messages;
745 if (common_messages != null && common_messages.Count > 0) {
746 messages_to_print = common_messages;
749 if (messages_to_print == null)
752 bool error_msg = false;
753 foreach (AbstractMessage msg in messages_to_print) {
754 dest.Print (msg, showFullPaths);
755 error_msg |= !msg.IsWarning;
758 if (reported_missing_definitions != null) {
759 foreach (var missing in reported_missing_definitions)
760 dest.MissingTypeReported (missing);
767 public class StreamReportPrinter : ReportPrinter
769 readonly TextWriter writer;
771 public StreamReportPrinter (TextWriter writer)
773 this.writer = writer;
776 public override void Print (AbstractMessage msg, bool showFullPath)
778 Print (msg, writer, showFullPath);
779 base.Print (msg, showFullPath);
783 public class ConsoleReportPrinter : StreamReportPrinter
785 static readonly string prefix, postfix;
787 static ConsoleReportPrinter ()
789 string term = Environment.GetEnvironmentVariable ("TERM");
790 bool xterm_colors = false;
796 if (Environment.GetEnvironmentVariable ("COLORTERM") != null){
802 case "xterm-256color":
809 if (!(UnixUtils.isatty (1) && UnixUtils.isatty (2)))
812 string config = Environment.GetEnvironmentVariable ("MCS_COLORS");
814 config = "errors=red";
815 //config = "brightwhite,red";
818 if (config == "disable")
821 if (!config.StartsWith ("errors="))
824 config = config.Substring (7);
826 int p = config.IndexOf (",");
828 prefix = GetForeground (config);
830 prefix = GetBackground (config.Substring (p+1)) + GetForeground (config.Substring (0, p));
831 postfix = "\x001b[0m";
834 public ConsoleReportPrinter ()
835 : base (Console.Error)
839 public ConsoleReportPrinter (TextWriter writer)
844 static int NameToCode (string s)
869 // maps a color name to its xterm color code
871 static string GetForeground (string s)
875 if (s.StartsWith ("bright")) {
881 return "\x001b[" + highcode + (30 + NameToCode (s)).ToString () + "m";
884 static string GetBackground (string s)
886 return "\x001b[" + (40 + NameToCode (s)).ToString () + "m";
889 protected override string FormatText (string txt)
892 return prefix + txt + postfix;
900 public enum TimerType
903 AssemblyBuilderSetup,
908 ModuleDefinitionTotal,
916 readonly Stopwatch[] timers;
919 public TimeReporter (bool enabled)
924 timers = new Stopwatch[System.Enum.GetValues(typeof (TimerType)).Length];
927 public void Start (TimerType type)
929 if (timers != null) {
930 var sw = new Stopwatch ();
931 timers[(int) type] = sw;
936 public void StartTotal ()
938 total = new Stopwatch ();
942 public void Stop (TimerType type)
944 if (timers != null) {
945 timers[(int) type].Stop ();
949 public void StopTotal ()
954 public void ShowStats ()
959 Dictionary<TimerType, string> timer_names = new Dictionary<TimerType,string> {
960 { TimerType.ParseTotal, "Parsing source files" },
961 { TimerType.AssemblyBuilderSetup, "Assembly builder setup" },
962 { TimerType.CreateTypeTotal, "Compiled types created" },
963 { TimerType.ReferencesLoading, "Referenced assemblies loading" },
964 { TimerType.ReferencesImporting, "Referenced assemblies importing" },
965 { TimerType.PredefinedTypesInit, "Predefined types initialization" },
966 { TimerType.ModuleDefinitionTotal, "Module definition" },
967 { TimerType.EmitTotal, "Resolving and emitting members blocks" },
968 { TimerType.CloseTypes, "Module types closed" },
969 { TimerType.Resouces, "Embedding resources" },
970 { TimerType.OutputSave, "Writing output file" },
971 { TimerType.DebugSave, "Writing debug symbols file" },
975 double percentage = (double) total.ElapsedMilliseconds / 100;
976 long subtotal = total.ElapsedMilliseconds;
977 foreach (var timer in timers) {
978 string msg = timer_names[(TimerType) counter++];
979 var ms = timer == null ? 0 : timer.ElapsedMilliseconds;
980 Console.WriteLine ("{0,4:0.0}% {1,5}ms {2}", ms / percentage, ms, msg);
984 Console.WriteLine ("{0,4:0.0}% {1,5}ms Other tasks", subtotal / percentage, subtotal);
985 Console.WriteLine ();
986 Console.WriteLine ("Total elapsed time: {0}", total.Elapsed);
990 public class InternalErrorException : Exception {
991 public InternalErrorException (MemberCore mc, Exception e)
992 : base (mc.Location + " " + mc.GetSignatureForError (), e)
996 public InternalErrorException ()
997 : base ("Internal error")
1001 public InternalErrorException (string message)
1006 public InternalErrorException (string message, params object[] args)
1007 : base (String.Format (message, args))
1011 public InternalErrorException (Exception exception, string message, params object[] args)
1012 : base (String.Format (message, args), exception)
1016 public InternalErrorException (Exception e, Location loc)
1017 : base (loc.ToString (), e)
1022 class FatalException : Exception
1024 public FatalException (string message)
1031 /// Handles #pragma warning
1033 public class WarningRegions {
1035 abstract class PragmaCmd
1039 protected PragmaCmd (int line)
1044 public abstract bool IsEnabled (int code, bool previous);
1047 class Disable : PragmaCmd
1050 public Disable (int line, int code)
1056 public override bool IsEnabled (int code, bool previous)
1058 return this.code != code && previous;
1062 class DisableAll : PragmaCmd
1064 public DisableAll (int line)
1067 public override bool IsEnabled(int code, bool previous)
1073 class Enable : PragmaCmd
1076 public Enable (int line, int code)
1082 public override bool IsEnabled(int code, bool previous)
1084 return this.code == code || previous;
1088 class EnableAll : PragmaCmd
1090 public EnableAll (int line)
1093 public override bool IsEnabled(int code, bool previous)
1100 List<PragmaCmd> regions = new List<PragmaCmd> ();
1102 public void WarningDisable (int line)
1104 regions.Add (new DisableAll (line));
1107 public void WarningDisable (Location location, int code, Report Report)
1109 if (Report.CheckWarningCode (code, location))
1110 regions.Add (new Disable (location.Row, code));
1113 public void WarningEnable (int line)
1115 regions.Add (new EnableAll (line));
1118 public void WarningEnable (Location location, int code, CompilerContext context)
1120 if (!context.Report.CheckWarningCode (code, location))
1123 if (context.Settings.IsWarningDisabledGlobally (code))
1124 context.Report.Warning (1635, 1, location, "Cannot restore warning `CS{0:0000}' because it was disabled globally", code);
1126 regions.Add (new Enable (location.Row, code));
1129 public bool IsWarningEnabled (int code, int src_line)
1132 foreach (PragmaCmd pragma in regions) {
1133 if (src_line < pragma.Line)
1136 result = pragma.IsEnabled (code, result);