2 // namespace.cs: Tracks namespaces
5 // Miguel de Icaza (miguel@ximian.com)
6 // Marek Safar (marek.safar@seznam.cz)
8 // Copyright 2001 Ximian, Inc.
9 // Copyright 2003-2008 Novell, Inc.
10 // Copyright 2011 Xamarin Inc
13 using System.Collections.Generic;
15 using Mono.CompilerServices.SymbolWriter;
17 namespace Mono.CSharp {
19 public class RootNamespace : Namespace {
21 readonly string alias_name;
22 readonly Dictionary<string, Namespace> all_namespaces;
24 public RootNamespace (string alias_name)
27 this.alias_name = alias_name;
28 RegisterNamespace (this);
30 all_namespaces = new Dictionary<string, Namespace> ();
31 all_namespaces.Add ("", this);
40 public static void Error_GlobalNamespaceRedefined (Report report, Location loc)
42 report.Error (1681, loc, "The global extern alias cannot be redefined");
46 // For better error reporting where we try to guess missing using directive
48 public List<string> FindTypeNamespaces (IMemberContext ctx, string name, int arity)
50 List<string> res = null;
52 foreach (var ns in all_namespaces) {
53 var type = ns.Value.LookupType (ctx, name, arity, LookupMode.Normal, Location.Null);
56 res = new List<string> ();
66 // For better error reporting where compiler tries to guess missing using directive
68 public List<string> FindExtensionMethodNamespaces (IMemberContext ctx, string name, int arity)
70 List<string> res = null;
72 foreach (var ns in all_namespaces) {
73 var methods = ns.Value.LookupExtensionMethod (ctx, name, arity);
74 if (methods != null) {
76 res = new List<string> ();
85 public void RegisterNamespace (Namespace child)
88 all_namespaces.Add (child.Name, child);
91 public override string GetSignatureForError ()
93 return alias_name + "::";
97 public sealed class GlobalRootNamespace : RootNamespace
99 public GlobalRootNamespace ()
106 // Namespace cache for imported and compiled namespaces
108 public class Namespace
110 readonly Namespace parent;
112 protected Dictionary<string, Namespace> namespaces;
113 protected Dictionary<string, IList<TypeSpec>> types;
114 List<TypeSpec> extension_method_types;
115 Dictionary<string, TypeSpec> cached_types;
119 /// Constructor Takes the current namespace and the
120 /// name. This is bootstrapped with parent == null
123 public Namespace (Namespace parent, string name)
127 throw new ArgumentNullException ("name");
129 this.parent = parent;
131 string pname = parent != null ? parent.fullname : null;
136 fullname = pname + "." + name;
138 while (parent.parent != null)
139 parent = parent.parent;
141 var root = parent as RootNamespace;
143 throw new InternalErrorException ("Root namespaces must be created using RootNamespace");
145 root.RegisterNamespace (this);
148 protected Namespace ()
150 namespaces = new Dictionary<string, Namespace> ();
151 cached_types = new Dictionary<string, TypeSpec> ();
157 /// The qualified name of the current namespace
160 get { return fullname; }
164 /// The parent of this namespace, used by the parser to "Pop"
165 /// the current namespace declaration
167 public Namespace Parent {
168 get { return parent; }
173 public Namespace AddNamespace (MemberName name)
175 var ns_parent = name.Left == null ? this : AddNamespace (name.Left);
176 return ns_parent.TryAddNamespace (name.Basename);
179 Namespace TryAddNamespace (string name)
183 if (!namespaces.TryGetValue (name, out ns)) {
184 ns = new Namespace (this, name);
185 namespaces.Add (name, ns);
191 public bool TryGetNamespace (string name, out Namespace ns)
193 return namespaces.TryGetValue (name, out ns);
196 // TODO: Replace with CreateNamespace where MemberName is created for the method call
197 public Namespace GetNamespace (string name, bool create)
199 int pos = name.IndexOf ('.');
204 first = name.Substring (0, pos);
208 if (!namespaces.TryGetValue (first, out ns)) {
212 ns = new Namespace (this, first);
213 namespaces.Add (first, ns);
217 ns = ns.GetNamespace (name.Substring (pos + 1), create);
222 public IList<TypeSpec> GetAllTypes (string name)
224 IList<TypeSpec> found;
225 if (types == null || !types.TryGetValue (name, out found))
231 public virtual string GetSignatureForError ()
236 public TypeSpec LookupType (IMemberContext ctx, string name, int arity, LookupMode mode, Location loc)
241 TypeSpec best = null;
242 if (arity == 0 && cached_types.TryGetValue (name, out best)) {
243 if (best != null || mode != LookupMode.IgnoreAccessibility)
247 IList<TypeSpec> found;
248 if (!types.TryGetValue (name, out found))
251 foreach (var ts in found) {
252 if (ts.Arity == arity) {
254 if ((ts.Modifiers & Modifiers.INTERNAL) != 0 && !ts.MemberDefinition.IsInternalAsPublic (ctx.Module.DeclaringAssembly) && mode != LookupMode.IgnoreAccessibility)
261 if (best.MemberDefinition.IsImported && ts.MemberDefinition.IsImported) {
262 if (ts.Kind == MemberKind.MissingType)
265 if (best.Kind == MemberKind.MissingType) {
270 if (mode == LookupMode.Normal) {
271 ctx.Module.Compiler.Report.SymbolRelatedToPreviousError (best);
272 ctx.Module.Compiler.Report.SymbolRelatedToPreviousError (ts);
273 ctx.Module.Compiler.Report.Error (433, loc, "The imported type `{0}' is defined multiple times", ts.GetSignatureForError ());
279 if (best.MemberDefinition.IsImported)
282 if ((best.Modifiers & Modifiers.INTERNAL) != 0 && !best.MemberDefinition.IsInternalAsPublic (ctx.Module.DeclaringAssembly))
285 if (mode != LookupMode.Normal)
288 if (ts.MemberDefinition.IsImported) {
289 ctx.Module.Compiler.Report.SymbolRelatedToPreviousError (best);
290 ctx.Module.Compiler.Report.SymbolRelatedToPreviousError (ts);
293 ctx.Module.Compiler.Report.Warning (436, 2, loc,
294 "The type `{0}' conflicts with the imported type of same name'. Ignoring the imported type definition",
295 best.GetSignatureForError ());
299 // Lookup for the best candidate with the closest arity match
304 } else if (System.Math.Abs (ts.Arity + arity) < System.Math.Abs (best.Arity + arity)) {
310 // TODO MemberCache: Cache more
311 if (arity == 0 && mode == LookupMode.Normal)
312 cached_types.Add (name, best);
317 public FullNamedExpression LookupTypeOrNamespace (IMemberContext ctx, string name, int arity, LookupMode mode, Location loc)
319 var texpr = LookupType (ctx, name, arity, mode, loc);
322 if (arity == 0 && namespaces.TryGetValue (name, out ns)) {
324 return new NamespaceExpression (ns, loc);
326 if (mode != LookupMode.Probing) {
327 //ctx.Module.Compiler.Report.SymbolRelatedToPreviousError (texpr.Type);
328 // ctx.Module.Compiler.Report.SymbolRelatedToPreviousError (ns.loc, "");
329 ctx.Module.Compiler.Report.Warning (437, 2, loc,
330 "The type `{0}' conflicts with the imported namespace `{1}'. Using the definition found in the source file",
331 texpr.GetSignatureForError (), ns.GetSignatureForError ());
334 if (texpr.MemberDefinition.IsImported)
335 return new NamespaceExpression (ns, loc);
341 return new TypeExpression (texpr, loc);
345 // Completes types with the given `prefix'
347 public IEnumerable<string> CompletionGetTypesStartingWith (string prefix)
350 return Enumerable.Empty<string> ();
352 var res = from item in types
353 where item.Key.StartsWith (prefix) && item.Value.Any (l => (l.Modifiers & Modifiers.PUBLIC) != 0)
356 if (namespaces != null)
357 res = res.Concat (from item in namespaces where item.Key.StartsWith (prefix) select item.Key);
363 // Looks for extension method in this namespace
365 public List<MethodSpec> LookupExtensionMethod (IMemberContext invocationContext, string name, int arity)
367 if (extension_method_types == null)
370 List<MethodSpec> found = null;
371 for (int i = 0; i < extension_method_types.Count; ++i) {
372 var ts = extension_method_types[i];
375 // When the list was built we didn't know what members the type
378 if ((ts.Modifiers & Modifiers.METHOD_EXTENSION) == 0) {
379 if (extension_method_types.Count == 1) {
380 extension_method_types = null;
384 extension_method_types.RemoveAt (i--);
388 var res = ts.MemberCache.FindExtensionMethods (invocationContext, name, arity);
395 found.AddRange (res);
402 public void AddType (ModuleContainer module, TypeSpec ts)
405 types = new Dictionary<string, IList<TypeSpec>> (64);
408 if (ts.IsClass && ts.Arity == 0) {
409 var extension_method_allowed = ts.MemberDefinition.IsImported ? (ts.Modifiers & Modifiers.METHOD_EXTENSION) != 0 : (ts.IsStatic || ts.MemberDefinition.IsPartial);
410 if (extension_method_allowed) {
411 if (extension_method_types == null)
412 extension_method_types = new List<TypeSpec> ();
414 extension_method_types.Add (ts);
419 IList<TypeSpec> existing;
420 if (types.TryGetValue (name, out existing)) {
421 TypeSpec better_type;
423 if (existing.Count == 1) {
425 if (ts.Arity == found.Arity) {
426 better_type = IsImportedTypeOverride (module, ts, found);
427 if (better_type == found)
430 if (better_type != null) {
431 existing [0] = better_type;
436 existing = new List<TypeSpec> ();
437 existing.Add (found);
438 types[name] = existing;
440 for (int i = 0; i < existing.Count; ++i) {
442 if (ts.Arity != found.Arity)
445 better_type = IsImportedTypeOverride (module, ts, found);
446 if (better_type == found)
449 if (better_type != null) {
450 existing.RemoveAt (i);
459 types.Add (name, new TypeSpec[] { ts });
464 // We import any types but in the situation there are same types
465 // but one has better visibility (either public or internal with friend)
466 // the less visible type is removed from the namespace cache
468 public static TypeSpec IsImportedTypeOverride (ModuleContainer module, TypeSpec ts, TypeSpec found)
470 var ts_accessible = (ts.Modifiers & Modifiers.PUBLIC) != 0 || ts.MemberDefinition.IsInternalAsPublic (module.DeclaringAssembly);
471 var found_accessible = (found.Modifiers & Modifiers.PUBLIC) != 0 || found.MemberDefinition.IsInternalAsPublic (module.DeclaringAssembly);
473 if (ts_accessible && !found_accessible)
476 // found is better always better for accessible or inaccessible ts
483 public void RemoveContainer (TypeContainer tc)
485 types.Remove (tc.Basename);
486 cached_types.Remove (tc.Basename);
489 public void SetBuiltinType (BuiltinTypeSpec pts)
491 var found = types[pts.Name];
492 cached_types.Remove (pts.Name);
493 if (found.Count == 1) {
494 types[pts.Name][0] = pts;
496 throw new NotImplementedException ();
500 public void VerifyClsCompliance ()
502 if (types == null || cls_checked)
507 // TODO: This is quite ugly way to check for CLS compliance at namespace level
509 var locase_types = new Dictionary<string, List<TypeSpec>> (StringComparer.OrdinalIgnoreCase);
510 foreach (var tgroup in types.Values) {
511 foreach (var tm in tgroup) {
512 if ((tm.Modifiers & Modifiers.PUBLIC) == 0 || !tm.IsCLSCompliant ())
515 List<TypeSpec> found;
516 if (!locase_types.TryGetValue (tm.Name, out found)) {
517 found = new List<TypeSpec> ();
518 locase_types.Add (tm.Name, found);
525 foreach (var locase in locase_types.Values) {
526 if (locase.Count < 2)
529 bool all_same = true;
530 foreach (var notcompliant in locase) {
531 all_same = notcompliant.Name == locase[0].Name;
539 TypeContainer compiled = null;
540 foreach (var notcompliant in locase) {
541 if (!notcompliant.MemberDefinition.IsImported) {
542 if (compiled != null)
543 compiled.Compiler.Report.SymbolRelatedToPreviousError (compiled);
545 compiled = notcompliant.MemberDefinition as TypeContainer;
547 compiled.Compiler.Report.SymbolRelatedToPreviousError (notcompliant);
551 compiled.Compiler.Report.Warning (3005, 1, compiled.Location,
552 "Identifier `{0}' differing only in case is not CLS-compliant", compiled.GetSignatureForError ());
557 public class CompilationSourceFile : NamespaceContainer
559 readonly SourceFile file;
560 CompileUnitEntry comp_unit;
561 Dictionary<string, SourceFile> include_files;
562 Dictionary<string, bool> conditionals;
564 public CompilationSourceFile (ModuleContainer parent, SourceFile sourceFile)
567 this.file = sourceFile;
570 public CompilationSourceFile (ModuleContainer parent)
575 public CompileUnitEntry SymbolUnitEntry {
581 public string FileName {
587 public SourceFile SourceFile {
593 public void AddIncludeFile (SourceFile file)
595 if (file == this.file)
598 if (include_files == null)
599 include_files = new Dictionary<string, SourceFile> ();
601 if (!include_files.ContainsKey (file.FullPathName))
602 include_files.Add (file.FullPathName, file);
605 public void AddDefine (string value)
607 if (conditionals == null)
608 conditionals = new Dictionary<string, bool> (2);
610 conditionals[value] = true;
613 public void AddUndefine (string value)
615 if (conditionals == null)
616 conditionals = new Dictionary<string, bool> (2);
618 conditionals[value] = false;
621 public override void PrepareEmit ()
623 var sw = Module.DeclaringAssembly.SymbolWriter;
625 CreateUnitSymbolInfo (sw);
632 // Creates symbol file index in debug symbol file
634 void CreateUnitSymbolInfo (MonoSymbolFile symwriter)
636 var si = file.CreateSymbolInfo (symwriter);
637 comp_unit = new CompileUnitEntry (symwriter, si);
639 if (include_files != null) {
640 foreach (SourceFile include in include_files.Values) {
641 si = include.CreateSymbolInfo (symwriter);
642 comp_unit.AddFile (si);
647 public bool IsConditionalDefined (string value)
649 if (conditionals != null) {
651 if (conditionals.TryGetValue (value, out res))
654 // When conditional was undefined
655 if (conditionals.ContainsKey (value))
659 return Compiler.Settings.IsConditionalSymbolDefined (value);
662 public override void Accept (StructuralVisitor visitor)
664 visitor.Visit (this);
670 // Namespace block as created by the parser
672 public class NamespaceContainer : TypeContainer, IMemberContext
674 static readonly Namespace[] empty_namespaces = new Namespace[0];
676 readonly Namespace ns;
678 public new readonly NamespaceContainer Parent;
680 List<UsingNamespace> clauses;
682 // Used by parsed to check for parser errors
683 public bool DeclarationFound;
685 Namespace[] namespace_using_table;
686 TypeSpec[] types_using_table;
687 Dictionary<string, UsingAliasNamespace> aliases;
689 public NamespaceContainer (MemberName name, NamespaceContainer parent)
690 : base (parent, name, null, MemberKind.Namespace)
692 this.Parent = parent;
693 this.ns = parent.NS.AddNamespace (name);
695 containers = new List<TypeContainer> ();
698 protected NamespaceContainer (ModuleContainer parent)
699 : base (parent, null, null, MemberKind.Namespace)
701 ns = parent.GlobalRootNamespace;
702 containers = new List<TypeContainer> (2);
707 public override AttributeTargets AttributeTargets {
709 throw new NotSupportedException ();
713 public override string DocCommentHeader {
715 throw new NotSupportedException ();
719 public Namespace NS {
725 public List<UsingNamespace> Usings {
731 public override string[] ValidAttributeTargets {
733 throw new NotSupportedException ();
739 public void AddUsing (UsingNamespace un)
741 if (DeclarationFound){
742 Compiler.Report.Error (1529, un.Location, "A using clause must precede all other namespace elements except extern alias declarations");
746 clauses = new List<UsingNamespace> ();
751 public void AddUsing (UsingAliasNamespace un)
753 if (DeclarationFound){
754 Compiler.Report.Error (1529, un.Location, "A using clause must precede all other namespace elements except extern alias declarations");
760 void AddAlias (UsingAliasNamespace un)
762 if (clauses == null) {
763 clauses = new List<UsingNamespace> ();
765 foreach (var entry in clauses) {
766 var a = entry as UsingAliasNamespace;
767 if (a != null && a.Alias.Value == un.Alias.Value) {
768 Compiler.Report.SymbolRelatedToPreviousError (a.Location, "");
769 Compiler.Report.Error (1537, un.Location,
770 "The using alias `{0}' appeared previously in this namespace", un.Alias.Value);
778 public override void AddPartial (TypeDefinition next_part)
780 var existing = ns.LookupType (this, next_part.MemberName.Name, next_part.MemberName.Arity, LookupMode.Probing, Location.Null);
781 var td = existing != null ? existing.MemberDefinition as TypeDefinition : null;
782 AddPartial (next_part, td);
785 public override void AddTypeContainer (TypeContainer tc)
787 string name = tc.Basename;
789 var mn = tc.MemberName;
790 while (mn.Left != null) {
795 var names_container = Parent == null ? Module : (TypeContainer) this;
798 if (names_container.DefinedNames.TryGetValue (name, out mc)) {
799 if (tc is NamespaceContainer && mc is NamespaceContainer) {
800 AddTypeContainerMember (tc);
804 Report.SymbolRelatedToPreviousError (mc);
805 if ((mc.ModFlags & Modifiers.PARTIAL) != 0 && (tc is ClassOrStruct || tc is Interface)) {
806 Error_MissingPartialModifier (tc);
808 Report.Error (101, tc.Location, "The namespace `{0}' already contains a definition for `{1}'",
809 GetSignatureForError (), mn.GetSignatureForError ());
812 names_container.DefinedNames.Add (name, tc);
814 var tdef = tc.PartialContainer;
817 // Same name conflict in different namespace containers
819 var conflict = ns.GetAllTypes (name);
820 if (conflict != null) {
821 foreach (var e in conflict) {
822 if (e.Arity == mn.Arity) {
823 mc = (MemberCore) e.MemberDefinition;
830 Report.SymbolRelatedToPreviousError (mc);
831 Report.Error (101, tc.Location, "The namespace `{0}' already contains a definition for `{1}'",
832 GetSignatureForError (), mn.GetSignatureForError ());
834 ns.AddType (Module, tdef.Definition);
839 base.AddTypeContainer (tc);
842 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
844 throw new NotSupportedException ();
847 public override void EmitContainer ()
849 VerifyClsCompliance ();
851 base.EmitContainer ();
854 public ExtensionMethodCandidates LookupExtensionMethod (IMemberContext invocationContext, TypeSpec extensionType, string name, int arity, int position)
857 // Here we try to resume the search for extension method at the point
858 // where the last bunch of candidates was found. It's more tricky than
859 // it seems as we have to check both namespace containers and namespace
867 // <our first search found candidates in A.B.C.D
871 // In the example above namespace A.B.C.D, A.B.C and A.B have to be
872 // checked before we hit A.N1 using
874 ExtensionMethodCandidates candidates;
875 var container = this;
877 candidates = container.LookupExtensionMethodCandidates (invocationContext, name, arity, ref position);
878 if (candidates != null || container.MemberName == null)
881 var container_ns = container.ns.Parent;
882 var mn = container.MemberName.Left;
883 int already_checked = position - 2;
884 while (already_checked-- > 0) {
886 container_ns = container_ns.Parent;
892 var methods = container_ns.LookupExtensionMethod (invocationContext, name, arity);
893 if (methods != null) {
894 return new ExtensionMethodCandidates (invocationContext, methods, container, position);
898 container_ns = container_ns.Parent;
902 container = container.Parent;
903 } while (container != null);
908 ExtensionMethodCandidates LookupExtensionMethodCandidates (IMemberContext invocationContext, string name, int arity, ref int position)
910 List<MethodSpec> candidates = null;
915 candidates = ns.LookupExtensionMethod (invocationContext, name, arity);
916 if (candidates != null) {
917 return new ExtensionMethodCandidates (invocationContext, candidates, this, position);
924 foreach (Namespace n in namespace_using_table) {
925 var a = n.LookupExtensionMethod (invocationContext, name, arity);
929 if (candidates == null)
932 candidates.AddRange (a);
935 if (candidates != null)
936 return new ExtensionMethodCandidates (invocationContext, candidates, this, position);
939 // LAMESPEC: TODO no spec about priority over normal extension methods yet
940 if (types_using_table != null) {
941 foreach (var t in types_using_table) {
943 var res = t.MemberCache.FindExtensionMethods (invocationContext, name, arity);
947 if (candidates == null)
950 candidates.AddRange (res);
953 if (candidates != null)
954 return new ExtensionMethodCandidates (invocationContext, candidates, this, position);
960 public override FullNamedExpression LookupNamespaceOrType (string name, int arity, LookupMode mode, Location loc)
963 // Only simple names (no dots) will be looked up with this function
965 FullNamedExpression resolved;
966 for (NamespaceContainer container = this; container != null; container = container.Parent) {
967 resolved = container.Lookup (name, arity, mode, loc);
968 if (resolved != null || container.MemberName == null)
971 var container_ns = container.ns.Parent;
972 var mn = container.MemberName.Left;
974 resolved = container_ns.LookupTypeOrNamespace (this, name, arity, mode, loc);
975 if (resolved != null)
979 container_ns = container_ns.Parent;
986 public override void GetCompletionStartingWith (string prefix, List<string> results)
991 foreach (var un in Usings) {
992 if (un.Alias != null)
995 var name = un.NamespaceExpression.Name;
996 if (name.StartsWith (prefix))
1001 IEnumerable<string> all = Enumerable.Empty<string> ();
1003 foreach (Namespace using_ns in namespace_using_table) {
1004 if (prefix.StartsWith (using_ns.Name)) {
1005 int ld = prefix.LastIndexOf ('.');
1007 string rest = prefix.Substring (ld + 1);
1009 all = all.Concat (using_ns.CompletionGetTypesStartingWith (rest));
1012 all = all.Concat (using_ns.CompletionGetTypesStartingWith (prefix));
1015 results.AddRange (all);
1017 base.GetCompletionStartingWith (prefix, results);
1022 // Looks-up a alias named @name in this and surrounding namespace declarations
1024 public FullNamedExpression LookupExternAlias (string name)
1026 if (aliases == null)
1029 UsingAliasNamespace uan;
1030 if (aliases.TryGetValue (name, out uan) && uan is UsingExternAlias)
1031 return uan.ResolvedExpression;
1037 // Looks-up a alias named @name in this and surrounding namespace declarations
1039 public override FullNamedExpression LookupNamespaceAlias (string name)
1041 for (NamespaceContainer n = this; n != null; n = n.Parent) {
1042 if (n.aliases == null)
1045 UsingAliasNamespace uan;
1046 if (n.aliases.TryGetValue (name, out uan))
1047 return uan.ResolvedExpression;
1053 FullNamedExpression Lookup (string name, int arity, LookupMode mode, Location loc)
1056 // Check whether it's in the namespace.
1058 FullNamedExpression fne = ns.LookupTypeOrNamespace (this, name, arity, mode, loc);
1063 if (aliases != null && arity == 0) {
1064 UsingAliasNamespace uan;
1065 if (aliases.TryGetValue (name, out uan)) {
1066 if (fne != null && mode != LookupMode.Probing) {
1067 // TODO: Namespace has broken location
1068 //Report.SymbolRelatedToPreviousError (fne.Location, null);
1069 Compiler.Report.SymbolRelatedToPreviousError (uan.Location, null);
1070 Compiler.Report.Error (576, loc,
1071 "Namespace `{0}' contains a definition with same name as alias `{1}'",
1072 GetSignatureForError (), name);
1075 return uan.ResolvedExpression;
1083 // Lookup can be called before the namespace is defined from different namespace using alias clause
1085 if (namespace_using_table == null) {
1086 DoDefineNamespace ();
1090 // Check using entries.
1092 FullNamedExpression match = null;
1093 foreach (Namespace using_ns in namespace_using_table) {
1095 // A using directive imports only types contained in the namespace, it
1096 // does not import any nested namespaces
1098 var t = using_ns.LookupType (this, name, arity, mode, loc);
1102 fne = new TypeExpression (t, loc);
1103 if (match == null) {
1108 // Prefer types over namespaces
1109 var texpr_fne = fne as TypeExpr;
1110 var texpr_match = match as TypeExpr;
1111 if (texpr_fne != null && texpr_match == null) {
1114 } else if (texpr_fne == null) {
1118 // It can be top level accessibility only
1119 var better = Namespace.IsImportedTypeOverride (Module, texpr_match.Type, texpr_fne.Type);
1120 if (better == null) {
1121 if (mode == LookupMode.Normal) {
1122 Compiler.Report.SymbolRelatedToPreviousError (texpr_match.Type);
1123 Compiler.Report.SymbolRelatedToPreviousError (texpr_fne.Type);
1124 Compiler.Report.Error (104, loc, "`{0}' is an ambiguous reference between `{1}' and `{2}'",
1125 name, texpr_match.GetSignatureForError (), texpr_fne.GetSignatureForError ());
1131 if (better == texpr_fne.Type)
1138 public static MethodGroupExpr LookupStaticUsings (IMemberContext mc, string name, int arity, Location loc)
1140 for (var m = mc.CurrentMemberDefinition; m != null; m = m.Parent) {
1142 var nc = m as NamespaceContainer;
1146 List<MemberSpec> candidates = null;
1147 if (nc.types_using_table != null) {
1148 foreach (var using_type in nc.types_using_table) {
1149 var members = MemberCache.FindMembers (using_type, name, true);
1150 if (members != null) {
1151 foreach (var member in members) {
1152 if ((member.Modifiers & Modifiers.METHOD_EXTENSION) != 0)
1155 if (arity > 0 && member.Arity != arity)
1158 if (candidates == null)
1159 candidates = new List<MemberSpec> ();
1161 candidates.Add (member);
1167 if (candidates != null)
1168 return new MethodGroupExpr (candidates, null, loc);
1174 protected override void DefineNamespace ()
1176 if (namespace_using_table == null)
1177 DoDefineNamespace ();
1179 base.DefineNamespace ();
1182 void DoDefineNamespace ()
1184 namespace_using_table = empty_namespaces;
1186 if (clauses != null) {
1187 List<Namespace> namespaces = null;
1188 List<TypeSpec> types = null;
1190 bool post_process_using_aliases = false;
1192 for (int i = 0; i < clauses.Count; ++i) {
1193 var entry = clauses[i];
1195 if (entry.Alias != null) {
1196 if (aliases == null)
1197 aliases = new Dictionary<string, UsingAliasNamespace> ();
1200 // Aliases are not available when resolving using section
1201 // except extern aliases
1203 if (entry is UsingExternAlias) {
1204 entry.Define (this);
1205 if (entry.ResolvedExpression != null)
1206 aliases.Add (entry.Alias.Value, (UsingExternAlias) entry);
1208 clauses.RemoveAt (i--);
1210 post_process_using_aliases = true;
1216 entry.Define (this);
1219 // It's needed for repl only, when using clause cannot be resolved don't hold it in
1220 // global list which is resolved for each evaluation
1222 if (entry.ResolvedExpression == null) {
1223 clauses.RemoveAt (i--);
1227 var using_ns = entry.ResolvedExpression as NamespaceExpression;
1228 if (using_ns == null) {
1230 var type = ((TypeExpr)entry.ResolvedExpression).Type;
1233 types = new List<TypeSpec> ();
1235 if (types.Contains (type)) {
1236 Warning_DuplicateEntry (entry);
1241 if (namespaces == null)
1242 namespaces = new List<Namespace> ();
1244 if (namespaces.Contains (using_ns.Namespace)) {
1245 // Ensure we don't report the warning multiple times in repl
1246 clauses.RemoveAt (i--);
1248 Warning_DuplicateEntry (entry);
1250 namespaces.Add (using_ns.Namespace);
1255 namespace_using_table = namespaces == null ? new Namespace [0] : namespaces.ToArray ();
1257 types_using_table = types.ToArray ();
1259 if (post_process_using_aliases) {
1260 for (int i = 0; i < clauses.Count; ++i) {
1261 var entry = clauses[i];
1262 if (entry.Alias != null) {
1263 entry.Define (this);
1264 if (entry.ResolvedExpression != null) {
1265 aliases.Add (entry.Alias.Value, (UsingAliasNamespace) entry);
1268 clauses.RemoveAt (i--);
1275 public void EnableRedefinition ()
1278 namespace_using_table = null;
1281 internal override void GenerateDocComment (DocumentationBuilder builder)
1283 if (containers != null) {
1284 foreach (var tc in containers)
1285 tc.GenerateDocComment (builder);
1289 public override string GetSignatureForError ()
1291 return MemberName == null ? "global::" : base.GetSignatureForError ();
1294 public override void RemoveContainer (TypeContainer cont)
1296 base.RemoveContainer (cont);
1297 NS.RemoveContainer (cont);
1300 protected override bool VerifyClsCompliance ()
1302 if (Module.IsClsComplianceRequired ()) {
1303 if (MemberName != null && MemberName.Name[0] == '_') {
1304 Warning_IdentifierNotCompliant ();
1307 ns.VerifyClsCompliance ();
1314 void Warning_DuplicateEntry (UsingNamespace entry)
1316 Compiler.Report.Warning (105, 3, entry.Location,
1317 "The using directive for `{0}' appeared previously in this namespace",
1318 entry.ResolvedExpression.GetSignatureForError ());
1321 public override void Accept (StructuralVisitor visitor)
1323 visitor.Visit (this);
1327 public class UsingNamespace
1329 readonly ATypeNameExpression expr;
1330 readonly Location loc;
1331 protected FullNamedExpression resolved;
1333 public UsingNamespace (ATypeNameExpression expr, Location loc)
1341 public virtual SimpleMemberName Alias {
1347 public Location Location {
1353 public ATypeNameExpression NamespaceExpression {
1359 public FullNamedExpression ResolvedExpression {
1367 public string GetSignatureForError ()
1369 return expr.GetSignatureForError ();
1372 public virtual void Define (NamespaceContainer ctx)
1374 resolved = expr.ResolveAsTypeOrNamespace (ctx);
1375 var ns = resolved as NamespaceExpression;
1379 if (resolved != null) {
1380 var compiler = ctx.Module.Compiler;
1381 var type = resolved.Type;
1382 if (compiler.Settings.Version >= LanguageVersion.V_6) {
1383 if (!type.IsClass || !type.IsStatic) {
1384 compiler.Report.SymbolRelatedToPreviousError (type);
1385 compiler.Report.Error (7007, Location,
1386 "`{0}' is not a static class. A using namespace directive can only be applied to static classes or namespace",
1387 GetSignatureForError ());
1393 compiler.Report.SymbolRelatedToPreviousError (type);
1394 compiler.Report.Error (138, Location,
1395 "`{0}' is a type not a namespace. A using namespace directive can only be applied to namespaces",
1396 GetSignatureForError ());
1400 public override string ToString()
1402 return resolved.ToString();
1406 public class UsingExternAlias : UsingAliasNamespace
1408 public UsingExternAlias (SimpleMemberName alias, Location loc)
1409 : base (alias, null, loc)
1413 public override void Define (NamespaceContainer ctx)
1415 var ns = ctx.Module.GetRootNamespace (Alias.Value);
1417 ctx.Module.Compiler.Report.Error (430, Location,
1418 "The extern alias `{0}' was not specified in -reference option",
1423 resolved = new NamespaceExpression (ns, Location);
1427 public class UsingAliasNamespace : UsingNamespace
1429 readonly SimpleMemberName alias;
1431 public struct AliasContext : IMemberContext
1433 readonly NamespaceContainer ns;
1435 public AliasContext (NamespaceContainer ns)
1440 public TypeSpec CurrentType {
1446 public TypeParameters CurrentTypeParameters {
1452 public MemberCore CurrentMemberDefinition {
1458 public bool IsObsolete {
1464 public bool IsUnsafe {
1466 throw new NotImplementedException ();
1470 public bool IsStatic {
1472 throw new NotImplementedException ();
1476 public ModuleContainer Module {
1482 public string GetSignatureForError ()
1484 throw new NotImplementedException ();
1487 public ExtensionMethodCandidates LookupExtensionMethod (TypeSpec extensionType, string name, int arity)
1492 public FullNamedExpression LookupNamespaceOrType (string name, int arity, LookupMode mode, Location loc)
1494 var fne = ns.NS.LookupTypeOrNamespace (ns, name, arity, mode, loc);
1499 // Only extern aliases are allowed in this context
1501 fne = ns.LookupExternAlias (name);
1502 if (fne != null || ns.MemberName == null)
1505 var container_ns = ns.NS.Parent;
1506 var mn = ns.MemberName.Left;
1507 while (mn != null) {
1508 fne = container_ns.LookupTypeOrNamespace (this, name, arity, mode, loc);
1513 container_ns = container_ns.Parent;
1516 if (ns.Parent != null)
1517 return ns.Parent.LookupNamespaceOrType (name, arity, mode, loc);
1522 public FullNamedExpression LookupNamespaceAlias (string name)
1524 return ns.LookupNamespaceAlias (name);
1528 public UsingAliasNamespace (SimpleMemberName alias, ATypeNameExpression expr, Location loc)
1534 public override SimpleMemberName Alias {
1540 public override void Define (NamespaceContainer ctx)
1543 // The namespace-or-type-name of a using-alias-directive is resolved as if
1544 // the immediately containing compilation unit or namespace body had no
1545 // using-directives. A using-alias-directive may however be affected
1546 // by extern-alias-directives in the immediately containing compilation
1547 // unit or namespace body
1549 // We achieve that by introducing alias-context which redirect any local
1550 // namespace or type resolve calls to parent namespace
1552 resolved = NamespaceExpression.ResolveAsTypeOrNamespace (new AliasContext (ctx));