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