Fix Location to have reasonable limits when running under MD
[mono.git] / mcs / mcs / location.cs
1 //
2 // location.cs: Keeps track of the location of source code entity
3 //
4 // Author:
5 //   Miguel de Icaza
6 //   Atsushi Enomoto  <atsushi@ximian.com>
7 //   Marek Safar (marek.safar@gmail.com)
8 //
9 // Copyright 2001 Ximian, Inc.
10 // Copyright 2005 Novell, Inc.
11 //
12
13 using System;
14 using System.IO;
15 using System.Collections.Generic;
16 using Mono.CompilerServices.SymbolWriter;
17 using System.Diagnostics;
18 using System.Linq;
19
20 namespace Mono.CSharp {
21         /// <summary>
22         ///   This is one single source file.
23         /// </summary>
24         /// <remarks>
25         ///   This is intentionally a class and not a struct since we need
26         ///   to pass this by reference.
27         /// </remarks>
28         public class SourceFile : ISourceFile {
29                 public readonly string Name;
30                 public readonly string Path;
31                 public readonly int Index;
32                 public bool AutoGenerated;
33                 public bool IsIncludeFile;
34
35                 SourceFileEntry file;
36                 byte[] guid, checksum;
37
38                 public SourceFile (string name, string path, int index, bool is_include)
39                 {
40                         this.Index = index;
41                         this.Name = name;
42                         this.Path = path;
43                         this.IsIncludeFile = is_include;
44                 }
45
46                 public SourceFileEntry SourceFileEntry {
47                         get { return file; }
48                 }
49
50                 SourceFileEntry ISourceFile.Entry {
51                         get { return file; }
52                 }
53
54                 public void SetChecksum (byte[] guid, byte[] checksum)
55                 {
56                         this.guid = guid;
57                         this.checksum = checksum;
58                 }
59
60                 public virtual void DefineSymbolInfo (MonoSymbolWriter symwriter)
61                 {
62                         if (guid != null)
63                                 file = symwriter.DefineDocument (Path, guid, checksum);
64                         else {
65                                 file = symwriter.DefineDocument (Path);
66                                 if (AutoGenerated)
67                                         file.SetAutoGenerated ();
68                         }
69                 }
70
71                 public override string ToString ()
72                 {
73                         return String.Format ("SourceFile ({0}:{1}:{2}:{3})",
74                                               Name, Path, Index, SourceFileEntry);
75                 }
76         }
77
78         public class CompilationUnit : SourceFile, ICompileUnit
79         {
80                 CompileUnitEntry comp_unit;
81                 Dictionary<string, SourceFile> include_files;
82                 Dictionary<string, bool> conditionals;
83
84                 public CompilationUnit (string name, string path, int index)
85                         : base (name, path, index, false)
86                 { }
87
88                 public void AddFile (SourceFile file)
89                 {
90                         if (file == this)
91                                 return;
92                         
93                         if (include_files == null)
94                                 include_files = new Dictionary<string, SourceFile> ();
95
96                         if (!include_files.ContainsKey (file.Path))
97                                 include_files.Add (file.Path, file);
98                 }
99
100                 public void AddDefine (string value)
101                 {
102                         if (conditionals == null)
103                                 conditionals = new Dictionary<string, bool> (2);
104
105                         conditionals [value] = true;
106                 }
107
108                 public void AddUndefine (string value)
109                 {
110                         if (conditionals == null)
111                                 conditionals = new Dictionary<string, bool> (2);
112
113                         conditionals [value] = false;
114                 }
115
116                 CompileUnitEntry ICompileUnit.Entry {
117                         get { return comp_unit; }
118                 }
119
120                 public CompileUnitEntry CompileUnitEntry {
121                         get { return comp_unit; }
122                 }
123
124                 public override void DefineSymbolInfo (MonoSymbolWriter symwriter)
125                 {
126                         base.DefineSymbolInfo (symwriter);
127
128                         comp_unit = symwriter.DefineCompilationUnit (SourceFileEntry);
129
130                         if (include_files != null) {
131                                 foreach (SourceFile include in include_files.Values) {
132                                         include.DefineSymbolInfo (symwriter);
133                                         comp_unit.AddFile (include.SourceFileEntry);
134                                 }
135                         }
136                 }
137
138                 public bool IsConditionalDefined (string value)
139                 {
140                         if (conditionals != null) {
141                                 bool res;
142                                 if (conditionals.TryGetValue (value, out res))
143                                         return res;
144                                 
145                                 // When conditional was undefined
146                                 if (conditionals.ContainsKey (value))
147                                         return false;                                   
148                         }
149
150                         return RootContext.IsConditionalDefined (value);
151                 }
152         }
153
154         /// <summary>
155         ///   Keeps track of the location in the program
156         /// </summary>
157         ///
158         /// <remarks>
159         ///   This uses a compact representation and a couple of auxiliary
160         ///   structures to keep track of tokens to (file,line and column) 
161         ///   mappings. The usage of the bits is:
162         ///   
163         ///     - 16 bits for "checkpoint" which is a mixed concept of
164         ///       file and "line segment"
165         ///     - 8 bits for line delta (offset) from the line segment
166         ///     - 8 bits for column number.
167         ///
168         ///   http://lists.ximian.com/pipermail/mono-devel-list/2004-December/009508.html
169         /// </remarks>
170         public struct Location : IEquatable<Location>
171         {
172                 struct Checkpoint {
173                         public readonly int LineOffset;
174                         public readonly int CompilationUnit;
175                         public readonly int File;
176
177                         public Checkpoint (int compile_unit, int file, int line)
178                         {
179                                 File = file;
180                                 CompilationUnit = compile_unit;
181                                 LineOffset = line - (int) (line % (1 << line_delta_bits));
182                         }
183                 }
184
185 #if FULL_AST
186                 long token;
187
188                 const int column_bits = 32;
189                 const int line_delta_bits = 16;
190 #else
191                 int token;
192
193                 const int column_bits = 8;
194                 const int line_delta_bits = 8;
195 #endif
196                 const int checkpoint_bits = 16;
197
198                 // -2 because the last one is used for hidden
199                 const int max_column = (1 << column_bits) - 2;
200                 const int column_mask = (1 << column_bits) - 1;
201
202                 static List<SourceFile> source_list;
203                 static List<CompilationUnit> compile_units;
204                 static Dictionary<string, int> source_files;
205                 static int source_count;
206                 static int current_source;
207                 static int current_compile_unit;
208                 static Checkpoint [] checkpoints;
209                 static int checkpoint_index;
210                 
211                 public readonly static Location Null = new Location (-1);
212                 public static bool InEmacs;
213                 
214                 static Location ()
215                 {
216                         Reset ();
217                 }
218
219                 public static void Reset ()
220                 {
221                         source_files = new Dictionary<string, int> ();
222                         source_list = new List<SourceFile> ();
223                         compile_units = new List<CompilationUnit> ();
224                         current_source = 0;
225                         current_compile_unit = 0;
226                         source_count = 0;
227                         checkpoint_index = 0;
228                 }
229
230                 // <summary>
231                 //   This must be called before parsing/tokenizing any files.
232                 // </summary>
233                 static public void AddFile (Report r, string name)
234                 {
235                         string path = Path.GetFullPath (name);
236                         int id;
237                         if (source_files.TryGetValue (path, out id)){
238                                 string other_name = source_list [id - 1].Name;
239                                 if (name.Equals (other_name))
240                                         r.Warning (2002, 1, "Source file `{0}' specified multiple times", other_name);
241                                 else
242                                         r.Warning (2002, 1, "Source filenames `{0}' and `{1}' both refer to the same file: {2}", name, other_name, path);
243                                 return;
244                         }
245
246                         source_files.Add (path, ++source_count);
247                         CompilationUnit unit = new CompilationUnit (name, path, source_count);
248                         source_list.Add (unit);
249                         compile_units.Add (unit);
250                 }
251
252                 public static string FirstFile {
253                         get {
254                                 return compile_units.Count == 0 ? null : compile_units[0].Name;
255                         }
256                 }
257
258                 public static IList<CompilationUnit> SourceFiles {
259                         get {
260                                 return compile_units;
261                         }
262                 }
263
264                 // <summary>
265                 //   After adding all source files we want to compile with AddFile(), this method
266                 //   must be called to `reserve' an appropriate number of bits in the token for the
267                 //   source file.  We reserve some extra space for files we encounter via #line
268                 //   directives while parsing.
269                 // </summary>
270                 static public void Initialize ()
271                 {
272                         checkpoints = new Checkpoint [source_list.Count * 2];
273                         if (checkpoints.Length > 0)
274                                 checkpoints [0] = new Checkpoint (0, 0, 0);
275                 }
276
277                 // <remarks>
278                 //   This is used when we encounter a #line preprocessing directive.
279                 // </remarks>
280                 static public SourceFile LookupFile (CompilationUnit comp_unit, string name)
281                 {
282                         string path;
283                         if (!Path.IsPathRooted (name)) {
284                                 string root = Path.GetDirectoryName (comp_unit.Path);
285                                 path = Path.Combine (root, name);
286                         } else
287                                 path = name;
288
289                         if (!source_files.ContainsKey (path)) {
290                                 if (source_count >= (1 << checkpoint_bits))
291                                         return new SourceFile (name, path, 0, true);
292
293                                 source_files.Add (path, ++source_count);
294                                 SourceFile retval = new SourceFile (name, path, source_count, true);
295                                 source_list.Add (retval);
296                                 return retval;
297                         }
298
299                         int index = source_files [path];
300                         return source_list [index - 1];
301                 }
302
303                 static public void Push (CompilationUnit compile_unit, SourceFile file)
304                 {
305                         current_source = file != null ? file.Index : -1;
306                         current_compile_unit = compile_unit != null ? compile_unit.Index : -1;
307                         // File is always pushed before being changed.
308                 }
309
310                 // <remarks>
311                 //   If we're compiling with debugging support, this is called between parsing
312                 //   and code generation to register all the source files with the
313                 //   symbol writer.
314                 // </remarks>
315                 static public void DefineSymbolDocuments (MonoSymbolWriter symwriter)
316                 {
317                         foreach (CompilationUnit unit in compile_units)
318                                 unit.DefineSymbolInfo (symwriter);
319                 }
320                 
321                 public Location (int row)
322                         : this (row, 0)
323                 {
324                 }
325
326                 public Location (int row, int column)
327                 {
328                         if (row <= 0)
329                                 token = 0;
330                         else {
331                                 if (column > max_column)
332                                         column = max_column;
333                                 else if (column < 0)
334                                         column = max_column + 1;
335
336                                 long target = -1;
337                                 long delta = 0;
338
339                                 // FIXME: This value is certainly wrong but what was the intension
340                                 int max = checkpoint_index < 10 ?
341                                         checkpoint_index : 10;
342                                 for (int i = 0; i < max; i++) {
343                                         int offset = checkpoints [checkpoint_index - i].LineOffset;
344                                         delta = row - offset;
345                                         if (delta >= 0 &&
346                                                 delta < (1 << line_delta_bits) &&
347                                                 checkpoints [checkpoint_index - i].File == current_source) {
348                                                 target = checkpoint_index - i;
349                                                 break;
350                                         }
351                                 }
352                                 if (target == -1) {
353                                         AddCheckpoint (current_compile_unit, current_source, row);
354                                         target = checkpoint_index;
355                                         delta = row % (1 << line_delta_bits);
356                                 }
357
358                                 long l = column +
359                                         (delta << column_bits) +
360                                         (target << (line_delta_bits + column_bits));
361 #if FULL_AST
362                                 token = l;
363 #else
364                                 token = l > 0xFFFFFFFF ? 0 : (int) l;
365 #endif
366                         }
367                 }
368
369                 public static Location operator - (Location loc, int columns)
370                 {
371                         return new Location (loc.Row, loc.Column - columns);
372                 }
373
374                 static void AddCheckpoint (int compile_unit, int file, int row)
375                 {
376                         if (checkpoints.Length == ++checkpoint_index) {
377                                 Array.Resize (ref checkpoints, checkpoint_index + 2);
378                         }
379                         checkpoints [checkpoint_index] = new Checkpoint (compile_unit, file, row);
380                 }
381
382                 string FormatLocation (string fileName)
383                 {
384                         if (column_bits == 0 || InEmacs)
385                                 return fileName + "(" + Row.ToString () + "):";
386
387                         return fileName + "(" + Row.ToString () + "," + Column.ToString () +
388                                 (Column == max_column ? "+):" : "):");
389                 }
390                 
391                 public override string ToString ()
392                 {
393                         return FormatLocation (Name);
394                 }
395
396                 public string ToStringFullName ()
397                 {
398                         return FormatLocation (NameFullPath);
399                 }
400                 
401                 /// <summary>
402                 ///   Whether the Location is Null
403                 /// </summary>
404                 public bool IsNull {
405                         get { return token == 0; }
406                 }
407
408                 public string Name {
409                         get {
410                                 int index = File;
411                                 if (token == 0 || index == 0)
412                                         return "Internal";
413
414                                 SourceFile file = source_list [index - 1];
415                                 return file.Name;
416                         }
417                 }
418
419                 public string NameFullPath {
420                         get {
421                                 int index = File;
422                                 if (token == 0 || index == 0)
423                                         return "Internal";
424
425                                 return source_list [index - 1].Path;
426                         }
427                 }
428
429                 int CheckpointIndex {
430                         get {
431                                 const int checkpoint_mask = (1 << checkpoint_bits) - 1;
432                                 return ((int) (token >> (line_delta_bits + column_bits))) & checkpoint_mask;
433                         }
434                 }
435
436                 public int Row {
437                         get {
438                                 if (token == 0)
439                                         return 1;
440
441                                 int offset = checkpoints[CheckpointIndex].LineOffset;
442
443                                 const int line_delta_mask = (1 << column_bits) - 1;
444                                 return offset + (((int)(token >> column_bits)) & line_delta_mask);
445                         }
446                 }
447
448                 public int Column {
449                         get {
450                                 if (token == 0)
451                                         return 1;
452                                 int col = (int) (token & column_mask);
453                                 return col > max_column ? 1 : col;
454                         }
455                 }
456
457                 public bool Hidden {
458                         get {
459                                 return (int) (token & column_mask) == max_column + 1;
460                         }
461                 }
462
463                 public int CompilationUnitIndex {
464                         get {
465                                 if (token == 0)
466                                         return 0;
467 if (checkpoints.Length <= CheckpointIndex) throw new Exception (String.Format ("Should not happen. Token is {0:X04}, checkpoints are {1}, index is {2}", token, checkpoints.Length, CheckpointIndex));
468                                 return checkpoints [CheckpointIndex].CompilationUnit;
469                         }
470                 }
471
472                 public int File {
473                         get {
474                                 if (token == 0)
475                                         return 0;
476 if (checkpoints.Length <= CheckpointIndex) throw new Exception (String.Format ("Should not happen. Token is {0:X04}, checkpoints are {1}, index is {2}", token, checkpoints.Length, CheckpointIndex));
477                                 return checkpoints [CheckpointIndex].File;
478                         }
479                 }
480
481                 // The ISymbolDocumentWriter interface is used by the symbol writer to
482                 // describe a single source file - for each source file there's exactly
483                 // one corresponding ISymbolDocumentWriter instance.
484                 //
485                 // This class has an internal hash table mapping source document names
486                 // to such ISymbolDocumentWriter instances - so there's exactly one
487                 // instance per document.
488                 //
489                 // This property returns the ISymbolDocumentWriter instance which belongs
490                 // to the location's source file.
491                 //
492                 // If we don't have a symbol writer, this property is always null.
493                 public SourceFile SourceFile {
494                         get {
495                                 int index = File;
496                                 if (index == 0)
497                                         return null;
498                                 return (SourceFile) source_list [index - 1];
499                         }
500                 }
501
502                 public CompilationUnit CompilationUnit {
503                         get {
504                                 int index = CompilationUnitIndex;
505                                 if (index == 0)
506                                         return null;
507                                 return (CompilationUnit) source_list [index - 1];
508                         }
509                 }
510
511                 #region IEquatable<Location> Members
512
513                 public bool Equals (Location other)
514                 {
515                         return this.token == other.token;
516                 }
517
518                 #endregion
519         }
520
521         //
522         // A bag of additional locations to support full ast tree
523         //
524         public class LocationsBag
525         {
526                 public class MemberLocations
527                 {
528                         public readonly IList<Tuple<Modifiers, Location>> Modifiers;
529                         Location[] locations;
530
531                         public MemberLocations (IList<Tuple<Modifiers, Location>> mods, Location[] locs)
532                         {
533                                 Modifiers = mods;
534                                 locations = locs;
535                         }
536
537                         #region Properties
538
539                         public Location this [int index] {
540                                 get {
541                                         return locations [index];
542                                 }
543                         }
544                         
545                         public int Count {
546                                 get {
547                                         return locations.Length;
548                                 }
549                         }
550
551                         #endregion
552
553                         public void AddLocations (params Location[] additional)
554                         {
555                                 if (locations == null) {
556                                         locations = additional;
557                                 } else {
558                                         int pos = locations.Length;
559                                         Array.Resize (ref locations, pos + additional.Length);
560                                         additional.CopyTo (locations, pos);
561                                 }
562                         }
563                 }
564
565                 Dictionary<object, Location[]> simple_locs = new Dictionary<object, Location[]> (ReferenceEquality<object>.Default);
566                 Dictionary<MemberCore, MemberLocations> member_locs = new Dictionary<MemberCore, MemberLocations> (ReferenceEquality<MemberCore>.Default);
567
568                 [Conditional ("FULL_AST")]
569                 public void AddLocation (object element, params Location[] locations)
570                 {
571                         simple_locs.Add (element, locations);
572                 }
573
574                 [Conditional ("FULL_AST")]
575                 public void AddStatement (object element, params Location[] locations)
576                 {
577                         if (locations.Length == 0)
578                                 throw new ArgumentException ("Statement is missing semicolon location");
579
580                         simple_locs.Add (element, locations);
581                 }
582
583                 [Conditional ("FULL_AST")]
584                 public void AddMember (MemberCore member, IList<Tuple<Modifiers, Location>> modLocations, params Location[] locations)
585                 {
586                         member_locs.Add (member, new MemberLocations (modLocations, locations));
587                 }
588
589                 [Conditional ("FULL_AST")]
590                 public void AppendTo (object existing, params Location[] locations)
591                 {
592                         Location[] locs;
593                         if (simple_locs.TryGetValue (existing, out locs)) {
594                                 simple_locs [existing] = locs.Concat (locations).ToArray ();
595                                 return;
596                         }
597                 }
598
599                 [Conditional ("FULL_AST")]
600                 public void AppendToMember (MemberCore existing, params Location[] locations)
601                 {
602                         MemberLocations member;
603                         if (member_locs.TryGetValue (existing, out member)) {
604                                 member.AddLocations (locations);
605                                 return;
606                         }
607                 }
608
609                 public Location[] GetLocations (object element)
610                 {
611                         Location[] found;
612                         simple_locs.TryGetValue (element, out found);
613                         return found;
614                 }
615
616                 public MemberLocations GetMemberLocation (MemberCore element)
617                 {
618                         MemberLocations found;
619                         member_locs.TryGetValue (element, out found);
620                         return found;
621                 }
622         }
623 }