040363edeff411f339ee172b32f8d9ae579c5f69
[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, null);
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, bool silent, 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                                         var pts = best as PredefinedTypeSpec;
377                                         if (pts == null)
378                                                 pts = ts as PredefinedTypeSpec;
379
380                                         if (pts != null) {
381                                                 ctx.Report.SymbolRelatedToPreviousError (best);
382                                                 ctx.Report.SymbolRelatedToPreviousError (ts);
383
384                                                 // TODO: This should use different warning number but we want to be csc compatible
385                                                 ctx.Report.Warning (1685, 1, loc,
386                                                         "The predefined type `{0}.{1}' is redefined in the source code. Ignoring the local type definition",
387                                                         pts.Namespace, pts.Name);
388                                                 best = pts;
389                                                 continue;
390                                         }
391
392                                         if (best.MemberDefinition.IsImported && ts.MemberDefinition.IsImported) {
393                                                 ctx.Report.SymbolRelatedToPreviousError (best);
394                                                 ctx.Report.SymbolRelatedToPreviousError (ts);
395                                                 if (silent) {
396                                                         ctx.Report.Warning (1685, 1, loc,
397                                                                 "The predefined type `{0}' is defined in multiple assemblies. Using definition from `{1}'",
398                                                                 ts.GetSignatureForError (), best.Assembly.GetName ().Name);
399                                                 } else {
400                                                         ctx.Report.Error (433, loc, "The imported type `{0}' is defined multiple times", ts.GetSignatureForError ());
401                                                 }
402
403                                                 break;
404                                         }
405
406                                         if (best.MemberDefinition.IsImported)
407                                                 best = ts;
408
409                                         if ((best.Modifiers & Modifiers.INTERNAL) != 0 && !TypeManager.IsThisOrFriendAssembly (CodeGen.Assembly.Builder, best.MemberDefinition.Assembly))
410                                                 continue;
411
412                                         if (silent)
413                                                 continue;
414
415                                         if (ts.MemberDefinition.IsImported)
416                                                 ctx.Report.SymbolRelatedToPreviousError (ts);
417
418                                         ctx.Report.Warning (436, 2, loc,
419                                                 "The type `{0}' conflicts with the imported type of same name'. Ignoring the imported type definition",
420                                                 best.GetSignatureForError ());
421                                 }
422
423                                 //
424                                 // Lookup for the best candidate with closest arity match
425                                 //
426                                 if (arity < 0) {
427                                         if (best == null) {
428                                                 best = ts;
429                                         } else if (System.Math.Abs (ts.Arity + arity) < System.Math.Abs (best.Arity + arity)) {
430                                                 best = ts;
431                                         }
432                                 }
433                         }
434
435                         if (best == null)
436                                 return null;
437
438                         te = new TypeExpression (best, Location.Null);
439
440                         // TODO MemberCache: Cache more
441                         if (arity == 0 && !silent)
442                                 cached_types.Add (name, te);
443
444                         return te;
445                 }
446
447                 TypeSpec LookupType (string name, int arity)
448                 {
449                         if (types == null)
450                                 return null;
451
452                         IList<TypeSpec> found;
453                         if (types.TryGetValue (name, out found)) {
454                                 TypeSpec best = null;
455
456                                 foreach (var ts in found) {
457                                         if (ts.Arity == arity)
458                                                 return ts;
459
460                                         //
461                                         // Lookup for the best candidate with closest arity match
462                                         //
463                                         if (arity < 0) {
464                                                 if (best == null) {
465                                                         best = ts;
466                                                 } else if (System.Math.Abs (ts.Arity + arity) < System.Math.Abs (best.Arity + arity)) {
467                                                         best = ts;
468                                                 }
469                                         }
470                                 }
471                                 
472                                 return best;
473                         }
474
475                         return null;
476                 }
477
478                 public FullNamedExpression Lookup (CompilerContext ctx, string name, int arity, Location loc)
479                 {
480                         if (arity == 0 && namespaces.ContainsKey (name))
481                                 return namespaces [name];
482
483                         return LookupType (ctx, name, arity, false, loc);
484                 }
485
486                 //
487                 // Completes types with the given `prefix'
488                 //
489                 public IEnumerable<string> CompletionGetTypesStartingWith (string prefix)
490                 {
491                         if (types == null)
492                                 return Enumerable.Empty<string> ();
493
494                         var res = from item in types
495                                           where item.Key.StartsWith (prefix) && item.Value.Any (l => (l.Modifiers & Modifiers.PUBLIC) != 0)
496                                           select item.Key;
497
498                         if (namespaces != null)
499                                 res = res.Concat (from item in namespaces where item.Key.StartsWith (prefix) select item.Key);
500
501                         return res;
502                 }
503
504                 /// 
505                 /// Looks for extension method in this namespace
506                 /// 
507                 public List<MethodSpec> LookupExtensionMethod (TypeSpec extensionType, ClassOrStruct currentClass, string name, int arity)
508                 {
509                         if (types == null)
510                                 return null;
511
512                         List<MethodSpec> found = null;
513
514                         var invocation_type = currentClass == null ? InternalType.FakeInternalType : currentClass.CurrentType;
515
516                         // TODO: Add per namespace flag when at least 1 type has extension
517
518                         foreach (var tgroup in types.Values) {
519                                 foreach (var ts in tgroup) {
520                                         if ((ts.Modifiers & Modifiers.METHOD_EXTENSION) == 0)
521                                                 continue;
522
523                                         var res = ts.MemberCache.FindExtensionMethods (invocation_type, extensionType, name, arity);
524                                         if (res == null)
525                                                 continue;
526
527                                         if (found == null) {
528                                                 found = res;
529                                         } else {
530                                                 found.AddRange (res);
531                                         }
532                                 }
533                         }
534
535                         return found;
536                 }
537
538                 public void AddType (TypeSpec ts)
539                 {
540                         if (types == null) {
541                                 types = new Dictionary<string, IList<TypeSpec>> (64);
542                         }
543
544                         var name = ts.Name;
545                         IList<TypeSpec> existing;
546                         if (types.TryGetValue (name, out existing)) {
547                                 TypeSpec better_type;
548                                 TypeSpec found;
549                                 if (existing.Count == 1) {
550                                         found = existing[0];
551                                         if (ts.Arity == found.Arity) {
552                                                 better_type = IsImportedTypeOverride (ts, found);
553                                                 if (better_type == found)
554                                                         return;
555
556                                                 if (better_type != null) {
557                                                         existing [0] = better_type;
558                                                         return;
559                                                 }
560                                         }
561
562                                         existing = new List<TypeSpec> ();
563                                         existing.Add (found);
564                                         types[name] = existing;
565                                 } else {
566                                         for (int i = 0; i < existing.Count; ++i) {
567                                                 found = existing[i];
568                                                 if (ts.Arity != found.Arity)
569                                                         continue;
570
571                                                 better_type = IsImportedTypeOverride (ts, found);
572                                                 if (better_type == found)
573                                                         return;
574
575                                                 if (better_type != null) {
576                                                         existing.RemoveAt (i);
577                                                         --i;
578                                                         continue;
579                                                 }
580                                         }
581                                 }
582
583                                 existing.Add (ts);
584                         } else {
585                                 types.Add (name, new TypeSpec[] { ts });
586                         }
587                 }
588
589                 //
590                 // We import any types but in the situation there are same types
591                 // but one has better visibility (either public or internal with friend)
592                 // the less visible type is removed from the namespace cache
593                 //
594                 public static TypeSpec IsImportedTypeOverride (TypeSpec ts, TypeSpec found)
595                 {
596                         var ts_accessible = (ts.Modifiers & Modifiers.PUBLIC) != 0 || TypeManager.IsThisOrFriendAssembly (CodeGen.Assembly.Builder, ts.MemberDefinition.Assembly);
597                         var found_accessible = (found.Modifiers & Modifiers.PUBLIC) != 0 || TypeManager.IsThisOrFriendAssembly (CodeGen.Assembly.Builder, found.MemberDefinition.Assembly);
598
599                         if (ts_accessible && !found_accessible)
600                                 return ts;
601
602                         // found is better always better for accessible or inaccessible ts
603                         if (!ts_accessible)
604                                 return found;
605
606                         return null;
607                 }
608
609                 public void RemoveDeclSpace (string name)
610                 {
611                         types.Remove (name);
612                 }
613
614                 public void ReplaceTypeWithPredefined (TypeSpec ts, PredefinedTypeSpec pts)
615                 {
616                         var found = types [ts.Name];
617                         cached_types.Remove (ts.Name);
618                         if (found.Count == 1) {
619                                 types[ts.Name][0] = pts;
620                         } else {
621                                 throw new NotImplementedException ();
622                         }
623                 }
624
625                 public void VerifyClsCompliance ()
626                 {
627                         if (types == null || cls_checked)
628                                 return;
629
630                         cls_checked = true;
631
632                         // TODO: This is quite ugly way to check for CLS compliance at namespace level
633
634                         var locase_types = new Dictionary<string, List<TypeSpec>> (StringComparer.OrdinalIgnoreCase);
635                         foreach (var tgroup in types.Values) {
636                                 foreach (var tm in tgroup) {
637                                         if ((tm.Modifiers & Modifiers.PUBLIC) == 0 || !tm.IsCLSCompliant ())
638                                                 continue;
639
640                                         List<TypeSpec> found;
641                                         if (!locase_types.TryGetValue (tm.Name, out found)) {
642                                                 found = new List<TypeSpec> ();
643                                                 locase_types.Add (tm.Name, found);
644                                         }
645
646                                         found.Add (tm);
647                                 }
648                         }
649
650                         foreach (var locase in locase_types.Values) {
651                                 if (locase.Count < 2)
652                                         continue;
653
654                                 bool all_same = true;
655                                 foreach (var notcompliant in locase) {
656                                         all_same = notcompliant.Name == locase[0].Name;
657                                         if (!all_same)
658                                                 break;
659                                 }
660
661                                 if (all_same)
662                                         continue;
663
664                                 TypeContainer compiled = null;
665                                 foreach (var notcompliant in locase) {
666                                         if (!notcompliant.MemberDefinition.IsImported) {
667                                                 if (compiled != null)
668                                                         compiled.Compiler.Report.SymbolRelatedToPreviousError (compiled);
669
670                                                 compiled = notcompliant.MemberDefinition as TypeContainer;
671                                         } else {
672                                                 compiled.Compiler.Report.SymbolRelatedToPreviousError (notcompliant);
673                                         }
674                                 }
675
676                                 compiled.Compiler.Report.Warning (3005, 1, compiled.Location,
677                                         "Identifier `{0}' differing only in case is not CLS-compliant", compiled.GetSignatureForError ());
678                         }
679                 }
680         }
681
682         //
683         // Namespace container as created by the parser
684         //
685         public class NamespaceEntry : IMemberContext {
686
687                 public class UsingEntry {
688                         readonly MemberName name;
689                         Namespace resolved;
690                         
691                         public UsingEntry (MemberName name)
692                         {
693                                 this.name = name;
694                         }
695
696                         public string GetSignatureForError ()
697                         {
698                                 return name.GetSignatureForError ();
699                         }
700
701                         public Location Location {
702                                 get { return name.Location; }
703                         }
704
705                         public MemberName MemberName {
706                                 get { return name; }
707                         }
708                         
709                         public string Name {
710                                 get { return GetSignatureForError (); }
711                         }
712
713                         public Namespace Resolve (IMemberContext rc)
714                         {
715                                 if (resolved != null)
716                                         return resolved;
717
718                                 FullNamedExpression fne = name.GetTypeExpression ().ResolveAsTypeStep (rc, false);
719                                 if (fne == null)
720                                         return null;
721
722                                 resolved = fne as Namespace;
723                                 if (resolved == null) {
724                                         rc.Compiler.Report.SymbolRelatedToPreviousError (fne.Type);
725                                         rc.Compiler.Report.Error (138, Location,
726                                                 "`{0}' is a type not a namespace. A using namespace directive can only be applied to namespaces",
727                                                 GetSignatureForError ());
728                                 }
729                                 return resolved;
730                         }
731
732                         public override string ToString ()
733                         {
734                                 return Name;
735                         }
736                 }
737
738                 public class UsingAliasEntry {
739                         public readonly string Alias;
740                         public Location Location;
741
742                         public UsingAliasEntry (string alias, Location loc)
743                         {
744                                 this.Alias = alias;
745                                 this.Location = loc;
746                         }
747
748                         public virtual FullNamedExpression Resolve (IMemberContext rc)
749                         {
750                                 FullNamedExpression fne = GlobalRootNamespace.Instance.GetRootNamespace (Alias);
751                                 if (fne == null) {
752                                         rc.Compiler.Report.Error (430, Location,
753                                                 "The extern alias `{0}' was not specified in -reference option",
754                                                 Alias);
755                                 }
756
757                                 return fne;
758                         }
759
760                         public override string ToString ()
761                         {
762                                 return Alias;
763                         }
764                         
765                 }
766
767                 class LocalUsingAliasEntry : UsingAliasEntry {
768                         FullNamedExpression resolved;
769                         MemberName value;
770
771                         public LocalUsingAliasEntry (string alias, MemberName name, Location loc)
772                                 : base (alias, loc)
773                         {
774                                 this.value = name;
775                         }
776
777                         public override FullNamedExpression Resolve (IMemberContext rc)
778                         {
779                                 if (resolved != null || value == null)
780                                         return resolved;
781
782                                 if (rc == null)
783                                         return null;
784
785                                 resolved = value.GetTypeExpression ().ResolveAsTypeStep (rc, false);
786                                 if (resolved == null) {
787                                         value = null;
788                                         return null;
789                                 }
790
791                                 if (resolved is TypeExpr)
792                                         resolved = resolved.ResolveAsTypeTerminal (rc, false);
793
794                                 return resolved;
795                         }
796
797                         public override string ToString ()
798                         {
799                                 return String.Format ("{0} = {1}", Alias, value.GetSignatureForError ());
800                         }
801                 }
802
803                 Namespace ns;
804                 NamespaceEntry parent, implicit_parent;
805                 CompilationUnit file;
806                 int symfile_id;
807
808                 // Namespace using import block
809                 List<UsingAliasEntry> using_aliases;
810                 List<UsingEntry> using_clauses;
811                 public bool DeclarationFound;
812                 // End
813
814                 public readonly bool IsImplicit;
815                 public readonly DeclSpace SlaveDeclSpace;
816                 static readonly Namespace [] empty_namespaces = new Namespace [0];
817                 Namespace [] namespace_using_table;
818
819                 static List<NamespaceEntry> entries = new List<NamespaceEntry> ();
820
821                 public static void Reset ()
822                 {
823                         entries = new List<NamespaceEntry> ();
824                 }
825
826                 public NamespaceEntry (NamespaceEntry parent, CompilationUnit file, string name)
827                 {
828                         this.parent = parent;
829                         this.file = file;
830                         entries.Add (this);
831
832                         if (parent != null)
833                                 ns = parent.NS.GetNamespace (name, true);
834                         else if (name != null)
835                                 ns = GlobalRootNamespace.Instance.GetNamespace (name, true);
836                         else
837                                 ns = GlobalRootNamespace.Instance;
838                         SlaveDeclSpace = new RootDeclSpace (this);
839                 }
840
841                 private NamespaceEntry (NamespaceEntry parent, CompilationUnit file, Namespace ns, bool slave)
842                 {
843                         this.parent = parent;
844                         this.file = file;
845                         this.IsImplicit = true;
846                         this.ns = ns;
847                         this.SlaveDeclSpace = slave ? new RootDeclSpace (this) : null;
848                 }
849
850                 //
851                 // Populates the Namespace with some using declarations, used by the
852                 // eval mode. 
853                 //
854                 public void Populate (List<UsingAliasEntry> source_using_aliases, List<UsingEntry> source_using_clauses)
855                 {
856                         foreach (UsingAliasEntry uae in source_using_aliases){
857                                 if (using_aliases == null)
858                                         using_aliases = new List<UsingAliasEntry> ();
859                                 
860                                 using_aliases.Add (uae);
861                         }
862
863                         foreach (UsingEntry ue in source_using_clauses){
864                                 if (using_clauses == null)
865                                         using_clauses = new List<UsingEntry> ();
866                                 
867                                 using_clauses.Add (ue);
868                         }
869                 }
870
871                 //
872                 // Extracts the using alises and using clauses into a couple of
873                 // arrays that might already have the same information;  Used by the
874                 // C# Eval mode.
875                 //
876                 public void Extract (List<UsingAliasEntry> out_using_aliases, List<UsingEntry> out_using_clauses)
877                 {
878                         if (using_aliases != null){
879                                 foreach (UsingAliasEntry uae in using_aliases){
880                                         bool replaced = false;
881                                         
882                                         for (int i = 0; i < out_using_aliases.Count; i++){
883                                                 UsingAliasEntry out_uea = (UsingAliasEntry) out_using_aliases [i];
884                                                 
885                                                 if (out_uea.Alias == uae.Alias){
886                                                         out_using_aliases [i] = uae;
887                                                         replaced = true;
888                                                         break;
889                                                 }
890                                         }
891                                         if (!replaced)
892                                                 out_using_aliases.Add (uae);
893                                 }
894                         }
895
896                         if (using_clauses != null){
897                                 foreach (UsingEntry ue in using_clauses){
898                                         bool found = false;
899                                         
900                                         foreach (UsingEntry out_ue in out_using_clauses)
901                                                 if (out_ue.Name == ue.Name){
902                                                         found = true;
903                                                         break;
904                                                 }
905                                         if (!found)
906                                                 out_using_clauses.Add (ue);
907                                 }
908                         }
909                 }
910                 
911                 //
912                 // According to section 16.3.1 (using-alias-directive), the namespace-or-type-name is
913                 // resolved as if the immediately containing namespace body has no using-directives.
914                 //
915                 // Section 16.3.2 says that the same rule is applied when resolving the namespace-name
916                 // in the using-namespace-directive.
917                 //
918                 // To implement these rules, the expressions in the using directives are resolved using 
919                 // the "doppelganger" (ghostly bodiless duplicate).
920                 //
921                 NamespaceEntry doppelganger;
922                 NamespaceEntry Doppelganger {
923                         get {
924                                 if (!IsImplicit && doppelganger == null) {
925                                         doppelganger = new NamespaceEntry (ImplicitParent, file, ns, true);
926                                         doppelganger.using_aliases = using_aliases;
927                                 }
928                                 return doppelganger;
929                         }
930                 }
931
932                 public Namespace NS {
933                         get { return ns; }
934                 }
935
936                 public NamespaceEntry Parent {
937                         get { return parent; }
938                 }
939
940                 public NamespaceEntry ImplicitParent {
941                         get {
942                                 if (parent == null)
943                                         return null;
944                                 if (implicit_parent == null) {
945                                         implicit_parent = (parent.NS == ns.Parent)
946                                                 ? parent
947                                                 : new NamespaceEntry (parent, file, ns.Parent, false);
948                                 }
949                                 return implicit_parent;
950                         }
951                 }
952
953                 /// <summary>
954                 ///   Records a new namespace for resolving name references
955                 /// </summary>
956                 public void AddUsing (MemberName name, Location loc)
957                 {
958                         if (DeclarationFound){
959                                 Compiler.Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
960                         }
961
962                         if (using_clauses == null) {
963                                 using_clauses = new List<UsingEntry> ();
964                         } else {
965                                 foreach (UsingEntry old_entry in using_clauses) {
966                                         if (name.Equals (old_entry.MemberName)) {
967                                                 Compiler.Report.SymbolRelatedToPreviousError (old_entry.Location, old_entry.GetSignatureForError ());
968                                                 Compiler.Report.Warning (105, 3, loc, "The using directive for `{0}' appeared previously in this namespace", name.GetSignatureForError ());
969                                                 return;
970                                         }
971                                 }
972                         }
973
974                         using_clauses.Add (new UsingEntry (name));
975                 }
976
977                 public void AddUsingAlias (string alias, MemberName name, Location loc)
978                 {
979                         // TODO: This is parser bussines
980                         if (DeclarationFound){
981                                 Compiler.Report.Error (1529, loc, "A using clause must precede all other namespace elements except extern alias declarations");
982                         }
983
984                         if (RootContext.Version != LanguageVersion.ISO_1 && alias == "global")
985                                 Compiler.Report.Warning (440, 2, loc, "An alias named `global' will not be used when resolving 'global::';" +
986                                         " the global namespace will be used instead");
987
988                         AddUsingAlias (new LocalUsingAliasEntry (alias, name, loc));
989                 }
990
991                 public void AddUsingExternalAlias (string alias, Location loc, Report Report)
992                 {
993                         // TODO: Do this in parser
994                         bool not_first = using_clauses != null || DeclarationFound;
995                         if (using_aliases != null && !not_first) {
996                                 foreach (UsingAliasEntry uae in using_aliases) {
997                                         if (uae is LocalUsingAliasEntry) {
998                                                 not_first = true;
999                                                 break;
1000                                         }
1001                                 }
1002                         }
1003
1004                         if (not_first)
1005                                 Report.Error (439, loc, "An extern alias declaration must precede all other elements");
1006
1007                         if (alias == "global") {
1008                                 Error_GlobalNamespaceRedefined (loc, Report);
1009                                 return;
1010                         }
1011
1012                         AddUsingAlias (new UsingAliasEntry (alias, loc));
1013                 }
1014
1015                 void AddUsingAlias (UsingAliasEntry uae)
1016                 {
1017                         if (using_aliases == null) {
1018                                 using_aliases = new List<UsingAliasEntry> ();
1019                         } else {
1020                                 foreach (UsingAliasEntry entry in using_aliases) {
1021                                         if (uae.Alias == entry.Alias) {
1022                                                 Compiler.Report.SymbolRelatedToPreviousError (uae.Location, uae.Alias);
1023                                                 Compiler.Report.Error (1537, entry.Location, "The using alias `{0}' appeared previously in this namespace",
1024                                                         entry.Alias);
1025                                                 return;
1026                                         }
1027                                 }
1028                         }
1029
1030                         using_aliases.Add (uae);
1031                 }
1032
1033                 ///
1034                 /// Does extension methods look up to find a method which matches name and extensionType.
1035                 /// Search starts from this namespace and continues hierarchically up to top level.
1036                 ///
1037                 public IList<MethodSpec> LookupExtensionMethod (TypeSpec extensionType, string name, int arity, ref NamespaceEntry scope)
1038                 {
1039                         List<MethodSpec> candidates = null;
1040                         foreach (Namespace n in GetUsingTable ()) {
1041                                 var a = n.LookupExtensionMethod (extensionType, null, name, arity);
1042                                 if (a == null)
1043                                         continue;
1044
1045                                 if (candidates == null)
1046                                         candidates = a;
1047                                 else
1048                                         candidates.AddRange (a);
1049                         }\r
1050 \r
1051                         scope = parent;\r
1052                         if (candidates != null)\r
1053                                 return candidates;\r
1054
1055                         if (parent == null)
1056                                 return null;
1057
1058                         //
1059                         // Inspect parent namespaces in namespace expression
1060                         //
1061                         Namespace parent_ns = ns.Parent;
1062                         do {
1063                                 candidates = parent_ns.LookupExtensionMethod (extensionType, null, name, arity);\r
1064                                 if (candidates != null)\r
1065                                         return candidates;
1066
1067                                 parent_ns = parent_ns.Parent;
1068                         } while (parent_ns != null);
1069
1070                         //
1071                         // Continue in parent scope
1072                         //
1073                         return parent.LookupExtensionMethod (extensionType, name, arity, ref scope);
1074                 }
1075
1076                 public FullNamedExpression LookupNamespaceOrType (string name, int arity, Location loc, bool ignore_cs0104)
1077                 {
1078                         // Precondition: Only simple names (no dots) will be looked up with this function.
1079                         FullNamedExpression resolved = null;
1080                         for (NamespaceEntry curr_ns = this; curr_ns != null; curr_ns = curr_ns.ImplicitParent) {
1081                                 if ((resolved = curr_ns.Lookup (name, arity, loc, ignore_cs0104)) != null)
1082                                         break;
1083                         }
1084
1085                         return resolved;
1086                 }
1087
1088                 public IList<string> CompletionGetTypesStartingWith (string prefix)
1089                 {
1090                         IEnumerable<string> all = Enumerable.Empty<string> ();
1091                         
1092                         for (NamespaceEntry curr_ns = this; curr_ns != null; curr_ns = curr_ns.ImplicitParent){
1093                                 foreach (Namespace using_ns in GetUsingTable ()){
1094                                         if (prefix.StartsWith (using_ns.Name)){
1095                                                 int ld = prefix.LastIndexOf ('.');
1096                                                 if (ld != -1){
1097                                                         string rest = prefix.Substring (ld+1);
1098
1099                                                         all = all.Concat (using_ns.CompletionGetTypesStartingWith (rest));
1100                                                 }
1101                                         }
1102                                         all = all.Concat (using_ns.CompletionGetTypesStartingWith (prefix));
1103                                 }
1104                         }
1105
1106                         return all.Distinct ().ToList ();
1107                 }
1108                 
1109                 // Looks-up a alias named @name in this and surrounding namespace declarations
1110                 public FullNamedExpression LookupNamespaceAlias (string name)
1111                 {
1112                         for (NamespaceEntry n = this; n != null; n = n.ImplicitParent) {
1113                                 if (n.using_aliases == null)
1114                                         continue;
1115
1116                                 foreach (UsingAliasEntry ue in n.using_aliases) {
1117                                         if (ue.Alias == name)
1118                                                 return ue.Resolve (Doppelganger);
1119                                 }
1120                         }
1121
1122                         return null;
1123                 }
1124
1125                 private FullNamedExpression Lookup (string name, int arity, Location loc, bool ignore_cs0104)
1126                 {
1127                         //
1128                         // Check whether it's in the namespace.
1129                         //
1130                         FullNamedExpression fne = ns.Lookup (Compiler, name, arity, loc);
1131
1132                         //
1133                         // Check aliases. 
1134                         //
1135                         if (using_aliases != null && arity == 0) {
1136                                 foreach (UsingAliasEntry ue in using_aliases) {
1137                                         if (ue.Alias == name) {
1138                                                 if (fne != null) {
1139                                                         if (Doppelganger != null) {
1140                                                                 // TODO: Namespace has broken location
1141                                                                 //Report.SymbolRelatedToPreviousError (fne.Location, null);
1142                                                                 Compiler.Report.SymbolRelatedToPreviousError (ue.Location, null);
1143                                                                 Compiler.Report.Error (576, loc,
1144                                                                         "Namespace `{0}' contains a definition with same name as alias `{1}'",
1145                                                                         GetSignatureForError (), name);
1146                                                         } else {
1147                                                                 return fne;
1148                                                         }
1149                                                 }
1150
1151                                                 return ue.Resolve (Doppelganger);
1152                                         }
1153                                 }
1154                         }
1155
1156                         if (fne != null) {
1157                                 if (!((fne.Type.Modifiers & Modifiers.INTERNAL) != 0 && !TypeManager.IsThisOrFriendAssembly (CodeGen.Assembly.Builder, fne.Type.Assembly)))
1158                                         return fne;
1159                         }
1160
1161                         if (IsImplicit)
1162                                 return null;
1163
1164                         //
1165                         // Check using entries.
1166                         //
1167                         FullNamedExpression match = null;
1168                         foreach (Namespace using_ns in GetUsingTable ()) {
1169                                 // A using directive imports only types contained in the namespace, it
1170                                 // does not import any nested namespaces
1171                                 fne = using_ns.LookupType (Compiler, name, arity, false, loc);
1172                                 if (fne == null)
1173                                         continue;
1174
1175                                 if (match == null) {
1176                                         match = fne;
1177                                         continue;
1178                                 }
1179
1180                                 // Prefer types over namespaces
1181                                 var texpr_fne = fne as TypeExpr;
1182                                 var texpr_match = match as TypeExpr;
1183                                 if (texpr_fne != null && texpr_match == null) {
1184                                         match = fne;
1185                                         continue;
1186                                 } else if (texpr_fne == null) {
1187                                         continue;
1188                                 }
1189
1190                                 if (ignore_cs0104)
1191                                         return match;
1192
1193                                 // It can be top level accessibility only
1194                                 var better = Namespace.IsImportedTypeOverride (texpr_match.Type, texpr_fne.Type);
1195                                 if (better == null) {
1196                                         Compiler.Report.SymbolRelatedToPreviousError (texpr_match.Type);
1197                                         Compiler.Report.SymbolRelatedToPreviousError (texpr_fne.Type);
1198                                         Compiler.Report.Error (104, loc, "`{0}' is an ambiguous reference between `{1}' and `{2}'",
1199                                                 name, texpr_match.GetSignatureForError (), texpr_fne.GetSignatureForError ());
1200                                         return match;
1201                                 }
1202
1203                                 if (better == texpr_fne.Type)
1204                                         match = texpr_fne;
1205                         }
1206
1207                         return match;
1208                 }
1209
1210                 Namespace [] GetUsingTable ()
1211                 {
1212                         if (namespace_using_table != null)
1213                                 return namespace_using_table;
1214
1215                         if (using_clauses == null) {
1216                                 namespace_using_table = empty_namespaces;
1217                                 return namespace_using_table;
1218                         }
1219
1220                         var list = new List<Namespace> (using_clauses.Count);
1221
1222                         foreach (UsingEntry ue in using_clauses) {
1223                                 Namespace using_ns = ue.Resolve (Doppelganger);
1224                                 if (using_ns == null)
1225                                         continue;
1226
1227                                 list.Add (using_ns);
1228                         }
1229
1230                         namespace_using_table = list.ToArray ();
1231                         return namespace_using_table;
1232                 }
1233
1234                 static readonly string [] empty_using_list = new string [0];
1235
1236                 public int SymbolFileID {
1237                         get {
1238                                 if (symfile_id == 0 && file.SourceFileEntry != null) {
1239                                         int parent_id = parent == null ? 0 : parent.SymbolFileID;
1240
1241                                         string [] using_list = empty_using_list;
1242                                         if (using_clauses != null) {
1243                                                 using_list = new string [using_clauses.Count];
1244                                                 for (int i = 0; i < using_clauses.Count; i++)
1245                                                         using_list [i] = ((UsingEntry) using_clauses [i]).MemberName.GetName ();
1246                                         }
1247
1248                                         symfile_id = SymbolWriter.DefineNamespace (ns.Name, file.CompileUnitEntry, using_list, parent_id);
1249                                 }
1250                                 return symfile_id;
1251                         }
1252                 }
1253
1254                 static void MsgtryRef (string s)
1255                 {
1256                         Console.WriteLine ("    Try using -r:" + s);
1257                 }
1258
1259                 static void MsgtryPkg (string s)
1260                 {
1261                         Console.WriteLine ("    Try using -pkg:" + s);
1262                 }
1263
1264                 public static void Error_GlobalNamespaceRedefined (Location loc, Report Report)
1265                 {
1266                         Report.Error (1681, loc, "You cannot redefine the global extern alias");
1267                 }
1268
1269                 public static void Error_NamespaceNotFound (Location loc, string name, Report Report)
1270                 {
1271                         Report.Error (246, loc, "The type or namespace name `{0}' could not be found. Are you missing a using directive or an assembly reference?",
1272                                 name);
1273
1274                         switch (name) {
1275                         case "Gtk": case "GtkSharp":
1276                                 MsgtryPkg ("gtk-sharp");
1277                                 break;
1278
1279                         case "Gdk": case "GdkSharp":
1280                                 MsgtryPkg ("gdk-sharp");
1281                                 break;
1282
1283                         case "Glade": case "GladeSharp":
1284                                 MsgtryPkg ("glade-sharp");
1285                                 break;
1286
1287                         case "System.Drawing":
1288                         case "System.Web.Services":
1289                         case "System.Web":
1290                         case "System.Data":
1291                         case "System.Windows.Forms":
1292                                 MsgtryRef (name);
1293                                 break;
1294                         }
1295                 }
1296
1297                 /// <summary>
1298                 ///   Used to validate that all the using clauses are correct
1299                 ///   after we are finished parsing all the files.  
1300                 /// </summary>
1301                 void VerifyUsing ()
1302                 {
1303                         if (using_aliases != null) {
1304                                 foreach (UsingAliasEntry ue in using_aliases)
1305                                         ue.Resolve (Doppelganger);
1306                         }
1307
1308                         if (using_clauses != null) {
1309                                 foreach (UsingEntry ue in using_clauses)
1310                                         ue.Resolve (Doppelganger);
1311                         }
1312                 }
1313
1314                 /// <summary>
1315                 ///   Used to validate that all the using clauses are correct
1316                 ///   after we are finished parsing all the files.  
1317                 /// </summary>
1318                 static public void VerifyAllUsing ()
1319                 {
1320                         foreach (NamespaceEntry entry in entries)
1321                                 entry.VerifyUsing ();
1322                 }
1323
1324                 public string GetSignatureForError ()
1325                 {
1326                         return ns.GetSignatureForError ();
1327                 }
1328
1329                 public override string ToString ()
1330                 {
1331                         return ns.ToString ();
1332                 }
1333
1334                 #region IMemberContext Members
1335
1336                 public CompilerContext Compiler {
1337                         get { return RootContext.ToplevelTypes.Compiler; }
1338                 }
1339
1340                 public TypeSpec CurrentType {
1341                         get { return SlaveDeclSpace.CurrentType; }
1342                 }
1343
1344                 public MemberCore CurrentMemberDefinition {
1345                         get { return SlaveDeclSpace.CurrentMemberDefinition; }
1346                 }
1347
1348                 public TypeParameter[] CurrentTypeParameters {
1349                         get { return SlaveDeclSpace.CurrentTypeParameters; }
1350                 }
1351
1352                 // FIXME: It's false for expression types
1353                 public bool HasUnresolvedConstraints {
1354                         get { return true; }
1355                 }
1356
1357                 public bool IsObsolete {
1358                         get { return SlaveDeclSpace.IsObsolete; }
1359                 }
1360
1361                 public bool IsUnsafe {
1362                         get { return SlaveDeclSpace.IsUnsafe; }
1363                 }
1364
1365                 public bool IsStatic {
1366                         get { return SlaveDeclSpace.IsStatic; }
1367                 }
1368
1369                 #endregion
1370         }
1371 }