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