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 public Report (CompilerContext context, ReportPrinter printer)
67 throw new ArgumentNullException ("context");
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:
104 case LanguageVersion.V_6:
108 throw new InternalErrorException ("Invalid feature version", compiler.Settings.Version);
112 "Feature `{0}' cannot be used because it is not part of the C# {1} language specification",
116 public void FeatureIsNotSupported (Location loc, string feature)
119 "Feature `{0}' is not supported in Mono mcs1 compiler. Consider using the `gmcs' compiler instead",
123 public void RuntimeMissingSupport (Location loc, string feature)
125 Error (-88, loc, "Your .NET Runtime does not support `{0}'. Please use the latest Mono runtime instead.", feature);
129 /// In most error cases is very useful to have information about symbol that caused the error.
130 /// Call this method before you call Report.Error when it makes sense.
132 public void SymbolRelatedToPreviousError (Location loc, string symbol)
134 SymbolRelatedToPreviousError (loc.ToString ());
137 public void SymbolRelatedToPreviousError (MemberSpec ms)
139 if (reporting_disabled > 0 || !printer.HasRelatedSymbolSupport)
142 var mc = ms.MemberDefinition as MemberCore;
143 while (ms is ElementTypeSpec) {
144 ms = ((ElementTypeSpec) ms).Element;
145 mc = ms.MemberDefinition as MemberCore;
149 SymbolRelatedToPreviousError (mc);
151 if (ms.DeclaringType != null)
152 ms = ms.DeclaringType;
154 var imported_type = ms.MemberDefinition as ImportedTypeDefinition;
155 if (imported_type != null) {
156 var iad = imported_type.DeclaringAssembly as ImportedAssemblyDefinition;
157 SymbolRelatedToPreviousError (iad.Location);
162 public void SymbolRelatedToPreviousError (MemberCore mc)
164 SymbolRelatedToPreviousError (mc.Location, mc.GetSignatureForError ());
167 public void SymbolRelatedToPreviousError (string loc)
169 string msg = String.Format ("{0} (Location of the symbol related to previous ", loc);
170 if (extra_information.Contains (msg))
173 extra_information.Add (msg);
176 public void ExtraInformation (Location loc, string msg)
178 extra_information.Add (String.Format ("{0} {1}", loc, msg));
181 public WarningRegions RegisterWarningRegion (Location location)
183 WarningRegions regions;
184 if (warning_regions_table == null) {
186 warning_regions_table = new Dictionary<int, WarningRegions> ();
188 warning_regions_table.TryGetValue (location.File, out regions);
191 if (regions == null) {
192 regions = new WarningRegions ();
193 warning_regions_table.Add (location.File, regions);
199 public void Warning (int code, int level, Location loc, string message)
201 if (reporting_disabled > 0)
204 if (!settings.IsWarningEnabled (code, level))
207 if (warning_regions_table != null && !loc.IsNull) {
208 WarningRegions regions;
209 if (warning_regions_table.TryGetValue (loc.File, out regions) && !regions.IsWarningEnabled (code, loc.Row))
214 if (settings.IsWarningAsError (code)) {
215 message = "Warning as Error: " + message;
216 msg = new ErrorMessage (code, loc, message, extra_information);
218 msg = new WarningMessage (code, loc, message, extra_information);
221 extra_information.Clear ();
222 printer.Print (msg, settings.ShowFullPaths);
225 public void Warning (int code, int level, Location loc, string format, string arg)
227 Warning (code, level, loc, String.Format (format, arg));
230 public void Warning (int code, int level, Location loc, string format, string arg1, string arg2)
232 Warning (code, level, loc, String.Format (format, arg1, arg2));
235 public void Warning (int code, int level, Location loc, string format, params object[] args)
237 Warning (code, level, loc, String.Format (format, args));
240 public void Warning (int code, int level, string message)
242 Warning (code, level, Location.Null, message);
245 public void Warning (int code, int level, string format, string arg)
247 Warning (code, level, Location.Null, format, arg);
250 public void Warning (int code, int level, string format, string arg1, string arg2)
252 Warning (code, level, Location.Null, format, arg1, arg2);
255 public void Warning (int code, int level, string format, params string[] args)
257 Warning (code, level, Location.Null, String.Format (format, args));
261 // Warnings encountered so far
263 public int Warnings {
264 get { return printer.WarningsCount; }
267 public void Error (int code, Location loc, string error)
269 if (reporting_disabled > 0)
272 ErrorMessage msg = new ErrorMessage (code, loc, error, extra_information);
273 extra_information.Clear ();
275 printer.Print (msg, settings.ShowFullPaths);
277 if (settings.Stacktrace)
278 Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
280 if (printer.ErrorsCount == settings.FatalCounter)
281 throw new FatalException (msg.Text);
284 public void Error (int code, Location loc, string format, string arg)
286 Error (code, loc, String.Format (format, arg));
289 public void Error (int code, Location loc, string format, string arg1, string arg2)
291 Error (code, loc, String.Format (format, arg1, arg2));
294 public void Error (int code, Location loc, string format, params string[] args)
296 Error (code, loc, String.Format (format, args));
299 public void Error (int code, string error)
301 Error (code, Location.Null, error);
304 public void Error (int code, string format, string arg)
306 Error (code, Location.Null, format, arg);
309 public void Error (int code, string format, string arg1, string arg2)
311 Error (code, Location.Null, format, arg1, arg2);
314 public void Error (int code, string format, params string[] args)
316 Error (code, Location.Null, String.Format (format, args));
320 // Errors encountered so far
323 get { return printer.ErrorsCount; }
326 public bool IsDisabled {
328 return reporting_disabled > 0;
332 public ReportPrinter Printer {
333 get { return printer; }
336 public ReportPrinter SetPrinter (ReportPrinter printer)
338 ReportPrinter old = this.printer;
339 this.printer = printer;
343 [Conditional ("MCS_DEBUG")]
344 static public void Debug (string message, params object[] args)
346 Debug (4, message, args);
349 [Conditional ("MCS_DEBUG")]
350 static public void Debug (int category, string message, params object[] args)
352 // if ((category & DebugFlags) == 0)
355 StringBuilder sb = new StringBuilder (message);
357 if ((args != null) && (args.Length > 0)) {
361 foreach (object arg in args) {
368 // else if (arg is ICollection)
369 // sb.Append (PrintCollection ((ICollection) arg));
375 Console.WriteLine (sb.ToString ());
378 static public string PrintCollection (ICollection collection)
380 StringBuilder sb = new StringBuilder ();
382 sb.Append (collection.GetType ());
386 foreach (object o in collection) {
395 return sb.ToString ();
398 static string FriendlyStackTrace (StackTrace t)
400 StringBuilder sb = new StringBuilder ();
402 bool foundUserCode = false;
404 for (int i = 0; i < t.FrameCount; i++) {
405 StackFrame f = t.GetFrame (i);
406 var mb = f.GetMethod ();
408 if (!foundUserCode && mb.ReflectedType == typeof (Report))
411 foundUserCode = true;
415 if (f.GetFileLineNumber () > 0)
416 sb.AppendFormat ("(at {0}:{1}) ", f.GetFileName (), f.GetFileLineNumber ());
418 sb.AppendFormat ("{0}.{1} (", mb.ReflectedType.Name, mb.Name);
421 foreach (var pi in mb.GetParameters ()) {
426 sb.Append (pi.ParameterType.FullName);
431 return sb.ToString ();
435 public abstract class AbstractMessage
437 readonly string[] extra_info;
438 protected readonly int code;
439 protected readonly Location location;
440 readonly string message;
442 protected AbstractMessage (int code, Location loc, string msg, List<string> extraInfo)
446 this.code = 8000 - code;
450 if (extraInfo.Count != 0) {
451 this.extra_info = extraInfo.ToArray ();
455 protected AbstractMessage (AbstractMessage aMsg)
457 this.code = aMsg.code;
458 this.location = aMsg.location;
459 this.message = aMsg.message;
460 this.extra_info = aMsg.extra_info;
467 public override bool Equals (object obj)
469 AbstractMessage msg = obj as AbstractMessage;
473 return code == msg.code && location.Equals (msg.location) && message == msg.message;
476 public override int GetHashCode ()
478 return code.GetHashCode ();
481 public abstract bool IsWarning { get; }
483 public Location Location {
484 get { return location; }
487 public abstract string MessageType { get; }
489 public string[] RelatedSymbols {
490 get { return extra_info; }
494 get { return message; }
498 sealed class WarningMessage : AbstractMessage
500 public WarningMessage (int code, Location loc, string message, List<string> extra_info)
501 : base (code, loc, message, extra_info)
505 public override bool IsWarning {
509 public override string MessageType {
516 sealed class ErrorMessage : AbstractMessage
518 public ErrorMessage (int code, Location loc, string message, List<string> extraInfo)
519 : base (code, loc, message, extraInfo)
523 public ErrorMessage (AbstractMessage aMsg)
528 public override bool IsWarning {
529 get { return false; }
532 public override string MessageType {
540 // Generic base for any message writer
542 public abstract class ReportPrinter
544 protected HashSet<ITypeDefinition> reported_missing_definitions;
548 public int ErrorsCount { get; protected set; }
550 public int WarningsCount { get; private set; }
553 // When (symbols related to previous ...) can be used
555 public virtual bool HasRelatedSymbolSupport {
562 protected virtual string FormatText (string txt)
567 public virtual void Print (AbstractMessage msg, bool showFullPath)
576 protected void Print (AbstractMessage msg, TextWriter output, bool showFullPath)
578 StringBuilder txt = new StringBuilder ();
579 if (!msg.Location.IsNull) {
581 txt.Append (msg.Location.ToStringFullName ());
583 txt.Append (msg.Location.ToString ());
588 txt.AppendFormat ("{0} CS{1:0000}: {2}", msg.MessageType, msg.Code, msg.Text);
591 output.WriteLine (FormatText (txt.ToString ()));
593 output.WriteLine (txt.ToString ());
595 if (msg.RelatedSymbols != null) {
596 foreach (string s in msg.RelatedSymbols)
597 output.WriteLine (s + msg.MessageType + ")");
602 // Tracks reported missing types. It needs to be session specific
603 // because we can run in probing mode
605 public bool MissingTypeReported (ITypeDefinition typeDefinition)
607 if (reported_missing_definitions == null)
608 reported_missing_definitions = new HashSet<ITypeDefinition> ();
610 if (reported_missing_definitions.Contains (typeDefinition))
613 reported_missing_definitions.Add (typeDefinition);
619 // HACK: Temporary hack for broken repl flow
620 ErrorsCount = WarningsCount = 0;
624 sealed class NullReportPrinter : ReportPrinter
629 // Default message recorder, it uses two types of message groups.
630 // Common messages: messages reported in all sessions.
631 // Merged messages: union of all messages in all sessions.
633 // Used by the Lambda expressions to compile the code with various
634 // parameter values, or by attribute resolver
636 class SessionReportPrinter : ReportPrinter
638 List<AbstractMessage> session_messages;
640 // A collection of exactly same messages reported in all sessions
642 List<AbstractMessage> common_messages;
645 // A collection of unique messages reported in all sessions
647 List<AbstractMessage> merged_messages;
651 public void ClearSession ()
653 session_messages = null;
656 public override void Print (AbstractMessage msg, bool showFullPath)
659 // This line is useful when debugging recorded messages
661 // Console.WriteLine ("RECORDING: {0}", msg.Text);
663 if (session_messages == null)
664 session_messages = new List<AbstractMessage> ();
666 session_messages.Add (msg);
668 this.showFullPaths = showFullPath;
669 base.Print (msg, showFullPath);
672 public void EndSession ()
674 if (session_messages == null)
678 // Handles the first session
680 if (common_messages == null) {
681 common_messages = new List<AbstractMessage> (session_messages);
682 merged_messages = session_messages;
683 session_messages = null;
688 // Store common messages if any
690 for (int i = 0; i < common_messages.Count; ++i) {
691 AbstractMessage cmsg = common_messages[i];
692 bool common_msg_found = false;
693 foreach (AbstractMessage msg in session_messages) {
694 if (cmsg.Equals (msg)) {
695 common_msg_found = true;
700 if (!common_msg_found)
701 common_messages.RemoveAt (i);
705 // Merge session and previous messages
707 for (int i = 0; i < session_messages.Count; ++i) {
708 AbstractMessage msg = session_messages[i];
709 bool msg_found = false;
710 for (int ii = 0; ii < merged_messages.Count; ++ii) {
711 if (msg.Equals (merged_messages[ii])) {
718 merged_messages.Add (msg);
722 public bool IsEmpty {
724 return merged_messages == null && common_messages == null;
729 // Prints collected messages, common messages have a priority
731 public bool Merge (ReportPrinter dest)
733 var messages_to_print = merged_messages;
734 if (common_messages != null && common_messages.Count > 0) {
735 messages_to_print = common_messages;
738 if (messages_to_print == null)
741 bool error_msg = false;
742 foreach (AbstractMessage msg in messages_to_print) {
743 dest.Print (msg, showFullPaths);
744 error_msg |= !msg.IsWarning;
747 if (reported_missing_definitions != null) {
748 foreach (var missing in reported_missing_definitions)
749 dest.MissingTypeReported (missing);
756 public class StreamReportPrinter : ReportPrinter
758 readonly TextWriter writer;
760 public StreamReportPrinter (TextWriter writer)
762 this.writer = writer;
765 public override void Print (AbstractMessage msg, bool showFullPath)
767 Print (msg, writer, showFullPath);
768 base.Print (msg, showFullPath);
772 public class ConsoleReportPrinter : StreamReportPrinter
774 static readonly string prefix, postfix;
776 static ConsoleReportPrinter ()
778 string term = Environment.GetEnvironmentVariable ("TERM");
779 bool xterm_colors = false;
785 if (Environment.GetEnvironmentVariable ("COLORTERM") != null){
791 case "xterm-256color":
798 if (!(UnixUtils.isatty (1) && UnixUtils.isatty (2)))
801 string config = Environment.GetEnvironmentVariable ("MCS_COLORS");
803 config = "errors=red";
804 //config = "brightwhite,red";
807 if (config == "disable")
810 if (!config.StartsWith ("errors="))
813 config = config.Substring (7);
815 int p = config.IndexOf (",");
817 prefix = GetForeground (config);
819 prefix = GetBackground (config.Substring (p+1)) + GetForeground (config.Substring (0, p));
820 postfix = "\x001b[0m";
823 public ConsoleReportPrinter ()
824 : base (Console.Error)
828 public ConsoleReportPrinter (TextWriter writer)
833 static int NameToCode (string s)
858 // maps a color name to its xterm color code
860 static string GetForeground (string s)
864 if (s.StartsWith ("bright")) {
870 return "\x001b[" + highcode + (30 + NameToCode (s)).ToString () + "m";
873 static string GetBackground (string s)
875 return "\x001b[" + (40 + NameToCode (s)).ToString () + "m";
878 protected override string FormatText (string txt)
881 return prefix + txt + postfix;
889 public enum TimerType
892 AssemblyBuilderSetup,
897 ModuleDefinitionTotal,
905 readonly Stopwatch[] timers;
908 public TimeReporter (bool enabled)
913 timers = new Stopwatch[System.Enum.GetValues(typeof (TimerType)).Length];
916 public void Start (TimerType type)
918 if (timers != null) {
919 var sw = new Stopwatch ();
920 timers[(int) type] = sw;
925 public void StartTotal ()
927 total = new Stopwatch ();
931 public void Stop (TimerType type)
933 if (timers != null) {
934 timers[(int) type].Stop ();
938 public void StopTotal ()
943 public void ShowStats ()
948 Dictionary<TimerType, string> timer_names = new Dictionary<TimerType,string> {
949 { TimerType.ParseTotal, "Parsing source files" },
950 { TimerType.AssemblyBuilderSetup, "Assembly builder setup" },
951 { TimerType.CreateTypeTotal, "Compiled types created" },
952 { TimerType.ReferencesLoading, "Referenced assemblies loading" },
953 { TimerType.ReferencesImporting, "Referenced assemblies importing" },
954 { TimerType.PredefinedTypesInit, "Predefined types initialization" },
955 { TimerType.ModuleDefinitionTotal, "Module definition" },
956 { TimerType.EmitTotal, "Resolving and emitting members blocks" },
957 { TimerType.CloseTypes, "Module types closed" },
958 { TimerType.Resouces, "Embedding resources" },
959 { TimerType.OutputSave, "Writing output file" },
960 { TimerType.DebugSave, "Writing debug symbols file" },
964 double percentage = (double) total.ElapsedMilliseconds / 100;
965 long subtotal = total.ElapsedMilliseconds;
966 foreach (var timer in timers) {
967 string msg = timer_names[(TimerType) counter++];
968 var ms = timer == null ? 0 : timer.ElapsedMilliseconds;
969 Console.WriteLine ("{0,4:0.0}% {1,5}ms {2}", ms / percentage, ms, msg);
973 Console.WriteLine ("{0,4:0.0}% {1,5}ms Other tasks", subtotal / percentage, subtotal);
974 Console.WriteLine ();
975 Console.WriteLine ("Total elapsed time: {0}", total.Elapsed);
979 public class InternalErrorException : Exception {
980 public InternalErrorException (MemberCore mc, Exception e)
981 : base (mc.Location + " " + mc.GetSignatureForError (), e)
985 public InternalErrorException ()
986 : base ("Internal error")
990 public InternalErrorException (string message)
995 public InternalErrorException (string message, params object[] args)
996 : base (String.Format (message, args))
1000 public InternalErrorException (Exception exception, string message, params object[] args)
1001 : base (String.Format (message, args), exception)
1005 public InternalErrorException (Exception e, Location loc)
1006 : base (loc.ToString (), e)
1011 class FatalException : Exception
1013 public FatalException (string message)
1020 /// Handles #pragma warning
1022 public class WarningRegions {
1024 abstract class PragmaCmd
1028 protected PragmaCmd (int line)
1033 public abstract bool IsEnabled (int code, bool previous);
1036 class Disable : PragmaCmd
1039 public Disable (int line, int code)
1045 public override bool IsEnabled (int code, bool previous)
1047 return this.code != code && previous;
1051 class DisableAll : PragmaCmd
1053 public DisableAll (int line)
1056 public override bool IsEnabled(int code, bool previous)
1062 class Enable : PragmaCmd
1065 public Enable (int line, int code)
1071 public override bool IsEnabled(int code, bool previous)
1073 return this.code == code || previous;
1077 class EnableAll : PragmaCmd
1079 public EnableAll (int line)
1082 public override bool IsEnabled(int code, bool previous)
1089 List<PragmaCmd> regions = new List<PragmaCmd> ();
1091 public void WarningDisable (int line)
1093 regions.Add (new DisableAll (line));
1096 public void WarningDisable (Location location, int code, Report Report)
1098 regions.Add (new Disable (location.Row, code));
1101 public void WarningEnable (int line)
1103 regions.Add (new EnableAll (line));
1106 public void WarningEnable (Location location, int code, CompilerContext context)
1108 if (context.Settings.IsWarningDisabledGlobally (code))
1109 context.Report.Warning (1635, 1, location, "Cannot restore warning `CS{0:0000}' because it was disabled globally", code);
1111 regions.Add (new Enable (location.Row, code));
1114 public bool IsWarningEnabled (int code, int src_line)
1117 foreach (PragmaCmd pragma in regions) {
1118 if (src_line < pragma.Line)
1121 result = pragma.IsEnabled (code, result);