Merge branch 'bugfix-main-thread-root'
[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                 }
470
471                 public void ReplaceTypeWithPredefined (TypeSpec ts, BuildinTypeSpec pts)
472                 {
473                         var found = types [ts.Name];
474                         cached_types.Remove (ts.Name);
475                         if (found.Count == 1) {
476                                 types[ts.Name][0] = pts;
477                         } else {
478                                 throw new NotImplementedException ();
479                         }
480                 }
481
482                 public void VerifyClsCompliance ()
483                 {
484                         if (types == null || cls_checked)
485                                 return;
486
487                         cls_checked = true;
488
489                         // TODO: This is quite ugly way to check for CLS compliance at namespace level
490
491                         var locase_types = new Dictionary<string, List<TypeSpec>> (StringComparer.OrdinalIgnoreCase);
492                         foreach (var tgroup in types.Values) {
493                                 foreach (var tm in tgroup) {
494                                         if ((tm.Modifiers & Modifiers.PUBLIC) == 0 || !tm.IsCLSCompliant ())
495                                                 continue;
496
497                                         List<TypeSpec> found;
498                                         if (!locase_types.TryGetValue (tm.Name, out found)) {
499                                                 found = new List<TypeSpec> ();
500                                                 locase_types.Add (tm.Name, found);
501                                         }
502
503                                         found.Add (tm);
504                                 }
505                         }
506
507                         foreach (var locase in locase_types.Values) {
508                                 if (locase.Count < 2)
509                                         continue;
510
511                                 bool all_same = true;
512                                 foreach (var notcompliant in locase) {
513                                         all_same = notcompliant.Name == locase[0].Name;
514                                         if (!all_same)
515                                                 break;
516                                 }
517
518                                 if (all_same)
519                                         continue;
520
521                                 TypeContainer compiled = null;
522                                 foreach (var notcompliant in locase) {
523                                         if (!notcompliant.MemberDefinition.IsImported) {
524                                                 if (compiled != null)
525                                                         compiled.Compiler.Report.SymbolRelatedToPreviousError (compiled);
526
527                                                 compiled = notcompliant.MemberDefinition as TypeContainer;
528                                         } else {
529                                                 compiled.Compiler.Report.SymbolRelatedToPreviousError (notcompliant);
530                                         }
531                                 }
532
533                                 compiled.Compiler.Report.Warning (3005, 1, compiled.Location,
534                                         "Identifier `{0}' differing only in case is not CLS-compliant", compiled.GetSignatureForError ());
535                         }
536                 }
537         }
538
539         //
540         // Namespace container as created by the parser
541         //
542         public class NamespaceEntry : IMemberContext {
543
544                 public class UsingEntry {
545                         readonly MemberName name;
546                         Namespace resolved;
547                         
548                         public UsingEntry (MemberName name)
549                         {
550                                 this.name = name;
551                         }
552
553                         public string GetSignatureForError ()
554                         {
555                                 return name.GetSignatureForError ();
556                         }
557
558                         public Location Location {
559                                 get { return name.Location; }
560                         }
561
562                         public MemberName MemberName {
563                                 get { return name; }
564                         }
565                         
566                         public string Name {
567                                 get { return GetSignatureForError (); }
568                         }
569
570                         public Namespace Resolve (IMemberContext rc)
571                         {
572                                 if (resolved != null)
573                                         return resolved;
574
575                                 FullNamedExpression fne = name.GetTypeExpression ().ResolveAsTypeStep (rc, false);
576                                 if (fne == null)
577                                         return null;
578
579                                 resolved = fne as Namespace;
580                                 if (resolved == null) {
581                                         rc.Module.Compiler.Report.SymbolRelatedToPreviousError (fne.Type);
582                                         rc.Module.Compiler.Report.Error (138, Location,
583                                                 "`{0}' is a type not a namespace. A using namespace directive can only be applied to namespaces",
584                                                 GetSignatureForError ());
585                                 }
586                                 return resolved;
587                         }
588
589                         public override string ToString ()
590                         {
591                                 return Name;
592                         }
593                 }
594
595                 public class UsingAliasEntry {
596                         public readonly string Alias;
597                         public Location Location;
598
599                         public UsingAliasEntry (string alias, Location loc)
600                         {
601                                 this.Alias = alias;
602                                 this.Location = loc;
603                         }
604
605                         public virtual FullNamedExpression Resolve (IMemberContext rc, bool local)
606                         {
607                                 FullNamedExpression fne = rc.Module.GetRootNamespace (Alias);
608                                 if (fne == null) {
609                                         rc.Module.Compiler.Report.Error (430, Location,
610                                                 "The extern alias `{0}' was not specified in -reference option",
611                                                 Alias);
612                                 }
613
614                                 return fne;
615                         }
616
617                         public override string ToString ()
618                         {
619                                 return Alias;
620                         }
621                         
622                 }
623
624                 class LocalUsingAliasEntry : UsingAliasEntry {
625                         FullNamedExpression resolved;
626                         MemberName value;
627
628                         public LocalUsingAliasEntry (string alias, MemberName name, Location loc)
629                                 : base (alias, loc)
630                         {
631                                 this.value = name;
632                         }
633
634                         public override FullNamedExpression Resolve (IMemberContext rc, bool local)
635                         {
636                                 if (resolved != null || value == null)
637                                         return resolved;
638
639                                 if (local)
640                                         return null;
641
642                                 resolved = value.GetTypeExpression ().ResolveAsTypeStep (rc, false);
643                                 if (resolved == null) {
644                                         value = null;
645                                         return null;
646                                 }
647
648                                 if (resolved is TypeExpr)
649                                         resolved = resolved.ResolveAsTypeTerminal (rc, false);
650
651                                 return resolved;
652                         }
653
654                         public override string ToString ()
655                         {
656                                 return String.Format ("{0} = {1}", Alias, value.GetSignatureForError ());
657                         }
658                 }
659
660                 Namespace ns;
661                 NamespaceEntry parent, implicit_parent;
662                 CompilationUnit file;
663                 int symfile_id;
664
665                 // Namespace using import block
666                 List<UsingAliasEntry> using_aliases;
667                 List<UsingEntry> using_clauses;
668                 public bool DeclarationFound;
669                 // End
670
671                 public readonly bool IsImplicit;
672                 public readonly DeclSpace SlaveDeclSpace;
673                 static readonly Namespace [] empty_namespaces = new Namespace [0];
674                 Namespace [] namespace_using_table;
675                 ModuleContainer ctx;
676
677                 static List<NamespaceEntry> entries = new List<NamespaceEntry> ();
678
679                 public static void Reset ()
680                 {
681                         entries = new List<NamespaceEntry> ();
682                 }
683
684                 public NamespaceEntry (ModuleContainer ctx, NamespaceEntry parent, CompilationUnit file, string name)
685                 {
686                         this.ctx = ctx;
687                         this.parent = parent;
688                         this.file = file;
689                         entries.Add (this);
690
691                         if (parent != null)
692                                 ns = parent.NS.GetNamespace (name, true);
693                         else if (name != null)
694                                 ns = ctx.GlobalRootNamespace.GetNamespace (name, true);
695                         else
696                                 ns = ctx.GlobalRootNamespace;
697
698                         SlaveDeclSpace = new RootDeclSpace (this);
699                 }
700
701                 private NamespaceEntry (ModuleContainer ctx, NamespaceEntry parent, CompilationUnit file, Namespace ns, bool slave)
702                 {
703                         this.ctx = ctx;
704                         this.parent = parent;
705                         this.file = file;
706                         this.IsImplicit = true;
707                         this.ns = ns;
708                         this.SlaveDeclSpace = slave ? new RootDeclSpace (this) : null;
709                 }
710
711                 public List<UsingEntry> Usings {
712                         get {
713                                 return using_clauses;
714                         }
715                 }
716
717                 //
718                 // Extracts the using alises and using clauses into a couple of
719                 // arrays that might already have the same information;  Used by the
720                 // C# Eval mode.
721                 //
722                 public void Extract (List<UsingAliasEntry> out_using_aliases, List<UsingEntry> out_using_clauses)
723                 {
724                         if (using_aliases != null){
725                                 foreach (UsingAliasEntry uae in using_aliases){
726                                         bool replaced = false;
727                                         
728                                         for (int i = 0; i < out_using_aliases.Count; i++){
729                                                 UsingAliasEntry out_uea = (UsingAliasEntry) out_using_aliases [i];
730                                                 
731                                                 if (out_uea.Alias == uae.Alias){
732                                                         out_using_aliases [i] = uae;
733                                                         replaced = true;
734                                                         break;
735                                                 }
736                                         }
737                                         if (!replaced)
738                                                 out_using_aliases.Add (uae);
739                                 }
740                         }
741
742                         if (using_clauses != null){
743                                 foreach (UsingEntry ue in using_clauses){
744                                         bool found = false;
745                                         
746                                         foreach (UsingEntry out_ue in out_using_clauses)
747                                                 if (out_ue.Name == ue.Name){
748                                                         found = true;
749                                                         break;
750                                                 }
751                                         if (!found)
752                                                 out_using_clauses.Add (ue);
753                                 }
754                         }
755                 }
756                 
757                 //
758                 // According to section 16.3.1 (using-alias-directive), the namespace-or-type-name is
759                 // resolved as if the immediately containing namespace body has no using-directives.
760                 //
761                 // Section 16.3.2 says that the same rule is applied when resolving the namespace-name
762                 // in the using-namespace-directive.
763                 //
764                 // To implement these rules, the expressions in the using directives are resolved using 
765                 // the "doppelganger" (ghostly bodiless duplicate).
766                 //
767                 NamespaceEntry doppelganger;
768                 NamespaceEntry Doppelganger {
769                         get {
770                                 if (!IsImplicit && doppelganger == null) {
771                                         doppelganger = new NamespaceEntry (ctx, ImplicitParent, file, ns, true);
772                                         doppelganger.using_aliases = using_aliases;
773                                 }
774                                 return doppelganger;
775                         }
776                 }
777
778                 public Namespace NS {
779                         get { return ns; }
780                 }
781
782                 public NamespaceEntry Parent {
783                         get { return parent; }
784                 }
785
786                 public NamespaceEntry ImplicitParent {
787                         get {
788                                 if (parent == null)
789                                         return null;
790                                 if (implicit_parent == null) {
791                                         implicit_parent = (parent.NS == ns.Parent)
792                                                 ? parent
793                                                 : new NamespaceEntry (ctx, parent, file, ns.Parent, false);
794                                 }
795                                 return implicit_parent;
796                         }
797                 }
798
799                 /// <summary>
800                 ///   Records a new namespace for resolving name references
801                 /// </summary>
802                 public void AddUsing (MemberName name, Location loc)
803                 {
804                         if (DeclarationFound){
805                                 Compiler.Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
806                         }
807
808                         if (using_clauses == null) {
809                                 using_clauses = new List<UsingEntry> ();
810                         } else {
811                                 foreach (UsingEntry old_entry in using_clauses) {
812                                         if (name.Equals (old_entry.MemberName)) {
813                                                 Compiler.Report.SymbolRelatedToPreviousError (old_entry.Location, old_entry.GetSignatureForError ());
814                                                 Compiler.Report.Warning (105, 3, loc, "The using directive for `{0}' appeared previously in this namespace", name.GetSignatureForError ());
815                                                 return;
816                                         }
817                                 }
818                         }
819
820                         using_clauses.Add (new UsingEntry (name));
821                 }
822
823                 public void AddUsingAlias (string alias, MemberName name, Location loc)
824                 {
825                         // TODO: This is parser bussines
826                         if (DeclarationFound){
827                                 Compiler.Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
828                         }
829
830                         if (RootContext.Version != LanguageVersion.ISO_1 && alias == "global")
831                                 Compiler.Report.Warning (440, 2, loc, "An alias named `global' will not be used when resolving 'global::';" +
832                                         " the global namespace will be used instead");
833
834                         AddUsingAlias (new LocalUsingAliasEntry (alias, name, loc));
835                 }
836
837                 public void AddUsingExternalAlias (string alias, Location loc, Report Report)
838                 {
839                         // TODO: Do this in parser
840                         bool not_first = using_clauses != null || DeclarationFound;
841                         if (using_aliases != null && !not_first) {
842                                 foreach (UsingAliasEntry uae in using_aliases) {
843                                         if (uae is LocalUsingAliasEntry) {
844                                                 not_first = true;
845                                                 break;
846                                         }
847                                 }
848                         }
849
850                         if (not_first)
851                                 Report.Error (439, loc, "An extern alias declaration must precede all other elements");
852
853                         if (alias == "global") {
854                                 Error_GlobalNamespaceRedefined (loc, Report);
855                                 return;
856                         }
857
858                         AddUsingAlias (new UsingAliasEntry (alias, loc));
859                 }
860
861                 void AddUsingAlias (UsingAliasEntry uae)
862                 {
863                         if (using_aliases == null) {
864                                 using_aliases = new List<UsingAliasEntry> ();
865                         } else {
866                                 foreach (UsingAliasEntry entry in using_aliases) {
867                                         if (uae.Alias == entry.Alias) {
868                                                 Compiler.Report.SymbolRelatedToPreviousError (uae.Location, uae.Alias);
869                                                 Compiler.Report.Error (1537, entry.Location, "The using alias `{0}' appeared previously in this namespace",
870                                                         entry.Alias);
871                                                 return;
872                                         }
873                                 }
874                         }
875
876                         using_aliases.Add (uae);
877                 }
878
879                 ///
880                 /// Does extension methods look up to find a method which matches name and extensionType.
881                 /// Search starts from this namespace and continues hierarchically up to top level.
882                 ///
883                 public IList<MethodSpec> LookupExtensionMethod (TypeSpec extensionType, string name, int arity, ref NamespaceEntry scope)
884                 {
885                         List<MethodSpec> candidates = null;
886                         foreach (Namespace n in GetUsingTable ()) {
887                                 var a = n.LookupExtensionMethod (extensionType, RootContext.ToplevelTypes, name, arity);
888                                 if (a == null)
889                                         continue;
890
891                                 if (candidates == null)
892                                         candidates = a;
893                                 else
894                                         candidates.AddRange (a);
895                         }
896
897                         scope = parent;
898                         if (candidates != null)
899                                 return candidates;
900
901                         if (parent == null)
902                                 return null;
903
904                         //
905                         // Inspect parent namespaces in namespace expression
906                         //
907                         Namespace parent_ns = ns.Parent;
908                         do {
909                                 candidates = parent_ns.LookupExtensionMethod (extensionType, RootContext.ToplevelTypes, name, arity);
910                                 if (candidates != null)
911                                         return candidates;
912
913                                 parent_ns = parent_ns.Parent;
914                         } while (parent_ns != null);
915
916                         //
917                         // Continue in parent scope
918                         //
919                         return parent.LookupExtensionMethod (extensionType, name, arity, ref scope);
920                 }
921
922                 public FullNamedExpression LookupNamespaceOrType (string name, int arity, Location loc, bool ignore_cs0104)
923                 {
924                         // Precondition: Only simple names (no dots) will be looked up with this function.
925                         FullNamedExpression resolved = null;
926                         for (NamespaceEntry curr_ns = this; curr_ns != null; curr_ns = curr_ns.ImplicitParent) {
927                                 if ((resolved = curr_ns.Lookup (name, arity, loc, ignore_cs0104)) != null)
928                                         break;
929                         }
930
931                         return resolved;
932                 }
933
934                 public IList<string> CompletionGetTypesStartingWith (string prefix)
935                 {
936                         IEnumerable<string> all = Enumerable.Empty<string> ();
937                         
938                         for (NamespaceEntry curr_ns = this; curr_ns != null; curr_ns = curr_ns.ImplicitParent){
939                                 foreach (Namespace using_ns in GetUsingTable ()){
940                                         if (prefix.StartsWith (using_ns.Name)){
941                                                 int ld = prefix.LastIndexOf ('.');
942                                                 if (ld != -1){
943                                                         string rest = prefix.Substring (ld+1);
944
945                                                         all = all.Concat (using_ns.CompletionGetTypesStartingWith (rest));
946                                                 }
947                                         }
948                                         all = all.Concat (using_ns.CompletionGetTypesStartingWith (prefix));
949                                 }
950                         }
951
952                         return all.Distinct ().ToList ();
953                 }
954                 
955                 // Looks-up a alias named @name in this and surrounding namespace declarations
956                 public FullNamedExpression LookupNamespaceAlias (string name)
957                 {
958                         for (NamespaceEntry n = this; n != null; n = n.ImplicitParent) {
959                                 if (n.using_aliases == null)
960                                         continue;
961
962                                 foreach (UsingAliasEntry ue in n.using_aliases) {
963                                         if (ue.Alias == name)
964                                                 return ue.Resolve (Doppelganger ?? this, Doppelganger == null);
965                                 }
966                         }
967
968                         return null;
969                 }
970
971                 private FullNamedExpression Lookup (string name, int arity, Location loc, bool ignore_cs0104)
972                 {
973                         //
974                         // Check whether it's in the namespace.
975                         //
976                         FullNamedExpression fne = ns.Lookup (this, name, arity, loc);
977
978                         //
979                         // Check aliases. 
980                         //
981                         if (using_aliases != null && arity == 0) {
982                                 foreach (UsingAliasEntry ue in using_aliases) {
983                                         if (ue.Alias == name) {
984                                                 if (fne != null) {
985                                                         if (Doppelganger != null) {
986                                                                 // TODO: Namespace has broken location
987                                                                 //Report.SymbolRelatedToPreviousError (fne.Location, null);
988                                                                 Compiler.Report.SymbolRelatedToPreviousError (ue.Location, null);
989                                                                 Compiler.Report.Error (576, loc,
990                                                                         "Namespace `{0}' contains a definition with same name as alias `{1}'",
991                                                                         GetSignatureForError (), name);
992                                                         } else {
993                                                                 return fne;
994                                                         }
995                                                 }
996
997                                                 return ue.Resolve (Doppelganger ?? this, Doppelganger == null);
998                                         }
999                                 }
1000                         }
1001
1002                         if (fne != null) {
1003                                 if (!((fne.Type.Modifiers & Modifiers.INTERNAL) != 0 && !fne.Type.MemberDefinition.IsInternalAsPublic (RootContext.ToplevelTypes.DeclaringAssembly)))
1004                                         return fne;
1005                         }
1006
1007                         if (IsImplicit)
1008                                 return null;
1009
1010                         //
1011                         // Check using entries.
1012                         //
1013                         FullNamedExpression match = null;
1014                         foreach (Namespace using_ns in GetUsingTable ()) {
1015                                 // A using directive imports only types contained in the namespace, it
1016                                 // does not import any nested namespaces
1017                                 fne = using_ns.LookupType (this, name, arity, false, loc);
1018                                 if (fne == null)
1019                                         continue;
1020
1021                                 if (match == null) {
1022                                         match = fne;
1023                                         continue;
1024                                 }
1025
1026                                 // Prefer types over namespaces
1027                                 var texpr_fne = fne as TypeExpr;
1028                                 var texpr_match = match as TypeExpr;
1029                                 if (texpr_fne != null && texpr_match == null) {
1030                                         match = fne;
1031                                         continue;
1032                                 } else if (texpr_fne == null) {
1033                                         continue;
1034                                 }
1035
1036                                 if (ignore_cs0104)
1037                                         return match;
1038
1039                                 // It can be top level accessibility only
1040                                 var better = Namespace.IsImportedTypeOverride (texpr_match.Type, texpr_fne.Type);
1041                                 if (better == null) {
1042                                         Compiler.Report.SymbolRelatedToPreviousError (texpr_match.Type);
1043                                         Compiler.Report.SymbolRelatedToPreviousError (texpr_fne.Type);
1044                                         Compiler.Report.Error (104, loc, "`{0}' is an ambiguous reference between `{1}' and `{2}'",
1045                                                 name, texpr_match.GetSignatureForError (), texpr_fne.GetSignatureForError ());
1046                                         return match;
1047                                 }
1048
1049                                 if (better == texpr_fne.Type)
1050                                         match = texpr_fne;
1051                         }
1052
1053                         return match;
1054                 }
1055
1056                 Namespace [] GetUsingTable ()
1057                 {
1058                         if (namespace_using_table != null)
1059                                 return namespace_using_table;
1060
1061                         if (using_clauses == null) {
1062                                 namespace_using_table = empty_namespaces;
1063                                 return namespace_using_table;
1064                         }
1065
1066                         var list = new List<Namespace> (using_clauses.Count);
1067
1068                         foreach (UsingEntry ue in using_clauses) {
1069                                 Namespace using_ns = ue.Resolve (Doppelganger);
1070                                 if (using_ns == null)
1071                                         continue;
1072
1073                                 list.Add (using_ns);
1074                         }
1075
1076                         namespace_using_table = list.ToArray ();
1077                         return namespace_using_table;
1078                 }
1079
1080                 static readonly string [] empty_using_list = new string [0];
1081
1082                 public int SymbolFileID {
1083                         get {
1084                                 if (symfile_id == 0 && file.SourceFileEntry != null) {
1085                                         int parent_id = parent == null ? 0 : parent.SymbolFileID;
1086
1087                                         string [] using_list = empty_using_list;
1088                                         if (using_clauses != null) {
1089                                                 using_list = new string [using_clauses.Count];
1090                                                 for (int i = 0; i < using_clauses.Count; i++)
1091                                                         using_list [i] = ((UsingEntry) using_clauses [i]).MemberName.GetName ();
1092                                         }
1093
1094                                         symfile_id = SymbolWriter.DefineNamespace (ns.Name, file.CompileUnitEntry, using_list, parent_id);
1095                                 }
1096                                 return symfile_id;
1097                         }
1098                 }
1099
1100                 static void MsgtryRef (string s)
1101                 {
1102                         Console.WriteLine ("    Try using -r:" + s);
1103                 }
1104
1105                 static void MsgtryPkg (string s)
1106                 {
1107                         Console.WriteLine ("    Try using -pkg:" + s);
1108                 }
1109
1110                 public static void Error_GlobalNamespaceRedefined (Location loc, Report Report)
1111                 {
1112                         Report.Error (1681, loc, "The global extern alias cannot be redefined");
1113                 }
1114
1115                 public static void Error_NamespaceNotFound (Location loc, string name, Report Report)
1116                 {
1117                         Report.Error (246, loc, "The type or namespace name `{0}' could not be found. Are you missing a using directive or an assembly reference?",
1118                                 name);
1119
1120                         switch (name) {
1121                         case "Gtk": case "GtkSharp":
1122                                 MsgtryPkg ("gtk-sharp");
1123                                 break;
1124
1125                         case "Gdk": case "GdkSharp":
1126                                 MsgtryPkg ("gdk-sharp");
1127                                 break;
1128
1129                         case "Glade": case "GladeSharp":
1130                                 MsgtryPkg ("glade-sharp");
1131                                 break;
1132
1133                         case "System.Drawing":
1134                         case "System.Web.Services":
1135                         case "System.Web":
1136                         case "System.Data":
1137                         case "System.Windows.Forms":
1138                                 MsgtryRef (name);
1139                                 break;
1140                         }
1141                 }
1142
1143                 /// <summary>
1144                 ///   Used to validate that all the using clauses are correct
1145                 ///   after we are finished parsing all the files.  
1146                 /// </summary>
1147                 void VerifyUsing ()
1148                 {
1149                         if (using_aliases != null) {
1150                                 foreach (UsingAliasEntry ue in using_aliases)
1151                                         ue.Resolve (Doppelganger, Doppelganger == null);
1152                         }
1153
1154                         if (using_clauses != null) {
1155                                 foreach (UsingEntry ue in using_clauses)
1156                                         ue.Resolve (Doppelganger);
1157                         }
1158                 }
1159
1160                 /// <summary>
1161                 ///   Used to validate that all the using clauses are correct
1162                 ///   after we are finished parsing all the files.  
1163                 /// </summary>
1164                 static public void VerifyAllUsing ()
1165                 {
1166                         foreach (NamespaceEntry entry in entries)
1167                                 entry.VerifyUsing ();
1168                 }
1169
1170                 public string GetSignatureForError ()
1171                 {
1172                         return ns.GetSignatureForError ();
1173                 }
1174
1175                 public override string ToString ()
1176                 {
1177                         return ns.ToString ();
1178                 }
1179
1180                 #region IMemberContext Members
1181
1182                 public CompilerContext Compiler {
1183                         get { return ctx.Compiler; }
1184                 }
1185
1186                 public TypeSpec CurrentType {
1187                         get { return SlaveDeclSpace.CurrentType; }
1188                 }
1189
1190                 public MemberCore CurrentMemberDefinition {
1191                         get { return SlaveDeclSpace.CurrentMemberDefinition; }
1192                 }
1193
1194                 public TypeParameter[] CurrentTypeParameters {
1195                         get { return SlaveDeclSpace.CurrentTypeParameters; }
1196                 }
1197
1198                 // FIXME: It's false for expression types
1199                 public bool HasUnresolvedConstraints {
1200                         get { return true; }
1201                 }
1202
1203                 public bool IsObsolete {
1204                         get { return SlaveDeclSpace.IsObsolete; }
1205                 }
1206
1207                 public bool IsUnsafe {
1208                         get { return SlaveDeclSpace.IsUnsafe; }
1209                 }
1210
1211                 public bool IsStatic {
1212                         get { return SlaveDeclSpace.IsStatic; }
1213                 }
1214
1215                 public ModuleContainer Module {
1216                         get { return ctx; }
1217                 }
1218
1219                 #endregion
1220         }
1221 }