PageRenderTime 47ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/src/Libraries/NewNRefactory/ICSharpCode.NRefactory.CSharp/Parser/mcs/ecore.cs

http://github.com/icsharpcode/SharpDevelop
C# | 6442 lines | 4510 code | 1065 blank | 867 comment | 1305 complexity | 09d7c15b599589235347866a4446af12 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, CPL-1.0, LGPL-2.1
  1. //
  2. // ecore.cs: Core of the Expression representation for the intermediate tree.
  3. //
  4. // Author:
  5. // Miguel de Icaza (miguel@ximian.com)
  6. // Marek Safar (marek.safar@seznam.cz)
  7. //
  8. // Copyright 2001, 2002, 2003 Ximian, Inc.
  9. // Copyright 2003-2008 Novell, Inc.
  10. // Copyright 2011 Xamarin Inc.
  11. //
  12. //
  13. using System;
  14. using System.Collections.Generic;
  15. using System.Text;
  16. using SLE = System.Linq.Expressions;
  17. using System.Linq;
  18. #if STATIC
  19. using IKVM.Reflection;
  20. using IKVM.Reflection.Emit;
  21. #else
  22. using System.Reflection;
  23. using System.Reflection.Emit;
  24. #endif
  25. namespace Mono.CSharp {
  26. /// <remarks>
  27. /// The ExprClass class contains the is used to pass the
  28. /// classification of an expression (value, variable, namespace,
  29. /// type, method group, property access, event access, indexer access,
  30. /// nothing).
  31. /// </remarks>
  32. public enum ExprClass : byte {
  33. Unresolved = 0,
  34. Value,
  35. Variable,
  36. Namespace,
  37. Type,
  38. TypeParameter,
  39. MethodGroup,
  40. PropertyAccess,
  41. EventAccess,
  42. IndexerAccess,
  43. Nothing,
  44. }
  45. /// <remarks>
  46. /// This is used to tell Resolve in which types of expressions we're
  47. /// interested.
  48. /// </remarks>
  49. [Flags]
  50. public enum ResolveFlags {
  51. // Returns Value, Variable, PropertyAccess, EventAccess or IndexerAccess.
  52. VariableOrValue = 1,
  53. // Returns a type expression.
  54. Type = 1 << 1,
  55. // Returns a method group.
  56. MethodGroup = 1 << 2,
  57. TypeParameter = 1 << 3,
  58. // Mask of all the expression class flags.
  59. MaskExprClass = VariableOrValue | Type | MethodGroup | TypeParameter,
  60. }
  61. //
  62. // This is just as a hint to AddressOf of what will be done with the
  63. // address.
  64. [Flags]
  65. public enum AddressOp {
  66. Store = 1,
  67. Load = 2,
  68. LoadStore = 3
  69. };
  70. /// <summary>
  71. /// This interface is implemented by variables
  72. /// </summary>
  73. public interface IMemoryLocation {
  74. /// <summary>
  75. /// The AddressOf method should generate code that loads
  76. /// the address of the object and leaves it on the stack.
  77. ///
  78. /// The `mode' argument is used to notify the expression
  79. /// of whether this will be used to read from the address or
  80. /// write to the address.
  81. ///
  82. /// This is just a hint that can be used to provide good error
  83. /// reporting, and should have no other side effects.
  84. /// </summary>
  85. void AddressOf (EmitContext ec, AddressOp mode);
  86. }
  87. //
  88. // An expressions resolved as a direct variable reference
  89. //
  90. public interface IVariableReference : IFixedExpression
  91. {
  92. bool IsHoisted { get; }
  93. string Name { get; }
  94. VariableInfo VariableInfo { get; }
  95. void SetHasAddressTaken ();
  96. }
  97. //
  98. // Implemented by an expression which could be or is always
  99. // fixed
  100. //
  101. public interface IFixedExpression
  102. {
  103. bool IsFixed { get; }
  104. }
  105. public interface IExpressionCleanup
  106. {
  107. void EmitCleanup (EmitContext ec);
  108. }
  109. /// <remarks>
  110. /// Base class for expressions
  111. /// </remarks>
  112. public abstract class Expression {
  113. public ExprClass eclass;
  114. protected TypeSpec type;
  115. protected Location loc;
  116. public TypeSpec Type {
  117. get { return type; }
  118. set { type = value; }
  119. }
  120. public virtual bool IsSideEffectFree {
  121. get {
  122. return false;
  123. }
  124. }
  125. public Location Location {
  126. get { return loc; }
  127. }
  128. public virtual bool IsNull {
  129. get {
  130. return false;
  131. }
  132. }
  133. //
  134. // Returns true when the expression during Emit phase breaks stack
  135. // by using await expression
  136. //
  137. public virtual bool ContainsEmitWithAwait ()
  138. {
  139. return false;
  140. }
  141. /// <summary>
  142. /// Performs semantic analysis on the Expression
  143. /// </summary>
  144. ///
  145. /// <remarks>
  146. /// The Resolve method is invoked to perform the semantic analysis
  147. /// on the node.
  148. ///
  149. /// The return value is an expression (it can be the
  150. /// same expression in some cases) or a new
  151. /// expression that better represents this node.
  152. ///
  153. /// For example, optimizations of Unary (LiteralInt)
  154. /// would return a new LiteralInt with a negated
  155. /// value.
  156. ///
  157. /// If there is an error during semantic analysis,
  158. /// then an error should be reported (using Report)
  159. /// and a null value should be returned.
  160. ///
  161. /// There are two side effects expected from calling
  162. /// Resolve(): the the field variable "eclass" should
  163. /// be set to any value of the enumeration
  164. /// `ExprClass' and the type variable should be set
  165. /// to a valid type (this is the type of the
  166. /// expression).
  167. /// </remarks>
  168. protected abstract Expression DoResolve (ResolveContext rc);
  169. public virtual Expression DoResolveLValue (ResolveContext rc, Expression right_side)
  170. {
  171. return null;
  172. }
  173. //
  174. // This is used if the expression should be resolved as a type or namespace name.
  175. // the default implementation fails.
  176. //
  177. public virtual TypeSpec ResolveAsType (IMemberContext mc)
  178. {
  179. ResolveContext ec = new ResolveContext (mc);
  180. Expression e = Resolve (ec);
  181. if (e != null)
  182. e.Error_UnexpectedKind (ec, ResolveFlags.Type, loc);
  183. return null;
  184. }
  185. public static void ErrorIsInaccesible (IMemberContext rc, string member, Location loc)
  186. {
  187. rc.Module.Compiler.Report.Error (122, loc, "`{0}' is inaccessible due to its protection level", member);
  188. }
  189. public void Error_ExpressionMustBeConstant (ResolveContext rc, Location loc, string e_name)
  190. {
  191. rc.Report.Error (133, loc, "The expression being assigned to `{0}' must be constant", e_name);
  192. }
  193. public void Error_ConstantCanBeInitializedWithNullOnly (ResolveContext rc, TypeSpec type, Location loc, string name)
  194. {
  195. rc.Report.Error (134, loc, "A constant `{0}' of reference type `{1}' can only be initialized with null",
  196. name, TypeManager.CSharpName (type));
  197. }
  198. public static void Error_InvalidExpressionStatement (Report Report, Location loc)
  199. {
  200. Report.Error (201, loc, "Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement");
  201. }
  202. public void Error_InvalidExpressionStatement (BlockContext ec)
  203. {
  204. Error_InvalidExpressionStatement (ec.Report, loc);
  205. }
  206. public static void Error_VoidInvalidInTheContext (Location loc, Report Report)
  207. {
  208. Report.Error (1547, loc, "Keyword `void' cannot be used in this context");
  209. }
  210. public virtual void Error_ValueCannotBeConverted (ResolveContext ec, TypeSpec target, bool expl)
  211. {
  212. Error_ValueCannotBeConvertedCore (ec, loc, target, expl);
  213. }
  214. protected void Error_ValueCannotBeConvertedCore (ResolveContext ec, Location loc, TypeSpec target, bool expl)
  215. {
  216. // The error was already reported as CS1660
  217. if (type == InternalType.AnonymousMethod || type == InternalType.ErrorType)
  218. return;
  219. string from_type = type.GetSignatureForError ();
  220. string to_type = target.GetSignatureForError ();
  221. if (from_type == to_type) {
  222. from_type = type.GetSignatureForErrorIncludingAssemblyName ();
  223. to_type = target.GetSignatureForErrorIncludingAssemblyName ();
  224. }
  225. if (expl) {
  226. ec.Report.Error (30, loc, "Cannot convert type `{0}' to `{1}'",
  227. from_type, to_type);
  228. return;
  229. }
  230. ec.Report.DisableReporting ();
  231. bool expl_exists = Convert.ExplicitConversion (ec, this, target, Location.Null) != null;
  232. ec.Report.EnableReporting ();
  233. if (expl_exists) {
  234. ec.Report.Error (266, loc,
  235. "Cannot implicitly convert type `{0}' to `{1}'. An explicit conversion exists (are you missing a cast?)",
  236. from_type, to_type);
  237. } else {
  238. ec.Report.Error (29, loc, "Cannot implicitly convert type `{0}' to `{1}'",
  239. from_type, to_type);
  240. }
  241. }
  242. public void Error_TypeArgumentsCannotBeUsed (IMemberContext context, MemberSpec member, int arity, Location loc)
  243. {
  244. // Better message for possible generic expressions
  245. if (member != null && (member.Kind & MemberKind.GenericMask) != 0) {
  246. var report = context.Module.Compiler.Report;
  247. report.SymbolRelatedToPreviousError (member);
  248. if (member is TypeSpec)
  249. member = ((TypeSpec) member).GetDefinition ();
  250. else
  251. member = ((MethodSpec) member).GetGenericMethodDefinition ();
  252. string name = member.Kind == MemberKind.Method ? "method" : "type";
  253. if (member.IsGeneric) {
  254. report.Error (305, loc, "Using the generic {0} `{1}' requires `{2}' type argument(s)",
  255. name, member.GetSignatureForError (), member.Arity.ToString ());
  256. } else {
  257. report.Error (308, loc, "The non-generic {0} `{1}' cannot be used with the type arguments",
  258. name, member.GetSignatureForError ());
  259. }
  260. } else {
  261. Error_TypeArgumentsCannotBeUsed (context, ExprClassName, GetSignatureForError (), loc);
  262. }
  263. }
  264. public void Error_TypeArgumentsCannotBeUsed (IMemberContext context, string exprType, string name, Location loc)
  265. {
  266. context.Module.Compiler.Report.Error (307, loc, "The {0} `{1}' cannot be used with type arguments",
  267. exprType, name);
  268. }
  269. protected virtual void Error_TypeDoesNotContainDefinition (ResolveContext ec, TypeSpec type, string name)
  270. {
  271. Error_TypeDoesNotContainDefinition (ec, loc, type, name);
  272. }
  273. public static void Error_TypeDoesNotContainDefinition (ResolveContext ec, Location loc, TypeSpec type, string name)
  274. {
  275. ec.Report.SymbolRelatedToPreviousError (type);
  276. ec.Report.Error (117, loc, "`{0}' does not contain a definition for `{1}'",
  277. TypeManager.CSharpName (type), name);
  278. }
  279. public virtual void Error_ValueAssignment (ResolveContext rc, Expression rhs)
  280. {
  281. if (rhs == EmptyExpression.LValueMemberAccess || rhs == EmptyExpression.LValueMemberOutAccess) {
  282. rc.Report.SymbolRelatedToPreviousError (type);
  283. if (rc.CurrentInitializerVariable != null) {
  284. rc.Report.Error (1918, loc, "Members of value type `{0}' cannot be assigned using a property `{1}' object initializer",
  285. type.GetSignatureForError (), GetSignatureForError ());
  286. } else {
  287. rc.Report.Error (1612, loc, "Cannot modify a value type return value of `{0}'. Consider storing the value in a temporary variable",
  288. GetSignatureForError ());
  289. }
  290. } else {
  291. rc.Report.Error (131, loc, "The left-hand side of an assignment must be a variable, a property or an indexer");
  292. }
  293. }
  294. protected void Error_VoidPointerOperation (ResolveContext rc)
  295. {
  296. rc.Report.Error (242, loc, "The operation in question is undefined on void pointers");
  297. }
  298. public ResolveFlags ExprClassToResolveFlags {
  299. get {
  300. switch (eclass) {
  301. case ExprClass.Type:
  302. case ExprClass.Namespace:
  303. return ResolveFlags.Type;
  304. case ExprClass.MethodGroup:
  305. return ResolveFlags.MethodGroup;
  306. case ExprClass.TypeParameter:
  307. return ResolveFlags.TypeParameter;
  308. case ExprClass.Value:
  309. case ExprClass.Variable:
  310. case ExprClass.PropertyAccess:
  311. case ExprClass.EventAccess:
  312. case ExprClass.IndexerAccess:
  313. return ResolveFlags.VariableOrValue;
  314. default:
  315. throw new InternalErrorException (loc.ToString () + " " + GetType () + " ExprClass is Invalid after resolve");
  316. }
  317. }
  318. }
  319. public virtual string GetSignatureForError ()
  320. {
  321. return type.GetDefinition ().GetSignatureForError ();
  322. }
  323. /// <summary>
  324. /// Resolves an expression and performs semantic analysis on it.
  325. /// </summary>
  326. ///
  327. /// <remarks>
  328. /// Currently Resolve wraps DoResolve to perform sanity
  329. /// checking and assertion checking on what we expect from Resolve.
  330. /// </remarks>
  331. public Expression Resolve (ResolveContext ec, ResolveFlags flags)
  332. {
  333. if (eclass != ExprClass.Unresolved)
  334. return this;
  335. Expression e;
  336. try {
  337. e = DoResolve (ec);
  338. if (e == null)
  339. return null;
  340. if ((flags & e.ExprClassToResolveFlags) == 0) {
  341. e.Error_UnexpectedKind (ec, flags, loc);
  342. return null;
  343. }
  344. if (e.type == null)
  345. throw new InternalErrorException ("Expression `{0}' didn't set its type in DoResolve", e.GetType ());
  346. return e;
  347. } catch (Exception ex) {
  348. if (loc.IsNull || ec.Module.Compiler.Settings.DebugFlags > 0 || ex is CompletionResult || ec.Report.IsDisabled || ex is FatalException)
  349. throw;
  350. ec.Report.Error (584, loc, "Internal compiler error: {0}", ex.Message);
  351. return ErrorExpression.Instance; // TODO: Add location
  352. }
  353. }
  354. /// <summary>
  355. /// Resolves an expression and performs semantic analysis on it.
  356. /// </summary>
  357. public Expression Resolve (ResolveContext rc)
  358. {
  359. return Resolve (rc, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
  360. }
  361. /// <summary>
  362. /// Resolves an expression for LValue assignment
  363. /// </summary>
  364. ///
  365. /// <remarks>
  366. /// Currently ResolveLValue wraps DoResolveLValue to perform sanity
  367. /// checking and assertion checking on what we expect from Resolve
  368. /// </remarks>
  369. public Expression ResolveLValue (ResolveContext ec, Expression right_side)
  370. {
  371. int errors = ec.Report.Errors;
  372. bool out_access = right_side == EmptyExpression.OutAccess;
  373. Expression e = DoResolveLValue (ec, right_side);
  374. if (e != null && out_access && !(e is IMemoryLocation)) {
  375. // FIXME: There's no problem with correctness, the 'Expr = null' handles that.
  376. // Enabling this 'throw' will "only" result in deleting useless code elsewhere,
  377. //throw new InternalErrorException ("ResolveLValue didn't return an IMemoryLocation: " +
  378. // e.GetType () + " " + e.GetSignatureForError ());
  379. e = null;
  380. }
  381. if (e == null) {
  382. if (errors == ec.Report.Errors) {
  383. if (out_access)
  384. ec.Report.Error (1510, loc, "A ref or out argument must be an assignable variable");
  385. else
  386. Error_ValueAssignment (ec, right_side);
  387. }
  388. return null;
  389. }
  390. if (e.eclass == ExprClass.Unresolved)
  391. throw new Exception ("Expression " + e + " ExprClass is Invalid after resolve");
  392. if ((e.type == null) && !(e is GenericTypeExpr))
  393. throw new Exception ("Expression " + e + " did not set its type after Resolve");
  394. return e;
  395. }
  396. public virtual void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
  397. {
  398. rc.Module.Compiler.Report.Error (182, loc,
  399. "An attribute argument must be a constant expression, typeof expression or array creation expression");
  400. }
  401. /// <summary>
  402. /// Emits the code for the expression
  403. /// </summary>
  404. ///
  405. /// <remarks>
  406. /// The Emit method is invoked to generate the code
  407. /// for the expression.
  408. /// </remarks>
  409. public abstract void Emit (EmitContext ec);
  410. // Emit code to branch to @target if this expression is equivalent to @on_true.
  411. // The default implementation is to emit the value, and then emit a brtrue or brfalse.
  412. // Subclasses can provide more efficient implementations, but those MUST be equivalent,
  413. // including the use of conditional branches. Note also that a branch MUST be emitted
  414. public virtual void EmitBranchable (EmitContext ec, Label target, bool on_true)
  415. {
  416. Emit (ec);
  417. ec.Emit (on_true ? OpCodes.Brtrue : OpCodes.Brfalse, target);
  418. }
  419. // Emit this expression for its side effects, not for its value.
  420. // The default implementation is to emit the value, and then throw it away.
  421. // Subclasses can provide more efficient implementations, but those MUST be equivalent
  422. public virtual void EmitSideEffect (EmitContext ec)
  423. {
  424. Emit (ec);
  425. ec.Emit (OpCodes.Pop);
  426. }
  427. //
  428. // Emits the expression into temporary field variable. The method
  429. // should be used for await expressions only
  430. //
  431. public virtual Expression EmitToField (EmitContext ec)
  432. {
  433. //
  434. // This is the await prepare Emit method. When emitting code like
  435. // a + b we emit code like
  436. //
  437. // a.Emit ()
  438. // b.Emit ()
  439. // Opcodes.Add
  440. //
  441. // For await a + await b we have to interfere the flow to keep the
  442. // stack clean because await yields from the expression. The emit
  443. // then changes to
  444. //
  445. // a = a.EmitToField () // a is changed to temporary field access
  446. // b = b.EmitToField ()
  447. // a.Emit ()
  448. // b.Emit ()
  449. // Opcodes.Add
  450. //
  451. //
  452. // The idea is to emit expression and leave the stack empty with
  453. // result value still available.
  454. //
  455. // Expressions should override this default implementation when
  456. // optimized version can be provided (e.g. FieldExpr)
  457. //
  458. //
  459. // We can optimize for side-effect free expressions, they can be
  460. // emitted out of order
  461. //
  462. if (IsSideEffectFree)
  463. return this;
  464. bool needs_temporary = ContainsEmitWithAwait ();
  465. if (!needs_temporary)
  466. ec.EmitThis ();
  467. // Emit original code
  468. var field = EmitToFieldSource (ec);
  469. if (field == null) {
  470. //
  471. // Store the result to temporary field when we
  472. // cannot load `this' directly
  473. //
  474. field = ec.GetTemporaryField (type);
  475. if (needs_temporary) {
  476. //
  477. // Create temporary local (we cannot load `this' before Emit)
  478. //
  479. var temp = ec.GetTemporaryLocal (type);
  480. ec.Emit (OpCodes.Stloc, temp);
  481. ec.EmitThis ();
  482. ec.Emit (OpCodes.Ldloc, temp);
  483. field.EmitAssignFromStack (ec);
  484. ec.FreeTemporaryLocal (temp, type);
  485. } else {
  486. field.EmitAssignFromStack (ec);
  487. }
  488. }
  489. return field;
  490. }
  491. protected virtual FieldExpr EmitToFieldSource (EmitContext ec)
  492. {
  493. //
  494. // Default implementation calls Emit method
  495. //
  496. Emit (ec);
  497. return null;
  498. }
  499. protected static void EmitExpressionsList (EmitContext ec, List<Expression> expressions)
  500. {
  501. if (ec.HasSet (BuilderContext.Options.AsyncBody)) {
  502. bool contains_await = false;
  503. for (int i = 1; i < expressions.Count; ++i) {
  504. if (expressions[i].ContainsEmitWithAwait ()) {
  505. contains_await = true;
  506. break;
  507. }
  508. }
  509. if (contains_await) {
  510. for (int i = 0; i < expressions.Count; ++i) {
  511. expressions[i] = expressions[i].EmitToField (ec);
  512. }
  513. }
  514. }
  515. for (int i = 0; i < expressions.Count; ++i) {
  516. expressions[i].Emit (ec);
  517. }
  518. }
  519. /// <summary>
  520. /// Protected constructor. Only derivate types should
  521. /// be able to be created
  522. /// </summary>
  523. protected Expression ()
  524. {
  525. }
  526. /// <summary>
  527. /// Returns a fully formed expression after a MemberLookup
  528. /// </summary>
  529. ///
  530. static Expression ExprClassFromMemberInfo (MemberSpec spec, Location loc)
  531. {
  532. if (spec is EventSpec)
  533. return new EventExpr ((EventSpec) spec, loc);
  534. if (spec is ConstSpec)
  535. return new ConstantExpr ((ConstSpec) spec, loc);
  536. if (spec is FieldSpec)
  537. return new FieldExpr ((FieldSpec) spec, loc);
  538. if (spec is PropertySpec)
  539. return new PropertyExpr ((PropertySpec) spec, loc);
  540. if (spec is TypeSpec)
  541. return new TypeExpression (((TypeSpec) spec), loc);
  542. return null;
  543. }
  544. public static MethodSpec ConstructorLookup (ResolveContext rc, TypeSpec type, ref Arguments args, Location loc)
  545. {
  546. var ctors = MemberCache.FindMembers (type, Constructor.ConstructorName, true);
  547. if (ctors == null) {
  548. rc.Report.SymbolRelatedToPreviousError (type);
  549. if (type.IsStruct) {
  550. // Report meaningful error for struct as they always have default ctor in C# context
  551. OverloadResolver.Error_ConstructorMismatch (rc, type, args == null ? 0 : args.Count, loc);
  552. } else {
  553. rc.Report.Error (143, loc, "The class `{0}' has no constructors defined",
  554. type.GetSignatureForError ());
  555. }
  556. return null;
  557. }
  558. var r = new OverloadResolver (ctors, OverloadResolver.Restrictions.NoBaseMembers, loc);
  559. if (!rc.HasSet (ResolveContext.Options.BaseInitializer)) {
  560. r.InstanceQualifier = new ConstructorInstanceQualifier (type);
  561. }
  562. return r.ResolveMember<MethodSpec> (rc, ref args);
  563. }
  564. [Flags]
  565. public enum MemberLookupRestrictions
  566. {
  567. None = 0,
  568. InvocableOnly = 1,
  569. ExactArity = 1 << 2,
  570. ReadAccess = 1 << 3
  571. }
  572. //
  573. // Lookup type `queried_type' for code in class `container_type' with a qualifier of
  574. // `qualifier_type' or null to lookup members in the current class.
  575. //
  576. public static Expression MemberLookup (IMemberContext rc, bool errorMode, TypeSpec queried_type, string name, int arity, MemberLookupRestrictions restrictions, Location loc)
  577. {
  578. var members = MemberCache.FindMembers (queried_type, name, false);
  579. if (members == null)
  580. return null;
  581. MemberSpec non_method = null;
  582. MemberSpec ambig_non_method = null;
  583. do {
  584. for (int i = 0; i < members.Count; ++i) {
  585. var member = members[i];
  586. // HACK: for events because +=/-= can appear at same class only, should use OverrideToBase there
  587. if ((member.Modifiers & Modifiers.OVERRIDE) != 0 && member.Kind != MemberKind.Event)
  588. continue;
  589. if ((member.Modifiers & Modifiers.BACKING_FIELD) != 0)
  590. continue;
  591. if ((arity > 0 || (restrictions & MemberLookupRestrictions.ExactArity) != 0) && member.Arity != arity)
  592. continue;
  593. if (!errorMode) {
  594. if (!member.IsAccessible (rc))
  595. continue;
  596. //
  597. // With runtime binder we can have a situation where queried type is inaccessible
  598. // because it came via dynamic object, the check about inconsisted accessibility
  599. // had no effect as the type was unknown during compilation
  600. //
  601. // class A {
  602. // private class N { }
  603. //
  604. // public dynamic Foo ()
  605. // {
  606. // return new N ();
  607. // }
  608. // }
  609. //
  610. if (rc.Module.Compiler.IsRuntimeBinder && !member.DeclaringType.IsAccessible (rc))
  611. continue;
  612. }
  613. if ((restrictions & MemberLookupRestrictions.InvocableOnly) != 0) {
  614. if (member is MethodSpec)
  615. return new MethodGroupExpr (members, queried_type, loc);
  616. if (!Invocation.IsMemberInvocable (member))
  617. continue;
  618. }
  619. if (non_method == null || member is MethodSpec || non_method.IsNotCSharpCompatible) {
  620. non_method = member;
  621. } else if (!errorMode && !member.IsNotCSharpCompatible) {
  622. ambig_non_method = member;
  623. }
  624. }
  625. if (non_method != null) {
  626. if (ambig_non_method != null && rc != null) {
  627. var report = rc.Module.Compiler.Report;
  628. report.SymbolRelatedToPreviousError (non_method);
  629. report.SymbolRelatedToPreviousError (ambig_non_method);
  630. report.Error (229, loc, "Ambiguity between `{0}' and `{1}'",
  631. non_method.GetSignatureForError (), ambig_non_method.GetSignatureForError ());
  632. }
  633. if (non_method is MethodSpec)
  634. return new MethodGroupExpr (members, queried_type, loc);
  635. return ExprClassFromMemberInfo (non_method, loc);
  636. }
  637. if (members[0].DeclaringType.BaseType == null)
  638. members = null;
  639. else
  640. members = MemberCache.FindMembers (members[0].DeclaringType.BaseType, name, false);
  641. } while (members != null);
  642. return null;
  643. }
  644. protected virtual void Error_NegativeArrayIndex (ResolveContext ec, Location loc)
  645. {
  646. throw new NotImplementedException ();
  647. }
  648. public virtual void Error_OperatorCannotBeApplied (ResolveContext rc, Location loc, string oper, TypeSpec t)
  649. {
  650. if (t == InternalType.ErrorType)
  651. return;
  652. rc.Report.Error (23, loc, "The `{0}' operator cannot be applied to operand of type `{1}'",
  653. oper, t.GetSignatureForError ());
  654. }
  655. protected void Error_PointerInsideExpressionTree (ResolveContext ec)
  656. {
  657. ec.Report.Error (1944, loc, "An expression tree cannot contain an unsafe pointer operation");
  658. }
  659. /// <summary>
  660. /// Returns an expression that can be used to invoke operator true
  661. /// on the expression if it exists.
  662. /// </summary>
  663. protected static Expression GetOperatorTrue (ResolveContext ec, Expression e, Location loc)
  664. {
  665. return GetOperatorTrueOrFalse (ec, e, true, loc);
  666. }
  667. /// <summary>
  668. /// Returns an expression that can be used to invoke operator false
  669. /// on the expression if it exists.
  670. /// </summary>
  671. protected static Expression GetOperatorFalse (ResolveContext ec, Expression e, Location loc)
  672. {
  673. return GetOperatorTrueOrFalse (ec, e, false, loc);
  674. }
  675. static Expression GetOperatorTrueOrFalse (ResolveContext ec, Expression e, bool is_true, Location loc)
  676. {
  677. var op = is_true ? Operator.OpType.True : Operator.OpType.False;
  678. var methods = MemberCache.GetUserOperator (e.type, op, false);
  679. if (methods == null)
  680. return null;
  681. Arguments arguments = new Arguments (1);
  682. arguments.Add (new Argument (e));
  683. var res = new OverloadResolver (methods, OverloadResolver.Restrictions.BaseMembersIncluded | OverloadResolver.Restrictions.NoBaseMembers, loc);
  684. var oper = res.ResolveOperator (ec, ref arguments);
  685. if (oper == null)
  686. return null;
  687. return new UserOperatorCall (oper, arguments, null, loc);
  688. }
  689. public virtual string ExprClassName
  690. {
  691. get {
  692. switch (eclass){
  693. case ExprClass.Unresolved:
  694. return "Unresolved";
  695. case ExprClass.Value:
  696. return "value";
  697. case ExprClass.Variable:
  698. return "variable";
  699. case ExprClass.Namespace:
  700. return "namespace";
  701. case ExprClass.Type:
  702. return "type";
  703. case ExprClass.MethodGroup:
  704. return "method group";
  705. case ExprClass.PropertyAccess:
  706. return "property access";
  707. case ExprClass.EventAccess:
  708. return "event access";
  709. case ExprClass.IndexerAccess:
  710. return "indexer access";
  711. case ExprClass.Nothing:
  712. return "null";
  713. case ExprClass.TypeParameter:
  714. return "type parameter";
  715. }
  716. throw new Exception ("Should not happen");
  717. }
  718. }
  719. /// <summary>
  720. /// Reports that we were expecting `expr' to be of class `expected'
  721. /// </summary>
  722. public void Error_UnexpectedKind (IMemberContext ctx, Expression memberExpr, string expected, string was, Location loc)
  723. {
  724. var name = memberExpr.GetSignatureForError ();
  725. ctx.Module.Compiler.Report.Error (118, loc, "`{0}' is a `{1}' but a `{2}' was expected", name, was, expected);
  726. }
  727. public virtual void Error_UnexpectedKind (ResolveContext ec, ResolveFlags flags, Location loc)
  728. {
  729. string [] valid = new string [4];
  730. int count = 0;
  731. if ((flags & ResolveFlags.VariableOrValue) != 0) {
  732. valid [count++] = "variable";
  733. valid [count++] = "value";
  734. }
  735. if ((flags & ResolveFlags.Type) != 0)
  736. valid [count++] = "type";
  737. if ((flags & ResolveFlags.MethodGroup) != 0)
  738. valid [count++] = "method group";
  739. if (count == 0)
  740. valid [count++] = "unknown";
  741. StringBuilder sb = new StringBuilder (valid [0]);
  742. for (int i = 1; i < count - 1; i++) {
  743. sb.Append ("', `");
  744. sb.Append (valid [i]);
  745. }
  746. if (count > 1) {
  747. sb.Append ("' or `");
  748. sb.Append (valid [count - 1]);
  749. }
  750. ec.Report.Error (119, loc,
  751. "Expression denotes a `{0}', where a `{1}' was expected", ExprClassName, sb.ToString ());
  752. }
  753. public static void UnsafeError (ResolveContext ec, Location loc)
  754. {
  755. UnsafeError (ec.Report, loc);
  756. }
  757. public static void UnsafeError (Report Report, Location loc)
  758. {
  759. Report.Error (214, loc, "Pointers and fixed size buffers may only be used in an unsafe context");
  760. }
  761. //
  762. // Converts `source' to an int, uint, long or ulong.
  763. //
  764. protected Expression ConvertExpressionToArrayIndex (ResolveContext ec, Expression source)
  765. {
  766. var btypes = ec.BuiltinTypes;
  767. if (source.type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
  768. Arguments args = new Arguments (1);
  769. args.Add (new Argument (source));
  770. return new DynamicConversion (btypes.Int, CSharpBinderFlags.ConvertArrayIndex, args, loc).Resolve (ec);
  771. }
  772. Expression converted;
  773. using (ec.Set (ResolveContext.Options.CheckedScope)) {
  774. converted = Convert.ImplicitConversion (ec, source, btypes.Int, source.loc);
  775. if (converted == null)
  776. converted = Convert.ImplicitConversion (ec, source, btypes.UInt, source.loc);
  777. if (converted == null)
  778. converted = Convert.ImplicitConversion (ec, source, btypes.Long, source.loc);
  779. if (converted == null)
  780. converted = Convert.ImplicitConversion (ec, source, btypes.ULong, source.loc);
  781. if (converted == null) {
  782. source.Error_ValueCannotBeConverted (ec, btypes.Int, false);
  783. return null;
  784. }
  785. }
  786. //
  787. // Only positive constants are allowed at compile time
  788. //
  789. Constant c = converted as Constant;
  790. if (c != null && c.IsNegative)
  791. Error_NegativeArrayIndex (ec, source.loc);
  792. // No conversion needed to array index
  793. if (converted.Type.BuiltinType == BuiltinTypeSpec.Type.Int)
  794. return converted;
  795. return new ArrayIndexCast (converted, btypes.Int).Resolve (ec);
  796. }
  797. //
  798. // Derived classes implement this method by cloning the fields that
  799. // could become altered during the Resolve stage
  800. //
  801. // Only expressions that are created for the parser need to implement
  802. // this.
  803. //
  804. protected virtual void CloneTo (CloneContext clonectx, Expression target)
  805. {
  806. throw new NotImplementedException (
  807. String.Format (
  808. "CloneTo not implemented for expression {0}", this.GetType ()));
  809. }
  810. //
  811. // Clones an expression created by the parser.
  812. //
  813. // We only support expressions created by the parser so far, not
  814. // expressions that have been resolved (many more classes would need
  815. // to implement CloneTo).
  816. //
  817. // This infrastructure is here merely for Lambda expressions which
  818. // compile the same code using different type values for the same
  819. // arguments to find the correct overload
  820. //
  821. public virtual Expression Clone (CloneContext clonectx)
  822. {
  823. Expression cloned = (Expression) MemberwiseClone ();
  824. CloneTo (clonectx, cloned);
  825. return cloned;
  826. }
  827. //
  828. // Implementation of expression to expression tree conversion
  829. //
  830. public abstract Expression CreateExpressionTree (ResolveContext ec);
  831. protected Expression CreateExpressionFactoryCall (ResolveContext ec, string name, Arguments args)
  832. {
  833. return CreateExpressionFactoryCall (ec, name, null, args, loc);
  834. }
  835. protected Expression CreateExpressionFactoryCall (ResolveContext ec, string name, TypeArguments typeArguments, Arguments args)
  836. {
  837. return CreateExpressionFactoryCall (ec, name, typeArguments, args, loc);
  838. }
  839. public static Expression CreateExpressionFactoryCall (ResolveContext ec, string name, TypeArguments typeArguments, Arguments args, Location loc)
  840. {
  841. return new Invocation (new MemberAccess (CreateExpressionTypeExpression (ec, loc), name, typeArguments, loc), args);
  842. }
  843. protected static TypeExpr CreateExpressionTypeExpression (ResolveContext ec, Location loc)
  844. {
  845. var t = ec.Module.PredefinedTypes.Expression.Resolve ();
  846. if (t == null)
  847. return null;
  848. return new TypeExpression (t, loc);
  849. }
  850. //
  851. // Implemented by all expressions which support conversion from
  852. // compiler expression to invokable runtime expression. Used by
  853. // dynamic C# binder.
  854. //
  855. public virtual SLE.Expression MakeExpression (BuilderContext ctx)
  856. {
  857. throw new NotImplementedException ("MakeExpression for " + GetType ());
  858. }
  859. public virtual object Accept (StructuralVisitor visitor)
  860. {
  861. return visitor.Visit (this);
  862. }
  863. }
  864. /// <summary>
  865. /// This is just a base class for expressions that can
  866. /// appear on statements (invocations, object creation,
  867. /// assignments, post/pre increment and decrement). The idea
  868. /// being that they would support an extra Emition interface that
  869. /// does not leave a result on the stack.
  870. /// </summary>
  871. public abstract class ExpressionStatement : Expression {
  872. public ExpressionStatement ResolveStatement (BlockContext ec)
  873. {
  874. Expression e = Resolve (ec);
  875. if (e == null)
  876. return null;
  877. ExpressionStatement es = e as ExpressionStatement;
  878. if (es == null)
  879. Error_InvalidExpressionStatement (ec);
  880. if (ec.CurrentAnonymousMethod is AsyncInitializer && !(e is Assign) &&
  881. (e.Type.IsGenericTask || e.Type == ec.Module.PredefinedTypes.Task.TypeSpec)) {
  882. ec.Report.Warning (4014, 1, e.Location,
  883. "The statement is not awaited and execution of current method continues before the call is completed. Consider using `await' operator");
  884. }
  885. return es;
  886. }
  887. /// <summary>
  888. /// Requests the expression to be emitted in a `statement'
  889. /// context. This means that no new value is left on the
  890. /// stack after invoking this method (constrasted with
  891. /// Emit that will always leave a value on the stack).
  892. /// </summary>
  893. public abstract void EmitStatement (EmitContext ec);
  894. public override void EmitSideEffect (EmitContext ec)
  895. {
  896. EmitStatement (ec);
  897. }
  898. }
  899. /// <summary>
  900. /// This kind of cast is used to encapsulate the child
  901. /// whose type is child.Type into an expression that is
  902. /// reported to return "return_type". This is used to encapsulate
  903. /// expressions which have compatible types, but need to be dealt
  904. /// at higher levels with.
  905. ///
  906. /// For example, a "byte" expression could be encapsulated in one
  907. /// of these as an "unsigned int". The type for the expression
  908. /// would be "unsigned int".
  909. ///
  910. /// </summary>
  911. public abstract class TypeCast : Expression
  912. {
  913. protected readonly Expression child;
  914. protected TypeCast (Expression child, TypeSpec return_type)
  915. {
  916. eclass = child.eclass;
  917. loc = child.Location;
  918. type = return_type;
  919. this.child = child;
  920. }
  921. public Expression Child {
  922. get {
  923. return child;
  924. }
  925. }
  926. public override bool ContainsEmitWithAwait ()
  927. {
  928. return child.ContainsEmitWithAwait ();
  929. }
  930. public override Expression CreateExpressionTree (ResolveContext ec)
  931. {
  932. Arguments args = new Arguments (2);
  933. args.Add (new Argument (child.CreateExpressionTree (ec)));
  934. args.Add (new Argument (new TypeOf (type, loc)));
  935. if (type.IsPointer || child.Type.IsPointer)
  936. Error_PointerInsideExpressionTree (ec);
  937. return CreateExpressionFactoryCall (ec, ec.HasSet (ResolveContext.Options.CheckedScope) ? "ConvertChecked" : "Convert", args);
  938. }
  939. protected override Expression DoResolve (ResolveContext ec)
  940. {
  941. // This should never be invoked, we are born in fully
  942. // initialized state.
  943. return this;
  944. }
  945. public override void Emit (EmitContext ec)
  946. {
  947. child.Emit (ec);
  948. }
  949. public override SLE.Expression MakeExpression (BuilderContext ctx)
  950. {
  951. #if STATIC
  952. return base.MakeExpression (ctx);
  953. #else
  954. return ctx.HasSet (BuilderContext.Options.CheckedScope) ?
  955. SLE.Expression.ConvertChecked (child.MakeExpression (ctx), type.GetMetaInfo ()) :
  956. SLE.Expression.Convert (child.MakeExpression (ctx), type.GetMetaInfo ());
  957. #endif
  958. }
  959. protected override void CloneTo (CloneContext clonectx, Expression t)
  960. {
  961. // Nothing to clone
  962. }
  963. public override bool IsNull {
  964. get { return child.IsNull; }
  965. }
  966. }
  967. public class EmptyCast : TypeCast {
  968. EmptyCast (Expression child, TypeSpec target_type)
  969. : base (child, target_type)
  970. {
  971. }
  972. public static Expression Create (Expression child, TypeSpec type)
  973. {
  974. Constant c = child as Constant;
  975. if (c != null)
  976. return new EmptyConstantCast (c, type);
  977. EmptyCast e = child as EmptyCast;
  978. if (e != null)
  979. return new EmptyCast (e.child, type);
  980. return new EmptyCast (child, type);
  981. }
  982. public override void EmitBranchable (EmitContext ec, Label label, bool on_true)
  983. {
  984. child.EmitBranchable (ec, label, on_true);
  985. }
  986. public override void EmitSideEffect (EmitContext ec)
  987. {
  988. child.EmitSideEffect (ec);
  989. }
  990. }
  991. //
  992. // Used for predefined type user operator (no obsolete check, etc.)
  993. //
  994. public class OperatorCast : TypeCast
  995. {
  996. readonly MethodSpec conversion_operator;
  997. public OperatorCast (Expression expr, TypeSpec target_type)
  998. : this (expr, target_type, target_type, false)
  999. {
  1000. }
  1001. public OperatorCast (Expression expr, TypeSpec target_type, bool find_explicit)
  1002. : this (expr, target_type, target_type, find_explicit)
  1003. {
  1004. }
  1005. public OperatorCast (Expression expr, TypeSpec declaringType, TypeSpec returnType, bool isExplicit)
  1006. : base (expr, returnType)
  1007. {
  1008. var op = isExplicit ? Operator.OpType.Explicit : Operator.OpType.Implicit;
  1009. var mi = MemberCache.GetUserOperator (declaringType, op, true);
  1010. if (mi != null) {
  1011. foreach (MethodSpec oper in mi) {
  1012. if (oper.ReturnType != returnType)
  1013. continue;
  1014. if (oper.Parameters.Types[0] == expr.Type) {
  1015. conversion_operator = oper;
  1016. return;
  1017. }
  1018. }
  1019. }
  1020. throw new InternalErrorException ("Missing predefined user operator between `{0}' and `{1}'",
  1021. returnType.GetSignatureForError (), expr.Type.GetSignatureForError ());
  1022. }
  1023. public override void Emit (EmitContext ec)
  1024. {
  1025. child.Emit (ec);
  1026. ec.Emit (OpCodes.Call, conversion_operator);
  1027. }
  1028. }
  1029. //
  1030. // Constant specialization of EmptyCast.
  1031. // We need to special case this since an empty cast of
  1032. // a constant is still a constant.
  1033. //
  1034. public class EmptyConstantCast : Constant
  1035. {
  1036. public readonly Constant child;
  1037. public EmptyConstantCast (Constant child, TypeSpec type)
  1038. : base (child.Location)
  1039. {
  1040. if (child == null)
  1041. throw new ArgumentNullException ("child");
  1042. this.child = child;
  1043. this.eclass = child.eclass;
  1044. this.type = type;
  1045. }
  1046. public override Constant ConvertExplicitly (bool in_checked_context, TypeSpec target_type)
  1047. {
  1048. if (child.Type == target_type)
  1049. return child;
  1050. // FIXME: check that 'type' can be converted to 'target_type' first
  1051. return child.ConvertExplicitly (in_checked_context, target_type);
  1052. }
  1053. public override Expression CreateExpressionTree (ResolveContext ec)
  1054. {
  1055. Arguments args = Arguments.CreateForExpressionTree (ec, null,
  1056. child.CreateExpressionTree (ec),
  1057. new TypeOf (type, loc));
  1058. if (type.IsPointer)
  1059. Error_PointerInsideExpressionTree (ec);
  1060. return CreateExpressionFactoryCall (ec, "Convert", args);
  1061. }
  1062. public override bool IsDefaultValue {
  1063. get { return child.IsDefaultValue; }
  1064. }
  1065. public override bool IsNegative {
  1066. get { return child.IsNegative; }
  1067. }
  1068. public override bool IsNull {
  1069. get { return child.IsNull; }
  1070. }
  1071. public override bool IsOneInteger {
  1072. get { return child.IsOneInteger; }
  1073. }
  1074. public override bool IsSideEffectFree {
  1075. get {
  1076. return child.IsSideEffectFree;
  1077. }
  1078. }
  1079. public override bool IsZeroInteger {
  1080. get { return child.IsZeroInteger; }
  1081. }
  1082. public override void Emit (EmitContext ec)
  1083. {
  1084. child.Emit (ec);
  1085. }
  1086. public override void EmitBranchable (EmitContext ec, Label label, bool on_true)
  1087. {
  1088. child.EmitBranchable (ec, label, on_true);
  1089. // Only to make verifier happy
  1090. if (TypeManager.IsGenericParameter (type) && child.IsNull)
  1091. ec.Emit (OpCodes.Unbox_Any, type);
  1092. }
  1093. public override void EmitSideEffect (EmitContext ec)
  1094. {
  1095. child.EmitSideEffect (ec);
  1096. }
  1097. public override object GetValue ()
  1098. {
  1099. return child.GetValue ();
  1100. }
  1101. public override string GetValueAsLiteral ()
  1102. {
  1103. return child.GetValueAsLiteral ();
  1104. }
  1105. public override long GetValueAsLong ()
  1106. {
  1107. return child.GetValueAsLong ();
  1108. }
  1109. public override Constant ConvertImplicitly (TypeSpec target_type)
  1110. {
  1111. if (type == target_type)
  1112. return this;
  1113. // FIXME: Do we need to check user conversions?
  1114. if (!Convert.ImplicitStandardConversionExists (this, target_type))
  1115. return null;
  1116. return child.ConvertImplicitly (target_type);
  1117. }
  1118. }
  1119. /// <summary>
  1120. /// This class is used to wrap literals which belong inside Enums
  1121. /// </summary>
  1122. public class EnumConstant : Constant
  1123. {
  1124. public Constant Child;
  1125. public EnumConstant (Constant child, TypeSpec enum_type)
  1126. : base (child.Location)
  1127. {
  1128. this.Child = child;
  1129. this.eclass = ExprClass.Value;
  1130. this.type = enum_type;
  1131. }
  1132. protected EnumConstant (Location loc)
  1133. : base (loc)
  1134. {
  1135. }
  1136. public override void Emit (EmitContext ec)
  1137. {
  1138. Child.Emit (ec);
  1139. }
  1140. public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
  1141. {
  1142. Child.EncodeAttributeValue (rc, enc, Child.Type);
  1143. }
  1144. public override void EmitBranchable (EmitContext ec, Label label, bool on_true)
  1145. {
  1146. Child.EmitBranchable (ec, label, on_true);
  1147. }
  1148. public override void EmitSideEffect (EmitContext ec)
  1149. {
  1150. Child.EmitSideEffect (ec);
  1151. }
  1152. public override string GetSignatureForError()
  1153. {
  1154. return TypeManager.CSharpName (Type);
  1155. }
  1156. public override object GetValue ()
  1157. {
  1158. return Child.GetValue ();
  1159. }
  1160. #if !STATIC
  1161. public override object GetTypedValue ()
  1162. {
  1163. //
  1164. // The method can be used in dynamic context only (on closed types)
  1165. //
  1166. // System.Enum.ToObject cannot be called on dynamic types
  1167. // EnumBuilder has to be used, but we cannot use EnumBuilder
  1168. // because it does not properly support generics
  1169. //
  1170. return System.Enum.ToObject (type.GetMetaInfo (), Child.GetValue ());
  1171. }
  1172. #endif
  1173. public override string GetValueAsLiteral ()
  1174. {
  1175. return Child.GetValueAsLiteral ();
  1176. }
  1177. public override long GetValueAsLong ()
  1178. {
  1179. return Child.GetValueAsLong ();
  1180. }
  1181. public EnumConstant Increment()
  1182. {
  1183. return new EnumConstant (((IntegralConstant) Child).Increment (), type);
  1184. }
  1185. public override bool IsDefaultValue {
  1186. get {
  1187. return Child.IsDefaultValue;
  1188. }
  1189. }
  1190. public override bool IsSideEffectFree {
  1191. get {
  1192. return Child.IsSideEffectFree;
  1193. }
  1194. }
  1195. public override bool IsZeroInteger {
  1196. get { return Child.IsZeroInteger; }
  1197. }
  1198. public override bool IsNegative {
  1199. get {
  1200. return Child.IsNegative;
  1201. }
  1202. }
  1203. public override Constant ConvertExplicitly(bool in_checked_context, TypeSpec target_type)
  1204. {
  1205. if (Child.Type == target_type)
  1206. return Child;
  1207. return Child.ConvertExplicitly (in_checked_context, target_type);
  1208. }
  1209. public override Constant ConvertImplicitly (TypeSpec type)
  1210. {
  1211. if (this.type == type) {
  1212. return this;
  1213. }
  1214. if (!Convert.ImplicitStandardConversionExists (this, type)){
  1215. return null;
  1216. }
  1217. return Child.ConvertImplicitly (type);
  1218. }
  1219. }
  1220. /// <summary>
  1221. /// This kind of cast is used to encapsulate Value Types in objects.
  1222. ///
  1223. /// The effect of it is to box the value type emitted by the previous
  1224. /// operation.
  1225. /// </summary>
  1226. public class BoxedCast : TypeCast {
  1227. public BoxedCast (Expression expr, TypeSpec target_type)
  1228. : base (expr, target_type)
  1229. {
  1230. eclass = ExprClass.Value;
  1231. }
  1232. protected override Expression DoResolve (ResolveContext ec)
  1233. {
  1234. // This should never be invoked, we are born in fully
  1235. // initialized state.
  1236. return this;
  1237. }
  1238. public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
  1239. {
  1240. // Only boxing to object type is supported
  1241. if (targetType.BuiltinType != BuiltinTypeSpec.Type.Object) {
  1242. base.EncodeAttributeValue (rc, enc, targetType);
  1243. return;
  1244. }
  1245. enc.Encode (child.Type);
  1246. child.EncodeAttributeValue (rc, enc, child.Type);
  1247. }
  1248. public override void Emit (EmitContext ec)
  1249. {
  1250. base.Emit (ec);
  1251. ec.Emit (OpCodes.Box, child.Type);
  1252. }
  1253. public override void EmitSideEffect (EmitContext ec)
  1254. {
  1255. // boxing is side-effectful, since it involves runtime checks, except when boxing to Object or ValueType
  1256. // so, we need to emit the box+pop instructions in most cases
  1257. if (child.Type.IsStruct &&
  1258. (type.BuiltinType == BuiltinTypeSpec.Type.Object || type.BuiltinType == BuiltinTypeSpec.Type.ValueType))
  1259. child.EmitSideEffect (ec);
  1260. else
  1261. base.EmitSideEffect (ec);
  1262. }
  1263. }
  1264. public class UnboxCast : TypeCast {
  1265. public UnboxCast (Expression expr, TypeSpec return_type)
  1266. : base (expr, return_type)
  1267. {
  1268. }
  1269. protected override Expression DoResolve (ResolveContext ec)
  1270. {
  1271. // This should never be invoked, we are born in fully
  1272. // initialized state.
  1273. return this;
  1274. }
  1275. public override void Emit (EmitContext ec)
  1276. {
  1277. base.Emit (ec);
  1278. ec.Emit (OpCodes.Unbox_Any, type);
  1279. }
  1280. }
  1281. /// <summary>
  1282. /// This is used to perform explicit numeric conversions.
  1283. ///
  1284. /// Explicit numeric conversions might trigger exceptions in a checked
  1285. /// context, so they should generate the conv.ovf opcodes instead of
  1286. /// conv opcodes.
  1287. /// </summary>
  1288. public class ConvCast : TypeCast {
  1289. public enum Mode : byte {
  1290. I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
  1291. U1_I1, U1_CH,
  1292. I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
  1293. U2_I1, U2_U1, U2_I2, U2_CH,
  1294. I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
  1295. U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
  1296. I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH, I8_I,
  1297. U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH, U8_I,
  1298. CH_I1, CH_U1, CH_I2,
  1299. R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
  1300. R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4,
  1301. I_I8,
  1302. }
  1303. Mode mode;
  1304. public ConvCast (Expression child, TypeSpec return_type, Mode m)
  1305. : base (child, return_type)
  1306. {
  1307. mode = m;
  1308. }
  1309. protected override Expression DoResolve (ResolveContext ec)
  1310. {
  1311. // This should never be invoked, we are born in fully
  1312. // initialized state.
  1313. return this;
  1314. }
  1315. public override string ToString ()
  1316. {
  1317. return String.Format ("ConvCast ({0}, {1})", mode, child);
  1318. }
  1319. public override void Emit (EmitContext ec)
  1320. {
  1321. base.Emit (ec);
  1322. if (ec.HasSet (EmitContext.Options.CheckedScope)) {
  1323. switch (mode){
  1324. case Mode.I1_U1: ec.Emit (OpCodes.Conv_Ovf_U1); break;
  1325. case Mode.I1_U2: ec.Emit (OpCodes.Conv_Ovf_U2); break;
  1326. case Mode.I1_U4: ec.Emit (OpCodes.Conv_Ovf_U4); break;
  1327. case Mode.I1_U8: ec.Emit (OpCodes.Conv_Ovf_U8); break;
  1328. case Mode.I1_CH: ec.Emit (OpCodes.Conv_Ovf_U2); break;
  1329. case Mode.U1_I1: ec.Emit (OpCodes.Conv_Ovf_I1_Un); break;
  1330. case Mode.U1_CH: /* nothing */ break;
  1331. case Mode.I2_I1: ec.Emit (OpCodes.Conv_Ovf_I1); break;
  1332. case Mode.I2_U1: ec.Emit (OpCodes.Conv_Ovf_U1); break;
  1333. case Mode.I2_U2: ec.Emit (OpCodes.Conv_Ovf_U2); break;
  1334. case Mode.I2_U4: ec.Emit (OpCodes.Conv_Ovf_U4); break;
  1335. case Mode.I2_U8: ec.Emit (OpCodes.Conv_Ovf_U8); break;
  1336. case Mode.I2_CH: ec.Emit (OpCodes.Conv_Ovf_U2); break;
  1337. case Mode.U2_I1: ec.Emit (OpCodes.Conv_Ovf_I1_Un); break;
  1338. case Mode.U2_U1: ec.Emit (OpCodes.Conv_Ovf_U1_Un); break;
  1339. case Mode.U2_I2: ec.Emit (OpCodes.Conv_Ovf_I2_Un); break;
  1340. case Mode.U2_CH: /* nothing */ break;
  1341. case Mode.I4_I1: ec.Emit (OpCodes.Conv_Ovf_I1); break;
  1342. case Mode.I4_U1: ec.Emit (OpCodes.Conv_Ovf_U1); break;
  1343. case Mode.I4_I2: ec.Emit (OpCodes.Conv_Ovf_I2); break;
  1344. case Mode.I4_U4: ec.Emit (OpCodes.Conv_Ovf_U4); break;
  1345. case Mode.I4_U2: ec.Emit (OpCodes.Conv_Ovf_U2); break;
  1346. case Mode.I4_U8: ec.Emit (OpCodes.Conv_Ovf_U8); break;
  1347. case Mode.I4_CH: ec.Emit (OpCodes.Conv_Ovf_U2); break;
  1348. case Mode.U4_I1: ec.Emit (OpCodes.Conv_Ovf_I1_Un); break;
  1349. case Mode.U4_U1: ec.Emit (OpCodes.Conv_Ovf_U1_Un); break;
  1350. case Mode.U4_I2: ec.Emit (OpCodes.Conv_Ovf_I2_Un); break;
  1351. case Mode.U4_U2: ec.Emit (OpCodes.Conv_Ovf_U2_Un); break;
  1352. case Mode.U4_I4: ec.Emit (OpCodes.Conv_Ovf_I4_Un); break;
  1353. case Mode.U4_CH: ec.Emit (OpCodes.Conv_Ovf_U2_Un); break;
  1354. case Mode.I8_I1: ec.Emit (OpCodes.Conv_Ovf_I1); break;
  1355. case Mode.I8_U1: ec.Emit (OpCodes.Conv_Ovf_U1); break;
  1356. case Mode.I8_I2: ec.Emit (OpCodes.Conv_Ovf_I2); break;
  1357. case Mode.I8_U2: ec.Emit (OpCodes.Conv_Ovf_U2); break;
  1358. case Mode.I8_I4: ec.Emit (OpCodes.Conv_Ovf_I4); break;
  1359. case Mode.I8_U4: ec.Emit (OpCodes.Conv_Ovf_U4); break;
  1360. case Mode.I8_U8: ec.Emit (OpCodes.Conv_Ovf_U8); break;
  1361. case Mode.I8_CH: ec.Emit (OpCodes.Conv_Ovf_U2); break;
  1362. case Mode.I8_I: ec.Emit (OpCodes.Conv_Ovf_U); break;
  1363. case Mode.U8_I1: ec.Emit (OpCodes.Conv_Ovf_I1_Un); break;
  1364. case Mode.U8_U1: ec.Emit (OpCodes.Conv_Ovf_U1_Un); break;
  1365. case Mode.U8_I2: ec.Emit (OpCodes.Conv_Ovf_I2_Un); break;
  1366. case Mode.U8_U2: ec.Emit (OpCodes.Conv_Ovf_U2_Un); break;
  1367. case Mode.U8_I4: ec.Emit (OpCodes.Conv_Ovf_I4_Un); break;
  1368. case Mode.U8_U4: ec.Emit (OpCodes.Conv_Ovf_U4_Un); break;
  1369. case Mode.U8_I8: ec.Emit (OpCodes.Conv_Ovf_I8_Un); break;
  1370. case Mode.U8_CH: ec.Emit (OpCodes.Conv_Ovf_U2_Un); break;
  1371. case Mode.U8_I: ec.Emit (OpCodes.Conv_Ovf_U_Un); break;
  1372. case Mode.CH_I1: ec.Emit (OpCodes.Conv_Ovf_I1_Un); break;
  1373. case Mode.CH_U1: ec.Emit (OpCodes.Conv_Ovf_U1_Un); break;
  1374. case Mode.CH_I2: ec.Emit (OpCodes.Conv_Ovf_I2_Un); break;
  1375. case Mode.R4_I1: ec.Emit (OpCodes.Conv_Ovf_I1); break;
  1376. case Mode.R4_U1: ec.Emit (OpCodes.Conv_Ovf_U1); break;
  1377. case Mode.R4_I2: ec.Emit (OpCodes.Conv_Ovf_I2); break;
  1378. case Mode.R4_U2: ec.Emit (OpCodes.Conv_Ovf_U2); break;
  1379. case Mode.R4_I4: ec.Emit (OpCodes.Conv_Ovf_I4); break;
  1380. case Mode.R4_U4: ec.Emit (OpCodes.Conv_Ovf_U4); break;
  1381. case Mode.R4_I8: ec.Emit (OpCodes.Conv_Ovf_I8); break;
  1382. case Mode.R4_U8: ec.Emit (OpCodes.Conv_Ovf_U8); break;
  1383. case Mode.R4_CH: ec.Emit (OpCodes.Conv_Ovf_U2); break;
  1384. case Mode.R8_I1: ec.Emit (OpCodes.Conv_Ovf_I1); break;
  1385. case Mode.R8_U1: ec.Emit (OpCodes.Conv_Ovf_U1); break;
  1386. case Mode.R8_I2: ec.Emit (OpCodes.Conv_Ovf_I2); break;
  1387. case Mode.R8_U2: ec.Emit (OpCodes.Conv_Ovf_U2); break;
  1388. case Mode.R8_I4: ec.Emit (OpCodes.Conv_Ovf_I4); break;
  1389. case Mode.R8_U4: ec.Emit (OpCodes.Conv_Ovf_U4); break;
  1390. case Mode.R8_I8: ec.Emit (OpCodes.Conv_Ovf_I8); break;
  1391. case Mode.R8_U8: ec.Emit (OpCodes.Conv_Ovf_U8); break;
  1392. case Mode.R8_CH: ec.Emit (OpCodes.Conv_Ovf_U2); break;
  1393. case Mode.R8_R4: ec.Emit (OpCodes.Conv_R4); break;
  1394. case Mode.I_I8: ec.Emit (OpCodes.Conv_Ovf_I8_Un); break;
  1395. }
  1396. } else {
  1397. switch (mode){
  1398. case Mode.I1_U1: ec.Emit (OpCodes.Conv_U1); break;
  1399. case Mode.I1_U2: ec.Emit (OpCodes.Conv_U2); break;
  1400. case Mode.I1_U4: ec.Emit (OpCodes.Conv_U4); break;
  1401. case Mode.I1_U8: ec.Emit (OpCodes.Conv_I8); break;
  1402. case Mode.I1_CH: ec.Emit (OpCodes.Conv_U2); break;
  1403. case Mode.U1_I1: ec.Emit (OpCodes.Conv_I1); break;
  1404. case Mode.U1_CH: ec.Emit (OpCodes.Conv_U2); break;
  1405. case Mode.I2_I1: ec.Emit (OpCodes.Conv_I1); break;
  1406. case Mode.I2_U1: ec.Emit (OpCodes.Conv_U1); break;
  1407. case Mode.I2_U2: ec.Emit (OpCodes.Conv_U2); break;
  1408. case Mode.I2_U4: ec.Emit (OpCodes.Conv_U4); break;
  1409. case Mode.I2_U8: ec.Emit (OpCodes.Conv_I8); break;
  1410. case Mode.I2_CH: ec.Emit (OpCodes.Conv_U2); break;
  1411. case Mode.U2_I1: ec.Emit (OpCodes.Conv_I1); break;
  1412. case Mode.U2_U1: ec.Emit (OpCodes.Conv_U1); break;
  1413. case Mode.U2_I2: ec.Emit (OpCodes.Conv_I2); break;
  1414. case Mode.U2_CH: /* nothing */ break;
  1415. case Mode.I4_I1: ec.Emit (OpCodes.Conv_I1); break;
  1416. case Mode.I4_U1: ec.Emit (OpCodes.Conv_U1); break;
  1417. case Mode.I4_I2: ec.Emit (OpCodes.Conv_I2); break;
  1418. case Mode.I4_U4: /* nothing */ break;
  1419. case Mode.I4_U2: ec.Emit (OpCodes.Conv_U2); break;
  1420. case Mode.I4_U8: ec.Emit (OpCodes.Conv_I8); break;
  1421. case Mode.I4_CH: ec.Emit (OpCodes.Conv_U2); break;
  1422. case Mode.U4_I1: ec.Emit (OpCodes.Conv_I1); break;
  1423. case Mode.U4_U1: ec.Emit (OpCodes.Conv_U1); break;
  1424. case Mode.U4_I2: ec.Emit (OpCodes.Conv_I2); break;
  1425. case Mode.U4_U2: ec.Emit (OpCodes.Conv_U2); break;
  1426. case Mode.U4_I4: /* nothing */ break;
  1427. case Mode.U4_CH: ec.Emit (OpCodes.Conv_U2); break;
  1428. case Mode.I8_I1: ec.Emit (OpCodes.Conv_I1); break;
  1429. case Mode.I8_U1: ec.Emit (OpCodes.Conv_U1); break;
  1430. case Mode.I8_I2: ec.Emit (OpCodes.Conv_I2); break;
  1431. case Mode.I8_U2: ec.Emit (OpCodes.Conv_U2); break;
  1432. case Mode.I8_I4: ec.Emit (OpCodes.Conv_I4); break;
  1433. case Mode.I8_U4: ec.Emit (OpCodes.Conv_U4); break;
  1434. case Mode.I8_U8: /* nothing */ break;
  1435. case Mode.I8_CH: ec.Emit (OpCodes.Conv_U2); break;
  1436. case Mode.I8_I: ec.Emit (OpCodes.Conv_U); break;
  1437. case Mode.U8_I1: ec.Emit (OpCodes.Conv_I1); break;
  1438. case Mode.U8_U1: ec.Emit (OpCodes.Conv_U1); break;
  1439. case Mode.U8_I2: ec.Emit (OpCodes.Conv_I2); break;
  1440. case Mode.U8_U2: ec.Emit (OpCodes.Conv_U2); break;
  1441. case Mode.U8_I4: ec.Emit (OpCodes.Conv_I4); break;
  1442. case Mode.U8_U4: ec.Emit (OpCodes.Conv_U4); break;
  1443. case Mode.U8_I8: /* nothing */ break;
  1444. case Mode.U8_CH: ec.Emit (OpCodes.Conv_U2); break;
  1445. case Mode.U8_I: ec.Emit (OpCodes.Conv_U); break;
  1446. case Mode.CH_I1: ec.Emit (OpCodes.Conv_I1); break;
  1447. case Mode.CH_U1: ec.Emit (OpCodes.Conv_U1); break;
  1448. case Mode.CH_I2: ec.Emit (OpCodes.Conv_I2); break;
  1449. case Mode.R4_I1: ec.Emit (OpCodes.Conv_I1); break;
  1450. case Mode.R4_U1: ec.Emit (OpCodes.Conv_U1); break;
  1451. case Mode.R4_I2: ec.Emit (OpCodes.Conv_I2); break;
  1452. case Mode.R4_U2: ec.Emit (OpCodes.Conv_U2); break;
  1453. case Mode.R4_I4: ec.Emit (OpCodes.Conv_I4); break;
  1454. case Mode.R4_U4: ec.Emit (OpCodes.Conv_U4); break;
  1455. case Mode.R4_I8: ec.Emit (OpCodes.Conv_I8); break;
  1456. case Mode.R4_U8: ec.Emit (OpCodes.Conv_U8); break;
  1457. case Mode.R4_CH: ec.Emit (OpCodes.Conv_U2); break;
  1458. case Mode.R8_I1: ec.Emit (OpCodes.Conv_I1); break;
  1459. case Mode.R8_U1: ec.Emit (OpCodes.Conv_U1); break;
  1460. case Mode.R8_I2: ec.Emit (OpCodes.Conv_I2); break;
  1461. case Mode.R8_U2: ec.Emit (OpCodes.Conv_U2); break;
  1462. case Mode.R8_I4: ec.Emit (OpCodes.Conv_I4); break;
  1463. case Mode.R8_U4: ec.Emit (OpCodes.Conv_U4); break;
  1464. case Mode.R8_I8: ec.Emit (OpCodes.Conv_I8); break;
  1465. case Mode.R8_U8: ec.Emit (OpCodes.Conv_U8); break;
  1466. case Mode.R8_CH: ec.Emit (OpCodes.Conv_U2); break;
  1467. case Mode.R8_R4: ec.Emit (OpCodes.Conv_R4); break;
  1468. case Mode.I_I8: ec.Emit (OpCodes.Conv_U8); break;
  1469. }
  1470. }
  1471. }
  1472. }
  1473. class OpcodeCast : TypeCast
  1474. {
  1475. readonly OpCode op;
  1476. public OpcodeCast (Expression child, TypeSpec return_type, OpCode op)
  1477. : base (child, return_type)
  1478. {
  1479. this.op = op;
  1480. }
  1481. protected override Expression DoResolve (ResolveContext ec)
  1482. {
  1483. // This should never be invoked, we are born in fully
  1484. // initialized state.
  1485. return this;
  1486. }
  1487. public override void Emit (EmitContext ec)
  1488. {
  1489. base.Emit (ec);
  1490. ec.Emit (op);
  1491. }
  1492. public TypeSpec UnderlyingType {
  1493. get { return child.Type; }
  1494. }
  1495. }
  1496. //
  1497. // Opcode casts expression with 2 opcodes but only
  1498. // single expression tree node
  1499. //
  1500. class OpcodeCastDuplex : OpcodeCast
  1501. {
  1502. readonly OpCode second;
  1503. public OpcodeCastDuplex (Expression child, TypeSpec returnType, OpCode first, OpCode second)
  1504. : base (child, returnType, first)
  1505. {
  1506. this.second = second;
  1507. }
  1508. public override void Emit (EmitContext ec)
  1509. {
  1510. base.Emit (ec);
  1511. ec.Emit (second);
  1512. }
  1513. }
  1514. /// <summary>
  1515. /// This kind of cast is used to encapsulate a child and cast it
  1516. /// to the class requested
  1517. /// </summary>
  1518. public sealed class ClassCast : TypeCast {
  1519. readonly bool forced;
  1520. public ClassCast (Expression child, TypeSpec return_type)
  1521. : base (child, return_type)
  1522. {
  1523. }
  1524. public ClassCast (Expression child, TypeSpec return_type, bool forced)
  1525. : base (child, return_type)
  1526. {
  1527. this.forced = forced;
  1528. }
  1529. public override void Emit (EmitContext ec)
  1530. {
  1531. base.Emit (ec);
  1532. bool gen = TypeManager.IsGenericParameter (child.Type);
  1533. if (gen)
  1534. ec.Emit (OpCodes.Box, child.Type);
  1535. if (type.IsGenericParameter) {
  1536. ec.Emit (OpCodes.Unbox_Any, type);
  1537. return;
  1538. }
  1539. if (gen && !forced)
  1540. return;
  1541. ec.Emit (OpCodes.Castclass, type);
  1542. }
  1543. }
  1544. //
  1545. // Created during resolving pahse when an expression is wrapped or constantified
  1546. // and original expression can be used later (e.g. for expression trees)
  1547. //
  1548. public class ReducedExpression : Expression
  1549. {
  1550. sealed class ReducedConstantExpression : EmptyConstantCast
  1551. {
  1552. readonly Expression orig_expr;
  1553. public ReducedConstantExpression (Constant expr, Expression orig_expr)
  1554. : base (expr, expr.Type)
  1555. {
  1556. this.orig_expr = orig_expr;
  1557. }
  1558. public override Constant ConvertImplicitly (TypeSpec target_type)
  1559. {
  1560. Constant c = base.ConvertImplicitly (target_type);
  1561. if (c != null)
  1562. c = new ReducedConstantExpression (c, orig_expr);
  1563. return c;
  1564. }
  1565. public override Expression CreateExpressionTree (ResolveContext ec)
  1566. {
  1567. return orig_expr.CreateExpressionTree (ec);
  1568. }
  1569. public override Constant ConvertExplicitly (bool in_checked_context, TypeSpec target_type)
  1570. {
  1571. Constant c = base.ConvertExplicitly (in_checked_context, target_type);
  1572. if (c != null)
  1573. c = new ReducedConstantExpression (c, orig_expr);
  1574. return c;
  1575. }
  1576. public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
  1577. {
  1578. //
  1579. // LAMESPEC: Reduced conditional expression is allowed as an attribute argument
  1580. //
  1581. if (orig_expr is Conditional)
  1582. child.EncodeAttributeValue (rc, enc, targetType);
  1583. else
  1584. base.EncodeAttributeValue (rc, enc, targetType);
  1585. }
  1586. }
  1587. sealed class ReducedExpressionStatement : ExpressionStatement
  1588. {
  1589. readonly Expression orig_expr;
  1590. readonly ExpressionStatement stm;
  1591. public ReducedExpressionStatement (ExpressionStatement stm, Expression orig)
  1592. {
  1593. this.orig_expr = orig;
  1594. this.stm = stm;
  1595. this.eclass = stm.eclass;
  1596. this.type = stm.Type;
  1597. this.loc = orig.Location;
  1598. }
  1599. public override bool ContainsEmitWithAwait ()
  1600. {
  1601. return stm.ContainsEmitWithAwait ();
  1602. }
  1603. public override Expression CreateExpressionTree (ResolveContext ec)
  1604. {
  1605. return orig_expr.CreateExpressionTree (ec);
  1606. }
  1607. protected override Expression DoResolve (ResolveContext ec)
  1608. {
  1609. return this;
  1610. }
  1611. public override void Emit (EmitContext ec)
  1612. {
  1613. stm.Emit (ec);
  1614. }
  1615. public override void EmitStatement (EmitContext ec)
  1616. {
  1617. stm.EmitStatement (ec);
  1618. }
  1619. }
  1620. readonly Expression expr, orig_expr;
  1621. private ReducedExpression (Expression expr, Expression orig_expr)
  1622. {
  1623. this.expr = expr;
  1624. this.eclass = expr.eclass;
  1625. this.type = expr.Type;
  1626. this.orig_expr = orig_expr;
  1627. this.loc = orig_expr.Location;
  1628. }
  1629. #region Properties
  1630. public override bool IsSideEffectFree {
  1631. get {
  1632. return expr.IsSideEffectFree;
  1633. }
  1634. }
  1635. public Expression OriginalExpression {
  1636. get {
  1637. return orig_expr;
  1638. }
  1639. }
  1640. #endregion
  1641. public override bool ContainsEmitWithAwait ()
  1642. {
  1643. return expr.ContainsEmitWithAwait ();
  1644. }
  1645. //
  1646. // Creates fully resolved expression switcher
  1647. //
  1648. public static Constant Create (Constant expr, Expression original_expr)
  1649. {
  1650. if (expr.eclass == ExprClass.Unresolved)
  1651. throw new ArgumentException ("Unresolved expression");
  1652. return new ReducedConstantExpression (expr, original_expr);
  1653. }
  1654. public static ExpressionStatement Create (ExpressionStatement s, Expression orig)
  1655. {
  1656. return new ReducedExpressionStatement (s, orig);
  1657. }
  1658. public static Expression Create (Expression expr, Expression original_expr)
  1659. {
  1660. return Create (expr, original_expr, true);
  1661. }
  1662. //
  1663. // Creates unresolved reduce expression. The original expression has to be
  1664. // already resolved. Created expression is constant based based on `expr'
  1665. // value unless canBeConstant is used
  1666. //
  1667. public static Expression Create (Expression expr, Expression original_expr, bool canBeConstant)
  1668. {
  1669. if (canBeConstant) {
  1670. Constant c = expr as Constant;
  1671. if (c != null)
  1672. return Create (c, original_expr);
  1673. }
  1674. ExpressionStatement s = expr as ExpressionStatement;
  1675. if (s != null)
  1676. return Create (s, original_expr);
  1677. if (expr.eclass == ExprClass.Unresolved)
  1678. throw new ArgumentException ("Unresolved expression");
  1679. return new ReducedExpression (expr, original_expr);
  1680. }
  1681. public override Expression CreateExpressionTree (ResolveContext ec)
  1682. {
  1683. return orig_expr.CreateExpressionTree (ec);
  1684. }
  1685. protected override Expression DoResolve (ResolveContext ec)
  1686. {
  1687. return this;
  1688. }
  1689. public override void Emit (EmitContext ec)
  1690. {
  1691. expr.Emit (ec);
  1692. }
  1693. public override Expression EmitToField (EmitContext ec)
  1694. {
  1695. return expr.EmitToField(ec);
  1696. }
  1697. public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
  1698. {
  1699. expr.EmitBranchable (ec, target, on_true);
  1700. }
  1701. public override SLE.Expression MakeExpression (BuilderContext ctx)
  1702. {
  1703. return orig_expr.MakeExpression (ctx);
  1704. }
  1705. }
  1706. //
  1707. // Standard composite pattern
  1708. //
  1709. public abstract class CompositeExpression : Expression
  1710. {
  1711. protected Expression expr;
  1712. protected CompositeExpression (Expression expr)
  1713. {
  1714. this.expr = expr;
  1715. this.loc = expr.Location;
  1716. }
  1717. public override bool ContainsEmitWithAwait ()
  1718. {
  1719. return expr.ContainsEmitWithAwait ();
  1720. }
  1721. public override Expression CreateExpressionTree (ResolveContext rc)
  1722. {
  1723. return expr.CreateExpressionTree (rc);
  1724. }
  1725. public Expression Child {
  1726. get { return expr; }
  1727. }
  1728. protected override Expression DoResolve (ResolveContext rc)
  1729. {
  1730. expr = expr.Resolve (rc);
  1731. if (expr != null) {
  1732. type = expr.Type;
  1733. eclass = expr.eclass;
  1734. }
  1735. return this;
  1736. }
  1737. public override void Emit (EmitContext ec)
  1738. {
  1739. expr.Emit (ec);
  1740. }
  1741. public override bool IsNull {
  1742. get { return expr.IsNull; }
  1743. }
  1744. }
  1745. //
  1746. // Base of expressions used only to narrow resolve flow
  1747. //
  1748. public abstract class ShimExpression : Expression
  1749. {
  1750. protected Expression expr;
  1751. protected ShimExpression (Expression expr)
  1752. {
  1753. this.expr = expr;
  1754. }
  1755. public Expression Expr {
  1756. get {
  1757. return expr;
  1758. }
  1759. }
  1760. protected override void CloneTo (CloneContext clonectx, Expression t)
  1761. {
  1762. if (expr == null)
  1763. return;
  1764. ShimExpression target = (ShimExpression) t;
  1765. target.expr = expr.Clone (clonectx);
  1766. }
  1767. public override bool ContainsEmitWithAwait ()
  1768. {
  1769. return expr.ContainsEmitWithAwait ();
  1770. }
  1771. public override Expression CreateExpressionTree (ResolveContext ec)
  1772. {
  1773. throw new NotSupportedException ("ET");
  1774. }
  1775. public override void Emit (EmitContext ec)
  1776. {
  1777. throw new InternalErrorException ("Missing Resolve call");
  1778. }
  1779. }
  1780. //
  1781. // Unresolved type name expressions
  1782. //
  1783. public abstract class ATypeNameExpression : FullNamedExpression
  1784. {
  1785. string name;
  1786. protected TypeArguments targs;
  1787. protected ATypeNameExpression (string name, Location l)
  1788. {
  1789. this.name = name;
  1790. loc = l;
  1791. }
  1792. protected ATypeNameExpression (string name, TypeArguments targs, Location l)
  1793. {
  1794. this.name = name;
  1795. this.targs = targs;
  1796. loc = l;
  1797. }
  1798. protected ATypeNameExpression (string name, int arity, Location l)
  1799. : this (name, new UnboundTypeArguments (arity), l)
  1800. {
  1801. }
  1802. #region Properties
  1803. protected int Arity {
  1804. get {
  1805. return targs == null ? 0 : targs.Count;
  1806. }
  1807. }
  1808. public bool HasTypeArguments {
  1809. get {
  1810. return targs != null && !targs.IsEmpty;
  1811. }
  1812. }
  1813. public string Name {
  1814. get {
  1815. return name;
  1816. }
  1817. set {
  1818. name = value;
  1819. }
  1820. }
  1821. public TypeArguments TypeArguments {
  1822. get {
  1823. return targs;
  1824. }
  1825. }
  1826. #endregion
  1827. public override bool Equals (object obj)
  1828. {
  1829. ATypeNameExpression atne = obj as ATypeNameExpression;
  1830. return atne != null && atne.Name == Name &&
  1831. (targs == null || targs.Equals (atne.targs));
  1832. }
  1833. public override int GetHashCode ()
  1834. {
  1835. return Name.GetHashCode ();
  1836. }
  1837. // TODO: Move it to MemberCore
  1838. public static string GetMemberType (MemberCore mc)
  1839. {
  1840. if (mc is Property)
  1841. return "property";
  1842. if (mc is Indexer)
  1843. return "indexer";
  1844. if (mc is FieldBase)
  1845. return "field";
  1846. if (mc is MethodCore)
  1847. return "method";
  1848. if (mc is EnumMember)
  1849. return "enum";
  1850. if (mc is Event)
  1851. return "event";
  1852. return "type";
  1853. }
  1854. public override string GetSignatureForError ()
  1855. {
  1856. if (targs != null) {
  1857. return Name + "<" + targs.GetSignatureForError () + ">";
  1858. }
  1859. return Name;
  1860. }
  1861. public abstract Expression LookupNameExpression (ResolveContext rc, MemberLookupRestrictions restriction);
  1862. }
  1863. /// <summary>
  1864. /// SimpleName expressions are formed of a single word and only happen at the beginning
  1865. /// of a dotted-name.
  1866. /// </summary>
  1867. public class SimpleName : ATypeNameExpression
  1868. {
  1869. public SimpleName (string name, Location l)
  1870. : base (name, l)
  1871. {
  1872. }
  1873. public SimpleName (string name, TypeArguments args, Location l)
  1874. : base (name, args, l)
  1875. {
  1876. }
  1877. public SimpleName (string name, int arity, Location l)
  1878. : base (name, arity, l)
  1879. {
  1880. }
  1881. public SimpleName GetMethodGroup ()
  1882. {
  1883. return new SimpleName (Name, targs, loc);
  1884. }
  1885. protected override Expression DoResolve (ResolveContext rc)
  1886. {
  1887. var e = SimpleNameResolve (rc, null, false);
  1888. var fe = e as FieldExpr;
  1889. if (fe != null) {
  1890. fe.VerifyAssignedStructField (rc, null);
  1891. }
  1892. return e;
  1893. }
  1894. public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
  1895. {
  1896. return SimpleNameResolve (ec, right_side, false);
  1897. }
  1898. protected virtual void Error_TypeOrNamespaceNotFound (IMemberContext ctx)
  1899. {
  1900. if (ctx.CurrentType != null) {
  1901. var member = MemberLookup (ctx, false, ctx.CurrentType, Name, 0, MemberLookupRestrictions.ExactArity, loc) as MemberExpr;
  1902. if (member != null) {
  1903. member.Error_UnexpectedKind (ctx, member, "type", member.KindName, loc);
  1904. return;
  1905. }
  1906. }
  1907. var retval = ctx.LookupNamespaceOrType (Name, Arity, LookupMode.IgnoreAccessibility, loc);
  1908. if (retval != null) {
  1909. ctx.Module.Compiler.Report.SymbolRelatedToPreviousError (retval.Type);
  1910. ErrorIsInaccesible (ctx, retval.GetSignatureForError (), loc);
  1911. return;
  1912. }
  1913. retval = ctx.LookupNamespaceOrType (Name, -System.Math.Max (1, Arity), LookupMode.Probing, loc);
  1914. if (retval != null) {
  1915. Error_TypeArgumentsCannotBeUsed (ctx, retval.Type, Arity, loc);
  1916. return;
  1917. }
  1918. NamespaceContainer.Error_NamespaceNotFound (loc, Name, ctx.Module.Compiler.Report);
  1919. }
  1920. public override FullNamedExpression ResolveAsTypeOrNamespace (IMemberContext ec)
  1921. {
  1922. FullNamedExpression fne = ec.LookupNamespaceOrType (Name, Arity, LookupMode.Normal, loc);
  1923. if (fne != null) {
  1924. if (fne.Type != null && Arity > 0) {
  1925. if (HasTypeArguments) {
  1926. GenericTypeExpr ct = new GenericTypeExpr (fne.Type, targs, loc);
  1927. if (ct.ResolveAsType (ec) == null)
  1928. return null;
  1929. return ct;
  1930. }
  1931. return new GenericOpenTypeExpr (fne.Type, loc);
  1932. }
  1933. //
  1934. // dynamic namespace is ignored when dynamic is allowed (does not apply to types)
  1935. //
  1936. if (!(fne is Namespace))
  1937. return fne;
  1938. }
  1939. if (Arity == 0 && Name == "dynamic" && ec.Module.Compiler.Settings.Version > LanguageVersion.V_3) {
  1940. if (!ec.Module.PredefinedAttributes.Dynamic.IsDefined) {
  1941. ec.Module.Compiler.Report.Error (1980, Location,
  1942. "Dynamic keyword requires `{0}' to be defined. Are you missing System.Core.dll assembly reference?",
  1943. ec.Module.PredefinedAttributes.Dynamic.GetSignatureForError ());
  1944. }
  1945. fne = new DynamicTypeExpr (loc);
  1946. fne.ResolveAsType (ec);
  1947. }
  1948. if (fne != null)
  1949. return fne;
  1950. Error_TypeOrNamespaceNotFound (ec);
  1951. return null;
  1952. }
  1953. public bool IsPossibleTypeOrNamespace (IMemberContext mc)
  1954. {
  1955. return mc.LookupNamespaceOrType (Name, Arity, LookupMode.Probing, loc) != null;
  1956. }
  1957. public override Expression LookupNameExpression (ResolveContext rc, MemberLookupRestrictions restrictions)
  1958. {
  1959. int lookup_arity = Arity;
  1960. bool errorMode = false;
  1961. Expression e;
  1962. Block current_block = rc.CurrentBlock;
  1963. INamedBlockVariable variable = null;
  1964. bool variable_found = false;
  1965. while (true) {
  1966. //
  1967. // Stage 1: binding to local variables or parameters
  1968. //
  1969. // LAMESPEC: It should take invocableOnly into account but that would break csc compatibility
  1970. //
  1971. if (current_block != null && lookup_arity == 0) {
  1972. if (current_block.ParametersBlock.TopBlock.GetLocalName (Name, current_block.Original, ref variable)) {
  1973. if (!variable.IsDeclared) {
  1974. // We found local name in accessible block but it's not
  1975. // initialized yet, maybe the user wanted to bind to something else
  1976. errorMode = true;
  1977. variable_found = true;
  1978. } else {
  1979. e = variable.CreateReferenceExpression (rc, loc);
  1980. if (e != null) {
  1981. if (Arity > 0)
  1982. Error_TypeArgumentsCannotBeUsed (rc, "variable", Name, loc);
  1983. return e;
  1984. }
  1985. }
  1986. }
  1987. }
  1988. //
  1989. // Stage 2: Lookup members if we are inside a type up to top level type for nested types
  1990. //
  1991. TypeSpec member_type = rc.CurrentType;
  1992. for (; member_type != null; member_type = member_type.DeclaringType) {
  1993. e = MemberLookup (rc, errorMode, member_type, Name, lookup_arity, restrictions, loc);
  1994. if (e == null)
  1995. continue;
  1996. var me = e as MemberExpr;
  1997. if (me == null) {
  1998. // The name matches a type, defer to ResolveAsTypeStep
  1999. if (e is TypeExpr)
  2000. break;
  2001. continue;
  2002. }
  2003. if (errorMode) {
  2004. if (variable != null) {
  2005. if (me is FieldExpr || me is ConstantExpr || me is EventExpr || me is PropertyExpr) {
  2006. rc.Report.Error (844, loc,
  2007. "A local variable `{0}' cannot be used before it is declared. Consider renaming the local variable when it hides the member `{1}'",
  2008. Name, me.GetSignatureForError ());
  2009. } else {
  2010. break;
  2011. }
  2012. } else if (me is MethodGroupExpr) {
  2013. // Leave it to overload resolution to report correct error
  2014. } else {
  2015. // TODO: rc.Report.SymbolRelatedToPreviousError ()
  2016. ErrorIsInaccesible (rc, me.GetSignatureForError (), loc);
  2017. }
  2018. } else {
  2019. // LAMESPEC: again, ignores InvocableOnly
  2020. if (variable != null) {
  2021. rc.Report.SymbolRelatedToPreviousError (variable.Location, Name);
  2022. rc.Report.Error (135, loc, "`{0}' conflicts with a declaration in a child block", Name);
  2023. }
  2024. //
  2025. // MemberLookup does not check accessors availability, this is actually needed for properties only
  2026. //
  2027. var pe = me as PropertyExpr;
  2028. if (pe != null) {
  2029. // Break as there is no other overload available anyway
  2030. if ((restrictions & MemberLookupRestrictions.ReadAccess) != 0) {
  2031. if (!pe.PropertyInfo.HasGet || !pe.PropertyInfo.Get.IsAccessible (rc))
  2032. break;
  2033. pe.Getter = pe.PropertyInfo.Get;
  2034. } else {
  2035. if (!pe.PropertyInfo.HasSet || !pe.PropertyInfo.Set.IsAccessible (rc))
  2036. break;
  2037. pe.Setter = pe.PropertyInfo.Set;
  2038. }
  2039. }
  2040. }
  2041. // TODO: It's used by EventExpr -> FieldExpr transformation only
  2042. // TODO: Should go to MemberAccess
  2043. me = me.ResolveMemberAccess (rc, null, null);
  2044. if (Arity > 0) {
  2045. targs.Resolve (rc);
  2046. me.SetTypeArguments (rc, targs);
  2047. }
  2048. return me;
  2049. }
  2050. //
  2051. // Stage 3: Lookup nested types, namespaces and type parameters in the context
  2052. //
  2053. if ((restrictions & MemberLookupRestrictions.InvocableOnly) == 0 && !variable_found) {
  2054. if (IsPossibleTypeOrNamespace (rc)) {
  2055. if (variable != null) {
  2056. rc.Report.SymbolRelatedToPreviousError (variable.Location, Name);
  2057. rc.Report.Error (135, loc, "`{0}' conflicts with a declaration in a child block", Name);
  2058. }
  2059. return ResolveAsTypeOrNamespace (rc);
  2060. }
  2061. }
  2062. if (errorMode) {
  2063. if (variable_found) {
  2064. rc.Report.Error (841, loc, "A local variable `{0}' cannot be used before it is declared", Name);
  2065. } else {
  2066. if (Arity > 0) {
  2067. var tparams = rc.CurrentTypeParameters;
  2068. if (tparams != null) {
  2069. if (tparams.Find (Name) != null) {
  2070. Error_TypeArgumentsCannotBeUsed (rc, "type parameter", Name, loc);
  2071. return null;
  2072. }
  2073. }
  2074. var ct = rc.CurrentType;
  2075. do {
  2076. if (ct.MemberDefinition.TypeParametersCount > 0) {
  2077. foreach (var ctp in ct.MemberDefinition.TypeParameters) {
  2078. if (ctp.Name == Name) {
  2079. Error_TypeArgumentsCannotBeUsed (rc, "type parameter", Name, loc);
  2080. return null;
  2081. }
  2082. }
  2083. }
  2084. ct = ct.DeclaringType;
  2085. } while (ct != null);
  2086. }
  2087. if ((restrictions & MemberLookupRestrictions.InvocableOnly) == 0) {
  2088. e = rc.LookupNamespaceOrType (Name, Arity, LookupMode.IgnoreAccessibility, loc);
  2089. if (e != null) {
  2090. rc.Report.SymbolRelatedToPreviousError (e.Type);
  2091. ErrorIsInaccesible (rc, e.GetSignatureForError (), loc);
  2092. return e;
  2093. }
  2094. } else {
  2095. var me = MemberLookup (rc, false, rc.CurrentType, Name, Arity, restrictions & ~MemberLookupRestrictions.InvocableOnly, loc) as MemberExpr;
  2096. if (me != null) {
  2097. me.Error_UnexpectedKind (rc, me, "method group", me.KindName, loc);
  2098. return ErrorExpression.Instance;
  2099. }
  2100. }
  2101. e = rc.LookupNamespaceOrType (Name, -System.Math.Max (1, Arity), LookupMode.Probing, loc);
  2102. if (e != null) {
  2103. if (e.Type.Arity != Arity) {
  2104. Error_TypeArgumentsCannotBeUsed (rc, e.Type, Arity, loc);
  2105. return e;
  2106. }
  2107. if (e is TypeExpr) {
  2108. e.Error_UnexpectedKind (rc, e, "variable", e.ExprClassName, loc);
  2109. return e;
  2110. }
  2111. }
  2112. rc.Report.Error (103, loc, "The name `{0}' does not exist in the current context", Name);
  2113. }
  2114. return ErrorExpression.Instance;
  2115. }
  2116. if (rc.Module.Evaluator != null) {
  2117. var fi = rc.Module.Evaluator.LookupField (Name);
  2118. if (fi != null)
  2119. return new FieldExpr (fi.Item1, loc);
  2120. }
  2121. lookup_arity = 0;
  2122. errorMode = true;
  2123. }
  2124. }
  2125. Expression SimpleNameResolve (ResolveContext ec, Expression right_side, bool intermediate)
  2126. {
  2127. Expression e = LookupNameExpression (ec, right_side == null ? MemberLookupRestrictions.ReadAccess : MemberLookupRestrictions.None);
  2128. if (e == null)
  2129. return null;
  2130. if (right_side != null) {
  2131. if (e is FullNamedExpression && e.eclass != ExprClass.Unresolved) {
  2132. e.Error_UnexpectedKind (ec, e, "variable", e.ExprClassName, loc);
  2133. return null;
  2134. }
  2135. e = e.ResolveLValue (ec, right_side);
  2136. } else {
  2137. e = e.Resolve (ec);
  2138. }
  2139. return e;
  2140. }
  2141. public override object Accept (StructuralVisitor visitor)
  2142. {
  2143. return visitor.Visit (this);
  2144. }
  2145. }
  2146. /// <summary>
  2147. /// Represents a namespace or a type. The name of the class was inspired by
  2148. /// section 10.8.1 (Fully Qualified Names).
  2149. /// </summary>
  2150. public abstract class FullNamedExpression : Expression
  2151. {
  2152. protected override void CloneTo (CloneContext clonectx, Expression target)
  2153. {
  2154. // Do nothing, most unresolved type expressions cannot be
  2155. // resolved to different type
  2156. }
  2157. public override bool ContainsEmitWithAwait ()
  2158. {
  2159. return false;
  2160. }
  2161. public override Expression CreateExpressionTree (ResolveContext ec)
  2162. {
  2163. throw new NotSupportedException ("ET");
  2164. }
  2165. public abstract FullNamedExpression ResolveAsTypeOrNamespace (IMemberContext mc);
  2166. //
  2167. // This is used to resolve the expression as a type, a null
  2168. // value will be returned if the expression is not a type
  2169. // reference
  2170. //
  2171. public override TypeSpec ResolveAsType (IMemberContext mc)
  2172. {
  2173. FullNamedExpression fne = ResolveAsTypeOrNamespace (mc);
  2174. if (fne == null)
  2175. return null;
  2176. TypeExpr te = fne as TypeExpr;
  2177. if (te == null) {
  2178. fne.Error_UnexpectedKind (mc, fne, "type", fne.ExprClassName, loc);
  2179. return null;
  2180. }
  2181. te.loc = loc;
  2182. type = te.Type;
  2183. var dep = type.GetMissingDependencies ();
  2184. if (dep != null) {
  2185. ImportedTypeDefinition.Error_MissingDependency (mc, dep, loc);
  2186. }
  2187. if (type.Kind == MemberKind.Void) {
  2188. mc.Module.Compiler.Report.Error (673, loc, "System.Void cannot be used from C#. Consider using `void'");
  2189. }
  2190. //
  2191. // Obsolete checks cannot be done when resolving base context as they
  2192. // require type dependencies to be set but we are in process of resolving them
  2193. //
  2194. if (!(mc is TypeDefinition.BaseContext) && !(mc is UsingAliasNamespace.AliasContext)) {
  2195. ObsoleteAttribute obsolete_attr = type.GetAttributeObsolete ();
  2196. if (obsolete_attr != null && !mc.IsObsolete) {
  2197. AttributeTester.Report_ObsoleteMessage (obsolete_attr, te.GetSignatureForError (), Location, mc.Module.Compiler.Report);
  2198. }
  2199. }
  2200. return type;
  2201. }
  2202. public override void Emit (EmitContext ec)
  2203. {
  2204. throw new InternalErrorException ("FullNamedExpression `{0}' found in resolved tree",
  2205. GetSignatureForError ());
  2206. }
  2207. }
  2208. /// <summary>
  2209. /// Expression that evaluates to a type
  2210. /// </summary>
  2211. public abstract class TypeExpr : FullNamedExpression
  2212. {
  2213. public sealed override FullNamedExpression ResolveAsTypeOrNamespace (IMemberContext mc)
  2214. {
  2215. ResolveAsType (mc);
  2216. return this;
  2217. }
  2218. protected sealed override Expression DoResolve (ResolveContext ec)
  2219. {
  2220. ResolveAsType (ec);
  2221. return this;
  2222. }
  2223. public override bool Equals (object obj)
  2224. {
  2225. TypeExpr tobj = obj as TypeExpr;
  2226. if (tobj == null)
  2227. return false;
  2228. return Type == tobj.Type;
  2229. }
  2230. public override int GetHashCode ()
  2231. {
  2232. return Type.GetHashCode ();
  2233. }
  2234. }
  2235. /// <summary>
  2236. /// Fully resolved Expression that already evaluated to a type
  2237. /// </summary>
  2238. public class TypeExpression : TypeExpr
  2239. {
  2240. public TypeExpression (TypeSpec t, Location l)
  2241. {
  2242. Type = t;
  2243. eclass = ExprClass.Type;
  2244. loc = l;
  2245. }
  2246. public sealed override TypeSpec ResolveAsType (IMemberContext ec)
  2247. {
  2248. return type;
  2249. }
  2250. public override object Accept (StructuralVisitor visitor)
  2251. {
  2252. return visitor.Visit (this);
  2253. }
  2254. }
  2255. /// <summary>
  2256. /// This class denotes an expression which evaluates to a member
  2257. /// of a struct or a class.
  2258. /// </summary>
  2259. public abstract class MemberExpr : Expression, OverloadResolver.IInstanceQualifier
  2260. {
  2261. //
  2262. // An instance expression associated with this member, if it's a
  2263. // non-static member
  2264. //
  2265. public Expression InstanceExpression;
  2266. /// <summary>
  2267. /// The name of this member.
  2268. /// </summary>
  2269. public abstract string Name {
  2270. get;
  2271. }
  2272. //
  2273. // When base.member is used
  2274. //
  2275. public bool IsBase {
  2276. get { return InstanceExpression is BaseThis; }
  2277. }
  2278. /// <summary>
  2279. /// Whether this is an instance member.
  2280. /// </summary>
  2281. public abstract bool IsInstance {
  2282. get;
  2283. }
  2284. /// <summary>
  2285. /// Whether this is a static member.
  2286. /// </summary>
  2287. public abstract bool IsStatic {
  2288. get;
  2289. }
  2290. public abstract string KindName {
  2291. get;
  2292. }
  2293. protected abstract TypeSpec DeclaringType {
  2294. get;
  2295. }
  2296. TypeSpec OverloadResolver.IInstanceQualifier.InstanceType {
  2297. get {
  2298. return InstanceExpression.Type;
  2299. }
  2300. }
  2301. //
  2302. // Converts best base candidate for virtual method starting from QueriedBaseType
  2303. //
  2304. protected MethodSpec CandidateToBaseOverride (ResolveContext rc, MethodSpec method)
  2305. {
  2306. //
  2307. // Only when base.member is used and method is virtual
  2308. //
  2309. if (!IsBase)
  2310. return method;
  2311. //
  2312. // Overload resulution works on virtual or non-virtual members only (no overrides). That
  2313. // means for base.member access we have to find the closest match after we found best candidate
  2314. //
  2315. if ((method.Modifiers & (Modifiers.ABSTRACT | Modifiers.VIRTUAL | Modifiers.OVERRIDE)) != 0) {
  2316. //
  2317. // The method could already be what we are looking for
  2318. //
  2319. TypeSpec[] targs = null;
  2320. if (method.DeclaringType != InstanceExpression.Type) {
  2321. var base_override = MemberCache.FindMember (InstanceExpression.Type, new MemberFilter (method), BindingRestriction.InstanceOnly) as MethodSpec;
  2322. if (base_override != null && base_override.DeclaringType != method.DeclaringType) {
  2323. if (base_override.IsGeneric)
  2324. targs = method.TypeArguments;
  2325. method = base_override;
  2326. }
  2327. }
  2328. // TODO: For now we do it for any hoisted call even if it's needed for
  2329. // hoisted stories only but that requires a new expression wrapper
  2330. if (rc.CurrentAnonymousMethod != null) {
  2331. if (targs == null && method.IsGeneric) {
  2332. targs = method.TypeArguments;
  2333. method = method.GetGenericMethodDefinition ();
  2334. }
  2335. if (method.Parameters.HasArglist)
  2336. throw new NotImplementedException ("__arglist base call proxy");
  2337. method = rc.CurrentMemberDefinition.Parent.PartialContainer.CreateHoistedBaseCallProxy (rc, method);
  2338. // Ideally this should apply to any proxy rewrite but in the case of unary mutators on
  2339. // get/set member expressions second call would fail to proxy because left expression
  2340. // would be of 'this' and not 'base'
  2341. if (rc.CurrentType.IsStruct)
  2342. InstanceExpression = new This (loc).Resolve (rc);
  2343. }
  2344. if (targs != null)
  2345. method = method.MakeGenericMethod (rc, targs);
  2346. }
  2347. //
  2348. // Only base will allow this invocation to happen.
  2349. //
  2350. if (method.IsAbstract) {
  2351. Error_CannotCallAbstractBase (rc, method.GetSignatureForError ());
  2352. }
  2353. return method;
  2354. }
  2355. protected void CheckProtectedMemberAccess (ResolveContext rc, MemberSpec member)
  2356. {
  2357. if (InstanceExpression == null)
  2358. return;
  2359. if ((member.Modifiers & Modifiers.PROTECTED) != 0 && !(InstanceExpression is This)) {
  2360. if (!CheckProtectedMemberAccess (rc, member, InstanceExpression.Type)) {
  2361. Error_ProtectedMemberAccess (rc, member, InstanceExpression.Type, loc);
  2362. }
  2363. }
  2364. }
  2365. bool OverloadResolver.IInstanceQualifier.CheckProtectedMemberAccess (ResolveContext rc, MemberSpec member)
  2366. {
  2367. if (InstanceExpression == null)
  2368. return true;
  2369. return InstanceExpression is This || CheckProtectedMemberAccess (rc, member, InstanceExpression.Type);
  2370. }
  2371. public static bool CheckProtectedMemberAccess<T> (ResolveContext rc, T member, TypeSpec qualifier) where T : MemberSpec
  2372. {
  2373. var ct = rc.CurrentType;
  2374. if (ct == qualifier)
  2375. return true;
  2376. if ((member.Modifiers & Modifiers.INTERNAL) != 0 && member.DeclaringType.MemberDefinition.IsInternalAsPublic (ct.MemberDefinition.DeclaringAssembly))
  2377. return true;
  2378. qualifier = qualifier.GetDefinition ();
  2379. if (ct != qualifier && !IsSameOrBaseQualifier (ct, qualifier)) {
  2380. return false;
  2381. }
  2382. return true;
  2383. }
  2384. public override bool ContainsEmitWithAwait ()
  2385. {
  2386. return InstanceExpression != null && InstanceExpression.ContainsEmitWithAwait ();
  2387. }
  2388. static bool IsSameOrBaseQualifier (TypeSpec type, TypeSpec qtype)
  2389. {
  2390. do {
  2391. type = type.GetDefinition ();
  2392. if (type == qtype || TypeManager.IsFamilyAccessible (qtype, type))
  2393. return true;
  2394. type = type.DeclaringType;
  2395. } while (type != null);
  2396. return false;
  2397. }
  2398. protected void DoBestMemberChecks<T> (ResolveContext rc, T member) where T : MemberSpec, IInterfaceMemberSpec
  2399. {
  2400. if (InstanceExpression != null) {
  2401. InstanceExpression = InstanceExpression.Resolve (rc);
  2402. CheckProtectedMemberAccess (rc, member);
  2403. }
  2404. if (member.MemberType.IsPointer && !rc.IsUnsafe) {
  2405. UnsafeError (rc, loc);
  2406. }
  2407. var dep = member.GetMissingDependencies ();
  2408. if (dep != null) {
  2409. ImportedTypeDefinition.Error_MissingDependency (rc, dep, loc);
  2410. }
  2411. if (!rc.IsObsolete) {
  2412. ObsoleteAttribute oa = member.GetAttributeObsolete ();
  2413. if (oa != null)
  2414. AttributeTester.Report_ObsoleteMessage (oa, member.GetSignatureForError (), loc, rc.Report);
  2415. }
  2416. if (!(member is FieldSpec))
  2417. member.MemberDefinition.SetIsUsed ();
  2418. }
  2419. protected virtual void Error_CannotCallAbstractBase (ResolveContext rc, string name)
  2420. {
  2421. rc.Report.Error (205, loc, "Cannot call an abstract base member `{0}'", name);
  2422. }
  2423. public static void Error_ProtectedMemberAccess (ResolveContext rc, MemberSpec member, TypeSpec qualifier, Location loc)
  2424. {
  2425. rc.Report.SymbolRelatedToPreviousError (member);
  2426. rc.Report.Error (1540, loc,
  2427. "Cannot access protected member `{0}' via a qualifier of type `{1}'. The qualifier must be of type `{2}' or derived from it",
  2428. member.GetSignatureForError (), qualifier.GetSignatureForError (), rc.CurrentType.GetSignatureForError ());
  2429. }
  2430. //
  2431. // Implements identicial simple name and type-name
  2432. //
  2433. public Expression ProbeIdenticalTypeName (ResolveContext rc, Expression left, SimpleName name)
  2434. {
  2435. var t = left.Type;
  2436. if (t.Kind == MemberKind.InternalCompilerType || t is ElementTypeSpec || t.Arity > 0)
  2437. return left;
  2438. // In a member access of the form E.I, if E is a single identifier, and if the meaning of E as a simple-name is
  2439. // a constant, field, property, local variable, or parameter with the same type as the meaning of E as a type-name
  2440. if (left is MemberExpr || left is VariableReference) {
  2441. var identical_type = rc.LookupNamespaceOrType (name.Name, 0, LookupMode.Probing, loc) as TypeExpr;
  2442. if (identical_type != null && identical_type.Type == left.Type)
  2443. return identical_type;
  2444. }
  2445. return left;
  2446. }
  2447. public bool ResolveInstanceExpression (ResolveContext rc, Expression rhs)
  2448. {
  2449. if (IsStatic) {
  2450. if (InstanceExpression != null) {
  2451. if (InstanceExpression is TypeExpr) {
  2452. var t = InstanceExpression.Type;
  2453. do {
  2454. ObsoleteAttribute oa = t.GetAttributeObsolete ();
  2455. if (oa != null && !rc.IsObsolete) {
  2456. AttributeTester.Report_ObsoleteMessage (oa, t.GetSignatureForError (), loc, rc.Report);
  2457. }
  2458. t = t.DeclaringType;
  2459. } while (t != null);
  2460. } else {
  2461. var runtime_expr = InstanceExpression as RuntimeValueExpression;
  2462. if (runtime_expr == null || !runtime_expr.IsSuggestionOnly) {
  2463. rc.Report.Error (176, loc,
  2464. "Static member `{0}' cannot be accessed with an instance reference, qualify it with a type name instead",
  2465. GetSignatureForError ());
  2466. }
  2467. }
  2468. InstanceExpression = null;
  2469. }
  2470. return false;
  2471. }
  2472. if (InstanceExpression == null || InstanceExpression is TypeExpr) {
  2473. if (InstanceExpression != null || !This.IsThisAvailable (rc, true)) {
  2474. if (rc.HasSet (ResolveContext.Options.FieldInitializerScope))
  2475. rc.Report.Error (236, loc,
  2476. "A field initializer cannot reference the nonstatic field, method, or property `{0}'",
  2477. GetSignatureForError ());
  2478. else
  2479. rc.Report.Error (120, loc,
  2480. "An object reference is required to access non-static member `{0}'",
  2481. GetSignatureForError ());
  2482. InstanceExpression = new CompilerGeneratedThis (type, loc).Resolve (rc);
  2483. return false;
  2484. }
  2485. if (!TypeManager.IsFamilyAccessible (rc.CurrentType, DeclaringType)) {
  2486. rc.Report.Error (38, loc,
  2487. "Cannot access a nonstatic member of outer type `{0}' via nested type `{1}'",
  2488. DeclaringType.GetSignatureForError (), rc.CurrentType.GetSignatureForError ());
  2489. }
  2490. InstanceExpression = new This (loc);
  2491. if (this is FieldExpr && rc.CurrentBlock.ParametersBlock.TopBlock.ThisVariable != null) {
  2492. using (rc.Set (ResolveContext.Options.OmitStructFlowAnalysis)) {
  2493. InstanceExpression = InstanceExpression.Resolve (rc);
  2494. }
  2495. } else {
  2496. InstanceExpression = InstanceExpression.Resolve (rc);
  2497. }
  2498. return false;
  2499. }
  2500. var me = InstanceExpression as MemberExpr;
  2501. if (me != null) {
  2502. me.ResolveInstanceExpression (rc, rhs);
  2503. var fe = me as FieldExpr;
  2504. if (fe != null && fe.IsMarshalByRefAccess (rc)) {
  2505. rc.Report.SymbolRelatedToPreviousError (me.DeclaringType);
  2506. rc.Report.Warning (1690, 1, loc,
  2507. "Cannot call methods, properties, or indexers on `{0}' because it is a value type member of a marshal-by-reference class",
  2508. me.GetSignatureForError ());
  2509. }
  2510. return true;
  2511. }
  2512. //
  2513. // Run member-access postponed check once we know that
  2514. // the expression is not field expression which is the only
  2515. // expression which can use uninitialized this
  2516. //
  2517. if (InstanceExpression is This && !(this is FieldExpr) && rc.CurrentBlock.ParametersBlock.TopBlock.ThisVariable != null) {
  2518. ((This)InstanceExpression).CheckStructThisDefiniteAssignment (rc);
  2519. }
  2520. //
  2521. // Additional checks for l-value member access
  2522. //
  2523. if (rhs != null) {
  2524. if (InstanceExpression is UnboxCast) {
  2525. rc.Report.Error (445, InstanceExpression.Location, "Cannot modify the result of an unboxing conversion");
  2526. }
  2527. }
  2528. return true;
  2529. }
  2530. public virtual MemberExpr ResolveMemberAccess (ResolveContext ec, Expression left, SimpleName original)
  2531. {
  2532. if (left != null && left.IsNull && TypeSpec.IsReferenceType (left.Type)) {
  2533. ec.Report.Warning (1720, 1, left.Location,
  2534. "Expression will always cause a `{0}'", "System.NullReferenceException");
  2535. }
  2536. InstanceExpression = left;
  2537. return this;
  2538. }
  2539. protected void EmitInstance (EmitContext ec, bool prepare_for_load)
  2540. {
  2541. TypeSpec instance_type = InstanceExpression.Type;
  2542. if (TypeSpec.IsValueType (instance_type)) {
  2543. if (InstanceExpression is IMemoryLocation) {
  2544. ((IMemoryLocation) InstanceExpression).AddressOf (ec, AddressOp.Load);
  2545. } else {
  2546. // Cannot release the temporary variable when its address
  2547. // is required to be on stack for any parent
  2548. LocalTemporary t = new LocalTemporary (instance_type);
  2549. InstanceExpression.Emit (ec);
  2550. t.Store (ec);
  2551. t.AddressOf (ec, AddressOp.Store);
  2552. }
  2553. } else {
  2554. InstanceExpression.Emit (ec);
  2555. // Only to make verifier happy
  2556. if (instance_type.IsGenericParameter && !(InstanceExpression is This) && TypeSpec.IsReferenceType (instance_type))
  2557. ec.Emit (OpCodes.Box, instance_type);
  2558. }
  2559. if (prepare_for_load)
  2560. ec.Emit (OpCodes.Dup);
  2561. }
  2562. public abstract void SetTypeArguments (ResolveContext ec, TypeArguments ta);
  2563. }
  2564. public class ExtensionMethodCandidates
  2565. {
  2566. readonly NamespaceContainer container;
  2567. readonly IList<MethodSpec> methods;
  2568. readonly int index;
  2569. readonly IMemberContext context;
  2570. public ExtensionMethodCandidates (IMemberContext context, IList<MethodSpec> methods, NamespaceContainer nsContainer, int lookupIndex)
  2571. {
  2572. this.context = context;
  2573. this.methods = methods;
  2574. this.container = nsContainer;
  2575. this.index = lookupIndex;
  2576. }
  2577. public NamespaceContainer Container {
  2578. get {
  2579. return container;
  2580. }
  2581. }
  2582. public IMemberContext Context {
  2583. get {
  2584. return context;
  2585. }
  2586. }
  2587. public int LookupIndex {
  2588. get {
  2589. return index;
  2590. }
  2591. }
  2592. public IList<MethodSpec> Methods {
  2593. get {
  2594. return methods;
  2595. }
  2596. }
  2597. }
  2598. //
  2599. // Represents a group of extension method candidates for whole namespace
  2600. //
  2601. class ExtensionMethodGroupExpr : MethodGroupExpr, OverloadResolver.IErrorHandler
  2602. {
  2603. ExtensionMethodCandidates candidates;
  2604. public readonly Expression ExtensionExpression;
  2605. public ExtensionMethodGroupExpr (ExtensionMethodCandidates candidates, Expression extensionExpr, Location loc)
  2606. : base (candidates.Methods.Cast<MemberSpec>().ToList (), extensionExpr.Type, loc)
  2607. {
  2608. this.candidates = candidates;
  2609. this.ExtensionExpression = extensionExpr;
  2610. }
  2611. public override bool IsStatic {
  2612. get { return true; }
  2613. }
  2614. //
  2615. // For extension methodgroup we are not looking for base members but parent
  2616. // namespace extension methods
  2617. //
  2618. public override IList<MemberSpec> GetBaseMembers (TypeSpec baseType)
  2619. {
  2620. // TODO: candidates are null only when doing error reporting, that's
  2621. // incorrect. We have to discover same extension methods in error mode
  2622. if (candidates == null)
  2623. return null;
  2624. int arity = type_arguments == null ? 0 : type_arguments.Count;
  2625. candidates = candidates.Container.LookupExtensionMethod (candidates.Context, ExtensionExpression.Type, Name, arity, candidates.LookupIndex);
  2626. if (candidates == null)
  2627. return null;
  2628. return candidates.Methods.Cast<MemberSpec> ().ToList ();
  2629. }
  2630. public override MethodGroupExpr LookupExtensionMethod (ResolveContext rc)
  2631. {
  2632. // We are already here
  2633. return null;
  2634. }
  2635. public override MethodGroupExpr OverloadResolve (ResolveContext ec, ref Arguments arguments, OverloadResolver.IErrorHandler ehandler, OverloadResolver.Restrictions restr)
  2636. {
  2637. if (arguments == null)
  2638. arguments = new Arguments (1);
  2639. arguments.Insert (0, new Argument (ExtensionExpression, Argument.AType.ExtensionType));
  2640. var res = base.OverloadResolve (ec, ref arguments, ehandler ?? this, restr);
  2641. // Store resolved argument and restore original arguments
  2642. if (res == null) {
  2643. // Clean-up modified arguments for error reporting
  2644. arguments.RemoveAt (0);
  2645. return null;
  2646. }
  2647. var me = ExtensionExpression as MemberExpr;
  2648. if (me != null)
  2649. me.ResolveInstanceExpression (ec, null);
  2650. InstanceExpression = null;
  2651. return this;
  2652. }
  2653. #region IErrorHandler Members
  2654. bool OverloadResolver.IErrorHandler.AmbiguousCandidates (ResolveContext rc, MemberSpec best, MemberSpec ambiguous)
  2655. {
  2656. return false;
  2657. }
  2658. bool OverloadResolver.IErrorHandler.ArgumentMismatch (ResolveContext rc, MemberSpec best, Argument arg, int index)
  2659. {
  2660. rc.Report.SymbolRelatedToPreviousError (best);
  2661. rc.Report.Error (1928, loc,
  2662. "Type `{0}' does not contain a member `{1}' and the best extension method overload `{2}' has some invalid arguments",
  2663. queried_type.GetSignatureForError (), Name, best.GetSignatureForError ());
  2664. if (index == 0) {
  2665. rc.Report.Error (1929, loc,
  2666. "Extension method instance type `{0}' cannot be converted to `{1}'",
  2667. arg.Type.GetSignatureForError (), ((MethodSpec)best).Parameters.ExtensionMethodType.GetSignatureForError ());
  2668. }
  2669. return true;
  2670. }
  2671. bool OverloadResolver.IErrorHandler.NoArgumentMatch (ResolveContext rc, MemberSpec best)
  2672. {
  2673. return false;
  2674. }
  2675. bool OverloadResolver.IErrorHandler.TypeInferenceFailed (ResolveContext rc, MemberSpec best)
  2676. {
  2677. return false;
  2678. }
  2679. #endregion
  2680. }
  2681. /// <summary>
  2682. /// MethodGroupExpr represents a group of method candidates which
  2683. /// can be resolved to the best method overload
  2684. /// </summary>
  2685. public class MethodGroupExpr : MemberExpr, OverloadResolver.IBaseMembersProvider
  2686. {
  2687. protected IList<MemberSpec> Methods;
  2688. MethodSpec best_candidate;
  2689. TypeSpec best_candidate_return;
  2690. protected TypeArguments type_arguments;
  2691. SimpleName simple_name;
  2692. protected TypeSpec queried_type;
  2693. public MethodGroupExpr (IList<MemberSpec> mi, TypeSpec type, Location loc)
  2694. {
  2695. Methods = mi;
  2696. this.loc = loc;
  2697. this.type = InternalType.MethodGroup;
  2698. eclass = ExprClass.MethodGroup;
  2699. queried_type = type;
  2700. }
  2701. public MethodGroupExpr (MethodSpec m, TypeSpec type, Location loc)
  2702. : this (new MemberSpec[] { m }, type, loc)
  2703. {
  2704. }
  2705. #region Properties
  2706. public MethodSpec BestCandidate {
  2707. get {
  2708. return best_candidate;
  2709. }
  2710. }
  2711. public TypeSpec BestCandidateReturnType {
  2712. get {
  2713. return best_candidate_return;
  2714. }
  2715. }
  2716. public IList<MemberSpec> Candidates {
  2717. get {
  2718. return Methods;
  2719. }
  2720. }
  2721. protected override TypeSpec DeclaringType {
  2722. get {
  2723. return queried_type;
  2724. }
  2725. }
  2726. public override bool IsInstance {
  2727. get {
  2728. if (best_candidate != null)
  2729. return !best_candidate.IsStatic;
  2730. return false;
  2731. }
  2732. }
  2733. public override bool IsStatic {
  2734. get {
  2735. if (best_candidate != null)
  2736. return best_candidate.IsStatic;
  2737. return false;
  2738. }
  2739. }
  2740. public override string KindName {
  2741. get { return "method"; }
  2742. }
  2743. public override string Name {
  2744. get {
  2745. if (best_candidate != null)
  2746. return best_candidate.Name;
  2747. // TODO: throw ?
  2748. return Methods.First ().Name;
  2749. }
  2750. }
  2751. #endregion
  2752. //
  2753. // When best candidate is already know this factory can be used
  2754. // to avoid expensive overload resolution to be called
  2755. //
  2756. // NOTE: InstanceExpression has to be set manually
  2757. //
  2758. public static MethodGroupExpr CreatePredefined (MethodSpec best, TypeSpec queriedType, Location loc)
  2759. {
  2760. return new MethodGroupExpr (best, queriedType, loc) {
  2761. best_candidate = best,
  2762. best_candidate_return = best.ReturnType
  2763. };
  2764. }
  2765. public override string GetSignatureForError ()
  2766. {
  2767. if (best_candidate != null)
  2768. return best_candidate.GetSignatureForError ();
  2769. return Methods.First ().GetSignatureForError ();
  2770. }
  2771. public override Expression CreateExpressionTree (ResolveContext ec)
  2772. {
  2773. if (best_candidate == null) {
  2774. ec.Report.Error (1953, loc, "An expression tree cannot contain an expression with method group");
  2775. return null;
  2776. }
  2777. if (best_candidate.IsConditionallyExcluded (ec, loc))
  2778. ec.Report.Error (765, loc,
  2779. "Partial methods with only a defining declaration or removed conditional methods cannot be used in an expression tree");
  2780. return new TypeOfMethod (best_candidate, loc);
  2781. }
  2782. protected override Expression DoResolve (ResolveContext ec)
  2783. {
  2784. this.eclass = ExprClass.MethodGroup;
  2785. if (InstanceExpression != null) {
  2786. InstanceExpression = InstanceExpression.Resolve (ec);
  2787. if (InstanceExpression == null)
  2788. return null;
  2789. }
  2790. return this;
  2791. }
  2792. public override void Emit (EmitContext ec)
  2793. {
  2794. throw new NotSupportedException ();
  2795. }
  2796. public void EmitCall (EmitContext ec, Arguments arguments)
  2797. {
  2798. var call = new CallEmitter ();
  2799. call.InstanceExpression = InstanceExpression;
  2800. call.Emit (ec, best_candidate, arguments, loc);
  2801. }
  2802. public override void Error_ValueCannotBeConverted (ResolveContext ec, TypeSpec target, bool expl)
  2803. {
  2804. ec.Report.Error (428, loc, "Cannot convert method group `{0}' to non-delegate type `{1}'. Consider using parentheses to invoke the method",
  2805. Name, TypeManager.CSharpName (target));
  2806. }
  2807. public static bool IsExtensionMethodArgument (Expression expr)
  2808. {
  2809. //
  2810. // LAMESPEC: No details about which expressions are not allowed
  2811. //
  2812. return !(expr is TypeExpr) && !(expr is BaseThis);
  2813. }
  2814. /// <summary>
  2815. /// Find the Applicable Function Members (7.4.2.1)
  2816. ///
  2817. /// me: Method Group expression with the members to select.
  2818. /// it might contain constructors or methods (or anything
  2819. /// that maps to a method).
  2820. ///
  2821. /// Arguments: ArrayList containing resolved Argument objects.
  2822. ///
  2823. /// loc: The location if we want an error to be reported, or a Null
  2824. /// location for "probing" purposes.
  2825. ///
  2826. /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
  2827. /// that is the best match of me on Arguments.
  2828. ///
  2829. /// </summary>
  2830. public virtual MethodGroupExpr OverloadResolve (ResolveContext ec, ref Arguments args, OverloadResolver.IErrorHandler cerrors, OverloadResolver.Restrictions restr)
  2831. {
  2832. // TODO: causes issues with probing mode, remove explicit Kind check
  2833. if (best_candidate != null && best_candidate.Kind == MemberKind.Destructor)
  2834. return this;
  2835. var r = new OverloadResolver (Methods, type_arguments, restr, loc);
  2836. if ((restr & OverloadResolver.Restrictions.NoBaseMembers) == 0) {
  2837. r.BaseMembersProvider = this;
  2838. r.InstanceQualifier = this;
  2839. }
  2840. if (cerrors != null)
  2841. r.CustomErrors = cerrors;
  2842. // TODO: When in probing mode do IsApplicable only and when called again do VerifyArguments for full error reporting
  2843. best_candidate = r.ResolveMember<MethodSpec> (ec, ref args);
  2844. if (best_candidate == null)
  2845. return r.BestCandidateIsDynamic ? this : null;
  2846. // Overload resolver had to create a new method group, all checks bellow have already been executed
  2847. if (r.BestCandidateNewMethodGroup != null)
  2848. return r.BestCandidateNewMethodGroup;
  2849. if (best_candidate.Kind == MemberKind.Method && (restr & OverloadResolver.Restrictions.ProbingOnly) == 0) {
  2850. if (InstanceExpression != null) {
  2851. if (best_candidate.IsExtensionMethod && args[0].Expr == InstanceExpression) {
  2852. InstanceExpression = null;
  2853. } else {
  2854. if (best_candidate.IsStatic && simple_name != null) {
  2855. InstanceExpression = ProbeIdenticalTypeName (ec, InstanceExpression, simple_name);
  2856. }
  2857. InstanceExpression.Resolve (ec);
  2858. }
  2859. }
  2860. ResolveInstanceExpression (ec, null);
  2861. }
  2862. var base_override = CandidateToBaseOverride (ec, best_candidate);
  2863. if (base_override == best_candidate) {
  2864. best_candidate_return = r.BestCandidateReturnType;
  2865. } else {
  2866. best_candidate = base_override;
  2867. best_candidate_return = best_candidate.ReturnType;
  2868. }
  2869. return this;
  2870. }
  2871. public override MemberExpr ResolveMemberAccess (ResolveContext ec, Expression left, SimpleName original)
  2872. {
  2873. simple_name = original;
  2874. return base.ResolveMemberAccess (ec, left, original);
  2875. }
  2876. public override void SetTypeArguments (ResolveContext ec, TypeArguments ta)
  2877. {
  2878. type_arguments = ta;
  2879. }
  2880. #region IBaseMembersProvider Members
  2881. public virtual IList<MemberSpec> GetBaseMembers (TypeSpec baseType)
  2882. {
  2883. return baseType == null ? null : MemberCache.FindMembers (baseType, Methods [0].Name, false);
  2884. }
  2885. public IParametersMember GetOverrideMemberParameters (MemberSpec member)
  2886. {
  2887. if (queried_type == member.DeclaringType)
  2888. return null;
  2889. return MemberCache.FindMember (queried_type, new MemberFilter ((MethodSpec) member),
  2890. BindingRestriction.InstanceOnly | BindingRestriction.OverrideOnly) as IParametersMember;
  2891. }
  2892. //
  2893. // Extension methods lookup after ordinary methods candidates failed to apply
  2894. //
  2895. public virtual MethodGroupExpr LookupExtensionMethod (ResolveContext rc)
  2896. {
  2897. if (InstanceExpression == null)
  2898. return null;
  2899. InstanceExpression = InstanceExpression.Resolve (rc);
  2900. if (!IsExtensionMethodArgument (InstanceExpression))
  2901. return null;
  2902. int arity = type_arguments == null ? 0 : type_arguments.Count;
  2903. var methods = rc.LookupExtensionMethod (InstanceExpression.Type, Methods[0].Name, arity);
  2904. if (methods == null)
  2905. return null;
  2906. var emg = new ExtensionMethodGroupExpr (methods, InstanceExpression, loc);
  2907. emg.SetTypeArguments (rc, type_arguments);
  2908. return emg;
  2909. }
  2910. #endregion
  2911. }
  2912. struct ConstructorInstanceQualifier : OverloadResolver.IInstanceQualifier
  2913. {
  2914. public ConstructorInstanceQualifier (TypeSpec type)
  2915. : this ()
  2916. {
  2917. InstanceType = type;
  2918. }
  2919. public TypeSpec InstanceType { get; private set; }
  2920. public bool CheckProtectedMemberAccess (ResolveContext rc, MemberSpec member)
  2921. {
  2922. return MemberExpr.CheckProtectedMemberAccess (rc, member, InstanceType);
  2923. }
  2924. }
  2925. public struct OverloadResolver
  2926. {
  2927. [Flags]
  2928. public enum Restrictions
  2929. {
  2930. None = 0,
  2931. DelegateInvoke = 1,
  2932. ProbingOnly = 1 << 1,
  2933. CovariantDelegate = 1 << 2,
  2934. NoBaseMembers = 1 << 3,
  2935. BaseMembersIncluded = 1 << 4
  2936. }
  2937. public interface IBaseMembersProvider
  2938. {
  2939. IList<MemberSpec> GetBaseMembers (TypeSpec baseType);
  2940. IParametersMember GetOverrideMemberParameters (MemberSpec member);
  2941. MethodGroupExpr LookupExtensionMethod (ResolveContext rc);
  2942. }
  2943. public interface IErrorHandler
  2944. {
  2945. bool AmbiguousCandidates (ResolveContext rc, MemberSpec best, MemberSpec ambiguous);
  2946. bool ArgumentMismatch (ResolveContext rc, MemberSpec best, Argument a, int index);
  2947. bool NoArgumentMatch (ResolveContext rc, MemberSpec best);
  2948. bool TypeInferenceFailed (ResolveContext rc, MemberSpec best);
  2949. }
  2950. public interface IInstanceQualifier
  2951. {
  2952. TypeSpec InstanceType { get; }
  2953. bool CheckProtectedMemberAccess (ResolveContext rc, MemberSpec member);
  2954. }
  2955. sealed class NoBaseMembers : IBaseMembersProvider
  2956. {
  2957. public static readonly IBaseMembersProvider Instance = new NoBaseMembers ();
  2958. public IList<MemberSpec> GetBaseMembers (TypeSpec baseType)
  2959. {
  2960. return null;
  2961. }
  2962. public IParametersMember GetOverrideMemberParameters (MemberSpec member)
  2963. {
  2964. return null;
  2965. }
  2966. public MethodGroupExpr LookupExtensionMethod (ResolveContext rc)
  2967. {
  2968. return null;
  2969. }
  2970. }
  2971. struct AmbiguousCandidate
  2972. {
  2973. public readonly MemberSpec Member;
  2974. public readonly bool Expanded;
  2975. public readonly AParametersCollection Parameters;
  2976. public AmbiguousCandidate (MemberSpec member, AParametersCollection parameters, bool expanded)
  2977. {
  2978. Member = member;
  2979. Parameters = parameters;
  2980. Expanded = expanded;
  2981. }
  2982. }
  2983. Location loc;
  2984. IList<MemberSpec> members;
  2985. TypeArguments type_arguments;
  2986. IBaseMembersProvider base_provider;
  2987. IErrorHandler custom_errors;
  2988. IInstanceQualifier instance_qualifier;
  2989. Restrictions restrictions;
  2990. MethodGroupExpr best_candidate_extension_group;
  2991. TypeSpec best_candidate_return_type;
  2992. SessionReportPrinter lambda_conv_msgs;
  2993. ReportPrinter prev_recorder;
  2994. public OverloadResolver (IList<MemberSpec> members, Restrictions restrictions, Location loc)
  2995. : this (members, null, restrictions, loc)
  2996. {
  2997. }
  2998. public OverloadResolver (IList<MemberSpec> members, TypeArguments targs, Restrictions restrictions, Location loc)
  2999. : this ()
  3000. {
  3001. if (members == null || members.Count == 0)
  3002. throw new ArgumentException ("empty members set");
  3003. this.members = members;
  3004. this.loc = loc;
  3005. type_arguments = targs;
  3006. this.restrictions = restrictions;
  3007. if (IsDelegateInvoke)
  3008. this.restrictions |= Restrictions.NoBaseMembers;
  3009. base_provider = NoBaseMembers.Instance;
  3010. }
  3011. #region Properties
  3012. public IBaseMembersProvider BaseMembersProvider {
  3013. get {
  3014. return base_provider;
  3015. }
  3016. set {
  3017. base_provider = value;
  3018. }
  3019. }
  3020. public bool BestCandidateIsDynamic { get; set; }
  3021. //
  3022. // Best candidate was found in newly created MethodGroupExpr, used by extension methods
  3023. //
  3024. public MethodGroupExpr BestCandidateNewMethodGroup {
  3025. get {
  3026. return best_candidate_extension_group;
  3027. }
  3028. }
  3029. //
  3030. // Return type can be different between best candidate and closest override
  3031. //
  3032. public TypeSpec BestCandidateReturnType {
  3033. get {
  3034. return best_candidate_return_type;
  3035. }
  3036. }
  3037. public IErrorHandler CustomErrors {
  3038. get {
  3039. return custom_errors;
  3040. }
  3041. set {
  3042. custom_errors = value;
  3043. }
  3044. }
  3045. TypeSpec DelegateType {
  3046. get {
  3047. if ((restrictions & Restrictions.DelegateInvoke) == 0)
  3048. throw new InternalErrorException ("Not running in delegate mode", loc);
  3049. return members [0].DeclaringType;
  3050. }
  3051. }
  3052. public IInstanceQualifier InstanceQualifier {
  3053. get {
  3054. return instance_qualifier;
  3055. }
  3056. set {
  3057. instance_qualifier = value;
  3058. }
  3059. }
  3060. bool IsProbingOnly {
  3061. get {
  3062. return (restrictions & Restrictions.ProbingOnly) != 0;
  3063. }
  3064. }
  3065. bool IsDelegateInvoke {
  3066. get {
  3067. return (restrictions & Restrictions.DelegateInvoke) != 0;
  3068. }
  3069. }
  3070. #endregion
  3071. //
  3072. // 7.4.3.3 Better conversion from expression
  3073. // Returns : 1 if a->p is better,
  3074. // 2 if a->q is better,
  3075. // 0 if neither is better
  3076. //
  3077. static int BetterExpressionConversion (ResolveContext ec, Argument a, TypeSpec p, TypeSpec q)
  3078. {
  3079. TypeSpec argument_type = a.Type;
  3080. //
  3081. // If argument is an anonymous function
  3082. //
  3083. if (argument_type == InternalType.AnonymousMethod && ec.Module.Compiler.Settings.Version > LanguageVersion.ISO_2) {
  3084. //
  3085. // p and q are delegate types or expression tree types
  3086. //
  3087. if (p.IsExpressionTreeType || q.IsExpressionTreeType) {
  3088. if (q.MemberDefinition != p.MemberDefinition) {
  3089. return 0;
  3090. }
  3091. //
  3092. // Uwrap delegate from Expression<T>
  3093. //
  3094. q = TypeManager.GetTypeArguments (q)[0];
  3095. p = TypeManager.GetTypeArguments (p)[0];
  3096. }
  3097. var p_m = Delegate.GetInvokeMethod (p);
  3098. var q_m = Delegate.GetInvokeMethod (q);
  3099. //
  3100. // With identical parameter lists
  3101. //
  3102. if (!TypeSpecComparer.Equals (p_m.Parameters.Types, q_m.Parameters.Types))
  3103. return 0;
  3104. p = p_m.ReturnType;
  3105. q = q_m.ReturnType;
  3106. //
  3107. // if p is void returning, and q has a return type Y, then C2 is the better conversion.
  3108. //
  3109. if (p.Kind == MemberKind.Void) {
  3110. return q.Kind != MemberKind.Void ? 2 : 0;
  3111. }
  3112. //
  3113. // if p has a return type Y, and q is void returning, then C1 is the better conversion.
  3114. //
  3115. if (q.Kind == MemberKind.Void) {
  3116. return p.Kind != MemberKind.Void ? 1: 0;
  3117. }
  3118. //
  3119. // When anonymous method is an asynchronous, and P has a return type Task<Y1>, and Q has a return type Task<Y2>
  3120. // better conversion is performed between underlying types Y1 and Y2
  3121. //
  3122. if (p.IsGenericTask || q.IsGenericTask) {
  3123. var async_am = a.Expr as AnonymousMethodExpression;
  3124. if (async_am != null && async_am.Block.IsAsync) {
  3125. if (p.IsGenericTask != q.IsGenericTask) {
  3126. return 0;
  3127. }
  3128. q = q.TypeArguments[0];
  3129. p = p.TypeArguments[0];
  3130. }
  3131. }
  3132. //
  3133. // The parameters are identicial and return type is not void, use better type conversion
  3134. // on return type to determine better one
  3135. //
  3136. } else {
  3137. if (argument_type == p)
  3138. return 1;
  3139. if (argument_type == q)
  3140. return 2;
  3141. }
  3142. return BetterTypeConversion (ec, p, q);
  3143. }
  3144. //
  3145. // 7.4.3.4 Better conversion from type
  3146. //
  3147. public static int BetterTypeConversion (ResolveContext ec, TypeSpec p, TypeSpec q)
  3148. {
  3149. if (p == null || q == null)
  3150. throw new InternalErrorException ("BetterTypeConversion got a null conversion");
  3151. switch (p.BuiltinType) {
  3152. case BuiltinTypeSpec.Type.Int:
  3153. if (q.BuiltinType == BuiltinTypeSpec.Type.UInt || q.BuiltinType == BuiltinTypeSpec.Type.ULong)
  3154. return 1;
  3155. break;
  3156. case BuiltinTypeSpec.Type.Long:
  3157. if (q.BuiltinType == BuiltinTypeSpec.Type.ULong)
  3158. return 1;
  3159. break;
  3160. case BuiltinTypeSpec.Type.SByte:
  3161. switch (q.BuiltinType) {
  3162. case BuiltinTypeSpec.Type.Byte:
  3163. case BuiltinTypeSpec.Type.UShort:
  3164. case BuiltinTypeSpec.Type.UInt:
  3165. case BuiltinTypeSpec.Type.ULong:
  3166. return 1;
  3167. }
  3168. break;
  3169. case BuiltinTypeSpec.Type.Short:
  3170. switch (q.BuiltinType) {
  3171. case BuiltinTypeSpec.Type.UShort:
  3172. case BuiltinTypeSpec.Type.UInt:
  3173. case BuiltinTypeSpec.Type.ULong:
  3174. return 1;
  3175. }
  3176. break;
  3177. case BuiltinTypeSpec.Type.Dynamic:
  3178. // Dynamic is never better
  3179. return 2;
  3180. }
  3181. switch (q.BuiltinType) {
  3182. case BuiltinTypeSpec.Type.Int:
  3183. if (p.BuiltinType == BuiltinTypeSpec.Type.UInt || p.BuiltinType == BuiltinTypeSpec.Type.ULong)
  3184. return 2;
  3185. break;
  3186. case BuiltinTypeSpec.Type.Long:
  3187. if (p.BuiltinType == BuiltinTypeSpec.Type.ULong)
  3188. return 2;
  3189. break;
  3190. case BuiltinTypeSpec.Type.SByte:
  3191. switch (p.BuiltinType) {
  3192. case BuiltinTypeSpec.Type.Byte:
  3193. case BuiltinTypeSpec.Type.UShort:
  3194. case BuiltinTypeSpec.Type.UInt:
  3195. case BuiltinTypeSpec.Type.ULong:
  3196. return 2;
  3197. }
  3198. break;
  3199. case BuiltinTypeSpec.Type.Short:
  3200. switch (p.BuiltinType) {
  3201. case BuiltinTypeSpec.Type.UShort:
  3202. case BuiltinTypeSpec.Type.UInt:
  3203. case BuiltinTypeSpec.Type.ULong:
  3204. return 2;
  3205. }
  3206. break;
  3207. case BuiltinTypeSpec.Type.Dynamic:
  3208. // Dynamic is never better
  3209. return 1;
  3210. }
  3211. // FIXME: handle lifted operators
  3212. // TODO: this is expensive
  3213. Expression p_tmp = new EmptyExpression (p);
  3214. Expression q_tmp = new EmptyExpression (q);
  3215. bool p_to_q = Convert.ImplicitConversionExists (ec, p_tmp, q);
  3216. bool q_to_p = Convert.ImplicitConversionExists (ec, q_tmp, p);
  3217. if (p_to_q && !q_to_p)
  3218. return 1;
  3219. if (q_to_p && !p_to_q)
  3220. return 2;
  3221. return 0;
  3222. }
  3223. /// <summary>
  3224. /// Determines "Better function" between candidate
  3225. /// and the current best match
  3226. /// </summary>
  3227. /// <remarks>
  3228. /// Returns a boolean indicating :
  3229. /// false if candidate ain't better
  3230. /// true if candidate is better than the current best match
  3231. /// </remarks>
  3232. static bool BetterFunction (ResolveContext ec, Arguments args, MemberSpec candidate, AParametersCollection cparam, bool candidate_params,
  3233. MemberSpec best, AParametersCollection bparam, bool best_params)
  3234. {
  3235. AParametersCollection candidate_pd = ((IParametersMember) candidate).Parameters;
  3236. AParametersCollection best_pd = ((IParametersMember) best).Parameters;
  3237. bool better_at_least_one = false;
  3238. bool same = true;
  3239. int args_count = args == null ? 0 : args.Count;
  3240. int j = 0;
  3241. Argument a = null;
  3242. TypeSpec ct, bt;
  3243. for (int c_idx = 0, b_idx = 0; j < args_count; ++j, ++c_idx, ++b_idx) {
  3244. a = args[j];
  3245. // Default arguments are ignored for better decision
  3246. if (a.IsDefaultArgument)
  3247. break;
  3248. //
  3249. // When comparing named argument the parameter type index has to be looked up
  3250. // in original parameter set (override version for virtual members)
  3251. //
  3252. NamedArgument na = a as NamedArgument;
  3253. if (na != null) {
  3254. int idx = cparam.GetParameterIndexByName (na.Name);
  3255. ct = candidate_pd.Types[idx];
  3256. if (candidate_params && candidate_pd.FixedParameters[idx].ModFlags == Parameter.Modifier.PARAMS)
  3257. ct = TypeManager.GetElementType (ct);
  3258. idx = bparam.GetParameterIndexByName (na.Name);
  3259. bt = best_pd.Types[idx];
  3260. if (best_params && best_pd.FixedParameters[idx].ModFlags == Parameter.Modifier.PARAMS)
  3261. bt = TypeManager.GetElementType (bt);
  3262. } else {
  3263. ct = candidate_pd.Types[c_idx];
  3264. bt = best_pd.Types[b_idx];
  3265. if (candidate_params && candidate_pd.FixedParameters[c_idx].ModFlags == Parameter.Modifier.PARAMS) {
  3266. ct = TypeManager.GetElementType (ct);
  3267. --c_idx;
  3268. }
  3269. if (best_params && best_pd.FixedParameters[b_idx].ModFlags == Parameter.Modifier.PARAMS) {
  3270. bt = TypeManager.GetElementType (bt);
  3271. --b_idx;
  3272. }
  3273. }
  3274. if (TypeSpecComparer.IsEqual (ct, bt))
  3275. continue;
  3276. same = false;
  3277. int result = BetterExpressionConversion (ec, a, ct, bt);
  3278. // for each argument, the conversion to 'ct' should be no worse than
  3279. // the conversion to 'bt'.
  3280. if (result == 2)
  3281. return false;
  3282. // for at least one argument, the conversion to 'ct' should be better than
  3283. // the conversion to 'bt'.
  3284. if (result != 0)
  3285. better_at_least_one = true;
  3286. }
  3287. if (better_at_least_one)
  3288. return true;
  3289. //
  3290. // This handles the case
  3291. //
  3292. // Add (float f1, float f2, float f3);
  3293. // Add (params decimal [] foo);
  3294. //
  3295. // The call Add (3, 4, 5) should be ambiguous. Without this check, the
  3296. // first candidate would've chosen as better.
  3297. //
  3298. if (!same && !a.IsDefaultArgument)
  3299. return false;
  3300. //
  3301. // The two methods have equal non-optional parameter types, apply tie-breaking rules
  3302. //
  3303. //
  3304. // This handles the following cases:
  3305. //
  3306. // Foo (int i) is better than Foo (int i, long l = 0)
  3307. // Foo (params int[] args) is better than Foo (int i = 0, params int[] args)
  3308. //
  3309. // Prefer non-optional version
  3310. //
  3311. // LAMESPEC: Specification claims this should be done at last but the opposite is true
  3312. //
  3313. if (candidate_params == best_params && candidate_pd.Count != best_pd.Count) {
  3314. if (candidate_pd.Count >= best_pd.Count)
  3315. return false;
  3316. if (j < candidate_pd.Count && candidate_pd.FixedParameters[j].HasDefaultValue)
  3317. return false;
  3318. return true;
  3319. }
  3320. //
  3321. // One is a non-generic method and second is a generic method, then non-generic is better
  3322. //
  3323. if (best.IsGeneric != candidate.IsGeneric)
  3324. return best.IsGeneric;
  3325. //
  3326. // This handles the following cases:
  3327. //
  3328. // Trim () is better than Trim (params char[] chars)
  3329. // Concat (string s1, string s2, string s3) is better than
  3330. // Concat (string s1, params string [] srest)
  3331. // Foo (int, params int [] rest) is better than Foo (params int [] rest)
  3332. //
  3333. // Prefer non-expanded version
  3334. //
  3335. if (candidate_params != best_params)
  3336. return best_params;
  3337. int candidate_param_count = candidate_pd.Count;
  3338. int best_param_count = best_pd.Count;
  3339. if (candidate_param_count != best_param_count)
  3340. // can only happen if (candidate_params && best_params)
  3341. return candidate_param_count > best_param_count && best_pd.HasParams;
  3342. //
  3343. // Both methods have the same number of parameters, and the parameters have equal types
  3344. // Pick the "more specific" signature using rules over original (non-inflated) types
  3345. //
  3346. var candidate_def_pd = ((IParametersMember) candidate.MemberDefinition).Parameters;
  3347. var best_def_pd = ((IParametersMember) best.MemberDefinition).Parameters;
  3348. bool specific_at_least_once = false;
  3349. for (j = 0; j < args_count; ++j) {
  3350. NamedArgument na = args_count == 0 ? null : args [j] as NamedArgument;
  3351. if (na != null) {
  3352. ct = candidate_def_pd.Types[cparam.GetParameterIndexByName (na.Name)];
  3353. bt = best_def_pd.Types[bparam.GetParameterIndexByName (na.Name)];
  3354. } else {
  3355. ct = candidate_def_pd.Types[j];
  3356. bt = best_def_pd.Types[j];
  3357. }
  3358. if (ct == bt)
  3359. continue;
  3360. TypeSpec specific = MoreSpecific (ct, bt);
  3361. if (specific == bt)
  3362. return false;
  3363. if (specific == ct)
  3364. specific_at_least_once = true;
  3365. }
  3366. if (specific_at_least_once)
  3367. return true;
  3368. return false;
  3369. }
  3370. public static void Error_ConstructorMismatch (ResolveContext rc, TypeSpec type, int argCount, Location loc)
  3371. {
  3372. rc.Report.Error (1729, loc,
  3373. "The type `{0}' does not contain a constructor that takes `{1}' arguments",
  3374. type.GetSignatureForError (), argCount.ToString ());
  3375. }
  3376. //
  3377. // Determines if the candidate method is applicable to the given set of arguments
  3378. // There could be two different set of parameters for same candidate where one
  3379. // is the closest override for default values and named arguments checks and second
  3380. // one being the virtual base for the parameter types and modifiers.
  3381. //
  3382. // A return value rates candidate method compatibility,
  3383. // 0 = the best, int.MaxValue = the worst
  3384. //
  3385. int IsApplicable (ResolveContext ec, ref Arguments arguments, int arg_count, ref MemberSpec candidate, IParametersMember pm, ref bool params_expanded_form, ref bool dynamicArgument, ref TypeSpec returnType)
  3386. {
  3387. // Parameters of most-derived type used mainly for named and optional parameters
  3388. var pd = pm.Parameters;
  3389. // Used for params modifier only, that's legacy of C# 1.0 which uses base type for
  3390. // params modifier instead of most-derived type
  3391. var cpd = ((IParametersMember) candidate).Parameters;
  3392. int param_count = pd.Count;
  3393. int optional_count = 0;
  3394. int score;
  3395. Arguments orig_args = arguments;
  3396. if (arg_count != param_count) {
  3397. //
  3398. // No arguments expansion when doing exact match for delegates
  3399. //
  3400. if ((restrictions & Restrictions.CovariantDelegate) == 0) {
  3401. for (int i = 0; i < pd.Count; ++i) {
  3402. if (pd.FixedParameters[i].HasDefaultValue) {
  3403. optional_count = pd.Count - i;
  3404. break;
  3405. }
  3406. }
  3407. }
  3408. if (optional_count != 0) {
  3409. // Readjust expected number when params used
  3410. if (cpd.HasParams) {
  3411. optional_count--;
  3412. if (arg_count < param_count)
  3413. param_count--;
  3414. } else if (arg_count > param_count) {
  3415. int args_gap = System.Math.Abs (arg_count - param_count);
  3416. return int.MaxValue - 10000 + args_gap;
  3417. }
  3418. } else if (arg_count != param_count) {
  3419. int args_gap = System.Math.Abs (arg_count - param_count);
  3420. if (!cpd.HasParams)
  3421. return int.MaxValue - 10000 + args_gap;
  3422. if (arg_count < param_count - 1)
  3423. return int.MaxValue - 10000 + args_gap;
  3424. }
  3425. // Resize to fit optional arguments
  3426. if (optional_count != 0) {
  3427. if (arguments == null) {
  3428. arguments = new Arguments (optional_count);
  3429. } else {
  3430. // Have to create a new container, so the next run can do same
  3431. var resized = new Arguments (param_count);
  3432. resized.AddRange (arguments);
  3433. arguments = resized;
  3434. }
  3435. for (int i = arg_count; i < param_count; ++i)
  3436. arguments.Add (null);
  3437. }
  3438. }
  3439. if (arg_count > 0) {
  3440. //
  3441. // Shuffle named arguments to the right positions if there are any
  3442. //
  3443. if (arguments[arg_count - 1] is NamedArgument) {
  3444. arg_count = arguments.Count;
  3445. for (int i = 0; i < arg_count; ++i) {
  3446. bool arg_moved = false;
  3447. while (true) {
  3448. NamedArgument na = arguments[i] as NamedArgument;
  3449. if (na == null)
  3450. break;
  3451. int index = pd.GetParameterIndexByName (na.Name);
  3452. // Named parameter not found
  3453. if (index < 0)
  3454. return (i + 1) * 3;
  3455. // already reordered
  3456. if (index == i)
  3457. break;
  3458. Argument temp;
  3459. if (index >= param_count) {
  3460. // When using parameters which should not be available to the user
  3461. if ((cpd.FixedParameters[index].ModFlags & Parameter.Modifier.PARAMS) == 0)
  3462. break;
  3463. arguments.Add (null);
  3464. ++arg_count;
  3465. temp = null;
  3466. } else {
  3467. temp = arguments[index];
  3468. // The slot has been taken by positional argument
  3469. if (temp != null && !(temp is NamedArgument))
  3470. break;
  3471. }
  3472. if (!arg_moved) {
  3473. arguments = arguments.MarkOrderedArgument (na);
  3474. arg_moved = true;
  3475. }
  3476. arguments[index] = arguments[i];
  3477. arguments[i] = temp;
  3478. if (temp == null)
  3479. break;
  3480. }
  3481. }
  3482. } else {
  3483. arg_count = arguments.Count;
  3484. }
  3485. } else if (arguments != null) {
  3486. arg_count = arguments.Count;
  3487. }
  3488. //
  3489. // 1. Handle generic method using type arguments when specified or type inference
  3490. //
  3491. TypeSpec[] ptypes;
  3492. var ms = candidate as MethodSpec;
  3493. if (ms != null && ms.IsGeneric) {
  3494. // Setup constraint checker for probing only
  3495. ConstraintChecker cc = new ConstraintChecker (null);
  3496. if (type_arguments != null) {
  3497. var g_args_count = ms.Arity;
  3498. if (g_args_count != type_arguments.Count)
  3499. return int.MaxValue - 20000 + System.Math.Abs (type_arguments.Count - g_args_count);
  3500. ms = ms.MakeGenericMethod (ec, type_arguments.Arguments);
  3501. } else {
  3502. // TODO: It should not be here (we don't know yet whether any argument is lambda) but
  3503. // for now it simplifies things. I should probably add a callback to ResolveContext
  3504. if (lambda_conv_msgs == null) {
  3505. lambda_conv_msgs = new SessionReportPrinter ();
  3506. prev_recorder = ec.Report.SetPrinter (lambda_conv_msgs);
  3507. }
  3508. var ti = new TypeInference (arguments);
  3509. TypeSpec[] i_args = ti.InferMethodArguments (ec, ms);
  3510. lambda_conv_msgs.EndSession ();
  3511. if (i_args == null)
  3512. return ti.InferenceScore - 20000;
  3513. if (i_args.Length != 0) {
  3514. ms = ms.MakeGenericMethod (ec, i_args);
  3515. }
  3516. cc.IgnoreInferredDynamic = true;
  3517. }
  3518. //
  3519. // Type arguments constraints have to match for the method to be applicable
  3520. //
  3521. if (!cc.CheckAll (ms.GetGenericMethodDefinition (), ms.TypeArguments, ms.Constraints, loc)) {
  3522. candidate = ms;
  3523. return int.MaxValue - 25000;
  3524. }
  3525. //
  3526. // We have a generic return type and at same time the method is override which
  3527. // means we have to also inflate override return type in case the candidate is
  3528. // best candidate and override return type is different to base return type.
  3529. //
  3530. // virtual Foo<T, object> with override Foo<T, dynamic>
  3531. //
  3532. if (candidate != pm) {
  3533. MethodSpec override_ms = (MethodSpec) pm;
  3534. var inflator = new TypeParameterInflator (ec, ms.DeclaringType, override_ms.GenericDefinition.TypeParameters, ms.TypeArguments);
  3535. returnType = inflator.Inflate (returnType);
  3536. } else {
  3537. returnType = ms.ReturnType;
  3538. }
  3539. candidate = ms;
  3540. ptypes = ms.Parameters.Types;
  3541. } else {
  3542. if (type_arguments != null)
  3543. return int.MaxValue - 15000;
  3544. ptypes = cpd.Types;
  3545. }
  3546. //
  3547. // 2. Each argument has to be implicitly convertible to method parameter
  3548. //
  3549. Parameter.Modifier p_mod = 0;
  3550. TypeSpec pt = null;
  3551. for (int i = 0; i < arg_count; i++) {
  3552. Argument a = arguments[i];
  3553. if (a == null) {
  3554. var fp = pd.FixedParameters[i];
  3555. if (!fp.HasDefaultValue) {
  3556. arguments = orig_args;
  3557. return arg_count * 2 + 2;
  3558. }
  3559. //
  3560. // Get the default value expression, we can use the same expression
  3561. // if the type matches
  3562. //
  3563. Expression e = fp.DefaultValue;
  3564. if (!(e is Constant) || e.Type.IsGenericOrParentIsGeneric || e.Type.IsGenericParameter) {
  3565. //
  3566. // LAMESPEC: No idea what the exact rules are for System.Reflection.Missing.Value instead of null
  3567. //
  3568. if (e == EmptyExpression.MissingValue && ptypes[i].BuiltinType == BuiltinTypeSpec.Type.Object || ptypes[i].BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
  3569. e = new MemberAccess (new MemberAccess (new MemberAccess (
  3570. new QualifiedAliasMember (QualifiedAliasMember.GlobalAlias, "System", loc), "Reflection", loc), "Missing", loc), "Value", loc);
  3571. } else {
  3572. e = new DefaultValueExpression (new TypeExpression (ptypes [i], loc), loc);
  3573. }
  3574. e = e.Resolve (ec);
  3575. }
  3576. if ((fp.ModFlags & Parameter.Modifier.CallerMask) != 0) {
  3577. //
  3578. // LAMESPEC: Attributes can be mixed together with build-in priority
  3579. //
  3580. if ((fp.ModFlags & Parameter.Modifier.CallerLineNumber) != 0) {
  3581. e = new IntLiteral (ec.BuiltinTypes, loc.Row, loc);
  3582. } else if ((fp.ModFlags & Parameter.Modifier.CallerFilePath) != 0) {
  3583. e = new StringLiteral (ec.BuiltinTypes, loc.NameFullPath, loc);
  3584. } else if (ec.MemberContext.CurrentMemberDefinition != null) {
  3585. e = new StringLiteral (ec.BuiltinTypes, ec.MemberContext.CurrentMemberDefinition.GetCallerMemberName (), loc);
  3586. }
  3587. }
  3588. arguments[i] = new Argument (e, Argument.AType.Default);
  3589. continue;
  3590. }
  3591. if (p_mod != Parameter.Modifier.PARAMS) {
  3592. p_mod = (pd.FixedParameters[i].ModFlags & ~Parameter.Modifier.PARAMS) | (cpd.FixedParameters[i].ModFlags & Parameter.Modifier.PARAMS);
  3593. pt = ptypes [i];
  3594. } else if (!params_expanded_form) {
  3595. params_expanded_form = true;
  3596. pt = ((ElementTypeSpec) pt).Element;
  3597. i -= 2;
  3598. continue;
  3599. }
  3600. score = 1;
  3601. if (!params_expanded_form) {
  3602. if (a.ArgType == Argument.AType.ExtensionType) {
  3603. //
  3604. // Indentity, implicit reference or boxing conversion must exist for the extension parameter
  3605. //
  3606. // LAMESPEC: or implicit type parameter conversion
  3607. //
  3608. var at = a.Type;
  3609. if (at == pt || TypeSpecComparer.IsEqual (at, pt) ||
  3610. Convert.ImplicitReferenceConversionExists (at, pt, false) ||
  3611. Convert.ImplicitBoxingConversion (null, at, pt) != null) {
  3612. score = 0;
  3613. continue;
  3614. }
  3615. } else {
  3616. score = IsArgumentCompatible (ec, a, p_mod, pt);
  3617. if (score < 0)
  3618. dynamicArgument = true;
  3619. }
  3620. }
  3621. //
  3622. // It can be applicable in expanded form (when not doing exact match like for delegates)
  3623. //
  3624. if (score != 0 && (p_mod & Parameter.Modifier.PARAMS) != 0 && (restrictions & Restrictions.CovariantDelegate) == 0) {
  3625. if (!params_expanded_form)
  3626. pt = ((ElementTypeSpec) pt).Element;
  3627. if (score > 0)
  3628. score = IsArgumentCompatible (ec, a, Parameter.Modifier.NONE, pt);
  3629. if (score == 0) {
  3630. params_expanded_form = true;
  3631. } else if (score < 0) {
  3632. params_expanded_form = true;
  3633. dynamicArgument = true;
  3634. }
  3635. }
  3636. if (score > 0) {
  3637. if (params_expanded_form)
  3638. ++score;
  3639. return (arg_count - i) * 2 + score;
  3640. }
  3641. }
  3642. //
  3643. // When params parameter has no argument it will be provided later if the method is the best candidate
  3644. //
  3645. if (arg_count + 1 == pd.Count && (cpd.FixedParameters [arg_count].ModFlags & Parameter.Modifier.PARAMS) != 0)
  3646. params_expanded_form = true;
  3647. //
  3648. // Restore original arguments for dynamic binder to keep the intention of original source code
  3649. //
  3650. if (dynamicArgument)
  3651. arguments = orig_args;
  3652. return 0;
  3653. }
  3654. //
  3655. // Tests argument compatibility with the parameter
  3656. // The possible return values are
  3657. // 0 - success
  3658. // 1 - modifier mismatch
  3659. // 2 - type mismatch
  3660. // -1 - dynamic binding required
  3661. //
  3662. int IsArgumentCompatible (ResolveContext ec, Argument argument, Parameter.Modifier param_mod, TypeSpec parameter)
  3663. {
  3664. //
  3665. // Types have to be identical when ref or out modifer
  3666. // is used and argument is not of dynamic type
  3667. //
  3668. if (((argument.Modifier | param_mod) & Parameter.Modifier.RefOutMask) != 0) {
  3669. if (argument.Type != parameter) {
  3670. //
  3671. // Do full equality check after quick path
  3672. //
  3673. if (!TypeSpecComparer.IsEqual (argument.Type, parameter)) {
  3674. //
  3675. // Using dynamic for ref/out parameter can still succeed at runtime
  3676. //
  3677. if (argument.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic && (argument.Modifier & Parameter.Modifier.RefOutMask) == 0 && (restrictions & Restrictions.CovariantDelegate) == 0)
  3678. return -1;
  3679. return 2;
  3680. }
  3681. }
  3682. if ((argument.Modifier & Parameter.Modifier.RefOutMask) != (param_mod & Parameter.Modifier.RefOutMask)) {
  3683. //
  3684. // Using dynamic for ref/out parameter can still succeed at runtime
  3685. //
  3686. if (argument.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic && (argument.Modifier & Parameter.Modifier.RefOutMask) == 0 && (restrictions & Restrictions.CovariantDelegate) == 0)
  3687. return -1;
  3688. return 1;
  3689. }
  3690. } else {
  3691. if (argument.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic && (restrictions & Restrictions.CovariantDelegate) == 0)
  3692. return -1;
  3693. //
  3694. // Deploy custom error reporting for lambda methods. When probing lambda methods
  3695. // keep all errors reported in separate set and once we are done and no best
  3696. // candidate was found, this set is used to report more details about what was wrong
  3697. // with lambda body
  3698. //
  3699. if (argument.Expr.Type == InternalType.AnonymousMethod) {
  3700. if (lambda_conv_msgs == null) {
  3701. lambda_conv_msgs = new SessionReportPrinter ();
  3702. prev_recorder = ec.Report.SetPrinter (lambda_conv_msgs);
  3703. }
  3704. }
  3705. //
  3706. // Use implicit conversion in all modes to return same candidates when the expression
  3707. // is used as argument or delegate conversion
  3708. //
  3709. if (!Convert.ImplicitConversionExists (ec, argument.Expr, parameter)) {
  3710. if (lambda_conv_msgs != null) {
  3711. lambda_conv_msgs.EndSession ();
  3712. }
  3713. return 2;
  3714. }
  3715. }
  3716. return 0;
  3717. }
  3718. static TypeSpec MoreSpecific (TypeSpec p, TypeSpec q)
  3719. {
  3720. if (TypeManager.IsGenericParameter (p) && !TypeManager.IsGenericParameter (q))
  3721. return q;
  3722. if (!TypeManager.IsGenericParameter (p) && TypeManager.IsGenericParameter (q))
  3723. return p;
  3724. var ac_p = p as ArrayContainer;
  3725. if (ac_p != null) {
  3726. var ac_q = q as ArrayContainer;
  3727. if (ac_q == null)
  3728. return null;
  3729. TypeSpec specific = MoreSpecific (ac_p.Element, ac_q.Element);
  3730. if (specific == ac_p.Element)
  3731. return p;
  3732. if (specific == ac_q.Element)
  3733. return q;
  3734. } else if (TypeManager.IsGenericType (p)) {
  3735. var pargs = TypeManager.GetTypeArguments (p);
  3736. var qargs = TypeManager.GetTypeArguments (q);
  3737. bool p_specific_at_least_once = false;
  3738. bool q_specific_at_least_once = false;
  3739. for (int i = 0; i < pargs.Length; i++) {
  3740. TypeSpec specific = MoreSpecific (pargs[i], qargs[i]);
  3741. if (specific == pargs[i])
  3742. p_specific_at_least_once = true;
  3743. if (specific == qargs[i])
  3744. q_specific_at_least_once = true;
  3745. }
  3746. if (p_specific_at_least_once && !q_specific_at_least_once)
  3747. return p;
  3748. if (!p_specific_at_least_once && q_specific_at_least_once)
  3749. return q;
  3750. }
  3751. return null;
  3752. }
  3753. //
  3754. // Find the best method from candidate list
  3755. //
  3756. public T ResolveMember<T> (ResolveContext rc, ref Arguments args) where T : MemberSpec, IParametersMember
  3757. {
  3758. List<AmbiguousCandidate> ambiguous_candidates = null;
  3759. MemberSpec best_candidate;
  3760. Arguments best_candidate_args = null;
  3761. bool best_candidate_params = false;
  3762. bool best_candidate_dynamic = false;
  3763. int best_candidate_rate;
  3764. IParametersMember best_parameter_member = null;
  3765. int args_count = args != null ? args.Count : 0;
  3766. Arguments candidate_args = args;
  3767. bool error_mode = false;
  3768. MemberSpec invocable_member = null;
  3769. // Be careful, cannot return until error reporter is restored
  3770. while (true) {
  3771. best_candidate = null;
  3772. best_candidate_rate = int.MaxValue;
  3773. var type_members = members;
  3774. try {
  3775. do {
  3776. for (int i = 0; i < type_members.Count; ++i) {
  3777. var member = type_members[i];
  3778. //
  3779. // Methods in a base class are not candidates if any method in a derived
  3780. // class is applicable
  3781. //
  3782. if ((member.Modifiers & Modifiers.OVERRIDE) != 0)
  3783. continue;
  3784. if (!error_mode) {
  3785. if (!member.IsAccessible (rc))
  3786. continue;
  3787. if (rc.IsRuntimeBinder && !member.DeclaringType.IsAccessible (rc))
  3788. continue;
  3789. if ((member.Modifiers & (Modifiers.PROTECTED | Modifiers.STATIC)) == Modifiers.PROTECTED &&
  3790. instance_qualifier != null && !instance_qualifier.CheckProtectedMemberAccess (rc, member)) {
  3791. continue;
  3792. }
  3793. }
  3794. IParametersMember pm = member as IParametersMember;
  3795. if (pm == null) {
  3796. //
  3797. // Will use it later to report ambiguity between best method and invocable member
  3798. //
  3799. if (Invocation.IsMemberInvocable (member))
  3800. invocable_member = member;
  3801. continue;
  3802. }
  3803. //
  3804. // Overload resolution is looking for base member but using parameter names
  3805. // and default values from the closest member. That means to do expensive lookup
  3806. // for the closest override for virtual or abstract members
  3807. //
  3808. if ((member.Modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT)) != 0) {
  3809. var override_params = base_provider.GetOverrideMemberParameters (member);
  3810. if (override_params != null)
  3811. pm = override_params;
  3812. }
  3813. //
  3814. // Check if the member candidate is applicable
  3815. //
  3816. bool params_expanded_form = false;
  3817. bool dynamic_argument = false;
  3818. TypeSpec rt = pm.MemberType;
  3819. int candidate_rate = IsApplicable (rc, ref candidate_args, args_count, ref member, pm, ref params_expanded_form, ref dynamic_argument, ref rt);
  3820. //
  3821. // How does it score compare to others
  3822. //
  3823. if (candidate_rate < best_candidate_rate) {
  3824. best_candidate_rate = candidate_rate;
  3825. best_candidate = member;
  3826. best_candidate_args = candidate_args;
  3827. best_candidate_params = params_expanded_form;
  3828. best_candidate_dynamic = dynamic_argument;
  3829. best_parameter_member = pm;
  3830. best_candidate_return_type = rt;
  3831. } else if (candidate_rate == 0) {
  3832. //
  3833. // The member look is done per type for most operations but sometimes
  3834. // it's not possible like for binary operators overload because they
  3835. // are unioned between 2 sides
  3836. //
  3837. if ((restrictions & Restrictions.BaseMembersIncluded) != 0) {
  3838. if (TypeSpec.IsBaseClass (best_candidate.DeclaringType, member.DeclaringType, true))
  3839. continue;
  3840. }
  3841. bool is_better;
  3842. if (best_candidate.DeclaringType.IsInterface && member.DeclaringType.ImplementsInterface (best_candidate.DeclaringType, false)) {
  3843. //
  3844. // We pack all interface members into top level type which makes the overload resolution
  3845. // more complicated for interfaces. We compensate it by removing methods with same
  3846. // signature when building the cache hence this path should not really be hit often
  3847. //
  3848. // Example:
  3849. // interface IA { void Foo (int arg); }
  3850. // interface IB : IA { void Foo (params int[] args); }
  3851. //
  3852. // IB::Foo is the best overload when calling IB.Foo (1)
  3853. //
  3854. is_better = true;
  3855. if (ambiguous_candidates != null) {
  3856. foreach (var amb_cand in ambiguous_candidates) {
  3857. if (member.DeclaringType.ImplementsInterface (best_candidate.DeclaringType, false)) {
  3858. continue;
  3859. }
  3860. is_better = false;
  3861. break;
  3862. }
  3863. if (is_better)
  3864. ambiguous_candidates = null;
  3865. }
  3866. } else {
  3867. // Is the new candidate better
  3868. is_better = BetterFunction (rc, candidate_args, member, pm.Parameters, params_expanded_form, best_candidate, best_parameter_member.Parameters, best_candidate_params);
  3869. }
  3870. if (is_better) {
  3871. best_candidate = member;
  3872. best_candidate_args = candidate_args;
  3873. best_candidate_params = params_expanded_form;
  3874. best_candidate_dynamic = dynamic_argument;
  3875. best_parameter_member = pm;
  3876. best_candidate_return_type = rt;
  3877. } else {
  3878. // It's not better but any other found later could be but we are not sure yet
  3879. if (ambiguous_candidates == null)
  3880. ambiguous_candidates = new List<AmbiguousCandidate> ();
  3881. ambiguous_candidates.Add (new AmbiguousCandidate (member, pm.Parameters, params_expanded_form));
  3882. }
  3883. }
  3884. // Restore expanded arguments
  3885. if (candidate_args != args)
  3886. candidate_args = args;
  3887. }
  3888. } while (best_candidate_rate != 0 && (type_members = base_provider.GetBaseMembers (type_members[0].DeclaringType.BaseType)) != null);
  3889. } finally {
  3890. if (prev_recorder != null)
  3891. rc.Report.SetPrinter (prev_recorder);
  3892. }
  3893. //
  3894. // We've found exact match
  3895. //
  3896. if (best_candidate_rate == 0)
  3897. break;
  3898. //
  3899. // Try extension methods lookup when no ordinary method match was found and provider enables it
  3900. //
  3901. if (!error_mode) {
  3902. var emg = base_provider.LookupExtensionMethod (rc);
  3903. if (emg != null) {
  3904. emg = emg.OverloadResolve (rc, ref args, null, restrictions);
  3905. if (emg != null) {
  3906. best_candidate_extension_group = emg;
  3907. return (T) (MemberSpec) emg.BestCandidate;
  3908. }
  3909. }
  3910. }
  3911. // Don't run expensive error reporting mode for probing
  3912. if (IsProbingOnly)
  3913. return null;
  3914. if (error_mode)
  3915. break;
  3916. if (lambda_conv_msgs != null && !lambda_conv_msgs.IsEmpty)
  3917. break;
  3918. lambda_conv_msgs = null;
  3919. error_mode = true;
  3920. }
  3921. //
  3922. // No best member match found, report an error
  3923. //
  3924. if (best_candidate_rate != 0 || error_mode) {
  3925. ReportOverloadError (rc, best_candidate, best_parameter_member, best_candidate_args, best_candidate_params);
  3926. return null;
  3927. }
  3928. if (best_candidate_dynamic) {
  3929. if (args[0].ArgType == Argument.AType.ExtensionType) {
  3930. rc.Report.Error (1973, loc,
  3931. "Type `{0}' does not contain a member `{1}' and the best extension method overload `{2}' cannot be dynamically dispatched. Consider calling the method without the extension method syntax",
  3932. args [0].Type.GetSignatureForError (), best_candidate.Name, best_candidate.GetSignatureForError ());
  3933. }
  3934. BestCandidateIsDynamic = true;
  3935. return null;
  3936. }
  3937. //
  3938. // These flags indicates we are running delegate probing conversion. No need to
  3939. // do more expensive checks
  3940. //
  3941. if ((restrictions & (Restrictions.ProbingOnly | Restrictions.CovariantDelegate)) == (Restrictions.CovariantDelegate | Restrictions.ProbingOnly))
  3942. return (T) best_candidate;
  3943. if (ambiguous_candidates != null) {
  3944. //
  3945. // Now check that there are no ambiguities i.e the selected method
  3946. // should be better than all the others
  3947. //
  3948. for (int ix = 0; ix < ambiguous_candidates.Count; ix++) {
  3949. var candidate = ambiguous_candidates [ix];
  3950. if (!BetterFunction (rc, best_candidate_args, best_candidate, best_parameter_member.Parameters, best_candidate_params, candidate.Member, candidate.Parameters, candidate.Expanded)) {
  3951. var ambiguous = candidate.Member;
  3952. if (custom_errors == null || !custom_errors.AmbiguousCandidates (rc, best_candidate, ambiguous)) {
  3953. rc.Report.SymbolRelatedToPreviousError (best_candidate);
  3954. rc.Report.SymbolRelatedToPreviousError (ambiguous);
  3955. rc.Report.Error (121, loc, "The call is ambiguous between the following methods or properties: `{0}' and `{1}'",
  3956. best_candidate.GetSignatureForError (), ambiguous.GetSignatureForError ());
  3957. }
  3958. return (T) best_candidate;
  3959. }
  3960. }
  3961. }
  3962. if (invocable_member != null) {
  3963. rc.Report.SymbolRelatedToPreviousError (best_candidate);
  3964. rc.Report.SymbolRelatedToPreviousError (invocable_member);
  3965. rc.Report.Warning (467, 2, loc, "Ambiguity between method `{0}' and invocable non-method `{1}'. Using method group",
  3966. best_candidate.GetSignatureForError (), invocable_member.GetSignatureForError ());
  3967. }
  3968. //
  3969. // And now check if the arguments are all
  3970. // compatible, perform conversions if
  3971. // necessary etc. and return if everything is
  3972. // all right
  3973. //
  3974. if (!VerifyArguments (rc, ref best_candidate_args, best_candidate, best_parameter_member, best_candidate_params))
  3975. return null;
  3976. if (best_candidate == null)
  3977. return null;
  3978. //
  3979. // Check ObsoleteAttribute on the best method
  3980. //
  3981. ObsoleteAttribute oa = best_candidate.GetAttributeObsolete ();
  3982. if (oa != null && !rc.IsObsolete)
  3983. AttributeTester.Report_ObsoleteMessage (oa, best_candidate.GetSignatureForError (), loc, rc.Report);
  3984. var dep = best_candidate.GetMissingDependencies ();
  3985. if (dep != null) {
  3986. ImportedTypeDefinition.Error_MissingDependency (rc, dep, loc);
  3987. }
  3988. best_candidate.MemberDefinition.SetIsUsed ();
  3989. args = best_candidate_args;
  3990. return (T) best_candidate;
  3991. }
  3992. public MethodSpec ResolveOperator (ResolveContext rc, ref Arguments args)
  3993. {
  3994. return ResolveMember<MethodSpec> (rc, ref args);
  3995. }
  3996. void ReportArgumentMismatch (ResolveContext ec, int idx, MemberSpec method,
  3997. Argument a, AParametersCollection expected_par, TypeSpec paramType)
  3998. {
  3999. if (custom_errors != null && custom_errors.ArgumentMismatch (ec, method, a, idx))
  4000. return;
  4001. if (a.Type == InternalType.ErrorType)
  4002. return;
  4003. if (a is CollectionElementInitializer.ElementInitializerArgument) {
  4004. ec.Report.SymbolRelatedToPreviousError (method);
  4005. if ((expected_par.FixedParameters[idx].ModFlags & Parameter.Modifier.RefOutMask) != 0) {
  4006. ec.Report.Error (1954, loc, "The best overloaded collection initalizer method `{0}' cannot have 'ref', or `out' modifier",
  4007. TypeManager.CSharpSignature (method));
  4008. return;
  4009. }
  4010. ec.Report.Error (1950, loc, "The best overloaded collection initalizer method `{0}' has some invalid arguments",
  4011. TypeManager.CSharpSignature (method));
  4012. } else if (IsDelegateInvoke) {
  4013. ec.Report.Error (1594, loc, "Delegate `{0}' has some invalid arguments",
  4014. DelegateType.GetSignatureForError ());
  4015. } else {
  4016. ec.Report.SymbolRelatedToPreviousError (method);
  4017. ec.Report.Error (1502, loc, "The best overloaded method match for `{0}' has some invalid arguments",
  4018. method.GetSignatureForError ());
  4019. }
  4020. Parameter.Modifier mod = idx >= expected_par.Count ? 0 : expected_par.FixedParameters[idx].ModFlags;
  4021. string index = (idx + 1).ToString ();
  4022. if (((mod & Parameter.Modifier.RefOutMask) ^ (a.Modifier & Parameter.Modifier.RefOutMask)) != 0) {
  4023. if ((mod & Parameter.Modifier.RefOutMask) == 0)
  4024. ec.Report.Error (1615, loc, "Argument `#{0}' does not require `{1}' modifier. Consider removing `{1}' modifier",
  4025. index, Parameter.GetModifierSignature (a.Modifier));
  4026. else
  4027. ec.Report.Error (1620, loc, "Argument `#{0}' is missing `{1}' modifier",
  4028. index, Parameter.GetModifierSignature (mod));
  4029. } else {
  4030. string p1 = a.GetSignatureForError ();
  4031. string p2 = TypeManager.CSharpName (paramType);
  4032. if (p1 == p2) {
  4033. p1 = a.Type.GetSignatureForErrorIncludingAssemblyName ();
  4034. p2 = paramType.GetSignatureForErrorIncludingAssemblyName ();
  4035. }
  4036. ec.Report.Error (1503, loc,
  4037. "Argument `#{0}' cannot convert `{1}' expression to type `{2}'", index, p1, p2);
  4038. }
  4039. }
  4040. //
  4041. // We have failed to find exact match so we return error info about the closest match
  4042. //
  4043. void ReportOverloadError (ResolveContext rc, MemberSpec best_candidate, IParametersMember pm, Arguments args, bool params_expanded)
  4044. {
  4045. int ta_count = type_arguments == null ? 0 : type_arguments.Count;
  4046. int arg_count = args == null ? 0 : args.Count;
  4047. if (ta_count != best_candidate.Arity && (ta_count > 0 || ((IParametersMember) best_candidate).Parameters.IsEmpty)) {
  4048. var mg = new MethodGroupExpr (new [] { best_candidate }, best_candidate.DeclaringType, loc);
  4049. mg.Error_TypeArgumentsCannotBeUsed (rc, best_candidate, ta_count, loc);
  4050. return;
  4051. }
  4052. if (lambda_conv_msgs != null) {
  4053. if (lambda_conv_msgs.Merge (rc.Report.Printer))
  4054. return;
  4055. }
  4056. if ((best_candidate.Modifiers & (Modifiers.PROTECTED | Modifiers.STATIC)) == Modifiers.PROTECTED &&
  4057. InstanceQualifier != null && !InstanceQualifier.CheckProtectedMemberAccess (rc, best_candidate)) {
  4058. MemberExpr.Error_ProtectedMemberAccess (rc, best_candidate, InstanceQualifier.InstanceType, loc);
  4059. }
  4060. //
  4061. // For candidates which match on parameters count report more details about incorrect arguments
  4062. //
  4063. if (pm != null) {
  4064. int unexpanded_count = ((IParametersMember) best_candidate).Parameters.HasParams ? pm.Parameters.Count - 1 : pm.Parameters.Count;
  4065. if (pm.Parameters.Count == arg_count || params_expanded || unexpanded_count == arg_count) {
  4066. // Reject any inaccessible member
  4067. if (!best_candidate.IsAccessible (rc) || !best_candidate.DeclaringType.IsAccessible (rc)) {
  4068. rc.Report.SymbolRelatedToPreviousError (best_candidate);
  4069. Expression.ErrorIsInaccesible (rc, best_candidate.GetSignatureForError (), loc);
  4070. return;
  4071. }
  4072. var ms = best_candidate as MethodSpec;
  4073. if (ms != null && ms.IsGeneric) {
  4074. bool constr_ok = true;
  4075. if (ms.TypeArguments != null)
  4076. constr_ok = new ConstraintChecker (rc.MemberContext).CheckAll (ms.GetGenericMethodDefinition (), ms.TypeArguments, ms.Constraints, loc);
  4077. if (ta_count == 0) {
  4078. if (custom_errors != null && custom_errors.TypeInferenceFailed (rc, best_candidate))
  4079. return;
  4080. if (constr_ok) {
  4081. rc.Report.Error (411, loc,
  4082. "The type arguments for method `{0}' cannot be inferred from the usage. Try specifying the type arguments explicitly",
  4083. ms.GetGenericMethodDefinition ().GetSignatureForError ());
  4084. }
  4085. return;
  4086. }
  4087. }
  4088. VerifyArguments (rc, ref args, best_candidate, pm, params_expanded);
  4089. return;
  4090. }
  4091. }
  4092. //
  4093. // We failed to find any method with correct argument count, report best candidate
  4094. //
  4095. if (custom_errors != null && custom_errors.NoArgumentMatch (rc, best_candidate))
  4096. return;
  4097. if (best_candidate.Kind == MemberKind.Constructor) {
  4098. rc.Report.SymbolRelatedToPreviousError (best_candidate);
  4099. Error_ConstructorMismatch (rc, best_candidate.DeclaringType, arg_count, loc);
  4100. } else if (IsDelegateInvoke) {
  4101. rc.Report.SymbolRelatedToPreviousError (DelegateType);
  4102. rc.Report.Error (1593, loc, "Delegate `{0}' does not take `{1}' arguments",
  4103. DelegateType.GetSignatureForError (), arg_count.ToString ());
  4104. } else {
  4105. string name = best_candidate.Kind == MemberKind.Indexer ? "this" : best_candidate.Name;
  4106. rc.Report.SymbolRelatedToPreviousError (best_candidate);
  4107. rc.Report.Error (1501, loc, "No overload for method `{0}' takes `{1}' arguments",
  4108. name, arg_count.ToString ());
  4109. }
  4110. }
  4111. bool VerifyArguments (ResolveContext ec, ref Arguments args, MemberSpec member, IParametersMember pm, bool chose_params_expanded)
  4112. {
  4113. var pd = pm.Parameters;
  4114. TypeSpec[] ptypes = ((IParametersMember) member).Parameters.Types;
  4115. Parameter.Modifier p_mod = 0;
  4116. TypeSpec pt = null;
  4117. int a_idx = 0, a_pos = 0;
  4118. Argument a = null;
  4119. ArrayInitializer params_initializers = null;
  4120. bool has_unsafe_arg = pm.MemberType.IsPointer;
  4121. int arg_count = args == null ? 0 : args.Count;
  4122. for (; a_idx < arg_count; a_idx++, ++a_pos) {
  4123. a = args[a_idx];
  4124. if (p_mod != Parameter.Modifier.PARAMS) {
  4125. p_mod = pd.FixedParameters[a_idx].ModFlags;
  4126. pt = ptypes[a_idx];
  4127. has_unsafe_arg |= pt.IsPointer;
  4128. if (p_mod == Parameter.Modifier.PARAMS) {
  4129. if (chose_params_expanded) {
  4130. params_initializers = new ArrayInitializer (arg_count - a_idx, a.Expr.Location);
  4131. pt = TypeManager.GetElementType (pt);
  4132. }
  4133. }
  4134. }
  4135. //
  4136. // Types have to be identical when ref or out modifer is used
  4137. //
  4138. if (((a.Modifier | p_mod) & Parameter.Modifier.RefOutMask) != 0) {
  4139. if ((a.Modifier & Parameter.Modifier.RefOutMask) != (p_mod & Parameter.Modifier.RefOutMask))
  4140. break;
  4141. if (a.Expr.Type == pt || TypeSpecComparer.IsEqual (a.Expr.Type, pt))
  4142. continue;
  4143. break;
  4144. }
  4145. NamedArgument na = a as NamedArgument;
  4146. if (na != null) {
  4147. int name_index = pd.GetParameterIndexByName (na.Name);
  4148. if (name_index < 0 || name_index >= pd.Count) {
  4149. if (IsDelegateInvoke) {
  4150. ec.Report.SymbolRelatedToPreviousError (DelegateType);
  4151. ec.Report.Error (1746, na.Location,
  4152. "The delegate `{0}' does not contain a parameter named `{1}'",
  4153. DelegateType.GetSignatureForError (), na.Name);
  4154. } else {
  4155. ec.Report.SymbolRelatedToPreviousError (member);
  4156. ec.Report.Error (1739, na.Location,
  4157. "The best overloaded method match for `{0}' does not contain a parameter named `{1}'",
  4158. TypeManager.CSharpSignature (member), na.Name);
  4159. }
  4160. } else if (args[name_index] != a) {
  4161. if (IsDelegateInvoke)
  4162. ec.Report.SymbolRelatedToPreviousError (DelegateType);
  4163. else
  4164. ec.Report.SymbolRelatedToPreviousError (member);
  4165. ec.Report.Error (1744, na.Location,
  4166. "Named argument `{0}' cannot be used for a parameter which has positional argument specified",
  4167. na.Name);
  4168. }
  4169. }
  4170. if (a.Expr.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
  4171. continue;
  4172. if ((restrictions & Restrictions.CovariantDelegate) != 0 && !Delegate.IsTypeCovariant (ec, a.Expr.Type, pt)) {
  4173. custom_errors.NoArgumentMatch (ec, member);
  4174. return false;
  4175. }
  4176. Expression conv = null;
  4177. if (a.ArgType == Argument.AType.ExtensionType) {
  4178. if (a.Expr.Type == pt || TypeSpecComparer.IsEqual (a.Expr.Type, pt)) {
  4179. conv = a.Expr;
  4180. } else {
  4181. conv = Convert.ImplicitReferenceConversion (a.Expr, pt, false);
  4182. if (conv == null)
  4183. conv = Convert.ImplicitBoxingConversion (a.Expr, a.Expr.Type, pt);
  4184. }
  4185. } else {
  4186. conv = Convert.ImplicitConversion (ec, a.Expr, pt, loc);
  4187. }
  4188. if (conv == null)
  4189. break;
  4190. //
  4191. // Convert params arguments to an array initializer
  4192. //
  4193. if (params_initializers != null) {
  4194. // we choose to use 'a.Expr' rather than 'conv' so that
  4195. // we don't hide the kind of expression we have (esp. CompoundAssign.Helper)
  4196. params_initializers.Add (a.Expr);
  4197. args.RemoveAt (a_idx--);
  4198. --arg_count;
  4199. continue;
  4200. }
  4201. // Update the argument with the implicit conversion
  4202. a.Expr = conv;
  4203. }
  4204. if (a_idx != arg_count) {
  4205. ReportArgumentMismatch (ec, a_pos, member, a, pd, pt);
  4206. return false;
  4207. }
  4208. //
  4209. // Fill not provided arguments required by params modifier
  4210. //
  4211. if (params_initializers == null && pd.HasParams && arg_count + 1 == pd.Count) {
  4212. if (args == null)
  4213. args = new Arguments (1);
  4214. pt = ptypes[pd.Count - 1];
  4215. pt = TypeManager.GetElementType (pt);
  4216. has_unsafe_arg |= pt.IsPointer;
  4217. params_initializers = new ArrayInitializer (0, loc);
  4218. }
  4219. //
  4220. // Append an array argument with all params arguments
  4221. //
  4222. if (params_initializers != null) {
  4223. args.Add (new Argument (
  4224. new ArrayCreation (new TypeExpression (pt, loc), params_initializers, loc).Resolve (ec)));
  4225. arg_count++;
  4226. }
  4227. if (has_unsafe_arg && !ec.IsUnsafe) {
  4228. Expression.UnsafeError (ec, loc);
  4229. }
  4230. //
  4231. // We could infer inaccesible type arguments
  4232. //
  4233. if (type_arguments == null && member.IsGeneric) {
  4234. var ms = (MethodSpec) member;
  4235. foreach (var ta in ms.TypeArguments) {
  4236. if (!ta.IsAccessible (ec)) {
  4237. ec.Report.SymbolRelatedToPreviousError (ta);
  4238. Expression.ErrorIsInaccesible (ec, member.GetSignatureForError (), loc);
  4239. break;
  4240. }
  4241. }
  4242. }
  4243. return true;
  4244. }
  4245. }
  4246. public class ConstantExpr : MemberExpr
  4247. {
  4248. readonly ConstSpec constant;
  4249. public ConstantExpr (ConstSpec constant, Location loc)
  4250. {
  4251. this.constant = constant;
  4252. this.loc = loc;
  4253. }
  4254. public override string Name {
  4255. get { throw new NotImplementedException (); }
  4256. }
  4257. public override string KindName {
  4258. get { return "constant"; }
  4259. }
  4260. public override bool IsInstance {
  4261. get { return !IsStatic; }
  4262. }
  4263. public override bool IsStatic {
  4264. get { return true; }
  4265. }
  4266. protected override TypeSpec DeclaringType {
  4267. get { return constant.DeclaringType; }
  4268. }
  4269. public override Expression CreateExpressionTree (ResolveContext ec)
  4270. {
  4271. throw new NotSupportedException ("ET");
  4272. }
  4273. protected override Expression DoResolve (ResolveContext rc)
  4274. {
  4275. ResolveInstanceExpression (rc, null);
  4276. DoBestMemberChecks (rc, constant);
  4277. var c = constant.GetConstant (rc);
  4278. // Creates reference expression to the constant value
  4279. return Constant.CreateConstant (constant.MemberType, c.GetValue (), loc);
  4280. }
  4281. public override void Emit (EmitContext ec)
  4282. {
  4283. throw new NotSupportedException ();
  4284. }
  4285. public override string GetSignatureForError ()
  4286. {
  4287. return constant.GetSignatureForError ();
  4288. }
  4289. public override void SetTypeArguments (ResolveContext ec, TypeArguments ta)
  4290. {
  4291. Error_TypeArgumentsCannotBeUsed (ec, "constant", GetSignatureForError (), loc);
  4292. }
  4293. }
  4294. //
  4295. // Fully resolved expression that references a Field
  4296. //
  4297. public class FieldExpr : MemberExpr, IDynamicAssign, IMemoryLocation, IVariableReference
  4298. {
  4299. protected FieldSpec spec;
  4300. VariableInfo variable_info;
  4301. LocalTemporary temp;
  4302. bool prepared;
  4303. protected FieldExpr (Location l)
  4304. {
  4305. loc = l;
  4306. }
  4307. public FieldExpr (FieldSpec spec, Location loc)
  4308. {
  4309. this.spec = spec;
  4310. this.loc = loc;
  4311. type = spec.MemberType;
  4312. }
  4313. public FieldExpr (FieldBase fi, Location l)
  4314. : this (fi.Spec, l)
  4315. {
  4316. }
  4317. #region Properties
  4318. public override string Name {
  4319. get {
  4320. return spec.Name;
  4321. }
  4322. }
  4323. public bool IsHoisted {
  4324. get {
  4325. IVariableReference hv = InstanceExpression as IVariableReference;
  4326. return hv != null && hv.IsHoisted;
  4327. }
  4328. }
  4329. public override bool IsInstance {
  4330. get {
  4331. return !spec.IsStatic;
  4332. }
  4333. }
  4334. public override bool IsStatic {
  4335. get {
  4336. return spec.IsStatic;
  4337. }
  4338. }
  4339. public override string KindName {
  4340. get { return "field"; }
  4341. }
  4342. public FieldSpec Spec {
  4343. get {
  4344. return spec;
  4345. }
  4346. }
  4347. protected override TypeSpec DeclaringType {
  4348. get {
  4349. return spec.DeclaringType;
  4350. }
  4351. }
  4352. public VariableInfo VariableInfo {
  4353. get {
  4354. return variable_info;
  4355. }
  4356. }
  4357. #endregion
  4358. public override string GetSignatureForError ()
  4359. {
  4360. return spec.GetSignatureForError ();
  4361. }
  4362. public bool IsMarshalByRefAccess (ResolveContext rc)
  4363. {
  4364. // Checks possible ldflda of field access expression
  4365. return !spec.IsStatic && TypeSpec.IsValueType (spec.MemberType) && !(InstanceExpression is This) &&
  4366. rc.Module.PredefinedTypes.MarshalByRefObject.Define () &&
  4367. TypeSpec.IsBaseClass (spec.DeclaringType, rc.Module.PredefinedTypes.MarshalByRefObject.TypeSpec, false);
  4368. }
  4369. public void SetHasAddressTaken ()
  4370. {
  4371. IVariableReference vr = InstanceExpression as IVariableReference;
  4372. if (vr != null) {
  4373. vr.SetHasAddressTaken ();
  4374. }
  4375. }
  4376. public override Expression CreateExpressionTree (ResolveContext ec)
  4377. {
  4378. Expression instance;
  4379. if (InstanceExpression == null) {
  4380. instance = new NullLiteral (loc);
  4381. } else {
  4382. instance = InstanceExpression.CreateExpressionTree (ec);
  4383. }
  4384. Arguments args = Arguments.CreateForExpressionTree (ec, null,
  4385. instance,
  4386. CreateTypeOfExpression ());
  4387. return CreateExpressionFactoryCall (ec, "Field", args);
  4388. }
  4389. public Expression CreateTypeOfExpression ()
  4390. {
  4391. return new TypeOfField (spec, loc);
  4392. }
  4393. protected override Expression DoResolve (ResolveContext ec)
  4394. {
  4395. return DoResolve (ec, null);
  4396. }
  4397. Expression DoResolve (ResolveContext ec, Expression rhs)
  4398. {
  4399. bool lvalue_instance = rhs != null && IsInstance && spec.DeclaringType.IsStruct;
  4400. if (rhs != this) {
  4401. if (ResolveInstanceExpression (ec, rhs)) {
  4402. // Resolve the field's instance expression while flow analysis is turned
  4403. // off: when accessing a field "a.b", we must check whether the field
  4404. // "a.b" is initialized, not whether the whole struct "a" is initialized.
  4405. if (lvalue_instance) {
  4406. using (ec.With (ResolveContext.Options.DoFlowAnalysis, false)) {
  4407. bool out_access = rhs == EmptyExpression.OutAccess || rhs == EmptyExpression.LValueMemberOutAccess;
  4408. Expression right_side =
  4409. out_access ? EmptyExpression.LValueMemberOutAccess : EmptyExpression.LValueMemberAccess;
  4410. InstanceExpression = InstanceExpression.ResolveLValue (ec, right_side);
  4411. }
  4412. } else {
  4413. using (ec.With (ResolveContext.Options.DoFlowAnalysis, false)) {
  4414. InstanceExpression = InstanceExpression.Resolve (ec, ResolveFlags.VariableOrValue);
  4415. }
  4416. }
  4417. if (InstanceExpression == null)
  4418. return null;
  4419. }
  4420. DoBestMemberChecks (ec, spec);
  4421. }
  4422. var fb = spec as FixedFieldSpec;
  4423. IVariableReference var = InstanceExpression as IVariableReference;
  4424. if (lvalue_instance && var != null && var.VariableInfo != null) {
  4425. var.VariableInfo.SetStructFieldAssigned (ec, Name);
  4426. }
  4427. if (fb != null) {
  4428. IFixedExpression fe = InstanceExpression as IFixedExpression;
  4429. if (!ec.HasSet (ResolveContext.Options.FixedInitializerScope) && (fe == null || !fe.IsFixed)) {
  4430. ec.Report.Error (1666, loc, "You cannot use fixed size buffers contained in unfixed expressions. Try using the fixed statement");
  4431. }
  4432. if (InstanceExpression.eclass != ExprClass.Variable) {
  4433. ec.Report.SymbolRelatedToPreviousError (spec);
  4434. ec.Report.Error (1708, loc, "`{0}': Fixed size buffers can only be accessed through locals or fields",
  4435. TypeManager.GetFullNameSignature (spec));
  4436. } else if (var != null && var.IsHoisted) {
  4437. AnonymousMethodExpression.Error_AddressOfCapturedVar (ec, var, loc);
  4438. }
  4439. return new FixedBufferPtr (this, fb.ElementType, loc).Resolve (ec);
  4440. }
  4441. //
  4442. // Set flow-analysis variable info for struct member access. It will be check later
  4443. // for precise error reporting
  4444. //
  4445. if (var != null && var.VariableInfo != null && InstanceExpression.Type.IsStruct) {
  4446. variable_info = var.VariableInfo.GetStructFieldInfo (Name);
  4447. if (rhs != null && variable_info != null)
  4448. variable_info.SetStructFieldAssigned (ec, Name);
  4449. }
  4450. eclass = ExprClass.Variable;
  4451. return this;
  4452. }
  4453. public void VerifyAssignedStructField (ResolveContext rc, Expression rhs)
  4454. {
  4455. var fe = this;
  4456. do {
  4457. var var = fe.InstanceExpression as IVariableReference;
  4458. if (var != null) {
  4459. var vi = var.VariableInfo;
  4460. if (vi != null && !vi.IsStructFieldAssigned (rc, fe.Name) && (rhs == null || !fe.type.IsStruct)) {
  4461. if (rhs != null) {
  4462. rc.Report.Warning (1060, 1, fe.loc, "Use of possibly unassigned field `{0}'", fe.Name);
  4463. } else {
  4464. rc.Report.Error (170, fe.loc, "Use of possibly unassigned field `{0}'", fe.Name);
  4465. }
  4466. return;
  4467. }
  4468. }
  4469. fe = fe.InstanceExpression as FieldExpr;
  4470. } while (fe != null);
  4471. }
  4472. static readonly int [] codes = {
  4473. 191, // instance, write access
  4474. 192, // instance, out access
  4475. 198, // static, write access
  4476. 199, // static, out access
  4477. 1648, // member of value instance, write access
  4478. 1649, // member of value instance, out access
  4479. 1650, // member of value static, write access
  4480. 1651 // member of value static, out access
  4481. };
  4482. static readonly string [] msgs = {
  4483. /*0191*/ "A readonly field `{0}' cannot be assigned to (except in a constructor or a variable initializer)",
  4484. /*0192*/ "A readonly field `{0}' cannot be passed ref or out (except in a constructor)",
  4485. /*0198*/ "A static readonly field `{0}' cannot be assigned to (except in a static constructor or a variable initializer)",
  4486. /*0199*/ "A static readonly field `{0}' cannot be passed ref or out (except in a static constructor)",
  4487. /*1648*/ "Members of readonly field `{0}' cannot be modified (except in a constructor or a variable initializer)",
  4488. /*1649*/ "Members of readonly field `{0}' cannot be passed ref or out (except in a constructor)",
  4489. /*1650*/ "Fields of static readonly field `{0}' cannot be assigned to (except in a static constructor or a variable initializer)",
  4490. /*1651*/ "Fields of static readonly field `{0}' cannot be passed ref or out (except in a static constructor)"
  4491. };
  4492. // The return value is always null. Returning a value simplifies calling code.
  4493. Expression Report_AssignToReadonly (ResolveContext ec, Expression right_side)
  4494. {
  4495. int i = 0;
  4496. if (right_side == EmptyExpression.OutAccess || right_side == EmptyExpression.LValueMemberOutAccess)
  4497. i += 1;
  4498. if (IsStatic)
  4499. i += 2;
  4500. if (right_side == EmptyExpression.LValueMemberAccess || right_side == EmptyExpression.LValueMemberOutAccess)
  4501. i += 4;
  4502. ec.Report.Error (codes [i], loc, msgs [i], GetSignatureForError ());
  4503. return null;
  4504. }
  4505. override public Expression DoResolveLValue (ResolveContext ec, Expression right_side)
  4506. {
  4507. Expression e = DoResolve (ec, right_side);
  4508. if (e == null)
  4509. return null;
  4510. spec.MemberDefinition.SetIsAssigned ();
  4511. if ((right_side == EmptyExpression.UnaryAddress || right_side == EmptyExpression.OutAccess) &&
  4512. (spec.Modifiers & Modifiers.VOLATILE) != 0) {
  4513. ec.Report.Warning (420, 1, loc,
  4514. "`{0}': A volatile field references will not be treated as volatile",
  4515. spec.GetSignatureForError ());
  4516. }
  4517. if (spec.IsReadOnly) {
  4518. // InitOnly fields can only be assigned in constructors or initializers
  4519. if (!ec.HasAny (ResolveContext.Options.FieldInitializerScope | ResolveContext.Options.ConstructorScope))
  4520. return Report_AssignToReadonly (ec, right_side);
  4521. if (ec.HasSet (ResolveContext.Options.ConstructorScope)) {
  4522. // InitOnly fields cannot be assigned-to in a different constructor from their declaring type
  4523. if (ec.CurrentMemberDefinition.Parent.PartialContainer.Definition != spec.DeclaringType.GetDefinition ())
  4524. return Report_AssignToReadonly (ec, right_side);
  4525. // static InitOnly fields cannot be assigned-to in an instance constructor
  4526. if (IsStatic && !ec.IsStatic)
  4527. return Report_AssignToReadonly (ec, right_side);
  4528. // instance constructors can't modify InitOnly fields of other instances of the same type
  4529. if (!IsStatic && !(InstanceExpression is This))
  4530. return Report_AssignToReadonly (ec, right_side);
  4531. }
  4532. }
  4533. if (right_side == EmptyExpression.OutAccess && IsMarshalByRefAccess (ec)) {
  4534. ec.Report.SymbolRelatedToPreviousError (spec.DeclaringType);
  4535. ec.Report.Warning (197, 1, loc,
  4536. "Passing `{0}' as ref or out or taking its address may cause a runtime exception because it is a field of a marshal-by-reference class",
  4537. GetSignatureForError ());
  4538. }
  4539. eclass = ExprClass.Variable;
  4540. return this;
  4541. }
  4542. public override int GetHashCode ()
  4543. {
  4544. return spec.GetHashCode ();
  4545. }
  4546. public bool IsFixed {
  4547. get {
  4548. //
  4549. // A variable of the form V.I is fixed when V is a fixed variable of a struct type
  4550. //
  4551. IVariableReference variable = InstanceExpression as IVariableReference;
  4552. if (variable != null)
  4553. return InstanceExpression.Type.IsStruct && variable.IsFixed;
  4554. IFixedExpression fe = InstanceExpression as IFixedExpression;
  4555. return fe != null && fe.IsFixed;
  4556. }
  4557. }
  4558. public override bool Equals (object obj)
  4559. {
  4560. FieldExpr fe = obj as FieldExpr;
  4561. if (fe == null)
  4562. return false;
  4563. if (spec != fe.spec)
  4564. return false;
  4565. if (InstanceExpression == null || fe.InstanceExpression == null)
  4566. return true;
  4567. return InstanceExpression.Equals (fe.InstanceExpression);
  4568. }
  4569. public void Emit (EmitContext ec, bool leave_copy)
  4570. {
  4571. bool is_volatile = (spec.Modifiers & Modifiers.VOLATILE) != 0;
  4572. spec.MemberDefinition.SetIsUsed ();
  4573. if (IsStatic){
  4574. if (is_volatile)
  4575. ec.Emit (OpCodes.Volatile);
  4576. ec.Emit (OpCodes.Ldsfld, spec);
  4577. } else {
  4578. if (!prepared)
  4579. EmitInstance (ec, false);
  4580. // Optimization for build-in types
  4581. if (type.IsStruct && type == ec.CurrentType && InstanceExpression.Type == type) {
  4582. ec.EmitLoadFromPtr (type);
  4583. } else {
  4584. var ff = spec as FixedFieldSpec;
  4585. if (ff != null) {
  4586. ec.Emit (OpCodes.Ldflda, spec);
  4587. ec.Emit (OpCodes.Ldflda, ff.Element);
  4588. } else {
  4589. if (is_volatile)
  4590. ec.Emit (OpCodes.Volatile);
  4591. ec.Emit (OpCodes.Ldfld, spec);
  4592. }
  4593. }
  4594. }
  4595. if (leave_copy) {
  4596. ec.Emit (OpCodes.Dup);
  4597. if (!IsStatic) {
  4598. temp = new LocalTemporary (this.Type);
  4599. temp.Store (ec);
  4600. }
  4601. }
  4602. }
  4603. public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound)
  4604. {
  4605. bool has_await_source = ec.HasSet (BuilderContext.Options.AsyncBody) && source.ContainsEmitWithAwait ();
  4606. if (isCompound && !(source is DynamicExpressionStatement)) {
  4607. if (has_await_source) {
  4608. if (IsInstance)
  4609. InstanceExpression = InstanceExpression.EmitToField (ec);
  4610. } else {
  4611. prepared = true;
  4612. }
  4613. }
  4614. if (IsInstance) {
  4615. if (has_await_source)
  4616. source = source.EmitToField (ec);
  4617. EmitInstance (ec, prepared);
  4618. }
  4619. source.Emit (ec);
  4620. if (leave_copy) {
  4621. ec.Emit (OpCodes.Dup);
  4622. if (!IsStatic) {
  4623. temp = new LocalTemporary (this.Type);
  4624. temp.Store (ec);
  4625. }
  4626. }
  4627. if ((spec.Modifiers & Modifiers.VOLATILE) != 0)
  4628. ec.Emit (OpCodes.Volatile);
  4629. spec.MemberDefinition.SetIsAssigned ();
  4630. if (IsStatic)
  4631. ec.Emit (OpCodes.Stsfld, spec);
  4632. else
  4633. ec.Emit (OpCodes.Stfld, spec);
  4634. if (temp != null) {
  4635. temp.Emit (ec);
  4636. temp.Release (ec);
  4637. temp = null;
  4638. }
  4639. }
  4640. //
  4641. // Emits store to field with prepared values on stack
  4642. //
  4643. public void EmitAssignFromStack (EmitContext ec)
  4644. {
  4645. if (IsStatic) {
  4646. ec.Emit (OpCodes.Stsfld, spec);
  4647. } else {
  4648. ec.Emit (OpCodes.Stfld, spec);
  4649. }
  4650. }
  4651. public override void Emit (EmitContext ec)
  4652. {
  4653. Emit (ec, false);
  4654. }
  4655. public override void EmitSideEffect (EmitContext ec)
  4656. {
  4657. bool is_volatile = (spec.Modifiers & Modifiers.VOLATILE) != 0;
  4658. if (is_volatile) // || is_marshal_by_ref ())
  4659. base.EmitSideEffect (ec);
  4660. }
  4661. public virtual void AddressOf (EmitContext ec, AddressOp mode)
  4662. {
  4663. if ((mode & AddressOp.Store) != 0)
  4664. spec.MemberDefinition.SetIsAssigned ();
  4665. if ((mode & AddressOp.Load) != 0)
  4666. spec.MemberDefinition.SetIsUsed ();
  4667. //
  4668. // Handle initonly fields specially: make a copy and then
  4669. // get the address of the copy.
  4670. //
  4671. bool need_copy;
  4672. if (spec.IsReadOnly){
  4673. need_copy = true;
  4674. if (ec.HasSet (EmitContext.Options.ConstructorScope) && spec.DeclaringType == ec.CurrentType) {
  4675. if (IsStatic){
  4676. if (ec.IsStatic)
  4677. need_copy = false;
  4678. } else
  4679. need_copy = false;
  4680. }
  4681. } else
  4682. need_copy = false;
  4683. if (need_copy) {
  4684. Emit (ec);
  4685. var temp = ec.GetTemporaryLocal (type);
  4686. ec.Emit (OpCodes.Stloc, temp);
  4687. ec.Emit (OpCodes.Ldloca, temp);
  4688. ec.FreeTemporaryLocal (temp, type);
  4689. return;
  4690. }
  4691. if (IsStatic){
  4692. ec.Emit (OpCodes.Ldsflda, spec);
  4693. } else {
  4694. if (!prepared)
  4695. EmitInstance (ec, false);
  4696. ec.Emit (OpCodes.Ldflda, spec);
  4697. }
  4698. }
  4699. public SLE.Expression MakeAssignExpression (BuilderContext ctx, Expression source)
  4700. {
  4701. return MakeExpression (ctx);
  4702. }
  4703. public override SLE.Expression MakeExpression (BuilderContext ctx)
  4704. {
  4705. #if STATIC
  4706. return base.MakeExpression (ctx);
  4707. #else
  4708. return SLE.Expression.Field (
  4709. IsStatic ? null : InstanceExpression.MakeExpression (ctx),
  4710. spec.GetMetaInfo ());
  4711. #endif
  4712. }
  4713. public override void SetTypeArguments (ResolveContext ec, TypeArguments ta)
  4714. {
  4715. Error_TypeArgumentsCannotBeUsed (ec, "field", GetSignatureForError (), loc);
  4716. }
  4717. }
  4718. //
  4719. // Expression that evaluates to a Property.
  4720. //
  4721. // This is not an LValue because we need to re-write the expression. We
  4722. // can not take data from the stack and store it.
  4723. //
  4724. sealed class PropertyExpr : PropertyOrIndexerExpr<PropertySpec>
  4725. {
  4726. public PropertyExpr (PropertySpec spec, Location l)
  4727. : base (l)
  4728. {
  4729. best_candidate = spec;
  4730. type = spec.MemberType;
  4731. }
  4732. #region Properties
  4733. protected override Arguments Arguments {
  4734. get {
  4735. return null;
  4736. }
  4737. set {
  4738. }
  4739. }
  4740. protected override TypeSpec DeclaringType {
  4741. get {
  4742. return best_candidate.DeclaringType;
  4743. }
  4744. }
  4745. public override string Name {
  4746. get {
  4747. return best_candidate.Name;
  4748. }
  4749. }
  4750. public override bool IsInstance {
  4751. get {
  4752. return !IsStatic;
  4753. }
  4754. }
  4755. public override bool IsStatic {
  4756. get {
  4757. return best_candidate.IsStatic;
  4758. }
  4759. }
  4760. public override string KindName {
  4761. get { return "property"; }
  4762. }
  4763. public PropertySpec PropertyInfo {
  4764. get {
  4765. return best_candidate;
  4766. }
  4767. }
  4768. #endregion
  4769. public static PropertyExpr CreatePredefined (PropertySpec spec, Location loc)
  4770. {
  4771. return new PropertyExpr (spec, loc) {
  4772. Getter = spec.Get,
  4773. Setter = spec.Set
  4774. };
  4775. }
  4776. public override Expression CreateExpressionTree (ResolveContext ec)
  4777. {
  4778. Arguments args;
  4779. if (IsSingleDimensionalArrayLength ()) {
  4780. args = new Arguments (1);
  4781. args.Add (new Argument (InstanceExpression.CreateExpressionTree (ec)));
  4782. return CreateExpressionFactoryCall (ec, "ArrayLength", args);
  4783. }
  4784. args = new Arguments (2);
  4785. if (InstanceExpression == null)
  4786. args.Add (new Argument (new NullLiteral (loc)));
  4787. else
  4788. args.Add (new Argument (InstanceExpression.CreateExpressionTree (ec)));
  4789. args.Add (new Argument (new TypeOfMethod (Getter, loc)));
  4790. return CreateExpressionFactoryCall (ec, "Property", args);
  4791. }
  4792. public Expression CreateSetterTypeOfExpression (ResolveContext rc)
  4793. {
  4794. DoResolveLValue (rc, null);
  4795. return new TypeOfMethod (Setter, loc);
  4796. }
  4797. public override string GetSignatureForError ()
  4798. {
  4799. return best_candidate.GetSignatureForError ();
  4800. }
  4801. public override SLE.Expression MakeAssignExpression (BuilderContext ctx, Expression source)
  4802. {
  4803. #if STATIC
  4804. return base.MakeExpression (ctx);
  4805. #else
  4806. return SLE.Expression.Property (InstanceExpression.MakeExpression (ctx), (MethodInfo) Setter.GetMetaInfo ());
  4807. #endif
  4808. }
  4809. public override SLE.Expression MakeExpression (BuilderContext ctx)
  4810. {
  4811. #if STATIC
  4812. return base.MakeExpression (ctx);
  4813. #else
  4814. return SLE.Expression.Property (InstanceExpression.MakeExpression (ctx), (MethodInfo) Getter.GetMetaInfo ());
  4815. #endif
  4816. }
  4817. void Error_PropertyNotValid (ResolveContext ec)
  4818. {
  4819. ec.Report.SymbolRelatedToPreviousError (best_candidate);
  4820. ec.Report.Error (1546, loc, "Property or event `{0}' is not supported by the C# language",
  4821. GetSignatureForError ());
  4822. }
  4823. bool IsSingleDimensionalArrayLength ()
  4824. {
  4825. if (best_candidate.DeclaringType.BuiltinType != BuiltinTypeSpec.Type.Array || !best_candidate.HasGet || Name != "Length")
  4826. return false;
  4827. ArrayContainer ac = InstanceExpression.Type as ArrayContainer;
  4828. return ac != null && ac.Rank == 1;
  4829. }
  4830. public override void Emit (EmitContext ec, bool leave_copy)
  4831. {
  4832. //
  4833. // Special case: length of single dimension array property is turned into ldlen
  4834. //
  4835. if (IsSingleDimensionalArrayLength ()) {
  4836. EmitInstance (ec, false);
  4837. ec.Emit (OpCodes.Ldlen);
  4838. ec.Emit (OpCodes.Conv_I4);
  4839. return;
  4840. }
  4841. base.Emit (ec, leave_copy);
  4842. }
  4843. public override void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound)
  4844. {
  4845. Arguments args;
  4846. LocalTemporary await_source_arg = null;
  4847. if (isCompound && !(source is DynamicExpressionStatement)) {
  4848. emitting_compound_assignment = true;
  4849. source.Emit (ec);
  4850. if (has_await_arguments) {
  4851. await_source_arg = new LocalTemporary (Type);
  4852. await_source_arg.Store (ec);
  4853. args = new Arguments (1);
  4854. args.Add (new Argument (await_source_arg));
  4855. if (leave_copy) {
  4856. temp = await_source_arg;
  4857. }
  4858. has_await_arguments = false;
  4859. } else {
  4860. args = null;
  4861. if (leave_copy) {
  4862. ec.Emit (OpCodes.Dup);
  4863. temp = new LocalTemporary (this.Type);
  4864. temp.Store (ec);
  4865. }
  4866. }
  4867. } else {
  4868. args = new Arguments (1);
  4869. if (leave_copy) {
  4870. source.Emit (ec);
  4871. temp = new LocalTemporary (this.Type);
  4872. temp.Store (ec);
  4873. args.Add (new Argument (temp));
  4874. } else {
  4875. args.Add (new Argument (source));
  4876. }
  4877. }
  4878. emitting_compound_assignment = false;
  4879. var call = new CallEmitter ();
  4880. call.InstanceExpression = InstanceExpression;
  4881. if (args == null)
  4882. call.InstanceExpressionOnStack = true;
  4883. call.Emit (ec, Setter, args, loc);
  4884. if (temp != null) {
  4885. temp.Emit (ec);
  4886. temp.Release (ec);
  4887. }
  4888. if (await_source_arg != null) {
  4889. await_source_arg.Release (ec);
  4890. }
  4891. }
  4892. protected override Expression OverloadResolve (ResolveContext rc, Expression right_side)
  4893. {
  4894. eclass = ExprClass.PropertyAccess;
  4895. if (best_candidate.IsNotCSharpCompatible) {
  4896. Error_PropertyNotValid (rc);
  4897. }
  4898. ResolveInstanceExpression (rc, right_side);
  4899. if ((best_candidate.Modifiers & (Modifiers.ABSTRACT | Modifiers.VIRTUAL)) != 0 && best_candidate.DeclaringType != InstanceExpression.Type) {
  4900. var filter = new MemberFilter (best_candidate.Name, 0, MemberKind.Property, null, null);
  4901. var p = MemberCache.FindMember (InstanceExpression.Type, filter, BindingRestriction.InstanceOnly | BindingRestriction.OverrideOnly) as PropertySpec;
  4902. if (p != null) {
  4903. type = p.MemberType;
  4904. }
  4905. }
  4906. DoBestMemberChecks (rc, best_candidate);
  4907. return this;
  4908. }
  4909. public override void SetTypeArguments (ResolveContext ec, TypeArguments ta)
  4910. {
  4911. Error_TypeArgumentsCannotBeUsed (ec, "property", GetSignatureForError (), loc);
  4912. }
  4913. }
  4914. abstract class PropertyOrIndexerExpr<T> : MemberExpr, IDynamicAssign where T : PropertySpec
  4915. {
  4916. // getter and setter can be different for base calls
  4917. MethodSpec getter, setter;
  4918. protected T best_candidate;
  4919. protected LocalTemporary temp;
  4920. protected bool emitting_compound_assignment;
  4921. protected bool has_await_arguments;
  4922. protected PropertyOrIndexerExpr (Location l)
  4923. {
  4924. loc = l;
  4925. }
  4926. #region Properties
  4927. protected abstract Arguments Arguments { get; set; }
  4928. public MethodSpec Getter {
  4929. get {
  4930. return getter;
  4931. }
  4932. set {
  4933. getter = value;
  4934. }
  4935. }
  4936. public MethodSpec Setter {
  4937. get {
  4938. return setter;
  4939. }
  4940. set {
  4941. setter = value;
  4942. }
  4943. }
  4944. #endregion
  4945. protected override Expression DoResolve (ResolveContext ec)
  4946. {
  4947. if (eclass == ExprClass.Unresolved) {
  4948. var expr = OverloadResolve (ec, null);
  4949. if (expr == null)
  4950. return null;
  4951. if (expr != this)
  4952. return expr.Resolve (ec);
  4953. }
  4954. if (!ResolveGetter (ec))
  4955. return null;
  4956. return this;
  4957. }
  4958. public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
  4959. {
  4960. if (right_side == EmptyExpression.OutAccess) {
  4961. // TODO: best_candidate can be null at this point
  4962. INamedBlockVariable variable = null;
  4963. if (best_candidate != null && ec.CurrentBlock.ParametersBlock.TopBlock.GetLocalName (best_candidate.Name, ec.CurrentBlock, ref variable) && variable is Linq.RangeVariable) {
  4964. ec.Report.Error (1939, loc, "A range variable `{0}' may not be passes as `ref' or `out' parameter",
  4965. best_candidate.Name);
  4966. } else {
  4967. right_side.DoResolveLValue (ec, this);
  4968. }
  4969. return null;
  4970. }
  4971. // if the property/indexer returns a value type, and we try to set a field in it
  4972. if (right_side == EmptyExpression.LValueMemberAccess || right_side == EmptyExpression.LValueMemberOutAccess) {
  4973. Error_ValueAssignment (ec, right_side);
  4974. }
  4975. if (eclass == ExprClass.Unresolved) {
  4976. var expr = OverloadResolve (ec, right_side);
  4977. if (expr == null)
  4978. return null;
  4979. if (expr != this)
  4980. return expr.ResolveLValue (ec, right_side);
  4981. }
  4982. if (!ResolveSetter (ec))
  4983. return null;
  4984. return this;
  4985. }
  4986. //
  4987. // Implements the IAssignMethod interface for assignments
  4988. //
  4989. public virtual void Emit (EmitContext ec, bool leave_copy)
  4990. {
  4991. var call = new CallEmitter ();
  4992. call.InstanceExpression = InstanceExpression;
  4993. if (has_await_arguments)
  4994. call.HasAwaitArguments = true;
  4995. else
  4996. call.DuplicateArguments = emitting_compound_assignment;
  4997. call.Emit (ec, Getter, Arguments, loc);
  4998. if (call.HasAwaitArguments) {
  4999. InstanceExpression = call.InstanceExpression;
  5000. Arguments = call.EmittedArguments;
  5001. has_await_arguments = true;
  5002. }
  5003. if (leave_copy) {
  5004. ec.Emit (OpCodes.Dup);
  5005. temp = new LocalTemporary (Type);
  5006. temp.Store (ec);
  5007. }
  5008. }
  5009. public abstract void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound);
  5010. public override void Emit (EmitContext ec)
  5011. {
  5012. Emit (ec, false);
  5013. }
  5014. protected override FieldExpr EmitToFieldSource (EmitContext ec)
  5015. {
  5016. has_await_arguments = true;
  5017. Emit (ec, false);
  5018. return null;
  5019. }
  5020. public abstract SLE.Expression MakeAssignExpression (BuilderContext ctx, Expression source);
  5021. protected abstract Expression OverloadResolve (ResolveContext rc, Expression right_side);
  5022. bool ResolveGetter (ResolveContext rc)
  5023. {
  5024. if (!best_candidate.HasGet) {
  5025. if (InstanceExpression != EmptyExpression.Null) {
  5026. rc.Report.SymbolRelatedToPreviousError (best_candidate);
  5027. rc.Report.Error (154, loc, "The property or indexer `{0}' cannot be used in this context because it lacks the `get' accessor",
  5028. best_candidate.GetSignatureForError ());
  5029. return false;
  5030. }
  5031. } else if (!best_candidate.Get.IsAccessible (rc)) {
  5032. if (best_candidate.HasDifferentAccessibility) {
  5033. rc.Report.SymbolRelatedToPreviousError (best_candidate.Get);
  5034. rc.Report.Error (271, loc, "The property or indexer `{0}' cannot be used in this context because the get accessor is inaccessible",
  5035. TypeManager.CSharpSignature (best_candidate));
  5036. } else {
  5037. rc.Report.SymbolRelatedToPreviousError (best_candidate.Get);
  5038. ErrorIsInaccesible (rc, best_candidate.Get.GetSignatureForError (), loc);
  5039. }
  5040. }
  5041. if (best_candidate.HasDifferentAccessibility) {
  5042. CheckProtectedMemberAccess (rc, best_candidate.Get);
  5043. }
  5044. getter = CandidateToBaseOverride (rc, best_candidate.Get);
  5045. return true;
  5046. }
  5047. bool ResolveSetter (ResolveContext rc)
  5048. {
  5049. if (!best_candidate.HasSet) {
  5050. rc.Report.Error (200, loc, "Property or indexer `{0}' cannot be assigned to (it is read-only)",
  5051. GetSignatureForError ());
  5052. return false;
  5053. }
  5054. if (!best_candidate.Set.IsAccessible (rc)) {
  5055. if (best_candidate.HasDifferentAccessibility) {
  5056. rc.Report.SymbolRelatedToPreviousError (best_candidate.Set);
  5057. rc.Report.Error (272, loc, "The property or indexer `{0}' cannot be used in this context because the set accessor is inaccessible",
  5058. GetSignatureForError ());
  5059. } else {
  5060. rc.Report.SymbolRelatedToPreviousError (best_candidate.Set);
  5061. ErrorIsInaccesible (rc, best_candidate.Set.GetSignatureForError (), loc);
  5062. }
  5063. }
  5064. if (best_candidate.HasDifferentAccessibility)
  5065. CheckProtectedMemberAccess (rc, best_candidate.Set);
  5066. setter = CandidateToBaseOverride (rc, best_candidate.Set);
  5067. return true;
  5068. }
  5069. }
  5070. /// <summary>
  5071. /// Fully resolved expression that evaluates to an Event
  5072. /// </summary>
  5073. public class EventExpr : MemberExpr, IAssignMethod
  5074. {
  5075. readonly EventSpec spec;
  5076. MethodSpec op;
  5077. public EventExpr (EventSpec spec, Location loc)
  5078. {
  5079. this.spec = spec;
  5080. this.loc = loc;
  5081. }
  5082. #region Properties
  5083. protected override TypeSpec DeclaringType {
  5084. get {
  5085. return spec.DeclaringType;
  5086. }
  5087. }
  5088. public override string Name {
  5089. get {
  5090. return spec.Name;
  5091. }
  5092. }
  5093. public override bool IsInstance {
  5094. get {
  5095. return !spec.IsStatic;
  5096. }
  5097. }
  5098. public override bool IsStatic {
  5099. get {
  5100. return spec.IsStatic;
  5101. }
  5102. }
  5103. public override string KindName {
  5104. get { return "event"; }
  5105. }
  5106. public MethodSpec Operator {
  5107. get {
  5108. return op;
  5109. }
  5110. }
  5111. #endregion
  5112. public override MemberExpr ResolveMemberAccess (ResolveContext ec, Expression left, SimpleName original)
  5113. {
  5114. //
  5115. // If the event is local to this class and we are not lhs of +=/-= we transform ourselves into a FieldExpr
  5116. //
  5117. if (!ec.HasSet (ResolveContext.Options.CompoundAssignmentScope)) {
  5118. if (spec.BackingField != null &&
  5119. (spec.DeclaringType == ec.CurrentType || TypeManager.IsNestedChildOf (ec.CurrentType, spec.DeclaringType.MemberDefinition))) {
  5120. spec.MemberDefinition.SetIsUsed ();
  5121. if (!ec.IsObsolete) {
  5122. ObsoleteAttribute oa = spec.GetAttributeObsolete ();
  5123. if (oa != null)
  5124. AttributeTester.Report_ObsoleteMessage (oa, spec.GetSignatureForError (), loc, ec.Report);
  5125. }
  5126. if ((spec.Modifiers & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
  5127. Error_AssignmentEventOnly (ec);
  5128. FieldExpr ml = new FieldExpr (spec.BackingField, loc);
  5129. InstanceExpression = null;
  5130. return ml.ResolveMemberAccess (ec, left, original);
  5131. }
  5132. }
  5133. return base.ResolveMemberAccess (ec, left, original);
  5134. }
  5135. public override Expression CreateExpressionTree (ResolveContext ec)
  5136. {
  5137. throw new NotSupportedException ("ET");
  5138. }
  5139. public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
  5140. {
  5141. if (right_side == EmptyExpression.EventAddition) {
  5142. op = spec.AccessorAdd;
  5143. } else if (right_side == EmptyExpression.EventSubtraction) {
  5144. op = spec.AccessorRemove;
  5145. }
  5146. if (op == null) {
  5147. Error_AssignmentEventOnly (ec);
  5148. return null;
  5149. }
  5150. op = CandidateToBaseOverride (ec, op);
  5151. return this;
  5152. }
  5153. protected override Expression DoResolve (ResolveContext ec)
  5154. {
  5155. eclass = ExprClass.EventAccess;
  5156. type = spec.MemberType;
  5157. ResolveInstanceExpression (ec, null);
  5158. if (!ec.HasSet (ResolveContext.Options.CompoundAssignmentScope)) {
  5159. Error_AssignmentEventOnly (ec);
  5160. }
  5161. DoBestMemberChecks (ec, spec);
  5162. return this;
  5163. }
  5164. public override void Emit (EmitContext ec)
  5165. {
  5166. throw new NotSupportedException ();
  5167. //Error_CannotAssign ();
  5168. }
  5169. #region IAssignMethod Members
  5170. public void Emit (EmitContext ec, bool leave_copy)
  5171. {
  5172. throw new NotImplementedException ();
  5173. }
  5174. public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound)
  5175. {
  5176. if (leave_copy || !isCompound)
  5177. throw new NotImplementedException ("EventExpr::EmitAssign");
  5178. Arguments args = new Arguments (1);
  5179. args.Add (new Argument (source));
  5180. var call = new CallEmitter ();
  5181. call.InstanceExpression = InstanceExpression;
  5182. call.Emit (ec, op, args, loc);
  5183. }
  5184. #endregion
  5185. void Error_AssignmentEventOnly (ResolveContext ec)
  5186. {
  5187. if (spec.DeclaringType == ec.CurrentType || TypeManager.IsNestedChildOf (ec.CurrentType, spec.DeclaringType.MemberDefinition)) {
  5188. ec.Report.Error (79, loc,
  5189. "The event `{0}' can only appear on the left hand side of `+=' or `-=' operator",
  5190. GetSignatureForError ());
  5191. } else {
  5192. ec.Report.Error (70, loc,
  5193. "The event `{0}' can only appear on the left hand side of += or -= when used outside of the type `{1}'",
  5194. GetSignatureForError (), spec.DeclaringType.GetSignatureForError ());
  5195. }
  5196. }
  5197. protected override void Error_CannotCallAbstractBase (ResolveContext rc, string name)
  5198. {
  5199. name = name.Substring (0, name.LastIndexOf ('.'));
  5200. base.Error_CannotCallAbstractBase (rc, name);
  5201. }
  5202. public override string GetSignatureForError ()
  5203. {
  5204. return TypeManager.CSharpSignature (spec);
  5205. }
  5206. public override void SetTypeArguments (ResolveContext ec, TypeArguments ta)
  5207. {
  5208. Error_TypeArgumentsCannotBeUsed (ec, "event", GetSignatureForError (), loc);
  5209. }
  5210. }
  5211. public class TemporaryVariableReference : VariableReference
  5212. {
  5213. public class Declarator : Statement
  5214. {
  5215. TemporaryVariableReference variable;
  5216. public Declarator (TemporaryVariableReference variable)
  5217. {
  5218. this.variable = variable;
  5219. loc = variable.loc;
  5220. }
  5221. protected override void DoEmit (EmitContext ec)
  5222. {
  5223. variable.li.CreateBuilder (ec);
  5224. }
  5225. public override void Emit (EmitContext ec)
  5226. {
  5227. // Don't create sequence point
  5228. DoEmit (ec);
  5229. }
  5230. protected override void CloneTo (CloneContext clonectx, Statement target)
  5231. {
  5232. // Nothing
  5233. }
  5234. }
  5235. LocalVariable li;
  5236. public TemporaryVariableReference (LocalVariable li, Location loc)
  5237. {
  5238. this.li = li;
  5239. this.type = li.Type;
  5240. this.loc = loc;
  5241. }
  5242. public override bool IsLockedByStatement {
  5243. get {
  5244. return false;
  5245. }
  5246. set {
  5247. }
  5248. }
  5249. public LocalVariable LocalInfo {
  5250. get {
  5251. return li;
  5252. }
  5253. }
  5254. public static TemporaryVariableReference Create (TypeSpec type, Block block, Location loc)
  5255. {
  5256. var li = LocalVariable.CreateCompilerGenerated (type, block, loc);
  5257. return new TemporaryVariableReference (li, loc);
  5258. }
  5259. protected override Expression DoResolve (ResolveContext ec)
  5260. {
  5261. eclass = ExprClass.Variable;
  5262. //
  5263. // Don't capture temporary variables except when using
  5264. // state machine redirection and block yields
  5265. //
  5266. if (ec.CurrentAnonymousMethod != null && ec.CurrentAnonymousMethod.IsIterator &&
  5267. ec.CurrentBlock.Explicit.HasYield && ec.IsVariableCapturingRequired) {
  5268. AnonymousMethodStorey storey = li.Block.Explicit.CreateAnonymousMethodStorey (ec);
  5269. storey.CaptureLocalVariable (ec, li);
  5270. }
  5271. return this;
  5272. }
  5273. public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
  5274. {
  5275. return Resolve (ec);
  5276. }
  5277. public override void Emit (EmitContext ec)
  5278. {
  5279. li.CreateBuilder (ec);
  5280. Emit (ec, false);
  5281. }
  5282. public void EmitAssign (EmitContext ec, Expression source)
  5283. {
  5284. li.CreateBuilder (ec);
  5285. EmitAssign (ec, source, false, false);
  5286. }
  5287. public override HoistedVariable GetHoistedVariable (AnonymousExpression ae)
  5288. {
  5289. return li.HoistedVariant;
  5290. }
  5291. public override bool IsFixed {
  5292. get { return true; }
  5293. }
  5294. public override bool IsRef {
  5295. get { return false; }
  5296. }
  5297. public override string Name {
  5298. get { throw new NotImplementedException (); }
  5299. }
  5300. public override void SetHasAddressTaken ()
  5301. {
  5302. throw new NotImplementedException ();
  5303. }
  5304. protected override ILocalVariable Variable {
  5305. get { return li; }
  5306. }
  5307. public override VariableInfo VariableInfo {
  5308. get { return null; }
  5309. }
  5310. public override void VerifyAssigned (ResolveContext rc)
  5311. {
  5312. }
  5313. }
  5314. ///
  5315. /// Handles `var' contextual keyword; var becomes a keyword only
  5316. /// if no type called var exists in a variable scope
  5317. ///
  5318. class VarExpr : SimpleName
  5319. {
  5320. public VarExpr (Location loc)
  5321. : base ("var", loc)
  5322. {
  5323. }
  5324. public bool InferType (ResolveContext ec, Expression right_side)
  5325. {
  5326. if (type != null)
  5327. throw new InternalErrorException ("An implicitly typed local variable could not be redefined");
  5328. type = right_side.Type;
  5329. if (type == InternalType.NullLiteral || type.Kind == MemberKind.Void || type == InternalType.AnonymousMethod || type == InternalType.MethodGroup) {
  5330. ec.Report.Error (815, loc,
  5331. "An implicitly typed local variable declaration cannot be initialized with `{0}'",
  5332. type.GetSignatureForError ());
  5333. return false;
  5334. }
  5335. eclass = ExprClass.Variable;
  5336. return true;
  5337. }
  5338. protected override void Error_TypeOrNamespaceNotFound (IMemberContext ec)
  5339. {
  5340. if (ec.Module.Compiler.Settings.Version < LanguageVersion.V_3)
  5341. base.Error_TypeOrNamespaceNotFound (ec);
  5342. else
  5343. ec.Module.Compiler.Report.Error (825, loc, "The contextual keyword `var' may only appear within a local variable declaration");
  5344. }
  5345. }
  5346. public class InvalidStatementExpression : Statement
  5347. {
  5348. public Expression Expression {
  5349. get;
  5350. private set;
  5351. }
  5352. public InvalidStatementExpression (Expression expr)
  5353. {
  5354. this.Expression = expr;
  5355. }
  5356. public override void Emit (EmitContext ec)
  5357. {
  5358. // nothing
  5359. }
  5360. protected override void DoEmit (EmitContext ec)
  5361. {
  5362. // nothing
  5363. }
  5364. protected override void CloneTo (CloneContext clonectx, Statement target)
  5365. {
  5366. // nothing
  5367. }
  5368. public override Mono.CSharp.Expression CreateExpressionTree (ResolveContext ec)
  5369. {
  5370. return null;
  5371. }
  5372. public override object Accept (Mono.CSharp.StructuralVisitor visitor)
  5373. {
  5374. return visitor.Visit (this);
  5375. }
  5376. }
  5377. }