[xbuild] Fix bug #674337.
[mono.git] / mcs / mcs / namespace.cs
1 //
2 // namespace.cs: Tracks namespaces
3 //
4 // Author:
5 //   Miguel de Icaza (miguel@ximian.com)
6 //   Marek Safar (marek.safar@seznam.cz)
7 //
8 // Copyright 2001 Ximian, Inc.
9 // Copyright 2003-2008 Novell, Inc.
10 //
11 using System;
12 using System.Collections.Generic;
13 using System.Linq;
14
15 namespace Mono.CSharp {
16
17         public class RootNamespace : Namespace {
18
19                 readonly string alias_name;
20                 readonly Dictionary<string, Namespace> all_namespaces;
21
22                 public RootNamespace (string alias_name)
23                         : base (null, String.Empty)
24                 {
25                         this.alias_name = alias_name;
26
27                         all_namespaces = new Dictionary<string, Namespace> ();
28                         all_namespaces.Add ("", this);
29                 }
30
31                 public string Alias {
32                         get {
33                                 return alias_name;
34                         }
35                 }
36
37                 public void RegisterNamespace (Namespace child)
38                 {
39                         if (child != this)
40                                 all_namespaces.Add (child.Name, child);
41                 }
42
43                 public bool IsNamespace (string name)
44                 {
45                         return all_namespaces.ContainsKey (name);
46                 }
47
48                 protected void RegisterNamespace (string dotted_name)
49                 {
50                         if (dotted_name != null && dotted_name.Length != 0 && ! IsNamespace (dotted_name))
51                                 GetNamespace (dotted_name, true);
52                 }
53
54                 public override string GetSignatureForError ()
55                 {
56                         return alias_name + "::";
57                 }
58         }
59
60         public class GlobalRootNamespace : RootNamespace
61         {
62                 public GlobalRootNamespace ()
63                         : base ("global")
64                 {
65                 }
66
67                 public override void Error_NamespaceDoesNotExist (Location loc, string name, int arity, IMemberContext ctx)
68                 {
69                         ctx.Module.Compiler.Report.Error (400, loc,
70                                 "The type or namespace name `{0}' could not be found in the global namespace (are you missing an assembly reference?)",
71                                 name);
72                 }
73         }
74
75         /// <summary>
76         ///   Keeps track of the namespaces defined in the C# code.
77         ///
78         ///   This is an Expression to allow it to be referenced in the
79         ///   compiler parse/intermediate tree during name resolution.
80         /// </summary>
81         public class Namespace : FullNamedExpression {
82                 
83                 Namespace parent;
84                 string fullname;
85                 protected Dictionary<string, Namespace> namespaces;
86                 protected Dictionary<string, IList<TypeSpec>> types;
87                 Dictionary<string, TypeExpr> cached_types;
88                 RootNamespace root;
89                 bool cls_checked;
90
91                 public readonly MemberName MemberName;
92
93                 /// <summary>
94                 ///   Constructor Takes the current namespace and the
95                 ///   name.  This is bootstrapped with parent == null
96                 ///   and name = ""
97                 /// </summary>
98                 public Namespace (Namespace parent, string name)
99                 {
100                         // Expression members.
101                         this.eclass = ExprClass.Namespace;
102                         this.Type = InternalType.FakeInternalType;
103                         this.loc = Location.Null;
104
105                         this.parent = parent;
106
107                         if (parent != null)
108                                 this.root = parent.root;
109                         else
110                                 this.root = this as RootNamespace;
111
112                         if (this.root == null)
113                                 throw new InternalErrorException ("Root namespaces must be created using RootNamespace");
114                         
115                         string pname = parent != null ? parent.fullname : "";
116                                 
117                         if (pname == "")
118                                 fullname = name;
119                         else
120                                 fullname = parent.fullname + "." + name;
121
122                         if (fullname == null)
123                                 throw new InternalErrorException ("Namespace has a null fullname");
124
125                         if (parent != null && parent.MemberName != MemberName.Null)
126                                 MemberName = new MemberName (parent.MemberName, name);
127                         else if (name.Length == 0)
128                                 MemberName = MemberName.Null;
129                         else
130                                 MemberName = new MemberName (name);
131
132                         namespaces = new Dictionary<string, Namespace> ();
133                         cached_types = new Dictionary<string, TypeExpr> ();
134
135                         root.RegisterNamespace (this);
136                 }
137
138                 #region Properties
139
140                 /// <summary>
141                 ///   The qualified name of the current namespace
142                 /// </summary>
143                 public string Name {
144                         get { return fullname; }
145                 }
146
147                 /// <summary>
148                 ///   The parent of this namespace, used by the parser to "Pop"
149                 ///   the current namespace declaration
150                 /// </summary>
151                 public Namespace Parent {
152                         get { return parent; }
153                 }
154
155                 #endregion
156
157                 protected override Expression DoResolve (ResolveContext ec)
158                 {
159                         return this;
160                 }
161
162                 public virtual void Error_NamespaceDoesNotExist (Location loc, string name, int arity, IMemberContext ctx)
163                 {
164                         FullNamedExpression retval = Lookup (ctx, name, -System.Math.Max (1, arity), loc);
165                         if (retval != null) {
166                                 Error_TypeArgumentsCannotBeUsed (ctx.Module.Compiler.Report, loc, retval.Type, arity);
167                                 return;
168                         }
169
170                         Namespace ns;
171                         if (arity > 0 && namespaces.TryGetValue (name, out ns)) {
172                                 ns.Error_TypeArgumentsCannotBeUsed (ctx.Module.Compiler.Report, loc, null, arity);
173                                 return;
174                         }
175
176                         ctx.Module.Compiler.Report.Error (234, loc,
177                                 "The type or namespace name `{0}' does not exist in the namespace `{1}'. Are you missing an assembly reference?",
178                                 name, GetSignatureForError ());
179                 }
180
181                 public override string GetSignatureForError ()
182                 {
183                         return fullname;
184                 }
185                 
186                 public Namespace GetNamespace (string name, bool create)
187                 {
188                         int pos = name.IndexOf ('.');
189
190                         Namespace ns;
191                         string first;
192                         if (pos >= 0)
193                                 first = name.Substring (0, pos);
194                         else
195                                 first = name;
196
197                         if (!namespaces.TryGetValue (first, out ns)) {
198                                 if (!create)
199                                         return null;
200
201                                 ns = new Namespace (this, first);
202                                 namespaces.Add (first, ns);
203                         }
204
205                         if (pos >= 0)
206                                 ns = ns.GetNamespace (name.Substring (pos + 1), create);
207
208                         return ns;
209                 }
210
211                 public TypeExpr LookupType (IMemberContext ctx, string name, int arity, bool silent, Location loc)
212                 {
213                         if (types == null)
214                                 return null;
215
216                         TypeExpr te;
217                         if (arity == 0 && cached_types.TryGetValue (name, out te))
218                                 return te;
219
220                         IList<TypeSpec> found;
221                         if (!types.TryGetValue (name, out found))
222                                 return null;
223
224                         TypeSpec best = null;
225                         foreach (var ts in found) {
226                                 if (ts.Arity == arity) {
227                                         if (best == null) {
228                                                 best = ts;
229                                                 continue;
230                                         }
231
232                                         var pts = best as BuildinTypeSpec;
233                                         if (pts == null)
234                                                 pts = ts as BuildinTypeSpec;
235
236                                         if (pts != null) {
237                                                 ctx.Module.Compiler.Report.SymbolRelatedToPreviousError (best);
238                                                 ctx.Module.Compiler.Report.SymbolRelatedToPreviousError (ts);
239
240                                                 // TODO: This should use different warning number but we want to be csc compatible
241                                                 ctx.Module.Compiler.Report.Warning (1685, 1, loc,
242                                                         "The predefined type `{0}.{1}' is redefined in the source code. Ignoring the local type definition",
243                                                         pts.Namespace, pts.Name);
244                                                 best = pts;
245                                                 continue;
246                                         }
247
248                                         if (best.MemberDefinition.IsImported && ts.MemberDefinition.IsImported) {
249                                                 ctx.Module.Compiler.Report.SymbolRelatedToPreviousError (best);
250                                                 ctx.Module.Compiler.Report.SymbolRelatedToPreviousError (ts);
251                                                 if (silent) {
252                                                         ctx.Module.Compiler.Report.Warning (1685, 1, loc,
253                                                                 "The predefined type `{0}' is defined in multiple assemblies. Using definition from `{1}'",
254                                                                 ts.GetSignatureForError (), best.MemberDefinition.DeclaringAssembly.Name);
255                                                 } else {
256                                                         ctx.Module.Compiler.Report.Error (433, loc, "The imported type `{0}' is defined multiple times", ts.GetSignatureForError ());
257                                                 }
258
259                                                 break;
260                                         }
261
262                                         if (best.MemberDefinition.IsImported)
263                                                 best = ts;
264
265                                         if ((best.Modifiers & Modifiers.INTERNAL) != 0 && !best.MemberDefinition.IsInternalAsPublic (RootContext.ToplevelTypes.DeclaringAssembly))
266                                                 continue;
267
268                                         if (silent)
269                                                 continue;
270
271                                         if (ts.MemberDefinition.IsImported)
272                                                 ctx.Module.Compiler.Report.SymbolRelatedToPreviousError (ts);
273
274                                         ctx.Module.Compiler.Report.Warning (436, 2, loc,
275                                                 "The type `{0}' conflicts with the imported type of same name'. Ignoring the imported type definition",
276                                                 best.GetSignatureForError ());
277                                 }
278
279                                 //
280                                 // Lookup for the best candidate with closest arity match
281                                 //
282                                 if (arity < 0) {
283                                         if (best == null) {
284                                                 best = ts;
285                                         } else if (System.Math.Abs (ts.Arity + arity) < System.Math.Abs (best.Arity + arity)) {
286                                                 best = ts;
287                                         }
288                                 }
289                         }
290
291                         if (best == null)
292                                 return null;
293
294                         if ((best.Modifiers & Modifiers.INTERNAL) != 0 && !best.MemberDefinition.IsInternalAsPublic (RootContext.ToplevelTypes.DeclaringAssembly))
295                                 return null;
296
297                         te = new TypeExpression (best, Location.Null);
298
299                         // TODO MemberCache: Cache more
300                         if (arity == 0 && !silent)
301                                 cached_types.Add (name, te);
302
303                         return te;
304                 }
305
306                 TypeSpec LookupType (string name, int arity)
307                 {
308                         if (types == null)
309                                 return null;
310
311                         IList<TypeSpec> found;
312                         if (types.TryGetValue (name, out found)) {
313                                 TypeSpec best = null;
314
315                                 foreach (var ts in found) {
316                                         if (ts.Arity == arity)
317                                                 return ts;
318
319                                         //
320                                         // Lookup for the best candidate with closest arity match
321                                         //
322                                         if (arity < 0) {
323                                                 if (best == null) {
324                                                         best = ts;
325                                                 } else if (System.Math.Abs (ts.Arity + arity) < System.Math.Abs (best.Arity + arity)) {
326                                                         best = ts;
327                                                 }
328                                         }
329                                 }
330                                 
331                                 return best;
332                         }
333
334                         return null;
335                 }
336
337                 public FullNamedExpression Lookup (IMemberContext ctx, string name, int arity, Location loc)
338                 {
339                         if (arity == 0 && namespaces.ContainsKey (name))
340                                 return namespaces [name];
341
342                         return LookupType (ctx, name, arity, false, loc);
343                 }
344
345                 //
346                 // Completes types with the given `prefix'
347                 //
348                 public IEnumerable<string> CompletionGetTypesStartingWith (string prefix)
349                 {
350                         if (types == null)
351                                 return Enumerable.Empty<string> ();
352
353                         var res = from item in types
354                                           where item.Key.StartsWith (prefix) && item.Value.Any (l => (l.Modifiers & Modifiers.PUBLIC) != 0)
355                                           select item.Key;
356
357                         if (namespaces != null)
358                                 res = res.Concat (from item in namespaces where item.Key.StartsWith (prefix) select item.Key);
359
360                         return res;
361                 }
362
363                 /// 
364                 /// Looks for extension method in this namespace
365                 /// 
366                 public List<MethodSpec> LookupExtensionMethod (TypeSpec extensionType, TypeContainer invocationContext, string name, int arity)
367                 {
368                         if (types == null)
369                                 return null;
370
371                         List<MethodSpec> found = null;
372
373                         // TODO: Add per namespace flag when at least 1 type has extension
374
375                         foreach (var tgroup in types.Values) {
376                                 foreach (var ts in tgroup) {
377                                         if ((ts.Modifiers & Modifiers.METHOD_EXTENSION) == 0)
378                                                 continue;
379
380                                         var res = ts.MemberCache.FindExtensionMethods (invocationContext, extensionType, name, arity);
381                                         if (res == null)
382                                                 continue;
383
384                                         if (found == null) {
385                                                 found = res;
386                                         } else {
387                                                 found.AddRange (res);
388                                         }
389                                 }
390                         }
391
392                         return found;
393                 }
394
395                 public void AddType (TypeSpec ts)
396                 {
397                         if (types == null) {
398                                 types = new Dictionary<string, IList<TypeSpec>> (64);
399                         }
400
401                         var name = ts.Name;
402                         IList<TypeSpec> existing;
403                         if (types.TryGetValue (name, out existing)) {
404                                 TypeSpec better_type;
405                                 TypeSpec found;
406                                 if (existing.Count == 1) {
407                                         found = existing[0];
408                                         if (ts.Arity == found.Arity) {
409                                                 better_type = IsImportedTypeOverride (ts, found);
410                                                 if (better_type == found)
411                                                         return;
412
413                                                 if (better_type != null) {
414                                                         existing [0] = better_type;
415                                                         return;
416                                                 }
417                                         }
418
419                                         existing = new List<TypeSpec> ();
420                                         existing.Add (found);
421                                         types[name] = existing;
422                                 } else {
423                                         for (int i = 0; i < existing.Count; ++i) {
424                                                 found = existing[i];
425                                                 if (ts.Arity != found.Arity)
426                                                         continue;
427
428                                                 better_type = IsImportedTypeOverride (ts, found);
429                                                 if (better_type == found)
430                                                         return;
431
432                                                 if (better_type != null) {
433                                                         existing.RemoveAt (i);
434                                                         --i;
435                                                         continue;
436                                                 }
437                                         }
438                                 }
439
440                                 existing.Add (ts);
441                         } else {
442                                 types.Add (name, new TypeSpec[] { ts });
443                         }
444                 }
445
446                 //
447                 // We import any types but in the situation there are same types
448                 // but one has better visibility (either public or internal with friend)
449                 // the less visible type is removed from the namespace cache
450                 //
451                 public static TypeSpec IsImportedTypeOverride (TypeSpec ts, TypeSpec found)
452                 {
453                         var ts_accessible = (ts.Modifiers & Modifiers.PUBLIC) != 0 || ts.MemberDefinition.IsInternalAsPublic (RootContext.ToplevelTypes.DeclaringAssembly);
454                         var found_accessible = (found.Modifiers & Modifiers.PUBLIC) != 0 || found.MemberDefinition.IsInternalAsPublic (RootContext.ToplevelTypes.DeclaringAssembly);
455
456                         if (ts_accessible && !found_accessible)
457                                 return ts;
458
459                         // found is better always better for accessible or inaccessible ts
460                         if (!ts_accessible)
461                                 return found;
462
463                         return null;
464                 }
465
466                 public void RemoveDeclSpace (string name)
467                 {
468                         types.Remove (name);
469                         cached_types.Remove (name);
470                 }
471
472                 public void ReplaceTypeWithPredefined (TypeSpec ts, BuildinTypeSpec pts)
473                 {
474                         var found = types [ts.Name];
475                         cached_types.Remove (ts.Name);
476                         if (found.Count == 1) {
477                                 types[ts.Name][0] = pts;
478                         } else {
479                                 throw new NotImplementedException ();
480                         }
481                 }
482
483                 public void VerifyClsCompliance ()
484                 {
485                         if (types == null || cls_checked)
486                                 return;
487
488                         cls_checked = true;
489
490                         // TODO: This is quite ugly way to check for CLS compliance at namespace level
491
492                         var locase_types = new Dictionary<string, List<TypeSpec>> (StringComparer.OrdinalIgnoreCase);
493                         foreach (var tgroup in types.Values) {
494                                 foreach (var tm in tgroup) {
495                                         if ((tm.Modifiers & Modifiers.PUBLIC) == 0 || !tm.IsCLSCompliant ())
496                                                 continue;
497
498                                         List<TypeSpec> found;
499                                         if (!locase_types.TryGetValue (tm.Name, out found)) {
500                                                 found = new List<TypeSpec> ();
501                                                 locase_types.Add (tm.Name, found);
502                                         }
503
504                                         found.Add (tm);
505                                 }
506                         }
507
508                         foreach (var locase in locase_types.Values) {
509                                 if (locase.Count < 2)
510                                         continue;
511
512                                 bool all_same = true;
513                                 foreach (var notcompliant in locase) {
514                                         all_same = notcompliant.Name == locase[0].Name;
515                                         if (!all_same)
516                                                 break;
517                                 }
518
519                                 if (all_same)
520                                         continue;
521
522                                 TypeContainer compiled = null;
523                                 foreach (var notcompliant in locase) {
524                                         if (!notcompliant.MemberDefinition.IsImported) {
525                                                 if (compiled != null)
526                                                         compiled.Compiler.Report.SymbolRelatedToPreviousError (compiled);
527
528                                                 compiled = notcompliant.MemberDefinition as TypeContainer;
529                                         } else {
530                                                 compiled.Compiler.Report.SymbolRelatedToPreviousError (notcompliant);
531                                         }
532                                 }
533
534                                 compiled.Compiler.Report.Warning (3005, 1, compiled.Location,
535                                         "Identifier `{0}' differing only in case is not CLS-compliant", compiled.GetSignatureForError ());
536                         }
537                 }
538         }
539
540         //
541         // Namespace container as created by the parser
542         //
543         public class NamespaceEntry : IMemberContext {
544
545                 public class UsingEntry {
546                         readonly MemberName name;
547                         Namespace resolved;
548                         
549                         public UsingEntry (MemberName name)
550                         {
551                                 this.name = name;
552                         }
553
554                         public string GetSignatureForError ()
555                         {
556                                 return name.GetSignatureForError ();
557                         }
558
559                         public Location Location {
560                                 get { return name.Location; }
561                         }
562
563                         public MemberName MemberName {
564                                 get { return name; }
565                         }
566                         
567                         public string Name {
568                                 get { return GetSignatureForError (); }
569                         }
570
571                         public Namespace Resolve (IMemberContext rc)
572                         {
573                                 if (resolved != null)
574                                         return resolved;
575
576                                 FullNamedExpression fne = name.GetTypeExpression ().ResolveAsTypeStep (rc, false);
577                                 if (fne == null)
578                                         return null;
579
580                                 resolved = fne as Namespace;
581                                 if (resolved == null) {
582                                         rc.Module.Compiler.Report.SymbolRelatedToPreviousError (fne.Type);
583                                         rc.Module.Compiler.Report.Error (138, Location,
584                                                 "`{0}' is a type not a namespace. A using namespace directive can only be applied to namespaces",
585                                                 GetSignatureForError ());
586                                 }
587                                 return resolved;
588                         }
589
590                         public override string ToString ()
591                         {
592                                 return Name;
593                         }
594                 }
595
596                 public class UsingAliasEntry {
597                         public readonly string Alias;
598                         public Location Location;
599
600                         public UsingAliasEntry (string alias, Location loc)
601                         {
602                                 this.Alias = alias;
603                                 this.Location = loc;
604                         }
605
606                         public virtual FullNamedExpression Resolve (IMemberContext rc, bool local)
607                         {
608                                 FullNamedExpression fne = rc.Module.GetRootNamespace (Alias);
609                                 if (fne == null) {
610                                         rc.Module.Compiler.Report.Error (430, Location,
611                                                 "The extern alias `{0}' was not specified in -reference option",
612                                                 Alias);
613                                 }
614
615                                 return fne;
616                         }
617
618                         public override string ToString ()
619                         {
620                                 return Alias;
621                         }
622                         
623                 }
624
625                 class LocalUsingAliasEntry : UsingAliasEntry {
626                         FullNamedExpression resolved;
627                         MemberName value;
628
629                         public LocalUsingAliasEntry (string alias, MemberName name, Location loc)
630                                 : base (alias, loc)
631                         {
632                                 this.value = name;
633                         }
634
635                         public override FullNamedExpression Resolve (IMemberContext rc, bool local)
636                         {
637                                 if (resolved != null || value == null)
638                                         return resolved;
639
640                                 if (local)
641                                         return null;
642
643                                 resolved = value.GetTypeExpression ().ResolveAsTypeStep (rc, false);
644                                 if (resolved == null) {
645                                         value = null;
646                                         return null;
647                                 }
648
649                                 if (resolved is TypeExpr)
650                                         resolved = resolved.ResolveAsTypeTerminal (rc, false);
651
652                                 return resolved;
653                         }
654
655                         public override string ToString ()
656                         {
657                                 return String.Format ("{0} = {1}", Alias, value.GetSignatureForError ());
658                         }
659                 }
660
661                 Namespace ns;
662                 NamespaceEntry parent, implicit_parent;
663                 CompilationUnit file;
664                 int symfile_id;
665
666                 // Namespace using import block
667                 List<UsingAliasEntry> using_aliases;
668                 List<UsingEntry> using_clauses;
669                 public bool DeclarationFound;
670                 // End
671
672                 public readonly bool IsImplicit;
673                 public readonly TypeContainer SlaveDeclSpace;
674                 static readonly Namespace [] empty_namespaces = new Namespace [0];
675                 Namespace [] namespace_using_table;
676                 ModuleContainer ctx;
677
678                 static List<NamespaceEntry> entries = new List<NamespaceEntry> ();
679
680                 public static void Reset ()
681                 {
682                         entries = new List<NamespaceEntry> ();
683                 }
684
685                 public NamespaceEntry (ModuleContainer ctx, NamespaceEntry parent, CompilationUnit file, string name)
686                 {
687                         this.ctx = ctx;
688                         this.parent = parent;
689                         this.file = file;
690                         entries.Add (this);
691
692                         if (parent != null)
693                                 ns = parent.NS.GetNamespace (name, true);
694                         else if (name != null)
695                                 ns = ctx.GlobalRootNamespace.GetNamespace (name, true);
696                         else
697                                 ns = ctx.GlobalRootNamespace;
698
699                         SlaveDeclSpace = new RootDeclSpace (ctx, this);
700                 }
701
702                 private NamespaceEntry (ModuleContainer ctx, NamespaceEntry parent, CompilationUnit file, Namespace ns, bool slave)
703                 {
704                         this.ctx = ctx;
705                         this.parent = parent;
706                         this.file = file;
707                         this.IsImplicit = true;
708                         this.ns = ns;
709                         this.SlaveDeclSpace = slave ? new RootDeclSpace (ctx, this) : null;
710                 }
711
712                 public List<UsingEntry> Usings {
713                         get {
714                                 return using_clauses;
715                         }
716                 }
717
718                 //
719                 // Extracts the using alises and using clauses into a couple of
720                 // arrays that might already have the same information;  Used by the
721                 // C# Eval mode.
722                 //
723                 public void Extract (List<UsingAliasEntry> out_using_aliases, List<UsingEntry> out_using_clauses)
724                 {
725                         if (using_aliases != null){
726                                 foreach (UsingAliasEntry uae in using_aliases){
727                                         bool replaced = false;
728                                         
729                                         for (int i = 0; i < out_using_aliases.Count; i++){
730                                                 UsingAliasEntry out_uea = (UsingAliasEntry) out_using_aliases [i];
731                                                 
732                                                 if (out_uea.Alias == uae.Alias){
733                                                         out_using_aliases [i] = uae;
734                                                         replaced = true;
735                                                         break;
736                                                 }
737                                         }
738                                         if (!replaced)
739                                                 out_using_aliases.Add (uae);
740                                 }
741                         }
742
743                         if (using_clauses != null){
744                                 foreach (UsingEntry ue in using_clauses){
745                                         bool found = false;
746                                         
747                                         foreach (UsingEntry out_ue in out_using_clauses)
748                                                 if (out_ue.Name == ue.Name){
749                                                         found = true;
750                                                         break;
751                                                 }
752                                         if (!found)
753                                                 out_using_clauses.Add (ue);
754                                 }
755                         }
756                 }
757                 
758                 //
759                 // According to section 16.3.1 (using-alias-directive), the namespace-or-type-name is
760                 // resolved as if the immediately containing namespace body has no using-directives.
761                 //
762                 // Section 16.3.2 says that the same rule is applied when resolving the namespace-name
763                 // in the using-namespace-directive.
764                 //
765                 // To implement these rules, the expressions in the using directives are resolved using 
766                 // the "doppelganger" (ghostly bodiless duplicate).
767                 //
768                 NamespaceEntry doppelganger;
769                 NamespaceEntry Doppelganger {
770                         get {
771                                 if (!IsImplicit && doppelganger == null) {
772                                         doppelganger = new NamespaceEntry (ctx, ImplicitParent, file, ns, true);
773                                         doppelganger.using_aliases = using_aliases;
774                                 }
775                                 return doppelganger;
776                         }
777                 }
778
779                 public Namespace NS {
780                         get { return ns; }
781                 }
782
783                 public NamespaceEntry Parent {
784                         get { return parent; }
785                 }
786
787                 public NamespaceEntry ImplicitParent {
788                         get {
789                                 if (parent == null)
790                                         return null;
791                                 if (implicit_parent == null) {
792                                         implicit_parent = (parent.NS == ns.Parent)
793                                                 ? parent
794                                                 : new NamespaceEntry (ctx, parent, file, ns.Parent, false);
795                                 }
796                                 return implicit_parent;
797                         }
798                 }
799
800                 /// <summary>
801                 ///   Records a new namespace for resolving name references
802                 /// </summary>
803                 public void AddUsing (MemberName name, Location loc)
804                 {
805                         if (DeclarationFound){
806                                 Compiler.Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
807                         }
808
809                         if (using_clauses == null) {
810                                 using_clauses = new List<UsingEntry> ();
811                         } else {
812                                 foreach (UsingEntry old_entry in using_clauses) {
813                                         if (name.Equals (old_entry.MemberName)) {
814                                                 Compiler.Report.SymbolRelatedToPreviousError (old_entry.Location, old_entry.GetSignatureForError ());
815                                                 Compiler.Report.Warning (105, 3, loc, "The using directive for `{0}' appeared previously in this namespace", name.GetSignatureForError ());
816                                                 return;
817                                         }
818                                 }
819                         }
820
821                         using_clauses.Add (new UsingEntry (name));
822                 }
823
824                 public void AddUsingAlias (string alias, MemberName name, Location loc)
825                 {
826                         // TODO: This is parser bussines
827                         if (DeclarationFound){
828                                 Compiler.Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
829                         }
830
831                         AddUsingAlias (new LocalUsingAliasEntry (alias, name, loc));
832                 }
833
834                 public void AddUsingExternalAlias (string alias, Location loc, Report Report)
835                 {
836                         // TODO: Do this in parser
837                         bool not_first = using_clauses != null || DeclarationFound;
838                         if (using_aliases != null && !not_first) {
839                                 foreach (UsingAliasEntry uae in using_aliases) {
840                                         if (uae is LocalUsingAliasEntry) {
841                                                 not_first = true;
842                                                 break;
843                                         }
844                                 }
845                         }
846
847                         if (not_first)
848                                 Report.Error (439, loc, "An extern alias declaration must precede all other elements");
849
850                         if (alias == "global") {
851                                 Error_GlobalNamespaceRedefined (loc, Report);
852                                 return;
853                         }
854
855                         AddUsingAlias (new UsingAliasEntry (alias, loc));
856                 }
857
858                 void AddUsingAlias (UsingAliasEntry uae)
859                 {
860                         if (using_aliases == null) {
861                                 using_aliases = new List<UsingAliasEntry> ();
862                         } else {
863                                 foreach (UsingAliasEntry entry in using_aliases) {
864                                         if (uae.Alias == entry.Alias) {
865                                                 Compiler.Report.SymbolRelatedToPreviousError (uae.Location, uae.Alias);
866                                                 Compiler.Report.Error (1537, entry.Location, "The using alias `{0}' appeared previously in this namespace",
867                                                         entry.Alias);
868                                                 return;
869                                         }
870                                 }
871                         }
872
873                         using_aliases.Add (uae);
874                 }
875
876                 ///
877                 /// Does extension methods look up to find a method which matches name and extensionType.
878                 /// Search starts from this namespace and continues hierarchically up to top level.
879                 ///
880                 public IList<MethodSpec> LookupExtensionMethod (TypeSpec extensionType, string name, int arity, ref NamespaceEntry scope)
881                 {
882                         List<MethodSpec> candidates = null;
883                         foreach (Namespace n in GetUsingTable ()) {
884                                 var a = n.LookupExtensionMethod (extensionType, RootContext.ToplevelTypes, name, arity);
885                                 if (a == null)
886                                         continue;
887
888                                 if (candidates == null)
889                                         candidates = a;
890                                 else
891                                         candidates.AddRange (a);
892                         }
893
894                         scope = parent;
895                         if (candidates != null)
896                                 return candidates;
897
898                         if (parent == null)
899                                 return null;
900
901                         //
902                         // Inspect parent namespaces in namespace expression
903                         //
904                         Namespace parent_ns = ns.Parent;
905                         do {
906                                 candidates = parent_ns.LookupExtensionMethod (extensionType, RootContext.ToplevelTypes, name, arity);
907                                 if (candidates != null)
908                                         return candidates;
909
910                                 parent_ns = parent_ns.Parent;
911                         } while (parent_ns != null);
912
913                         //
914                         // Continue in parent scope
915                         //
916                         return parent.LookupExtensionMethod (extensionType, name, arity, ref scope);
917                 }
918
919                 public FullNamedExpression LookupNamespaceOrType (string name, int arity, Location loc, bool ignore_cs0104)
920                 {
921                         // Precondition: Only simple names (no dots) will be looked up with this function.
922                         FullNamedExpression resolved = null;
923                         for (NamespaceEntry curr_ns = this; curr_ns != null; curr_ns = curr_ns.ImplicitParent) {
924                                 if ((resolved = curr_ns.Lookup (name, arity, loc, ignore_cs0104)) != null)
925                                         break;
926                         }
927
928                         return resolved;
929                 }
930
931                 public IList<string> CompletionGetTypesStartingWith (string prefix)
932                 {
933                         IEnumerable<string> all = Enumerable.Empty<string> ();
934                         
935                         for (NamespaceEntry curr_ns = this; curr_ns != null; curr_ns = curr_ns.ImplicitParent){
936                                 foreach (Namespace using_ns in GetUsingTable ()){
937                                         if (prefix.StartsWith (using_ns.Name)){
938                                                 int ld = prefix.LastIndexOf ('.');
939                                                 if (ld != -1){
940                                                         string rest = prefix.Substring (ld+1);
941
942                                                         all = all.Concat (using_ns.CompletionGetTypesStartingWith (rest));
943                                                 }
944                                         }
945                                         all = all.Concat (using_ns.CompletionGetTypesStartingWith (prefix));
946                                 }
947                         }
948
949                         return all.Distinct ().ToList ();
950                 }
951                 
952                 // Looks-up a alias named @name in this and surrounding namespace declarations
953                 public FullNamedExpression LookupNamespaceAlias (string name)
954                 {
955                         for (NamespaceEntry n = this; n != null; n = n.ImplicitParent) {
956                                 if (n.using_aliases == null)
957                                         continue;
958
959                                 foreach (UsingAliasEntry ue in n.using_aliases) {
960                                         if (ue.Alias == name)
961                                                 return ue.Resolve (Doppelganger ?? this, Doppelganger == null);
962                                 }
963                         }
964
965                         return null;
966                 }
967
968                 private FullNamedExpression Lookup (string name, int arity, Location loc, bool ignore_cs0104)
969                 {
970                         //
971                         // Check whether it's in the namespace.
972                         //
973                         FullNamedExpression fne = ns.Lookup (this, name, arity, loc);
974
975                         //
976                         // Check aliases. 
977                         //
978                         if (using_aliases != null && arity == 0) {
979                                 foreach (UsingAliasEntry ue in using_aliases) {
980                                         if (ue.Alias == name) {
981                                                 if (fne != null) {
982                                                         if (Doppelganger != null) {
983                                                                 // TODO: Namespace has broken location
984                                                                 //Report.SymbolRelatedToPreviousError (fne.Location, null);
985                                                                 Compiler.Report.SymbolRelatedToPreviousError (ue.Location, null);
986                                                                 Compiler.Report.Error (576, loc,
987                                                                         "Namespace `{0}' contains a definition with same name as alias `{1}'",
988                                                                         GetSignatureForError (), name);
989                                                         } else {
990                                                                 return fne;
991                                                         }
992                                                 }
993
994                                                 return ue.Resolve (Doppelganger ?? this, Doppelganger == null);
995                                         }
996                                 }
997                         }
998
999                         if (fne != null) {
1000                                 if (!((fne.Type.Modifiers & Modifiers.INTERNAL) != 0 && !fne.Type.MemberDefinition.IsInternalAsPublic (RootContext.ToplevelTypes.DeclaringAssembly)))
1001                                         return fne;
1002                         }
1003
1004                         if (IsImplicit)
1005                                 return null;
1006
1007                         //
1008                         // Check using entries.
1009                         //
1010                         FullNamedExpression match = null;
1011                         foreach (Namespace using_ns in GetUsingTable ()) {
1012                                 // A using directive imports only types contained in the namespace, it
1013                                 // does not import any nested namespaces
1014                                 fne = using_ns.LookupType (this, name, arity, false, loc);
1015                                 if (fne == null)
1016                                         continue;
1017
1018                                 if (match == null) {
1019                                         match = fne;
1020                                         continue;
1021                                 }
1022
1023                                 // Prefer types over namespaces
1024                                 var texpr_fne = fne as TypeExpr;
1025                                 var texpr_match = match as TypeExpr;
1026                                 if (texpr_fne != null && texpr_match == null) {
1027                                         match = fne;
1028                                         continue;
1029                                 } else if (texpr_fne == null) {
1030                                         continue;
1031                                 }
1032
1033                                 if (ignore_cs0104)
1034                                         return match;
1035
1036                                 // It can be top level accessibility only
1037                                 var better = Namespace.IsImportedTypeOverride (texpr_match.Type, texpr_fne.Type);
1038                                 if (better == null) {
1039                                         Compiler.Report.SymbolRelatedToPreviousError (texpr_match.Type);
1040                                         Compiler.Report.SymbolRelatedToPreviousError (texpr_fne.Type);
1041                                         Compiler.Report.Error (104, loc, "`{0}' is an ambiguous reference between `{1}' and `{2}'",
1042                                                 name, texpr_match.GetSignatureForError (), texpr_fne.GetSignatureForError ());
1043                                         return match;
1044                                 }
1045
1046                                 if (better == texpr_fne.Type)
1047                                         match = texpr_fne;
1048                         }
1049
1050                         return match;
1051                 }
1052
1053                 Namespace [] GetUsingTable ()
1054                 {
1055                         if (namespace_using_table != null)
1056                                 return namespace_using_table;
1057
1058                         if (using_clauses == null) {
1059                                 namespace_using_table = empty_namespaces;
1060                                 return namespace_using_table;
1061                         }
1062
1063                         var list = new List<Namespace> (using_clauses.Count);
1064
1065                         foreach (UsingEntry ue in using_clauses) {
1066                                 Namespace using_ns = ue.Resolve (Doppelganger);
1067                                 if (using_ns == null)
1068                                         continue;
1069
1070                                 list.Add (using_ns);
1071                         }
1072
1073                         namespace_using_table = list.ToArray ();
1074                         return namespace_using_table;
1075                 }
1076
1077                 static readonly string [] empty_using_list = new string [0];
1078
1079                 public int SymbolFileID {
1080                         get {
1081                                 if (symfile_id == 0 && file.SourceFileEntry != null) {
1082                                         int parent_id = parent == null ? 0 : parent.SymbolFileID;
1083
1084                                         string [] using_list = empty_using_list;
1085                                         if (using_clauses != null) {
1086                                                 using_list = new string [using_clauses.Count];
1087                                                 for (int i = 0; i < using_clauses.Count; i++)
1088                                                         using_list [i] = ((UsingEntry) using_clauses [i]).MemberName.GetName ();
1089                                         }
1090
1091                                         symfile_id = SymbolWriter.DefineNamespace (ns.Name, file.CompileUnitEntry, using_list, parent_id);
1092                                 }
1093                                 return symfile_id;
1094                         }
1095                 }
1096
1097                 static void MsgtryRef (string s)
1098                 {
1099                         Console.WriteLine ("    Try using -r:" + s);
1100                 }
1101
1102                 static void MsgtryPkg (string s)
1103                 {
1104                         Console.WriteLine ("    Try using -pkg:" + s);
1105                 }
1106
1107                 public static void Error_GlobalNamespaceRedefined (Location loc, Report Report)
1108                 {
1109                         Report.Error (1681, loc, "The global extern alias cannot be redefined");
1110                 }
1111
1112                 public static void Error_NamespaceNotFound (Location loc, string name, Report Report)
1113                 {
1114                         Report.Error (246, loc, "The type or namespace name `{0}' could not be found. Are you missing a using directive or an assembly reference?",
1115                                 name);
1116
1117                         switch (name) {
1118                         case "Gtk": case "GtkSharp":
1119                                 MsgtryPkg ("gtk-sharp");
1120                                 break;
1121
1122                         case "Gdk": case "GdkSharp":
1123                                 MsgtryPkg ("gdk-sharp");
1124                                 break;
1125
1126                         case "Glade": case "GladeSharp":
1127                                 MsgtryPkg ("glade-sharp");
1128                                 break;
1129
1130                         case "System.Drawing":
1131                         case "System.Web.Services":
1132                         case "System.Web":
1133                         case "System.Data":
1134                         case "System.Windows.Forms":
1135                                 MsgtryRef (name);
1136                                 break;
1137                         }
1138                 }
1139
1140                 /// <summary>
1141                 ///   Used to validate that all the using clauses are correct
1142                 ///   after we are finished parsing all the files.  
1143                 /// </summary>
1144                 void VerifyUsing ()
1145                 {
1146                         if (using_aliases != null) {
1147                                 foreach (UsingAliasEntry ue in using_aliases)
1148                                         ue.Resolve (Doppelganger, Doppelganger == null);
1149                         }
1150
1151                         if (using_clauses != null) {
1152                                 foreach (UsingEntry ue in using_clauses)
1153                                         ue.Resolve (Doppelganger);
1154                         }
1155                 }
1156
1157                 /// <summary>
1158                 ///   Used to validate that all the using clauses are correct
1159                 ///   after we are finished parsing all the files.  
1160                 /// </summary>
1161                 static public void VerifyAllUsing ()
1162                 {
1163                         foreach (NamespaceEntry entry in entries)
1164                                 entry.VerifyUsing ();
1165                 }
1166
1167                 public string GetSignatureForError ()
1168                 {
1169                         return ns.GetSignatureForError ();
1170                 }
1171
1172                 public override string ToString ()
1173                 {
1174                         return ns.ToString ();
1175                 }
1176
1177                 #region IMemberContext Members
1178
1179                 public CompilerContext Compiler {
1180                         get { return ctx.Compiler; }
1181                 }
1182
1183                 public TypeSpec CurrentType {
1184                         get { return SlaveDeclSpace.CurrentType; }
1185                 }
1186
1187                 public MemberCore CurrentMemberDefinition {
1188                         get { return SlaveDeclSpace.CurrentMemberDefinition; }
1189                 }
1190
1191                 public TypeParameter[] CurrentTypeParameters {
1192                         get { return SlaveDeclSpace.CurrentTypeParameters; }
1193                 }
1194
1195                 // FIXME: It's false for expression types
1196                 public bool HasUnresolvedConstraints {
1197                         get { return true; }
1198                 }
1199
1200                 public bool IsObsolete {
1201                         get { return SlaveDeclSpace.IsObsolete; }
1202                 }
1203
1204                 public bool IsUnsafe {
1205                         get { return SlaveDeclSpace.IsUnsafe; }
1206                 }
1207
1208                 public bool IsStatic {
1209                         get { return SlaveDeclSpace.IsStatic; }
1210                 }
1211
1212                 public ModuleContainer Module {
1213                         get { return ctx; }
1214                 }
1215
1216                 #endregion
1217         }
1218 }