2
// report.cs: report errors and warnings.
4
// Author: Miguel de Icaza (miguel@ximian.com)
5
// Marek Safar (marek.safar@seznam.cz)
7
// Copyright 2001 Ximian, Inc. (http://www.ximian.com)
13
using System.Collections.Generic;
14
using System.Diagnostics;
16
namespace Mono.CSharp {
19
// Errors and warnings manager
24
/// Whether warnings should be considered errors
26
public bool WarningsAreErrors;
27
List<int> warnings_as_error;
28
List<int> warnings_only;
30
public const int RuntimeErrorId = 10000;
33
// Keeps track of the warnings that we are ignoring
35
HashSet<int> warning_ignore_table;
37
Dictionary<int, WarningRegions> warning_regions_table;
41
ReportPrinter printer;
43
int reporting_disabled;
46
/// List of symbols related to reported error/warning. You have to fill it before error/warning is reported.
48
List<string> extra_information = new List<string> ();
51
// IF YOU ADD A NEW WARNING YOU HAVE TO ADD ITS ID HERE
53
public static readonly int[] AllWarnings = new int[] {
55
105, 108, 109, 114, 162, 164, 168, 169, 183, 184, 197,
56
219, 251, 252, 253, 278, 282,
57
402, 414, 419, 420, 429, 436, 437, 440, 458, 464, 465, 467, 469, 472, 473,
58
612, 618, 626, 628, 642, 649, 652, 657, 658, 659, 660, 661, 665, 672, 675, 693,
62
1522, 1570, 1571, 1572, 1573, 1574, 1580, 1581, 1584, 1587, 1589, 1590, 1591, 1592,
63
1607, 1616, 1633, 1634, 1635, 1685, 1690, 1691, 1692, 1695, 1696, 1699,
64
1700, 1701, 1702, 1709, 1717, 1718, 1720,
67
3000, 3001, 3002, 3003, 3005, 3006, 3007, 3008, 3009,
68
3010, 3011, 3012, 3013, 3014, 3015, 3016, 3017, 3018, 3019,
69
3021, 3022, 3023, 3024, 3026, 3027
72
static HashSet<int> AllWarningsHashSet;
74
public Report (ReportPrinter printer)
77
throw new ArgumentNullException ("printer");
79
this.printer = printer;
83
public void DisableReporting ()
88
public void EnableReporting ()
93
public void FeatureIsNotAvailable (CompilerContext compiler, Location loc, string feature)
96
switch (compiler.Settings.Version) {
97
case LanguageVersion.ISO_1:
100
case LanguageVersion.ISO_2:
103
case LanguageVersion.V_3:
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
bool IsWarningEnabled (int code, int level, Location loc)
124
if (WarningLevel < level)
127
if (IsWarningDisabledGlobally (code))
130
if (warning_regions_table == null || loc.IsNull)
133
WarningRegions regions;
134
if (!warning_regions_table.TryGetValue (loc.File, out regions))
137
return regions.IsWarningEnabled (code, loc.Row);
140
public bool IsWarningDisabledGlobally (int code)
142
return warning_ignore_table != null && warning_ignore_table.Contains (code);
145
bool IsWarningAsError (int code)
147
bool is_error = WarningsAreErrors;
149
// Check specific list
150
if (warnings_as_error != null)
151
is_error |= warnings_as_error.Contains (code);
153
// Ignore excluded warnings
154
if (warnings_only != null && warnings_only.Contains (code))
160
public void RuntimeMissingSupport (Location loc, string feature)
162
Error (-88, loc, "Your .NET Runtime does not support `{0}'. Please use the latest Mono runtime instead.", feature);
166
/// In most error cases is very useful to have information about symbol that caused the error.
167
/// Call this method before you call Report.Error when it makes sense.
169
public void SymbolRelatedToPreviousError (Location loc, string symbol)
171
SymbolRelatedToPreviousError (loc.ToString ());
174
public void SymbolRelatedToPreviousError (MemberSpec ms)
176
if (reporting_disabled > 0 || !printer.HasRelatedSymbolSupport)
179
var mc = ms.MemberDefinition as MemberCore;
180
while (ms is ElementTypeSpec) {
181
ms = ((ElementTypeSpec) ms).Element;
182
mc = ms.MemberDefinition as MemberCore;
186
SymbolRelatedToPreviousError (mc);
188
if (ms.DeclaringType != null)
189
ms = ms.DeclaringType;
191
var imported_type = ms.MemberDefinition as ImportedTypeDefinition;
192
if (imported_type != null) {
193
var iad = imported_type.DeclaringAssembly as ImportedAssemblyDefinition;
194
SymbolRelatedToPreviousError (iad.Location);
199
public void SymbolRelatedToPreviousError (MemberCore mc)
201
SymbolRelatedToPreviousError (mc.Location, mc.GetSignatureForError ());
204
public void SymbolRelatedToPreviousError (string loc)
206
string msg = String.Format ("{0} (Location of the symbol related to previous ", loc);
207
if (extra_information.Contains (msg))
210
extra_information.Add (msg);
213
public void AddWarningAsError (string warningId)
217
id = int.Parse (warningId);
219
CheckWarningCode (warningId, Location.Null);
223
if (!CheckWarningCode (id, Location.Null))
226
if (warnings_as_error == null)
227
warnings_as_error = new List<int> ();
229
warnings_as_error.Add (id);
232
public void RemoveWarningAsError (string warningId)
236
id = int.Parse (warningId);
238
CheckWarningCode (warningId, Location.Null);
242
if (!CheckWarningCode (id, Location.Null))
245
if (warnings_only == null)
246
warnings_only = new List<int> ();
248
warnings_only.Add (id);
251
public bool CheckWarningCode (string code, Location loc)
253
Warning (1691, 1, loc, "`{0}' is not a valid warning number", code);
257
public bool CheckWarningCode (int code, Location loc)
259
if (AllWarningsHashSet == null)
260
AllWarningsHashSet = new HashSet<int> (AllWarnings);
262
if (AllWarningsHashSet.Contains (code))
265
return CheckWarningCode (code.ToString (), loc);
268
public void ExtraInformation (Location loc, string msg)
270
extra_information.Add (String.Format ("{0} {1}", loc, msg));
273
public WarningRegions RegisterWarningRegion (Location location)
275
WarningRegions regions;
276
if (warning_regions_table == null) {
278
warning_regions_table = new Dictionary<int, WarningRegions> ();
280
warning_regions_table.TryGetValue (location.File, out regions);
283
if (regions == null) {
284
regions = new WarningRegions ();
285
warning_regions_table.Add (location.File, regions);
291
public void Warning (int code, int level, Location loc, string message)
293
if (reporting_disabled > 0)
296
if (!IsWarningEnabled (code, level, loc))
300
if (IsWarningAsError (code)) {
301
message = "Warning as Error: " + message;
302
msg = new ErrorMessage (code, loc, message, extra_information);
304
msg = new WarningMessage (code, loc, message, extra_information);
307
extra_information.Clear ();
311
public void Warning (int code, int level, Location loc, string format, string arg)
313
Warning (code, level, loc, String.Format (format, arg));
316
public void Warning (int code, int level, Location loc, string format, string arg1, string arg2)
318
Warning (code, level, loc, String.Format (format, arg1, arg2));
321
public void Warning (int code, int level, Location loc, string format, params object[] args)
323
Warning (code, level, loc, String.Format (format, args));
326
public void Warning (int code, int level, string message)
328
Warning (code, level, Location.Null, message);
331
public void Warning (int code, int level, string format, string arg)
333
Warning (code, level, Location.Null, format, arg);
336
public void Warning (int code, int level, string format, string arg1, string arg2)
338
Warning (code, level, Location.Null, format, arg1, arg2);
341
public void Warning (int code, int level, string format, params string[] args)
343
Warning (code, level, Location.Null, String.Format (format, args));
347
// Warnings encountered so far
349
public int Warnings {
350
get { return printer.WarningsCount; }
353
public void Error (int code, Location loc, string error)
355
if (reporting_disabled > 0)
358
ErrorMessage msg = new ErrorMessage (code, loc, error, extra_information);
359
extra_information.Clear ();
364
public void Error (int code, Location loc, string format, string arg)
366
Error (code, loc, String.Format (format, arg));
369
public void Error (int code, Location loc, string format, string arg1, string arg2)
371
Error (code, loc, String.Format (format, arg1, arg2));
374
public void Error (int code, Location loc, string format, params string[] args)
376
Error (code, loc, String.Format (format, args));
379
public void Error (int code, string error)
381
Error (code, Location.Null, error);
384
public void Error (int code, string format, string arg)
386
Error (code, Location.Null, format, arg);
389
public void Error (int code, string format, string arg1, string arg2)
391
Error (code, Location.Null, format, arg1, arg2);
394
public void Error (int code, string format, params string[] args)
396
Error (code, Location.Null, String.Format (format, args));
400
// Errors encountered so far
403
get { return printer.ErrorsCount; }
406
public bool IsDisabled {
408
return reporting_disabled > 0;
412
public ReportPrinter Printer {
413
get { return printer; }
416
public void SetIgnoreWarning (int code)
418
if (warning_ignore_table == null)
419
warning_ignore_table = new HashSet<int> ();
421
warning_ignore_table.Add (code);
424
public ReportPrinter SetPrinter (ReportPrinter printer)
426
ReportPrinter old = this.printer;
427
this.printer = printer;
431
public int WarningLevel {
433
return warning_level;
436
warning_level = value;
440
[Conditional ("MCS_DEBUG")]
441
static public void Debug (string message, params object[] args)
443
Debug (4, message, args);
446
[Conditional ("MCS_DEBUG")]
447
static public void Debug (int category, string message, params object[] args)
449
// if ((category & DebugFlags) == 0)
452
StringBuilder sb = new StringBuilder (message);
454
if ((args != null) && (args.Length > 0)) {
458
foreach (object arg in args) {
465
// else if (arg is ICollection)
466
// sb.Append (PrintCollection ((ICollection) arg));
472
Console.WriteLine (sb.ToString ());
475
static public string PrintCollection (ICollection collection)
477
StringBuilder sb = new StringBuilder ();
479
sb.Append (collection.GetType ());
483
foreach (object o in collection) {
492
return sb.ToString ();
497
public abstract class AbstractMessage
499
readonly string[] extra_info;
500
protected readonly int code;
501
protected readonly Location location;
502
readonly string message;
504
protected AbstractMessage (int code, Location loc, string msg, List<string> extraInfo)
508
this.code = 8000 - code;
512
if (extraInfo.Count != 0) {
513
this.extra_info = extraInfo.ToArray ();
517
protected AbstractMessage (AbstractMessage aMsg)
519
this.code = aMsg.code;
520
this.location = aMsg.location;
521
this.message = aMsg.message;
522
this.extra_info = aMsg.extra_info;
529
public override bool Equals (object obj)
531
AbstractMessage msg = obj as AbstractMessage;
535
return code == msg.code && location.Equals (msg.location) && message == msg.message;
538
public override int GetHashCode ()
540
return code.GetHashCode ();
543
public abstract bool IsWarning { get; }
545
public Location Location {
546
get { return location; }
549
public abstract string MessageType { get; }
551
public string[] RelatedSymbols {
552
get { return extra_info; }
556
get { return message; }
560
sealed class WarningMessage : AbstractMessage
562
public WarningMessage (int code, Location loc, string message, List<string> extra_info)
563
: base (code, loc, message, extra_info)
567
public override bool IsWarning {
571
public override string MessageType {
578
sealed class ErrorMessage : AbstractMessage
580
public ErrorMessage (int code, Location loc, string message, List<string> extraInfo)
581
: base (code, loc, message, extraInfo)
585
public ErrorMessage (AbstractMessage aMsg)
590
public override bool IsWarning {
591
get { return false; }
594
public override string MessageType {
602
// Generic base for any message writer
604
public abstract class ReportPrinter
608
public int FatalCounter { get; set; }
610
public int ErrorsCount { get; protected set; }
612
public bool ShowFullPaths { get; set; }
615
// Whether to dump a stack trace on errors.
617
public bool Stacktrace { get; set; }
619
public int WarningsCount { get; private set; }
622
// When (symbols related to previous ...) can be used
624
public virtual bool HasRelatedSymbolSupport {
631
protected virtual string FormatText (string txt)
636
public virtual void Print (AbstractMessage msg)
643
if (ErrorsCount == FatalCounter)
644
throw new Exception (msg.Text);
648
protected void Print (AbstractMessage msg, TextWriter output)
650
StringBuilder txt = new StringBuilder ();
651
if (!msg.Location.IsNull) {
653
txt.Append (msg.Location.ToStringFullName ());
655
txt.Append (msg.Location.ToString ());
660
txt.AppendFormat ("{0} CS{1:0000}: {2}", msg.MessageType, msg.Code, msg.Text);
663
output.WriteLine (FormatText (txt.ToString ()));
665
output.WriteLine (txt.ToString ());
667
if (msg.RelatedSymbols != null) {
668
foreach (string s in msg.RelatedSymbols)
669
output.WriteLine (s + msg.MessageType + ")");
675
// HACK: Temporary hack for broken repl flow
676
ErrorsCount = WarningsCount = 0;
680
sealed class NullReportPrinter : ReportPrinter
685
// Default message recorder, it uses two types of message groups.
686
// Common messages: messages reported in all sessions.
687
// Merged messages: union of all messages in all sessions.
689
// Used by the Lambda expressions to compile the code with various
690
// parameter values, or by attribute resolver
692
class SessionReportPrinter : ReportPrinter
694
List<AbstractMessage> session_messages;
696
// A collection of exactly same messages reported in all sessions
698
List<AbstractMessage> common_messages;
701
// A collection of unique messages reported in all sessions
703
List<AbstractMessage> merged_messages;
705
public override void Print (AbstractMessage msg)
708
// This line is useful when debugging recorded messages
710
// Console.WriteLine ("RECORDING: {0}", msg.ToString ());
712
if (session_messages == null)
713
session_messages = new List<AbstractMessage> ();
715
session_messages.Add (msg);
720
public void EndSession ()
722
if (session_messages == null)
726
// Handles the first session
728
if (common_messages == null) {
729
common_messages = new List<AbstractMessage> (session_messages);
730
merged_messages = session_messages;
731
session_messages = null;
736
// Store common messages if any
738
for (int i = 0; i < common_messages.Count; ++i) {
739
AbstractMessage cmsg = common_messages[i];
740
bool common_msg_found = false;
741
foreach (AbstractMessage msg in session_messages) {
742
if (cmsg.Equals (msg)) {
743
common_msg_found = true;
748
if (!common_msg_found)
749
common_messages.RemoveAt (i);
753
// Merge session and previous messages
755
for (int i = 0; i < session_messages.Count; ++i) {
756
AbstractMessage msg = session_messages[i];
757
bool msg_found = false;
758
for (int ii = 0; ii < merged_messages.Count; ++ii) {
759
if (msg.Equals (merged_messages[ii])) {
766
merged_messages.Add (msg);
770
public bool IsEmpty {
772
return merged_messages == null && common_messages == null;
777
// Prints collected messages, common messages have a priority
779
public bool Merge (ReportPrinter dest)
781
var messages_to_print = merged_messages;
782
if (common_messages != null && common_messages.Count > 0) {
783
messages_to_print = common_messages;
786
if (messages_to_print == null)
789
bool error_msg = false;
790
foreach (AbstractMessage msg in messages_to_print) {
792
error_msg |= !msg.IsWarning;
799
public class StreamReportPrinter : ReportPrinter
801
readonly TextWriter writer;
803
public StreamReportPrinter (TextWriter writer)
805
this.writer = writer;
808
public override void Print (AbstractMessage msg)
815
public class ConsoleReportPrinter : StreamReportPrinter
817
static readonly string prefix, postfix;
819
static ConsoleReportPrinter ()
821
string term = Environment.GetEnvironmentVariable ("TERM");
822
bool xterm_colors = false;
828
if (Environment.GetEnvironmentVariable ("COLORTERM") != null){
840
if (!(UnixUtils.isatty (1) && UnixUtils.isatty (2)))
843
string config = Environment.GetEnvironmentVariable ("MCS_COLORS");
845
config = "errors=red";
846
//config = "brightwhite,red";
849
if (config == "disable")
852
if (!config.StartsWith ("errors="))
855
config = config.Substring (7);
857
int p = config.IndexOf (",");
859
prefix = GetForeground (config);
861
prefix = GetBackground (config.Substring (p+1)) + GetForeground (config.Substring (0, p));
862
postfix = "\x001b[0m";
865
public ConsoleReportPrinter ()
866
: base (Console.Error)
870
public ConsoleReportPrinter (TextWriter writer)
875
static int NameToCode (string s)
900
// maps a color name to its xterm color code
902
static string GetForeground (string s)
906
if (s.StartsWith ("bright")) {
912
return "\x001b[" + highcode + (30 + NameToCode (s)).ToString () + "m";
915
static string GetBackground (string s)
917
return "\x001b[" + (40 + NameToCode (s)).ToString () + "m";
920
protected override string FormatText (string txt)
923
return prefix + txt + postfix;
928
static string FriendlyStackTrace (StackTrace t)
930
StringBuilder sb = new StringBuilder ();
932
bool foundUserCode = false;
934
for (int i = 0; i < t.FrameCount; i++) {
935
StackFrame f = t.GetFrame (i);
936
var mb = f.GetMethod ();
938
if (!foundUserCode && mb.ReflectedType == typeof (Report))
941
foundUserCode = true;
945
if (f.GetFileLineNumber () > 0)
946
sb.AppendFormat ("(at {0}:{1}) ", f.GetFileName (), f.GetFileLineNumber ());
948
sb.AppendFormat ("{0}.{1} (", mb.ReflectedType.Name, mb.Name);
951
foreach (var pi in mb.GetParameters ()) {
956
sb.Append (pi.ParameterType.FullName);
961
return sb.ToString ();
964
public override void Print (AbstractMessage msg)
969
Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
972
public static string FriendlyStackTrace (Exception e)
974
return FriendlyStackTrace (new StackTrace (e, true));
977
public static void StackTrace ()
979
Console.WriteLine (FriendlyStackTrace (new StackTrace (true)));
985
public enum TimerType
988
AssemblyBuilderSetup,
993
ModuleDefinitionTotal,
1002
readonly Stopwatch[] timers;
1005
public TimeReporter (bool enabled)
1010
timers = new Stopwatch[System.Enum.GetValues(typeof (TimerType)).Length];
1013
public void Start (TimerType type)
1015
if (timers != null) {
1016
var sw = new Stopwatch ();
1017
timers[(int) type] = sw;
1022
public void StartTotal ()
1024
total = new Stopwatch ();
1028
public void Stop (TimerType type)
1030
if (timers != null) {
1031
timers[(int) type].Stop ();
1035
public void StopTotal ()
1040
public void ShowStats ()
1045
Dictionary<TimerType, string> timer_names = new Dictionary<TimerType,string> () {
1046
{ TimerType.ParseTotal, "Parsing source files" },
1047
{ TimerType.AssemblyBuilderSetup, "Assembly builder setup" },
1048
{ TimerType.CreateTypeTotal, "Compiled types created" },
1049
{ TimerType.ReferencesLoading, "Referenced assemblies loading" },
1050
{ TimerType.ReferencesImporting, "Referenced assemblies importing" },
1051
{ TimerType.PredefinedTypesInit, "Predefined types initialization" },
1052
{ TimerType.ModuleDefinitionTotal, "Module definition" },
1053
{ TimerType.UsingResolve, "Top-level usings resolve" },
1054
{ TimerType.EmitTotal, "Resolving and emitting members blocks" },
1055
{ TimerType.CloseTypes, "Module types closed" },
1056
{ TimerType.Resouces, "Embedding resources" },
1057
{ TimerType.OutputSave, "Writing output file" },
1058
{ TimerType.DebugSave, "Writing debug symbols file" },
1062
double percentage = (double) total.ElapsedMilliseconds / 100;
1063
long subtotal = total.ElapsedMilliseconds;
1064
foreach (var timer in timers) {
1065
string msg = timer_names[(TimerType) counter++];
1066
var ms = timer == null ? 0 : timer.ElapsedMilliseconds;
1067
Console.WriteLine ("{0,4:0.0}% {1,5}ms {2}", ms / percentage, ms, msg);
1071
Console.WriteLine ("{0,4:0.0}% {1,5}ms Other tasks", subtotal / percentage, subtotal);
1072
Console.WriteLine ();
1073
Console.WriteLine ("Total elapsed time: {0}", total.Elapsed);
1077
public class InternalErrorException : Exception {
1078
public InternalErrorException (MemberCore mc, Exception e)
1079
: base (mc.Location + " " + mc.GetSignatureForError (), e)
1083
public InternalErrorException ()
1084
: base ("Internal error")
1088
public InternalErrorException (string message)
1093
public InternalErrorException (string message, params object[] args)
1094
: base (String.Format (message, args))
1098
public InternalErrorException (Exception exception, string message, params object[] args)
1099
: base (String.Format (message, args), exception)
1103
public InternalErrorException (Exception e, Location loc)
1104
: base (loc.ToString (), e)
1110
/// Handles #pragma warning
1112
public class WarningRegions {
1114
abstract class PragmaCmd
1118
protected PragmaCmd (int line)
1123
public abstract bool IsEnabled (int code, bool previous);
1126
class Disable : PragmaCmd
1129
public Disable (int line, int code)
1135
public override bool IsEnabled (int code, bool previous)
1137
return this.code == code ? false : previous;
1141
class DisableAll : PragmaCmd
1143
public DisableAll (int line)
1146
public override bool IsEnabled(int code, bool previous)
1152
class Enable : PragmaCmd
1155
public Enable (int line, int code)
1161
public override bool IsEnabled(int code, bool previous)
1163
return this.code == code ? true : previous;
1167
class EnableAll : PragmaCmd
1169
public EnableAll (int line)
1172
public override bool IsEnabled(int code, bool previous)
1179
List<PragmaCmd> regions = new List<PragmaCmd> ();
1181
public void WarningDisable (int line)
1183
regions.Add (new DisableAll (line));
1186
public void WarningDisable (Location location, int code, Report Report)
1188
if (Report.CheckWarningCode (code, location))
1189
regions.Add (new Disable (location.Row, code));
1192
public void WarningEnable (int line)
1194
regions.Add (new EnableAll (line));
1197
public void WarningEnable (Location location, int code, Report Report)
1199
if (!Report.CheckWarningCode (code, location))
1202
if (Report.IsWarningDisabledGlobally (code))
1203
Report.Warning (1635, 1, location, "Cannot restore warning `CS{0:0000}' because it was disabled globally", code);
1205
regions.Add (new Enable (location.Row, code));
1208
public bool IsWarningEnabled (int code, int src_line)
1211
foreach (PragmaCmd pragma in regions) {
1212
if (src_line < pragma.Line)
1215
result = pragma.IsEnabled (code, result);