Added unit test.
[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 // Copyright 2011 Xamarin Inc
11 //
12 using System;
13 using System.Collections.Generic;
14 using System.Linq;
15 using Mono.CompilerServices.SymbolWriter;
16
17 namespace Mono.CSharp {
18
19         public class RootNamespace : Namespace {
20
21                 readonly string alias_name;
22                 readonly Dictionary<string, Namespace> all_namespaces;
23
24                 public RootNamespace (string alias_name)
25                         : base (null, String.Empty)
26                 {
27                         this.alias_name = alias_name;
28
29                         all_namespaces = new Dictionary<string, Namespace> ();
30                         all_namespaces.Add ("", this);
31                 }
32
33                 public string Alias {
34                         get {
35                                 return alias_name;
36                         }
37                 }
38
39                 public static void Error_GlobalNamespaceRedefined (Report report, Location loc)
40                 {
41                         report.Error (1681, loc, "The global extern alias cannot be redefined");
42                 }
43
44                 public void RegisterNamespace (Namespace child)
45                 {
46                         if (child != this)
47                                 all_namespaces.Add (child.Name, child);
48                 }
49
50                 public bool IsNamespace (string name)
51                 {
52                         return all_namespaces.ContainsKey (name);
53                 }
54
55                 protected void RegisterNamespace (string dotted_name)
56                 {
57                         if (dotted_name != null && dotted_name.Length != 0 && ! IsNamespace (dotted_name))
58                                 GetNamespace (dotted_name, true);
59                 }
60
61                 public override string GetSignatureForError ()
62                 {
63                         return alias_name + "::";
64                 }
65         }
66
67         public class GlobalRootNamespace : RootNamespace
68         {
69                 public GlobalRootNamespace ()
70                         : base ("global")
71                 {
72                 }
73         }
74
75         //
76         // Namespace cache for imported and compiled namespaces
77         //
78         // This is an Expression to allow it to be referenced in the
79         // compiler parse/intermediate tree during name resolution.
80         //
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                 List<TypeSpec> extension_method_types;
88                 Dictionary<string, TypeExpr> cached_types;
89                 RootNamespace root;
90                 bool cls_checked;
91
92                 public readonly MemberName MemberName;
93
94                 /// <summary>
95                 ///   Constructor Takes the current namespace and the
96                 ///   name.  This is bootstrapped with parent == null
97                 ///   and name = ""
98                 /// </summary>
99                 public Namespace (Namespace parent, string name)
100                 {
101                         // Expression members.
102                         this.eclass = ExprClass.Namespace;
103                         this.Type = InternalType.Namespace;
104                         this.loc = Location.Null;
105
106                         this.parent = parent;
107
108                         if (parent != null)
109                                 this.root = parent.root;
110                         else
111                                 this.root = this as RootNamespace;
112
113                         if (this.root == null)
114                                 throw new InternalErrorException ("Root namespaces must be created using RootNamespace");
115                         
116                         string pname = parent != null ? parent.fullname : "";
117                                 
118                         if (pname == "")
119                                 fullname = name;
120                         else
121                                 fullname = parent.fullname + "." + name;
122
123                         if (fullname == null)
124                                 throw new InternalErrorException ("Namespace has a null fullname");
125
126                         if (parent != null && parent.MemberName != MemberName.Null)
127                                 MemberName = new MemberName (parent.MemberName, name, Location.Null);
128                         else if (name.Length == 0)
129                                 MemberName = MemberName.Null;
130                         else
131                                 MemberName = new MemberName (name, Location.Null);
132
133                         namespaces = new Dictionary<string, Namespace> ();
134                         cached_types = new Dictionary<string, TypeExpr> ();
135
136                         root.RegisterNamespace (this);
137                 }
138
139                 #region Properties
140
141                 /// <summary>
142                 ///   The qualified name of the current namespace
143                 /// </summary>
144                 public string Name {
145                         get { return fullname; }
146                 }
147
148                 /// <summary>
149                 ///   The parent of this namespace, used by the parser to "Pop"
150                 ///   the current namespace declaration
151                 /// </summary>
152                 public Namespace Parent {
153                         get { return parent; }
154                 }
155
156                 #endregion
157
158                 protected override Expression DoResolve (ResolveContext ec)
159                 {
160                         return this;
161                 }
162
163                 public void Error_NamespaceDoesNotExist (IMemberContext ctx, string name, int arity, Location loc)
164                 {
165                         var retval = LookupType (ctx, name, arity, LookupMode.IgnoreAccessibility, loc);
166                         if (retval != null) {
167                                 ctx.Module.Compiler.Report.SymbolRelatedToPreviousError (retval.Type);
168                                 ErrorIsInaccesible (ctx, retval.GetSignatureForError (), loc);
169                                 return;
170                         }
171
172                         retval = LookupType (ctx, name, -System.Math.Max (1, arity), LookupMode.Probing, loc);
173                         if (retval != null) {
174                                 Error_TypeArgumentsCannotBeUsed (ctx, retval.Type, arity, loc);
175                                 return;
176                         }
177
178                         Namespace ns;
179                         if (arity > 0 && namespaces.TryGetValue (name, out ns)) {
180                                 ns.Error_TypeArgumentsCannotBeUsed (ctx, null, arity, loc);
181                                 return;
182                         }
183
184                         if (this is GlobalRootNamespace) {
185                                 ctx.Module.Compiler.Report.Error (400, loc,
186                                         "The type or namespace name `{0}' could not be found in the global namespace (are you missing an assembly reference?)",
187                                         name);
188                         } else {
189                                 ctx.Module.Compiler.Report.Error (234, loc,
190                                         "The type or namespace name `{0}' does not exist in the namespace `{1}'. Are you missing an assembly reference?",
191                                         name, GetSignatureForError ());
192                         }
193                 }
194
195                 public override string GetSignatureForError ()
196                 {
197                         return fullname;
198                 }
199
200                 public Namespace AddNamespace (MemberName name)
201                 {
202                         Namespace ns_parent;
203                         if (name.Left != null) {
204                                 if (parent != null)
205                                         ns_parent = parent.AddNamespace (name.Left);
206                                 else
207                                         ns_parent = AddNamespace (name.Left);
208                         } else {
209                                 ns_parent = this;
210                         }
211
212                         return ns_parent.TryAddNamespace (name.Basename);
213                 }
214
215                 Namespace TryAddNamespace (string name)
216                 {
217                         Namespace ns;
218
219                         if (!namespaces.TryGetValue (name, out ns)) {
220                                 ns = new Namespace (this, name);
221                                 namespaces.Add (name, ns);
222                         }
223
224                         return ns;
225                 }
226
227                 // TODO: Replace with CreateNamespace where MemberName is created for the method call
228                 public Namespace GetNamespace (string name, bool create)
229                 {
230                         int pos = name.IndexOf ('.');
231
232                         Namespace ns;
233                         string first;
234                         if (pos >= 0)
235                                 first = name.Substring (0, pos);
236                         else
237                                 first = name;
238
239                         if (!namespaces.TryGetValue (first, out ns)) {
240                                 if (!create)
241                                         return null;
242
243                                 ns = new Namespace (this, first);
244                                 namespaces.Add (first, ns);
245                         }
246
247                         if (pos >= 0)
248                                 ns = ns.GetNamespace (name.Substring (pos + 1), create);
249
250                         return ns;
251                 }
252
253                 public IList<TypeSpec> GetAllTypes (string name)
254                 {
255                         IList<TypeSpec> found;
256                         if (types == null || !types.TryGetValue (name, out found))
257                                 return null;
258
259                         return found;
260                 }
261
262                 public TypeExpr LookupType (IMemberContext ctx, string name, int arity, LookupMode mode, Location loc)
263                 {
264                         if (types == null)
265                                 return null;
266
267                         TypeExpr te;
268                         if (arity == 0 && cached_types.TryGetValue (name, out te))
269                                 return te;
270
271                         IList<TypeSpec> found;
272                         if (!types.TryGetValue (name, out found))
273                                 return null;
274
275                         TypeSpec best = null;
276                         foreach (var ts in found) {
277                                 if (ts.Arity == arity) {
278                                         if (best == null) {
279                                                 if ((ts.Modifiers & Modifiers.INTERNAL) != 0 && !ts.MemberDefinition.IsInternalAsPublic (ctx.Module.DeclaringAssembly) && mode != LookupMode.IgnoreAccessibility)
280                                                         continue;
281
282                                                 best = ts;
283                                                 continue;
284                                         }
285
286                                         if (best.MemberDefinition.IsImported && ts.MemberDefinition.IsImported) {
287                                                 if (mode == LookupMode.Normal) {
288                                                         ctx.Module.Compiler.Report.SymbolRelatedToPreviousError (best);
289                                                         ctx.Module.Compiler.Report.SymbolRelatedToPreviousError (ts);
290                                                         ctx.Module.Compiler.Report.Error (433, loc, "The imported type `{0}' is defined multiple times", ts.GetSignatureForError ());
291                                                 }
292                                                 break;
293                                         }
294
295                                         if (best.MemberDefinition.IsImported)
296                                                 best = ts;
297
298                                         if ((best.Modifiers & Modifiers.INTERNAL) != 0 && !best.MemberDefinition.IsInternalAsPublic (ctx.Module.DeclaringAssembly))
299                                                 continue;
300
301                                         if (mode != LookupMode.Normal)
302                                                 continue;
303
304                                         if (ts.MemberDefinition.IsImported)
305                                                 ctx.Module.Compiler.Report.SymbolRelatedToPreviousError (ts);
306
307                                         ctx.Module.Compiler.Report.Warning (436, 2, loc,
308                                                 "The type `{0}' conflicts with the imported type of same name'. Ignoring the imported type definition",
309                                                 best.GetSignatureForError ());
310                                 }
311
312                                 //
313                                 // Lookup for the best candidate with the closest arity match
314                                 //
315                                 if (arity < 0) {
316                                         if (best == null) {
317                                                 best = ts;
318                                         } else if (System.Math.Abs (ts.Arity + arity) < System.Math.Abs (best.Arity + arity)) {
319                                                 best = ts;
320                                         }
321                                 }
322                         }
323
324                         if (best == null)
325                                 return null;
326
327                         te = new TypeExpression (best, Location.Null);
328
329                         // TODO MemberCache: Cache more
330                         if (arity == 0 && mode == LookupMode.Normal)
331                                 cached_types.Add (name, te);
332
333                         return te;
334                 }
335
336                 public FullNamedExpression LookupTypeOrNamespace (IMemberContext ctx, string name, int arity, LookupMode mode, Location loc)
337                 {
338                         var texpr = LookupType (ctx, name, arity, mode, loc);
339
340                         Namespace ns;
341                         if (arity == 0 && namespaces.TryGetValue (name, out ns)) {
342                                 if (texpr == null)
343                                         return ns;
344
345                                 if (mode != LookupMode.Probing) {
346                                         ctx.Module.Compiler.Report.SymbolRelatedToPreviousError (texpr.Type);
347                                         // ctx.Module.Compiler.Report.SymbolRelatedToPreviousError (ns.loc, "");
348                                         ctx.Module.Compiler.Report.Warning (437, 2, loc,
349                                                 "The type `{0}' conflicts with the imported namespace `{1}'. Using the definition found in the source file",
350                                                 texpr.GetSignatureForError (), ns.GetSignatureForError ());
351                                 }
352
353                                 if (texpr.Type.MemberDefinition.IsImported)
354                                         return ns;
355                         }
356
357                         return texpr;
358                 }
359
360                 //
361                 // Completes types with the given `prefix'
362                 //
363                 public IEnumerable<string> CompletionGetTypesStartingWith (string prefix)
364                 {
365                         if (types == null)
366                                 return Enumerable.Empty<string> ();
367
368                         var res = from item in types
369                                           where item.Key.StartsWith (prefix) && item.Value.Any (l => (l.Modifiers & Modifiers.PUBLIC) != 0)
370                                           select item.Key;
371
372                         if (namespaces != null)
373                                 res = res.Concat (from item in namespaces where item.Key.StartsWith (prefix) select item.Key);
374
375                         return res;
376                 }
377
378                 // 
379                 // Looks for extension method in this namespace
380                 //
381                 public List<MethodSpec> LookupExtensionMethod (IMemberContext invocationContext, TypeSpec extensionType, string name, int arity)
382                 {
383                         if (extension_method_types == null)
384                                 return null;
385
386                         List<MethodSpec> found = null;
387                         for (int i = 0; i < extension_method_types.Count; ++i) {
388                                 var ts = extension_method_types[i];
389
390                                 //
391                                 // When the list was built we didn't know what members the type
392                                 // contains
393                                 //
394                                 if ((ts.Modifiers & Modifiers.METHOD_EXTENSION) == 0) {
395                                         if (extension_method_types.Count == 1) {
396                                                 extension_method_types = null;
397                                                 return found;
398                                         }
399
400                                         extension_method_types.RemoveAt (i--);
401                                         continue;
402                                 }
403
404                                 var res = ts.MemberCache.FindExtensionMethods (invocationContext, extensionType, name, arity);
405                                 if (res == null)
406                                         continue;
407
408                                 if (found == null) {
409                                         found = res;
410                                 } else {
411                                         found.AddRange (res);
412                                 }
413                         }
414
415                         return found;
416                 }
417
418                 public void AddType (ModuleContainer module, TypeSpec ts)
419                 {
420                         if (types == null) {
421                                 types = new Dictionary<string, IList<TypeSpec>> (64);
422                         }
423
424                         if ((ts.IsStatic || ts.MemberDefinition.IsPartial) && ts.Arity == 0 &&
425                                 (ts.MemberDefinition.DeclaringAssembly == null || ts.MemberDefinition.DeclaringAssembly.HasExtensionMethod)) {
426                                 if (extension_method_types == null)
427                                         extension_method_types = new List<TypeSpec> ();
428
429                                 extension_method_types.Add (ts);
430                         }
431
432                         var name = ts.Name;
433                         IList<TypeSpec> existing;
434                         if (types.TryGetValue (name, out existing)) {
435                                 TypeSpec better_type;
436                                 TypeSpec found;
437                                 if (existing.Count == 1) {
438                                         found = existing[0];
439                                         if (ts.Arity == found.Arity) {
440                                                 better_type = IsImportedTypeOverride (module, ts, found);
441                                                 if (better_type == found)
442                                                         return;
443
444                                                 if (better_type != null) {
445                                                         existing [0] = better_type;
446                                                         return;
447                                                 }
448                                         }
449
450                                         existing = new List<TypeSpec> ();
451                                         existing.Add (found);
452                                         types[name] = existing;
453                                 } else {
454                                         for (int i = 0; i < existing.Count; ++i) {
455                                                 found = existing[i];
456                                                 if (ts.Arity != found.Arity)
457                                                         continue;
458
459                                                 better_type = IsImportedTypeOverride (module, ts, found);
460                                                 if (better_type == found)
461                                                         return;
462
463                                                 if (better_type != null) {
464                                                         existing.RemoveAt (i);
465                                                         --i;
466                                                         continue;
467                                                 }
468                                         }
469                                 }
470
471                                 existing.Add (ts);
472                         } else {
473                                 types.Add (name, new TypeSpec[] { ts });
474                         }
475                 }
476
477                 //
478                 // We import any types but in the situation there are same types
479                 // but one has better visibility (either public or internal with friend)
480                 // the less visible type is removed from the namespace cache
481                 //
482                 public static TypeSpec IsImportedTypeOverride (ModuleContainer module, TypeSpec ts, TypeSpec found)
483                 {
484                         var ts_accessible = (ts.Modifiers & Modifiers.PUBLIC) != 0 || ts.MemberDefinition.IsInternalAsPublic (module.DeclaringAssembly);
485                         var found_accessible = (found.Modifiers & Modifiers.PUBLIC) != 0 || found.MemberDefinition.IsInternalAsPublic (module.DeclaringAssembly);
486
487                         if (ts_accessible && !found_accessible)
488                                 return ts;
489
490                         // found is better always better for accessible or inaccessible ts
491                         if (!ts_accessible)
492                                 return found;
493
494                         return null;
495                 }
496
497                 public void RemoveContainer (TypeContainer tc)
498                 {
499                         types.Remove (tc.Basename);
500                         cached_types.Remove (tc.Basename);
501                 }
502
503                 public override FullNamedExpression ResolveAsTypeOrNamespace (IMemberContext mc)
504                 {
505                         return this;
506                 }
507
508                 public void SetBuiltinType (BuiltinTypeSpec pts)
509                 {
510                         var found = types[pts.Name];
511                         cached_types.Remove (pts.Name);
512                         if (found.Count == 1) {
513                                 types[pts.Name][0] = pts;
514                         } else {
515                                 throw new NotImplementedException ();
516                         }
517                 }
518
519                 public void VerifyClsCompliance ()
520                 {
521                         if (types == null || cls_checked)
522                                 return;
523
524                         cls_checked = true;
525
526                         // TODO: This is quite ugly way to check for CLS compliance at namespace level
527
528                         var locase_types = new Dictionary<string, List<TypeSpec>> (StringComparer.OrdinalIgnoreCase);
529                         foreach (var tgroup in types.Values) {
530                                 foreach (var tm in tgroup) {
531                                         if ((tm.Modifiers & Modifiers.PUBLIC) == 0 || !tm.IsCLSCompliant ())
532                                                 continue;
533
534                                         List<TypeSpec> found;
535                                         if (!locase_types.TryGetValue (tm.Name, out found)) {
536                                                 found = new List<TypeSpec> ();
537                                                 locase_types.Add (tm.Name, found);
538                                         }
539
540                                         found.Add (tm);
541                                 }
542                         }
543
544                         foreach (var locase in locase_types.Values) {
545                                 if (locase.Count < 2)
546                                         continue;
547
548                                 bool all_same = true;
549                                 foreach (var notcompliant in locase) {
550                                         all_same = notcompliant.Name == locase[0].Name;
551                                         if (!all_same)
552                                                 break;
553                                 }
554
555                                 if (all_same)
556                                         continue;
557
558                                 TypeContainer compiled = null;
559                                 foreach (var notcompliant in locase) {
560                                         if (!notcompliant.MemberDefinition.IsImported) {
561                                                 if (compiled != null)
562                                                         compiled.Compiler.Report.SymbolRelatedToPreviousError (compiled);
563
564                                                 compiled = notcompliant.MemberDefinition as TypeContainer;
565                                         } else {
566                                                 compiled.Compiler.Report.SymbolRelatedToPreviousError (notcompliant);
567                                         }
568                                 }
569
570                                 compiled.Compiler.Report.Warning (3005, 1, compiled.Location,
571                                         "Identifier `{0}' differing only in case is not CLS-compliant", compiled.GetSignatureForError ());
572                         }
573                 }
574         }
575
576         public class CompilationSourceFile : NamespaceContainer
577         {
578                 readonly SourceFile file;
579                 CompileUnitEntry comp_unit;
580                 Dictionary<string, SourceFile> include_files;
581                 Dictionary<string, bool> conditionals;
582
583                 public CompilationSourceFile (ModuleContainer parent, SourceFile sourceFile)
584                         : this (parent)
585                 {
586                         this.file = sourceFile;
587                 }
588
589                 public CompilationSourceFile (ModuleContainer parent)
590                         : base (parent)
591                 {
592                 }
593
594                 public CompileUnitEntry SymbolUnitEntry {
595                         get {
596                                 return comp_unit;
597                         }
598                 }
599
600                 public string FileName {
601                         get {
602                                 return file.Name;
603                         }
604                 }
605
606                 public SourceFile SourceFile {
607                         get {
608                                 return file;
609                         }
610                 }
611
612                 public void AddIncludeFile (SourceFile file)
613                 {
614                         if (file == this.file)
615                                 return;
616
617                         if (include_files == null)
618                                 include_files = new Dictionary<string, SourceFile> ();
619
620                         if (!include_files.ContainsKey (file.FullPathName))
621                                 include_files.Add (file.FullPathName, file);
622                 }
623
624                 public void AddDefine (string value)
625                 {
626                         if (conditionals == null)
627                                 conditionals = new Dictionary<string, bool> (2);
628
629                         conditionals[value] = true;
630                 }
631
632                 public void AddUndefine (string value)
633                 {
634                         if (conditionals == null)
635                                 conditionals = new Dictionary<string, bool> (2);
636
637                         conditionals[value] = false;
638                 }
639
640                 public override void PrepareEmit ()
641                 {
642                         var sw = Module.DeclaringAssembly.SymbolWriter;
643                         if (sw != null) {
644                                 CreateUnitSymbolInfo (sw);
645                         }
646
647                         base.PrepareEmit ();
648                 }
649
650                 //
651                 // Creates symbol file index in debug symbol file
652                 //
653                 void CreateUnitSymbolInfo (MonoSymbolFile symwriter)
654                 {
655                         var si = file.CreateSymbolInfo (symwriter);
656                         comp_unit = new CompileUnitEntry (symwriter, si);;
657
658                         if (include_files != null) {
659                                 foreach (SourceFile include in include_files.Values) {
660                                         si = include.CreateSymbolInfo (symwriter);
661                                         comp_unit.AddFile (si);
662                                 }
663                         }
664                 }
665
666                 public bool IsConditionalDefined (string value)
667                 {
668                         if (conditionals != null) {
669                                 bool res;
670                                 if (conditionals.TryGetValue (value, out res))
671                                         return res;
672
673                                 // When conditional was undefined
674                                 if (conditionals.ContainsKey (value))
675                                         return false;
676                         }
677
678                         return Compiler.Settings.IsConditionalSymbolDefined (value);
679                 }
680         }
681
682
683         //
684         // Namespace block as created by the parser
685         //
686         public class NamespaceContainer : TypeContainer, IMemberContext
687         {
688                 static readonly Namespace[] empty_namespaces = new Namespace[0];
689
690                 readonly Namespace ns;
691
692                 public new readonly NamespaceContainer Parent;
693
694                 List<UsingNamespace> clauses;
695
696                 // Used by parsed to check for parser errors
697                 public bool DeclarationFound;
698
699                 Namespace[] namespace_using_table;
700                 Dictionary<string, UsingAliasNamespace> aliases;
701
702                 public NamespaceContainer (MemberName name, NamespaceContainer parent)
703                         : base (parent, name, null, MemberKind.Namespace)
704                 {
705                         this.Parent = parent;
706                         this.ns = parent.NS.AddNamespace (name);
707
708                         containers = new List<TypeContainer> ();
709                 }
710
711                 protected NamespaceContainer (ModuleContainer parent)
712                         : base (parent, null, null, MemberKind.Namespace)
713                 {
714                         ns = parent.GlobalRootNamespace;
715                         containers = new List<TypeContainer> (2);
716                 }
717
718                 #region Properties
719
720                 public override AttributeTargets AttributeTargets {
721                         get {
722                                 throw new NotSupportedException ();
723                         }
724                 }
725
726                 public override string DocCommentHeader {
727                         get {
728                                 throw new NotSupportedException ();
729                         }
730                 }
731
732                 public Namespace NS {
733                         get {
734                                 return ns;
735                         }
736                 }
737
738                 public List<UsingNamespace> Usings {
739                         get {
740                                 return clauses;
741                         }
742                 }
743
744                 public override string[] ValidAttributeTargets {
745                         get {
746                                 throw new NotSupportedException ();
747                         }
748                 }
749
750                 #endregion
751
752                 public void AddUsing (UsingNamespace un)
753                 {
754                         if (DeclarationFound){
755                                 Compiler.Report.Error (1529, un.Location, "A using clause must precede all other namespace elements except extern alias declarations");
756                         }
757
758                         if (clauses == null)
759                                 clauses = new List<UsingNamespace> ();
760
761                         clauses.Add (un);
762                 }
763
764                 public void AddUsing (UsingAliasNamespace un)
765                 {
766                         if (DeclarationFound){
767                                 Compiler.Report.Error (1529, un.Location, "A using clause must precede all other namespace elements except extern alias declarations");
768                         }
769
770                         AddAlias (un);
771                 }
772
773                 void AddAlias (UsingAliasNamespace un)
774                 {
775                         if (clauses == null) {
776                                 clauses = new List<UsingNamespace> ();
777                         } else {
778                                 foreach (var entry in clauses) {
779                                         var a = entry as UsingAliasNamespace;
780                                         if (a != null && a.Alias.Value == un.Alias.Value) {
781                                                 Compiler.Report.SymbolRelatedToPreviousError (a.Location, "");
782                                                 Compiler.Report.Error (1537, un.Location,
783                                                         "The using alias `{0}' appeared previously in this namespace", un.Alias.Value);
784                                         }
785                                 }
786                         }
787
788                         clauses.Add (un);
789                 }
790
791                 public override void AddPartial (TypeDefinition next_part)
792                 {
793                         var existing = ns.LookupType (this, next_part.MemberName.Name, next_part.MemberName.Arity, LookupMode.Probing, Location.Null);
794                         var td = existing != null ? existing.Type.MemberDefinition as TypeDefinition : null;
795                         AddPartial (next_part, td);
796                 }
797
798                 public override void AddTypeContainer (TypeContainer tc)
799                 {
800                         string name = tc.Basename;
801
802                         var mn = tc.MemberName;
803                         while (mn.Left != null) {
804                                 mn = mn.Left;
805                                 name = mn.Name;
806                         }
807
808                         var names_container = Parent == null ? Module : (TypeContainer) this;
809
810                         MemberCore mc;
811                         if (names_container.DefinedNames.TryGetValue (name, out mc)) {
812                                 if (tc is NamespaceContainer && mc is NamespaceContainer) {
813                                         containers.Add (tc);
814                                         return;
815                                 }
816
817                                 Report.SymbolRelatedToPreviousError (mc);
818                                 if ((mc.ModFlags & Modifiers.PARTIAL) != 0 && (tc is ClassOrStruct || tc is Interface)) {
819                                         Error_MissingPartialModifier (tc);
820                                 } else {
821                                         Report.Error (101, tc.Location, "The namespace `{0}' already contains a definition for `{1}'",
822                                                 GetSignatureForError (), mn.GetSignatureForError ());
823                                 }
824                         } else {
825                                 names_container.DefinedNames.Add (name, tc);
826                         }
827
828                         base.AddTypeContainer (tc);
829
830                         var tdef = tc.PartialContainer;
831                         if (tdef != null)
832                                 ns.AddType (Module, tdef.Definition);
833                 }
834
835                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
836                 {
837                         throw new NotSupportedException ();
838                 }
839
840                 public override void EmitContainer ()
841                 {
842                         VerifyClsCompliance ();
843
844                         base.EmitContainer ();
845                 }
846
847                 public ExtensionMethodCandidates LookupExtensionMethod (IMemberContext invocationContext, TypeSpec extensionType, string name, int arity, int position)
848                 {
849                         //
850                         // Here we try to resume the search for extension method at the point
851                         // where the last bunch of candidates was found. It's more tricky than
852                         // it seems as we have to check both namespace containers and namespace
853                         // in correct order.
854                         //
855                         // Consider:
856                         // 
857                         // namespace A {
858                         //      using N1;
859                         //  namespace B.C.D {
860                         //              <our first search found candidates in A.B.C.D
861                         //  }
862                         // }
863                         //
864                         // In the example above namespace A.B.C.D, A.B.C and A.B have to be
865                         // checked before we hit A.N1 using
866                         //
867                         ExtensionMethodCandidates candidates;
868                         var container = this;
869                         do {
870                                 candidates = container.LookupExtensionMethodCandidates (invocationContext, extensionType, name, arity, ref position);
871                                 if (candidates != null || container.MemberName == null)
872                                         return candidates;
873
874                                 var container_ns = container.ns.Parent;
875                                 var mn = container.MemberName.Left;
876                                 int already_checked = position - 2;
877                                 while (already_checked-- > 0) {
878                                         mn = mn.Left;
879                                         container_ns = container_ns.Parent;
880                                 }
881
882                                 while (mn != null) {
883                                         ++position;
884
885                                         var methods = container_ns.LookupExtensionMethod (invocationContext, extensionType, name, arity);
886                                         if (methods != null) {
887                                                 return new ExtensionMethodCandidates (invocationContext, methods, container, position);
888                                         }
889
890                                         mn = mn.Left;
891                                         container_ns = container_ns.Parent;
892                                 }
893
894                                 position = 0;
895                                 container = container.Parent;
896                         } while (container != null);
897
898                         return null;
899                 }
900
901                 ExtensionMethodCandidates LookupExtensionMethodCandidates (IMemberContext invocationContext, TypeSpec extensionType, string name, int arity, ref int position)
902                 {
903                         List<MethodSpec> candidates = null;
904
905                         if (position == 0) {
906                                 ++position;
907
908                                 candidates = ns.LookupExtensionMethod (invocationContext, extensionType, name, arity);
909                                 if (candidates != null) {
910                                         return new ExtensionMethodCandidates (invocationContext, candidates, this, position);
911                                 }
912                         }
913
914                         if (position == 1) {
915                                 ++position;
916
917                                 foreach (Namespace n in namespace_using_table) {
918                                         var a = n.LookupExtensionMethod (invocationContext, extensionType, name, arity);
919                                         if (a == null)
920                                                 continue;
921
922                                         if (candidates == null)
923                                                 candidates = a;
924                                         else
925                                                 candidates.AddRange (a);
926                                 }
927
928                                 if (candidates != null)
929                                         return new ExtensionMethodCandidates (invocationContext, candidates, this, position);
930                         }
931
932                         return null;
933                 }
934
935                 public override FullNamedExpression LookupNamespaceOrType (string name, int arity, LookupMode mode, Location loc)
936                 {
937                         //
938                         // Only simple names (no dots) will be looked up with this function
939                         //
940                         FullNamedExpression resolved;
941                         for (NamespaceContainer container = this; container != null; container = container.Parent) {
942                                 resolved = container.Lookup (name, arity, mode, loc);
943                                 if (resolved != null || container.MemberName == null)
944                                         return resolved;
945
946                                 var container_ns = container.ns.Parent;
947                                 var mn = container.MemberName.Left;
948                                 while (mn != null) {
949                                         resolved = container_ns.LookupTypeOrNamespace (this, name, arity, mode, loc);
950                                         if (resolved != null)
951                                                 return resolved;
952
953                                         mn = mn.Left;
954                                         container_ns = container_ns.Parent;
955                                 }
956                         }
957
958                         return null;
959                 }
960
961                 public override void GetCompletionStartingWith (string prefix, List<string> results)
962                 {
963                         foreach (var un in Usings) {
964                                 if (un.Alias != null)
965                                         continue;
966
967                                 var name = un.NamespaceExpression.Name;
968                                 if (name.StartsWith (prefix))
969                                         results.Add (name);
970                         }
971
972
973                         IEnumerable<string> all = Enumerable.Empty<string> ();
974
975                         foreach (Namespace using_ns in namespace_using_table) {
976                                 if (prefix.StartsWith (using_ns.Name)) {
977                                         int ld = prefix.LastIndexOf ('.');
978                                         if (ld != -1) {
979                                                 string rest = prefix.Substring (ld + 1);
980
981                                                 all = all.Concat (using_ns.CompletionGetTypesStartingWith (rest));
982                                         }
983                                 }
984                                 all = all.Concat (using_ns.CompletionGetTypesStartingWith (prefix));
985                         }
986
987                         results.AddRange (all);
988
989                         base.GetCompletionStartingWith (prefix, results);
990                 }
991
992                 
993                 //
994                 // Looks-up a alias named @name in this and surrounding namespace declarations
995                 //
996                 public FullNamedExpression LookupExternAlias (string name)
997                 {
998                         if (aliases == null)
999                                 return null;
1000
1001                         UsingAliasNamespace uan;
1002                         if (aliases.TryGetValue (name, out uan) && uan is UsingExternAlias)
1003                                 return uan.ResolvedExpression;
1004
1005                         return null;
1006                 }
1007                 
1008                 //
1009                 // Looks-up a alias named @name in this and surrounding namespace declarations
1010                 //
1011                 public override FullNamedExpression LookupNamespaceAlias (string name)
1012                 {
1013                         for (NamespaceContainer n = this; n != null; n = n.Parent) {
1014                                 if (n.aliases == null)
1015                                         continue;
1016
1017                                 UsingAliasNamespace uan;
1018                                 if (n.aliases.TryGetValue (name, out uan))
1019                                         return uan.ResolvedExpression;
1020                         }
1021
1022                         return null;
1023                 }
1024
1025                 FullNamedExpression Lookup (string name, int arity, LookupMode mode, Location loc)
1026                 {
1027                         //
1028                         // Check whether it's in the namespace.
1029                         //
1030                         FullNamedExpression fne = ns.LookupTypeOrNamespace (this, name, arity, mode, loc);
1031
1032                         //
1033                         // Check aliases. 
1034                         //
1035                         if (aliases != null && arity == 0) {
1036                                 UsingAliasNamespace uan;
1037                                 if (aliases.TryGetValue (name, out uan)) {
1038                                         if (fne != null) {
1039                                                 // TODO: Namespace has broken location
1040                                                 //Report.SymbolRelatedToPreviousError (fne.Location, null);
1041                                                 Compiler.Report.SymbolRelatedToPreviousError (uan.Location, null);
1042                                                 Compiler.Report.Error (576, loc,
1043                                                         "Namespace `{0}' contains a definition with same name as alias `{1}'",
1044                                                         GetSignatureForError (), name);
1045                                         }
1046
1047                                         return uan.ResolvedExpression;
1048                                 }
1049                         }
1050
1051                         if (fne != null)
1052                                 return fne;
1053
1054                         //
1055                         // Lookup can be called before the namespace is defined from different namespace using alias clause
1056                         //
1057                         if (namespace_using_table == null) {
1058                                 DoDefineNamespace ();
1059                         }
1060
1061                         //
1062                         // Check using entries.
1063                         //
1064                         FullNamedExpression match = null;
1065                         foreach (Namespace using_ns in namespace_using_table) {
1066                                 //
1067                                 // A using directive imports only types contained in the namespace, it
1068                                 // does not import any nested namespaces
1069                                 //
1070                                 fne = using_ns.LookupType (this, name, arity, mode, loc);
1071                                 if (fne == null)
1072                                         continue;
1073
1074                                 if (match == null) {
1075                                         match = fne;
1076                                         continue;
1077                                 }
1078
1079                                 // Prefer types over namespaces
1080                                 var texpr_fne = fne as TypeExpr;
1081                                 var texpr_match = match as TypeExpr;
1082                                 if (texpr_fne != null && texpr_match == null) {
1083                                         match = fne;
1084                                         continue;
1085                                 } else if (texpr_fne == null) {
1086                                         continue;
1087                                 }
1088
1089                                 // It can be top level accessibility only
1090                                 var better = Namespace.IsImportedTypeOverride (Module, texpr_match.Type, texpr_fne.Type);
1091                                 if (better == null) {
1092                                         if (mode == LookupMode.Normal) {
1093                                                 Compiler.Report.SymbolRelatedToPreviousError (texpr_match.Type);
1094                                                 Compiler.Report.SymbolRelatedToPreviousError (texpr_fne.Type);
1095                                                 Compiler.Report.Error (104, loc, "`{0}' is an ambiguous reference between `{1}' and `{2}'",
1096                                                         name, texpr_match.GetSignatureForError (), texpr_fne.GetSignatureForError ());
1097                                         }
1098
1099                                         return match;
1100                                 }
1101
1102                                 if (better == texpr_fne.Type)
1103                                         match = texpr_fne;
1104                         }
1105
1106                         return match;
1107                 }
1108
1109                 static void MsgtryRef (string s)
1110                 {
1111                         Console.WriteLine ("    Try using -r:" + s);
1112                 }
1113
1114                 static void MsgtryPkg (string s)
1115                 {
1116                         Console.WriteLine ("    Try using -pkg:" + s);
1117                 }
1118
1119                 public static void Error_NamespaceNotFound (Location loc, string name, Report Report)
1120                 {
1121                         Report.Error (246, loc, "The type or namespace name `{0}' could not be found. Are you missing a using directive or an assembly reference?",
1122                                 name);
1123
1124                         switch (name) {
1125                         case "Gtk": case "GtkSharp":
1126                                 MsgtryPkg ("gtk-sharp-2.0");
1127                                 break;
1128
1129                         case "Gdk": case "GdkSharp":
1130                                 MsgtryPkg ("gdk-sharp-2.0");
1131                                 break;
1132
1133                         case "Glade": case "GladeSharp":
1134                                 MsgtryPkg ("glade-sharp-2.0");
1135                                 break;
1136
1137                         case "System.Drawing":
1138                         case "System.Web.Services":
1139                         case "System.Web":
1140                         case "System.Data":
1141                         case "System.Windows.Forms":
1142                                 MsgtryRef (name);
1143                                 break;
1144                         }
1145                 }
1146
1147                 protected override void DefineNamespace ()
1148                 {
1149                         if (namespace_using_table == null)
1150                                 DoDefineNamespace ();
1151
1152                         base.DefineNamespace ();
1153                 }
1154
1155                 void DoDefineNamespace ()
1156                 {
1157                         namespace_using_table = empty_namespaces;
1158
1159                         if (clauses != null) {
1160                                 var list = new List<Namespace> (clauses.Count);
1161                                 bool post_process_using_aliases = false;
1162
1163                                 for (int i = 0; i < clauses.Count; ++i) {
1164                                         var entry = clauses[i];
1165
1166                                         if (entry.Alias != null) {
1167                                                 if (aliases == null)
1168                                                         aliases = new Dictionary<string, UsingAliasNamespace> ();
1169
1170                                                 //
1171                                                 // Aliases are not available when resolving using section
1172                                                 // except extern aliases
1173                                                 //
1174                                                 if (entry is UsingExternAlias) {
1175                                                         entry.Define (this);
1176                                                         if (entry.ResolvedExpression != null)
1177                                                                 aliases.Add (entry.Alias.Value, (UsingExternAlias) entry);
1178
1179                                                         clauses.RemoveAt (i--);
1180                                                 } else {
1181                                                         post_process_using_aliases = true;
1182                                                 }
1183
1184                                                 continue;
1185                                         }
1186
1187                                         entry.Define (this);
1188
1189                                         //
1190                                         // It's needed for repl only, when using clause cannot be resolved don't hold it in
1191                                         // global list which is resolved for each evaluation
1192                                         //
1193                                         if (entry.ResolvedExpression == null) {
1194                                                 clauses.RemoveAt (i--);
1195                                                 continue;
1196                                         }
1197
1198                                         Namespace using_ns = entry.ResolvedExpression as Namespace;
1199                                         if (using_ns == null)
1200                                                 continue;
1201
1202                                         if (list.Contains (using_ns)) {
1203                                                 // Ensure we don't report the warning multiple times in repl
1204                                                 clauses.RemoveAt (i--);
1205
1206                                                 Compiler.Report.Warning (105, 3, entry.Location,
1207                                                         "The using directive for `{0}' appeared previously in this namespace", using_ns.GetSignatureForError ());
1208                                         } else {
1209                                                 list.Add (using_ns);
1210                                         }
1211                                 }
1212
1213                                 namespace_using_table = list.ToArray ();
1214
1215                                 if (post_process_using_aliases) {
1216                                         for (int i = 0; i < clauses.Count; ++i) {
1217                                                 var entry = clauses[i];
1218                                                 if (entry.Alias != null) {
1219                                                         entry.Define (this);
1220                                                         if (entry.ResolvedExpression != null) {
1221                                                                 aliases.Add (entry.Alias.Value, (UsingAliasNamespace) entry);
1222                                                         }
1223
1224                                                         clauses.RemoveAt (i--);
1225                                                 }
1226                                         }
1227                                 }
1228                         }
1229                 }
1230
1231                 public void EnableUsingClausesRedefinition ()
1232                 {
1233                         namespace_using_table = null;
1234                 }
1235
1236                 internal override void GenerateDocComment (DocumentationBuilder builder)
1237                 {
1238                         if (containers != null) {
1239                                 foreach (var tc in containers)
1240                                         tc.GenerateDocComment (builder);
1241                         }
1242                 }
1243
1244                 public override string GetSignatureForError ()
1245                 {
1246                         return MemberName == null ? "global::" : base.GetSignatureForError ();
1247                 }
1248
1249                 public override void RemoveContainer (TypeContainer cont)
1250                 {
1251                         base.RemoveContainer (cont);
1252                         NS.RemoveContainer (cont);
1253                 }
1254
1255                 protected override bool VerifyClsCompliance ()
1256                 {
1257                         if (Module.IsClsComplianceRequired ()) {
1258                                 if (MemberName != null && MemberName.Name[0] == '_') {
1259                                         Warning_IdentifierNotCompliant ();
1260                                 }
1261
1262                                 ns.VerifyClsCompliance ();
1263                                 return true;
1264                         }
1265
1266                         return false;
1267                 }
1268         }
1269
1270         public class UsingNamespace
1271         {
1272                 readonly ATypeNameExpression expr;
1273                 readonly Location loc;
1274                 protected FullNamedExpression resolved;
1275
1276                 public UsingNamespace (ATypeNameExpression expr, Location loc)
1277                 {
1278                         this.expr = expr;
1279                         this.loc = loc;
1280                 }
1281
1282                 #region Properties
1283
1284                 public virtual SimpleMemberName Alias {
1285                         get {
1286                                 return null;
1287                         }
1288                 }
1289
1290                 public Location Location {
1291                         get {
1292                                 return loc;
1293                         }
1294                 }
1295
1296                 public ATypeNameExpression NamespaceExpression  {
1297                         get {
1298                                 return expr;
1299                         }
1300                 }
1301
1302                 public FullNamedExpression ResolvedExpression {
1303                         get {
1304                                 return resolved;
1305                         }
1306                 }
1307
1308                 #endregion
1309
1310                 public string GetSignatureForError ()
1311                 {
1312                         return expr.GetSignatureForError ();
1313                 }
1314
1315                 public virtual void Define (NamespaceContainer ctx)
1316                 {
1317                         resolved = expr.ResolveAsTypeOrNamespace (ctx);
1318                         var ns = resolved as Namespace;
1319                         if (ns == null) {
1320                                 if (resolved != null) {
1321                                         ctx.Module.Compiler.Report.SymbolRelatedToPreviousError (resolved.Type);
1322                                         ctx.Module.Compiler.Report.Error (138, Location,
1323                                                 "`{0}' is a type not a namespace. A using namespace directive can only be applied to namespaces",
1324                                                 GetSignatureForError ());
1325                                 }
1326                         }
1327                 }
1328         }
1329
1330         public class UsingExternAlias : UsingAliasNamespace
1331         {
1332                 public UsingExternAlias (SimpleMemberName alias, Location loc)
1333                         : base (alias, null, loc)
1334                 {
1335                 }
1336
1337                 public override void Define (NamespaceContainer ctx)
1338                 {
1339                         resolved = ctx.Module.GetRootNamespace (Alias.Value);
1340                         if (resolved == null) {
1341                                 ctx.Module.Compiler.Report.Error (430, Location,
1342                                         "The extern alias `{0}' was not specified in -reference option",
1343                                         Alias.Value);
1344                         }
1345                 }
1346         }
1347
1348         public class UsingAliasNamespace : UsingNamespace
1349         {
1350                 readonly SimpleMemberName alias;
1351
1352                 public struct AliasContext : IMemberContext
1353                 {
1354                         readonly NamespaceContainer ns;
1355
1356                         public AliasContext (NamespaceContainer ns)
1357                         {
1358                                 this.ns = ns;
1359                         }
1360
1361                         public TypeSpec CurrentType {
1362                                 get {
1363                                         return null;
1364                                 }
1365                         }
1366
1367                         public TypeParameters CurrentTypeParameters {
1368                                 get {
1369                                         return null;
1370                                 }
1371                         }
1372
1373                         public MemberCore CurrentMemberDefinition {
1374                                 get {
1375                                         return null;
1376                                 }
1377                         }
1378
1379                         public bool IsObsolete {
1380                                 get {
1381                                         return false;
1382                                 }
1383                         }
1384
1385                         public bool IsUnsafe {
1386                                 get {
1387                                         throw new NotImplementedException ();
1388                                 }
1389                         }
1390
1391                         public bool IsStatic {
1392                                 get {
1393                                         throw new NotImplementedException ();
1394                                 }
1395                         }
1396
1397                         public ModuleContainer Module {
1398                                 get {
1399                                         return ns.Module;
1400                                 }
1401                         }
1402
1403                         public string GetSignatureForError ()
1404                         {
1405                                 throw new NotImplementedException ();
1406                         }
1407
1408                         public ExtensionMethodCandidates LookupExtensionMethod (TypeSpec extensionType, string name, int arity)
1409                         {
1410                                 return null;
1411                         }
1412
1413                         public FullNamedExpression LookupNamespaceOrType (string name, int arity, LookupMode mode, Location loc)
1414                         {
1415                                 var fne = ns.NS.LookupTypeOrNamespace (ns, name, arity, mode, loc);
1416                                 if (fne != null)
1417                                         return fne;
1418
1419                                 //
1420                                 // Only extern aliases are allowed in this context
1421                                 //
1422                                 fne = ns.LookupExternAlias (name);
1423                                 if (fne != null || ns.MemberName == null)
1424                                         return fne;
1425
1426                                 var container_ns = ns.NS.Parent;
1427                                 var mn = ns.MemberName.Left;
1428                                 while (mn != null) {
1429                                         fne = container_ns.LookupTypeOrNamespace (this, name, arity, mode, loc);
1430                                         if (fne != null)
1431                                                 return fne;
1432
1433                                         mn = mn.Left;
1434                                         container_ns = container_ns.Parent;
1435                                 }
1436
1437                                 if (ns.Parent != null)
1438                                         return ns.Parent.LookupNamespaceOrType (name, arity, mode, loc);
1439
1440                                 return null;
1441                         }
1442
1443                         public FullNamedExpression LookupNamespaceAlias (string name)
1444                         {
1445                                 return ns.LookupNamespaceAlias (name);
1446                         }
1447                 }
1448
1449                 public UsingAliasNamespace (SimpleMemberName alias, ATypeNameExpression expr, Location loc)
1450                         : base (expr, loc)
1451                 {
1452                         this.alias = alias;
1453                 }
1454
1455                 public override SimpleMemberName Alias {
1456                         get {
1457                                 return alias;
1458                         }
1459                 }
1460
1461                 public override void Define (NamespaceContainer ctx)
1462                 {
1463                         //
1464                         // The namespace-or-type-name of a using-alias-directive is resolved as if
1465                         // the immediately containing compilation unit or namespace body had no
1466                         // using-directives. A using-alias-directive may however be affected
1467                         // by extern-alias-directives in the immediately containing compilation
1468                         // unit or namespace body
1469                         //
1470                         // We achieve that by introducing alias-context which redirect any local
1471                         // namespace or type resolve calls to parent namespace
1472                         //
1473                         resolved = NamespaceExpression.ResolveAsTypeOrNamespace (new AliasContext (ctx));
1474                 }
1475         }
1476 }