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:
107 case LanguageVersion.V_7:
111 throw new InternalErrorException ("Invalid feature version", compiler.Settings.Version);
115 "Feature `{0}' cannot be used because it is not part of the C# {1} language specification",
119 public void FeatureIsNotSupported (Location loc, string feature)
122 "Feature `{0}' is not supported in Mono mcs1 compiler. Consider using the `gmcs' compiler instead",
126 public void RuntimeMissingSupport (Location loc, string feature)
128 Error (-88, loc, "Your .NET Runtime does not support `{0}'. Please use the latest Mono runtime instead.", feature);
132 /// In most error cases is very useful to have information about symbol that caused the error.
133 /// Call this method before you call Report.Error when it makes sense.
135 public void SymbolRelatedToPreviousError (Location loc, string symbol)
137 SymbolRelatedToPreviousError (loc.ToString ());
140 public void SymbolRelatedToPreviousError (MemberSpec ms)
142 if (reporting_disabled > 0 || !printer.HasRelatedSymbolSupport)
145 var mc = ms.MemberDefinition as MemberCore;
146 while (ms is ElementTypeSpec) {
147 ms = ((ElementTypeSpec) ms).Element;
148 mc = ms.MemberDefinition as MemberCore;
152 SymbolRelatedToPreviousError (mc);
154 if (ms.DeclaringType != null)
155 ms = ms.DeclaringType;
157 var imported_type = ms.MemberDefinition as ImportedTypeDefinition;
158 if (imported_type != null) {
159 var iad = imported_type.DeclaringAssembly as ImportedAssemblyDefinition;
160 SymbolRelatedToPreviousError (iad.Location);
165 public void SymbolRelatedToPreviousError (MemberCore mc)
167 SymbolRelatedToPreviousError (mc.Location, mc.GetSignatureForError ());
170 public void SymbolRelatedToPreviousError (string loc)
172 string msg = String.Format ("{0} (Location of the symbol related to previous ", loc);
173 if (extra_information.Contains (msg))
176 extra_information.Add (msg);
179 public void ExtraInformation (Location loc, string msg)
181 extra_information.Add (String.Format ("{0} {1}", loc, msg));
184 public WarningRegions RegisterWarningRegion (Location location)
186 WarningRegions regions;
187 if (warning_regions_table == null) {
189 warning_regions_table = new Dictionary<int, WarningRegions> ();
191 warning_regions_table.TryGetValue (location.File, out regions);
194 if (regions == null) {
195 regions = new WarningRegions ();
196 warning_regions_table.Add (location.File, regions);
202 public void Warning (int code, int level, Location loc, string message)
204 if (reporting_disabled > 0)
207 if (!settings.IsWarningEnabled (code, level))
210 if (warning_regions_table != null && !loc.IsNull) {
211 WarningRegions regions;
212 if (warning_regions_table.TryGetValue (loc.File, out regions) && !regions.IsWarningEnabled (code, loc.Row))
217 if (settings.IsWarningAsError (code)) {
218 message = "Warning as Error: " + message;
219 msg = new ErrorMessage (code, loc, message, extra_information);
221 msg = new WarningMessage (code, loc, message, extra_information);
224 extra_information.Clear ();
225 printer.Print (msg, settings.ShowFullPaths);
228 public void Warning (int code, int level, Location loc, string format, string arg)
230 Warning (code, level, loc, String.Format (format, arg));
233 public void Warning (int code, int level, Location loc, string format, string arg1, string arg2)
235 Warning (code, level, loc, String.Format (format, arg1, arg2));
238 public void Warning (int code, int level, Location loc, string format, params object[] args)
240 Warning (code, level, loc, String.Format (format, args));
243 public void Warning (int code, int level, string message)
245 Warning (code, level, Location.Null, message);
248 public void Warning (int code, int level, string format, string arg)
250 Warning (code, level, Location.Null, format, arg);
253 public void Warning (int code, int level, string format, string arg1, string arg2)
255 Warning (code, level, Location.Null, format, arg1, arg2);
258 public void Warning (int code, int level, string format, params string[] args)
260 Warning (code, level, Location.Null, String.Format (format, args));
264 // Warnings encountered so far
266 public int Warnings {
267 get { return printer.WarningsCount; }
270 public void Error (int code, Location loc, string error)
272 if (reporting_disabled > 0)
275 ErrorMessage msg = new ErrorMessage (code, loc, error, extra_information);
276 extra_information.Clear ();
278 printer.Print (msg, settings.ShowFullPaths);
280 if (settings.Stacktrace)
281 Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
283 if (printer.ErrorsCount == settings.FatalCounter)
284 throw new FatalException (msg.Text);
287 public void Error (int code, Location loc, string format, string arg)
289 Error (code, loc, String.Format (format, arg));
292 public void Error (int code, Location loc, string format, string arg1, string arg2)
294 Error (code, loc, String.Format (format, arg1, arg2));
297 public void Error (int code, Location loc, string format, params string[] args)
299 Error (code, loc, String.Format (format, args));
302 public void Error (int code, string error)
304 Error (code, Location.Null, error);
307 public void Error (int code, string format, string arg)
309 Error (code, Location.Null, format, arg);
312 public void Error (int code, string format, string arg1, string arg2)
314 Error (code, Location.Null, format, arg1, arg2);
317 public void Error (int code, string format, params string[] args)
319 Error (code, Location.Null, String.Format (format, args));
323 // Errors encountered so far
326 get { return printer.ErrorsCount; }
329 public bool IsDisabled {
331 return reporting_disabled > 0;
335 public ReportPrinter Printer {
336 get { return printer; }
339 public ReportPrinter SetPrinter (ReportPrinter printer)
341 ReportPrinter old = this.printer;
342 this.printer = printer;
346 [Conditional ("MCS_DEBUG")]
347 static public void Debug (string message, params object[] args)
349 Debug (4, message, args);
352 [Conditional ("MCS_DEBUG")]
353 static public void Debug (int category, string message, params object[] args)
355 // if ((category & DebugFlags) == 0)
358 StringBuilder sb = new StringBuilder (message);
360 if ((args != null) && (args.Length > 0)) {
364 foreach (object arg in args) {
371 // else if (arg is ICollection)
372 // sb.Append (PrintCollection ((ICollection) arg));
378 Console.WriteLine (sb.ToString ());
381 static public string PrintCollection (ICollection collection)
383 StringBuilder sb = new StringBuilder ();
385 sb.Append (collection.GetType ());
389 foreach (object o in collection) {
398 return sb.ToString ();
401 static string FriendlyStackTrace (StackTrace t)
403 StringBuilder sb = new StringBuilder ();
405 bool foundUserCode = false;
407 for (int i = 0; i < t.FrameCount; i++) {
408 StackFrame f = t.GetFrame (i);
409 var mb = f.GetMethod ();
411 if (!foundUserCode && mb.ReflectedType == typeof (Report))
414 foundUserCode = true;
418 if (f.GetFileLineNumber () > 0)
419 sb.AppendFormat ("(at {0}:{1}) ", f.GetFileName (), f.GetFileLineNumber ());
421 sb.AppendFormat ("{0}.{1} (", mb.ReflectedType.Name, mb.Name);
424 foreach (var pi in mb.GetParameters ()) {
429 sb.Append (pi.ParameterType.FullName);
434 return sb.ToString ();
438 public abstract class AbstractMessage
440 readonly string[] extra_info;
441 protected readonly int code;
442 protected readonly Location location;
443 readonly string message;
445 protected AbstractMessage (int code, Location loc, string msg, List<string> extraInfo)
449 this.code = 8000 - code;
453 if (extraInfo.Count != 0) {
454 this.extra_info = extraInfo.ToArray ();
458 protected AbstractMessage (AbstractMessage aMsg)
460 this.code = aMsg.code;
461 this.location = aMsg.location;
462 this.message = aMsg.message;
463 this.extra_info = aMsg.extra_info;
470 public override bool Equals (object obj)
472 AbstractMessage msg = obj as AbstractMessage;
476 return code == msg.code && location.Equals (msg.location) && message == msg.message;
479 public override int GetHashCode ()
481 return code.GetHashCode ();
484 public abstract bool IsWarning { get; }
486 public Location Location {
487 get { return location; }
490 public abstract string MessageType { get; }
492 public string[] RelatedSymbols {
493 get { return extra_info; }
497 get { return message; }
501 sealed class WarningMessage : AbstractMessage
503 public WarningMessage (int code, Location loc, string message, List<string> extra_info)
504 : base (code, loc, message, extra_info)
508 public override bool IsWarning {
512 public override string MessageType {
519 sealed class ErrorMessage : AbstractMessage
521 public ErrorMessage (int code, Location loc, string message, List<string> extraInfo)
522 : base (code, loc, message, extraInfo)
526 public ErrorMessage (AbstractMessage aMsg)
531 public override bool IsWarning {
532 get { return false; }
535 public override string MessageType {
543 // Generic base for any message writer
545 public abstract class ReportPrinter
547 protected HashSet<ITypeDefinition> reported_missing_definitions;
551 public int ErrorsCount { get; protected set; }
553 public int WarningsCount { get; private set; }
556 // When (symbols related to previous ...) can be used
558 public virtual bool HasRelatedSymbolSupport {
565 protected virtual string FormatText (string txt)
570 public virtual void Print (AbstractMessage msg, bool showFullPath)
579 protected void Print (AbstractMessage msg, TextWriter output, bool showFullPath)
581 StringBuilder txt = new StringBuilder ();
582 if (!msg.Location.IsNull) {
584 txt.Append (msg.Location.ToStringFullName ());
586 txt.Append (msg.Location.ToString ());
591 txt.AppendFormat ("{0} CS{1:0000}: {2}", msg.MessageType, msg.Code, msg.Text);
594 output.WriteLine (FormatText (txt.ToString ()));
596 output.WriteLine (txt.ToString ());
598 if (msg.RelatedSymbols != null) {
599 foreach (string s in msg.RelatedSymbols)
600 output.WriteLine (s + msg.MessageType + ")");
605 // Tracks reported missing types. It needs to be session specific
606 // because we can run in probing mode
608 public bool MissingTypeReported (ITypeDefinition typeDefinition)
610 if (reported_missing_definitions == null)
611 reported_missing_definitions = new HashSet<ITypeDefinition> ();
613 if (reported_missing_definitions.Contains (typeDefinition))
616 reported_missing_definitions.Add (typeDefinition);
622 // HACK: Temporary hack for broken repl flow
623 ErrorsCount = WarningsCount = 0;
627 sealed class NullReportPrinter : ReportPrinter
632 // Default message recorder, it uses two types of message groups.
633 // Common messages: messages reported in all sessions.
634 // Merged messages: union of all messages in all sessions.
636 // Used by the Lambda expressions to compile the code with various
637 // parameter values, or by attribute resolver
639 class SessionReportPrinter : ReportPrinter
641 List<AbstractMessage> session_messages;
643 // A collection of exactly same messages reported in all sessions
645 List<AbstractMessage> common_messages;
648 // A collection of unique messages reported in all sessions
650 List<AbstractMessage> merged_messages;
654 public void ClearSession ()
656 session_messages = null;
659 public override void Print (AbstractMessage msg, bool showFullPath)
662 // This line is useful when debugging recorded messages
664 // Console.WriteLine ("RECORDING: {0}", msg.Text);
666 if (session_messages == null)
667 session_messages = new List<AbstractMessage> ();
669 session_messages.Add (msg);
671 this.showFullPaths = showFullPath;
672 base.Print (msg, showFullPath);
675 public void EndSession ()
677 if (session_messages == null)
681 // Handles the first session
683 if (common_messages == null) {
684 common_messages = new List<AbstractMessage> (session_messages);
685 merged_messages = session_messages;
686 session_messages = null;
691 // Store common messages if any
693 for (int i = 0; i < common_messages.Count; ++i) {
694 AbstractMessage cmsg = common_messages[i];
695 bool common_msg_found = false;
696 foreach (AbstractMessage msg in session_messages) {
697 if (cmsg.Equals (msg)) {
698 common_msg_found = true;
703 if (!common_msg_found)
704 common_messages.RemoveAt (i);
708 // Merge session and previous messages
710 for (int i = 0; i < session_messages.Count; ++i) {
711 AbstractMessage msg = session_messages[i];
712 bool msg_found = false;
713 for (int ii = 0; ii < merged_messages.Count; ++ii) {
714 if (msg.Equals (merged_messages[ii])) {
721 merged_messages.Add (msg);
725 public bool IsEmpty {
727 return merged_messages == null && common_messages == null;
732 // Prints collected messages, common messages have a priority
734 public bool Merge (ReportPrinter dest)
736 var messages_to_print = merged_messages;
737 if (common_messages != null && common_messages.Count > 0) {
738 messages_to_print = common_messages;
741 if (messages_to_print == null)
744 bool error_msg = false;
745 foreach (AbstractMessage msg in messages_to_print) {
746 dest.Print (msg, showFullPaths);
747 error_msg |= !msg.IsWarning;
750 if (reported_missing_definitions != null) {
751 foreach (var missing in reported_missing_definitions)
752 dest.MissingTypeReported (missing);
759 public class StreamReportPrinter : ReportPrinter
761 readonly TextWriter writer;
763 public StreamReportPrinter (TextWriter writer)
765 this.writer = writer;
768 public override void Print (AbstractMessage msg, bool showFullPath)
770 Print (msg, writer, showFullPath);
771 base.Print (msg, showFullPath);
775 public class ConsoleReportPrinter : StreamReportPrinter
777 static readonly string prefix, postfix;
779 static ConsoleReportPrinter ()
781 string term = Environment.GetEnvironmentVariable ("TERM");
782 bool xterm_colors = false;
788 if (Environment.GetEnvironmentVariable ("COLORTERM") != null){
794 case "xterm-256color":
801 if (!(UnixUtils.isatty (1) && UnixUtils.isatty (2)))
804 string config = Environment.GetEnvironmentVariable ("MCS_COLORS");
806 config = "errors=red";
807 //config = "brightwhite,red";
810 if (config == "disable")
813 if (!config.StartsWith ("errors="))
816 config = config.Substring (7);
818 int p = config.IndexOf (",");
820 prefix = GetForeground (config);
822 prefix = GetBackground (config.Substring (p+1)) + GetForeground (config.Substring (0, p));
823 postfix = "\x001b[0m";
826 public ConsoleReportPrinter ()
827 : base (Console.Error)
831 public ConsoleReportPrinter (TextWriter writer)
836 static int NameToCode (string s)
861 // maps a color name to its xterm color code
863 static string GetForeground (string s)
867 if (s.StartsWith ("bright")) {
873 return "\x001b[" + highcode + (30 + NameToCode (s)).ToString () + "m";
876 static string GetBackground (string s)
878 return "\x001b[" + (40 + NameToCode (s)).ToString () + "m";
881 protected override string FormatText (string txt)
884 return prefix + txt + postfix;
892 public enum TimerType
895 AssemblyBuilderSetup,
900 ModuleDefinitionTotal,
908 readonly Stopwatch[] timers;
911 public TimeReporter (bool enabled)
916 timers = new Stopwatch[System.Enum.GetValues(typeof (TimerType)).Length];
919 public void Start (TimerType type)
921 if (timers != null) {
922 var sw = new Stopwatch ();
923 timers[(int) type] = sw;
928 public void StartTotal ()
930 total = new Stopwatch ();
934 public void Stop (TimerType type)
936 if (timers != null) {
937 timers[(int) type].Stop ();
941 public void StopTotal ()
946 public void ShowStats ()
951 Dictionary<TimerType, string> timer_names = new Dictionary<TimerType,string> {
952 { TimerType.ParseTotal, "Parsing source files" },
953 { TimerType.AssemblyBuilderSetup, "Assembly builder setup" },
954 { TimerType.CreateTypeTotal, "Compiled types created" },
955 { TimerType.ReferencesLoading, "Referenced assemblies loading" },
956 { TimerType.ReferencesImporting, "Referenced assemblies importing" },
957 { TimerType.PredefinedTypesInit, "Predefined types initialization" },
958 { TimerType.ModuleDefinitionTotal, "Module definition" },
959 { TimerType.EmitTotal, "Resolving and emitting members blocks" },
960 { TimerType.CloseTypes, "Module types closed" },
961 { TimerType.Resouces, "Embedding resources" },
962 { TimerType.OutputSave, "Writing output file" },
963 { TimerType.DebugSave, "Writing debug symbols file" },
967 double percentage = (double) total.ElapsedMilliseconds / 100;
968 long subtotal = total.ElapsedMilliseconds;
969 foreach (var timer in timers) {
970 string msg = timer_names[(TimerType) counter++];
971 var ms = timer == null ? 0 : timer.ElapsedMilliseconds;
972 Console.WriteLine ("{0,4:0.0}% {1,5}ms {2}", ms / percentage, ms, msg);
976 Console.WriteLine ("{0,4:0.0}% {1,5}ms Other tasks", subtotal / percentage, subtotal);
977 Console.WriteLine ();
978 Console.WriteLine ("Total elapsed time: {0}", total.Elapsed);
982 public class InternalErrorException : Exception {
983 public InternalErrorException (MemberCore mc, Exception e)
984 : base (mc.Location + " " + mc.GetSignatureForError (), e)
988 public InternalErrorException ()
989 : base ("Internal error")
993 public InternalErrorException (string message)
998 public InternalErrorException (string message, params object[] args)
999 : base (String.Format (message, args))
1003 public InternalErrorException (Exception exception, string message, params object[] args)
1004 : base (String.Format (message, args), exception)
1008 public InternalErrorException (Exception e, Location loc)
1009 : base (loc.ToString (), e)
1014 class FatalException : Exception
1016 public FatalException (string message)
1023 /// Handles #pragma warning
1025 public class WarningRegions {
1027 abstract class PragmaCmd
1031 protected PragmaCmd (int line)
1036 public abstract bool IsEnabled (int code, bool previous);
1039 class Disable : PragmaCmd
1042 public Disable (int line, int code)
1048 public override bool IsEnabled (int code, bool previous)
1050 return this.code != code && previous;
1054 class DisableAll : PragmaCmd
1056 public DisableAll (int line)
1059 public override bool IsEnabled(int code, bool previous)
1065 class Enable : PragmaCmd
1068 public Enable (int line, int code)
1074 public override bool IsEnabled(int code, bool previous)
1076 return this.code == code || previous;
1080 class EnableAll : PragmaCmd
1082 public EnableAll (int line)
1085 public override bool IsEnabled(int code, bool previous)
1092 List<PragmaCmd> regions = new List<PragmaCmd> ();
1094 public void WarningDisable (int line)
1096 regions.Add (new DisableAll (line));
1099 public void WarningDisable (Location location, int code, Report Report)
1101 regions.Add (new Disable (location.Row, code));
1104 public void WarningEnable (int line)
1106 regions.Add (new EnableAll (line));
1109 public void WarningEnable (Location location, int code, CompilerContext context)
1111 if (context.Settings.IsWarningDisabledGlobally (code))
1112 context.Report.Warning (1635, 1, location, "Cannot restore warning `CS{0:0000}' because it was disabled globally", code);
1114 regions.Add (new Enable (location.Row, code));
1117 public bool IsWarningEnabled (int code, int src_line)
1120 foreach (PragmaCmd pragma in regions) {
1121 if (src_line < pragma.Line)
1124 result = pragma.IsEnabled (code, result);