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