Add missing Clone
[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 {
171                 int token; 
172
173                 struct Checkpoint {
174                         public readonly int LineOffset;
175                         public readonly int CompilationUnit;
176                         public readonly int File;
177
178                         public Checkpoint (int compile_unit, int file, int line)
179                         {
180                                 File = file;
181                                 CompilationUnit = compile_unit;
182                                 LineOffset = line - (int) (line % (1 << line_delta_bits));
183                         }
184                 }
185
186                 static List<SourceFile> source_list;
187                 static List<CompilationUnit> compile_units;
188                 static Dictionary<string, int> source_files;
189                 static int checkpoint_bits;
190                 static int source_count;
191                 static int current_source;
192                 static int current_compile_unit;
193                 static int line_delta_bits;
194                 static int line_delta_mask;
195                 static int column_bits;
196                 static int column_mask;
197                 static Checkpoint [] checkpoints;
198                 static int checkpoint_index;
199                 
200                 public readonly static Location Null = new Location (-1);
201                 public static bool InEmacs;
202                 
203                 static Location ()
204                 {
205                         Reset ();
206                         checkpoints = new Checkpoint [10];
207                 }
208
209                 public static void Reset ()
210                 {
211                         source_files = new Dictionary<string, int> ();
212                         source_list = new List<SourceFile> ();
213                         compile_units = new List<CompilationUnit> ();
214                         current_source = 0;
215                         current_compile_unit = 0;
216                         source_count = 0;
217                 }
218
219                 // <summary>
220                 //   This must be called before parsing/tokenizing any files.
221                 // </summary>
222                 static public void AddFile (Report r, string name)
223                 {
224                         string path = Path.GetFullPath (name);
225                         int id;
226                         if (source_files.TryGetValue (path, out id)){
227                                 string other_name = source_list [id - 1].Name;
228                                 if (name.Equals (other_name))
229                                         r.Warning (2002, 1, "Source file `{0}' specified multiple times", other_name);
230                                 else
231                                         r.Warning (2002, 1, "Source filenames `{0}' and `{1}' both refer to the same file: {2}", name, other_name, path);
232                                 return;
233                         }
234
235                         source_files.Add (path, ++source_count);
236                         CompilationUnit unit = new CompilationUnit (name, path, source_count);
237                         source_list.Add (unit);
238                         compile_units.Add (unit);
239                 }
240
241                 public static IList<CompilationUnit> SourceFiles {
242                         get {
243                                 return compile_units;
244                         }
245                 }
246
247                 // <summary>
248                 //   After adding all source files we want to compile with AddFile(), this method
249                 //   must be called to `reserve' an appropriate number of bits in the token for the
250                 //   source file.  We reserve some extra space for files we encounter via #line
251                 //   directives while parsing.
252                 // </summary>
253                 static public void Initialize ()
254                 {
255                         checkpoints = new Checkpoint [source_list.Count * 2];
256                         if (checkpoints.Length > 0)
257                                 checkpoints [0] = new Checkpoint (0, 0, 0);
258
259                         column_bits = 8;
260                         column_mask = 0xFF;
261                         line_delta_bits = 8;
262                         line_delta_mask = 0xFF00;
263                         checkpoint_index = 0;
264                         checkpoint_bits = 16;
265                 }
266
267                 // <remarks>
268                 //   This is used when we encounter a #line preprocessing directive.
269                 // </remarks>
270                 static public SourceFile LookupFile (CompilationUnit comp_unit, string name)
271                 {
272                         string path;
273                         if (!Path.IsPathRooted (name)) {
274                                 string root = Path.GetDirectoryName (comp_unit.Path);
275                                 path = Path.Combine (root, name);
276                         } else
277                                 path = name;
278
279                         if (!source_files.ContainsKey (path)) {
280                                 if (source_count >= (1 << checkpoint_bits))
281                                         return new SourceFile (name, path, 0, true);
282
283                                 source_files.Add (path, ++source_count);
284                                 SourceFile retval = new SourceFile (name, path, source_count, true);
285                                 source_list.Add (retval);
286                                 return retval;
287                         }
288
289                         int index = (int) source_files [path];
290                         return (SourceFile) source_list [index - 1];
291                 }
292
293                 static public void Push (CompilationUnit compile_unit, SourceFile file)
294                 {
295                         current_source = file != null ? file.Index : -1;
296                         current_compile_unit = compile_unit != null ? compile_unit.Index : -1;
297                         // File is always pushed before being changed.
298                 }
299
300                 // <remarks>
301                 //   If we're compiling with debugging support, this is called between parsing
302                 //   and code generation to register all the source files with the
303                 //   symbol writer.
304                 // </remarks>
305                 static public void DefineSymbolDocuments (MonoSymbolWriter symwriter)
306                 {
307                         foreach (CompilationUnit unit in compile_units)
308                                 unit.DefineSymbolInfo (symwriter);
309                 }
310                 
311                 public Location (int row)
312                         : this (row, 0)
313                 {
314                 }
315
316                 public Location (int row, int column)
317                 {
318                         if (row <= 0)
319                                 token = 0;
320                         else {
321                                 if (column > 254)
322                                         column = 254;
323                                 if (column < 0)
324                                         column = 255;
325                                 int target = -1;
326                                 int delta = 0;
327                                 int max = checkpoint_index < 10 ?
328                                         checkpoint_index : 10;
329                                 for (int i = 0; i < max; i++) {
330                                         int offset = checkpoints [checkpoint_index - i].LineOffset;
331                                         delta = row - offset;
332                                         if (delta >= 0 &&
333                                                 delta < (1 << line_delta_bits) &&
334                                                 checkpoints [checkpoint_index - i].File == current_source) {
335                                                 target = checkpoint_index - i;
336                                                 break;
337                                         }
338                                 }
339                                 if (target == -1) {
340                                         AddCheckpoint (current_compile_unit, current_source, row);
341                                         target = checkpoint_index;
342                                         delta = row % (1 << line_delta_bits);
343                                 }
344                                 long l = column +
345                                         (long) (delta << column_bits) +
346                                         (long) (target << (line_delta_bits + column_bits));
347                                 token = l > 0xFFFFFFFF ? 0 : (int) l;
348                         }
349                 }
350
351                 public static Location operator - (Location loc, int columns)
352                 {
353                         return new Location (loc.Row, loc.Column - columns);
354                 }
355
356                 static void AddCheckpoint (int compile_unit, int file, int row)
357                 {
358                         if (checkpoints.Length == ++checkpoint_index) {
359                                 Checkpoint [] tmp = new Checkpoint [checkpoint_index * 2];
360                                 Array.Copy (checkpoints, tmp, checkpoints.Length);
361                                 checkpoints = tmp;
362                         }
363                         checkpoints [checkpoint_index] = new Checkpoint (compile_unit, file, row);
364                 }
365                 
366                 public override string ToString ()
367                 {
368                         if (column_bits == 0 || InEmacs)
369                                 return Name + "(" + Row.ToString () + "):";
370                         else
371                                 return Name + "(" + Row.ToString () + "," + Column.ToString () +
372                                         (Column == column_mask ? "+):" : "):");
373                 }
374                 
375                 /// <summary>
376                 ///   Whether the Location is Null
377                 /// </summary>
378                 public bool IsNull {
379                         get { return token == 0; }
380                 }
381
382                 public string Name {
383                         get {
384                                 int index = File;
385                                 if (token == 0 || index == 0)
386                                         return "Internal";
387
388                                 SourceFile file = (SourceFile) source_list [index - 1];
389                                 return file.Name;
390                         }
391                 }
392
393                 int CheckpointIndex {
394                         get { return (int) ((token & 0xFFFF0000) >> (line_delta_bits + column_bits)); }
395                 }
396
397                 public int Row {
398                         get {
399                                 if (token == 0)
400                                         return 1;
401                                 return checkpoints [CheckpointIndex].LineOffset + ((token & line_delta_mask) >> column_bits);
402                         }
403                 }
404
405                 public int Column {
406                         get {
407                                 if (token == 0)
408                                         return 1;
409                                 int col = (int) (token & column_mask);
410                                 return col == 255 ? 1 : col;
411                         }
412                 }
413
414                 public bool Hidden {
415                         get {
416                                 return (int) (token & column_mask) == 255;
417                         }
418                 }
419
420                 public int CompilationUnitIndex {
421                         get {
422                                 if (token == 0)
423                                         return 0;
424 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));
425                                 return checkpoints [CheckpointIndex].CompilationUnit;
426                         }
427                 }
428
429                 public int File {
430                         get {
431                                 if (token == 0)
432                                         return 0;
433 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));
434                                 return checkpoints [CheckpointIndex].File;
435                         }
436                 }
437
438                 // The ISymbolDocumentWriter interface is used by the symbol writer to
439                 // describe a single source file - for each source file there's exactly
440                 // one corresponding ISymbolDocumentWriter instance.
441                 //
442                 // This class has an internal hash table mapping source document names
443                 // to such ISymbolDocumentWriter instances - so there's exactly one
444                 // instance per document.
445                 //
446                 // This property returns the ISymbolDocumentWriter instance which belongs
447                 // to the location's source file.
448                 //
449                 // If we don't have a symbol writer, this property is always null.
450                 public SourceFile SourceFile {
451                         get {
452                                 int index = File;
453                                 if (index == 0)
454                                         return null;
455                                 return (SourceFile) source_list [index - 1];
456                         }
457                 }
458
459                 public CompilationUnit CompilationUnit {
460                         get {
461                                 int index = CompilationUnitIndex;
462                                 if (index == 0)
463                                         return null;
464                                 return (CompilationUnit) source_list [index - 1];
465                         }
466                 }
467         }
468
469         //
470         // A bag of additional locations to support full ast tree
471         //
472         public class LocationsBag
473         {
474                 public class MemberLocations
475                 {
476                         public readonly IList<Tuple<Modifiers, Location>> Modifiers;
477                         Location[] locations;
478
479                         public MemberLocations (IList<Tuple<Modifiers, Location>> mods, Location[] locs)
480                         {
481                                 Modifiers = mods;
482                                 locations = locs;
483                         }
484
485                         #region Properties
486
487                         public Location this [int index] {
488                                 get {
489                                         return locations [index];
490                                 }
491                         }
492                         
493                         public int Count {
494                                 get {
495                                         return locations.Length;
496                                 }
497                         }
498
499                         #endregion
500
501                         public void AddLocations (params Location[] additional)
502                         {
503                                 if (locations == null) {
504                                         locations = additional;
505                                 } else {
506                                         int pos = locations.Length;
507                                         Array.Resize (ref locations, pos + additional.Length);
508                                         additional.CopyTo (locations, pos);
509                                 }
510                         }
511                 }
512
513                 Dictionary<object, Location[]> simple_locs = new Dictionary<object, Location[]> (ReferenceEquality<object>.Default);
514                 Dictionary<MemberCore, MemberLocations> member_locs = new Dictionary<MemberCore, MemberLocations> (ReferenceEquality<MemberCore>.Default);
515
516                 [Conditional ("FULL_AST")]
517                 public void AddLocation (object element, params Location[] locations)
518                 {
519                         simple_locs.Add (element, locations);
520                 }
521
522                 [Conditional ("FULL_AST")]
523                 public void AddStatement (object element, params Location[] locations)
524                 {
525                         if (locations.Length == 0)
526                                 throw new ArgumentException ("Statement is missing semicolon location");
527
528                         simple_locs.Add (element, locations);
529                 }
530
531                 [Conditional ("FULL_AST")]
532                 public void AddMember (MemberCore member, IList<Tuple<Modifiers, Location>> modLocations, params Location[] locations)
533                 {
534                         member_locs.Add (member, new MemberLocations (modLocations, locations));
535                 }
536
537                 [Conditional ("FULL_AST")]
538                 public void AppendTo (object existing, params Location[] locations)
539                 {
540                         Location[] locs;
541                         if (simple_locs.TryGetValue (existing, out locs)) {
542                                 simple_locs [existing] = locs.Concat (locations).ToArray ();
543                                 return;
544                         }
545                 }
546
547                 [Conditional ("FULL_AST")]
548                 public void AppendToMember (MemberCore existing, params Location[] locations)
549                 {
550                         MemberLocations member;
551                         if (member_locs.TryGetValue (existing, out member)) {
552                                 member.AddLocations (locations);
553                                 return;
554                         }
555                 }
556
557                 public Location[] GetLocations (object element)
558                 {
559                         Location[] found;
560                         simple_locs.TryGetValue (element, out found);
561                         return found;
562                 }
563
564                 public MemberLocations GetMemberLocation (MemberCore element)
565                 {
566                         MemberLocations found;
567                         member_locs.TryGetValue (element, out found);
568                         return found;
569                 }
570         }
571 }