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