PageRenderTime 78ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 1ms

/mcs/mcs/class.cs

https://bitbucket.org/danipen/mono
C# | 3651 lines | 2682 code | 645 blank | 324 comment | 882 complexity | 925afe5e700c847677d859e41ac7fc89 MD5 | raw file
Possible License(s): Unlicense, Apache-2.0, LGPL-2.0, MPL-2.0-no-copyleft-exception, CC-BY-SA-3.0, GPL-2.0
  1. //
  2. // class.cs: Class and Struct handlers
  3. //
  4. // Authors: Miguel de Icaza (miguel@gnu.org)
  5. // Martin Baulig (martin@ximian.com)
  6. // Marek Safar (marek.safar@gmail.com)
  7. //
  8. // Dual licensed under the terms of the MIT X11 or GNU GPL
  9. //
  10. // Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
  11. // Copyright 2004-2011 Novell, Inc
  12. // Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
  13. //
  14. using System;
  15. using System.Collections.Generic;
  16. using System.Runtime.InteropServices;
  17. using System.Security;
  18. using System.Security.Permissions;
  19. using System.Linq;
  20. using System.Text;
  21. using System.Diagnostics;
  22. using Mono.CompilerServices.SymbolWriter;
  23. #if NET_2_1
  24. using XmlElement = System.Object;
  25. #endif
  26. #if STATIC
  27. using SecurityType = System.Collections.Generic.List<IKVM.Reflection.Emit.CustomAttributeBuilder>;
  28. using IKVM.Reflection;
  29. using IKVM.Reflection.Emit;
  30. #else
  31. using SecurityType = System.Collections.Generic.Dictionary<System.Security.Permissions.SecurityAction, System.Security.PermissionSet>;
  32. using System.Reflection;
  33. using System.Reflection.Emit;
  34. #endif
  35. namespace Mono.CSharp
  36. {
  37. //
  38. // General types container, used as a base class for all constructs which can hold types
  39. //
  40. public abstract class TypeContainer : MemberCore
  41. {
  42. public readonly MemberKind Kind;
  43. public readonly string Basename;
  44. protected List<TypeContainer> containers;
  45. TypeDefinition main_container;
  46. protected Dictionary<string, MemberCore> defined_names;
  47. protected bool is_defined;
  48. public TypeContainer (TypeContainer parent, MemberName name, Attributes attrs, MemberKind kind)
  49. : base (parent, name, attrs)
  50. {
  51. this.Kind = kind;
  52. if (name != null)
  53. this.Basename = name.Basename;
  54. defined_names = new Dictionary<string, MemberCore> ();
  55. }
  56. public override TypeSpec CurrentType {
  57. get {
  58. return null;
  59. }
  60. }
  61. public Dictionary<string, MemberCore> DefinedNames {
  62. get {
  63. return defined_names;
  64. }
  65. }
  66. public TypeDefinition PartialContainer {
  67. get {
  68. return main_container;
  69. }
  70. protected set {
  71. main_container = value;
  72. }
  73. }
  74. public IList<TypeContainer> Containers {
  75. get {
  76. return containers;
  77. }
  78. }
  79. //
  80. // Any unattached attributes during parsing get added here. User
  81. // by FULL_AST mode
  82. //
  83. public Attributes UnattachedAttributes {
  84. get; set;
  85. }
  86. public virtual void AddCompilerGeneratedClass (CompilerGeneratedContainer c)
  87. {
  88. containers.Add (c);
  89. }
  90. public virtual void AddPartial (TypeDefinition next_part)
  91. {
  92. MemberCore mc;
  93. (PartialContainer ?? this).defined_names.TryGetValue (next_part.Basename, out mc);
  94. AddPartial (next_part, mc as TypeDefinition);
  95. }
  96. protected void AddPartial (TypeDefinition next_part, TypeDefinition existing)
  97. {
  98. next_part.ModFlags |= Modifiers.PARTIAL;
  99. if (existing == null) {
  100. AddTypeContainer (next_part);
  101. return;
  102. }
  103. if ((existing.ModFlags & Modifiers.PARTIAL) == 0) {
  104. if (existing.Kind != next_part.Kind) {
  105. AddTypeContainer (next_part);
  106. } else {
  107. Report.SymbolRelatedToPreviousError (next_part);
  108. Error_MissingPartialModifier (existing);
  109. }
  110. return;
  111. }
  112. if (existing.Kind != next_part.Kind) {
  113. Report.SymbolRelatedToPreviousError (existing);
  114. Report.Error (261, next_part.Location,
  115. "Partial declarations of `{0}' must be all classes, all structs or all interfaces",
  116. next_part.GetSignatureForError ());
  117. }
  118. if ((existing.ModFlags & Modifiers.AccessibilityMask) != (next_part.ModFlags & Modifiers.AccessibilityMask) &&
  119. ((existing.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0 &&
  120. (next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0)) {
  121. Report.SymbolRelatedToPreviousError (existing);
  122. Report.Error (262, next_part.Location,
  123. "Partial declarations of `{0}' have conflicting accessibility modifiers",
  124. next_part.GetSignatureForError ());
  125. }
  126. var tc_names = existing.CurrentTypeParameters;
  127. if (tc_names != null) {
  128. for (int i = 0; i < tc_names.Count; ++i) {
  129. var tp = next_part.MemberName.TypeParameters[i];
  130. if (tc_names[i].MemberName.Name != tp.MemberName.Name) {
  131. Report.SymbolRelatedToPreviousError (existing.Location, "");
  132. Report.Error (264, next_part.Location, "Partial declarations of `{0}' must have the same type parameter names in the same order",
  133. next_part.GetSignatureForError ());
  134. break;
  135. }
  136. if (tc_names[i].Variance != tp.Variance) {
  137. Report.SymbolRelatedToPreviousError (existing.Location, "");
  138. Report.Error (1067, next_part.Location, "Partial declarations of `{0}' must have the same type parameter variance modifiers",
  139. next_part.GetSignatureForError ());
  140. break;
  141. }
  142. }
  143. }
  144. if ((next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) != 0) {
  145. existing.ModFlags |= next_part.ModFlags & ~(Modifiers.DEFAULT_ACCESS_MODIFER | Modifiers.AccessibilityMask);
  146. } else if ((existing.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) != 0) {
  147. existing.ModFlags &= ~(Modifiers.DEFAULT_ACCESS_MODIFER | Modifiers.AccessibilityMask);
  148. existing.ModFlags |= next_part.ModFlags;
  149. } else {
  150. existing.ModFlags |= next_part.ModFlags;
  151. }
  152. existing.Definition.Modifiers = existing.ModFlags;
  153. if (next_part.attributes != null) {
  154. if (existing.attributes == null)
  155. existing.attributes = next_part.attributes;
  156. else
  157. existing.attributes.AddAttributes (next_part.attributes.Attrs);
  158. }
  159. next_part.PartialContainer = existing;
  160. if (containers == null)
  161. containers = new List<TypeContainer> ();
  162. containers.Add (next_part);
  163. }
  164. public virtual void AddTypeContainer (TypeContainer tc)
  165. {
  166. containers.Add (tc);
  167. var tparams = tc.MemberName.TypeParameters;
  168. if (tparams != null && tc.PartialContainer != null) {
  169. var td = (TypeDefinition) tc;
  170. for (int i = 0; i < tparams.Count; ++i) {
  171. var tp = tparams[i];
  172. if (tp.MemberName == null)
  173. continue;
  174. td.AddNameToContainer (tp, tp.Name);
  175. }
  176. }
  177. }
  178. public virtual void CloseContainer ()
  179. {
  180. if (containers != null) {
  181. foreach (TypeContainer tc in containers) {
  182. tc.CloseContainer ();
  183. }
  184. }
  185. }
  186. public virtual void CreateMetadataName (StringBuilder sb)
  187. {
  188. if (Parent != null && Parent.MemberName != null)
  189. Parent.CreateMetadataName (sb);
  190. MemberName.CreateMetadataName (sb);
  191. }
  192. public virtual bool CreateContainer ()
  193. {
  194. if (containers != null) {
  195. foreach (TypeContainer tc in containers) {
  196. tc.CreateContainer ();
  197. }
  198. }
  199. return true;
  200. }
  201. public override bool Define ()
  202. {
  203. if (containers != null) {
  204. foreach (TypeContainer tc in containers) {
  205. tc.Define ();
  206. }
  207. }
  208. // Release cache used by parser only
  209. if (Module.Evaluator == null) {
  210. defined_names = null;
  211. } else {
  212. defined_names.Clear ();
  213. }
  214. return true;
  215. }
  216. public virtual void PrepareEmit ()
  217. {
  218. if (containers != null) {
  219. foreach (var t in containers) {
  220. try {
  221. t.PrepareEmit ();
  222. } catch (Exception e) {
  223. if (MemberName == MemberName.Null)
  224. throw;
  225. throw new InternalErrorException (t, e);
  226. }
  227. }
  228. }
  229. }
  230. public virtual bool DefineContainer ()
  231. {
  232. if (is_defined)
  233. return true;
  234. is_defined = true;
  235. DoDefineContainer ();
  236. if (containers != null) {
  237. foreach (TypeContainer tc in containers) {
  238. try {
  239. tc.DefineContainer ();
  240. } catch (Exception e) {
  241. if (MemberName == MemberName.Null)
  242. throw;
  243. throw new InternalErrorException (tc, e);
  244. }
  245. }
  246. }
  247. return true;
  248. }
  249. public virtual void ExpandBaseInterfaces ()
  250. {
  251. if (containers != null) {
  252. foreach (TypeContainer tc in containers) {
  253. tc.ExpandBaseInterfaces ();
  254. }
  255. }
  256. }
  257. protected virtual void DefineNamespace ()
  258. {
  259. if (containers != null) {
  260. foreach (var tc in containers) {
  261. try {
  262. tc.DefineNamespace ();
  263. } catch (Exception e) {
  264. throw new InternalErrorException (tc, e);
  265. }
  266. }
  267. }
  268. }
  269. protected virtual void DoDefineContainer ()
  270. {
  271. }
  272. public virtual void EmitContainer ()
  273. {
  274. if (containers != null) {
  275. for (int i = 0; i < containers.Count; ++i)
  276. containers[i].EmitContainer ();
  277. }
  278. }
  279. protected void Error_MissingPartialModifier (MemberCore type)
  280. {
  281. Report.Error (260, type.Location,
  282. "Missing partial modifier on declaration of type `{0}'. Another partial declaration of this type exists",
  283. type.GetSignatureForError ());
  284. }
  285. public override string GetSignatureForDocumentation ()
  286. {
  287. if (Parent != null && Parent.MemberName != null)
  288. return Parent.GetSignatureForDocumentation () + "." + MemberName.GetSignatureForDocumentation ();
  289. return MemberName.GetSignatureForDocumentation ();
  290. }
  291. public override string GetSignatureForError ()
  292. {
  293. if (Parent != null && Parent.MemberName != null)
  294. return Parent.GetSignatureForError () + "." + MemberName.GetSignatureForError ();
  295. return MemberName.GetSignatureForError ();
  296. }
  297. public string GetSignatureForMetadata ()
  298. {
  299. #if STATIC
  300. if (Parent is TypeDefinition) {
  301. return Parent.GetSignatureForMetadata () + "+" + TypeNameParser.Escape (MemberName.Basename);
  302. }
  303. var sb = new StringBuilder ();
  304. CreateMetadataName (sb);
  305. return sb.ToString ();
  306. #else
  307. throw new NotImplementedException ();
  308. #endif
  309. }
  310. public virtual void RemoveContainer (TypeContainer cont)
  311. {
  312. if (containers != null)
  313. containers.Remove (cont);
  314. var tc = Parent == Module ? Module : this;
  315. tc.defined_names.Remove (cont.Basename);
  316. }
  317. public virtual void VerifyMembers ()
  318. {
  319. if (containers != null) {
  320. foreach (TypeContainer tc in containers)
  321. tc.VerifyMembers ();
  322. }
  323. }
  324. public override void WriteDebugSymbol (MonoSymbolFile file)
  325. {
  326. if (containers != null) {
  327. foreach (TypeContainer tc in containers) {
  328. tc.WriteDebugSymbol (file);
  329. }
  330. }
  331. }
  332. }
  333. public abstract class TypeDefinition : TypeContainer, ITypeDefinition
  334. {
  335. //
  336. // Different context is needed when resolving type container base
  337. // types. Type names come from the parent scope but type parameter
  338. // names from the container scope.
  339. //
  340. public struct BaseContext : IMemberContext
  341. {
  342. TypeContainer tc;
  343. public BaseContext (TypeContainer tc)
  344. {
  345. this.tc = tc;
  346. }
  347. #region IMemberContext Members
  348. public CompilerContext Compiler {
  349. get { return tc.Compiler; }
  350. }
  351. public TypeSpec CurrentType {
  352. get { return tc.Parent.CurrentType; }
  353. }
  354. public TypeParameters CurrentTypeParameters {
  355. get { return tc.PartialContainer.CurrentTypeParameters; }
  356. }
  357. public MemberCore CurrentMemberDefinition {
  358. get { return tc; }
  359. }
  360. public bool IsObsolete {
  361. get { return tc.IsObsolete; }
  362. }
  363. public bool IsUnsafe {
  364. get { return tc.IsUnsafe; }
  365. }
  366. public bool IsStatic {
  367. get { return tc.IsStatic; }
  368. }
  369. public ModuleContainer Module {
  370. get { return tc.Module; }
  371. }
  372. public string GetSignatureForError ()
  373. {
  374. return tc.GetSignatureForError ();
  375. }
  376. public ExtensionMethodCandidates LookupExtensionMethod (TypeSpec extensionType, string name, int arity)
  377. {
  378. return null;
  379. }
  380. public FullNamedExpression LookupNamespaceAlias (string name)
  381. {
  382. return tc.Parent.LookupNamespaceAlias (name);
  383. }
  384. public FullNamedExpression LookupNamespaceOrType (string name, int arity, LookupMode mode, Location loc)
  385. {
  386. if (arity == 0) {
  387. var tp = CurrentTypeParameters;
  388. if (tp != null) {
  389. TypeParameter t = tp.Find (name);
  390. if (t != null)
  391. return new TypeParameterExpr (t, loc);
  392. }
  393. }
  394. return tc.Parent.LookupNamespaceOrType (name, arity, mode, loc);
  395. }
  396. #endregion
  397. }
  398. [Flags]
  399. enum CachedMethods
  400. {
  401. Equals = 1,
  402. GetHashCode = 1 << 1,
  403. HasStaticFieldInitializer = 1 << 2
  404. }
  405. readonly List<MemberCore> members;
  406. // Holds a list of fields that have initializers
  407. protected List<FieldInitializer> initialized_fields;
  408. // Holds a list of static fields that have initializers
  409. protected List<FieldInitializer> initialized_static_fields;
  410. Dictionary<MethodSpec, Method> hoisted_base_call_proxies;
  411. Dictionary<string, FullNamedExpression> Cache = new Dictionary<string, FullNamedExpression> ();
  412. //
  413. // Points to the first non-static field added to the container.
  414. //
  415. // This is an arbitrary choice. We are interested in looking at _some_ non-static field,
  416. // and the first one's as good as any.
  417. //
  418. protected FieldBase first_nonstatic_field;
  419. //
  420. // This one is computed after we can distinguish interfaces
  421. // from classes from the arraylist `type_bases'
  422. //
  423. protected TypeSpec base_type;
  424. FullNamedExpression base_type_expr; // TODO: It's temporary variable
  425. protected TypeSpec[] iface_exprs;
  426. protected List<FullNamedExpression> type_bases;
  427. TypeDefinition InTransit;
  428. public TypeBuilder TypeBuilder;
  429. GenericTypeParameterBuilder[] all_tp_builders;
  430. //
  431. // All recursive type parameters put together sharing same
  432. // TypeParameter instances
  433. //
  434. TypeParameters all_type_parameters;
  435. public const string DefaultIndexerName = "Item";
  436. bool has_normal_indexers;
  437. string indexer_name;
  438. protected bool requires_delayed_unmanagedtype_check;
  439. bool error;
  440. bool members_defined;
  441. bool members_defined_ok;
  442. protected bool has_static_constructor;
  443. private CachedMethods cached_method;
  444. protected TypeSpec spec;
  445. TypeSpec current_type;
  446. public int DynamicSitesCounter;
  447. public int AnonymousMethodsCounter;
  448. static readonly string[] attribute_targets = new string[] { "type" };
  449. /// <remarks>
  450. /// The pending methods that need to be implemented
  451. // (interfaces or abstract methods)
  452. /// </remarks>
  453. PendingImplementation pending;
  454. public TypeDefinition (TypeContainer parent, MemberName name, Attributes attrs, MemberKind kind)
  455. : base (parent, name, attrs, kind)
  456. {
  457. PartialContainer = this;
  458. members = new List<MemberCore> ();
  459. }
  460. #region Properties
  461. public List<FullNamedExpression> BaseTypeExpressions {
  462. get {
  463. return type_bases;
  464. }
  465. }
  466. public override TypeSpec CurrentType {
  467. get {
  468. if (current_type == null) {
  469. if (IsGenericOrParentIsGeneric) {
  470. //
  471. // Switch to inflated version as it's used by all expressions
  472. //
  473. var targs = CurrentTypeParameters == null ? TypeSpec.EmptyTypes : CurrentTypeParameters.Types;
  474. current_type = spec.MakeGenericType (this, targs);
  475. } else {
  476. current_type = spec;
  477. }
  478. }
  479. return current_type;
  480. }
  481. }
  482. public override TypeParameters CurrentTypeParameters {
  483. get {
  484. return PartialContainer.MemberName.TypeParameters;
  485. }
  486. }
  487. int CurrentTypeParametersStartIndex {
  488. get {
  489. int total = all_tp_builders.Length;
  490. if (CurrentTypeParameters != null) {
  491. return total - CurrentTypeParameters.Count;
  492. }
  493. return total;
  494. }
  495. }
  496. public virtual AssemblyDefinition DeclaringAssembly {
  497. get {
  498. return Module.DeclaringAssembly;
  499. }
  500. }
  501. IAssemblyDefinition ITypeDefinition.DeclaringAssembly {
  502. get {
  503. return Module.DeclaringAssembly;
  504. }
  505. }
  506. public TypeSpec Definition {
  507. get {
  508. return spec;
  509. }
  510. }
  511. public bool HasMembersDefined {
  512. get {
  513. return members_defined;
  514. }
  515. }
  516. public bool HasInstanceConstructor {
  517. get {
  518. return (caching_flags & Flags.HasInstanceConstructor) != 0;
  519. }
  520. set {
  521. caching_flags |= Flags.HasInstanceConstructor;
  522. }
  523. }
  524. // Indicated whether container has StructLayout attribute set Explicit
  525. public bool HasExplicitLayout {
  526. get { return (caching_flags & Flags.HasExplicitLayout) != 0; }
  527. set { caching_flags |= Flags.HasExplicitLayout; }
  528. }
  529. public bool HasOperators {
  530. get {
  531. return (caching_flags & Flags.HasUserOperators) != 0;
  532. }
  533. set {
  534. caching_flags |= Flags.HasUserOperators;
  535. }
  536. }
  537. public bool HasStructLayout {
  538. get { return (caching_flags & Flags.HasStructLayout) != 0; }
  539. set { caching_flags |= Flags.HasStructLayout; }
  540. }
  541. public TypeSpec[] Interfaces {
  542. get {
  543. return iface_exprs;
  544. }
  545. }
  546. public bool IsGenericOrParentIsGeneric {
  547. get {
  548. return all_type_parameters != null;
  549. }
  550. }
  551. public bool IsTopLevel {
  552. get {
  553. return !(Parent is TypeDefinition);
  554. }
  555. }
  556. public bool IsPartial {
  557. get {
  558. return (ModFlags & Modifiers.PARTIAL) != 0;
  559. }
  560. }
  561. bool ITypeDefinition.IsTypeForwarder {
  562. get {
  563. return false;
  564. }
  565. }
  566. //
  567. // Returns true for secondary partial containers
  568. //
  569. bool IsPartialPart {
  570. get {
  571. return PartialContainer != this;
  572. }
  573. }
  574. public MemberCache MemberCache {
  575. get {
  576. return spec.MemberCache;
  577. }
  578. }
  579. public List<MemberCore> Members {
  580. get {
  581. return members;
  582. }
  583. }
  584. string ITypeDefinition.Namespace {
  585. get {
  586. var p = Parent;
  587. while (p.Kind != MemberKind.Namespace)
  588. p = p.Parent;
  589. return p.MemberName == null ? null : p.GetSignatureForError ();
  590. }
  591. }
  592. public TypeParameters TypeParametersAll {
  593. get {
  594. return all_type_parameters;
  595. }
  596. }
  597. public override string[] ValidAttributeTargets {
  598. get {
  599. return attribute_targets;
  600. }
  601. }
  602. #endregion
  603. public override void Accept (StructuralVisitor visitor)
  604. {
  605. visitor.Visit (this);
  606. }
  607. public void AddMember (MemberCore symbol)
  608. {
  609. if (symbol.MemberName.ExplicitInterface != null) {
  610. if (!(Kind == MemberKind.Class || Kind == MemberKind.Struct)) {
  611. Report.Error (541, symbol.Location,
  612. "`{0}': explicit interface declaration can only be declared in a class or struct",
  613. symbol.GetSignatureForError ());
  614. }
  615. }
  616. AddNameToContainer (symbol, symbol.MemberName.Basename);
  617. members.Add (symbol);
  618. }
  619. public override void AddTypeContainer (TypeContainer tc)
  620. {
  621. AddNameToContainer (tc, tc.Basename);
  622. if (containers == null)
  623. containers = new List<TypeContainer> ();
  624. members.Add (tc);
  625. base.AddTypeContainer (tc);
  626. }
  627. public override void AddCompilerGeneratedClass (CompilerGeneratedContainer c)
  628. {
  629. members.Add (c);
  630. if (containers == null)
  631. containers = new List<TypeContainer> ();
  632. base.AddCompilerGeneratedClass (c);
  633. }
  634. //
  635. // Adds the member to defined_names table. It tests for duplications and enclosing name conflicts
  636. //
  637. public virtual void AddNameToContainer (MemberCore symbol, string name)
  638. {
  639. if (((ModFlags | symbol.ModFlags) & Modifiers.COMPILER_GENERATED) != 0)
  640. return;
  641. MemberCore mc;
  642. if (!PartialContainer.defined_names.TryGetValue (name, out mc)) {
  643. PartialContainer.defined_names.Add (name, symbol);
  644. return;
  645. }
  646. if (symbol.EnableOverloadChecks (mc))
  647. return;
  648. InterfaceMemberBase im = mc as InterfaceMemberBase;
  649. if (im != null && im.IsExplicitImpl)
  650. return;
  651. Report.SymbolRelatedToPreviousError (mc);
  652. if ((mc.ModFlags & Modifiers.PARTIAL) != 0 && (symbol is ClassOrStruct || symbol is Interface)) {
  653. Error_MissingPartialModifier (symbol);
  654. return;
  655. }
  656. if (symbol is TypeParameter) {
  657. Report.Error (692, symbol.Location,
  658. "Duplicate type parameter `{0}'", symbol.GetSignatureForError ());
  659. } else {
  660. Report.Error (102, symbol.Location,
  661. "The type `{0}' already contains a definition for `{1}'",
  662. GetSignatureForError (), name);
  663. }
  664. return;
  665. }
  666. public void AddConstructor (Constructor c)
  667. {
  668. AddConstructor (c, false);
  669. }
  670. public void AddConstructor (Constructor c, bool isDefault)
  671. {
  672. bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
  673. if (!isDefault)
  674. AddNameToContainer (c, is_static ? Constructor.TypeConstructorName : Constructor.ConstructorName);
  675. if (is_static && c.ParameterInfo.IsEmpty) {
  676. PartialContainer.has_static_constructor = true;
  677. } else {
  678. PartialContainer.HasInstanceConstructor = true;
  679. }
  680. members.Add (c);
  681. }
  682. public bool AddField (FieldBase field)
  683. {
  684. AddMember (field);
  685. if ((field.ModFlags & Modifiers.STATIC) != 0)
  686. return true;
  687. var first_field = PartialContainer.first_nonstatic_field;
  688. if (first_field == null) {
  689. PartialContainer.first_nonstatic_field = field;
  690. return true;
  691. }
  692. if (Kind == MemberKind.Struct && first_field.Parent != field.Parent) {
  693. Report.SymbolRelatedToPreviousError (first_field.Parent);
  694. Report.Warning (282, 3, field.Location,
  695. "struct instance field `{0}' found in different declaration from instance field `{1}'",
  696. field.GetSignatureForError (), first_field.GetSignatureForError ());
  697. }
  698. return true;
  699. }
  700. /// <summary>
  701. /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
  702. /// </summary>
  703. public void AddIndexer (Indexer i)
  704. {
  705. members.Add (i);
  706. }
  707. public void AddOperator (Operator op)
  708. {
  709. PartialContainer.HasOperators = true;
  710. AddMember (op);
  711. }
  712. public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
  713. {
  714. if (has_normal_indexers && a.Type == pa.DefaultMember) {
  715. Report.Error (646, a.Location, "Cannot specify the `DefaultMember' attribute on type containing an indexer");
  716. return;
  717. }
  718. if (a.Type == pa.Required) {
  719. Report.Error (1608, a.Location, "The RequiredAttribute attribute is not permitted on C# types");
  720. return;
  721. }
  722. TypeBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
  723. }
  724. public override AttributeTargets AttributeTargets {
  725. get {
  726. throw new NotSupportedException ();
  727. }
  728. }
  729. public TypeSpec BaseType {
  730. get {
  731. return spec.BaseType;
  732. }
  733. }
  734. protected virtual TypeAttributes TypeAttr {
  735. get {
  736. return ModifiersExtensions.TypeAttr (ModFlags, IsTopLevel);
  737. }
  738. }
  739. public int TypeParametersCount {
  740. get {
  741. return MemberName.Arity;
  742. }
  743. }
  744. TypeParameterSpec[] ITypeDefinition.TypeParameters {
  745. get {
  746. return PartialContainer.CurrentTypeParameters.Types;
  747. }
  748. }
  749. public string GetAttributeDefaultMember ()
  750. {
  751. return indexer_name ?? DefaultIndexerName;
  752. }
  753. public bool IsComImport {
  754. get {
  755. if (OptAttributes == null)
  756. return false;
  757. return OptAttributes.Contains (Module.PredefinedAttributes.ComImport);
  758. }
  759. }
  760. public virtual void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
  761. {
  762. if (IsPartialPart)
  763. PartialContainer.RegisterFieldForInitialization (field, expression);
  764. if ((field.ModFlags & Modifiers.STATIC) != 0){
  765. if (initialized_static_fields == null) {
  766. HasStaticFieldInitializer = true;
  767. initialized_static_fields = new List<FieldInitializer> (4);
  768. }
  769. initialized_static_fields.Add (expression);
  770. } else {
  771. if (initialized_fields == null)
  772. initialized_fields = new List<FieldInitializer> (4);
  773. initialized_fields.Add (expression);
  774. }
  775. }
  776. public void ResolveFieldInitializers (BlockContext ec)
  777. {
  778. Debug.Assert (!IsPartialPart);
  779. if (ec.IsStatic) {
  780. if (initialized_static_fields == null)
  781. return;
  782. bool has_complex_initializer = !ec.Module.Compiler.Settings.Optimize;
  783. int i;
  784. ExpressionStatement [] init = new ExpressionStatement [initialized_static_fields.Count];
  785. for (i = 0; i < initialized_static_fields.Count; ++i) {
  786. FieldInitializer fi = initialized_static_fields [i];
  787. ExpressionStatement s = fi.ResolveStatement (ec);
  788. if (s == null) {
  789. s = EmptyExpressionStatement.Instance;
  790. } else if (!fi.IsSideEffectFree) {
  791. has_complex_initializer |= true;
  792. }
  793. init [i] = s;
  794. }
  795. for (i = 0; i < initialized_static_fields.Count; ++i) {
  796. FieldInitializer fi = initialized_static_fields [i];
  797. //
  798. // Need special check to not optimize code like this
  799. // static int a = b = 5;
  800. // static int b = 0;
  801. //
  802. if (!has_complex_initializer && fi.IsDefaultInitializer)
  803. continue;
  804. ec.CurrentBlock.AddScopeStatement (new StatementExpression (init [i]));
  805. }
  806. return;
  807. }
  808. if (initialized_fields == null)
  809. return;
  810. for (int i = 0; i < initialized_fields.Count; ++i) {
  811. FieldInitializer fi = initialized_fields [i];
  812. ExpressionStatement s = fi.ResolveStatement (ec);
  813. if (s == null)
  814. continue;
  815. //
  816. // Field is re-initialized to its default value => removed
  817. //
  818. if (fi.IsDefaultInitializer && ec.Module.Compiler.Settings.Optimize)
  819. continue;
  820. ec.CurrentBlock.AddScopeStatement (new StatementExpression (s));
  821. }
  822. }
  823. public override string DocComment {
  824. get {
  825. return comment;
  826. }
  827. set {
  828. if (value == null)
  829. return;
  830. comment += value;
  831. }
  832. }
  833. public PendingImplementation PendingImplementations {
  834. get { return pending; }
  835. }
  836. internal override void GenerateDocComment (DocumentationBuilder builder)
  837. {
  838. if (IsPartialPart)
  839. return;
  840. base.GenerateDocComment (builder);
  841. foreach (var member in members)
  842. member.GenerateDocComment (builder);
  843. }
  844. public TypeSpec GetAttributeCoClass ()
  845. {
  846. if (OptAttributes == null)
  847. return null;
  848. Attribute a = OptAttributes.Search (Module.PredefinedAttributes.CoClass);
  849. if (a == null)
  850. return null;
  851. return a.GetCoClassAttributeValue ();
  852. }
  853. public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
  854. {
  855. Attribute a = null;
  856. if (OptAttributes != null) {
  857. a = OptAttributes.Search (pa);
  858. }
  859. if (a == null)
  860. return null;
  861. return a.GetAttributeUsageAttribute ();
  862. }
  863. public virtual CompilationSourceFile GetCompilationSourceFile ()
  864. {
  865. TypeContainer ns = Parent;
  866. while (true) {
  867. var sf = ns as CompilationSourceFile;
  868. if (sf != null)
  869. return sf;
  870. ns = ns.Parent;
  871. }
  872. }
  873. public virtual void AddBasesForPart (List<FullNamedExpression> bases)
  874. {
  875. type_bases = bases;
  876. }
  877. /// <summary>
  878. /// This function computes the Base class and also the
  879. /// list of interfaces that the class or struct @c implements.
  880. ///
  881. /// The return value is an array (might be null) of
  882. /// interfaces implemented (as Types).
  883. ///
  884. /// The @base_class argument is set to the base object or null
  885. /// if this is `System.Object'.
  886. /// </summary>
  887. protected virtual TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class)
  888. {
  889. base_class = null;
  890. if (type_bases == null)
  891. return null;
  892. int count = type_bases.Count;
  893. TypeSpec[] ifaces = null;
  894. var base_context = new BaseContext (this);
  895. for (int i = 0, j = 0; i < count; i++){
  896. FullNamedExpression fne = type_bases [i];
  897. var fne_resolved = fne.ResolveAsType (base_context);
  898. if (fne_resolved == null)
  899. continue;
  900. if (i == 0 && Kind == MemberKind.Class && !fne_resolved.IsInterface) {
  901. if (fne_resolved.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
  902. Report.Error (1965, Location, "Class `{0}' cannot derive from the dynamic type",
  903. GetSignatureForError ());
  904. continue;
  905. }
  906. base_type = fne_resolved;
  907. base_class = fne;
  908. continue;
  909. }
  910. if (ifaces == null)
  911. ifaces = new TypeSpec [count - i];
  912. if (fne_resolved.IsInterface) {
  913. for (int ii = 0; ii < j; ++ii) {
  914. if (fne_resolved == ifaces [ii]) {
  915. Report.Error (528, Location, "`{0}' is already listed in interface list",
  916. fne_resolved.GetSignatureForError ());
  917. break;
  918. }
  919. }
  920. if (Kind == MemberKind.Interface && !IsAccessibleAs (fne_resolved)) {
  921. Report.Error (61, fne.Location,
  922. "Inconsistent accessibility: base interface `{0}' is less accessible than interface `{1}'",
  923. fne_resolved.GetSignatureForError (), GetSignatureForError ());
  924. }
  925. } else {
  926. Report.SymbolRelatedToPreviousError (fne_resolved);
  927. if (Kind != MemberKind.Class) {
  928. Report.Error (527, fne.Location, "Type `{0}' in interface list is not an interface", fne_resolved.GetSignatureForError ());
  929. } else if (base_class != null)
  930. Report.Error (1721, fne.Location, "`{0}': Classes cannot have multiple base classes (`{1}' and `{2}')",
  931. GetSignatureForError (), base_class.GetSignatureForError (), fne_resolved.GetSignatureForError ());
  932. else {
  933. Report.Error (1722, fne.Location, "`{0}': Base class `{1}' must be specified as first",
  934. GetSignatureForError (), fne_resolved.GetSignatureForError ());
  935. }
  936. }
  937. ifaces [j++] = fne_resolved;
  938. }
  939. return ifaces;
  940. }
  941. //
  942. // Checks that some operators come in pairs:
  943. // == and !=
  944. // > and <
  945. // >= and <=
  946. // true and false
  947. //
  948. // They are matched based on the return type and the argument types
  949. //
  950. void CheckPairedOperators ()
  951. {
  952. bool has_equality_or_inequality = false;
  953. List<Operator.OpType> found_matched = new List<Operator.OpType> ();
  954. for (int i = 0; i < members.Count; ++i) {
  955. var o_a = members[i] as Operator;
  956. if (o_a == null)
  957. continue;
  958. var o_type = o_a.OperatorType;
  959. if (o_type == Operator.OpType.Equality || o_type == Operator.OpType.Inequality)
  960. has_equality_or_inequality = true;
  961. if (found_matched.Contains (o_type))
  962. continue;
  963. var matching_type = o_a.GetMatchingOperator ();
  964. if (matching_type == Operator.OpType.TOP) {
  965. continue;
  966. }
  967. bool pair_found = false;
  968. for (int ii = i + 1; ii < members.Count; ++ii) {
  969. var o_b = members[ii] as Operator;
  970. if (o_b == null || o_b.OperatorType != matching_type)
  971. continue;
  972. if (!TypeSpecComparer.IsEqual (o_a.ReturnType, o_b.ReturnType))
  973. continue;
  974. if (!TypeSpecComparer.Equals (o_a.ParameterTypes, o_b.ParameterTypes))
  975. continue;
  976. found_matched.Add (matching_type);
  977. pair_found = true;
  978. break;
  979. }
  980. if (!pair_found) {
  981. Report.Error (216, o_a.Location,
  982. "The operator `{0}' requires a matching operator `{1}' to also be defined",
  983. o_a.GetSignatureForError (), Operator.GetName (matching_type));
  984. }
  985. }
  986. if (has_equality_or_inequality) {
  987. if (!HasEquals)
  988. Report.Warning (660, 2, Location, "`{0}' defines operator == or operator != but does not override Object.Equals(object o)",
  989. GetSignatureForError ());
  990. if (!HasGetHashCode)
  991. Report.Warning (661, 2, Location, "`{0}' defines operator == or operator != but does not override Object.GetHashCode()",
  992. GetSignatureForError ());
  993. }
  994. }
  995. public override void CreateMetadataName (StringBuilder sb)
  996. {
  997. if (Parent.MemberName != null) {
  998. Parent.CreateMetadataName (sb);
  999. if (sb.Length != 0) {
  1000. sb.Append (".");
  1001. }
  1002. }
  1003. sb.Append (MemberName.Basename);
  1004. }
  1005. bool CreateTypeBuilder ()
  1006. {
  1007. //
  1008. // Sets .size to 1 for structs with no instance fields
  1009. //
  1010. int type_size = Kind == MemberKind.Struct && first_nonstatic_field == null && !(this is StateMachine) ? 1 : 0;
  1011. var parent_def = Parent as TypeDefinition;
  1012. if (parent_def == null) {
  1013. var sb = new StringBuilder ();
  1014. CreateMetadataName (sb);
  1015. TypeBuilder = Module.CreateBuilder (sb.ToString (), TypeAttr, type_size);
  1016. } else {
  1017. TypeBuilder = parent_def.TypeBuilder.DefineNestedType (Basename, TypeAttr, null, type_size);
  1018. }
  1019. if (DeclaringAssembly.Importer != null)
  1020. DeclaringAssembly.Importer.AddCompiledType (TypeBuilder, spec);
  1021. spec.SetMetaInfo (TypeBuilder);
  1022. spec.MemberCache = new MemberCache (this);
  1023. TypeParameters parentAllTypeParameters = null;
  1024. if (parent_def != null) {
  1025. spec.DeclaringType = Parent.CurrentType;
  1026. parent_def.MemberCache.AddMember (spec);
  1027. parentAllTypeParameters = parent_def.all_type_parameters;
  1028. }
  1029. if (MemberName.TypeParameters != null || parentAllTypeParameters != null) {
  1030. var tparam_names = CreateTypeParameters (parentAllTypeParameters);
  1031. all_tp_builders = TypeBuilder.DefineGenericParameters (tparam_names);
  1032. if (CurrentTypeParameters != null)
  1033. CurrentTypeParameters.Define (all_tp_builders, spec, CurrentTypeParametersStartIndex, this);
  1034. }
  1035. return true;
  1036. }
  1037. string[] CreateTypeParameters (TypeParameters parentAllTypeParameters)
  1038. {
  1039. string[] names;
  1040. int parent_offset = 0;
  1041. if (parentAllTypeParameters != null) {
  1042. if (CurrentTypeParameters == null) {
  1043. all_type_parameters = parentAllTypeParameters;
  1044. return parentAllTypeParameters.GetAllNames ();
  1045. }
  1046. names = new string[parentAllTypeParameters.Count + CurrentTypeParameters.Count];
  1047. all_type_parameters = new TypeParameters (names.Length);
  1048. all_type_parameters.Add (parentAllTypeParameters);
  1049. parent_offset = all_type_parameters.Count;
  1050. for (int i = 0; i < parent_offset; ++i)
  1051. names[i] = all_type_parameters[i].MemberName.Name;
  1052. } else {
  1053. names = new string[CurrentTypeParameters.Count];
  1054. }
  1055. for (int i = 0; i < CurrentTypeParameters.Count; ++i) {
  1056. if (all_type_parameters != null)
  1057. all_type_parameters.Add (MemberName.TypeParameters[i]);
  1058. var name = CurrentTypeParameters[i].MemberName.Name;
  1059. names[parent_offset + i] = name;
  1060. for (int ii = 0; ii < parent_offset + i; ++ii) {
  1061. if (names[ii] != name)
  1062. continue;
  1063. var tp = CurrentTypeParameters[i];
  1064. var conflict = all_type_parameters[ii];
  1065. tp.WarningParentNameConflict (conflict);
  1066. }
  1067. }
  1068. if (all_type_parameters == null)
  1069. all_type_parameters = CurrentTypeParameters;
  1070. return names;
  1071. }
  1072. public SourceMethodBuilder CreateMethodSymbolEntry ()
  1073. {
  1074. if (Module.DeclaringAssembly.SymbolWriter == null)
  1075. return null;
  1076. var source_file = GetCompilationSourceFile ();
  1077. if (source_file == null)
  1078. return null;
  1079. return new SourceMethodBuilder (source_file.SymbolUnitEntry);
  1080. }
  1081. //
  1082. // Creates a proxy base method call inside this container for hoisted base member calls
  1083. //
  1084. public MethodSpec CreateHoistedBaseCallProxy (ResolveContext rc, MethodSpec method)
  1085. {
  1086. Method proxy_method;
  1087. //
  1088. // One proxy per base method is enough
  1089. //
  1090. if (hoisted_base_call_proxies == null) {
  1091. hoisted_base_call_proxies = new Dictionary<MethodSpec, Method> ();
  1092. proxy_method = null;
  1093. } else {
  1094. hoisted_base_call_proxies.TryGetValue (method, out proxy_method);
  1095. }
  1096. if (proxy_method == null) {
  1097. string name = CompilerGeneratedContainer.MakeName (method.Name, null, "BaseCallProxy", hoisted_base_call_proxies.Count);
  1098. MemberName member_name;
  1099. TypeArguments targs = null;
  1100. TypeSpec return_type = method.ReturnType;
  1101. var local_param_types = method.Parameters.Types;
  1102. if (method.IsGeneric) {
  1103. //
  1104. // Copy all base generic method type parameters info
  1105. //
  1106. var hoisted_tparams = method.GenericDefinition.TypeParameters;
  1107. var tparams = new TypeParameters ();
  1108. targs = new TypeArguments ();
  1109. targs.Arguments = new TypeSpec[hoisted_tparams.Length];
  1110. for (int i = 0; i < hoisted_tparams.Length; ++i) {
  1111. var tp = hoisted_tparams[i];
  1112. var local_tp = new TypeParameter (tp, null, new MemberName (tp.Name, Location), null);
  1113. tparams.Add (local_tp);
  1114. targs.Add (new SimpleName (tp.Name, Location));
  1115. targs.Arguments[i] = local_tp.Type;
  1116. }
  1117. member_name = new MemberName (name, tparams, Location);
  1118. //
  1119. // Mutate any method type parameters from original
  1120. // to newly created hoisted version
  1121. //
  1122. var mutator = new TypeParameterMutator (hoisted_tparams, tparams);
  1123. return_type = mutator.Mutate (return_type);
  1124. local_param_types = mutator.Mutate (local_param_types);
  1125. } else {
  1126. member_name = new MemberName (name);
  1127. }
  1128. var base_parameters = new Parameter[method.Parameters.Count];
  1129. for (int i = 0; i < base_parameters.Length; ++i) {
  1130. var base_param = method.Parameters.FixedParameters[i];
  1131. base_parameters[i] = new Parameter (new TypeExpression (local_param_types [i], Location),
  1132. base_param.Name, base_param.ModFlags, null, Location);
  1133. base_parameters[i].Resolve (this, i);
  1134. }
  1135. var cloned_params = ParametersCompiled.CreateFullyResolved (base_parameters, method.Parameters.Types);
  1136. if (method.Parameters.HasArglist) {
  1137. cloned_params.FixedParameters[0] = new Parameter (null, "__arglist", Parameter.Modifier.NONE, null, Location);
  1138. cloned_params.Types[0] = Module.PredefinedTypes.RuntimeArgumentHandle.Resolve ();
  1139. }
  1140. // Compiler generated proxy
  1141. proxy_method = new Method (this, new TypeExpression (return_type, Location),
  1142. Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED | Modifiers.DEBUGGER_HIDDEN,
  1143. member_name, cloned_params, null);
  1144. var block = new ToplevelBlock (Compiler, proxy_method.ParameterInfo, Location) {
  1145. IsCompilerGenerated = true
  1146. };
  1147. var mg = MethodGroupExpr.CreatePredefined (method, method.DeclaringType, Location);
  1148. mg.InstanceExpression = new BaseThis (method.DeclaringType, Location);
  1149. if (targs != null)
  1150. mg.SetTypeArguments (rc, targs);
  1151. // Get all the method parameters and pass them as arguments
  1152. var real_base_call = new Invocation (mg, block.GetAllParametersArguments ());
  1153. Statement statement;
  1154. if (method.ReturnType.Kind == MemberKind.Void)
  1155. statement = new StatementExpression (real_base_call);
  1156. else
  1157. statement = new Return (real_base_call, Location);
  1158. block.AddStatement (statement);
  1159. proxy_method.Block = block;
  1160. members.Add (proxy_method);
  1161. proxy_method.Define ();
  1162. hoisted_base_call_proxies.Add (method, proxy_method);
  1163. }
  1164. return proxy_method.Spec;
  1165. }
  1166. protected bool DefineBaseTypes ()
  1167. {
  1168. iface_exprs = ResolveBaseTypes (out base_type_expr);
  1169. bool set_base_type;
  1170. if (IsPartialPart) {
  1171. set_base_type = false;
  1172. if (base_type_expr != null) {
  1173. if (PartialContainer.base_type_expr != null && PartialContainer.base_type != base_type) {
  1174. Report.SymbolRelatedToPreviousError (base_type_expr.Location, "");
  1175. Report.Error (263, Location,
  1176. "Partial declarations of `{0}' must not specify different base classes",
  1177. GetSignatureForError ());
  1178. } else {
  1179. PartialContainer.base_type_expr = base_type_expr;
  1180. PartialContainer.base_type = base_type;
  1181. set_base_type = true;
  1182. }
  1183. }
  1184. if (iface_exprs != null) {
  1185. if (PartialContainer.iface_exprs == null)
  1186. PartialContainer.iface_exprs = iface_exprs;
  1187. else {
  1188. var ifaces = new List<TypeSpec> (PartialContainer.iface_exprs);
  1189. foreach (var iface_partial in iface_exprs) {
  1190. if (ifaces.Contains (iface_partial))
  1191. continue;
  1192. ifaces.Add (iface_partial);
  1193. }
  1194. PartialContainer.iface_exprs = ifaces.ToArray ();
  1195. }
  1196. }
  1197. PartialContainer.members.AddRange (members);
  1198. if (containers != null) {
  1199. if (PartialContainer.containers == null)
  1200. PartialContainer.containers = new List<TypeContainer> ();
  1201. PartialContainer.containers.AddRange (containers);
  1202. }
  1203. members_defined = members_defined_ok = true;
  1204. caching_flags |= Flags.CloseTypeCreated;
  1205. } else {
  1206. set_base_type = true;
  1207. }
  1208. var cycle = CheckRecursiveDefinition (this);
  1209. if (cycle != null) {
  1210. Report.SymbolRelatedToPreviousError (cycle);
  1211. if (this is Interface) {
  1212. Report.Error (529, Location,
  1213. "Inherited interface `{0}' causes a cycle in the interface hierarchy of `{1}'",
  1214. GetSignatureForError (), cycle.GetSignatureForError ());
  1215. iface_exprs = null;
  1216. PartialContainer.iface_exprs = null;
  1217. } else {
  1218. Report.Error (146, Location,
  1219. "Circular base class dependency involving `{0}' and `{1}'",
  1220. GetSignatureForError (), cycle.GetSignatureForError ());
  1221. base_type = null;
  1222. PartialContainer.base_type = null;
  1223. }
  1224. }
  1225. if (iface_exprs != null) {
  1226. foreach (var iface_type in iface_exprs) {
  1227. // Prevents a crash, the interface might not have been resolved: 442144
  1228. if (iface_type == null)
  1229. continue;
  1230. if (!spec.AddInterfaceDefined (iface_type))
  1231. continue;
  1232. TypeBuilder.AddInterfaceImplementation (iface_type.GetMetaInfo ());
  1233. }
  1234. }
  1235. if (Kind == MemberKind.Interface) {
  1236. spec.BaseType = Compiler.BuiltinTypes.Object;
  1237. return true;
  1238. }
  1239. if (set_base_type) {
  1240. if (base_type != null) {
  1241. spec.BaseType = base_type;
  1242. // Set base type after type creation
  1243. TypeBuilder.SetParent (base_type.GetMetaInfo ());
  1244. } else {
  1245. TypeBuilder.SetParent (null);
  1246. }
  1247. }
  1248. return true;
  1249. }
  1250. public override void ExpandBaseInterfaces ()
  1251. {
  1252. if (!IsPartialPart)
  1253. DoExpandBaseInterfaces ();
  1254. base.ExpandBaseInterfaces ();
  1255. }
  1256. public void DoExpandBaseInterfaces ()
  1257. {
  1258. if ((caching_flags & Flags.InterfacesExpanded) != 0)
  1259. return;
  1260. caching_flags |= Flags.InterfacesExpanded;
  1261. //
  1262. // Expand base interfaces. It cannot be done earlier because all partial
  1263. // interface parts need to be defined before the type they are used from
  1264. //
  1265. if (iface_exprs != null) {
  1266. foreach (var iface in iface_exprs) {
  1267. if (iface == null)
  1268. continue;
  1269. var td = iface.MemberDefinition as TypeDefinition;
  1270. if (td != null)
  1271. td.DoExpandBaseInterfaces ();
  1272. if (iface.Interfaces == null)
  1273. continue;
  1274. foreach (var biface in iface.Interfaces) {
  1275. if (spec.AddInterfaceDefined (biface)) {
  1276. TypeBuilder.AddInterfaceImplementation (biface.GetMetaInfo ());
  1277. }
  1278. }
  1279. }
  1280. }
  1281. //
  1282. // Include all base type interfaces too, see ImportTypeBase for details
  1283. //
  1284. if (base_type != null) {
  1285. var td = base_type.MemberDefinition as TypeDefinition;
  1286. if (td != null)
  1287. td.DoExpandBaseInterfaces ();
  1288. //
  1289. // Simply use base interfaces only, they are all expanded which makes
  1290. // it easy to handle generic type argument propagation with single
  1291. // inflator only.
  1292. //
  1293. // interface IA<T> : IB<T>
  1294. // interface IB<U> : IC<U>
  1295. // interface IC<V>
  1296. //
  1297. if (base_type.Interfaces != null) {
  1298. foreach (var iface in base_type.Interfaces) {
  1299. spec.AddInterfaceDefined (iface);
  1300. }
  1301. }
  1302. }
  1303. }
  1304. public override void PrepareEmit ()
  1305. {
  1306. if ((caching_flags & Flags.CloseTypeCreated) != 0)
  1307. return;
  1308. foreach (var member in members) {
  1309. var pm = member as IParametersMember;
  1310. if (pm != null) {
  1311. var p = pm.Parameters;
  1312. if (p.IsEmpty)
  1313. continue;
  1314. ((ParametersCompiled) p).ResolveDefaultValues (member);
  1315. }
  1316. var c = member as Const;
  1317. if (c != null)
  1318. c.DefineValue ();
  1319. }
  1320. base.PrepareEmit ();
  1321. }
  1322. //
  1323. // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
  1324. //
  1325. public override bool CreateContainer ()
  1326. {
  1327. if (TypeBuilder != null)
  1328. return !error;
  1329. if (error)
  1330. return false;
  1331. if (IsPartialPart) {
  1332. spec = PartialContainer.spec;
  1333. TypeBuilder = PartialContainer.TypeBuilder;
  1334. all_tp_builders = PartialContainer.all_tp_builders;
  1335. all_type_parameters = PartialContainer.all_type_parameters;
  1336. } else {
  1337. if (!CreateTypeBuilder ()) {
  1338. error = true;
  1339. return false;
  1340. }
  1341. }
  1342. return base.CreateContainer ();
  1343. }
  1344. protected override void DoDefineContainer ()
  1345. {
  1346. DefineBaseTypes ();
  1347. DoResolveTypeParameters ();
  1348. }
  1349. //
  1350. // Replaces normal spec with predefined one when compiling corlib
  1351. // and this type container defines predefined type
  1352. //
  1353. public void SetPredefinedSpec (BuiltinTypeSpec spec)
  1354. {
  1355. // When compiling build-in types we start with two
  1356. // version of same type. One is of BuiltinTypeSpec and
  1357. // second one is ordinary TypeSpec. The unification
  1358. // happens at later stage when we know which type
  1359. // really matches the builtin type signature. However
  1360. // that means TypeSpec create during CreateType of this
  1361. // type has to be replaced with builtin one
  1362. //
  1363. spec.SetMetaInfo (TypeBuilder);
  1364. spec.MemberCache = this.spec.MemberCache;
  1365. spec.DeclaringType = this.spec.DeclaringType;
  1366. this.spec = spec;
  1367. current_type = null;
  1368. }
  1369. void UpdateTypeParameterConstraints (TypeDefinition part)
  1370. {
  1371. for (int i = 0; i < CurrentTypeParameters.Count; i++) {
  1372. if (CurrentTypeParameters[i].AddPartialConstraints (part, part.MemberName.TypeParameters[i]))
  1373. continue;
  1374. Report.SymbolRelatedToPreviousError (Location, "");
  1375. Report.Error (265, part.Location,
  1376. "Partial declarations of `{0}' have inconsistent constraints for type parameter `{1}'",
  1377. GetSignatureForError (), CurrentTypeParameters[i].GetSignatureForError ());
  1378. }
  1379. }
  1380. public override void RemoveContainer (TypeContainer cont)
  1381. {
  1382. base.RemoveContainer (cont);
  1383. Members.Remove (cont);
  1384. Cache.Remove (cont.Basename);
  1385. }
  1386. protected virtual bool DoResolveTypeParameters ()
  1387. {
  1388. var tparams = CurrentTypeParameters;
  1389. if (tparams == null)
  1390. return true;
  1391. var base_context = new BaseContext (this);
  1392. for (int i = 0; i < tparams.Count; ++i) {
  1393. var tp = tparams[i];
  1394. if (!tp.ResolveConstraints (base_context)) {
  1395. error = true;
  1396. return false;
  1397. }
  1398. }
  1399. if (IsPartialPart) {
  1400. PartialContainer.UpdateTypeParameterConstraints (this);
  1401. }
  1402. return true;
  1403. }
  1404. TypeSpec CheckRecursiveDefinition (TypeDefinition tc)
  1405. {
  1406. if (InTransit != null)
  1407. return spec;
  1408. InTransit = tc;
  1409. if (base_type != null) {
  1410. var ptc = base_type.MemberDefinition as TypeDefinition;
  1411. if (ptc != null && ptc.CheckRecursiveDefinition (this) != null)
  1412. return base_type;
  1413. }
  1414. if (iface_exprs != null) {
  1415. foreach (var iface in iface_exprs) {
  1416. // the interface might not have been resolved, prevents a crash, see #442144
  1417. if (iface == null)
  1418. continue;
  1419. var ptc = iface.MemberDefinition as Interface;
  1420. if (ptc != null && ptc.CheckRecursiveDefinition (this) != null)
  1421. return iface;
  1422. }
  1423. }
  1424. if (!IsTopLevel && Parent.PartialContainer.CheckRecursiveDefinition (this) != null)
  1425. return spec;
  1426. InTransit = null;
  1427. return null;
  1428. }
  1429. /// <summary>
  1430. /// Populates our TypeBuilder with fields and methods
  1431. /// </summary>
  1432. public sealed override bool Define ()
  1433. {
  1434. if (members_defined)
  1435. return members_defined_ok;
  1436. members_defined_ok = DoDefineMembers ();
  1437. members_defined = true;
  1438. base.Define ();
  1439. return members_defined_ok;
  1440. }
  1441. protected virtual bool DoDefineMembers ()
  1442. {
  1443. Debug.Assert (!IsPartialPart);
  1444. if (iface_exprs != null) {
  1445. foreach (var iface_type in iface_exprs) {
  1446. if (iface_type == null)
  1447. continue;
  1448. // Ensure the base is always setup
  1449. var compiled_iface = iface_type.MemberDefinition as Interface;
  1450. if (compiled_iface != null)
  1451. compiled_iface.Define ();
  1452. ObsoleteAttribute oa = iface_type.GetAttributeObsolete ();
  1453. if (oa != null && !IsObsolete)
  1454. AttributeTester.Report_ObsoleteMessage (oa, iface_type.GetSignatureForError (), Location, Report);
  1455. if (iface_type.Arity > 0) {
  1456. // TODO: passing `this' is wrong, should be base type iface instead
  1457. TypeManager.CheckTypeVariance (iface_type, Variance.Covariant, this);
  1458. if (((InflatedTypeSpec) iface_type).HasDynamicArgument () && !IsCompilerGenerated) {
  1459. Report.Error (1966, Location,
  1460. "`{0}': cannot implement a dynamic interface `{1}'",
  1461. GetSignatureForError (), iface_type.GetSignatureForError ());
  1462. return false;
  1463. }
  1464. }
  1465. if (iface_type.IsGenericOrParentIsGeneric) {
  1466. foreach (var prev_iface in iface_exprs) {
  1467. if (prev_iface == iface_type || prev_iface == null)
  1468. break;
  1469. if (!TypeSpecComparer.Unify.IsEqual (iface_type, prev_iface))
  1470. continue;
  1471. Report.Error (695, Location,
  1472. "`{0}' cannot implement both `{1}' and `{2}' because they may unify for some type parameter substitutions",
  1473. GetSignatureForError (), prev_iface.GetSignatureForError (), iface_type.GetSignatureForError ());
  1474. }
  1475. }
  1476. }
  1477. if (Kind == MemberKind.Interface) {
  1478. foreach (var iface in spec.Interfaces) {
  1479. MemberCache.AddInterface (iface);
  1480. }
  1481. }
  1482. }
  1483. if (base_type != null) {
  1484. //
  1485. // Run checks skipped during DefineType (e.g FullNamedExpression::ResolveAsType)
  1486. //
  1487. if (base_type_expr != null) {
  1488. ObsoleteAttribute obsolete_attr = base_type.GetAttributeObsolete ();
  1489. if (obsolete_attr != null && !IsObsolete)
  1490. AttributeTester.Report_ObsoleteMessage (obsolete_attr, base_type.GetSignatureForError (), base_type_expr.Location, Report);
  1491. if (IsGenericOrParentIsGeneric && base_type.IsAttribute) {
  1492. Report.Error (698, base_type_expr.Location,
  1493. "A generic type cannot derive from `{0}' because it is an attribute class",
  1494. base_type.GetSignatureForError ());
  1495. }
  1496. }
  1497. var baseContainer = base_type.MemberDefinition as ClassOrStruct;
  1498. if (baseContainer != null) {
  1499. baseContainer.Define ();
  1500. //
  1501. // It can trigger define of this type (for generic types only)
  1502. //
  1503. if (HasMembersDefined)
  1504. return true;
  1505. }
  1506. }
  1507. if (Kind == MemberKind.Struct || Kind == MemberKind.Class) {
  1508. pending = PendingImplementation.GetPendingImplementations (this);
  1509. }
  1510. var count = members.Count;
  1511. for (int i = 0; i < count; ++i) {
  1512. var mc = members[i] as InterfaceMemberBase;
  1513. if (mc == null || !mc.IsExplicitImpl)
  1514. continue;
  1515. try {
  1516. mc.Define ();
  1517. } catch (Exception e) {
  1518. throw new InternalErrorException (mc, e);
  1519. }
  1520. }
  1521. for (int i = 0; i < count; ++i) {
  1522. var mc = members[i] as InterfaceMemberBase;
  1523. if (mc != null && mc.IsExplicitImpl)
  1524. continue;
  1525. if (members[i] is TypeContainer)
  1526. continue;
  1527. try {
  1528. members[i].Define ();
  1529. } catch (Exception e) {
  1530. throw new InternalErrorException (members[i], e);
  1531. }
  1532. }
  1533. if (HasOperators) {
  1534. CheckPairedOperators ();
  1535. }
  1536. if (requires_delayed_unmanagedtype_check) {
  1537. requires_delayed_unmanagedtype_check = false;
  1538. foreach (var member in members) {
  1539. var f = member as Field;
  1540. if (f != null && f.MemberType != null && f.MemberType.IsPointer)
  1541. TypeManager.VerifyUnmanaged (Module, f.MemberType, f.Location);
  1542. }
  1543. }
  1544. ComputeIndexerName();
  1545. if (HasEquals && !HasGetHashCode) {
  1546. Report.Warning (659, 3, Location,
  1547. "`{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", GetSignatureForError ());
  1548. }
  1549. if (Kind == MemberKind.Interface && iface_exprs != null) {
  1550. MemberCache.RemoveHiddenMembers (spec);
  1551. }
  1552. return true;
  1553. }
  1554. void ComputeIndexerName ()
  1555. {
  1556. var indexers = MemberCache.FindMembers (spec, MemberCache.IndexerNameAlias, true);
  1557. if (indexers == null)
  1558. return;
  1559. string class_indexer_name = null;
  1560. //
  1561. // Check normal indexers for consistent name, explicit interface implementation
  1562. // indexers are ignored
  1563. //
  1564. foreach (var indexer in indexers) {
  1565. //
  1566. // FindMembers can return unfiltered full hierarchy names
  1567. //
  1568. if (indexer.DeclaringType != spec)
  1569. continue;
  1570. has_normal_indexers = true;
  1571. if (class_indexer_name == null) {
  1572. indexer_name = class_indexer_name = indexer.Name;
  1573. continue;
  1574. }
  1575. if (indexer.Name != class_indexer_name)
  1576. Report.Error (668, ((Indexer)indexer.MemberDefinition).Location,
  1577. "Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type");
  1578. }
  1579. }
  1580. void EmitIndexerName ()
  1581. {
  1582. if (!has_normal_indexers)
  1583. return;
  1584. var ctor = Module.PredefinedMembers.DefaultMemberAttributeCtor.Get ();
  1585. if (ctor == null)
  1586. return;
  1587. var encoder = new AttributeEncoder ();
  1588. encoder.Encode (GetAttributeDefaultMember ());
  1589. encoder.EncodeEmptyNamedArguments ();
  1590. TypeBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
  1591. }
  1592. public override void VerifyMembers ()
  1593. {
  1594. //
  1595. // Check for internal or private fields that were never assigned
  1596. //
  1597. if (!IsCompilerGenerated && Compiler.Settings.WarningLevel >= 3 && this == PartialContainer) {
  1598. bool is_type_exposed = Kind == MemberKind.Struct || IsExposedFromAssembly ();
  1599. foreach (var member in members) {
  1600. if (member is Event) {
  1601. //
  1602. // An event can be assigned from same class only, so we can report
  1603. // this warning for all accessibility modes
  1604. //
  1605. if (!member.IsUsed)
  1606. Report.Warning (67, 3, member.Location, "The event `{0}' is never used", member.GetSignatureForError ());
  1607. continue;
  1608. }
  1609. if ((member.ModFlags & Modifiers.AccessibilityMask) != Modifiers.PRIVATE) {
  1610. if (is_type_exposed)
  1611. continue;
  1612. member.SetIsUsed ();
  1613. }
  1614. var f = member as Field;
  1615. if (f == null)
  1616. continue;
  1617. if (!member.IsUsed) {
  1618. if ((member.caching_flags & Flags.IsAssigned) == 0) {
  1619. Report.Warning (169, 3, member.Location, "The private field `{0}' is never used", member.GetSignatureForError ());
  1620. } else {
  1621. Report.Warning (414, 3, member.Location, "The private field `{0}' is assigned but its value is never used",
  1622. member.GetSignatureForError ());
  1623. }
  1624. continue;
  1625. }
  1626. if ((f.caching_flags & Flags.IsAssigned) != 0)
  1627. continue;
  1628. //
  1629. // Only report 649 on level 4
  1630. //
  1631. if (Compiler.Settings.WarningLevel < 4)
  1632. continue;
  1633. //
  1634. // Don't be pedantic when type requires specific layout
  1635. //
  1636. if (f.OptAttributes != null || PartialContainer.HasStructLayout)
  1637. continue;
  1638. Constant c = New.Constantify (f.MemberType, f.Location);
  1639. string value;
  1640. if (c != null) {
  1641. value = c.GetValueAsLiteral ();
  1642. } else if (TypeSpec.IsReferenceType (f.MemberType)) {
  1643. value = "null";
  1644. } else {
  1645. value = null;
  1646. }
  1647. if (value != null)
  1648. value = " `" + value + "'";
  1649. Report.Warning (649, 4, f.Location, "Field `{0}' is never assigned to, and will always have its default value{1}",
  1650. f.GetSignatureForError (), value);
  1651. }
  1652. }
  1653. base.VerifyMembers ();
  1654. }
  1655. public override void Emit ()
  1656. {
  1657. if (OptAttributes != null)
  1658. OptAttributes.Emit ();
  1659. if (!IsCompilerGenerated) {
  1660. if (!IsTopLevel) {
  1661. MemberSpec candidate;
  1662. bool overrides = false;
  1663. var conflict_symbol = MemberCache.FindBaseMember (this, out candidate, ref overrides);
  1664. if (conflict_symbol == null && candidate == null) {
  1665. if ((ModFlags & Modifiers.NEW) != 0)
  1666. Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required",
  1667. GetSignatureForError ());
  1668. } else {
  1669. if ((ModFlags & Modifiers.NEW) == 0) {
  1670. if (candidate == null)
  1671. candidate = conflict_symbol;
  1672. Report.SymbolRelatedToPreviousError (candidate);
  1673. Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
  1674. GetSignatureForError (), candidate.GetSignatureForError ());
  1675. }
  1676. }
  1677. }
  1678. // Run constraints check on all possible generic types
  1679. if (base_type != null && base_type_expr != null) {
  1680. ConstraintChecker.Check (this, base_type, base_type_expr.Location);
  1681. }
  1682. if (iface_exprs != null) {
  1683. foreach (var iface_type in iface_exprs) {
  1684. if (iface_type == null)
  1685. continue;
  1686. ConstraintChecker.Check (this, iface_type, Location); // TODO: Location is wrong
  1687. }
  1688. }
  1689. }
  1690. if (all_tp_builders != null) {
  1691. int current_starts_index = CurrentTypeParametersStartIndex;
  1692. for (int i = 0; i < all_tp_builders.Length; i++) {
  1693. if (i < current_starts_index) {
  1694. all_type_parameters[i].EmitConstraints (all_tp_builders [i]);
  1695. } else {
  1696. var tp = CurrentTypeParameters [i - current_starts_index];
  1697. tp.CheckGenericConstraints (!IsObsolete);
  1698. tp.Emit ();
  1699. }
  1700. }
  1701. }
  1702. if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
  1703. Module.PredefinedAttributes.CompilerGenerated.EmitAttribute (TypeBuilder);
  1704. #if STATIC
  1705. if ((TypeBuilder.Attributes & TypeAttributes.StringFormatMask) == 0 && Module.HasDefaultCharSet)
  1706. TypeBuilder.__SetAttributes (TypeBuilder.Attributes | Module.DefaultCharSetType);
  1707. #endif
  1708. base.Emit ();
  1709. for (int i = 0; i < members.Count; i++)
  1710. members[i].Emit ();
  1711. EmitIndexerName ();
  1712. CheckAttributeClsCompliance ();
  1713. if (pending != null)
  1714. pending.VerifyPendingMethods ();
  1715. }
  1716. void CheckAttributeClsCompliance ()
  1717. {
  1718. if (!spec.IsAttribute || !IsExposedFromAssembly () || !Compiler.Settings.VerifyClsCompliance || !IsClsComplianceRequired ())
  1719. return;
  1720. foreach (var m in members) {
  1721. var c = m as Constructor;
  1722. if (c == null)
  1723. continue;
  1724. if (c.HasCompliantArgs)
  1725. return;
  1726. }
  1727. Report.Warning (3015, 1, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
  1728. }
  1729. public sealed override void EmitContainer ()
  1730. {
  1731. if ((caching_flags & Flags.CloseTypeCreated) != 0)
  1732. return;
  1733. Emit ();
  1734. }
  1735. public override void CloseContainer ()
  1736. {
  1737. if ((caching_flags & Flags.CloseTypeCreated) != 0)
  1738. return;
  1739. // Close base type container first to avoid TypeLoadException
  1740. if (spec.BaseType != null) {
  1741. var btype = spec.BaseType.MemberDefinition as TypeContainer;
  1742. if (btype != null) {
  1743. btype.CloseContainer ();
  1744. if ((caching_flags & Flags.CloseTypeCreated) != 0)
  1745. return;
  1746. }
  1747. }
  1748. try {
  1749. caching_flags |= Flags.CloseTypeCreated;
  1750. TypeBuilder.CreateType ();
  1751. } catch (TypeLoadException) {
  1752. //
  1753. // This is fine, the code still created the type
  1754. //
  1755. } catch (Exception e) {
  1756. throw new InternalErrorException (this, e);
  1757. }
  1758. base.CloseContainer ();
  1759. containers = null;
  1760. initialized_fields = null;
  1761. initialized_static_fields = null;
  1762. type_bases = null;
  1763. OptAttributes = null;
  1764. }
  1765. //
  1766. // Performs the validation on a Method's modifiers (properties have
  1767. // the same properties).
  1768. //
  1769. // TODO: Why is it not done at parse stage, move to Modifiers::Check
  1770. //
  1771. public bool MethodModifiersValid (MemberCore mc)
  1772. {
  1773. const Modifiers vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
  1774. const Modifiers nv = (Modifiers.NEW | Modifiers.VIRTUAL);
  1775. bool ok = true;
  1776. var flags = mc.ModFlags;
  1777. //
  1778. // At most one of static, virtual or override
  1779. //
  1780. if ((flags & Modifiers.STATIC) != 0){
  1781. if ((flags & vao) != 0){
  1782. Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract",
  1783. mc.GetSignatureForError ());
  1784. ok = false;
  1785. }
  1786. }
  1787. if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
  1788. Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual",
  1789. mc.GetSignatureForError ());
  1790. ok = false;
  1791. }
  1792. //
  1793. // If the declaration includes the abstract modifier, then the
  1794. // declaration does not include static, virtual or extern
  1795. //
  1796. if ((flags & Modifiers.ABSTRACT) != 0){
  1797. if ((flags & Modifiers.EXTERN) != 0){
  1798. Report.Error (
  1799. 180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ());
  1800. ok = false;
  1801. }
  1802. if ((flags & Modifiers.SEALED) != 0) {
  1803. Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
  1804. ok = false;
  1805. }
  1806. if ((flags & Modifiers.VIRTUAL) != 0){
  1807. Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ());
  1808. ok = false;
  1809. }
  1810. if ((ModFlags & Modifiers.ABSTRACT) == 0){
  1811. Report.SymbolRelatedToPreviousError (this);
  1812. Report.Error (513, mc.Location, "`{0}' is abstract but it is declared in the non-abstract class `{1}'",
  1813. mc.GetSignatureForError (), GetSignatureForError ());
  1814. ok = false;
  1815. }
  1816. }
  1817. if ((flags & Modifiers.PRIVATE) != 0){
  1818. if ((flags & vao) != 0){
  1819. Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ());
  1820. ok = false;
  1821. }
  1822. }
  1823. if ((flags & Modifiers.SEALED) != 0){
  1824. if ((flags & Modifiers.OVERRIDE) == 0){
  1825. Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
  1826. ok = false;
  1827. }
  1828. }
  1829. return ok;
  1830. }
  1831. protected override bool VerifyClsCompliance ()
  1832. {
  1833. if (!base.VerifyClsCompliance ())
  1834. return false;
  1835. // Check all container names for user classes
  1836. if (Kind != MemberKind.Delegate)
  1837. MemberCache.VerifyClsCompliance (Definition, Report);
  1838. if (BaseType != null && !BaseType.IsCLSCompliant ()) {
  1839. Report.Warning (3009, 1, Location, "`{0}': base type `{1}' is not CLS-compliant",
  1840. GetSignatureForError (), BaseType.GetSignatureForError ());
  1841. }
  1842. return true;
  1843. }
  1844. /// <summary>
  1845. /// Performs checks for an explicit interface implementation. First it
  1846. /// checks whether the `interface_type' is a base inteface implementation.
  1847. /// Then it checks whether `name' exists in the interface type.
  1848. /// </summary>
  1849. public bool VerifyImplements (InterfaceMemberBase mb)
  1850. {
  1851. var ifaces = spec.Interfaces;
  1852. if (ifaces != null) {
  1853. foreach (TypeSpec t in ifaces){
  1854. if (t == mb.InterfaceType)
  1855. return true;
  1856. }
  1857. }
  1858. Report.SymbolRelatedToPreviousError (mb.InterfaceType);
  1859. Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
  1860. mb.GetSignatureForError (), TypeManager.CSharpName (mb.InterfaceType));
  1861. return false;
  1862. }
  1863. //
  1864. // Used for visiblity checks to tests whether this definition shares
  1865. // base type baseType, it does member-definition search
  1866. //
  1867. public bool IsBaseTypeDefinition (TypeSpec baseType)
  1868. {
  1869. // RootContext check
  1870. if (TypeBuilder == null)
  1871. return false;
  1872. var type = spec;
  1873. do {
  1874. if (type.MemberDefinition == baseType.MemberDefinition)
  1875. return true;
  1876. type = type.BaseType;
  1877. } while (type != null);
  1878. return false;
  1879. }
  1880. public override bool IsClsComplianceRequired ()
  1881. {
  1882. if (IsPartialPart)
  1883. return PartialContainer.IsClsComplianceRequired ();
  1884. return base.IsClsComplianceRequired ();
  1885. }
  1886. bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
  1887. {
  1888. return Module.DeclaringAssembly == assembly;
  1889. }
  1890. public virtual bool IsUnmanagedType ()
  1891. {
  1892. return false;
  1893. }
  1894. public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
  1895. {
  1896. throw new NotSupportedException ("Not supported for compiled definition " + GetSignatureForError ());
  1897. }
  1898. //
  1899. // Public function used to locate types.
  1900. //
  1901. // Set 'ignore_cs0104' to true if you want to ignore cs0104 errors.
  1902. //
  1903. // Returns: Type or null if they type can not be found.
  1904. //
  1905. public override FullNamedExpression LookupNamespaceOrType (string name, int arity, LookupMode mode, Location loc)
  1906. {
  1907. FullNamedExpression e;
  1908. if (arity == 0 && Cache.TryGetValue (name, out e) && mode != LookupMode.IgnoreAccessibility)
  1909. return e;
  1910. e = null;
  1911. if (arity == 0) {
  1912. var tp = CurrentTypeParameters;
  1913. if (tp != null) {
  1914. TypeParameter tparam = tp.Find (name);
  1915. if (tparam != null)
  1916. e = new TypeParameterExpr (tparam, Location.Null);
  1917. }
  1918. }
  1919. if (e == null) {
  1920. TypeSpec t = LookupNestedTypeInHierarchy (name, arity);
  1921. if (t != null && (t.IsAccessible (this) || mode == LookupMode.IgnoreAccessibility))
  1922. e = new TypeExpression (t, Location.Null);
  1923. else {
  1924. e = Parent.LookupNamespaceOrType (name, arity, mode, loc);
  1925. }
  1926. }
  1927. // TODO MemberCache: How to cache arity stuff ?
  1928. if (arity == 0 && mode == LookupMode.Normal)
  1929. Cache[name] = e;
  1930. return e;
  1931. }
  1932. TypeSpec LookupNestedTypeInHierarchy (string name, int arity)
  1933. {
  1934. // Has any nested type
  1935. // Does not work, because base type can have
  1936. //if (PartialContainer.Types == null)
  1937. // return null;
  1938. var container = PartialContainer.CurrentType;
  1939. return MemberCache.FindNestedType (container, name, arity);
  1940. }
  1941. public void Mark_HasEquals ()
  1942. {
  1943. cached_method |= CachedMethods.Equals;
  1944. }
  1945. public void Mark_HasGetHashCode ()
  1946. {
  1947. cached_method |= CachedMethods.GetHashCode;
  1948. }
  1949. public override void WriteDebugSymbol (MonoSymbolFile file)
  1950. {
  1951. if (IsPartialPart)
  1952. return;
  1953. foreach (var m in members) {
  1954. m.WriteDebugSymbol (file);
  1955. }
  1956. }
  1957. /// <summary>
  1958. /// Method container contains Equals method
  1959. /// </summary>
  1960. public bool HasEquals {
  1961. get {
  1962. return (cached_method & CachedMethods.Equals) != 0;
  1963. }
  1964. }
  1965. /// <summary>
  1966. /// Method container contains GetHashCode method
  1967. /// </summary>
  1968. public bool HasGetHashCode {
  1969. get {
  1970. return (cached_method & CachedMethods.GetHashCode) != 0;
  1971. }
  1972. }
  1973. public bool HasStaticFieldInitializer {
  1974. get {
  1975. return (cached_method & CachedMethods.HasStaticFieldInitializer) != 0;
  1976. }
  1977. set {
  1978. if (value)
  1979. cached_method |= CachedMethods.HasStaticFieldInitializer;
  1980. else
  1981. cached_method &= ~CachedMethods.HasStaticFieldInitializer;
  1982. }
  1983. }
  1984. public override string DocCommentHeader {
  1985. get { return "T:"; }
  1986. }
  1987. }
  1988. public abstract class ClassOrStruct : TypeDefinition
  1989. {
  1990. public const TypeAttributes StaticClassAttribute = TypeAttributes.Abstract | TypeAttributes.Sealed;
  1991. SecurityType declarative_security;
  1992. public ClassOrStruct (TypeContainer parent, MemberName name, Attributes attrs, MemberKind kind)
  1993. : base (parent, name, attrs, kind)
  1994. {
  1995. }
  1996. protected override TypeAttributes TypeAttr {
  1997. get {
  1998. TypeAttributes ta = base.TypeAttr;
  1999. if (!has_static_constructor)
  2000. ta |= TypeAttributes.BeforeFieldInit;
  2001. if (Kind == MemberKind.Class) {
  2002. ta |= TypeAttributes.AutoLayout | TypeAttributes.Class;
  2003. if (IsStatic)
  2004. ta |= StaticClassAttribute;
  2005. } else {
  2006. ta |= TypeAttributes.SequentialLayout;
  2007. }
  2008. return ta;
  2009. }
  2010. }
  2011. public override void AddNameToContainer (MemberCore symbol, string name)
  2012. {
  2013. if (!(symbol is Constructor) && symbol.MemberName.Name == MemberName.Name) {
  2014. if (symbol is TypeParameter) {
  2015. Report.Error (694, symbol.Location,
  2016. "Type parameter `{0}' has same name as containing type, or method",
  2017. symbol.GetSignatureForError ());
  2018. return;
  2019. }
  2020. InterfaceMemberBase imb = symbol as InterfaceMemberBase;
  2021. if (imb == null || !imb.IsExplicitImpl) {
  2022. Report.SymbolRelatedToPreviousError (this);
  2023. Report.Error (542, symbol.Location, "`{0}': member names cannot be the same as their enclosing type",
  2024. symbol.GetSignatureForError ());
  2025. return;
  2026. }
  2027. }
  2028. base.AddNameToContainer (symbol, name);
  2029. }
  2030. public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
  2031. {
  2032. if (a.IsValidSecurityAttribute ()) {
  2033. a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
  2034. return;
  2035. }
  2036. if (a.Type == pa.StructLayout) {
  2037. PartialContainer.HasStructLayout = true;
  2038. if (a.IsExplicitLayoutKind ())
  2039. PartialContainer.HasExplicitLayout = true;
  2040. }
  2041. if (a.Type == pa.Dynamic) {
  2042. a.Error_MisusedDynamicAttribute ();
  2043. return;
  2044. }
  2045. base.ApplyAttributeBuilder (a, ctor, cdata, pa);
  2046. }
  2047. /// <summary>
  2048. /// Defines the default constructors
  2049. /// </summary>
  2050. protected Constructor DefineDefaultConstructor (bool is_static)
  2051. {
  2052. // The default instance constructor is public
  2053. // If the class is abstract, the default constructor is protected
  2054. // The default static constructor is private
  2055. Modifiers mods;
  2056. if (is_static) {
  2057. mods = Modifiers.STATIC | Modifiers.PRIVATE;
  2058. } else {
  2059. mods = ((ModFlags & Modifiers.ABSTRACT) != 0) ? Modifiers.PROTECTED : Modifiers.PUBLIC;
  2060. }
  2061. var c = new Constructor (this, MemberName.Name, mods, null, ParametersCompiled.EmptyReadOnlyParameters, Location);
  2062. c.Initializer = new GeneratedBaseInitializer (Location);
  2063. AddConstructor (c, true);
  2064. c.Block = new ToplevelBlock (Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location) {
  2065. IsCompilerGenerated = true
  2066. };
  2067. return c;
  2068. }
  2069. protected override bool DoDefineMembers ()
  2070. {
  2071. CheckProtectedModifier ();
  2072. base.DoDefineMembers ();
  2073. return true;
  2074. }
  2075. public override void Emit ()
  2076. {
  2077. if (!has_static_constructor && HasStaticFieldInitializer) {
  2078. var c = DefineDefaultConstructor (true);
  2079. c.Define ();
  2080. }
  2081. base.Emit ();
  2082. if (declarative_security != null) {
  2083. foreach (var de in declarative_security) {
  2084. #if STATIC
  2085. TypeBuilder.__AddDeclarativeSecurity (de);
  2086. #else
  2087. TypeBuilder.AddDeclarativeSecurity (de.Key, de.Value);
  2088. #endif
  2089. }
  2090. }
  2091. }
  2092. }
  2093. public sealed class Class : ClassOrStruct
  2094. {
  2095. const Modifiers AllowedModifiers =
  2096. Modifiers.NEW |
  2097. Modifiers.PUBLIC |
  2098. Modifiers.PROTECTED |
  2099. Modifiers.INTERNAL |
  2100. Modifiers.PRIVATE |
  2101. Modifiers.ABSTRACT |
  2102. Modifiers.SEALED |
  2103. Modifiers.STATIC |
  2104. Modifiers.UNSAFE;
  2105. public Class (TypeContainer parent, MemberName name, Modifiers mod, Attributes attrs)
  2106. : base (parent, name, attrs, MemberKind.Class)
  2107. {
  2108. var accmods = IsTopLevel ? Modifiers.INTERNAL : Modifiers.PRIVATE;
  2109. this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, Location, Report);
  2110. spec = new TypeSpec (Kind, null, this, null, ModFlags);
  2111. }
  2112. public override void Accept (StructuralVisitor visitor)
  2113. {
  2114. visitor.Visit (this);
  2115. }
  2116. public override void AddBasesForPart (List<FullNamedExpression> bases)
  2117. {
  2118. var pmn = MemberName;
  2119. if (pmn.Name == "Object" && !pmn.IsGeneric && Parent.MemberName.Name == "System" && Parent.MemberName.Left == null)
  2120. Report.Error (537, Location,
  2121. "The class System.Object cannot have a base class or implement an interface.");
  2122. base.AddBasesForPart (bases);
  2123. }
  2124. public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
  2125. {
  2126. if (a.Type == pa.AttributeUsage) {
  2127. if (!BaseType.IsAttribute && spec.BuiltinType != BuiltinTypeSpec.Type.Attribute) {
  2128. Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
  2129. }
  2130. }
  2131. if (a.Type == pa.Conditional && !BaseType.IsAttribute) {
  2132. Report.Error (1689, a.Location, "Attribute `System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
  2133. return;
  2134. }
  2135. if (a.Type == pa.ComImport && !attributes.Contains (pa.Guid)) {
  2136. a.Error_MissingGuidAttribute ();
  2137. return;
  2138. }
  2139. if (a.Type == pa.Extension) {
  2140. a.Error_MisusedExtensionAttribute ();
  2141. return;
  2142. }
  2143. if (a.Type.IsConditionallyExcluded (this, Location))
  2144. return;
  2145. base.ApplyAttributeBuilder (a, ctor, cdata, pa);
  2146. }
  2147. public override AttributeTargets AttributeTargets {
  2148. get {
  2149. return AttributeTargets.Class;
  2150. }
  2151. }
  2152. protected override bool DoDefineMembers ()
  2153. {
  2154. if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
  2155. Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
  2156. }
  2157. if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
  2158. Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
  2159. }
  2160. if (IsStatic) {
  2161. foreach (var m in Members) {
  2162. if (m is Operator) {
  2163. Report.Error (715, m.Location, "`{0}': Static classes cannot contain user-defined operators", m.GetSignatureForError ());
  2164. continue;
  2165. }
  2166. if (m is Destructor) {
  2167. Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
  2168. continue;
  2169. }
  2170. if (m is Indexer) {
  2171. Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
  2172. continue;
  2173. }
  2174. if ((m.ModFlags & Modifiers.STATIC) != 0 || m is TypeContainer)
  2175. continue;
  2176. if (m is Constructor) {
  2177. Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
  2178. continue;
  2179. }
  2180. Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
  2181. }
  2182. } else {
  2183. if (!PartialContainer.HasInstanceConstructor)
  2184. DefineDefaultConstructor (false);
  2185. }
  2186. return base.DoDefineMembers ();
  2187. }
  2188. public override void Emit ()
  2189. {
  2190. base.Emit ();
  2191. if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
  2192. Module.PredefinedAttributes.Extension.EmitAttribute (TypeBuilder);
  2193. if (base_type != null && base_type.HasDynamicElement) {
  2194. Module.PredefinedAttributes.Dynamic.EmitAttribute (TypeBuilder, base_type, Location);
  2195. }
  2196. }
  2197. protected override TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class)
  2198. {
  2199. var ifaces = base.ResolveBaseTypes (out base_class);
  2200. if (base_class == null) {
  2201. if (spec.BuiltinType != BuiltinTypeSpec.Type.Object)
  2202. base_type = Compiler.BuiltinTypes.Object;
  2203. } else {
  2204. if (base_type.IsGenericParameter){
  2205. Report.Error (689, base_class.Location, "`{0}': Cannot derive from type parameter `{1}'",
  2206. GetSignatureForError (), base_type.GetSignatureForError ());
  2207. } else if (base_type.IsStatic) {
  2208. Report.SymbolRelatedToPreviousError (base_type);
  2209. Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
  2210. GetSignatureForError (), base_type.GetSignatureForError ());
  2211. } else if (base_type.IsSealed) {
  2212. Report.SymbolRelatedToPreviousError (base_type);
  2213. Report.Error (509, Location, "`{0}': cannot derive from sealed type `{1}'",
  2214. GetSignatureForError (), base_type.GetSignatureForError ());
  2215. } else if (PartialContainer.IsStatic && base_type.BuiltinType != BuiltinTypeSpec.Type.Object) {
  2216. Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object",
  2217. GetSignatureForError (), base_type.GetSignatureForError ());
  2218. }
  2219. switch (base_type.BuiltinType) {
  2220. case BuiltinTypeSpec.Type.Enum:
  2221. case BuiltinTypeSpec.Type.ValueType:
  2222. case BuiltinTypeSpec.Type.MulticastDelegate:
  2223. case BuiltinTypeSpec.Type.Delegate:
  2224. case BuiltinTypeSpec.Type.Array:
  2225. if (!(spec is BuiltinTypeSpec)) {
  2226. Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
  2227. GetSignatureForError (), base_type.GetSignatureForError ());
  2228. base_type = Compiler.BuiltinTypes.Object;
  2229. }
  2230. break;
  2231. }
  2232. if (!IsAccessibleAs (base_type)) {
  2233. Report.SymbolRelatedToPreviousError (base_type);
  2234. Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
  2235. base_type.GetSignatureForError (), GetSignatureForError ());
  2236. }
  2237. }
  2238. if (PartialContainer.IsStatic && ifaces != null) {
  2239. foreach (var t in ifaces)
  2240. Report.SymbolRelatedToPreviousError (t);
  2241. Report.Error (714, Location, "Static class `{0}' cannot implement interfaces", GetSignatureForError ());
  2242. }
  2243. return ifaces;
  2244. }
  2245. /// Search for at least one defined condition in ConditionalAttribute of attribute class
  2246. /// Valid only for attribute classes.
  2247. public override string[] ConditionalConditions ()
  2248. {
  2249. if ((caching_flags & (Flags.Excluded_Undetected | Flags.Excluded)) == 0)
  2250. return null;
  2251. caching_flags &= ~Flags.Excluded_Undetected;
  2252. if (OptAttributes == null)
  2253. return null;
  2254. Attribute[] attrs = OptAttributes.SearchMulti (Module.PredefinedAttributes.Conditional);
  2255. if (attrs == null)
  2256. return null;
  2257. string[] conditions = new string[attrs.Length];
  2258. for (int i = 0; i < conditions.Length; ++i)
  2259. conditions[i] = attrs[i].GetConditionalAttributeValue ();
  2260. caching_flags |= Flags.Excluded;
  2261. return conditions;
  2262. }
  2263. }
  2264. public sealed class Struct : ClassOrStruct
  2265. {
  2266. bool is_unmanaged, has_unmanaged_check_done;
  2267. bool InTransit;
  2268. // <summary>
  2269. // Modifiers allowed in a struct declaration
  2270. // </summary>
  2271. const Modifiers AllowedModifiers =
  2272. Modifiers.NEW |
  2273. Modifiers.PUBLIC |
  2274. Modifiers.PROTECTED |
  2275. Modifiers.INTERNAL |
  2276. Modifiers.UNSAFE |
  2277. Modifiers.PRIVATE;
  2278. public Struct (TypeContainer parent, MemberName name, Modifiers mod, Attributes attrs)
  2279. : base (parent, name, attrs, MemberKind.Struct)
  2280. {
  2281. var accmods = IsTopLevel ? Modifiers.INTERNAL : Modifiers.PRIVATE;
  2282. this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, Location, Report) | Modifiers.SEALED ;
  2283. spec = new TypeSpec (Kind, null, this, null, ModFlags);
  2284. }
  2285. public override AttributeTargets AttributeTargets {
  2286. get {
  2287. return AttributeTargets.Struct;
  2288. }
  2289. }
  2290. public override void Accept (StructuralVisitor visitor)
  2291. {
  2292. visitor.Visit (this);
  2293. }
  2294. public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
  2295. {
  2296. base.ApplyAttributeBuilder (a, ctor, cdata, pa);
  2297. //
  2298. // When struct constains fixed fixed and struct layout has explicitly
  2299. // set CharSet, its value has to be propagated to compiler generated
  2300. // fixed types
  2301. //
  2302. if (a.Type == pa.StructLayout) {
  2303. var value = a.GetNamedValue ("CharSet");
  2304. if (value == null)
  2305. return;
  2306. for (int i = 0; i < Members.Count; ++i) {
  2307. FixedField ff = Members [i] as FixedField;
  2308. if (ff == null)
  2309. continue;
  2310. ff.CharSet = (CharSet) System.Enum.Parse (typeof (CharSet), value.GetValue ().ToString ());
  2311. }
  2312. }
  2313. }
  2314. bool CheckStructCycles ()
  2315. {
  2316. if (InTransit)
  2317. return false;
  2318. InTransit = true;
  2319. foreach (var member in Members) {
  2320. var field = member as Field;
  2321. if (field == null)
  2322. continue;
  2323. TypeSpec ftype = field.Spec.MemberType;
  2324. if (!ftype.IsStruct)
  2325. continue;
  2326. if (ftype is BuiltinTypeSpec)
  2327. continue;
  2328. foreach (var targ in ftype.TypeArguments) {
  2329. if (!CheckFieldTypeCycle (targ)) {
  2330. Report.Error (523, field.Location,
  2331. "Struct member `{0}' of type `{1}' causes a cycle in the struct layout",
  2332. field.GetSignatureForError (), ftype.GetSignatureForError ());
  2333. break;
  2334. }
  2335. }
  2336. //
  2337. // Static fields of exactly same type are allowed
  2338. //
  2339. if (field.IsStatic && ftype == CurrentType)
  2340. continue;
  2341. if (!CheckFieldTypeCycle (ftype)) {
  2342. Report.Error (523, field.Location,
  2343. "Struct member `{0}' of type `{1}' causes a cycle in the struct layout",
  2344. field.GetSignatureForError (), ftype.GetSignatureForError ());
  2345. break;
  2346. }
  2347. }
  2348. InTransit = false;
  2349. return true;
  2350. }
  2351. static bool CheckFieldTypeCycle (TypeSpec ts)
  2352. {
  2353. var fts = ts.MemberDefinition as Struct;
  2354. if (fts == null)
  2355. return true;
  2356. return fts.CheckStructCycles ();
  2357. }
  2358. public override void Emit ()
  2359. {
  2360. CheckStructCycles ();
  2361. base.Emit ();
  2362. }
  2363. public override bool IsUnmanagedType ()
  2364. {
  2365. if (has_unmanaged_check_done)
  2366. return is_unmanaged;
  2367. if (requires_delayed_unmanagedtype_check)
  2368. return true;
  2369. var parent_def = Parent.PartialContainer;
  2370. if (parent_def != null && parent_def.IsGenericOrParentIsGeneric) {
  2371. has_unmanaged_check_done = true;
  2372. return false;
  2373. }
  2374. if (first_nonstatic_field != null) {
  2375. requires_delayed_unmanagedtype_check = true;
  2376. foreach (var member in Members) {
  2377. var f = member as Field;
  2378. if (f == null)
  2379. continue;
  2380. if (f.IsStatic)
  2381. continue;
  2382. // It can happen when recursive unmanaged types are defined
  2383. // struct S { S* s; }
  2384. TypeSpec mt = f.MemberType;
  2385. if (mt == null) {
  2386. return true;
  2387. }
  2388. if (mt.IsUnmanaged)
  2389. continue;
  2390. has_unmanaged_check_done = true;
  2391. return false;
  2392. }
  2393. has_unmanaged_check_done = true;
  2394. }
  2395. is_unmanaged = true;
  2396. return true;
  2397. }
  2398. protected override TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class)
  2399. {
  2400. var ifaces = base.ResolveBaseTypes (out base_class);
  2401. base_type = Compiler.BuiltinTypes.ValueType;
  2402. return ifaces;
  2403. }
  2404. public override void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
  2405. {
  2406. if ((field.ModFlags & Modifiers.STATIC) == 0) {
  2407. Report.Error (573, field.Location, "`{0}': Structs cannot have instance field initializers",
  2408. field.GetSignatureForError ());
  2409. return;
  2410. }
  2411. base.RegisterFieldForInitialization (field, expression);
  2412. }
  2413. }
  2414. /// <summary>
  2415. /// Interfaces
  2416. /// </summary>
  2417. public sealed class Interface : TypeDefinition {
  2418. /// <summary>
  2419. /// Modifiers allowed in a class declaration
  2420. /// </summary>
  2421. const Modifiers AllowedModifiers =
  2422. Modifiers.NEW |
  2423. Modifiers.PUBLIC |
  2424. Modifiers.PROTECTED |
  2425. Modifiers.INTERNAL |
  2426. Modifiers.UNSAFE |
  2427. Modifiers.PRIVATE;
  2428. public Interface (TypeContainer parent, MemberName name, Modifiers mod, Attributes attrs)
  2429. : base (parent, name, attrs, MemberKind.Interface)
  2430. {
  2431. var accmods = IsTopLevel ? Modifiers.INTERNAL : Modifiers.PRIVATE;
  2432. this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, name.Location, Report);
  2433. spec = new TypeSpec (Kind, null, this, null, ModFlags);
  2434. }
  2435. #region Properties
  2436. public override AttributeTargets AttributeTargets {
  2437. get {
  2438. return AttributeTargets.Interface;
  2439. }
  2440. }
  2441. protected override TypeAttributes TypeAttr {
  2442. get {
  2443. const TypeAttributes DefaultTypeAttributes =
  2444. TypeAttributes.AutoLayout |
  2445. TypeAttributes.Abstract |
  2446. TypeAttributes.Interface;
  2447. return base.TypeAttr | DefaultTypeAttributes;
  2448. }
  2449. }
  2450. #endregion
  2451. public override void Accept (StructuralVisitor visitor)
  2452. {
  2453. visitor.Visit (this);
  2454. }
  2455. public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
  2456. {
  2457. if (a.Type == pa.ComImport && !attributes.Contains (pa.Guid)) {
  2458. a.Error_MissingGuidAttribute ();
  2459. return;
  2460. }
  2461. base.ApplyAttributeBuilder (a, ctor, cdata, pa);
  2462. }
  2463. protected override bool VerifyClsCompliance ()
  2464. {
  2465. if (!base.VerifyClsCompliance ())
  2466. return false;
  2467. if (iface_exprs != null) {
  2468. foreach (var iface in iface_exprs) {
  2469. if (iface.IsCLSCompliant ())
  2470. continue;
  2471. Report.SymbolRelatedToPreviousError (iface);
  2472. Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
  2473. GetSignatureForError (), TypeManager.CSharpName (iface));
  2474. }
  2475. }
  2476. return true;
  2477. }
  2478. }
  2479. public abstract class InterfaceMemberBase : MemberBase
  2480. {
  2481. //
  2482. // Common modifiers allowed in a class declaration
  2483. //
  2484. protected const Modifiers AllowedModifiersClass =
  2485. Modifiers.NEW |
  2486. Modifiers.PUBLIC |
  2487. Modifiers.PROTECTED |
  2488. Modifiers.INTERNAL |
  2489. Modifiers.PRIVATE |
  2490. Modifiers.STATIC |
  2491. Modifiers.VIRTUAL |
  2492. Modifiers.SEALED |
  2493. Modifiers.OVERRIDE |
  2494. Modifiers.ABSTRACT |
  2495. Modifiers.UNSAFE |
  2496. Modifiers.EXTERN;
  2497. //
  2498. // Common modifiers allowed in a struct declaration
  2499. //
  2500. protected const Modifiers AllowedModifiersStruct =
  2501. Modifiers.NEW |
  2502. Modifiers.PUBLIC |
  2503. Modifiers.PROTECTED |
  2504. Modifiers.INTERNAL |
  2505. Modifiers.PRIVATE |
  2506. Modifiers.STATIC |
  2507. Modifiers.OVERRIDE |
  2508. Modifiers.UNSAFE |
  2509. Modifiers.EXTERN;
  2510. //
  2511. // Common modifiers allowed in a interface declaration
  2512. //
  2513. protected const Modifiers AllowedModifiersInterface =
  2514. Modifiers.NEW |
  2515. Modifiers.UNSAFE;
  2516. //
  2517. // Whether this is an interface member.
  2518. //
  2519. public bool IsInterface;
  2520. //
  2521. // If true, this is an explicit interface implementation
  2522. //
  2523. public readonly bool IsExplicitImpl;
  2524. protected bool is_external_implementation;
  2525. //
  2526. // The interface type we are explicitly implementing
  2527. //
  2528. public TypeSpec InterfaceType;
  2529. //
  2530. // The method we're overriding if this is an override method.
  2531. //
  2532. protected MethodSpec base_method;
  2533. readonly Modifiers explicit_mod_flags;
  2534. public MethodAttributes flags;
  2535. public InterfaceMemberBase (TypeDefinition parent, FullNamedExpression type, Modifiers mod, Modifiers allowed_mod, MemberName name, Attributes attrs)
  2536. : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE, name, attrs)
  2537. {
  2538. IsInterface = parent.Kind == MemberKind.Interface;
  2539. IsExplicitImpl = (MemberName.ExplicitInterface != null);
  2540. explicit_mod_flags = mod;
  2541. }
  2542. public abstract Variance ExpectedMemberTypeVariance { get; }
  2543. protected override bool CheckBase ()
  2544. {
  2545. if (!base.CheckBase ())
  2546. return false;
  2547. if ((caching_flags & Flags.MethodOverloadsExist) != 0)
  2548. CheckForDuplications ();
  2549. if (IsExplicitImpl)
  2550. return true;
  2551. // For System.Object only
  2552. if (Parent.BaseType == null)
  2553. return true;
  2554. MemberSpec candidate;
  2555. bool overrides = false;
  2556. var base_member = FindBaseMember (out candidate, ref overrides);
  2557. if ((ModFlags & Modifiers.OVERRIDE) != 0) {
  2558. if (base_member == null) {
  2559. if (candidate == null) {
  2560. if (this is Method && ((Method)this).ParameterInfo.IsEmpty && MemberName.Name == Destructor.MetadataName && MemberName.Arity == 0) {
  2561. Report.Error (249, Location, "Do not override `{0}'. Use destructor syntax instead",
  2562. "object.Finalize()");
  2563. } else {
  2564. Report.Error (115, Location, "`{0}' is marked as an override but no suitable {1} found to override",
  2565. GetSignatureForError (), SimpleName.GetMemberType (this));
  2566. }
  2567. } else {
  2568. Report.SymbolRelatedToPreviousError (candidate);
  2569. if (this is Event)
  2570. Report.Error (72, Location, "`{0}': cannot override because `{1}' is not an event",
  2571. GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
  2572. else if (this is PropertyBase)
  2573. Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property",
  2574. GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
  2575. else
  2576. Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method",
  2577. GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
  2578. }
  2579. return false;
  2580. }
  2581. //
  2582. // Handles ambiguous overrides
  2583. //
  2584. if (candidate != null) {
  2585. Report.SymbolRelatedToPreviousError (candidate);
  2586. Report.SymbolRelatedToPreviousError (base_member);
  2587. // Get member definition for error reporting
  2588. var m1 = MemberCache.GetMember (base_member.DeclaringType.GetDefinition (), base_member);
  2589. var m2 = MemberCache.GetMember (candidate.DeclaringType.GetDefinition (), candidate);
  2590. Report.Error (462, Location,
  2591. "`{0}' cannot override inherited members `{1}' and `{2}' because they have the same signature when used in type `{3}'",
  2592. GetSignatureForError (), m1.GetSignatureForError (), m2.GetSignatureForError (), Parent.GetSignatureForError ());
  2593. }
  2594. if (!CheckOverrideAgainstBase (base_member))
  2595. return false;
  2596. ObsoleteAttribute oa = base_member.GetAttributeObsolete ();
  2597. if (oa != null) {
  2598. if (OptAttributes == null || !OptAttributes.Contains (Module.PredefinedAttributes.Obsolete)) {
  2599. Report.SymbolRelatedToPreviousError (base_member);
  2600. Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
  2601. GetSignatureForError (), base_member.GetSignatureForError ());
  2602. }
  2603. } else {
  2604. if (OptAttributes != null && OptAttributes.Contains (Module.PredefinedAttributes.Obsolete)) {
  2605. Report.SymbolRelatedToPreviousError (base_member);
  2606. Report.Warning (809, 1, Location, "Obsolete member `{0}' overrides non-obsolete member `{1}'",
  2607. GetSignatureForError (), base_member.GetSignatureForError ());
  2608. }
  2609. }
  2610. base_method = base_member as MethodSpec;
  2611. return true;
  2612. }
  2613. if (base_member == null && candidate != null && (!(candidate is IParametersMember) || !(this is IParametersMember)))
  2614. base_member = candidate;
  2615. if (base_member == null) {
  2616. if ((ModFlags & Modifiers.NEW) != 0) {
  2617. if (base_member == null) {
  2618. Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required",
  2619. GetSignatureForError ());
  2620. }
  2621. }
  2622. } else {
  2623. if ((ModFlags & Modifiers.NEW) == 0) {
  2624. ModFlags |= Modifiers.NEW;
  2625. if (!IsCompilerGenerated) {
  2626. Report.SymbolRelatedToPreviousError (base_member);
  2627. if (!IsInterface && (base_member.Modifiers & (Modifiers.ABSTRACT | Modifiers.VIRTUAL | Modifiers.OVERRIDE)) != 0) {
  2628. Report.Warning (114, 2, Location, "`{0}' hides inherited member `{1}'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword",
  2629. GetSignatureForError (), base_member.GetSignatureForError ());
  2630. } else {
  2631. Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
  2632. GetSignatureForError (), base_member.GetSignatureForError ());
  2633. }
  2634. }
  2635. }
  2636. if (!IsInterface && base_member.IsAbstract && !overrides) {
  2637. Report.SymbolRelatedToPreviousError (base_member);
  2638. Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
  2639. GetSignatureForError (), base_member.GetSignatureForError ());
  2640. }
  2641. }
  2642. return true;
  2643. }
  2644. protected virtual bool CheckForDuplications ()
  2645. {
  2646. return Parent.MemberCache.CheckExistingMembersOverloads (this, ParametersCompiled.EmptyReadOnlyParameters);
  2647. }
  2648. //
  2649. // Performs various checks on the MethodInfo `mb' regarding the modifier flags
  2650. // that have been defined.
  2651. //
  2652. protected virtual bool CheckOverrideAgainstBase (MemberSpec base_member)
  2653. {
  2654. bool ok = true;
  2655. if ((base_member.Modifiers & (Modifiers.ABSTRACT | Modifiers.VIRTUAL | Modifiers.OVERRIDE)) == 0) {
  2656. Report.SymbolRelatedToPreviousError (base_member);
  2657. Report.Error (506, Location,
  2658. "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
  2659. GetSignatureForError (), TypeManager.CSharpSignature (base_member));
  2660. ok = false;
  2661. }
  2662. // Now we check that the overriden method is not final
  2663. if ((base_member.Modifiers & Modifiers.SEALED) != 0) {
  2664. Report.SymbolRelatedToPreviousError (base_member);
  2665. Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
  2666. GetSignatureForError (), TypeManager.CSharpSignature (base_member));
  2667. ok = false;
  2668. }
  2669. var base_member_type = ((IInterfaceMemberSpec) base_member).MemberType;
  2670. if (!TypeSpecComparer.Override.IsEqual (MemberType, base_member_type)) {
  2671. Report.SymbolRelatedToPreviousError (base_member);
  2672. if (this is PropertyBasedMember) {
  2673. Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
  2674. GetSignatureForError (), TypeManager.CSharpName (base_member_type), TypeManager.CSharpSignature (base_member));
  2675. } else {
  2676. Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
  2677. GetSignatureForError (), TypeManager.CSharpName (base_member_type), TypeManager.CSharpSignature (base_member));
  2678. }
  2679. ok = false;
  2680. }
  2681. return ok;
  2682. }
  2683. protected static bool CheckAccessModifiers (MemberCore this_member, MemberSpec base_member)
  2684. {
  2685. var thisp = this_member.ModFlags & Modifiers.AccessibilityMask;
  2686. var base_classp = base_member.Modifiers & Modifiers.AccessibilityMask;
  2687. if ((base_classp & (Modifiers.PROTECTED | Modifiers.INTERNAL)) == (Modifiers.PROTECTED | Modifiers.INTERNAL)) {
  2688. //
  2689. // It must be at least "protected"
  2690. //
  2691. if ((thisp & Modifiers.PROTECTED) == 0) {
  2692. return false;
  2693. }
  2694. //
  2695. // when overriding protected internal, the method can be declared
  2696. // protected internal only within the same assembly or assembly
  2697. // which has InternalsVisibleTo
  2698. //
  2699. if ((thisp & Modifiers.INTERNAL) != 0) {
  2700. return base_member.DeclaringType.MemberDefinition.IsInternalAsPublic (this_member.Module.DeclaringAssembly);
  2701. }
  2702. //
  2703. // protected overriding protected internal inside same assembly
  2704. // requires internal modifier as well
  2705. //
  2706. if (base_member.DeclaringType.MemberDefinition.IsInternalAsPublic (this_member.Module.DeclaringAssembly)) {
  2707. return false;
  2708. }
  2709. return true;
  2710. }
  2711. return thisp == base_classp;
  2712. }
  2713. public override bool Define ()
  2714. {
  2715. if (IsInterface) {
  2716. ModFlags = Modifiers.PUBLIC | Modifiers.ABSTRACT |
  2717. Modifiers.VIRTUAL | (ModFlags & (Modifiers.UNSAFE | Modifiers.NEW));
  2718. flags = MethodAttributes.Public |
  2719. MethodAttributes.Abstract |
  2720. MethodAttributes.HideBySig |
  2721. MethodAttributes.NewSlot |
  2722. MethodAttributes.Virtual;
  2723. } else {
  2724. Parent.PartialContainer.MethodModifiersValid (this);
  2725. flags = ModifiersExtensions.MethodAttr (ModFlags);
  2726. }
  2727. if (IsExplicitImpl) {
  2728. InterfaceType = MemberName.ExplicitInterface.ResolveAsType (Parent);
  2729. if (InterfaceType == null)
  2730. return false;
  2731. if ((ModFlags & Modifiers.PARTIAL) != 0) {
  2732. Report.Error (754, Location, "A partial method `{0}' cannot explicitly implement an interface",
  2733. GetSignatureForError ());
  2734. }
  2735. if (!InterfaceType.IsInterface) {
  2736. Report.SymbolRelatedToPreviousError (InterfaceType);
  2737. Report.Error (538, Location, "The type `{0}' in explicit interface declaration is not an interface",
  2738. TypeManager.CSharpName (InterfaceType));
  2739. } else {
  2740. Parent.PartialContainer.VerifyImplements (this);
  2741. }
  2742. ModifiersExtensions.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location, Report);
  2743. }
  2744. return base.Define ();
  2745. }
  2746. protected bool DefineParameters (ParametersCompiled parameters)
  2747. {
  2748. if (!parameters.Resolve (this))
  2749. return false;
  2750. bool error = false;
  2751. for (int i = 0; i < parameters.Count; ++i) {
  2752. Parameter p = parameters [i];
  2753. if (p.HasDefaultValue && (IsExplicitImpl || this is Operator || (this is Indexer && parameters.Count == 1)))
  2754. p.Warning_UselessOptionalParameter (Report);
  2755. if (p.CheckAccessibility (this))
  2756. continue;
  2757. TypeSpec t = parameters.Types [i];
  2758. Report.SymbolRelatedToPreviousError (t);
  2759. if (this is Indexer)
  2760. Report.Error (55, Location,
  2761. "Inconsistent accessibility: parameter type `{0}' is less accessible than indexer `{1}'",
  2762. TypeManager.CSharpName (t), GetSignatureForError ());
  2763. else if (this is Operator)
  2764. Report.Error (57, Location,
  2765. "Inconsistent accessibility: parameter type `{0}' is less accessible than operator `{1}'",
  2766. TypeManager.CSharpName (t), GetSignatureForError ());
  2767. else
  2768. Report.Error (51, Location,
  2769. "Inconsistent accessibility: parameter type `{0}' is less accessible than method `{1}'",
  2770. TypeManager.CSharpName (t), GetSignatureForError ());
  2771. error = true;
  2772. }
  2773. return !error;
  2774. }
  2775. protected override void DoMemberTypeDependentChecks ()
  2776. {
  2777. base.DoMemberTypeDependentChecks ();
  2778. TypeManager.CheckTypeVariance (MemberType, ExpectedMemberTypeVariance, this);
  2779. }
  2780. public override void Emit()
  2781. {
  2782. // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
  2783. // We are more strict than csc and report this as an error because SRE does not allow emit that
  2784. if ((ModFlags & Modifiers.EXTERN) != 0 && !is_external_implementation && (OptAttributes == null || !OptAttributes.HasResolveError ())) {
  2785. if (this is Constructor) {
  2786. Report.Warning (824, 1, Location,
  2787. "Constructor `{0}' is marked `external' but has no external implementation specified", GetSignatureForError ());
  2788. } else {
  2789. Report.Warning (626, 1, Location,
  2790. "`{0}' is marked as an external but has no DllImport attribute. Consider adding a DllImport attribute to specify the external implementation",
  2791. GetSignatureForError ());
  2792. }
  2793. }
  2794. base.Emit ();
  2795. }
  2796. public override bool EnableOverloadChecks (MemberCore overload)
  2797. {
  2798. //
  2799. // Two members can differ in their explicit interface
  2800. // type parameter only
  2801. //
  2802. InterfaceMemberBase imb = overload as InterfaceMemberBase;
  2803. if (imb != null && imb.IsExplicitImpl) {
  2804. if (IsExplicitImpl) {
  2805. caching_flags |= Flags.MethodOverloadsExist;
  2806. }
  2807. return true;
  2808. }
  2809. return IsExplicitImpl;
  2810. }
  2811. protected void Error_CannotChangeAccessModifiers (MemberCore member, MemberSpec base_member)
  2812. {
  2813. var base_modifiers = base_member.Modifiers;
  2814. // Remove internal modifier from types which are not internally accessible
  2815. if ((base_modifiers & Modifiers.AccessibilityMask) == (Modifiers.PROTECTED | Modifiers.INTERNAL) &&
  2816. !base_member.DeclaringType.MemberDefinition.IsInternalAsPublic (member.Module.DeclaringAssembly))
  2817. base_modifiers = Modifiers.PROTECTED;
  2818. Report.SymbolRelatedToPreviousError (base_member);
  2819. Report.Error (507, member.Location,
  2820. "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
  2821. member.GetSignatureForError (),
  2822. ModifiersExtensions.AccessibilityName (base_modifiers),
  2823. base_member.GetSignatureForError ());
  2824. }
  2825. protected void Error_StaticReturnType ()
  2826. {
  2827. Report.Error (722, Location,
  2828. "`{0}': static types cannot be used as return types",
  2829. MemberType.GetSignatureForError ());
  2830. }
  2831. /// <summary>
  2832. /// Gets base method and its return type
  2833. /// </summary>
  2834. protected virtual MemberSpec FindBaseMember (out MemberSpec bestCandidate, ref bool overrides)
  2835. {
  2836. return MemberCache.FindBaseMember (this, out bestCandidate, ref overrides);
  2837. }
  2838. //
  2839. // The "short" name of this property / indexer / event. This is the
  2840. // name without the explicit interface.
  2841. //
  2842. public string ShortName {
  2843. get { return MemberName.Name; }
  2844. }
  2845. //
  2846. // Returns full metadata method name
  2847. //
  2848. public string GetFullName (MemberName name)
  2849. {
  2850. return GetFullName (name.Name);
  2851. }
  2852. public string GetFullName (string name)
  2853. {
  2854. if (!IsExplicitImpl)
  2855. return name;
  2856. //
  2857. // When dealing with explicit members a full interface type
  2858. // name is added to member name to avoid possible name conflicts
  2859. //
  2860. // We use CSharpName which gets us full name with benefit of
  2861. // replacing predefined names which saves some space and name
  2862. // is still unique
  2863. //
  2864. return TypeManager.CSharpName (InterfaceType) + "." + name;
  2865. }
  2866. public override string GetSignatureForDocumentation ()
  2867. {
  2868. if (IsExplicitImpl)
  2869. return Parent.GetSignatureForDocumentation () + "." + InterfaceType.GetExplicitNameSignatureForDocumentation () + "#" + ShortName;
  2870. return Parent.GetSignatureForDocumentation () + "." + ShortName;
  2871. }
  2872. public override bool IsUsed
  2873. {
  2874. get { return IsExplicitImpl || base.IsUsed; }
  2875. }
  2876. public override void SetConstraints (List<Constraints> constraints_list)
  2877. {
  2878. if (((ModFlags & Modifiers.OVERRIDE) != 0 || IsExplicitImpl)) {
  2879. Report.Error (460, Location,
  2880. "`{0}': Cannot specify constraints for overrides and explicit interface implementation methods",
  2881. GetSignatureForError ());
  2882. }
  2883. base.SetConstraints (constraints_list);
  2884. }
  2885. }
  2886. public abstract class MemberBase : MemberCore
  2887. {
  2888. protected FullNamedExpression type_expr;
  2889. protected TypeSpec member_type;
  2890. public new TypeDefinition Parent;
  2891. protected MemberBase (TypeDefinition parent, FullNamedExpression type, Modifiers mod, Modifiers allowed_mod, Modifiers def_mod, MemberName name, Attributes attrs)
  2892. : base (parent, name, attrs)
  2893. {
  2894. this.Parent = parent;
  2895. this.type_expr = type;
  2896. ModFlags = ModifiersExtensions.Check (allowed_mod, mod, def_mod, Location, Report);
  2897. }
  2898. #region Properties
  2899. public TypeSpec MemberType {
  2900. get {
  2901. return member_type;
  2902. }
  2903. }
  2904. public FullNamedExpression TypeExpression {
  2905. get {
  2906. return type_expr;
  2907. }
  2908. }
  2909. #endregion
  2910. //
  2911. // Main member define entry
  2912. //
  2913. public override bool Define ()
  2914. {
  2915. DoMemberTypeIndependentChecks ();
  2916. //
  2917. // Returns false only when type resolution failed
  2918. //
  2919. if (!ResolveMemberType ())
  2920. return false;
  2921. DoMemberTypeDependentChecks ();
  2922. return true;
  2923. }
  2924. //
  2925. // Any type_name independent checks
  2926. //
  2927. protected virtual void DoMemberTypeIndependentChecks ()
  2928. {
  2929. if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
  2930. (ModFlags & (Modifiers.VIRTUAL | Modifiers.ABSTRACT)) != 0) {
  2931. Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
  2932. GetSignatureForError (), Parent.GetSignatureForError ());
  2933. }
  2934. }
  2935. //
  2936. // Any type_name dependent checks
  2937. //
  2938. protected virtual void DoMemberTypeDependentChecks ()
  2939. {
  2940. // verify accessibility
  2941. if (!IsAccessibleAs (MemberType)) {
  2942. Report.SymbolRelatedToPreviousError (MemberType);
  2943. if (this is Property)
  2944. Report.Error (53, Location,
  2945. "Inconsistent accessibility: property type `" +
  2946. TypeManager.CSharpName (MemberType) + "' is less " +
  2947. "accessible than property `" + GetSignatureForError () + "'");
  2948. else if (this is Indexer)
  2949. Report.Error (54, Location,
  2950. "Inconsistent accessibility: indexer return type `" +
  2951. TypeManager.CSharpName (MemberType) + "' is less " +
  2952. "accessible than indexer `" + GetSignatureForError () + "'");
  2953. else if (this is MethodCore) {
  2954. if (this is Operator)
  2955. Report.Error (56, Location,
  2956. "Inconsistent accessibility: return type `" +
  2957. TypeManager.CSharpName (MemberType) + "' is less " +
  2958. "accessible than operator `" + GetSignatureForError () + "'");
  2959. else
  2960. Report.Error (50, Location,
  2961. "Inconsistent accessibility: return type `" +
  2962. TypeManager.CSharpName (MemberType) + "' is less " +
  2963. "accessible than method `" + GetSignatureForError () + "'");
  2964. } else {
  2965. Report.Error (52, Location,
  2966. "Inconsistent accessibility: field type `" +
  2967. TypeManager.CSharpName (MemberType) + "' is less " +
  2968. "accessible than field `" + GetSignatureForError () + "'");
  2969. }
  2970. }
  2971. }
  2972. protected void IsTypePermitted ()
  2973. {
  2974. if (MemberType.IsSpecialRuntimeType) {
  2975. if (Parent is StateMachine) {
  2976. Report.Error (4012, Location,
  2977. "Parameters or local variables of type `{0}' cannot be declared in async methods or iterators",
  2978. MemberType.GetSignatureForError ());
  2979. } else if (Parent is HoistedStoreyClass) {
  2980. Report.Error (4013, Location,
  2981. "Local variables of type `{0}' cannot be used inside anonymous methods, lambda expressions or query expressions",
  2982. MemberType.GetSignatureForError ());
  2983. } else {
  2984. Report.Error (610, Location,
  2985. "Field or property cannot be of type `{0}'", MemberType.GetSignatureForError ());
  2986. }
  2987. }
  2988. }
  2989. protected virtual bool CheckBase ()
  2990. {
  2991. CheckProtectedModifier ();
  2992. return true;
  2993. }
  2994. public override string GetSignatureForDocumentation ()
  2995. {
  2996. return Parent.GetSignatureForDocumentation () + "." + MemberName.Basename;
  2997. }
  2998. protected virtual bool ResolveMemberType ()
  2999. {
  3000. if (member_type != null)
  3001. throw new InternalErrorException ("Multi-resolve");
  3002. member_type = type_expr.ResolveAsType (this);
  3003. return member_type != null;
  3004. }
  3005. }
  3006. }