PageRenderTime 56ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 1ms

/Dependencies/boo/src/Boo.Lang.Compiler/Steps/ProcessMethodBodies.cs

https://github.com/w4x/boolangstudio
C# | 6380 lines | 5479 code | 793 blank | 108 comment | 1044 complexity | 1604e4efa8f1fc1de7fa6f9b5ad7dd7d MD5 | raw file
Possible License(s): GPL-2.0
  1. #region license
  2. // Copyright (c) 2004, Rodrigo B. de Oliveira (rbo@acm.org)
  3. // All rights reserved.
  4. //
  5. // Redistribution and use in source and binary forms, with or without modification,
  6. // are permitted provided that the following conditions are met:
  7. //
  8. // * Redistributions of source code must retain the above copyright notice,
  9. // this list of conditions and the following disclaimer.
  10. // * Redistributions in binary form must reproduce the above copyright notice,
  11. // this list of conditions and the following disclaimer in the documentation
  12. // and/or other materials provided with the distribution.
  13. // * Neither the name of Rodrigo B. de Oliveira nor the names of its
  14. // contributors may be used to endorse or promote products derived from this
  15. // software without specific prior written permission.
  16. //
  17. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  18. // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  19. // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  20. // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
  21. // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  22. // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  23. // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  24. // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  25. // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  26. // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  27. #endregion
  28. using System;
  29. using System.Collections;
  30. using System.Collections.Generic;
  31. using System.Diagnostics;
  32. using System.IO;
  33. using System.Reflection;
  34. using System.Text;
  35. using Boo.Lang.Compiler.Ast;
  36. using Boo.Lang.Compiler.Ast.Visitors;
  37. using Boo.Lang.Compiler.TypeSystem;
  38. using Boo.Lang.Runtime;
  39. using Attribute = Boo.Lang.Compiler.Ast.Attribute;
  40. using Module=Boo.Lang.Compiler.Ast.Module;
  41. namespace Boo.Lang.Compiler.Steps
  42. {
  43. /// <summary>
  44. /// AST semantic evaluation.
  45. /// </summary>
  46. public class ProcessMethodBodies : AbstractNamespaceSensitiveVisitorCompilerStep
  47. {
  48. static readonly ExpressionCollection EmptyExpressionCollection = new ExpressionCollection();
  49. static readonly object OptionalReturnStatementAnnotation = new object();
  50. protected Stack _methodStack;
  51. protected Stack _memberStack;
  52. // for accurate error reporting during type inference
  53. protected Module _currentModule;
  54. protected InternalMethod _currentMethod;
  55. IMethod Array_EnumerableConstructor;
  56. IMethod Array_TypedEnumerableConstructor;
  57. IMethod Array_TypedCollectionConstructor;
  58. IMethod Array_TypedConstructor2;
  59. IMethod MultiDimensionalArray_TypedConstructor;
  60. protected CallableResolutionService _callableResolution;
  61. protected bool _optimizeNullComparisons = true;
  62. public ProcessMethodBodies()
  63. {
  64. }
  65. override public void Run()
  66. {
  67. NameResolutionService.Reset();
  68. _currentModule = null;
  69. _currentMethod = null;
  70. _methodStack = new Stack();
  71. _memberStack = new Stack();
  72. _callableResolution = new CallableResolutionService();
  73. _callableResolution.Initialize(_context);
  74. InitializeMemberCache();
  75. Visit(CompileUnit);
  76. }
  77. protected IMethod ResolveMethod(IType type, string name)
  78. {
  79. return NameResolutionService.ResolveMethod(type, name);
  80. }
  81. protected IProperty ResolveProperty(IType type, string name)
  82. {
  83. return NameResolutionService.ResolveProperty(type, name);
  84. }
  85. virtual protected void InitializeMemberCache()
  86. {
  87. Array_EnumerableConstructor = TypeSystemServices.Map(Types.Builtins.GetMethod("array", new Type[] { Types.IEnumerable }));
  88. Array_TypedEnumerableConstructor = TypeSystemServices.Map(Types.Builtins.GetMethod("array", new Type[] { Types.Type, Types.IEnumerable }));
  89. Array_TypedCollectionConstructor= TypeSystemServices.Map(Types.Builtins.GetMethod("array", new Type[] { Types.Type, Types.ICollection }));
  90. Array_TypedConstructor2 = TypeSystemServices.Map(Types.Builtins.GetMethod("array", new Type[] { Types.Type, Types.Int }));
  91. MultiDimensionalArray_TypedConstructor = TypeSystemServices.Map(Types.Builtins.GetMethod("matrix", new Type[] { Types.Type, typeof(int[]) }));
  92. }
  93. override public void Dispose()
  94. {
  95. base.Dispose();
  96. if (null != _callableResolution)
  97. {
  98. _callableResolution.Dispose();
  99. _callableResolution = null;
  100. }
  101. _currentModule = null;
  102. _currentMethod = null;
  103. _methodStack = null;
  104. _memberStack = null;
  105. _RuntimeServices_Len = null;
  106. _RuntimeServices_Mid = null;
  107. _RuntimeServices_NormalizeStringIndex = null;
  108. _RuntimeServices_AddArrays = null;
  109. _RuntimeServices_GetRange1 = null;
  110. _RuntimeServices_GetRange2 = null;
  111. _RuntimeServices_GetMultiDimensionalRange1 = null;
  112. _RuntimeServices_SetMultiDimensionalRange1 = null;
  113. _RuntimeServices_GetEnumerable = null;
  114. _RuntimeServices_EqualityOperator = null;
  115. _Array_get_Length = null;
  116. _Array_GetLength = null;
  117. _String_get_Length = null;
  118. _String_Substring_Int = null;
  119. _ICollection_get_Count = null;
  120. _List_GetRange1 = null;
  121. _List_GetRange2 = null;
  122. _ICallable_Call = null;
  123. _Activator_CreateInstance = null;
  124. _Exception_StringConstructor = null;
  125. _TextReaderEnumerator_lines = null;
  126. }
  127. override public void OnModule(Module module)
  128. {
  129. if (WasVisited(module)) return;
  130. MarkVisited(module);
  131. _currentModule = module;
  132. EnterNamespace((INamespace)TypeSystemServices.GetEntity(module));
  133. Visit(module.Members);
  134. Visit(module.AssemblyAttributes);
  135. LeaveNamespace();
  136. }
  137. override public void OnInterfaceDefinition(InterfaceDefinition node)
  138. {
  139. if (WasVisited(node)) return;
  140. MarkVisited(node);
  141. VisitTypeDefinition(node);
  142. }
  143. private void VisitBaseTypes(TypeDefinition node)
  144. {
  145. foreach (TypeReference typeRef in node.BaseTypes)
  146. {
  147. EnsureRelatedNodeWasVisited(typeRef, typeRef.Entity);
  148. }
  149. }
  150. private void VisitTypeDefinition(TypeDefinition node)
  151. {
  152. INamespace ns = (INamespace)GetEntity(node);
  153. EnterNamespace(ns);
  154. VisitBaseTypes(node);
  155. Visit(node.Attributes);
  156. Visit(node.Members);
  157. LeaveNamespace();
  158. }
  159. override public void OnClassDefinition(ClassDefinition node)
  160. {
  161. if (WasVisited(node)) return;
  162. MarkVisited(node);
  163. VisitTypeDefinition(node);
  164. ProcessFieldInitializers(node);
  165. }
  166. void ProcessFieldInitializers(ClassDefinition node)
  167. {
  168. foreach (TypeMember member in node.Members)
  169. {
  170. if (NodeType.Field == member.NodeType)
  171. {
  172. ProcessFieldInitializer((Field) member);
  173. }
  174. }
  175. }
  176. override public void OnAttribute(Attribute node)
  177. {
  178. IType tag = node.Entity as IType;
  179. if (null != tag && !TypeSystemServices.IsError(tag))
  180. {
  181. Visit(node.Arguments);
  182. ResolveNamedArguments(tag, node.NamedArguments);
  183. IConstructor constructor = GetCorrectConstructor(node, tag, node.Arguments);
  184. if (null != constructor)
  185. {
  186. Bind(node, constructor);
  187. }
  188. }
  189. }
  190. override public void OnProperty(Property node)
  191. {
  192. if (WasVisited(node))
  193. {
  194. return;
  195. }
  196. MarkVisited(node);
  197. Method setter = node.Setter;
  198. Method getter = node.Getter;
  199. Visit(node.Attributes);
  200. Visit(node.Type);
  201. Visit(node.Parameters);
  202. ResolvePropertyOverride(node);
  203. if (null != getter)
  204. {
  205. if (null != node.Type)
  206. {
  207. getter.ReturnType = node.Type.CloneNode();
  208. }
  209. getter.Parameters.ExtendWithClones(node.Parameters);
  210. Visit(getter);
  211. }
  212. IType typeInfo = null;
  213. if (null != node.Type)
  214. {
  215. typeInfo = GetType(node.Type);
  216. }
  217. else
  218. {
  219. if (null != getter)
  220. {
  221. typeInfo = GetType(node.Getter.ReturnType);
  222. if (typeInfo == TypeSystemServices.VoidType)
  223. {
  224. typeInfo = TypeSystemServices.ObjectType;
  225. node.Getter.ReturnType = CodeBuilder.CreateTypeReference(getter.LexicalInfo, typeInfo);
  226. }
  227. }
  228. else
  229. {
  230. typeInfo = TypeSystemServices.ObjectType;
  231. }
  232. node.Type = CodeBuilder.CreateTypeReference(node.LexicalInfo, typeInfo);
  233. }
  234. if (null != setter)
  235. {
  236. ParameterDeclaration parameter = new ParameterDeclaration();
  237. parameter.Type = CodeBuilder.CreateTypeReference(typeInfo);
  238. parameter.Name = "value";
  239. parameter.Entity = new InternalParameter(parameter, node.Parameters.Count+CodeBuilder.GetFirstParameterIndex(setter));
  240. setter.Parameters.ExtendWithClones(node.Parameters);
  241. setter.Parameters.Add(parameter);
  242. setter.Name = "set_" + node.Name;
  243. Visit(setter);
  244. }
  245. }
  246. override public void OnField(Field node)
  247. {
  248. if (WasVisited(node)) return;
  249. MarkVisited(node);
  250. InternalField entity = (InternalField)GetEntity(node);
  251. Visit(node.Attributes);
  252. Visit(node.Type);
  253. if (null != node.Initializer)
  254. {
  255. IType type = (null != node.Type) ? GetType(node.Type) : null;
  256. if (null != type && TypeSystemServices.IsNullable(type))
  257. {
  258. BindNullableInitializer(node, node.Initializer, type);
  259. }
  260. if (entity.DeclaringType.IsValueType && !node.IsStatic)
  261. {
  262. Error(
  263. CompilerErrorFactory.ValueTypeFieldsCannotHaveInitializers(
  264. node.Initializer));
  265. }
  266. try
  267. {
  268. PushMember(node);
  269. PreProcessFieldInitializer(node);
  270. }
  271. finally
  272. {
  273. PopMember();
  274. }
  275. }
  276. else
  277. {
  278. if (null == node.Type)
  279. {
  280. node.Type = CreateTypeReference(node.LexicalInfo, TypeSystemServices.ObjectType);
  281. }
  282. }
  283. CheckFieldType(node.Type);
  284. }
  285. bool IsValidLiteralInitializer(Expression e)
  286. {
  287. switch (e.NodeType)
  288. {
  289. case NodeType.BoolLiteralExpression:
  290. case NodeType.IntegerLiteralExpression:
  291. case NodeType.DoubleLiteralExpression:
  292. case NodeType.NullLiteralExpression:
  293. case NodeType.StringLiteralExpression:
  294. {
  295. return true;
  296. }
  297. }
  298. return false;
  299. }
  300. void ProcessLiteralField(Field node)
  301. {
  302. Visit(node.Initializer);
  303. ProcessFieldInitializerType(node, node.Initializer.ExpressionType);
  304. ((InternalField)node.Entity).StaticValue = node.Initializer;
  305. node.Initializer = null;
  306. }
  307. void ProcessFieldInitializerType(Field node, IType initializerType)
  308. {
  309. if (null == node.Type)
  310. {
  311. node.Type = CreateTypeReference(node.LexicalInfo, MapNullToObject(initializerType));
  312. }
  313. else
  314. {
  315. AssertTypeCompatibility(node.Initializer, GetType(node.Type), initializerType);
  316. }
  317. }
  318. private TypeReference CreateTypeReference(LexicalInfo info, IType type)
  319. {
  320. TypeReference reference = CodeBuilder.CreateTypeReference(type);
  321. reference.LexicalInfo = info;
  322. return reference;
  323. }
  324. private void PreProcessFieldInitializer(Field node)
  325. {
  326. Expression initializer = node.Initializer;
  327. if (node.IsFinal && node.IsStatic)
  328. {
  329. if (IsValidLiteralInitializer(initializer))
  330. {
  331. ProcessLiteralField(node);
  332. return;
  333. }
  334. }
  335. Method method = GetFieldsInitializerMethod(node);
  336. InternalMethod entity = (InternalMethod)method.Entity;
  337. ReferenceExpression temp = new ReferenceExpression("___temp_initializer");
  338. BinaryExpression assignment = new BinaryExpression(
  339. node.LexicalInfo,
  340. BinaryOperatorType.Assign,
  341. temp,
  342. initializer);
  343. ProcessNodeInMethodContext(entity, entity, assignment);
  344. method.Locals.RemoveByEntity(temp.Entity);
  345. IType initializerType = GetExpressionType(assignment.Right);
  346. ProcessFieldInitializerType(node, initializerType);
  347. node.Initializer = assignment.Right;
  348. }
  349. void ProcessFieldInitializer(Field node)
  350. {
  351. Expression initializer = node.Initializer;
  352. if (null == initializer) return;
  353. Method method = GetFieldsInitializerMethod(node);
  354. method.Body.Add(
  355. CodeBuilder.CreateAssignment(
  356. initializer.LexicalInfo,
  357. CodeBuilder.CreateReference(node),
  358. initializer));
  359. node.Initializer = null;
  360. }
  361. Method CreateInitializerMethod(TypeDefinition type, string name, TypeMemberModifiers modifiers)
  362. {
  363. Method method = new Method(name);
  364. method.Modifiers |= modifiers;
  365. method.ReturnType = CodeBuilder.CreateTypeReference(TypeSystemServices.VoidType);
  366. InternalMethod entity = new InternalMethod(TypeSystemServices, method);
  367. method.Entity = entity;
  368. type.Members.Add(method);
  369. MarkVisited(method);
  370. return method;
  371. }
  372. Method GetFieldsInitializerMethod(Field node)
  373. {
  374. TypeDefinition type = node.DeclaringType;
  375. string methodName = node.IsStatic ? "$static_initializer$" : "$initializer$";
  376. Method method = (Method)type[methodName];
  377. if (null == method)
  378. {
  379. if (node.IsStatic)
  380. {
  381. if (null == FindStaticConstructor(type))
  382. {
  383. // when the class doesnt have a static constructor
  384. // yet, create one and use it as the static
  385. // field initializer method
  386. method = CreateStaticConstructor(type);
  387. }
  388. else
  389. {
  390. method = CreateInitializerMethod(type, methodName, TypeMemberModifiers.Static);
  391. AddInitializerToStaticConstructor(type, (InternalMethod)method.Entity);
  392. }
  393. }
  394. else
  395. {
  396. method = CreateInitializerMethod(type, methodName, TypeMemberModifiers.None);
  397. AddInitializerToInstanceConstructors(type, (InternalMethod)method.Entity);
  398. }
  399. type[methodName] = method;
  400. }
  401. return method;
  402. }
  403. void AddInitializerToStaticConstructor(TypeDefinition type, InternalMethod initializer)
  404. {
  405. GetStaticConstructor(type).Body.Insert(0,
  406. CodeBuilder.CreateMethodInvocation(initializer));
  407. }
  408. void AddInitializerToInstanceConstructors(TypeDefinition type, InternalMethod initializer)
  409. {
  410. foreach (TypeMember node in type.Members)
  411. {
  412. if (NodeType.Constructor == node.NodeType && !node.IsStatic)
  413. {
  414. Constructor constructor = (Constructor)node;
  415. constructor.Body.Insert(GetIndexAfterSuperInvocation(constructor.Body),
  416. CodeBuilder.CreateMethodInvocation(
  417. CodeBuilder.CreateSelfReference((IType)type.Entity),
  418. initializer));
  419. }
  420. }
  421. }
  422. int GetIndexAfterSuperInvocation(Block body)
  423. {
  424. int index = 0;
  425. foreach (Statement s in body.Statements)
  426. {
  427. if (NodeType.ExpressionStatement == s.NodeType)
  428. {
  429. Expression expression = ((ExpressionStatement)s).Expression;
  430. if (NodeType.MethodInvocationExpression == expression.NodeType)
  431. {
  432. if (NodeType.SuperLiteralExpression == ((MethodInvocationExpression)expression).Target.NodeType)
  433. {
  434. return index + 1;
  435. }
  436. }
  437. }
  438. ++index;
  439. }
  440. return 0;
  441. }
  442. Constructor FindStaticConstructor(TypeDefinition type)
  443. {
  444. foreach (TypeMember member in type.Members)
  445. {
  446. if (member.IsStatic && NodeType.Constructor == member.NodeType)
  447. {
  448. return (Constructor)member;
  449. }
  450. }
  451. return null;
  452. }
  453. Constructor GetStaticConstructor(TypeDefinition type)
  454. {
  455. Constructor constructor = FindStaticConstructor(type);
  456. if (null == constructor)
  457. {
  458. constructor = CreateStaticConstructor(type);
  459. }
  460. return constructor;
  461. }
  462. Constructor CreateStaticConstructor(TypeDefinition type)
  463. {
  464. Constructor constructor = new Constructor();
  465. constructor.Entity = new InternalConstructor(TypeSystemServices, constructor);
  466. constructor.Modifiers = TypeMemberModifiers.Public|TypeMemberModifiers.Static;
  467. type.Members.Add(constructor);
  468. MarkVisited(constructor);
  469. return constructor;
  470. }
  471. void AddFieldInitializerToStaticConstructor(int index, Field node)
  472. {
  473. Constructor constructor = GetStaticConstructor(node.DeclaringType);
  474. Statement stmt = CodeBuilder.CreateFieldAssignment(node, node.Initializer);
  475. constructor.Body.Statements.Insert(index, stmt);
  476. node.Initializer = null;
  477. }
  478. void CheckRuntimeMethod(Method method)
  479. {
  480. if (method.Body.Statements.Count > 0)
  481. {
  482. Error(CompilerErrorFactory.RuntimeMethodBodyMustBeEmpty(method, method.FullName));
  483. }
  484. }
  485. override public void OnConstructor(Constructor node)
  486. {
  487. if (WasVisited(node))
  488. {
  489. return;
  490. }
  491. MarkVisited(node);
  492. Visit(node.Attributes);
  493. Visit(node.Parameters);
  494. InternalConstructor entity = (InternalConstructor)node.Entity;
  495. ProcessMethodBody(entity);
  496. if (node.IsRuntime)
  497. {
  498. CheckRuntimeMethod(node);
  499. }
  500. else
  501. {
  502. if (entity.DeclaringType.IsValueType)
  503. {
  504. if (0 == node.Parameters.Count &&
  505. !node.IsSynthetic)
  506. {
  507. Error(
  508. CompilerErrorFactory.ValueTypesCannotDeclareParameterlessConstructors(node));
  509. }
  510. }
  511. else if (
  512. !entity.HasSelfCall &&
  513. !entity.HasSuperCall &&
  514. !entity.IsStatic)
  515. {
  516. IType baseType = entity.DeclaringType.BaseType;
  517. IConstructor super = GetCorrectConstructor(node, baseType, EmptyExpressionCollection);
  518. if (null != super)
  519. {
  520. node.Body.Statements.Insert(0,
  521. CodeBuilder.CreateSuperConstructorInvocation(super));
  522. }
  523. }
  524. }
  525. }
  526. override public void LeaveParameterDeclaration(ParameterDeclaration node)
  527. {
  528. AssertIdentifierName(node, node.Name);
  529. CheckParameterType(node.Type);
  530. }
  531. void CheckParameterType(TypeReference type)
  532. {
  533. if (type.Entity != TypeSystemServices.VoidType) return;
  534. Error(CompilerErrorFactory.InvalidParameterType(type, type.Entity.ToString()));
  535. }
  536. void CheckFieldType(TypeReference type)
  537. {
  538. if (type.Entity != TypeSystemServices.VoidType) return;
  539. Error(CompilerErrorFactory.InvalidFieldType(type, type.Entity.ToString()));
  540. }
  541. void CheckDeclarationType(TypeReference type)
  542. {
  543. if (type.Entity != TypeSystemServices.VoidType) return;
  544. Error(CompilerErrorFactory.InvalidDeclarationType(type, type.Entity.ToString()));
  545. }
  546. override public void OnBlockExpression(BlockExpression node)
  547. {
  548. if (WasVisited(node)) return;
  549. MarkVisited(node);
  550. Method closure = CodeBuilder.CreateMethod(
  551. ClosureNameFor(node),
  552. Unknown.Default,
  553. ClosureModifiers());
  554. MarkVisited(closure);
  555. InternalMethod closureEntity = (InternalMethod)closure.Entity;
  556. closure.LexicalInfo = node.LexicalInfo;
  557. closure.Parameters = node.Parameters;
  558. closure.Body = node.Body;
  559. _currentMethod.Method.DeclaringType.Members.Add(closure);
  560. CodeBuilder.BindParameterDeclarations(_currentMethod.IsStatic, closure);
  561. // check for invalid names and
  562. // resolve parameter types
  563. Visit(closure.Parameters);
  564. if (node.ContainsAnnotation("inline"))
  565. {
  566. AddOptionalReturnStatement(node.Body);
  567. }
  568. // Connects the closure method namespace with the current
  569. NamespaceDelegator ns = new NamespaceDelegator(CurrentNamespace, closureEntity);
  570. ProcessMethodBody(closureEntity, ns);
  571. TryToResolveReturnType(closureEntity);
  572. node.ExpressionType = closureEntity.Type;
  573. node.Entity = closureEntity;
  574. }
  575. private TypeMemberModifiers ClosureModifiers()
  576. {
  577. TypeMemberModifiers modifiers = TypeMemberModifiers.Internal;
  578. if (_currentMethod.IsStatic)
  579. {
  580. modifiers |= TypeMemberModifiers.Static;
  581. }
  582. return modifiers;
  583. }
  584. private string ClosureNameFor(BlockExpression block)
  585. {
  586. string closureHint = (block["ClosureName"] as string) ?? "closure";
  587. return _currentMethod.Name + "$" + closureHint + "$" + _context.AllocIndex();
  588. }
  589. private void AddOptionalReturnStatement(Block body)
  590. {
  591. if (body.Statements.Count != 1) return;
  592. ExpressionStatement stmt = body.Statements[0] as ExpressionStatement;
  593. if (null == stmt) return;
  594. ReturnStatement rs = new ReturnStatement(stmt.LexicalInfo, stmt.Expression, null);
  595. rs.Annotate(OptionalReturnStatementAnnotation);
  596. body.Replace(stmt, rs);
  597. }
  598. override public void OnMethod(Method method)
  599. {
  600. if (WasVisited(method)) return;
  601. MarkVisited(method);
  602. Visit(method.Attributes);
  603. Visit(method.Parameters);
  604. Visit(method.ReturnType);
  605. Visit(method.ReturnTypeAttributes);
  606. bool ispinvoke = GetEntity(method).IsPInvoke;
  607. if (method.IsRuntime || ispinvoke)
  608. {
  609. CheckRuntimeMethod(method);
  610. if (ispinvoke)
  611. {
  612. method.Modifiers |= TypeMemberModifiers.Static;
  613. }
  614. }
  615. else
  616. {
  617. try
  618. {
  619. PushMember(method);
  620. ProcessRegularMethod(method);
  621. }
  622. finally
  623. {
  624. PopMember();
  625. }
  626. }
  627. }
  628. void CheckIfIsMethodOverride(InternalMethod entity)
  629. {
  630. if (entity.IsStatic) return;
  631. IMethod overriden = FindMethodOverride(entity);
  632. if (null == overriden) return;
  633. ProcessMethodOverride(entity, overriden);
  634. }
  635. IMethod FindPropertyAccessorOverride(Property property, Method accessor)
  636. {
  637. IProperty baseProperty = ((InternalProperty)property.Entity).Override;
  638. if (null == baseProperty) return null;
  639. IMethod baseMethod = null;
  640. if (property.Getter == accessor)
  641. {
  642. baseMethod = baseProperty.GetGetMethod();
  643. }
  644. else
  645. {
  646. baseMethod = baseProperty.GetSetMethod();
  647. }
  648. if (null != baseMethod)
  649. {
  650. IMethod accessorEntity = (IMethod)accessor.Entity;
  651. if (TypeSystemServices.CheckOverrideSignature(accessorEntity, baseMethod))
  652. {
  653. return baseMethod;
  654. }
  655. }
  656. return null;
  657. }
  658. IMethod FindMethodOverride(InternalMethod entity)
  659. {
  660. Method method = entity.Method;
  661. if (NodeType.Property == method.ParentNode.NodeType)
  662. {
  663. return FindPropertyAccessorOverride((Property)method.ParentNode, method);
  664. }
  665. IType baseType = entity.DeclaringType.BaseType;
  666. IEntity candidates = NameResolutionService.Resolve(baseType, entity.Name, EntityType.Method);
  667. if (null != candidates)
  668. {
  669. IMethod baseMethod = null;
  670. if (EntityType.Method == candidates.EntityType)
  671. {
  672. IMethod candidate = (IMethod)candidates;
  673. if (TypeSystemServices.CheckOverrideSignature(entity, candidate))
  674. {
  675. baseMethod = candidate;
  676. }
  677. }
  678. else if (EntityType.Ambiguous == candidates.EntityType)
  679. {
  680. IEntity[] entities = ((Ambiguous)candidates).Entities;
  681. foreach (IMethod candidate in entities)
  682. {
  683. if (TypeSystemServices.CheckOverrideSignature(entity, candidate))
  684. {
  685. baseMethod = candidate;
  686. break;
  687. }
  688. }
  689. }
  690. if (null != baseMethod)
  691. {
  692. EnsureRelatedNodeWasVisited(method, baseMethod);
  693. }
  694. return baseMethod;
  695. }
  696. return null;
  697. }
  698. void ResolveMethodOverride(InternalMethod entity)
  699. {
  700. IMethod baseMethod = FindMethodOverride(entity);
  701. if (null == baseMethod)
  702. {
  703. Error(CompilerErrorFactory.NoMethodToOverride(entity.Method, entity.ToString()));
  704. }
  705. else
  706. {
  707. if (!baseMethod.IsVirtual)
  708. {
  709. CantOverrideNonVirtual(entity.Method, baseMethod);
  710. }
  711. else
  712. {
  713. ProcessMethodOverride(entity, baseMethod);
  714. }
  715. }
  716. }
  717. void ProcessMethodOverride(InternalMethod entity, IMethod baseMethod)
  718. {
  719. if (TypeSystemServices.IsUnknown(entity.ReturnType))
  720. {
  721. entity.Method.ReturnType = CodeBuilder.CreateTypeReference(entity.Method.LexicalInfo, baseMethod.ReturnType);
  722. }
  723. else if (GenericsServices.IsGenericParameter(entity.ReturnType)
  724. == GenericsServices.IsGenericParameter(baseMethod.ReturnType))
  725. {
  726. if (!baseMethod.ReturnType.Equals(entity.ReturnType))
  727. {
  728. Error(CompilerErrorFactory.InvalidOverrideReturnType(
  729. entity.Method.ReturnType,
  730. baseMethod.FullName,
  731. baseMethod.ReturnType.ToString(),
  732. entity.ReturnType.ToString()));
  733. }
  734. }
  735. SetOverride(entity, baseMethod);
  736. }
  737. void CantOverrideNonVirtual(Method method, IMethod baseMethod)
  738. {
  739. Error(CompilerErrorFactory.CantOverrideNonVirtual(method, baseMethod.ToString()));
  740. }
  741. void SetPropertyAccessorOverride(Method accessor)
  742. {
  743. if (null != accessor)
  744. {
  745. accessor.Modifiers |= TypeMemberModifiers.Override;
  746. }
  747. }
  748. IProperty ResolvePropertyOverride(IProperty p, IEntity[] candidates)
  749. {
  750. foreach (IEntity candidate in candidates)
  751. {
  752. if (EntityType.Property != candidate.EntityType) continue;
  753. IProperty candidateProperty = (IProperty)candidate;
  754. if (CheckOverrideSignature(p, candidateProperty))
  755. {
  756. return candidateProperty;
  757. }
  758. }
  759. return null;
  760. }
  761. bool CheckOverrideSignature(IProperty p, IProperty candidate)
  762. {
  763. return TypeSystemServices.CheckOverrideSignature(p.GetParameters(), candidate.GetParameters());
  764. }
  765. void ResolvePropertyOverride(Property property)
  766. {
  767. InternalProperty entity = (InternalProperty)property.Entity;
  768. IType baseType = entity.DeclaringType.BaseType;
  769. IEntity baseProperties = NameResolutionService.Resolve(baseType, property.Name, EntityType.Property);
  770. if (null != baseProperties)
  771. {
  772. if (EntityType.Property == baseProperties.EntityType)
  773. {
  774. IProperty candidate = (IProperty)baseProperties;
  775. if (CheckOverrideSignature(entity, candidate))
  776. {
  777. entity.Override = candidate;
  778. }
  779. }
  780. else if (EntityType.Ambiguous == baseProperties.EntityType)
  781. {
  782. entity.Override = ResolvePropertyOverride(entity, ((Ambiguous)baseProperties).Entities);
  783. }
  784. }
  785. if (null != entity.Override)
  786. {
  787. EnsureRelatedNodeWasVisited(property, entity.Override);
  788. if (property.IsOverride)
  789. {
  790. SetPropertyAccessorOverride(property.Getter);
  791. SetPropertyAccessorOverride(property.Setter);
  792. }
  793. else
  794. {
  795. if (null != entity.Override.GetGetMethod())
  796. {
  797. SetPropertyAccessorOverride(property.Getter);
  798. }
  799. if (null != entity.Override.GetSetMethod())
  800. {
  801. SetPropertyAccessorOverride(property.Setter);
  802. }
  803. }
  804. if (null == property.Type)
  805. {
  806. property.Type = CodeBuilder.CreateTypeReference(entity.Override.Type);
  807. }
  808. }
  809. }
  810. void SetOverride(InternalMethod entity, IMethod baseMethod)
  811. {
  812. TraceOverride(entity.Method, baseMethod);
  813. entity.Overriden = baseMethod;
  814. entity.Method.Modifiers |= TypeMemberModifiers.Override;
  815. }
  816. void TraceOverride(Method method, IMethod baseMethod)
  817. {
  818. _context.TraceInfo("{0}: Method '{1}' overrides '{2}'", method.LexicalInfo, method.Name, baseMethod);
  819. }
  820. class ReturnExpressionFinder : DepthFirstVisitor
  821. {
  822. bool _hasReturnStatements = false;
  823. bool _hasYieldStatements = false;
  824. public ReturnExpressionFinder(Method node)
  825. {
  826. Visit(node.Body);
  827. }
  828. public bool HasReturnStatements
  829. {
  830. get
  831. {
  832. return _hasReturnStatements;
  833. }
  834. }
  835. public bool HasYieldStatements
  836. {
  837. get
  838. {
  839. return _hasYieldStatements;
  840. }
  841. }
  842. public override void OnReturnStatement(ReturnStatement node)
  843. {
  844. _hasReturnStatements |= (null != node.Expression);
  845. }
  846. public override void OnYieldStatement(YieldStatement node)
  847. {
  848. _hasYieldStatements = true;
  849. }
  850. }
  851. bool DontHaveReturnExpressionsNorYield(Method node)
  852. {
  853. ReturnExpressionFinder finder = new ReturnExpressionFinder(node);
  854. return !(finder.HasReturnStatements || finder.HasYieldStatements);
  855. }
  856. void PreProcessMethod(Method node)
  857. {
  858. if (WasAlreadyPreProcessed(node)) return;
  859. MarkPreProcessed(node);
  860. InternalMethod entity = (InternalMethod)GetEntity(node);
  861. if (node.IsOverride)
  862. {
  863. ResolveMethodOverride(entity);
  864. }
  865. else
  866. {
  867. CheckIfIsMethodOverride(entity);
  868. if (TypeSystemServices.IsUnknown(entity.ReturnType))
  869. {
  870. if (DontHaveReturnExpressionsNorYield(node))
  871. {
  872. node.ReturnType = CodeBuilder.CreateTypeReference(node.LexicalInfo, TypeSystemServices.VoidType);
  873. }
  874. }
  875. }
  876. }
  877. static readonly object PreProcessedKey = new object();
  878. private bool WasAlreadyPreProcessed(Method node)
  879. {
  880. return node.ContainsAnnotation(PreProcessedKey);
  881. }
  882. private void MarkPreProcessed(Method node)
  883. {
  884. node[PreProcessedKey] = PreProcessedKey;
  885. }
  886. void ProcessRegularMethod(Method node)
  887. {
  888. PreProcessMethod(node);
  889. InternalMethod entity = (InternalMethod) GetEntity(node);
  890. ProcessMethodBody(entity);
  891. PostProcessMethod(node);
  892. }
  893. private void PostProcessMethod(Method node)
  894. {
  895. bool parentIsClass = node.DeclaringType.NodeType == NodeType.ClassDefinition;
  896. if (!parentIsClass) return;
  897. InternalMethod entity = (InternalMethod)GetEntity(node);
  898. if (TypeSystemServices.IsUnknown(entity.ReturnType))
  899. {
  900. TryToResolveReturnType(entity);
  901. }
  902. else
  903. {
  904. if (entity.IsGenerator)
  905. {
  906. CheckGeneratorReturnType(node, entity.ReturnType);
  907. CheckGeneratorYieldType(entity, entity.ReturnType);
  908. }
  909. }
  910. CheckGeneratorCantReturnValues(entity);
  911. }
  912. void CheckGeneratorCantReturnValues(InternalMethod entity)
  913. {
  914. if (!entity.IsGenerator) return;
  915. if (null == entity.ReturnExpressions) return;
  916. foreach (Expression e in entity.ReturnExpressions)
  917. {
  918. Error(CompilerErrorFactory.GeneratorCantReturnValue(e));
  919. }
  920. }
  921. void CheckGeneratorReturnType(Method method, IType returnType)
  922. {
  923. bool validReturnType =
  924. (TypeSystemServices.IEnumerableType == returnType ||
  925. TypeSystemServices.IEnumeratorType == returnType ||
  926. TypeSystemServices.IsSystemObject(returnType) ||
  927. CheckGenericGeneratorReturnType(returnType));
  928. if (!validReturnType)
  929. {
  930. Error(CompilerErrorFactory.InvalidGeneratorReturnType(method.ReturnType));
  931. }
  932. }
  933. bool CheckGenericGeneratorReturnType(IType returnType)
  934. {
  935. return returnType.ConstructedInfo != null &&
  936. (returnType.ConstructedInfo.GenericDefinition == TypeSystemServices.IEnumerableGenericType ||
  937. returnType.ConstructedInfo.GenericDefinition == TypeSystemServices.IEnumeratorGenericType);
  938. }
  939. void CheckGeneratorYieldType(InternalMethod method, IType returnType)
  940. {
  941. if (CheckGenericGeneratorReturnType(returnType))
  942. {
  943. IType returnElementType = returnType.ConstructedInfo.GenericArguments[0];
  944. foreach (Expression yieldExpression in method.YieldExpressions)
  945. {
  946. IType yieldType = yieldExpression.ExpressionType;
  947. if (!returnElementType.IsAssignableFrom(yieldType) &&
  948. !TypeSystemServices.CanBeReachedByDownCastOrPromotion(returnElementType, yieldType))
  949. {
  950. Error(CompilerErrorFactory.YieldTypeDoesNotMatchReturnType(
  951. yieldExpression, yieldType.ToString(), returnElementType.ToString()));
  952. }
  953. }
  954. }
  955. }
  956. void ProcessMethodBody(InternalMethod entity)
  957. {
  958. ProcessMethodBody(entity, entity);
  959. }
  960. void ProcessMethodBody(InternalMethod entity, INamespace ns)
  961. {
  962. ProcessNodeInMethodContext(entity, ns, entity.Method.Body);
  963. if (entity.IsGenerator) CreateGeneratorSkeleton(entity);
  964. }
  965. void ProcessNodeInMethodContext(InternalMethod entity, INamespace ns, Node node)
  966. {
  967. PushMethodInfo(entity);
  968. EnterNamespace(ns);
  969. try
  970. {
  971. Visit(node);
  972. }
  973. finally
  974. {
  975. LeaveNamespace();
  976. PopMethodInfo();
  977. }
  978. }
  979. void ResolveGeneratorReturnType(InternalMethod entity)
  980. {
  981. Method method = entity.Method;
  982. // Make method return a generic IEnumerable
  983. IType itemType = (IType)method["GeneratorItemType"];
  984. if (TypeSystemServices.VoidType == itemType)
  985. {
  986. // circunvent exception in MakeGenericType
  987. method.ReturnType = CodeBuilder.CreateTypeReference(TypeSystemServices.ErrorEntity);
  988. return;
  989. }
  990. IType returnType = GetGeneratorReturnType(itemType);
  991. method.ReturnType = CodeBuilder.CreateTypeReference(returnType);
  992. }
  993. protected virtual IType GetGeneratorReturnType(IType itemType)
  994. {
  995. IType enumerableType = TypeSystemServices.IEnumerableGenericType;
  996. return enumerableType.GenericInfo.ConstructType(itemType);
  997. }
  998. void TryToResolveReturnType(InternalMethod entity)
  999. {
  1000. if (entity.IsGenerator)
  1001. {
  1002. ResolveGeneratorReturnType(entity);
  1003. }
  1004. else
  1005. {
  1006. if (CanResolveReturnType(entity))
  1007. {
  1008. ResolveReturnType(entity);
  1009. }
  1010. }
  1011. }
  1012. override public void OnSuperLiteralExpression(SuperLiteralExpression node)
  1013. {
  1014. if (!AstUtil.IsTargetOfMethodInvocation(node))
  1015. {
  1016. node.ExpressionType = _currentMethod.DeclaringType.BaseType;
  1017. return;
  1018. }
  1019. if (EntityType.Constructor == _currentMethod.EntityType)
  1020. {
  1021. // TODO: point to super ctor
  1022. node.Entity = _currentMethod;
  1023. return;
  1024. }
  1025. if (null == _currentMethod.Overriden)
  1026. {
  1027. Error(node,
  1028. CompilerErrorFactory.MethodIsNotOverride(node, _currentMethod.ToString()));
  1029. return;
  1030. }
  1031. node.Entity = _currentMethod;
  1032. }
  1033. bool CanResolveReturnType(InternalMethod tag)
  1034. {
  1035. ExpressionCollection expressions = tag.ReturnExpressions;
  1036. if (null != expressions)
  1037. {
  1038. foreach (Expression expression in expressions)
  1039. {
  1040. IType type = expression.ExpressionType;
  1041. if (null == type || TypeSystemServices.IsUnknown(type))
  1042. {
  1043. return false;
  1044. }
  1045. }
  1046. }
  1047. return true;
  1048. }
  1049. TypeReference GetMostGenericTypeReference(ExpressionCollection expressions)
  1050. {
  1051. IType type = MapNullToObject(GetMostGenericType(expressions));
  1052. return CodeBuilder.CreateTypeReference(type);
  1053. }
  1054. void ResolveReturnType(InternalMethod entity)
  1055. {
  1056. Method method = entity.Method;
  1057. if (null == entity.ReturnExpressions)
  1058. {
  1059. method.ReturnType = CodeBuilder.CreateTypeReference(TypeSystemServices.VoidType);
  1060. }
  1061. else
  1062. {
  1063. method.ReturnType = GetMostGenericTypeReference(entity.ReturnExpressions);
  1064. }
  1065. TraceReturnType(method, entity);
  1066. }
  1067. IType MapNullToObject(IType type)
  1068. {
  1069. if (Null.Default == type)
  1070. {
  1071. return TypeSystemServices.ObjectType;
  1072. }
  1073. return type;
  1074. }
  1075. IType GetMostGenericType(IType lhs, IType rhs)
  1076. {
  1077. return TypeSystemServices.GetMostGenericType(lhs, rhs);
  1078. }
  1079. IType GetMostGenericType(ExpressionCollection args)
  1080. {
  1081. IType type = GetConcreteExpressionType(args[0]);
  1082. for (int i=1; i<args.Count; ++i)
  1083. {
  1084. IType newType = GetConcreteExpressionType(args[i]);
  1085. if (type == newType)
  1086. {
  1087. continue;
  1088. }
  1089. type = GetMostGenericType(type, newType);
  1090. if (TypeSystemServices.IsSystemObject(type))
  1091. {
  1092. break;
  1093. }
  1094. }
  1095. return type;
  1096. }
  1097. override public void OnBoolLiteralExpression(BoolLiteralExpression node)
  1098. {
  1099. BindExpressionType(node, TypeSystemServices.BoolType);
  1100. }
  1101. override public void OnTimeSpanLiteralExpression(TimeSpanLiteralExpression node)
  1102. {
  1103. BindExpressionType(node, TypeSystemServices.TimeSpanType);
  1104. }
  1105. override public void OnIntegerLiteralExpression(IntegerLiteralExpression node)
  1106. {
  1107. if (node.IsLong)
  1108. {
  1109. BindExpressionType(node, TypeSystemServices.LongType);
  1110. }
  1111. else
  1112. {
  1113. BindExpressionType(node, TypeSystemServices.IntType);
  1114. }
  1115. }
  1116. override public void OnDoubleLiteralExpression(DoubleLiteralExpression node)
  1117. {
  1118. BindExpressionType(node, node.IsSingle ? TypeSystemServices.SingleType : TypeSystemServices.DoubleType);
  1119. }
  1120. override public void OnStringLiteralExpression(StringLiteralExpression node)
  1121. {
  1122. BindExpressionType(node, TypeSystemServices.StringType);
  1123. }
  1124. override public void OnCharLiteralExpression(CharLiteralExpression node)
  1125. {
  1126. string value = node.Value;
  1127. if (null == value || 1 != value.Length)
  1128. {
  1129. Errors.Add(CompilerErrorFactory.InvalidCharLiteral(node, value));
  1130. }
  1131. BindExpressionType(node, TypeSystemServices.CharType);
  1132. }
  1133. IEntity[] GetSetMethods(IEntity[] entities)
  1134. {
  1135. List setMethods = new List();
  1136. for (int i=0; i<entities.Length; ++i)
  1137. {
  1138. IProperty property = entities[i] as IProperty;
  1139. if (null != property)
  1140. {
  1141. IMethod setter = property.GetSetMethod();
  1142. if (null != setter)
  1143. {
  1144. setMethods.AddUnique(setter);
  1145. }
  1146. }
  1147. }
  1148. return ToEntityArray(setMethods);
  1149. }
  1150. IEntity[] GetGetMethods(IEntity[] entities)
  1151. {
  1152. List getMethods = new List();
  1153. for (int i=0; i<entities.Length; ++i)
  1154. {
  1155. IProperty property = entities[i] as IProperty;
  1156. if (null != property)
  1157. {
  1158. IMethod getter = property.GetGetMethod();
  1159. if (null != getter)
  1160. {
  1161. getMethods.AddUnique(getter);
  1162. }
  1163. }
  1164. }
  1165. return ToEntityArray(getMethods);
  1166. }
  1167. private static IEntity[] ToEntityArray(List entities)
  1168. {
  1169. return (IEntity[])entities.ToArray(new IEntity[entities.Count]);
  1170. }
  1171. void CheckNoComplexSlicing(SlicingExpression node)
  1172. {
  1173. if (AstUtil.IsComplexSlicing(node))
  1174. {
  1175. NotImplemented(node, "complex slicing");
  1176. }
  1177. }
  1178. protected MethodInvocationExpression CreateEquals(BinaryExpression node)
  1179. {
  1180. return CodeBuilder.CreateMethodInvocation(RuntimeServices_EqualityOperator, node.Left, node.Right);
  1181. }
  1182. IntegerLiteralExpression CreateIntegerLiteral(long value)
  1183. {
  1184. IntegerLiteralExpression expression = new IntegerLiteralExpression(value);
  1185. Visit(expression);
  1186. return expression;
  1187. }
  1188. bool CheckComplexSlicingParameters(SlicingExpression node)
  1189. {
  1190. foreach (Slice slice in node.Indices)
  1191. {
  1192. if (!CheckComplexSlicingParameters(slice))
  1193. {
  1194. return false;
  1195. }
  1196. }
  1197. return true;
  1198. }
  1199. bool CheckComplexSlicingParameters(Slice node)
  1200. {
  1201. if (null != node.Step)
  1202. {
  1203. NotImplemented(node, "slicing step");
  1204. return false;
  1205. }
  1206. if (OmittedExpression.Default == node.Begin)
  1207. {
  1208. node.Begin = CreateIntegerLiteral(0);
  1209. }
  1210. else
  1211. {
  1212. if (!AssertTypeCompatibility(node.Begin, TypeSystemServices.IntType, GetExpressionType(node.Begin)))
  1213. {
  1214. return false;
  1215. }
  1216. }
  1217. if (null != node.End && OmittedExpression.Default != node.End)
  1218. {
  1219. if (!AssertTypeCompatibility(node.End, TypeSystemServices.IntType, GetExpressionType(node.End)))
  1220. {
  1221. return false;
  1222. }
  1223. }
  1224. return true;
  1225. }
  1226. void BindComplexListSlicing(SlicingExpression node)
  1227. {
  1228. Slice slice = node.Indices[0];
  1229. if (CheckComplexSlicingParameters(slice))
  1230. {
  1231. MethodInvocationExpression mie = null;
  1232. if (null == slice.End || slice.End == OmittedExpression.Default)
  1233. {
  1234. mie = CodeBuilder.CreateMethodInvocation(node.Target, List_GetRange1);
  1235. mie.Arguments.Add(slice.Begin);
  1236. }
  1237. else
  1238. {
  1239. mie = CodeBuilder.CreateMethodInvocation(node.Target, List_GetRange2);
  1240. mie.Arguments.Add(slice.Begin);
  1241. mie.Arguments.Add(slice.End);
  1242. }
  1243. node.ParentNode.Replace(node, mie);
  1244. }
  1245. }
  1246. void BindComplexArraySlicing(SlicingExpression node)
  1247. {
  1248. if (AstUtil.IsLhsOfAssignment(node))
  1249. {
  1250. return;
  1251. }
  1252. if (CheckComplexSlicingParameters(node))
  1253. {
  1254. if (node.Indices.Count > 1)
  1255. {
  1256. IArrayType arrayType = (IArrayType)GetExpressionType(node.Target);
  1257. MethodInvocationExpression mie = null;
  1258. ArrayLiteralExpression collapse = new ArrayLiteralExpression();
  1259. ArrayLiteralExpression ranges = new ArrayLiteralExpression();
  1260. int collapseCount = 0;
  1261. for (int i = 0; i < node.Indices.Count; i++)
  1262. {
  1263. ranges.Items.Add(node.Indices[i].Begin);
  1264. if (node.Indices[i].End == null ||
  1265. node.Indices[i].End == OmittedExpression.Default)
  1266. {
  1267. BinaryExpression end = new BinaryExpression(BinaryOperatorType.Addition,
  1268. node.Indices[i].Begin,
  1269. new IntegerLiteralExpression(1));
  1270. ranges.Items.Add(end);
  1271. BindExpressionType(end, GetExpressionType(node.Indices[i].Begin));
  1272. collapse.Items.Add(new BoolLiteralExpression(true));
  1273. collapseCount++;
  1274. }
  1275. else
  1276. {
  1277. ranges.Items.Add(node.Indices[i].End);
  1278. collapse.Items.Add(new BoolLiteralExpression(false));
  1279. }
  1280. }
  1281. mie = CodeBuilder.CreateMethodInvocation(RuntimeServices_GetMultiDimensionalRange1, node.Target, ranges);
  1282. mie.Arguments.Add(collapse);
  1283. BindExpressionType(ranges, TypeSystemServices.Map(typeof(int[])));
  1284. BindExpressionType(collapse, TypeSystemServices.Map(typeof(bool[])));
  1285. BindExpressionType(mie, TypeSystemServices.GetArrayType(arrayType.GetElementType(), node.Indices.Count - collapseCount));
  1286. node.ParentNode.Replace(node, mie);
  1287. }
  1288. else
  1289. {
  1290. Slice slice = node.Indices[0];
  1291. if (CheckComplexSlicingParameters(slice))
  1292. {
  1293. MethodInvocationExpression mie = null;
  1294. if (null == slice.End || slice.End == OmittedExpression.Default)
  1295. {
  1296. mie = CodeBuilder.CreateMethodInvocation(RuntimeServices_GetRange1, node.Target, slice.Begin);
  1297. }
  1298. else
  1299. {
  1300. mie = CodeBuilder.CreateMethodInvocation(RuntimeServices_GetRange2, node.Target, slice.Begin, slice.End);
  1301. }
  1302. BindExpressionType(mie, GetExpressionType(node.Target));
  1303. node.ParentNode.Replace(node, mie);
  1304. }
  1305. }
  1306. }
  1307. }
  1308. bool NeedsNormalization(Expression index)
  1309. {
  1310. if (NodeType.IntegerLiteralExpression == index.NodeType)
  1311. {
  1312. return ((IntegerLiteralExpression)index).Value < 0;
  1313. }
  1314. return true;
  1315. }
  1316. void BindComplexStringSlicing(SlicingExpression node)
  1317. {
  1318. Slice slice = node.Indices[0];
  1319. if (CheckComplexSlicingParameters(slice))
  1320. {
  1321. MethodInvocationExpression mie = null;
  1322. if (null == slice.End || slice.End == OmittedExpression.Default)
  1323. {
  1324. if (NeedsNormalization(slice.Begin))
  1325. {
  1326. mie = CodeBuilder.CreateEvalInvocation(node.LexicalInfo);
  1327. mie.ExpressionType = TypeSystemServices.StringType;
  1328. InternalLocal temp = DeclareTempLocal(TypeSystemServices.StringType);
  1329. mie.Arguments.Add(
  1330. CodeBuilder.CreateAssignment(
  1331. CodeBuilder.CreateReference(temp),
  1332. node.Target));
  1333. mie.Arguments.Add(
  1334. CodeBuilder.CreateMethodInvocation(
  1335. CodeBuilder.CreateReference(temp),
  1336. String_Substring_Int,
  1337. CodeBuilder.CreateMethodInvocation(
  1338. RuntimeServices_NormalizeStringIndex,
  1339. CodeBuilder.CreateReference(temp),
  1340. slice.Begin)));
  1341. }
  1342. else
  1343. {
  1344. mie = CodeBuilder.CreateMethodInvocation(node.Target, String_Substring_Int, slice.Begin);
  1345. }
  1346. }
  1347. else
  1348. {
  1349. mie = CodeBuilder.CreateMethodInvocation(RuntimeServices_Mid, node.Target, slice.Begin, slice.End);
  1350. }
  1351. node.ParentNode.Replace(node, mie);
  1352. }
  1353. }
  1354. bool IsIndexedProperty(Expression expression)
  1355. {
  1356. IEntity entity = expression.Entity;
  1357. if (null != entity)
  1358. {
  1359. return IsIndexedProperty(entity);
  1360. }
  1361. return false;
  1362. }
  1363. override public void LeaveSlicingExpression(SlicingExpression node)
  1364. {
  1365. if (IsAmbiguous(node.Target.Entity))
  1366. {
  1367. BindIndexedPropertySlicing(node);
  1368. return;
  1369. }
  1370. // target[indices]
  1371. IType targetType = GetExpressionType(node.Target);
  1372. if (TypeSystemServices.IsError(targetType))
  1373. {
  1374. Error(node);
  1375. return;
  1376. }
  1377. if (IsIndexedProperty(node.Target))
  1378. {
  1379. BindIndexedPropertySlicing(node);
  1380. }
  1381. else
  1382. {
  1383. if (targetType.IsArray)
  1384. {
  1385. IArrayType arrayType = (IArrayType)targetType;
  1386. if (arrayType.GetArrayRank() != node.Indices.Count)
  1387. {
  1388. Error(node, CompilerErrorFactory.InvalidArrayRank(node, node.Target.ToString(), arrayType.GetArrayRank(), node.Indices.Count));
  1389. }
  1390. if (AstUtil.IsComplexSlicing(node))
  1391. {
  1392. BindComplexArraySlicing(node);
  1393. }
  1394. else
  1395. {
  1396. if (arrayType.GetArrayRank() > 1)
  1397. {
  1398. BindMultiDimensionalArraySlicing(node);
  1399. }
  1400. else
  1401. {
  1402. BindExpressionType(node, arrayType.GetElementType());
  1403. }
  1404. }
  1405. }
  1406. else
  1407. {
  1408. if (AstUtil.IsComplexSlicing(node))
  1409. {
  1410. if (TypeSystemServices.StringType == targetType)
  1411. {
  1412. BindComplexStringSlicing(node);
  1413. }
  1414. else
  1415. {
  1416. if (TypeSystemServices.ListType.IsAssignableFrom(targetType))
  1417. {
  1418. BindComplexListSlicing(node);
  1419. }
  1420. else
  1421. {
  1422. NotImplemented(node, "complex slicing for anything but lists, arrays and strings");
  1423. }
  1424. }
  1425. }
  1426. else
  1427. {
  1428. IEntity member = targetType.GetDefaultMember();
  1429. if (null == member)
  1430. {
  1431. Error(node, CompilerErrorFactory.TypeDoesNotSupportSlicing(node.Target, targetType.ToString()));
  1432. }
  1433. else
  1434. {
  1435. node.Target = new MemberReferenceExpression(node.LexicalInfo, node.Target, member.Name);
  1436. node.Target.Entity = member;
  1437. // to be resolved later
  1438. node.Target.ExpressionType = Null.Default;
  1439. SliceMember(node, member);
  1440. }
  1441. }
  1442. }
  1443. }
  1444. }
  1445. private void BindIndexedPropertySlicing(SlicingExpression node)
  1446. {
  1447. CheckNoComplexSlicing(node);
  1448. SliceMember(node, node.Target.Entity);
  1449. }
  1450. private bool IsAmbiguous(IEntity entity)
  1451. {
  1452. return null != entity && EntityType.Ambiguous == entity.EntityType;
  1453. }
  1454. bool IsIndexedProperty(IEntity tag)
  1455. {
  1456. return EntityType.Property == tag.EntityType &&
  1457. ((IProperty)tag).GetParameters().Length > 0;
  1458. }
  1459. void BindMultiDimensionalArraySlicing(SlicingExpression node)
  1460. {
  1461. if (AstUtil.IsLhsOfAssignment(node))
  1462. {
  1463. // leave it to LeaveBinaryExpression to resolve
  1464. return;
  1465. }
  1466. MethodInvocationExpression mie = CodeBuilder.CreateMethodInvocation(
  1467. node.Target,
  1468. TypeSystemServices.Map(
  1469. typeof(Array).GetMethod("GetValue", new Type[] { typeof(int[]) })));
  1470. for (int i = 0; i < node.Indices.Count; i++)
  1471. {
  1472. mie.Arguments.Add(node.Indices[i].Begin);
  1473. }
  1474. IType elementType = node.Target.ExpressionType.GetElementType();
  1475. node.ParentNode.Replace(node, CodeBuilder.CreateCast(elementType, mie));
  1476. }
  1477. void SliceMember(SlicingExpression node, IEntity member)
  1478. {
  1479. EnsureRelatedNodeWasVisited(node, member);
  1480. if (AstUtil.IsLhsOfAssignment(node))
  1481. {
  1482. // leave it to LeaveBinaryExpression to resolve
  1483. Bind(node, member);
  1484. return;
  1485. }
  1486. MethodInvocationExpression mie = new MethodInvocationExpression(node.LexicalInfo);
  1487. foreach (Slice index in node.Indices)
  1488. {
  1489. mie.Arguments.Add(index.Begin);
  1490. }
  1491. IMethod getter = null;
  1492. if (EntityType.Ambiguous == member.EntityType)
  1493. {
  1494. IEntity result = ResolveAmbiguousPropertyReference((ReferenceExpression)node.Target, (Ambiguous)member, mie.Arguments);
  1495. IProperty found = result as IProperty;
  1496. if (null != found)
  1497. {
  1498. getter = found.GetGetMethod();
  1499. }
  1500. else if (EntityType.Ambiguous == result.EntityType)
  1501. {
  1502. Error(node);
  1503. return;
  1504. }
  1505. }
  1506. else if (EntityType.Property == member.EntityType)
  1507. {
  1508. getter = ((IProperty)member).GetGetMethod();
  1509. }
  1510. if (null != getter)
  1511. {
  1512. if (AssertParameters(node, getter, mie.Arguments))
  1513. {
  1514. Expression target = GetIndexedPropertySlicingTarget(node);
  1515. mie.Target = CodeBuilder.CreateMemberReference(target, getter);
  1516. BindExpressionType(mie, getter.ReturnType);
  1517. node.ParentNode.Replace(node, mie);
  1518. }
  1519. else
  1520. {
  1521. Error(node);
  1522. }
  1523. }
  1524. else
  1525. {
  1526. NotImplemented(node, "slice for anything but arrays and default properties");
  1527. }
  1528. }
  1529. private Expression GetIndexedPropertySlicingTarget(SlicingExpression node)
  1530. {
  1531. Expression target = node.Target;
  1532. MemberReferenceExpression mre = target as MemberReferenceExpression;
  1533. if (null != mre) return mre.Target;
  1534. return CreateSelfReference();
  1535. }
  1536. override public void LeaveExpressionInterpolationExpression(ExpressionInterpolationExpression node)
  1537. {
  1538. BindExpressionType(node, TypeSystemServices.StringType);
  1539. }
  1540. override public void LeaveListLiteralExpression(ListLiteralExpression node)
  1541. {
  1542. BindExpressionType(node, TypeSystemServices.ListType);
  1543. TypeSystemServices.MapToConcreteExpressionTypes(node.Items);
  1544. }
  1545. override public void OnExtendedGeneratorExpression(ExtendedGeneratorExpression node)
  1546. {
  1547. BlockExpression block = new BlockExpression(node.LexicalInfo);
  1548. Block body = block.Body;
  1549. Expression e = node.Items[0].Expression;
  1550. foreach (GeneratorExpression ge in node.Items)
  1551. {
  1552. ForStatement fs = new ForStatement(ge.LexicalInfo);
  1553. fs.Iterator = ge.Iterator;
  1554. fs.Declarations = ge.Declarations;
  1555. body.Add(fs);
  1556. if (null == ge.Filter)
  1557. {
  1558. body = fs.Block;
  1559. }
  1560. else
  1561. {
  1562. fs.Block.Add(
  1563. NormalizeStatementModifiers.MapStatementModifier(ge.Filter, out body));
  1564. }
  1565. }
  1566. body.Add(new YieldStatement(e.LexicalInfo, e));
  1567. MethodInvocationExpression mie = new MethodInvocationExpression(node.LexicalInfo);
  1568. mie.Target = block;
  1569. Node parentNode = node.ParentNode;
  1570. bool isGenerator = AstUtil.IsListMultiGenerator(parentNode);
  1571. parentNode.Replace(node, mie);
  1572. mie.Accept(this);
  1573. if (isGenerator)
  1574. {
  1575. parentNode.ParentNode.Replace(
  1576. parentNode,
  1577. CodeBuilder.CreateConstructorInvocation(
  1578. TypeSystemServices.Map(ProcessGenerators.List_IEnumerableConstructor),
  1579. mie));
  1580. }
  1581. }
  1582. override public void OnGeneratorExpression(GeneratorExpression node)
  1583. {
  1584. Visit(node.Iterator);
  1585. node.Iterator = ProcessIterator(node.Iterator, node.Declarations);
  1586. EnterNamespace(new DeclarationsNamespace(CurrentNamespace, TypeSystemServices, node.Declarations));
  1587. Visit(node.Filter);
  1588. Visit(node.Expression);
  1589. LeaveNamespace();
  1590. BooClassBuilder generatorType = CreateGeneratorSkeleton(node);
  1591. BindExpressionType(node, generatorType.Entity);
  1592. }
  1593. void CreateGeneratorSkeleton(InternalMethod entity)
  1594. {
  1595. Method method = entity.Method;
  1596. IType itemType = GetGeneratorItemType(entity);
  1597. BooClassBuilder builder = CreateGeneratorSkeleton(method, method, itemType);
  1598. method.DeclaringType.Members.Add(builder.ClassDefinition);
  1599. // TypeSystemServices.AddCompilerGeneratedType(builder.ClassDefinition);
  1600. }
  1601. private IType GetGeneratorItemType(InternalMethod entity)
  1602. {
  1603. IType itemType = null;
  1604. if (CheckGenericGeneratorReturnType(entity.ReturnType))
  1605. {
  1606. itemType = entity.ReturnType.ConstructedInfo.GenericArguments[0];
  1607. }
  1608. if (itemType == null)
  1609. {
  1610. ExpressionCollection yieldExpressions = entity.YieldExpressions;
  1611. itemType = yieldExpressions.Count > 0
  1612. ? GetMostGenericType(yieldExpressions)
  1613. : TypeSystemServices.ObjectType;
  1614. }
  1615. return itemType;
  1616. }
  1617. BooClassBuilder CreateGeneratorSkeleton(GeneratorExpression node)
  1618. {
  1619. BooClassBuilder builder = CreateGeneratorSkeleton(node, _currentMethod.Method, GetConcreteExpressionType(node.Expression));
  1620. _currentMethod.Method.DeclaringType.Members.Add(builder.ClassDefinition);
  1621. return builder;
  1622. }
  1623. protected IType GetConstructedType(IType genericType, IType argType)
  1624. {
  1625. return genericType.GenericInfo.ConstructType(argType);
  1626. }
  1627. BooClassBuilder CreateGeneratorSkeleton(Node sourceNode, Method method, IType generatorItemType)
  1628. {
  1629. // create the class skeleton for type inference to work
  1630. BooClassBuilder builder = CodeBuilder.CreateClass(
  1631. string.Format("{0}${1}", method.Name, _context.AllocIndex()),
  1632. TypeMemberModifiers.Internal|TypeMemberModifiers.Final);
  1633. builder.LexicalInfo = sourceNode.LexicalInfo;
  1634. builder.AddAttribute(CodeBuilder.CreateAttribute(typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute)));
  1635. BooMethodBuilder getEnumeratorBuilder = null;
  1636. if (generatorItemType != TypeSystemServices.VoidType)
  1637. {
  1638. builder.AddBaseType(
  1639. TypeSystemServices.Map(typeof(GenericGenerator<>)).GenericInfo.ConstructType(generatorItemType));
  1640. getEnumeratorBuilder = builder.AddVirtualMethod(
  1641. "GetEnumerator",
  1642. TypeSystemServices.IEnumeratorGenericType.GenericInfo.ConstructType(generatorItemType));
  1643. getEnumeratorBuilder.Method.LexicalInfo = sourceNode.LexicalInfo;
  1644. }
  1645. sourceNode["GeneratorClassBuilder"] = builder;
  1646. sourceNode["GetEnumeratorBuilder"] = getEnumeratorBuilder;
  1647. sourceNode["GeneratorItemType"] = generatorItemType;
  1648. return builder;
  1649. }
  1650. override public void LeaveHashLiteralExpression(HashLiteralExpression node)
  1651. {
  1652. BindExpressionType(node, TypeSystemServices.HashType);
  1653. foreach (ExpressionPair pair in node.Items)
  1654. {
  1655. GetConcreteExpressionType(pair.First);
  1656. GetConcreteExpressionType(pair.Second);
  1657. }
  1658. }
  1659. override public void LeaveArrayLiteralExpression(ArrayLiteralExpression node)
  1660. {
  1661. TypeSystemServices.MapToConcreteExpressionTypes(node.Items);
  1662. IArrayType type = InferArrayType(node);
  1663. BindExpressionType(node, type);
  1664. if (null == node.Type)
  1665. {
  1666. node.Type = (ArrayTypeReference)CodeBuilder.CreateTypeReference(type);
  1667. }
  1668. else
  1669. {
  1670. CheckItems(type.GetElementType(), node.Items);
  1671. }
  1672. }
  1673. private IArrayType InferArrayType(ArrayLiteralExpression node)
  1674. {
  1675. if (null != node.Type) return (IArrayType)node.Type.Entity;
  1676. if (0 == node.Items.Count) return TypeSystemServices.ObjectArrayType;
  1677. return TypeSystemServices.GetArrayType(GetMostGenericType(node.Items), 1);
  1678. }
  1679. override public void LeaveDeclaration(Declaration node)
  1680. {
  1681. if (null == node.Type) return;
  1682. CheckDeclarationType(node.Type);
  1683. }
  1684. override public void LeaveDeclarationStatement(DeclarationStatement node)
  1685. {
  1686. IType type = GetDeclarationType(node);
  1687. AssertDeclarationName(node.Declaration);
  1688. IEntity localInfo = DeclareLocal(node, node.Declaration.Name, type);
  1689. if (null != node.Initializer)
  1690. {
  1691. IType itype = GetExpressionType(node.Initializer);
  1692. AssertTypeCompatibility(node.Initializer, type, itype);
  1693. if (TypeSystemServices.IsNullable(type) && !TypeSystemServices.IsNullable(itype))
  1694. {
  1695. BindNullableInitializer(node, node.Initializer, type);
  1696. }
  1697. node.ReplaceBy(
  1698. new ExpressionStatement(
  1699. CodeBuilder.CreateAssignment(
  1700. node.LexicalInfo,
  1701. CodeBuilder.CreateReference(localInfo),
  1702. node.Initializer)));
  1703. }
  1704. else
  1705. {
  1706. node.ReplaceBy(
  1707. new ExpressionStatement(
  1708. CreateDefaultLocalInitializer(node, localInfo)));
  1709. }
  1710. }
  1711. private IType GetDeclarationType(DeclarationStatement node)
  1712. {
  1713. if (null != node.Declaration.Type) return GetType(node.Declaration.Type);
  1714. return InferDeclarationType(node);
  1715. }
  1716. private IType InferDeclarationType(DeclarationStatement node)
  1717. {
  1718. if (null == node.Initializer) return TypeSystemServices.ObjectType;
  1719. // The boo syntax does not require this check because
  1720. // there's no way to create an untyped declaration statement.
  1721. // This is here to support languages that do allow untyped variable
  1722. // declarations (unityscript is such an example).
  1723. return GetConcreteExpressionType(node.Initializer);
  1724. }
  1725. virtual protected Expression CreateDefaultLocalInitializer(Node sourceNode, IEntity local)
  1726. {
  1727. return CodeBuilder.CreateDefaultInitializer(
  1728. sourceNode.LexicalInfo,
  1729. (InternalLocal)local);
  1730. }
  1731. override public void LeaveExpressionStatement(ExpressionStatement node)
  1732. {
  1733. AssertHasSideEffect(node.Expression);
  1734. }
  1735. override public void OnNullLiteralExpression(NullLiteralExpression node)
  1736. {
  1737. BindExpressionType(node, Null.Default);
  1738. }
  1739. override public void OnSelfLiteralExpression(SelfLiteralExpression node)
  1740. {
  1741. if (null == _currentMethod)
  1742. {
  1743. Error(node, CompilerErrorFactory.SelfOutsideMethod(node));
  1744. }
  1745. else
  1746. {
  1747. if (_currentMethod.IsStatic)
  1748. {
  1749. if (NodeType.MemberReferenceExpression != node.ParentNode.NodeType)
  1750. {
  1751. // if we are inside a MemberReferenceExpression
  1752. // let the MemberReferenceExpression deal with it
  1753. // as it can provide a better message
  1754. Error(CompilerErrorFactory.SelfIsNotValidInStaticMember(node));
  1755. }
  1756. }
  1757. node.Entity = _currentMethod;
  1758. node.ExpressionType = _currentMethod.DeclaringType;
  1759. }
  1760. }
  1761. override public void LeaveTypeofExpression(TypeofExpression node)
  1762. {
  1763. BindExpressionType(node, TypeSystemServices.TypeType);
  1764. }
  1765. override public void LeaveCastExpression(CastExpression node)
  1766. {
  1767. IType fromType = GetExpressionType(node.Target);
  1768. IType toType = GetType(node.Type);
  1769. if (!TypeSystemServices.AreTypesRelated(toType, fromType) &&
  1770. !(toType.IsInterface && !fromType.IsFinal) &&
  1771. !(TypeSystemServices.IsIntegerNumber(toType) && TypeSystemServices.CanBeExplicitlyCastToInteger(fromType)) &&
  1772. !(TypeSystemServices.IsIntegerNumber(fromType) && TypeSystemServices.CanBeExplicitlyCastToInteger(toType)))
  1773. {
  1774. IMethod explicitOperator = TypeSystemServices.FindExplicitConversionOperator(fromType, toType);
  1775. if (null != explicitOperator)
  1776. {
  1777. node.ParentNode.Replace(
  1778. node,
  1779. CodeBuilder.CreateMethodInvocation(
  1780. explicitOperator,
  1781. node.Target));
  1782. return;
  1783. }
  1784. Error(
  1785. CompilerErrorFactory.IncompatibleExpressionType(
  1786. node,
  1787. toType.ToString(),
  1788. fromType.ToString()));
  1789. }
  1790. BindExpressionType(node, toType);
  1791. }
  1792. override public void LeaveTryCastExpression(TryCastExpression node)
  1793. {
  1794. IType target = GetExpressionType(node.Target);
  1795. IType toType = GetType(node.Type);
  1796. if (target.IsValueType)
  1797. {
  1798. Error(CompilerErrorFactory.CantCastToValueType(node.Target, target.ToString()));
  1799. }
  1800. else if (toType.IsValueType)
  1801. {
  1802. Error(CompilerErrorFactory.CantCastToValueType(node.Type, toType.ToString()));
  1803. }
  1804. BindExpressionType(node, toType);
  1805. }
  1806. protected Expression CreateMemberReferenceTarget(Node sourceNode, IMember member)
  1807. {
  1808. Expression target = null;
  1809. if (member.IsStatic)
  1810. {
  1811. target = new ReferenceExpression(sourceNode.LexicalInfo, member.DeclaringType.FullName);
  1812. Bind(target, member.DeclaringType);
  1813. }
  1814. else
  1815. {
  1816. //check if found entity can't possibly be a member of self:
  1817. if (member.DeclaringType != CurrentType
  1818. && !(CurrentType.IsSubclassOf(member.DeclaringType)))
  1819. {
  1820. Error(
  1821. CompilerErrorFactory.InstanceRequired(sourceNode,
  1822. member.DeclaringType.ToString(),
  1823. member.Name));
  1824. }
  1825. target = new SelfLiteralExpression(sourceNode.LexicalInfo);
  1826. }
  1827. BindExpressionType(target, member.DeclaringType);
  1828. return target;
  1829. }
  1830. protected MemberReferenceExpression MemberReferenceFromReference(ReferenceExpression node, IMember member)
  1831. {
  1832. MemberReferenceExpression memberRef = new MemberReferenceExpression(node.LexicalInfo);
  1833. memberRef.Name = node.Name;
  1834. memberRef.Target = CreateMemberReferenceTarget(node, member);
  1835. return memberRef;
  1836. }
  1837. void ResolveMemberInfo(ReferenceExpression node, IMember member)
  1838. {
  1839. MemberReferenceExpression memberRef = MemberReferenceFromReference(node, member);
  1840. Bind(memberRef, member);
  1841. node.ParentNode.Replace(node, memberRef);
  1842. Visit(memberRef);
  1843. }
  1844. override public void OnRELiteralExpression(RELiteralExpression node)
  1845. {
  1846. if (null != node.Entity)
  1847. {
  1848. return;
  1849. }
  1850. IType type = TypeSystemServices.RegexType;
  1851. BindExpressionType(node, type);
  1852. if (NodeType.Field != node.ParentNode.NodeType)
  1853. {
  1854. ReplaceByStaticFieldReference(node, "$re$" + _context.AllocIndex(), type);
  1855. }
  1856. }
  1857. void ReplaceByStaticFieldReference(Expression node, string fieldName, IType type)
  1858. {
  1859. Node parent = node.ParentNode;
  1860. Field field = CodeBuilder.CreateField(fieldName, type);
  1861. field.Modifiers = TypeMemberModifiers.Internal|TypeMemberModifiers.Static;
  1862. field.Initializer = node;
  1863. _currentMethod.Method.DeclaringType.Members.Add(field);
  1864. parent.Replace(node, CodeBuilder.CreateReference(field));
  1865. AddFieldInitializerToStaticConstructor(0, field);
  1866. }
  1867. override public void LeaveGenericReferenceExpression(GenericReferenceExpression node)
  1868. {
  1869. if (node.Target.Entity == null || TypeSystemServices.IsError(node.Target.Entity))
  1870. {
  1871. BindExpressionType(node, TypeSystemServices.ErrorEntity);
  1872. return;
  1873. }
  1874. IEntity entity = NameResolutionService.ResolveGenericReferenceExpression(node, node.Target.Entity);
  1875. Bind(node, entity);
  1876. if (entity.EntityType == EntityType.Type)
  1877. {
  1878. BindTypeReferenceExpressionType(node, (IType)entity);
  1879. }
  1880. else if (entity.EntityType == EntityType.Method)
  1881. {
  1882. if (null == (node.Target as MemberReferenceExpression)) //no self.
  1883. {
  1884. MemberReferenceExpression target =
  1885. CodeBuilder.MemberReferenceForEntity(
  1886. CreateSelfReference(),
  1887. entity);
  1888. node.Replace(node.Target, target);
  1889. }
  1890. BindExpressionType(node, ((IMethod)entity).Type);
  1891. }
  1892. }
  1893. override public void OnReferenceExpression(ReferenceExpression node)
  1894. {
  1895. if (AlreadyBound(node)) return;
  1896. IEntity entity = ResolveName(node, node.Name);
  1897. if (null == entity)
  1898. {
  1899. Error(node);
  1900. return;
  1901. }
  1902. // BOO-314 - if we are trying to invoke
  1903. // something, let's make sure it is
  1904. // something callable, otherwise, let's
  1905. // try to find something callable
  1906. if (AstUtil.IsTargetOfMethodInvocation(node)
  1907. && !IsCallableEntity(entity))
  1908. {
  1909. IEntity callable = ResolveCallable(node);
  1910. if (null != callable) entity = callable;
  1911. }
  1912. IMember member = entity as IMember;
  1913. if (null != member)
  1914. {
  1915. if (IsExtensionMethod(member))
  1916. {
  1917. Bind(node, member);
  1918. return;
  1919. }
  1920. ResolveMemberInfo(node, member);
  1921. return;
  1922. }
  1923. EnsureRelatedNodeWasVisited(node, entity);
  1924. node.Entity = entity;
  1925. PostProcessReferenceExpression(node);
  1926. }
  1927. private static bool AlreadyBound(ReferenceExpression node)
  1928. {
  1929. return null != node.ExpressionType;
  1930. }
  1931. private IEntity ResolveCallable(ReferenceExpression node)
  1932. {
  1933. return NameResolutionService.Resolve(node.Name,
  1934. EntityType.Type
  1935. | EntityType.Method
  1936. | EntityType.BuiltinFunction
  1937. | EntityType.Event);
  1938. }
  1939. private bool IsCallableEntity(IEntity entity)
  1940. {
  1941. switch (entity.EntityType)
  1942. {
  1943. case EntityType.Method:
  1944. case EntityType.Type:
  1945. case EntityType.Event:
  1946. case EntityType.BuiltinFunction:
  1947. case EntityType.Constructor:
  1948. return true;
  1949. case EntityType.Ambiguous:
  1950. // let overload resolution deal with it
  1951. return true;
  1952. }
  1953. ITypedEntity typed = entity as ITypedEntity;
  1954. return null == typed ? false : TypeSystemServices.IsCallable(typed.Type);
  1955. }
  1956. void PostProcessReferenceExpression(ReferenceExpression node)
  1957. {
  1958. IEntity tag = GetEntity(node);
  1959. switch (tag.EntityType)
  1960. {
  1961. case EntityType.Type:
  1962. {
  1963. BindTypeReferenceExpressionType(node, (IType)tag);
  1964. break;
  1965. }
  1966. case EntityType.Ambiguous:
  1967. {
  1968. tag = ResolveAmbiguousReference(node, (Ambiguous)tag);
  1969. IMember resolvedMember = tag as IMember;
  1970. if (null != resolvedMember)
  1971. {
  1972. ResolveMemberInfo(node, resolvedMember);
  1973. break;
  1974. }
  1975. if (tag is IType)
  1976. {
  1977. BindTypeReferenceExpressionType(node, (IType)tag);
  1978. break;
  1979. }
  1980. if (!AstUtil.IsTargetOfMethodInvocation(node)
  1981. && !AstUtil.IsTargetOfSlicing(node)
  1982. && !AstUtil.IsLhsOfAssignment(node))
  1983. {
  1984. Error(node, CompilerErrorFactory.AmbiguousReference(
  1985. node,
  1986. node.Name,
  1987. ((Ambiguous)tag).Entities));
  1988. }
  1989. break;
  1990. }
  1991. case EntityType.Namespace:
  1992. {
  1993. if (IsStandaloneReference(node))
  1994. {
  1995. Error(node, CompilerErrorFactory.NamespaceIsNotAnExpression(node, tag.Name));
  1996. }
  1997. break;
  1998. }
  1999. case EntityType.Parameter:
  2000. case EntityType.Local:
  2001. {
  2002. ILocalEntity local = (ILocalEntity)node.Entity;
  2003. local.IsUsed = true;
  2004. BindExpressionType(node, local.Type);
  2005. break;
  2006. }
  2007. default:
  2008. {
  2009. if (EntityType.BuiltinFunction == tag.EntityType)
  2010. {
  2011. CheckBuiltinUsage(node, tag);
  2012. }
  2013. else
  2014. {
  2015. if (node.ExpressionType == null)
  2016. {
  2017. BindExpressionType(node, ((ITypedEntity)tag).Type);
  2018. }
  2019. }
  2020. break;
  2021. }
  2022. }
  2023. }
  2024. protected virtual void BindTypeReferenceExpressionType(Expression node, IType type)
  2025. {
  2026. if (IsStandaloneReference(node))
  2027. {
  2028. BindExpressionType(node, TypeSystemServices.TypeType);
  2029. }
  2030. else
  2031. {
  2032. BindExpressionType(node, type);
  2033. }
  2034. }
  2035. protected virtual void CheckBuiltinUsage(ReferenceExpression node, IEntity entity)
  2036. {
  2037. if (!AstUtil.IsTargetOfMethodInvocation(node))
  2038. {
  2039. Error(node, CompilerErrorFactory.BuiltinCannotBeUsedAsExpression(node, entity.Name));
  2040. }
  2041. }
  2042. override public bool EnterMemberReferenceExpression(MemberReferenceExpression node)
  2043. {
  2044. return null == node.ExpressionType;
  2045. }
  2046. INamespace GetReferenceNamespace(MemberReferenceExpression expression)
  2047. {
  2048. Expression target = expression.Target;
  2049. INamespace ns = target.ExpressionType;
  2050. if (null != ns)
  2051. {
  2052. return GetConcreteExpressionType(target);
  2053. }
  2054. return (INamespace)GetEntity(target);
  2055. }
  2056. protected virtual void LeaveExplodeExpression(UnaryExpression node)
  2057. {
  2058. IType type = GetConcreteExpressionType(node.Operand);
  2059. if (!type.IsArray)
  2060. {
  2061. Error(CompilerErrorFactory.ExplodedExpressionMustBeArray(node));
  2062. }
  2063. BindExpressionType(node, type);
  2064. }
  2065. override public void LeaveMemberReferenceExpression(MemberReferenceExpression node)
  2066. {
  2067. _context.TraceVerbose("LeaveMemberReferenceExpression: {0}", node);
  2068. if (TypeSystemServices.IsError(node.Target))
  2069. {
  2070. Error(node);
  2071. }
  2072. else
  2073. {
  2074. ProcessMemberReferenceExpression(node);
  2075. }
  2076. }
  2077. virtual protected void MemberNotFound(MemberReferenceExpression node, INamespace ns)
  2078. {
  2079. EntityType et = (!AstUtil.IsTargetOfMethodInvocation(node)) ? EntityType.Any : EntityType.Method;
  2080. Error(node,
  2081. CompilerErrorFactory.MemberNotFound(node,
  2082. (((IEntity)ns).ToString()),
  2083. NameResolutionService.GetMostSimilarMemberName(ns, node.Name, et)));
  2084. }
  2085. virtual protected bool ShouldRebindMember(IEntity entity)
  2086. {
  2087. return entity == null;
  2088. }
  2089. IEntity ResolveMember(MemberReferenceExpression node)
  2090. {
  2091. IEntity member = node.Entity;
  2092. if (!ShouldRebindMember(member)) return member;
  2093. INamespace ns = GetReferenceNamespace(node);
  2094. member = NameResolutionService.Resolve(ns, node.Name);
  2095. if (null != member)
  2096. {
  2097. IAccessibleMember accessible = member as IAccessibleMember;
  2098. if (null != accessible && !IsAccessible(accessible))
  2099. {
  2100. IEntity extension = NameResolutionService.ResolveExtension(ns, node.Name);
  2101. if (null != extension) return extension;
  2102. }
  2103. return member;
  2104. }
  2105. member = NameResolutionService.ResolveExtension(ns, node.Name);
  2106. if (null == member) MemberNotFound(node, ns);
  2107. return member;
  2108. }
  2109. virtual protected void ProcessMemberReferenceExpression(MemberReferenceExpression node)
  2110. {
  2111. IEntity member = ResolveMember(node);
  2112. if (null == member) return;
  2113. if (EntityType.Ambiguous == member.EntityType)
  2114. {
  2115. member = ResolveAmbiguousReference(node, (Ambiguous)member);
  2116. }
  2117. EnsureRelatedNodeWasVisited(node, member);
  2118. if (EntityType.Namespace == member.EntityType)
  2119. {
  2120. string ns = null;
  2121. foreach (Import import in _currentModule.Imports)
  2122. {
  2123. if (import.NamespaceUsed) continue;
  2124. if (null == ns) ns = node.ToCodeString();
  2125. if (import.Namespace == ns)
  2126. {
  2127. import.NamespaceUsed = true;
  2128. break;
  2129. }
  2130. }
  2131. }
  2132. IMember memberInfo = member as IMember;
  2133. if (null != memberInfo)
  2134. {
  2135. if (!AssertTargetContext(node, memberInfo))
  2136. {
  2137. Error(node);
  2138. return;
  2139. }
  2140. if (EntityType.Method != memberInfo.EntityType)
  2141. {
  2142. BindExpressionType(node, GetInferredType(memberInfo));
  2143. }
  2144. else
  2145. {
  2146. BindExpressionType(node, memberInfo.Type);
  2147. }
  2148. }
  2149. if (EntityType.Property == member.EntityType)
  2150. {
  2151. IProperty property = (IProperty)member;
  2152. if (IsIndexedProperty(property))
  2153. {
  2154. if (!AstUtil.IsTargetOfSlicing(node)
  2155. && (!property.IsExtension || property.GetParameters().Length > 1))
  2156. {
  2157. Error(node, CompilerErrorFactory.PropertyRequiresParameters(
  2158. AstUtil.GetMemberAnchor(node),
  2159. member.FullName));
  2160. return;
  2161. }
  2162. }
  2163. if (IsWriteOnlyProperty(property) && !IsBeingAssignedTo(node))
  2164. {
  2165. Error(node, CompilerErrorFactory.PropertyIsWriteOnly(
  2166. AstUtil.GetMemberAnchor(node),
  2167. member.FullName));
  2168. }
  2169. }
  2170. else if (EntityType.Event == member.EntityType)
  2171. {
  2172. if (!AstUtil.IsTargetOfMethodInvocation(node) &&
  2173. !AstUtil.IsLhsOfInPlaceAddSubtract(node))
  2174. {
  2175. if (CurrentType == memberInfo.DeclaringType)
  2176. {
  2177. InternalEvent ev = (InternalEvent)member;
  2178. node.Name = ev.BackingField.Name;
  2179. node.Entity = ev.BackingField;
  2180. BindExpressionType(node, ev.BackingField.Type);
  2181. return;
  2182. }
  2183. else
  2184. {
  2185. Error(node,
  2186. CompilerErrorFactory.EventIsNotAnExpression(node,
  2187. member.FullName));
  2188. }
  2189. }
  2190. }
  2191. Bind(node, member);
  2192. PostProcessReferenceExpression(node);
  2193. }
  2194. private bool IsBeingAssignedTo(MemberReferenceExpression node)
  2195. {
  2196. Node current = node;
  2197. Node parent = current.ParentNode;
  2198. while (!(parent is BinaryExpression))
  2199. {
  2200. current = parent;
  2201. parent = parent.ParentNode;
  2202. if (parent == null || !(parent is Expression)) return false;
  2203. }
  2204. return ((BinaryExpression)parent).Left == current;
  2205. }
  2206. private bool IsWriteOnlyProperty(IProperty property)
  2207. {
  2208. return null == property.GetGetMethod();
  2209. }
  2210. private IEntity ResolveAmbiguousLValue(Expression sourceNode, Ambiguous candidates, Expression rvalue)
  2211. {
  2212. if (!candidates.AllEntitiesAre(EntityType.Property)) return null;
  2213. IEntity[] entities = candidates.Entities;
  2214. IEntity[] getters = GetSetMethods(entities);
  2215. ExpressionCollection args = new ExpressionCollection();
  2216. args.Add(rvalue);
  2217. IEntity found = GetCorrectCallableReference(sourceNode, args, getters);
  2218. if (null != found && EntityType.Method == found.EntityType)
  2219. {
  2220. IProperty property = (IProperty)entities[GetIndex(getters, found)];
  2221. BindProperty(sourceNode, property);
  2222. return property;
  2223. }
  2224. return null;
  2225. }
  2226. private static void BindProperty(Expression expression, IProperty property)
  2227. {
  2228. expression.Entity = property;
  2229. expression.ExpressionType = property.Type;
  2230. }
  2231. private IEntity ResolveAmbiguousReference(ReferenceExpression node, Ambiguous candidates)
  2232. {
  2233. if (!AstUtil.IsTargetOfSlicing(node)
  2234. && !AstUtil.IsLhsOfAssignment(node))
  2235. {
  2236. if (candidates.AllEntitiesAre(EntityType.Property))
  2237. {
  2238. return ResolveAmbiguousPropertyReference(node, candidates, EmptyExpressionCollection);
  2239. }
  2240. else if (candidates.AllEntitiesAre(EntityType.Method))
  2241. {
  2242. return ResolveAmbiguousMethodReference(node, candidates, EmptyExpressionCollection);
  2243. }
  2244. else if (candidates.AllEntitiesAre(EntityType.Type))
  2245. {
  2246. return ResolveAmbiguousTypeReference(node, candidates);
  2247. }
  2248. }
  2249. return ResolveAmbiguousReferenceByAccessibility(candidates);
  2250. }
  2251. private IEntity ResolveAmbiguousMethodReference(ReferenceExpression node, Ambiguous candidates, ExpressionCollection args)
  2252. {
  2253. //BOO-656
  2254. if (!AstUtil.IsTargetOfMethodInvocation(node)
  2255. && !AstUtil.IsTargetOfSlicing(node)
  2256. && !AstUtil.IsLhsOfAssignment(node))
  2257. {
  2258. return candidates.Entities[0];
  2259. }
  2260. return candidates;
  2261. }
  2262. private IEntity ResolveAmbiguousPropertyReference(ReferenceExpression node, Ambiguous candidates, ExpressionCollection args)
  2263. {
  2264. IEntity[] entities = candidates.Entities;
  2265. IEntity[] getters = GetGetMethods(entities);
  2266. IEntity found = GetCorrectCallableReference(node, args, getters);
  2267. if (null != found && EntityType.Method == found.EntityType)
  2268. {
  2269. IProperty property = (IProperty)entities[GetIndex(getters, found)];
  2270. BindProperty(node, property);
  2271. return property;
  2272. }
  2273. return candidates;
  2274. }
  2275. private IEntity ResolveAmbiguousTypeReference(ReferenceExpression node, Ambiguous candidates)
  2276. {
  2277. bool isGenericReference = (node.ParentNode is GenericReferenceExpression);
  2278. List matches = new List();
  2279. foreach (IEntity candidate in candidates.Entities)
  2280. {
  2281. IType type = candidate as IType;
  2282. bool isGenericType = (type != null && type.GenericInfo != null);
  2283. if (isGenericType == isGenericReference)
  2284. {
  2285. matches.Add(candidate);
  2286. }
  2287. }
  2288. if (matches.Count == 1)
  2289. {
  2290. Bind(node, (IEntity)matches[0]);
  2291. }
  2292. else
  2293. {
  2294. Bind(node, new Ambiguous(matches));
  2295. }
  2296. return node.Entity;
  2297. }
  2298. private IEntity ResolveAmbiguousReferenceByAccessibility(Ambiguous candidates)
  2299. {
  2300. List newEntities = new List();
  2301. foreach (IEntity entity in candidates.Entities)
  2302. {
  2303. if (!IsInaccessible(entity))
  2304. { newEntities.Add(entity); }
  2305. }
  2306. if (newEntities.Count == 1)
  2307. { return (IEntity)newEntities[0]; }
  2308. return new Ambiguous(newEntities);
  2309. }
  2310. private int GetIndex(IEntity[] entities, IEntity entity)
  2311. {
  2312. for (int i=0; i<entities.Length; ++i)
  2313. {
  2314. if (entities[i] == entity) return i;
  2315. }
  2316. throw new ArgumentException("entity");
  2317. }
  2318. override public void LeaveUnlessStatement(UnlessStatement node)
  2319. {
  2320. node.Condition = AssertBoolContext(node.Condition);
  2321. }
  2322. override public void LeaveIfStatement(IfStatement node)
  2323. {
  2324. node.Condition = AssertBoolContext(node.Condition);
  2325. }
  2326. override public void LeaveConditionalExpression(ConditionalExpression node)
  2327. {
  2328. node.Condition = AssertBoolContext(node.Condition);
  2329. IType trueType = GetExpressionType(node.TrueValue);
  2330. IType falseType = GetExpressionType(node.FalseValue);
  2331. BindExpressionType(node, GetMostGenericType(trueType, falseType));
  2332. }
  2333. override public bool EnterWhileStatement(WhileStatement node)
  2334. {
  2335. return true;
  2336. }
  2337. override public void LeaveWhileStatement(WhileStatement node)
  2338. {
  2339. node.Condition = AssertBoolContext(node.Condition);
  2340. }
  2341. override public void LeaveYieldStatement(YieldStatement node)
  2342. {
  2343. if (EntityType.Constructor == _currentMethod.EntityType)
  2344. {
  2345. Error(CompilerErrorFactory.YieldInsideConstructor(node));
  2346. }
  2347. else
  2348. {
  2349. _currentMethod.AddYieldStatement(node);
  2350. }
  2351. }
  2352. override public void LeaveReturnStatement(ReturnStatement node)
  2353. {
  2354. if (null == node.Expression) return;
  2355. // forces anonymous types to be correctly
  2356. // instantiated
  2357. IType expressionType = GetConcreteExpressionType(node.Expression);
  2358. if (TypeSystemServices.VoidType == expressionType
  2359. && node.ContainsAnnotation(OptionalReturnStatementAnnotation))
  2360. {
  2361. node.ParentNode.Replace(
  2362. node,
  2363. new ExpressionStatement(node.Expression));
  2364. return;
  2365. }
  2366. IType returnType = _currentMethod.ReturnType;
  2367. if (TypeSystemServices.IsUnknown(returnType))
  2368. {
  2369. _currentMethod.AddReturnExpression(node.Expression);
  2370. }
  2371. else
  2372. {
  2373. AssertTypeCompatibility(node.Expression, returnType, expressionType);
  2374. }
  2375. }
  2376. protected Expression GetCorrectIterator(Expression iterator)
  2377. {
  2378. IType type = GetExpressionType(iterator);
  2379. if (TypeSystemServices.IsError(type))
  2380. {
  2381. return iterator;
  2382. }
  2383. if (!TypeSystemServices.IEnumerableType.IsAssignableFrom(type) &&
  2384. !TypeSystemServices.IEnumeratorType.IsAssignableFrom(type))
  2385. {
  2386. if (IsRuntimeIterator(type))
  2387. {
  2388. if (IsTextReader(type))
  2389. {
  2390. return CodeBuilder.CreateMethodInvocation(TextReaderEnumerator_lines, iterator);
  2391. }
  2392. else
  2393. {
  2394. return CodeBuilder.CreateMethodInvocation(RuntimeServices_GetEnumerable, iterator);
  2395. }
  2396. }
  2397. else
  2398. {
  2399. IMethod method = ResolveGetEnumerator(iterator, type);
  2400. if (null == method)
  2401. {
  2402. Error(CompilerErrorFactory.InvalidIteratorType(iterator, type.ToString()));
  2403. }
  2404. else
  2405. {
  2406. return CodeBuilder.CreateMethodInvocation(iterator, method);
  2407. }
  2408. }
  2409. }
  2410. return iterator;
  2411. }
  2412. IMethod ResolveGetEnumerator(Node sourceNode, IType type)
  2413. {
  2414. IMethod method = ResolveMethod(type, "GetEnumerator");
  2415. if (null != method)
  2416. {
  2417. EnsureRelatedNodeWasVisited(sourceNode, method);
  2418. if (0 == method.GetParameters().Length &&
  2419. method.ReturnType.IsSubclassOf(TypeSystemServices.IEnumeratorType))
  2420. {
  2421. return method;
  2422. }
  2423. }
  2424. return null;
  2425. }
  2426. /// <summary>
  2427. /// Process a iterator and its declarations and returns a new iterator
  2428. /// expression if necessary.
  2429. /// </summary>
  2430. protected Expression ProcessIterator(Expression iterator, DeclarationCollection declarations)
  2431. {
  2432. iterator = GetCorrectIterator(iterator);
  2433. ProcessDeclarationsForIterator(declarations, GetExpressionType(iterator));
  2434. return iterator;
  2435. }
  2436. public override void OnGotoStatement(GotoStatement node)
  2437. {
  2438. // don't try to resolve label references
  2439. }
  2440. override public void OnForStatement(ForStatement node)
  2441. {
  2442. Visit(node.Iterator);
  2443. node.Iterator = ProcessIterator(node.Iterator, node.Declarations);
  2444. VisitForStatementBlock(node);
  2445. }
  2446. protected void VisitForStatementBlock(ForStatement node)
  2447. {
  2448. EnterForNamespace(node);
  2449. Visit(node.Block);
  2450. Visit(node.OrBlock);
  2451. Visit(node.ThenBlock);
  2452. LeaveNamespace();
  2453. }
  2454. private void EnterForNamespace(ForStatement node)
  2455. {
  2456. EnterNamespace(new DeclarationsNamespace(CurrentNamespace, TypeSystemServices, node.Declarations));
  2457. }
  2458. override public void OnUnpackStatement(UnpackStatement node)
  2459. {
  2460. Visit(node.Expression);
  2461. node.Expression = GetCorrectIterator(node.Expression);
  2462. IType defaultDeclarationType = GetEnumeratorItemType(GetExpressionType(node.Expression));
  2463. foreach (Declaration d in node.Declarations)
  2464. {
  2465. bool declareNewVariable = d.Type != null;
  2466. GetDeclarationType(defaultDeclarationType, d);
  2467. if (declareNewVariable)
  2468. {
  2469. AssertUniqueLocal(d);
  2470. }
  2471. else
  2472. {
  2473. IEntity tag = NameResolutionService.Resolve(d.Name);
  2474. if (null != tag)
  2475. {
  2476. Bind(d, tag);
  2477. AssertLValue(d);
  2478. continue;
  2479. }
  2480. }
  2481. DeclareLocal(d, false);
  2482. }
  2483. }
  2484. override public void LeaveRaiseStatement(RaiseStatement node)
  2485. {
  2486. if (node.Exception == null) return;
  2487. IType exceptionType = GetExpressionType(node.Exception);
  2488. if (TypeSystemServices.StringType == exceptionType)
  2489. {
  2490. node.Exception = CodeBuilder.CreateConstructorInvocation(
  2491. node.Exception.LexicalInfo,
  2492. Exception_StringConstructor,
  2493. node.Exception);
  2494. }
  2495. else if (!TypeSystemServices.IsValidException(exceptionType))
  2496. {
  2497. Error(CompilerErrorFactory.InvalidRaiseArgument(node.Exception,
  2498. exceptionType.ToString()));
  2499. }
  2500. }
  2501. override public void OnExceptionHandler(ExceptionHandler node)
  2502. {
  2503. bool untypedException = (node.Flags & ExceptionHandlerFlags.Untyped) == ExceptionHandlerFlags.Untyped;
  2504. bool anonymousException = (node.Flags & ExceptionHandlerFlags.Anonymous) == ExceptionHandlerFlags.Anonymous;
  2505. bool filterHandler = (node.Flags & ExceptionHandlerFlags.Filter) == ExceptionHandlerFlags.Filter;
  2506. if (untypedException)
  2507. {
  2508. // If untyped, set the handler to except System.Exception
  2509. node.Declaration.Type = CodeBuilder.CreateTypeReference(TypeSystemServices.ExceptionType);
  2510. }
  2511. else
  2512. {
  2513. Visit(node.Declaration.Type);
  2514. // Require typed exception handlers to except only
  2515. // exceptions at least as derived as System.Exception
  2516. if(!TypeSystemServices.IsValidException(GetType(node.Declaration.Type)))
  2517. {
  2518. Errors.Add(CompilerErrorFactory.InvalidExceptArgument(node.Declaration.Type, GetType(node.Declaration.Type).FullName));
  2519. }
  2520. }
  2521. if(!anonymousException)
  2522. {
  2523. // If the exception is not anonymous, place it into a
  2524. // local variable and enter a new namespace
  2525. node.Declaration.Entity = DeclareLocal(node.Declaration, node.Declaration.Name, GetType(node.Declaration.Type), true);
  2526. EnterNamespace(new DeclarationsNamespace(CurrentNamespace, TypeSystemServices, node.Declaration));
  2527. }
  2528. try
  2529. {
  2530. // The filter handler has access to the exception if it
  2531. // is not anonymous, so it is protected to ensure
  2532. // any exception in the filter condition (a big no-no)
  2533. // will still clean up the namespace if necessary
  2534. if (filterHandler)
  2535. {
  2536. Visit(node.FilterCondition);
  2537. }
  2538. Visit(node.Block);
  2539. }
  2540. finally
  2541. {
  2542. // Clean up the namespace if necessary
  2543. if(!anonymousException)
  2544. {
  2545. LeaveNamespace();
  2546. }
  2547. }
  2548. }
  2549. protected virtual bool IsValidIncrementDecrementOperand(Expression e)
  2550. {
  2551. IType type = GetExpressionType(e);
  2552. if (TypeSystemServices.IsNullable(type))
  2553. {
  2554. type = TypeSystemServices.GetNullableUnderlyingType(type);
  2555. }
  2556. return IsNumber(type) || TypeSystemServices.IsDuckType(type);
  2557. }
  2558. void LeaveIncrementDecrement(UnaryExpression node)
  2559. {
  2560. if (AssertLValue(node.Operand))
  2561. {
  2562. if (!IsValidIncrementDecrementOperand(node.Operand))
  2563. {
  2564. InvalidOperatorForType(node);
  2565. }
  2566. else
  2567. {
  2568. ExpandIncrementDecrement(node);
  2569. }
  2570. }
  2571. else
  2572. {
  2573. Error(node);
  2574. }
  2575. }
  2576. void ExpandIncrementDecrement(UnaryExpression node)
  2577. {
  2578. Node expansion = null;
  2579. if (IsArraySlicing(node.Operand))
  2580. {
  2581. expansion = ExpandIncrementDecrementArraySlicing(node);
  2582. }
  2583. else
  2584. {
  2585. expansion = ExpandSimpleIncrementDecrement(node);
  2586. }
  2587. node.ParentNode.Replace(node, expansion);
  2588. Visit(expansion);
  2589. }
  2590. Expression ExpandIncrementDecrementArraySlicing(UnaryExpression node)
  2591. {
  2592. SlicingExpression slicing = (SlicingExpression)node.Operand;
  2593. CheckNoComplexSlicing(slicing);
  2594. Visit(slicing);
  2595. return CreateSideEffectAwareSlicingOperation(
  2596. node.LexicalInfo,
  2597. GetEquivalentBinaryOperator(node.Operator),
  2598. slicing,
  2599. CodeBuilder.CreateIntegerLiteral(1),
  2600. DeclareOldValueTempIfNeeded(node));
  2601. }
  2602. private Expression CreateSideEffectAwareSlicingOperation(LexicalInfo lexicalInfo, BinaryOperatorType binaryOperator, SlicingExpression lvalue, Expression rvalue, InternalLocal returnValue)
  2603. {
  2604. MethodInvocationExpression eval = CodeBuilder.CreateEvalInvocation(lexicalInfo);
  2605. if (HasSideEffect(lvalue.Target))
  2606. {
  2607. InternalLocal temp = AddInitializedTempLocal(eval, lvalue.Target);
  2608. lvalue.Target = CodeBuilder.CreateReference(temp);
  2609. }
  2610. foreach (Slice slice in lvalue.Indices)
  2611. {
  2612. Expression index = slice.Begin;
  2613. if (HasSideEffect(index))
  2614. {
  2615. InternalLocal temp = AddInitializedTempLocal(eval, index);
  2616. slice.Begin = CodeBuilder.CreateReference(temp);
  2617. }
  2618. }
  2619. BinaryExpression addition = CodeBuilder.CreateBoundBinaryExpression(
  2620. GetExpressionType(lvalue),
  2621. binaryOperator,
  2622. CloneOrAssignToTemp(returnValue, lvalue),
  2623. rvalue);
  2624. Expression expansion = CodeBuilder.CreateAssignment(
  2625. lvalue.CloneNode(),
  2626. addition);
  2627. // Resolve operator overloads if any
  2628. BindArithmeticOperator(addition);
  2629. if (eval.Arguments.Count > 0 || null != returnValue)
  2630. {
  2631. eval.Arguments.Add(expansion);
  2632. if (null != returnValue)
  2633. {
  2634. eval.Arguments.Add(CodeBuilder.CreateReference(returnValue));
  2635. }
  2636. BindExpressionType(eval, GetExpressionType(lvalue));
  2637. expansion = eval;
  2638. }
  2639. return expansion;
  2640. }
  2641. InternalLocal AddInitializedTempLocal(MethodInvocationExpression eval, Expression initializer)
  2642. {
  2643. InternalLocal temp = DeclareTempLocal(GetExpressionType(initializer));
  2644. eval.Arguments.Add(
  2645. CodeBuilder.CreateAssignment(
  2646. CodeBuilder.CreateReference(temp),
  2647. initializer));
  2648. return temp;
  2649. }
  2650. InternalLocal DeclareOldValueTempIfNeeded(UnaryExpression node)
  2651. {
  2652. return AstUtil.IsPostUnaryOperator(node.Operator)
  2653. ? DeclareTempLocal(GetExpressionType(node.Operand))
  2654. : null;
  2655. }
  2656. Expression ExpandSimpleIncrementDecrement(UnaryExpression node)
  2657. {
  2658. InternalLocal oldValue = DeclareOldValueTempIfNeeded(node);
  2659. BinaryExpression addition = CodeBuilder.CreateBoundBinaryExpression(
  2660. GetExpressionType(node.Operand),
  2661. GetEquivalentBinaryOperator(node.Operator),
  2662. CloneOrAssignToTemp(oldValue, node.Operand),
  2663. CodeBuilder.CreateIntegerLiteral(1));
  2664. BinaryExpression assign = CodeBuilder.CreateAssignment(
  2665. node.LexicalInfo,
  2666. node.Operand,
  2667. addition);
  2668. // Resolve operator overloads if any
  2669. BindArithmeticOperator(addition);
  2670. return null == oldValue
  2671. ? (Expression) assign
  2672. : CodeBuilder.CreateEvalInvocation(
  2673. node.LexicalInfo,
  2674. assign,
  2675. CodeBuilder.CreateReference(oldValue));
  2676. }
  2677. Expression CloneOrAssignToTemp(InternalLocal temp, Expression operand)
  2678. {
  2679. return null == temp
  2680. ? operand.CloneNode()
  2681. : CodeBuilder.CreateAssignment(
  2682. CodeBuilder.CreateReference(temp),
  2683. operand.CloneNode());
  2684. }
  2685. BinaryOperatorType GetEquivalentBinaryOperator(UnaryOperatorType op)
  2686. {
  2687. return op == UnaryOperatorType.Increment || op == UnaryOperatorType.PostIncrement
  2688. ? BinaryOperatorType.Addition
  2689. : BinaryOperatorType.Subtraction;
  2690. }
  2691. UnaryOperatorType GetRelatedPreOperator(UnaryOperatorType op)
  2692. {
  2693. switch (op)
  2694. {
  2695. case UnaryOperatorType.PostIncrement:
  2696. {
  2697. return UnaryOperatorType.Increment;
  2698. }
  2699. case UnaryOperatorType.PostDecrement:
  2700. {
  2701. return UnaryOperatorType.Decrement;
  2702. }
  2703. }
  2704. throw new ArgumentException("op");
  2705. }
  2706. override public bool EnterUnaryExpression(UnaryExpression node)
  2707. {
  2708. if (AstUtil.IsPostUnaryOperator(node.Operator))
  2709. {
  2710. if (NodeType.ExpressionStatement == node.ParentNode.NodeType)
  2711. {
  2712. // nothing to do, a post operator inside a statement
  2713. // behaves just like its equivalent pre operator
  2714. node.Operator = GetRelatedPreOperator(node.Operator);
  2715. }
  2716. }
  2717. return true;
  2718. }
  2719. override public void LeaveUnaryExpression(UnaryExpression node)
  2720. {
  2721. switch (node.Operator)
  2722. {
  2723. case UnaryOperatorType.Explode:
  2724. {
  2725. LeaveExplodeExpression(node);
  2726. break;
  2727. }
  2728. case UnaryOperatorType.LogicalNot:
  2729. {
  2730. LeaveLogicalNot(node);
  2731. break;
  2732. }
  2733. case UnaryOperatorType.Increment:
  2734. case UnaryOperatorType.PostIncrement:
  2735. case UnaryOperatorType.Decrement:
  2736. case UnaryOperatorType.PostDecrement:
  2737. {
  2738. LeaveIncrementDecrement(node);
  2739. break;
  2740. }
  2741. case UnaryOperatorType.UnaryNegation:
  2742. {
  2743. LeaveUnaryNegation(node);
  2744. break;
  2745. }
  2746. case UnaryOperatorType.OnesComplement:
  2747. {
  2748. LeaveOnesComplement(node);
  2749. break;
  2750. }
  2751. default:
  2752. {
  2753. NotImplemented(node, "unary operator not supported");
  2754. break;
  2755. }
  2756. }
  2757. }
  2758. private void LeaveOnesComplement(UnaryExpression node)
  2759. {
  2760. if (IsPrimitiveOnesComplementOperand(node.Operand))
  2761. {
  2762. BindExpressionType(node, GetExpressionType(node.Operand));
  2763. }
  2764. else
  2765. {
  2766. ProcessOperatorOverload(node);
  2767. }
  2768. }
  2769. private bool IsPrimitiveOnesComplementOperand(Expression operand)
  2770. {
  2771. IType type = GetExpressionType(operand);
  2772. return TypeSystemServices.IsIntegerNumber(type) || type.IsEnum;
  2773. }
  2774. private void LeaveLogicalNot(UnaryExpression node)
  2775. {
  2776. node.Operand = AssertBoolContext(node.Operand);
  2777. BindExpressionType(node, TypeSystemServices.BoolType);
  2778. }
  2779. private void LeaveUnaryNegation(UnaryExpression node)
  2780. {
  2781. if (IsPrimitiveNumber(node.Operand))
  2782. {
  2783. BindExpressionType(node, GetExpressionType(node.Operand));
  2784. }
  2785. else
  2786. {
  2787. ProcessOperatorOverload(node);
  2788. }
  2789. }
  2790. private void ProcessOperatorOverload(UnaryExpression node)
  2791. {
  2792. if (! ResolveOperator(node))
  2793. {
  2794. InvalidOperatorForType(node);
  2795. }
  2796. }
  2797. override public bool EnterBinaryExpression(BinaryExpression node)
  2798. {
  2799. if (BinaryOperatorType.Assign == node.Operator)
  2800. {
  2801. if (NodeType.ReferenceExpression == node.Left.NodeType &&
  2802. null == node.Left.Entity)
  2803. {
  2804. // Auto local declaration:
  2805. // assign to unknown reference implies local
  2806. // declaration
  2807. ReferenceExpression reference = (ReferenceExpression)node.Left;
  2808. IEntity info = NameResolutionService.Resolve(reference.Name);
  2809. if (null == info || TypeSystemServices.IsBuiltin(info) || IsInaccessible(info))
  2810. {
  2811. Visit(node.Right);
  2812. IType expressionType = MapNullToObject(GetConcreteExpressionType(node.Right));
  2813. IEntity local = DeclareLocal(reference, reference.Name, expressionType);
  2814. reference.Entity = local;
  2815. BindExpressionType(node.Left, expressionType);
  2816. BindExpressionType(node, expressionType);
  2817. return false;
  2818. }
  2819. }
  2820. }
  2821. return true;
  2822. }
  2823. bool IsInaccessible(IEntity info)
  2824. {
  2825. IAccessibleMember accessible = info as IAccessibleMember;
  2826. if (accessible != null && accessible.IsPrivate
  2827. && accessible.DeclaringType != CurrentType)
  2828. {
  2829. return true;
  2830. }
  2831. return false;
  2832. }
  2833. override public void LeaveBinaryExpression(BinaryExpression node)
  2834. {
  2835. if (TypeSystemServices.IsUnknown(node.Left) ||
  2836. TypeSystemServices.IsUnknown(node.Right))
  2837. {
  2838. BindExpressionType(node, Unknown.Default);
  2839. return;
  2840. }
  2841. if (TypeSystemServices.IsError(node.Left)
  2842. || TypeSystemServices.IsError(node.Right))
  2843. {
  2844. Error(node);
  2845. return;
  2846. }
  2847. BindBinaryExpression(node);
  2848. }
  2849. protected virtual void BindBinaryExpression(BinaryExpression node)
  2850. {
  2851. if (IsEnumOperation(node))
  2852. {
  2853. BindEnumOperation(node);
  2854. return;
  2855. }
  2856. switch (node.Operator)
  2857. {
  2858. case BinaryOperatorType.Assign:
  2859. {
  2860. BindAssignment(node);
  2861. break;
  2862. }
  2863. case BinaryOperatorType.Addition:
  2864. {
  2865. if (GetExpressionType(node.Left).IsArray &&
  2866. GetExpressionType(node.Right).IsArray)
  2867. {
  2868. BindArrayAddition(node);
  2869. }
  2870. else
  2871. {
  2872. BindArithmeticOperator(node);
  2873. }
  2874. break;
  2875. }
  2876. case BinaryOperatorType.Subtraction:
  2877. case BinaryOperatorType.Multiply:
  2878. case BinaryOperatorType.Division:
  2879. case BinaryOperatorType.Modulus:
  2880. case BinaryOperatorType.Exponentiation:
  2881. {
  2882. BindArithmeticOperator(node);
  2883. break;
  2884. }
  2885. case BinaryOperatorType.TypeTest:
  2886. {
  2887. BindTypeTest(node);
  2888. break;
  2889. }
  2890. case BinaryOperatorType.ReferenceEquality:
  2891. {
  2892. BindReferenceEquality(node);
  2893. break;
  2894. }
  2895. case BinaryOperatorType.ReferenceInequality:
  2896. {
  2897. BindReferenceEquality(node);
  2898. break;
  2899. }
  2900. case BinaryOperatorType.Or:
  2901. case BinaryOperatorType.And:
  2902. {
  2903. BindLogicalOperator(node);
  2904. break;
  2905. }
  2906. case BinaryOperatorType.BitwiseAnd:
  2907. case BinaryOperatorType.BitwiseOr:
  2908. case BinaryOperatorType.ExclusiveOr:
  2909. case BinaryOperatorType.ShiftLeft:
  2910. case BinaryOperatorType.ShiftRight:
  2911. {
  2912. BindBitwiseOperator(node);
  2913. break;
  2914. }
  2915. case BinaryOperatorType.InPlaceSubtraction:
  2916. case BinaryOperatorType.InPlaceAddition:
  2917. {
  2918. BindInPlaceAddSubtract(node);
  2919. break;
  2920. }
  2921. case BinaryOperatorType.InPlaceShiftLeft:
  2922. case BinaryOperatorType.InPlaceShiftRight:
  2923. case BinaryOperatorType.InPlaceDivision:
  2924. case BinaryOperatorType.InPlaceMultiply:
  2925. case BinaryOperatorType.InPlaceBitwiseOr:
  2926. case BinaryOperatorType.InPlaceBitwiseAnd:
  2927. case BinaryOperatorType.InPlaceExclusiveOr:
  2928. {
  2929. BindInPlaceArithmeticOperator(node);
  2930. break;
  2931. }
  2932. case BinaryOperatorType.GreaterThan:
  2933. case BinaryOperatorType.GreaterThanOrEqual:
  2934. case BinaryOperatorType.LessThan:
  2935. case BinaryOperatorType.LessThanOrEqual:
  2936. case BinaryOperatorType.Inequality:
  2937. case BinaryOperatorType.Equality:
  2938. {
  2939. BindCmpOperator(node);
  2940. break;
  2941. }
  2942. default:
  2943. {
  2944. if (!ResolveOperator(node))
  2945. {
  2946. InvalidOperatorForTypes(node);
  2947. }
  2948. break;
  2949. }
  2950. }
  2951. }
  2952. IType GetMostGenericType(BinaryExpression node)
  2953. {
  2954. return GetMostGenericType(
  2955. GetExpressionType(node.Left),
  2956. GetExpressionType(node.Right));
  2957. }
  2958. bool IsNullableOperation(BinaryExpression node)
  2959. {
  2960. if (null == node.Left.ExpressionType || null == node.Right.ExpressionType)
  2961. {
  2962. return false;
  2963. }
  2964. return TypeSystemServices.IsNullable(GetExpressionType(node.Left))
  2965. || TypeSystemServices.IsNullable(GetExpressionType(node.Right));
  2966. }
  2967. bool IsEnumOperation(BinaryExpression node)
  2968. {
  2969. switch (node.Operator)
  2970. {
  2971. case BinaryOperatorType.Addition:
  2972. case BinaryOperatorType.Subtraction:
  2973. case BinaryOperatorType.BitwiseAnd:
  2974. case BinaryOperatorType.BitwiseOr:
  2975. case BinaryOperatorType.ExclusiveOr:
  2976. IType lhs = GetExpressionType(node.Left);
  2977. IType rhs = GetExpressionType(node.Right);
  2978. if (lhs.IsEnum) return IsValidEnumOperand(lhs, rhs);
  2979. if (rhs.IsEnum) return IsValidEnumOperand(rhs, lhs);
  2980. break;
  2981. }
  2982. return false;
  2983. }
  2984. bool IsValidEnumOperand(IType expected, IType actual)
  2985. {
  2986. if (expected == actual) return true;
  2987. if (actual.IsEnum) return true;
  2988. return TypeSystemServices.IsIntegerNumber(actual);
  2989. }
  2990. void BindEnumOperation(BinaryExpression node)
  2991. {
  2992. IType lhs = GetExpressionType(node.Left);
  2993. IType rhs = GetExpressionType(node.Right);
  2994. switch(node.Operator)
  2995. {
  2996. case BinaryOperatorType.Addition:
  2997. if (lhs.IsEnum != rhs.IsEnum)
  2998. {
  2999. BindExpressionType(node, lhs.IsEnum ? lhs : rhs);
  3000. return;
  3001. }
  3002. break;
  3003. case BinaryOperatorType.Subtraction:
  3004. if (lhs == rhs)
  3005. {
  3006. BindExpressionType(node, TypeSystemServices.IntType);
  3007. return;
  3008. }
  3009. else if (lhs.IsEnum && !rhs.IsEnum)
  3010. {
  3011. BindExpressionType(node, lhs);
  3012. return;
  3013. }
  3014. break;
  3015. case BinaryOperatorType.BitwiseAnd:
  3016. case BinaryOperatorType.BitwiseOr:
  3017. case BinaryOperatorType.ExclusiveOr:
  3018. if (lhs == rhs)
  3019. {
  3020. BindExpressionType(node, lhs);
  3021. return;
  3022. }
  3023. break;
  3024. }
  3025. if (!ResolveOperator(node))
  3026. {
  3027. InvalidOperatorForTypes(node);
  3028. }
  3029. }
  3030. void BindBitwiseOperator(BinaryExpression node)
  3031. {
  3032. IType lhs = GetExpressionType(node.Left);
  3033. IType rhs = GetExpressionType(node.Right);
  3034. if (TypeSystemServices.IsIntegerOrBool(lhs) &&
  3035. TypeSystemServices.IsIntegerOrBool(rhs))
  3036. {
  3037. BindExpressionType(node, TypeSystemServices.GetPromotedNumberType(lhs, rhs));
  3038. }
  3039. else
  3040. {
  3041. // if (lhs.IsEnum && rhs == lhs)
  3042. // {
  3043. // BindExpressionType(node, lhs);
  3044. // }
  3045. // else
  3046. // {
  3047. if (!ResolveOperator(node))
  3048. {
  3049. InvalidOperatorForTypes(node);
  3050. }
  3051. // }
  3052. }
  3053. }
  3054. bool IsChar(IType type)
  3055. {
  3056. return TypeSystemServices.CharType == type;
  3057. }
  3058. void BindCmpOperator(BinaryExpression node)
  3059. {
  3060. if (BindNullableComparison(node))
  3061. {
  3062. return;
  3063. }
  3064. IType lhs = GetExpressionType(node.Left);
  3065. IType rhs = GetExpressionType(node.Right);
  3066. if (IsPrimitiveComparison(lhs, rhs))
  3067. {
  3068. BindExpressionType(node, TypeSystemServices.BoolType);
  3069. return;
  3070. }
  3071. if (lhs.IsEnum || rhs.IsEnum)
  3072. {
  3073. if (lhs == rhs || IsPrimitiveNumber(rhs) || IsPrimitiveNumber(lhs))
  3074. {
  3075. BindExpressionType(node, TypeSystemServices.BoolType);
  3076. }
  3077. else
  3078. {
  3079. if (!ResolveOperator(node))
  3080. {
  3081. InvalidOperatorForTypes(node);
  3082. }
  3083. }
  3084. return;
  3085. }
  3086. if (!ResolveOperator(node))
  3087. {
  3088. switch (node.Operator)
  3089. {
  3090. case BinaryOperatorType.Equality:
  3091. {
  3092. if (OptimizeNullComparisons
  3093. && (IsNull(node.Left) || IsNull(node.Right)))
  3094. {
  3095. node.Operator = BinaryOperatorType.ReferenceEquality;
  3096. BindReferenceEquality(node);
  3097. break;
  3098. }
  3099. Expression expression = CreateEquals(node);
  3100. node.ParentNode.Replace(node, expression);
  3101. break;
  3102. }
  3103. case BinaryOperatorType.Inequality:
  3104. {
  3105. if (OptimizeNullComparisons
  3106. && (IsNull(node.Left) || IsNull(node.Right)))
  3107. {
  3108. node.Operator = BinaryOperatorType.ReferenceInequality;
  3109. BindReferenceEquality(node);
  3110. break;
  3111. }
  3112. Expression expression = CreateEquals(node);
  3113. Node parent = node.ParentNode;
  3114. parent.Replace(node, CodeBuilder.CreateNotExpression(expression));
  3115. break;
  3116. }
  3117. default:
  3118. {
  3119. InvalidOperatorForTypes(node);
  3120. break;
  3121. }
  3122. }
  3123. }
  3124. }
  3125. private bool IsPrimitiveComparison(IType lhs, IType rhs)
  3126. {
  3127. if (IsPrimitiveNumberOrChar(lhs) && IsPrimitiveNumberOrChar(rhs)) return true;
  3128. if (IsBool(lhs) && IsBool(rhs)) return true;
  3129. return false;
  3130. }
  3131. private bool IsPrimitiveNumberOrChar(IType lhs)
  3132. {
  3133. return IsPrimitiveNumber(lhs) || IsChar(lhs);
  3134. }
  3135. private bool IsBool(IType lhs)
  3136. {
  3137. return TypeSystemServices.BoolType == lhs;
  3138. }
  3139. static bool IsNull(Expression node)
  3140. {
  3141. return NodeType.NullLiteralExpression == node.NodeType;
  3142. }
  3143. void BindLogicalOperator(BinaryExpression node)
  3144. {
  3145. node.Left = AssertBoolContext(node.Left);
  3146. node.Right = AssertBoolContext(node.Right);
  3147. BindExpressionType(node, GetMostGenericType(node));
  3148. }
  3149. void BindInPlaceAddSubtract(BinaryExpression node)
  3150. {
  3151. IEntity entity = node.Left.Entity;
  3152. if (null != entity &&
  3153. (EntityType.Event == entity.EntityType
  3154. || EntityType.Ambiguous == entity.EntityType))
  3155. {
  3156. BindEventSubscription(node);
  3157. }
  3158. else
  3159. {
  3160. BindInPlaceArithmeticOperator(node);
  3161. }
  3162. }
  3163. void BindEventSubscription(BinaryExpression node)
  3164. {
  3165. IEntity tag = GetEntity(node.Left);
  3166. if (EntityType.Event != tag.EntityType)
  3167. {
  3168. if (EntityType.Ambiguous == tag.EntityType)
  3169. {
  3170. IList found = ((Ambiguous)tag).Select(IsPublicEvent);
  3171. if (found.Count != 1)
  3172. {
  3173. tag = null;
  3174. }
  3175. else
  3176. {
  3177. tag = (IEntity)found[0];
  3178. Bind(node.Left, tag);
  3179. }
  3180. }
  3181. }
  3182. IEvent eventInfo = (IEvent)tag;
  3183. IType rtype = GetExpressionType(node.Right);
  3184. if (!AssertDelegateArgument(node, eventInfo, rtype))
  3185. {
  3186. Error(node);
  3187. return;
  3188. }
  3189. IMethod method = null;
  3190. if (node.Operator == BinaryOperatorType.InPlaceAddition)
  3191. {
  3192. method = eventInfo.GetAddMethod();
  3193. }
  3194. else
  3195. {
  3196. method = eventInfo.GetRemoveMethod();
  3197. CallableSignature expected = GetCallableSignature(eventInfo.Type);
  3198. CallableSignature actual = GetCallableSignature(node.Right);
  3199. if (expected != actual)
  3200. {
  3201. Warnings.Add(
  3202. CompilerWarningFactory.InvalidEventUnsubscribe(
  3203. node,
  3204. eventInfo.FullName,
  3205. expected));
  3206. }
  3207. }
  3208. MethodInvocationExpression mie = CodeBuilder.CreateMethodInvocation(
  3209. ((MemberReferenceExpression)node.Left).Target,
  3210. method,
  3211. node.Right);
  3212. node.ParentNode.Replace(node, mie);
  3213. }
  3214. CallableSignature GetCallableSignature(Expression node)
  3215. {
  3216. return GetCallableSignature(GetExpressionType(node));
  3217. }
  3218. CallableSignature GetCallableSignature(IType type)
  3219. {
  3220. return ((ICallableType)type).GetSignature();
  3221. }
  3222. virtual protected void ProcessBuiltinInvocation(BuiltinFunction function, MethodInvocationExpression node)
  3223. {
  3224. switch (function.FunctionType)
  3225. {
  3226. case BuiltinFunctionType.Len:
  3227. {
  3228. ProcessLenInvocation(node);
  3229. break;
  3230. }
  3231. case BuiltinFunctionType.AddressOf:
  3232. {
  3233. ProcessAddressOfInvocation(node);
  3234. break;
  3235. }
  3236. case BuiltinFunctionType.Eval:
  3237. {
  3238. ProcessEvalInvocation(node);
  3239. break;
  3240. }
  3241. default:
  3242. {
  3243. NotImplemented(node, "BuiltinFunction: " + function);
  3244. break;
  3245. }
  3246. }
  3247. }
  3248. bool ProcessSwitchInvocation(MethodInvocationExpression node)
  3249. {
  3250. if (BuiltinFunction.Switch != node.Target.Entity) return false;
  3251. BindSwitchLabelReferences(node);
  3252. if (CheckSwitchArguments(node)) return true;
  3253. Error(node, CompilerErrorFactory.InvalidSwitch(node.Target));
  3254. return true;
  3255. }
  3256. private static void BindSwitchLabelReferences(MethodInvocationExpression node)
  3257. {
  3258. for (int i = 1; i < node.Arguments.Count; ++i)
  3259. {
  3260. ReferenceExpression label = (ReferenceExpression)node.Arguments[i];
  3261. label.ExpressionType = Unknown.Default;
  3262. }
  3263. }
  3264. bool CheckSwitchArguments(MethodInvocationExpression node)
  3265. {
  3266. ExpressionCollection args = node.Arguments;
  3267. if (args.Count > 1)
  3268. {
  3269. Visit(args[0]);
  3270. if (TypeSystemServices.IsIntegerNumber(GetExpressionType(args[0])))
  3271. {
  3272. for (int i=1; i<args.Count; ++i)
  3273. {
  3274. if (NodeType.ReferenceExpression != args[i].NodeType)
  3275. {
  3276. return false;
  3277. }
  3278. }
  3279. return true;
  3280. }
  3281. }
  3282. return false;
  3283. }
  3284. void ProcessEvalInvocation(MethodInvocationExpression node)
  3285. {
  3286. if (node.Arguments.Count > 0)
  3287. {
  3288. int allButLast = node.Arguments.Count-1;
  3289. for (int i=0; i<allButLast; ++i)
  3290. {
  3291. AssertHasSideEffect(node.Arguments[i]);
  3292. }
  3293. BindExpressionType(node, GetConcreteExpressionType(node.Arguments[-1]));
  3294. }
  3295. else
  3296. {
  3297. BindExpressionType(node, TypeSystemServices.VoidType);
  3298. }
  3299. }
  3300. void ProcessAddressOfInvocation(MethodInvocationExpression node)
  3301. {
  3302. if (node.Arguments.Count != 1)
  3303. {
  3304. Error(node, CompilerErrorFactory.MethodArgumentCount(node.Target, "__addressof__", 1));
  3305. }
  3306. else
  3307. {
  3308. Expression arg = node.Arguments[0];
  3309. EntityType type = GetEntity(arg).EntityType;
  3310. if (EntityType.Method != type)
  3311. {
  3312. ReferenceExpression reference = arg as ReferenceExpression;
  3313. if (null != reference && EntityType.Ambiguous == type)
  3314. {
  3315. Error(node, CompilerErrorFactory.AmbiguousReference(arg, reference.Name, ((Ambiguous)arg.Entity).Entities));
  3316. }
  3317. else
  3318. {
  3319. Error(node, CompilerErrorFactory.MethodReferenceExpected(arg));
  3320. }
  3321. }
  3322. else
  3323. {
  3324. BindExpressionType(node, TypeSystemServices.IntPtrType);
  3325. }
  3326. }
  3327. }
  3328. void ProcessLenInvocation(MethodInvocationExpression node)
  3329. {
  3330. if ((node.Arguments.Count < 1) || (node.Arguments.Count > 2))
  3331. {
  3332. Error(node, CompilerErrorFactory.MethodArgumentCount(node.Target, "len", node.Arguments.Count));
  3333. return;
  3334. }
  3335. MethodInvocationExpression resultingNode = null;
  3336. Expression target = node.Arguments[0];
  3337. IType type = GetExpressionType(target);
  3338. bool isArray = TypeSystemServices.ArrayType.IsAssignableFrom(type);
  3339. if ((!isArray) && (node.Arguments.Count != 1))
  3340. {
  3341. Error(node, CompilerErrorFactory.MethodArgumentCount(node.Target, "len", node.Arguments.Count));
  3342. }
  3343. if (TypeSystemServices.IsSystemObject(type))
  3344. {
  3345. resultingNode = CodeBuilder.CreateMethodInvocation(RuntimeServices_Len, target);
  3346. }
  3347. else if (TypeSystemServices.StringType == type)
  3348. {
  3349. resultingNode = CodeBuilder.CreateMethodInvocation(target, String_get_Length);
  3350. }
  3351. else if (isArray)
  3352. {
  3353. if (node.Arguments.Count == 1)
  3354. {
  3355. resultingNode = CodeBuilder.CreateMethodInvocation(target, Array_get_Length);
  3356. }
  3357. else
  3358. {
  3359. resultingNode = CodeBuilder.CreateMethodInvocation(target,
  3360. Array_GetLength, node.Arguments[1]);
  3361. }
  3362. }
  3363. else if (TypeSystemServices.ICollectionType.IsAssignableFrom(type))
  3364. {
  3365. resultingNode = CodeBuilder.CreateMethodInvocation(target, ICollection_get_Count);
  3366. }
  3367. else
  3368. {
  3369. Error(CompilerErrorFactory.InvalidLen(target, type.ToString()));
  3370. }
  3371. if (null != resultingNode)
  3372. {
  3373. node.ParentNode.Replace(node, resultingNode);
  3374. }
  3375. }
  3376. void CheckListLiteralArgumentInArrayConstructor(IType expectedElementType, MethodInvocationExpression constructor)
  3377. {
  3378. ListLiteralExpression elements = constructor.Arguments[1] as ListLiteralExpression;
  3379. if (null == elements) return;
  3380. CheckItems(expectedElementType, elements.Items);
  3381. }
  3382. private void CheckItems(IType expectedElementType, ExpressionCollection items)
  3383. {
  3384. foreach (Expression element in items)
  3385. {
  3386. AssertTypeCompatibility(element, expectedElementType, GetExpressionType(element));
  3387. }
  3388. }
  3389. void ApplyBuiltinMethodTypeInference(MethodInvocationExpression expression, IMethod method)
  3390. {
  3391. IType inferredType = null;
  3392. if (Array_TypedEnumerableConstructor == method ||
  3393. Array_TypedCollectionConstructor == method ||
  3394. Array_TypedConstructor2 == method)
  3395. {
  3396. IType type = TypeSystemServices.GetReferencedType(expression.Arguments[0]);
  3397. if (null != type)
  3398. {
  3399. if (Array_TypedCollectionConstructor == method)
  3400. {
  3401. CheckListLiteralArgumentInArrayConstructor(type, expression);
  3402. }
  3403. inferredType = TypeSystemServices.GetArrayType(type, 1);
  3404. }
  3405. }
  3406. else if (MultiDimensionalArray_TypedConstructor == method)
  3407. {
  3408. IType type = TypeSystemServices.GetReferencedType(expression.Arguments[0]);
  3409. if (null != type)
  3410. {
  3411. inferredType = TypeSystemServices.GetArrayType(type, expression.Arguments.Count-1);
  3412. }
  3413. }
  3414. else if (Array_EnumerableConstructor == method)
  3415. {
  3416. IType enumeratorItemType = GetEnumeratorItemType(GetExpressionType(expression.Arguments[0]));
  3417. if (TypeSystemServices.ObjectType != enumeratorItemType)
  3418. {
  3419. inferredType = TypeSystemServices.GetArrayType(enumeratorItemType, 1);
  3420. expression.Target.Entity = Array_TypedEnumerableConstructor;
  3421. expression.ExpressionType = Array_TypedEnumerableConstructor.ReturnType;
  3422. expression.Arguments.Insert(0, CodeBuilder.CreateReference(enumeratorItemType));
  3423. }
  3424. }
  3425. if (null != inferredType)
  3426. {
  3427. Node parent = expression.ParentNode;
  3428. parent.Replace(expression,
  3429. CodeBuilder.CreateCast(inferredType, expression));
  3430. }
  3431. }
  3432. protected virtual IEntity ResolveAmbiguousMethodInvocation(MethodInvocationExpression node, Ambiguous entity)
  3433. {
  3434. _context.TraceVerbose("{0}: resolving ambigous method invocation: {1}", node.LexicalInfo, entity);
  3435. IEntity resolved = ResolveCallableReference(node, entity);
  3436. if (null != resolved) return resolved;
  3437. if (TryToProcessAsExtensionInvocation(node)) return null;
  3438. return CantResolveAmbiguousMethodInvocation(node, entity.Entities);
  3439. }
  3440. private IEntity ResolveCallableReference(MethodInvocationExpression node, Ambiguous entity)
  3441. {
  3442. IEntity resolved = _callableResolution.ResolveCallableReference(node.Arguments, entity.Entities);
  3443. if (null == resolved) return null;
  3444. IMember member = (IMember)resolved;
  3445. if (NodeType.ReferenceExpression == node.Target.NodeType)
  3446. {
  3447. ResolveMemberInfo((ReferenceExpression)node.Target, member);
  3448. }
  3449. else
  3450. {
  3451. Bind(node.Target, member);
  3452. BindExpressionType(node.Target, member.Type);
  3453. }
  3454. return resolved;
  3455. }
  3456. private bool TryToProcessAsExtensionInvocation(MethodInvocationExpression node)
  3457. {
  3458. IEntity extension = ResolveExtension(node);
  3459. if (null == extension) return false;
  3460. ProcessExtensionMethodInvocation(node, extension);
  3461. return true;
  3462. }
  3463. private IEntity ResolveExtension(MethodInvocationExpression node)
  3464. {
  3465. MemberReferenceExpression mre = node.Target as MemberReferenceExpression;
  3466. if (mre == null) return null;
  3467. return NameResolutionService.ResolveExtension(GetReferenceNamespace(mre), mre.Name);
  3468. }
  3469. protected virtual IEntity CantResolveAmbiguousMethodInvocation(MethodInvocationExpression node, IEntity[] entities)
  3470. {
  3471. EmitCallableResolutionError(node, entities, node.Arguments);
  3472. Error(node);
  3473. return null;
  3474. }
  3475. override public void OnMethodInvocationExpression(MethodInvocationExpression node)
  3476. {
  3477. if (null != node.ExpressionType)
  3478. {
  3479. _context.TraceVerbose("{0}: Method invocation already bound.", node.LexicalInfo);
  3480. return;
  3481. }
  3482. Visit(node.Target);
  3483. if (ProcessSwitchInvocation(node)) return;
  3484. if (ProcessMetaMethodInvocation(node)) return;
  3485. Visit(node.Arguments);
  3486. if (TypeSystemServices.IsError(node.Target)
  3487. || TypeSystemServices.IsErrorAny(node.Arguments))
  3488. {
  3489. Error(node);
  3490. return;
  3491. }
  3492. IEntity targetEntity = node.Target.Entity;
  3493. if (null == targetEntity)
  3494. {
  3495. ProcessGenericMethodInvocation(node);
  3496. return;
  3497. }
  3498. if (IsOrContainsBooExtensionMethod(targetEntity))
  3499. {
  3500. ProcessExtensionMethodInvocation(node, targetEntity);
  3501. return;
  3502. }
  3503. ProcessMethodInvocationExpression(node, targetEntity);
  3504. }
  3505. private bool ProcessMetaMethodInvocation(MethodInvocationExpression node)
  3506. {
  3507. IEntity targetEntity = node.Target.Entity;
  3508. if (null == targetEntity) return false;
  3509. if (!IsOrContainMetaMethod(targetEntity)) return false;
  3510. object[] arguments = GetMetaMethodInvocationArguments(node);
  3511. Type[] argumentTypes = MethodResolver.GetArgumentTypes(arguments);
  3512. MethodResolver resolver = new MethodResolver(argumentTypes);
  3513. CandidateMethod method = resolver.ResolveMethod(EnumerateMetaMethods(targetEntity));
  3514. if (null == method) return false;
  3515. // TODO: cache emitted dispatchers
  3516. MethodDispatcherEmitter emitter = new MethodDispatcherEmitter(method, argumentTypes);
  3517. Node replacement = (Node)emitter.Emit()(null, arguments);
  3518. ReplaceMetaMethodInvocationSite(node, replacement);
  3519. return true;
  3520. }
  3521. private static object[] GetMetaMethodInvocationArguments(MethodInvocationExpression node)
  3522. {
  3523. if (node.NamedArguments.Count == 0) return node.Arguments.ToArray();
  3524. List arguments = new List();
  3525. arguments.Add(node.NamedArguments.ToArray());
  3526. arguments.Extend(node.Arguments);
  3527. return arguments.ToArray();
  3528. }
  3529. private void ReplaceMetaMethodInvocationSite(MethodInvocationExpression node, Node replacement)
  3530. {
  3531. if (replacement is Statement)
  3532. {
  3533. if (node.ParentNode.NodeType != NodeType.ExpressionStatement)
  3534. NotImplemented(node, "Cant use an statement where an expression is expected.");
  3535. node.ParentNode.ParentNode.Replace(node.ParentNode, replacement);
  3536. }
  3537. else
  3538. {
  3539. node.ParentNode.Replace(node, replacement);
  3540. }
  3541. Visit(replacement);
  3542. }
  3543. private System.Collections.Generic.IEnumerable<System.Reflection.MethodInfo> EnumerateMetaMethods(IEntity entity)
  3544. {
  3545. if (entity.EntityType == EntityType.Method)
  3546. {
  3547. yield return GetMethodInfo(entity);
  3548. }
  3549. else
  3550. {
  3551. foreach (IEntity item in ((Ambiguous)entity).Entities)
  3552. {
  3553. yield return GetMethodInfo(item);
  3554. }
  3555. }
  3556. }
  3557. private static MethodInfo GetMethodInfo(IEntity entity)
  3558. {
  3559. return (MethodInfo)((ExternalMethod) entity).MethodInfo;
  3560. }
  3561. private bool IsOrContainMetaMethod(IEntity entity)
  3562. {
  3563. switch (entity.EntityType)
  3564. {
  3565. case EntityType.Ambiguous:
  3566. return ((Ambiguous) entity).Any(IsMetaMethod);
  3567. case EntityType.Method:
  3568. return IsMetaMethod(entity);
  3569. }
  3570. return false;
  3571. }
  3572. private static bool IsMetaMethod(IEntity entity)
  3573. {
  3574. ExternalMethod m = entity as ExternalMethod;
  3575. if (m == null) return false;
  3576. return m.IsMeta;
  3577. }
  3578. private void ProcessMethodInvocationExpression(MethodInvocationExpression node, IEntity targetEntity)
  3579. {
  3580. switch (targetEntity.EntityType)
  3581. {
  3582. case EntityType.Ambiguous:
  3583. {
  3584. ProcessAmbiguousMethodInvocation(node, targetEntity);
  3585. break;
  3586. }
  3587. case EntityType.BuiltinFunction:
  3588. {
  3589. ProcessBuiltinInvocation((BuiltinFunction)targetEntity, node);
  3590. break;
  3591. }
  3592. case EntityType.Event:
  3593. {
  3594. ProcessEventInvocation((IEvent)targetEntity, node);
  3595. break;
  3596. }
  3597. case EntityType.Method:
  3598. {
  3599. ProcessMethodInvocation(node, targetEntity);
  3600. break;
  3601. }
  3602. case EntityType.Constructor:
  3603. {
  3604. ProcessConstructorInvocation(node, targetEntity);
  3605. break;
  3606. }
  3607. case EntityType.Type:
  3608. {
  3609. ProcessTypeInvocation(node);
  3610. break;
  3611. }
  3612. case EntityType.Error:
  3613. {
  3614. Error(node);
  3615. break;
  3616. }
  3617. default:
  3618. {
  3619. ProcessGenericMethodInvocation(node);
  3620. break;
  3621. }
  3622. }
  3623. }
  3624. protected virtual void ProcessAmbiguousMethodInvocation(MethodInvocationExpression node, IEntity targetEntity)
  3625. {
  3626. targetEntity = ResolveAmbiguousMethodInvocation(node, (Ambiguous)targetEntity);
  3627. if (null == targetEntity) return;
  3628. ProcessMethodInvocationExpression(node, targetEntity);
  3629. }
  3630. private void ProcessConstructorInvocation(MethodInvocationExpression node, IEntity targetEntity)
  3631. {
  3632. NamedArgumentsNotAllowed(node);
  3633. InternalConstructor constructorInfo = targetEntity as InternalConstructor;
  3634. if (null == constructorInfo) return;
  3635. IType targetType = null;
  3636. if (NodeType.SuperLiteralExpression == node.Target.NodeType)
  3637. {
  3638. constructorInfo.HasSuperCall = true;
  3639. targetType = constructorInfo.DeclaringType.BaseType;
  3640. }
  3641. else if (node.Target.NodeType == NodeType.SelfLiteralExpression)
  3642. {
  3643. constructorInfo.HasSelfCall = true;
  3644. targetType = constructorInfo.DeclaringType;
  3645. }
  3646. IConstructor targetConstructorInfo = GetCorrectConstructor(node, targetType, node.Arguments);
  3647. if (null != targetConstructorInfo)
  3648. {
  3649. Bind(node.Target, targetConstructorInfo);
  3650. }
  3651. }
  3652. protected virtual bool ProcessMethodInvocationWithInvalidParameters(MethodInvocationExpression node, IMethod targetMethod)
  3653. {
  3654. return false;
  3655. }
  3656. protected virtual void ProcessMethodInvocation(MethodInvocationExpression node, IEntity targetEntity)
  3657. {
  3658. IMethod targetMethod = (IMethod)targetEntity;
  3659. if (!CheckParameters(targetMethod.CallableType, node.Arguments, false)
  3660. || !IsAccessible(targetMethod))
  3661. {
  3662. if (TryToProcessAsExtensionInvocation(node)) return;
  3663. if (ProcessMethodInvocationWithInvalidParameters(node, targetMethod)) return;
  3664. AssertParameters(node, targetMethod, node.Arguments);
  3665. }
  3666. AssertTargetContext(node.Target, targetMethod);
  3667. NamedArgumentsNotAllowed(node);
  3668. EnsureRelatedNodeWasVisited(node.Target, targetMethod);
  3669. BindExpressionType(node, GetInferredType(targetMethod));
  3670. ApplyBuiltinMethodTypeInference(node, targetMethod);
  3671. }
  3672. private bool IsAccessible(IAccessibleMember method)
  3673. {
  3674. return GetAccessibilityChecker().IsAccessible(method);
  3675. }
  3676. private IAccessibilityChecker GetAccessibilityChecker()
  3677. {
  3678. if (null == _currentMethod) return AccessibilityChecker.Global;
  3679. return new AccessibilityChecker(CurrentTypeDefinition);
  3680. }
  3681. private TypeDefinition CurrentTypeDefinition
  3682. {
  3683. get { return _currentMethod.Method.DeclaringType; }
  3684. }
  3685. private void NamedArgumentsNotAllowed(MethodInvocationExpression node)
  3686. {
  3687. if (node.NamedArguments.Count == 0) return;
  3688. Error(CompilerErrorFactory.NamedArgumentsNotAllowed(node.NamedArguments[0]));
  3689. }
  3690. private void ProcessExtensionMethodInvocation(MethodInvocationExpression node, IEntity targetEntity)
  3691. {
  3692. PreNormalizeExtensionInvocation(node);
  3693. if (EntityType.Ambiguous == targetEntity.EntityType)
  3694. {
  3695. targetEntity = ResolveAmbiguousExtension(node, (Ambiguous)targetEntity);
  3696. if (null == targetEntity) return;
  3697. }
  3698. IMethod targetMethod = (IMethod)targetEntity;
  3699. PostNormalizationExtensionInvocation(node, targetMethod);
  3700. NamedArgumentsNotAllowed(node);
  3701. AssertParameters(node, targetMethod, node.Arguments);
  3702. BindExpressionType(node, targetMethod.ReturnType);
  3703. }
  3704. private IEntity ResolveAmbiguousExtension(MethodInvocationExpression node, Ambiguous ambiguous)
  3705. {
  3706. IEntity resolved = ResolveCallableReference(node, ambiguous);
  3707. if (null != resolved) return resolved;
  3708. return CantResolveAmbiguousMethodInvocation(node, ambiguous.Entities);
  3709. }
  3710. private bool IsExtensionMethod(IEntity entity)
  3711. {
  3712. if (EntityType.Method != entity.EntityType) return false;
  3713. return ((IMethod)entity).IsExtension;
  3714. }
  3715. private bool IsOrContainsBooExtensionMethod(IEntity entity)
  3716. {
  3717. if (entity.EntityType == EntityType.Ambiguous) return IsBooExtensionMethod(((Ambiguous)entity).Entities[0]);
  3718. return IsBooExtensionMethod(entity);
  3719. }
  3720. private bool IsBooExtensionMethod(IEntity entity)
  3721. {
  3722. if (EntityType.Method != entity.EntityType) return false;
  3723. return ((IMethod)entity).IsBooExtension;
  3724. }
  3725. private void PostNormalizationExtensionInvocation(MethodInvocationExpression node, IMethod targetMethod)
  3726. {
  3727. node.Target = CodeBuilder.CreateMethodReference(node.Target.LexicalInfo, targetMethod);
  3728. }
  3729. private void PreNormalizeExtensionInvocation(MethodInvocationExpression node)
  3730. {
  3731. node.Arguments.Insert(0, EnsureMemberReferenceForExtension(node).Target);
  3732. }
  3733. private MemberReferenceExpression EnsureMemberReferenceForExtension(MethodInvocationExpression node)
  3734. {
  3735. MemberReferenceExpression memberRef = node.Target as MemberReferenceExpression;
  3736. if (null != memberRef) return memberRef;
  3737. node.Target = memberRef = CodeBuilder.MemberReferenceForEntity(
  3738. CreateSelfReference(),
  3739. GetEntity(node.Target));
  3740. return memberRef;
  3741. }
  3742. private SelfLiteralExpression CreateSelfReference()
  3743. {
  3744. return CodeBuilder.CreateSelfReference(CurrentType);
  3745. }
  3746. protected virtual bool IsDuckTyped(IMember entity)
  3747. {
  3748. return entity.IsDuckTyped;
  3749. }
  3750. private IType GetInferredType(IMethod entity)
  3751. {
  3752. return IsDuckTyped(entity)
  3753. ? this.TypeSystemServices.DuckType
  3754. : entity.ReturnType;
  3755. }
  3756. private IType GetInferredType(IMember entity)
  3757. {
  3758. Debug.Assert(EntityType.Method != entity.EntityType);
  3759. return IsDuckTyped(entity)
  3760. ? this.TypeSystemServices.DuckType
  3761. : entity.Type;
  3762. }
  3763. void ReplaceTypeInvocationByEval(IType type, MethodInvocationExpression node)
  3764. {
  3765. Node parent = node.ParentNode;
  3766. parent.Replace(node, EvalForTypeInvocation(type, node));
  3767. }
  3768. private MethodInvocationExpression EvalForTypeInvocation(IType type, MethodInvocationExpression node)
  3769. {
  3770. MethodInvocationExpression eval = CodeBuilder.CreateEvalInvocation(node.LexicalInfo);
  3771. ReferenceExpression local = CreateTempLocal(node.Target.LexicalInfo, type);
  3772. eval.Arguments.Add(CodeBuilder.CreateAssignment(local.CloneNode(), node));
  3773. AddResolvedNamedArgumentsToEval(eval, node.NamedArguments, local);
  3774. node.NamedArguments.Clear();
  3775. eval.Arguments.Add(local);
  3776. BindExpressionType(eval, type);
  3777. return eval;
  3778. }
  3779. private void AddResolvedNamedArgumentsToEval(MethodInvocationExpression eval, ExpressionPairCollection namedArguments, ReferenceExpression instance)
  3780. {
  3781. foreach (ExpressionPair pair in namedArguments)
  3782. {
  3783. if (TypeSystemServices.IsError(pair.First)) continue;
  3784. AddResolvedNamedArgumentToEval(eval, pair, instance);
  3785. }
  3786. }
  3787. protected virtual void AddResolvedNamedArgumentToEval(MethodInvocationExpression eval, ExpressionPair pair, ReferenceExpression instance)
  3788. {
  3789. IEntity entity = GetEntity(pair.First);
  3790. switch (entity.EntityType)
  3791. {
  3792. case EntityType.Event:
  3793. {
  3794. IEvent member = (IEvent)entity;
  3795. eval.Arguments.Add(
  3796. CodeBuilder.CreateMethodInvocation(
  3797. pair.First.LexicalInfo,
  3798. instance.CloneNode(),
  3799. member.GetAddMethod(),
  3800. pair.Second));
  3801. break;
  3802. }
  3803. case EntityType.Field:
  3804. {
  3805. eval.Arguments.Add(
  3806. CodeBuilder.CreateAssignment(
  3807. pair.First.LexicalInfo,
  3808. CodeBuilder.CreateMemberReference(
  3809. instance.CloneNode(),
  3810. (IMember)entity),
  3811. pair.Second));
  3812. break;
  3813. }
  3814. case EntityType.Property:
  3815. {
  3816. IProperty property = (IProperty)entity;
  3817. IMethod setter = property.GetSetMethod();
  3818. if (null == setter)
  3819. {
  3820. Error(CompilerErrorFactory.PropertyIsReadOnly(
  3821. pair.First,
  3822. property.FullName));
  3823. }
  3824. else
  3825. {
  3826. //EnsureRelatedNodeWasVisited(pair.First, setter);
  3827. eval.Arguments.Add(
  3828. CodeBuilder.CreateAssignment(
  3829. pair.First.LexicalInfo,
  3830. CodeBuilder.CreateMemberReference(
  3831. instance.CloneNode(),
  3832. property),
  3833. pair.Second));
  3834. }
  3835. break;
  3836. }
  3837. }
  3838. }
  3839. void ProcessEventInvocation(IEvent ev, MethodInvocationExpression node)
  3840. {
  3841. NamedArgumentsNotAllowed(node);
  3842. if (!EnsureInternalEventInvocation(ev, node)) return;
  3843. IMethod method = ev.GetRaiseMethod();
  3844. if (AssertParameters(node, method, node.Arguments))
  3845. {
  3846. node.Target = CodeBuilder.CreateMemberReference(
  3847. ((MemberReferenceExpression)node.Target).Target,
  3848. method);
  3849. BindExpressionType(node, method.ReturnType);
  3850. }
  3851. }
  3852. public bool EnsureInternalEventInvocation(IEvent ev, MethodInvocationExpression node)
  3853. {
  3854. if (ev.IsAbstract || ev.IsVirtual || ev.DeclaringType == CurrentType)
  3855. return true;
  3856. Error(CompilerErrorFactory.EventCanOnlyBeInvokedFromWithinDeclaringClass(node, ev));
  3857. return false;
  3858. }
  3859. void ProcessCallableTypeInvocation(MethodInvocationExpression node, ICallableType type)
  3860. {
  3861. NamedArgumentsNotAllowed(node);
  3862. if (node.Arguments.Count == 1)
  3863. {
  3864. AssertTypeCompatibility(node.Arguments[0], type, GetExpressionType(node.Arguments[0]));
  3865. node.ParentNode.Replace(
  3866. node,
  3867. CodeBuilder.CreateCast(
  3868. type,
  3869. node.Arguments[0]));
  3870. }
  3871. else
  3872. {
  3873. IConstructor ctor = GetCorrectConstructor(node, type, node.Arguments);
  3874. if (null != ctor)
  3875. {
  3876. BindConstructorInvocation(node, ctor);
  3877. }
  3878. else
  3879. {
  3880. Error(node);
  3881. }
  3882. }
  3883. }
  3884. void ProcessTypeInvocation(MethodInvocationExpression node)
  3885. {
  3886. IType type = (IType)node.Target.Entity;
  3887. ICallableType callableType = type as ICallableType;
  3888. if (null != callableType)
  3889. {
  3890. ProcessCallableTypeInvocation(node, callableType);
  3891. return;
  3892. }
  3893. if (!AssertCanCreateInstance(node.Target, type))
  3894. {
  3895. Error(node);
  3896. return;
  3897. }
  3898. ResolveNamedArguments(type, node.NamedArguments);
  3899. if (type.IsValueType && node.Arguments.Count == 0)
  3900. {
  3901. ProcessValueTypeInstantiation(type, node);
  3902. return;
  3903. }
  3904. IConstructor ctor = GetCorrectConstructor(node, type, node.Arguments);
  3905. if (null != ctor)
  3906. {
  3907. BindConstructorInvocation(node, ctor);
  3908. if (node.NamedArguments.Count > 0)
  3909. {
  3910. ReplaceTypeInvocationByEval(type, node);
  3911. }
  3912. }
  3913. else
  3914. {
  3915. Error(node);
  3916. }
  3917. }
  3918. void BindConstructorInvocation(MethodInvocationExpression node, IConstructor ctor)
  3919. {
  3920. // rebind the target now we know
  3921. // it is a constructor call
  3922. Bind(node.Target, ctor);
  3923. BindExpressionType(node.Target, ctor.Type);
  3924. BindExpressionType(node, ctor.DeclaringType);
  3925. }
  3926. private void ProcessValueTypeInstantiation(IType type, MethodInvocationExpression node)
  3927. {
  3928. // XXX: naive and unoptimized but correct approach
  3929. // simply initialize a new temporary value type
  3930. // TODO: OPTIMIZE by detecting assignments to local variables
  3931. MethodInvocationExpression eval = CodeBuilder.CreateEvalInvocation(node.LexicalInfo);
  3932. BindExpressionType(eval, type);
  3933. InternalLocal local = DeclareTempLocal(type);
  3934. ReferenceExpression localReference = CodeBuilder.CreateReference(local);
  3935. eval.Arguments.Add(CodeBuilder.CreateDefaultInitializer(node.LexicalInfo, local));
  3936. AddResolvedNamedArgumentsToEval(eval, node.NamedArguments, localReference);
  3937. eval.Arguments.Add(localReference);
  3938. node.ParentNode.Replace(node, eval);
  3939. }
  3940. void ProcessGenericMethodInvocation(MethodInvocationExpression node)
  3941. {
  3942. IType type = GetExpressionType(node.Target);
  3943. if (TypeSystemServices.IsCallable(type))
  3944. {
  3945. ProcessMethodInvocationOnCallableExpression(node);
  3946. }
  3947. else
  3948. {
  3949. Error(node,
  3950. CompilerErrorFactory.TypeIsNotCallable(node.Target, type.ToString()));
  3951. }
  3952. }
  3953. void ProcessMethodInvocationOnCallableExpression(MethodInvocationExpression node)
  3954. {
  3955. IType type = node.Target.ExpressionType;
  3956. ICallableType delegateType = type as ICallableType;
  3957. if (null != delegateType)
  3958. {
  3959. if (AssertParameters(node.Target, delegateType, delegateType, node.Arguments))
  3960. {
  3961. IMethod invoke = ResolveMethod(delegateType, "Invoke");
  3962. node.Target = CodeBuilder.CreateMemberReference(node.Target, invoke);
  3963. BindExpressionType(node, invoke.ReturnType);
  3964. }
  3965. else
  3966. {
  3967. Error(node);
  3968. }
  3969. }
  3970. else if (TypeSystemServices.ICallableType.IsAssignableFrom(type))
  3971. {
  3972. node.Target = CodeBuilder.CreateMemberReference(node.Target, ICallable_Call);
  3973. ArrayLiteralExpression arg = CodeBuilder.CreateObjectArray(node.Arguments);
  3974. node.Arguments.Clear();
  3975. node.Arguments.Add(arg);
  3976. BindExpressionType(node, ICallable_Call.ReturnType);
  3977. }
  3978. else if (TypeSystemServices.TypeType == type)
  3979. {
  3980. ProcessSystemTypeInvocation(node);
  3981. }
  3982. else
  3983. {
  3984. ProcessInvocationOnUnknownCallableExpression(node);
  3985. }
  3986. }
  3987. private void ProcessSystemTypeInvocation(MethodInvocationExpression node)
  3988. {
  3989. MethodInvocationExpression invocation = CreateInstanceInvocationFor(node);
  3990. if (invocation.NamedArguments.Count == 0)
  3991. {
  3992. node.ParentNode.Replace(node, invocation);
  3993. return;
  3994. }
  3995. ProcessNamedArgumentsForTypeInvocation(invocation);
  3996. node.ParentNode.Replace(node, EvalForTypeInvocation(TypeSystemServices.ObjectType, invocation));
  3997. }
  3998. private void ProcessNamedArgumentsForTypeInvocation(MethodInvocationExpression invocation)
  3999. {
  4000. foreach (ExpressionPair pair in invocation.NamedArguments)
  4001. {
  4002. if (!ProcessNamedArgument(pair)) continue;
  4003. NamedArgumentNotFound(TypeSystemServices.ObjectType, (ReferenceExpression)pair.First);
  4004. }
  4005. }
  4006. private MethodInvocationExpression CreateInstanceInvocationFor(MethodInvocationExpression node)
  4007. {
  4008. MethodInvocationExpression invocation = CodeBuilder.CreateMethodInvocation(Activator_CreateInstance, node.Target);
  4009. if (Activator_CreateInstance.AcceptVarArgs)
  4010. {
  4011. invocation.Arguments.Extend(node.Arguments);
  4012. }
  4013. else
  4014. {
  4015. invocation.Arguments.Add(CodeBuilder.CreateObjectArray(node.Arguments));
  4016. }
  4017. invocation.NamedArguments = node.NamedArguments;
  4018. return invocation;
  4019. }
  4020. protected virtual void ProcessInvocationOnUnknownCallableExpression(MethodInvocationExpression node)
  4021. {
  4022. NotImplemented(node, "Method invocation on type '" + node.Target.ExpressionType + "'.");
  4023. }
  4024. bool AssertIdentifierName(Node node, string name)
  4025. {
  4026. if (TypeSystemServices.IsPrimitive(name))
  4027. {
  4028. Error(CompilerErrorFactory.CantRedefinePrimitive(node, name));
  4029. return false;
  4030. }
  4031. return true;
  4032. }
  4033. private bool CheckIsNotValueType(BinaryExpression node, Expression expression)
  4034. {
  4035. IType tag = GetExpressionType(expression);
  4036. if (tag.IsValueType)
  4037. {
  4038. Error(CompilerErrorFactory.OperatorCantBeUsedWithValueType(
  4039. expression,
  4040. GetBinaryOperatorText(node.Operator),
  4041. tag.ToString()));
  4042. return false;
  4043. }
  4044. return true;
  4045. }
  4046. void BindAssignmentToSlice(BinaryExpression node)
  4047. {
  4048. SlicingExpression slice = (SlicingExpression)node.Left;
  4049. if (!IsAmbiguous(slice.Target.Entity)
  4050. && GetExpressionType(slice.Target).IsArray)
  4051. {
  4052. BindAssignmentToSliceArray(node);
  4053. }
  4054. else if (TypeSystemServices.IsDuckTyped(slice.Target))
  4055. {
  4056. BindExpressionType(node, TypeSystemServices.DuckType);
  4057. }
  4058. else
  4059. {
  4060. BindAssignmentToSliceProperty(node);
  4061. }
  4062. }
  4063. void BindAssignmentToSliceArray(BinaryExpression node)
  4064. {
  4065. SlicingExpression slice = (SlicingExpression)node.Left;
  4066. IArrayType sliceTargetType = (IArrayType)GetExpressionType(slice.Target);
  4067. IType lhsType = GetExpressionType(node.Right);
  4068. foreach (Slice item in slice.Indices)
  4069. {
  4070. if (!AssertTypeCompatibility(item.Begin, TypeSystemServices.IntType, GetExpressionType(item.Begin)))
  4071. {
  4072. Error(node);
  4073. return;
  4074. }
  4075. }
  4076. if (slice.Indices.Count > 1)
  4077. {
  4078. if (AstUtil.IsComplexSlicing(slice))
  4079. {
  4080. // FIXME: Check type compatibility
  4081. BindAssignmentToComplexSliceArray(node);
  4082. }
  4083. else
  4084. {
  4085. if (!AssertTypeCompatibility(node.Right, sliceTargetType.GetElementType(), lhsType))
  4086. {
  4087. Error(node);
  4088. return;
  4089. }
  4090. BindAssignmentToSimpleSliceArray(node);
  4091. }
  4092. }
  4093. else
  4094. {
  4095. if (!AssertTypeCompatibility(node.Right, sliceTargetType.GetElementType(), lhsType))
  4096. {
  4097. Error(node);
  4098. return;
  4099. }
  4100. node.ExpressionType = sliceTargetType.GetElementType();
  4101. }
  4102. }
  4103. void BindAssignmentToSimpleSliceArray(BinaryExpression node)
  4104. {
  4105. SlicingExpression slice = (SlicingExpression)node.Left;
  4106. MethodInvocationExpression mie = CodeBuilder.CreateMethodInvocation(
  4107. slice.Target,
  4108. TypeSystemServices.Map(typeof(Array).GetMethod("SetValue", new Type[] { typeof(object), typeof(int[]) })),
  4109. node.Right);
  4110. for (int i = 0; i < slice.Indices.Count; i++)
  4111. {
  4112. mie.Arguments.Add(slice.Indices[i].Begin);
  4113. }
  4114. BindExpressionType(mie, TypeSystemServices.VoidType);
  4115. node.ParentNode.Replace(node, mie);
  4116. }
  4117. void BindAssignmentToComplexSliceArray(BinaryExpression node)
  4118. {
  4119. SlicingExpression slice = (SlicingExpression)node.Left;
  4120. ArrayLiteralExpression ale = new ArrayLiteralExpression();
  4121. ArrayLiteralExpression collapse = new ArrayLiteralExpression();
  4122. for (int i = 0; i < slice.Indices.Count; i++)
  4123. {
  4124. ale.Items.Add(slice.Indices[i].Begin);
  4125. if (null == slice.Indices[i].End ||
  4126. OmittedExpression.Default == slice.Indices[i].End)
  4127. {
  4128. ale.Items.Add(new IntegerLiteralExpression(1 + (int)((IntegerLiteralExpression)slice.Indices[i].Begin).Value));
  4129. collapse.Items.Add(new BoolLiteralExpression(true));
  4130. }
  4131. else
  4132. {
  4133. ale.Items.Add(slice.Indices[i].End);
  4134. collapse.Items.Add(new BoolLiteralExpression(false));
  4135. }
  4136. }
  4137. MethodInvocationExpression mie = CodeBuilder.CreateMethodInvocation(
  4138. RuntimeServices_SetMultiDimensionalRange1,
  4139. node.Right,
  4140. slice.Target,
  4141. ale);
  4142. mie.Arguments.Add(collapse);
  4143. BindExpressionType(mie, TypeSystemServices.VoidType);
  4144. BindExpressionType(ale, TypeSystemServices.Map(typeof(int[])));
  4145. BindExpressionType(collapse, TypeSystemServices.Map(typeof(bool[])));
  4146. node.ParentNode.Replace(node, mie);
  4147. }
  4148. void BindAssignmentToSliceProperty(BinaryExpression node)
  4149. {
  4150. SlicingExpression slice = (SlicingExpression)node.Left;
  4151. IEntity lhs = GetEntity(node.Left);
  4152. IMethod setter = null;
  4153. MethodInvocationExpression mie = new MethodInvocationExpression(node.Left.LexicalInfo);
  4154. foreach (Slice index in slice.Indices)
  4155. {
  4156. mie.Arguments.Add(index.Begin);
  4157. }
  4158. mie.Arguments.Add(node.Right);
  4159. if (EntityType.Property == lhs.EntityType)
  4160. {
  4161. IMethod setMethod = ((IProperty)lhs).GetSetMethod();
  4162. if (null == setMethod)
  4163. {
  4164. Error(node, CompilerErrorFactory.PropertyIsReadOnly(slice.Target, lhs.FullName));
  4165. return;
  4166. }
  4167. if (AssertParameters(node.Left, setMethod, mie.Arguments))
  4168. {
  4169. setter = setMethod;
  4170. }
  4171. }
  4172. else if (EntityType.Ambiguous == lhs.EntityType)
  4173. {
  4174. setter = (IMethod)GetCorrectCallableReference(node.Left, mie.Arguments, GetSetMethods(lhs));
  4175. if (setter == null)
  4176. {
  4177. Error(node.Left);
  4178. return;
  4179. }
  4180. }
  4181. if (null == setter)
  4182. {
  4183. Error(node, CompilerErrorFactory.LValueExpected(node.Left));
  4184. }
  4185. else
  4186. {
  4187. mie.Target = CodeBuilder.CreateMemberReference(
  4188. GetIndexedPropertySlicingTarget(slice),
  4189. setter);
  4190. BindExpressionType(mie, setter.ReturnType);
  4191. node.ParentNode.Replace(node, mie);
  4192. }
  4193. }
  4194. private IEntity[] GetSetMethods(IEntity candidates)
  4195. {
  4196. return GetSetMethods(((Ambiguous)candidates).Entities);
  4197. }
  4198. void BindAssignment(BinaryExpression node)
  4199. {
  4200. BindNullableOperation(node);
  4201. if (NodeType.SlicingExpression == node.Left.NodeType)
  4202. {
  4203. BindAssignmentToSlice(node);
  4204. }
  4205. else
  4206. {
  4207. ProcessAssignment(node);
  4208. }
  4209. }
  4210. virtual protected void ProcessAssignment(BinaryExpression node)
  4211. {
  4212. TryToResolveAmbiguousAssignment(node);
  4213. ValidateAssignment(node);
  4214. BindExpressionType(node, GetExpressionType(node.Right));
  4215. }
  4216. virtual protected void ValidateAssignment(BinaryExpression node)
  4217. {
  4218. IEntity lhs = node.Left.Entity;
  4219. IType rtype = GetExpressionType(node.Right);
  4220. if (AssertLValue(node.Left, lhs))
  4221. {
  4222. IType lhsType = GetExpressionType(node.Left);
  4223. AssertTypeCompatibility(node.Right, lhsType, rtype);
  4224. CheckAssignmentToIndexedProperty(node.Left, lhs);
  4225. }
  4226. }
  4227. virtual protected void TryToResolveAmbiguousAssignment(BinaryExpression node)
  4228. {
  4229. IEntity lhs = node.Left.Entity;
  4230. if (null == lhs) return;
  4231. if (EntityType.Ambiguous != lhs.EntityType) return;
  4232. Expression lvalue = node.Left;
  4233. lhs = ResolveAmbiguousLValue(lvalue, (Ambiguous)lhs, node.Right);
  4234. if (NodeType.ReferenceExpression == lvalue.NodeType)
  4235. {
  4236. IMember member = lhs as IMember;
  4237. if (null != member)
  4238. {
  4239. ResolveMemberInfo((ReferenceExpression)lvalue, member);
  4240. }
  4241. }
  4242. }
  4243. private void CheckAssignmentToIndexedProperty(Node node, IEntity lhs)
  4244. {
  4245. IProperty property = lhs as IProperty;
  4246. if (null != property && IsIndexedProperty(property))
  4247. {
  4248. Error(CompilerErrorFactory.PropertyRequiresParameters(AstUtil.GetMemberAnchor(node), property.FullName));
  4249. }
  4250. }
  4251. bool CheckIsaArgument(Expression e)
  4252. {
  4253. if (TypeSystemServices.TypeType != GetExpressionType(e))
  4254. {
  4255. Error(CompilerErrorFactory.IsaArgument(e));
  4256. return false;
  4257. }
  4258. return true;
  4259. }
  4260. bool BindNullableOperation(BinaryExpression node)
  4261. {
  4262. if (!IsNullableOperation(node))
  4263. return false;
  4264. if (BinaryOperatorType.ReferenceEquality == node.Operator)
  4265. {
  4266. node.Operator = BinaryOperatorType.Equality;
  4267. return BindNullableComparison(node);
  4268. }
  4269. else if (BinaryOperatorType.ReferenceInequality == node.Operator)
  4270. {
  4271. node.Operator = BinaryOperatorType.Inequality;
  4272. return BindNullableComparison(node);
  4273. }
  4274. IType lhs = GetExpressionType(node.Left);
  4275. IType rhs = GetExpressionType(node.Right);
  4276. bool lhsIsNullable = TypeSystemServices.IsNullable(lhs);
  4277. bool rhsIsNullable = TypeSystemServices.IsNullable(rhs);
  4278. if (BinaryOperatorType.Assign == node.Operator)
  4279. {
  4280. if (lhsIsNullable)
  4281. {
  4282. if (rhsIsNullable)
  4283. return false;
  4284. BindNullableInitializer(node, node.Right, lhs);
  4285. return false;
  4286. }
  4287. }
  4288. if (lhsIsNullable)
  4289. {
  4290. MemberReferenceExpression mre = new MemberReferenceExpression(node.Left, "Value");
  4291. node.Replace(node.Left, mre);
  4292. Visit(mre);
  4293. mre.Annotate("nullableTarget", true);
  4294. }
  4295. if (rhsIsNullable)
  4296. {
  4297. MemberReferenceExpression mre = new MemberReferenceExpression(node.Right, "Value");
  4298. node.Replace(node.Right, mre);
  4299. Visit(mre);
  4300. mre.Annotate("nullableTarget", true);
  4301. }
  4302. return false;
  4303. }
  4304. bool BindNullableComparison(BinaryExpression node)
  4305. {
  4306. if (!IsNullableOperation(node))
  4307. return false;
  4308. if (IsNull(node.Left) || IsNull(node.Right))
  4309. {
  4310. Expression nullable = IsNull(node.Left) ? node.Right : node.Left;
  4311. Expression val = new MemberReferenceExpression(nullable, "HasValue");
  4312. node.Replace(node.Left, val);
  4313. Visit(val);
  4314. Expression nil = new BoolLiteralExpression(false);
  4315. node.Replace(node.Right, nil);
  4316. Visit(nil);
  4317. BindExpressionType(node, TypeSystemServices.BoolType);
  4318. return true;
  4319. }
  4320. BinaryExpression valueCheck = new BinaryExpression(
  4321. BinaryOperatorType.BitwiseOr,
  4322. new BinaryExpression(
  4323. node.Operator,
  4324. CreateNullableHasValueOrTrueExpression(node.Left),
  4325. CreateNullableHasValueOrTrueExpression(node.Right)
  4326. ),
  4327. new BinaryExpression(
  4328. node.Operator,
  4329. CreateNullableGetValueOrDefaultExpression(node.Left),
  4330. CreateNullableGetValueOrDefaultExpression(node.Right)
  4331. )
  4332. );
  4333. node.ParentNode.Replace(node, valueCheck);
  4334. Visit(valueCheck);
  4335. return true;
  4336. }
  4337. private IEnumerable<Expression> FindNullableExpressions(Expression exp)
  4338. {
  4339. if (exp.ContainsAnnotation("nullableTarget"))
  4340. {
  4341. yield return ((MemberReferenceExpression) exp).Target;
  4342. }
  4343. else
  4344. {
  4345. BinaryExpression bex = exp as BinaryExpression;
  4346. if (null != bex)
  4347. {
  4348. foreach (Expression inner in FindNullableExpressions(bex.Left))
  4349. yield return inner;
  4350. foreach (Expression inner in FindNullableExpressions(bex.Right))
  4351. yield return inner;
  4352. }
  4353. }
  4354. }
  4355. private Expression BuildNullableCoalescingConditional(Expression exp)
  4356. {
  4357. if (IsNull(exp)) return null;
  4358. IEnumerator<Expression> enumerator = FindNullableExpressions(exp).GetEnumerator();
  4359. Expression root = null;
  4360. BinaryExpression and = null;
  4361. Expression lookahead = null;
  4362. while (enumerator.MoveNext())
  4363. {
  4364. Expression cur = enumerator.Current;
  4365. lookahead = enumerator.MoveNext() ? enumerator.Current : null;
  4366. if (null != and)
  4367. {
  4368. and.Right = new BinaryExpression(
  4369. BinaryOperatorType.BitwiseAnd,
  4370. and.Right,
  4371. new BinaryExpression(
  4372. BinaryOperatorType.BitwiseAnd,
  4373. CreateNullableHasValueOrTrueExpression(cur),
  4374. CreateNullableHasValueOrTrueExpression(lookahead)
  4375. )
  4376. );
  4377. }
  4378. else
  4379. {
  4380. if (null == lookahead)
  4381. return CreateNullableHasValueOrTrueExpression(cur);
  4382. root = and = new BinaryExpression(
  4383. BinaryOperatorType.BitwiseAnd,
  4384. CreateNullableHasValueOrTrueExpression(cur),
  4385. CreateNullableHasValueOrTrueExpression(lookahead)
  4386. );
  4387. }
  4388. }
  4389. return root;
  4390. }
  4391. void BindNullableInitializer(Node node, Expression rhs, IType type)
  4392. {
  4393. Expression instantiation = CreateNullableInstantiation(rhs, type);
  4394. node.Replace(rhs, instantiation);
  4395. Visit(instantiation);
  4396. Expression coalescing = BuildNullableCoalescingConditional(rhs);
  4397. if (null != coalescing) //rhs contains at least one nullable
  4398. {
  4399. ConditionalExpression cond = new ConditionalExpression();
  4400. cond.Condition = coalescing;
  4401. cond.TrueValue = instantiation;
  4402. cond.FalseValue = CreateNullableInstantiation(type);
  4403. node.Replace(instantiation, cond);
  4404. Visit(cond);
  4405. }
  4406. }
  4407. private Expression CreateNullableInstantiation(IType type)
  4408. {
  4409. return CreateNullableInstantiation(null, type);
  4410. }
  4411. private Expression CreateNullableInstantiation(Expression val, IType type)
  4412. {
  4413. MethodInvocationExpression mie = new MethodInvocationExpression();
  4414. GenericReferenceExpression gre = new GenericReferenceExpression();
  4415. gre.Target = new MemberReferenceExpression(new ReferenceExpression("System"), "Nullable");
  4416. gre.GenericArguments.Add(TypeReference.Lift(Nullable.GetUnderlyingType(((ExternalType) type).ActualType)));
  4417. mie.Target = gre;
  4418. if (null != val && !IsNull(val))
  4419. mie.Arguments.Add(val);
  4420. return mie;
  4421. }
  4422. private Expression CreateNullableHasValueOrTrueExpression(Expression target)
  4423. {
  4424. if (null == target || !TypeSystemServices.IsNullable(GetExpressionType(target)))
  4425. return new BoolLiteralExpression(true);
  4426. return new MemberReferenceExpression(target, "HasValue");
  4427. }
  4428. private Expression CreateNullableGetValueOrDefaultExpression(Expression target)
  4429. {
  4430. if (null == target || !TypeSystemServices.IsNullable(GetExpressionType(target)))
  4431. return target;
  4432. MethodInvocationExpression mie = new MethodInvocationExpression();
  4433. mie.Target = new MemberReferenceExpression(target, "GetValueOrDefault");
  4434. return mie;
  4435. }
  4436. void BindTypeTest(BinaryExpression node)
  4437. {
  4438. if (CheckIsNotValueType(node, node.Left) &&
  4439. CheckIsaArgument(node.Right))
  4440. {
  4441. BindExpressionType(node, TypeSystemServices.BoolType);
  4442. }
  4443. else
  4444. {
  4445. Error(node);
  4446. }
  4447. }
  4448. void BindReferenceEquality(BinaryExpression node)
  4449. {
  4450. if (BindNullableOperation(node))
  4451. {
  4452. return;
  4453. }
  4454. if (CheckIsNotValueType(node, node.Left) &&
  4455. CheckIsNotValueType(node, node.Right))
  4456. {
  4457. BindExpressionType(node, TypeSystemServices.BoolType);
  4458. }
  4459. else
  4460. {
  4461. Error(node);
  4462. }
  4463. }
  4464. void BindInPlaceArithmeticOperator(BinaryExpression node)
  4465. {
  4466. if (IsArraySlicing(node.Left))
  4467. {
  4468. BindInPlaceArithmeticOperatorOnArraySlicing(node);
  4469. return;
  4470. }
  4471. Node parent = node.ParentNode;
  4472. Expression target = node.Left;
  4473. if (null != target.Entity && EntityType.Property == target.Entity.EntityType)
  4474. {
  4475. // if target is a property force a rebinding
  4476. target.ExpressionType = null;
  4477. }
  4478. BinaryExpression assign = ExpandInPlaceBinaryExpression(node);
  4479. parent.Replace(node, assign);
  4480. Visit(assign);
  4481. }
  4482. protected BinaryExpression ExpandInPlaceBinaryExpression(BinaryExpression node)
  4483. {
  4484. BinaryExpression assign = new BinaryExpression(node.LexicalInfo);
  4485. assign.Operator = BinaryOperatorType.Assign;
  4486. assign.Left = node.Left.CloneNode();
  4487. assign.Right = node;
  4488. node.Operator = GetRelatedBinaryOperatorForInPlaceOperator(node.Operator);
  4489. return assign;
  4490. }
  4491. private void BindInPlaceArithmeticOperatorOnArraySlicing(BinaryExpression node)
  4492. {
  4493. Node parent = node.ParentNode;
  4494. Expression expansion = CreateSideEffectAwareSlicingOperation(
  4495. node.LexicalInfo,
  4496. GetRelatedBinaryOperatorForInPlaceOperator(node.Operator),
  4497. (SlicingExpression) node.Left,
  4498. node.Right,
  4499. null);
  4500. parent.Replace(node, expansion);
  4501. }
  4502. BinaryOperatorType GetRelatedBinaryOperatorForInPlaceOperator(BinaryOperatorType op)
  4503. {
  4504. switch (op)
  4505. {
  4506. case BinaryOperatorType.InPlaceAddition:
  4507. return BinaryOperatorType.Addition;
  4508. case BinaryOperatorType.InPlaceSubtraction:
  4509. return BinaryOperatorType.Subtraction;
  4510. case BinaryOperatorType.InPlaceMultiply:
  4511. return BinaryOperatorType.Multiply;
  4512. case BinaryOperatorType.InPlaceDivision:
  4513. return BinaryOperatorType.Division;
  4514. case BinaryOperatorType.InPlaceBitwiseAnd:
  4515. return BinaryOperatorType.BitwiseAnd;
  4516. case BinaryOperatorType.InPlaceBitwiseOr:
  4517. return BinaryOperatorType.BitwiseOr;
  4518. case BinaryOperatorType.InPlaceShiftLeft:
  4519. return BinaryOperatorType.ShiftLeft;
  4520. case BinaryOperatorType.InPlaceShiftRight:
  4521. return BinaryOperatorType.ShiftRight;
  4522. }
  4523. throw new ArgumentException("op");
  4524. }
  4525. void BindArrayAddition(BinaryExpression node)
  4526. {
  4527. IArrayType lhs = (IArrayType)GetExpressionType(node.Left);
  4528. IArrayType rhs = (IArrayType)GetExpressionType(node.Right);
  4529. if (lhs.GetElementType() == rhs.GetElementType())
  4530. {
  4531. node.ParentNode.Replace(
  4532. node,
  4533. CodeBuilder.CreateCast(
  4534. lhs,
  4535. CodeBuilder.CreateMethodInvocation(
  4536. RuntimeServices_AddArrays,
  4537. CodeBuilder.CreateTypeofExpression(lhs.GetElementType()),
  4538. node.Left,
  4539. node.Right)));
  4540. }
  4541. else
  4542. {
  4543. InvalidOperatorForTypes(node);
  4544. }
  4545. }
  4546. void BindArithmeticOperator(BinaryExpression node)
  4547. {
  4548. BindNullableOperation(node);
  4549. IType left = GetExpressionType(node.Left);
  4550. IType right = GetExpressionType(node.Right);
  4551. if (IsPrimitiveNumber(left) && IsPrimitiveNumber(right))
  4552. {
  4553. BindExpressionType(node, TypeSystemServices.GetPromotedNumberType(left, right));
  4554. }
  4555. else if (!ResolveOperator(node))
  4556. {
  4557. InvalidOperatorForTypes(node);
  4558. }
  4559. }
  4560. static string GetBinaryOperatorText(BinaryOperatorType op)
  4561. {
  4562. return BooPrinterVisitor.GetBinaryOperatorText(op);
  4563. }
  4564. static string GetUnaryOperatorText(UnaryOperatorType op)
  4565. {
  4566. return BooPrinterVisitor.GetUnaryOperatorText(op);
  4567. }
  4568. IEntity ResolveName(Node node, string name)
  4569. {
  4570. IEntity tag = NameResolutionService.Resolve(name);
  4571. CheckNameResolution(node, name, tag);
  4572. return tag;
  4573. }
  4574. bool CheckNameResolution(Node node, string name, IEntity tag)
  4575. {
  4576. if (null == tag)
  4577. {
  4578. Error(CompilerErrorFactory.UnknownIdentifier(node, name));
  4579. return false;
  4580. }
  4581. return true;
  4582. }
  4583. private bool IsPublicEvent(IEntity tag)
  4584. {
  4585. return (EntityType.Event == tag.EntityType) && ((IMember)tag).IsPublic;
  4586. }
  4587. private bool IsPublicFieldPropertyEvent(IEntity entity)
  4588. {
  4589. return IsFieldPropertyOrEvent(entity) && ((IMember)entity).IsPublic;
  4590. }
  4591. private static bool IsFieldPropertyOrEvent(IEntity entity)
  4592. {
  4593. return ((EntityType.Field|EntityType.Property|EntityType.Event) & entity.EntityType) > 0;
  4594. }
  4595. private IMember ResolvePublicFieldPropertyEvent(Expression sourceNode, IType type, string name)
  4596. {
  4597. IEntity candidate = ResolveFieldPropertyEvent(type, name);
  4598. if (null == candidate) return null;
  4599. if (IsPublicFieldPropertyEvent(candidate)) return (IMember)candidate;
  4600. if (candidate.EntityType != EntityType.Ambiguous) return null;
  4601. IList found = ((Ambiguous)candidate).Select(IsPublicFieldPropertyEvent);
  4602. if (found.Count == 0) return null;
  4603. if (found.Count == 1) return (IMember)found[0];
  4604. Error(sourceNode, CompilerErrorFactory.AmbiguousReference(sourceNode, name, found));
  4605. return null;
  4606. }
  4607. protected IEntity ResolveFieldPropertyEvent(IType type, string name)
  4608. {
  4609. return NameResolutionService.Resolve(type, name, EntityType.Property|EntityType.Event|EntityType.Field);
  4610. }
  4611. void ResolveNamedArguments(IType type, ExpressionPairCollection arguments)
  4612. {
  4613. foreach (ExpressionPair arg in arguments)
  4614. {
  4615. if (!ProcessNamedArgument(arg)) continue;
  4616. ResolveNamedArgument(type, (ReferenceExpression)arg.First, arg.Second);
  4617. }
  4618. }
  4619. private bool ProcessNamedArgument(ExpressionPair arg)
  4620. {
  4621. Visit(arg.Second);
  4622. if (NodeType.ReferenceExpression != arg.First.NodeType)
  4623. {
  4624. Error(arg.First, CompilerErrorFactory.NamedParameterMustBeIdentifier(arg));
  4625. return false;
  4626. }
  4627. return true;
  4628. }
  4629. void ResolveNamedArgument(IType type, ReferenceExpression name, Expression value)
  4630. {
  4631. IMember member = ResolvePublicFieldPropertyEvent(name, type, name.Name);
  4632. if (null == member)
  4633. {
  4634. NamedArgumentNotFound(type, name);
  4635. return;
  4636. }
  4637. EnsureRelatedNodeWasVisited(name, member);
  4638. Bind(name, member);
  4639. IType memberType = member.Type;
  4640. if (member.EntityType == EntityType.Event)
  4641. {
  4642. AssertDelegateArgument(value, member, GetExpressionType(value));
  4643. }
  4644. else
  4645. {
  4646. AssertTypeCompatibility(value, memberType, GetExpressionType(value));
  4647. }
  4648. }
  4649. protected virtual void NamedArgumentNotFound(IType type, ReferenceExpression name)
  4650. {
  4651. Error(name, CompilerErrorFactory.NotAPublicFieldOrProperty(name, type.ToString(), name.Name));
  4652. }
  4653. bool AssertTypeCompatibility(Node sourceNode, IType expectedType, IType actualType)
  4654. {
  4655. if (TypeSystemServices.IsError(expectedType)
  4656. || TypeSystemServices.IsError(actualType))
  4657. {
  4658. return false;
  4659. }
  4660. if (!TypeSystemServices.AreTypesRelated(expectedType, actualType))
  4661. {
  4662. Error(CompilerErrorFactory.IncompatibleExpressionType(sourceNode, expectedType.ToString(), actualType.ToString()));
  4663. return false;
  4664. }
  4665. return true;
  4666. }
  4667. bool AssertDelegateArgument(Node sourceNode, ITypedEntity delegateMember, ITypedEntity argumentInfo)
  4668. {
  4669. if (!delegateMember.Type.IsAssignableFrom(argumentInfo.Type))
  4670. {
  4671. Error(CompilerErrorFactory.EventArgumentMustBeAMethod(sourceNode, delegateMember.FullName, delegateMember.Type.ToString()));
  4672. return false;
  4673. }
  4674. return true;
  4675. }
  4676. bool CheckParameterTypesStrictly(IMethod method, ExpressionCollection args)
  4677. {
  4678. IParameter[] parameters = method.GetParameters();
  4679. for (int i=0; i<args.Count; ++i)
  4680. {
  4681. IType expressionType = GetExpressionType(args[i]);
  4682. IType parameterType = parameters[i].Type;
  4683. if (!IsAssignableFrom(parameterType, expressionType) &&
  4684. !(IsNumber(expressionType) && IsNumber(parameterType))
  4685. && TypeSystemServices.FindImplicitConversionOperator(expressionType,parameterType) == null)
  4686. {
  4687. return false;
  4688. }
  4689. }
  4690. return true;
  4691. }
  4692. bool AssertParameterTypes(ICallableType method, ExpressionCollection args, int count, bool reportErrors)
  4693. {
  4694. IParameter[] parameters = method.GetSignature().Parameters;
  4695. for (int i=0; i<count; ++i)
  4696. {
  4697. IParameter param = parameters[i];
  4698. IType parameterType = param.Type;
  4699. IType argumentType = GetExpressionType(args[i]);
  4700. if (param.IsByRef)
  4701. {
  4702. if (!(args[i] is ReferenceExpression
  4703. || args[i] is SlicingExpression))
  4704. {
  4705. if (reportErrors) Error(CompilerErrorFactory.RefArgTakesLValue(args[i]));
  4706. return false;
  4707. }
  4708. if (!_callableResolution.IsValidByRefArg(param, parameterType, argumentType, args[i]))
  4709. {
  4710. return false;
  4711. }
  4712. }
  4713. else
  4714. {
  4715. if (!TypeSystemServices.AreTypesRelated(parameterType, argumentType))
  4716. {
  4717. return false;
  4718. }
  4719. }
  4720. }
  4721. return true;
  4722. }
  4723. bool AssertParameters(Node sourceNode, IMethod method, ExpressionCollection args)
  4724. {
  4725. return AssertParameters(sourceNode, method, method.CallableType, args);
  4726. }
  4727. bool AcceptVarArgs(ICallableType method)
  4728. {
  4729. return method.GetSignature().AcceptVarArgs;
  4730. }
  4731. bool AssertParameters(Node sourceNode, IEntity sourceEntity, ICallableType method, ExpressionCollection args)
  4732. {
  4733. if (CheckParameters(method, args, true)) return true;
  4734. Error(CompilerErrorFactory.MethodSignature(sourceNode, sourceEntity.ToString(), GetSignature(args)));
  4735. return false;
  4736. }
  4737. private bool CheckParameters(ICallableType method, ExpressionCollection args, bool reportErrors)
  4738. {
  4739. return AcceptVarArgs(method)
  4740. ? CheckVarArgsParameters(method, args)
  4741. : CheckExactArgsParameters(method, args, reportErrors);
  4742. }
  4743. bool CheckVarArgsParameters(ICallableType method, ExpressionCollection args)
  4744. {
  4745. return _callableResolution.IsValidVargsInvocation(method.GetSignature().Parameters, args);
  4746. }
  4747. bool CheckExactArgsParameters(ICallableType method, ExpressionCollection args, bool reportErrors)
  4748. {
  4749. if (method.GetSignature().Parameters.Length != args.Count) return false;
  4750. return AssertParameterTypes(method, args, args.Count, reportErrors);
  4751. }
  4752. bool IsRuntimeIterator(IType type)
  4753. {
  4754. return TypeSystemServices.IsSystemObject(type)
  4755. || IsTextReader(type);
  4756. }
  4757. bool IsTextReader(IType type)
  4758. {
  4759. return IsAssignableFrom(typeof(TextReader), type);
  4760. }
  4761. bool AssertTargetContext(Expression targetContext, IMember member)
  4762. {
  4763. if (member.IsStatic) return true;
  4764. if (NodeType.MemberReferenceExpression != targetContext.NodeType) return true;
  4765. Expression targetReference = ((MemberReferenceExpression)targetContext).Target;
  4766. IEntity entity = targetReference.Entity;
  4767. if ((null != entity && EntityType.Type == entity.EntityType)
  4768. || (NodeType.SelfLiteralExpression == targetReference.NodeType
  4769. && _currentMethod.IsStatic))
  4770. {
  4771. Error(CompilerErrorFactory.InstanceRequired(targetContext, member.DeclaringType.ToString(), member.Name));
  4772. return false;
  4773. }
  4774. return true;
  4775. }
  4776. static bool IsAssignableFrom(IType expectedType, IType actualType)
  4777. {
  4778. return expectedType.IsAssignableFrom(actualType);
  4779. }
  4780. bool IsAssignableFrom(Type expectedType, IType actualType)
  4781. {
  4782. return TypeSystemServices.Map(expectedType).IsAssignableFrom(actualType);
  4783. }
  4784. bool IsNumber(IType type)
  4785. {
  4786. return TypeSystemServices.IsNumber(type);
  4787. }
  4788. bool IsPrimitiveNumber(IType type)
  4789. {
  4790. return TypeSystemServices.IsPrimitiveNumber(type);
  4791. }
  4792. bool IsPrimitiveNumber(Expression expression)
  4793. {
  4794. return IsPrimitiveNumber(GetExpressionType(expression));
  4795. }
  4796. IConstructor GetCorrectConstructor(Node sourceNode, IType type, ExpressionCollection arguments)
  4797. {
  4798. IConstructor[] constructors = type.GetConstructors();
  4799. if (null != constructors && constructors.Length > 0)
  4800. {
  4801. return (IConstructor)GetCorrectCallableReference(sourceNode, arguments, constructors);
  4802. }
  4803. else
  4804. {
  4805. if (!TypeSystemServices.IsError(type))
  4806. {
  4807. if (null == (type as IGenericParameter))
  4808. {
  4809. Error(CompilerErrorFactory.NoApropriateConstructorFound(sourceNode, type.ToString(), GetSignature(arguments)));
  4810. }
  4811. else
  4812. {
  4813. Error(CompilerErrorFactory.CannotCreateAnInstanceOfGenericParameterWithoutDefaultConstructorConstraint(sourceNode, type.ToString()));
  4814. }
  4815. }
  4816. }
  4817. return null;
  4818. }
  4819. IEntity GetCorrectCallableReference(Node sourceNode, ExpressionCollection args, IEntity[] candidates)
  4820. {
  4821. // BOO-844: Ensure all candidates were visited (to make property setters have correct signature)
  4822. foreach (IEntity candidate in candidates)
  4823. {
  4824. EnsureRelatedNodeWasVisited(sourceNode, candidate);
  4825. }
  4826. IEntity found = _callableResolution.ResolveCallableReference(args, candidates);
  4827. if (null == found) EmitCallableResolutionError(sourceNode, candidates, args);
  4828. return found;
  4829. }
  4830. private void EmitCallableResolutionError(Node sourceNode, IEntity[] candidates, ExpressionCollection args)
  4831. {
  4832. if (_callableResolution.ValidCandidates.Count > 1)
  4833. {
  4834. Error(CompilerErrorFactory.AmbiguousReference(sourceNode, candidates[0].Name, _callableResolution.ValidCandidates));
  4835. }
  4836. else
  4837. {
  4838. IEntity candidate = candidates[0];
  4839. IConstructor constructor = candidate as IConstructor;
  4840. if (null != constructor)
  4841. {
  4842. Error(CompilerErrorFactory.NoApropriateConstructorFound(sourceNode, constructor.DeclaringType.ToString(), GetSignature(args)));
  4843. }
  4844. else
  4845. {
  4846. Error(CompilerErrorFactory.NoApropriateOverloadFound(sourceNode, GetSignature(args), candidate.FullName));
  4847. }
  4848. }
  4849. }
  4850. override protected void EnsureRelatedNodeWasVisited(Node sourceNode, IEntity entity)
  4851. {
  4852. IInternalEntity internalInfo = entity as IInternalEntity;
  4853. if (null == internalInfo)
  4854. {
  4855. ITypedEntity typedEntity = entity as ITypedEntity;
  4856. if (null == typedEntity) return;
  4857. internalInfo = typedEntity.Type as IInternalEntity;
  4858. if (null == internalInfo) return;
  4859. }
  4860. Node node = internalInfo.Node;
  4861. //member has been used so remove private member unused annotation
  4862. TypeMember member = node as TypeMember;
  4863. if (null != member
  4864. && member.IsPrivate
  4865. && member.ContainsAnnotation("PrivateMemberNeverUsed"))
  4866. {
  4867. node.RemoveAnnotation("PrivateMemberNeverUsed");
  4868. }
  4869. switch (node.NodeType)
  4870. {
  4871. case NodeType.Property:
  4872. case NodeType.Field:
  4873. {
  4874. IMember memberEntity = (IMember)entity;
  4875. if (EntityType.Property == entity.EntityType
  4876. || TypeSystemServices.IsUnknown(memberEntity.Type))
  4877. {
  4878. VisitMemberForTypeResolution(node);
  4879. AssertTypeIsKnown(sourceNode, memberEntity, memberEntity.Type);
  4880. }
  4881. break;
  4882. }
  4883. case NodeType.Method:
  4884. {
  4885. IMethod methodEntity = (IMethod)entity;
  4886. if (TypeSystemServices.IsUnknown(methodEntity.ReturnType))
  4887. {
  4888. // try to preprocess the method to resolve its return type
  4889. Method method = (Method)node;
  4890. PreProcessMethod(method);
  4891. if (TypeSystemServices.IsUnknown(methodEntity.ReturnType))
  4892. {
  4893. // still unknown?
  4894. VisitMemberForTypeResolution(node);
  4895. AssertTypeIsKnown(sourceNode, methodEntity, methodEntity.ReturnType);
  4896. }
  4897. }
  4898. break;
  4899. }
  4900. case NodeType.ClassDefinition:
  4901. case NodeType.StructDefinition:
  4902. case NodeType.InterfaceDefinition:
  4903. {
  4904. if (WasVisited(node)) break;
  4905. VisitInParentNamespace(node);
  4906. //visit dependent attributes such as EnumeratorItemType
  4907. //foreach (Attribute att in ((TypeDefinition)node).Attributes)
  4908. {
  4909. //VisitMemberForTypeResolution(att);
  4910. }
  4911. break;
  4912. }
  4913. }
  4914. }
  4915. private void VisitInParentNamespace(Node node)
  4916. {
  4917. INamespace saved = NameResolutionService.CurrentNamespace;
  4918. try
  4919. {
  4920. NameResolutionService.EnterNamespace((INamespace)node.ParentNode.Entity);
  4921. Visit(node);
  4922. }
  4923. finally
  4924. {
  4925. NameResolutionService.Restore(saved);
  4926. }
  4927. }
  4928. private void AssertTypeIsKnown(Node sourceNode, IEntity sourceEntity, IType type)
  4929. {
  4930. if (TypeSystemServices.IsUnknown(type))
  4931. {
  4932. Error(
  4933. CompilerErrorFactory.UnresolvedDependency(
  4934. sourceNode,
  4935. CurrentMember.FullName,
  4936. sourceEntity.FullName));
  4937. }
  4938. }
  4939. void VisitMemberForTypeResolution(Node node)
  4940. {
  4941. if (WasVisited(node)) return;
  4942. _context.TraceVerbose("Info {0} needs resolving.", node.Entity.Name);
  4943. INamespace saved = NameResolutionService.CurrentNamespace;
  4944. try
  4945. {
  4946. Visit(node);
  4947. }
  4948. finally
  4949. {
  4950. NameResolutionService.Restore(saved);
  4951. }
  4952. }
  4953. bool ResolveOperator(UnaryExpression node)
  4954. {
  4955. MethodInvocationExpression mie = new MethodInvocationExpression(node.LexicalInfo);
  4956. mie.Arguments.Add(node.Operand.CloneNode());
  4957. string operatorName = AstUtil.GetMethodNameForOperator(node.Operator);
  4958. IType operand = GetExpressionType(node.Operand);
  4959. if (ResolveOperator(node, operand, operatorName, mie))
  4960. {
  4961. return true;
  4962. }
  4963. return ResolveOperator(node, TypeSystemServices.RuntimeServicesType, operatorName, mie);
  4964. }
  4965. bool ResolveOperator(BinaryExpression node)
  4966. {
  4967. MethodInvocationExpression mie = new MethodInvocationExpression(node.LexicalInfo);
  4968. mie.Arguments.Add(node.Left.CloneNode());
  4969. mie.Arguments.Add(node.Right.CloneNode());
  4970. string operatorName = AstUtil.GetMethodNameForOperator(node.Operator);
  4971. IType lhs = GetExpressionType(node.Left);
  4972. if (ResolveOperator(node, lhs, operatorName, mie))
  4973. {
  4974. return true;
  4975. }
  4976. IType rhs = GetExpressionType(node.Right);
  4977. if (ResolveOperator(node, rhs, operatorName, mie))
  4978. {
  4979. return true;
  4980. }
  4981. return ResolveRuntimeOperator(node, operatorName, mie);
  4982. }
  4983. protected virtual bool ResolveRuntimeOperator(BinaryExpression node, string operatorName, MethodInvocationExpression mie)
  4984. {
  4985. return ResolveOperator(node, TypeSystemServices.RuntimeServicesType, operatorName, mie);
  4986. }
  4987. IMethod ResolveAmbiguousOperator(IEntity[] entities, ExpressionCollection args)
  4988. {
  4989. foreach (IEntity entity in entities)
  4990. {
  4991. IMethod method = entity as IMethod;
  4992. if (null != method)
  4993. {
  4994. if (HasOperatorSignature(method, args))
  4995. {
  4996. return method;
  4997. }
  4998. }
  4999. }
  5000. return null;
  5001. }
  5002. bool HasOperatorSignature(IMethod method, ExpressionCollection args)
  5003. {
  5004. return method.IsStatic &&
  5005. (args.Count == method.GetParameters().Length) &&
  5006. CheckParameterTypesStrictly(method, args);
  5007. }
  5008. IMethod FindOperator(IType type, string operatorName, ExpressionCollection args)
  5009. {
  5010. IEntity entity = NameResolutionService.Resolve(type, operatorName, EntityType.Method);
  5011. if (null != entity)
  5012. {
  5013. IMethod method = ResolveOperatorEntity(entity, args);
  5014. if (null != method) return method;
  5015. }
  5016. entity = NameResolutionService.ResolveExtension(type, operatorName);
  5017. if (null != entity)
  5018. {
  5019. return ResolveOperatorEntity(entity, args);
  5020. }
  5021. return null;
  5022. }
  5023. private IMethod ResolveOperatorEntity(IEntity op, ExpressionCollection args)
  5024. {
  5025. if (EntityType.Ambiguous == op.EntityType)
  5026. {
  5027. return ResolveAmbiguousOperator(((Ambiguous)op).Entities, args);
  5028. }
  5029. if (EntityType.Method == op.EntityType)
  5030. {
  5031. IMethod candidate = (IMethod)op;
  5032. if (HasOperatorSignature(candidate, args))
  5033. {
  5034. return candidate;
  5035. }
  5036. }
  5037. return null;
  5038. }
  5039. bool ResolveOperator(Expression node, IType type, string operatorName, MethodInvocationExpression mie)
  5040. {
  5041. IMethod entity = FindOperator(type, operatorName, mie.Arguments);
  5042. if (null == entity) return false;
  5043. EnsureRelatedNodeWasVisited(node, entity);
  5044. mie.Target = new ReferenceExpression(entity.FullName);
  5045. IMethod operatorMethod = entity;
  5046. BindExpressionType(mie, operatorMethod.ReturnType);
  5047. BindExpressionType(mie.Target, operatorMethod.Type);
  5048. Bind(mie.Target, entity);
  5049. node.ParentNode.Replace(node, mie);
  5050. return true;
  5051. }
  5052. Expression AssertBoolContext(Expression expression)
  5053. {
  5054. IType type = GetExpressionType(expression);
  5055. if (type == TypeSystemServices.BoolType) return expression;
  5056. if (IsNumber(type)) return expression;
  5057. if (type.IsEnum) return expression;
  5058. // nullable types can be used in bool context
  5059. if (TypeSystemServices.IsNullable(type))
  5060. {
  5061. MemberReferenceExpression mre = new MemberReferenceExpression(expression, "HasValue");
  5062. Visit(mre);
  5063. return mre;
  5064. }
  5065. IMethod method = TypeSystemServices.FindImplicitConversionOperator(type, TypeSystemServices.BoolType);
  5066. if (null != method) return CodeBuilder.CreateMethodInvocation(method, expression);
  5067. // reference types can be used in bool context
  5068. if (!type.IsValueType) return expression;
  5069. Error(CompilerErrorFactory.BoolExpressionRequired(expression, type.ToString()));
  5070. return expression;
  5071. }
  5072. ReferenceExpression CreateTempLocal(LexicalInfo li, IType type)
  5073. {
  5074. InternalLocal local = DeclareTempLocal(type);
  5075. ReferenceExpression reference = new ReferenceExpression(li, local.Name);
  5076. reference.Entity = local;
  5077. reference.ExpressionType = type;
  5078. return reference;
  5079. }
  5080. protected InternalLocal DeclareTempLocal(IType localType)
  5081. {
  5082. return CodeBuilder.DeclareTempLocal(_currentMethod.Method, localType);
  5083. }
  5084. IEntity DeclareLocal(Node sourceNode, string name, IType localType)
  5085. {
  5086. return DeclareLocal(sourceNode, name, localType, false);
  5087. }
  5088. virtual protected IEntity DeclareLocal(Node sourceNode, string name, IType localType, bool privateScope)
  5089. {
  5090. Local local = new Local(name, privateScope);
  5091. local.LexicalInfo = sourceNode.LexicalInfo;
  5092. InternalLocal entity = new InternalLocal(local, localType);
  5093. local.Entity = entity;
  5094. _currentMethod.Method.Locals.Add(local);
  5095. return entity;
  5096. }
  5097. protected IType CurrentType
  5098. {
  5099. get
  5100. {
  5101. return _currentMethod.DeclaringType;
  5102. }
  5103. }
  5104. void PushMember(TypeMember member)
  5105. {
  5106. _memberStack.Push(member);
  5107. }
  5108. TypeMember CurrentMember
  5109. {
  5110. get
  5111. {
  5112. return (TypeMember)_memberStack.Peek();
  5113. }
  5114. }
  5115. void PopMember()
  5116. {
  5117. _memberStack.Pop();
  5118. }
  5119. void PushMethodInfo(InternalMethod tag)
  5120. {
  5121. _methodStack.Push(_currentMethod);
  5122. _currentMethod = tag;
  5123. }
  5124. void PopMethodInfo()
  5125. {
  5126. _currentMethod = (InternalMethod)_methodStack.Pop();
  5127. }
  5128. void AssertHasSideEffect(Expression expression)
  5129. {
  5130. if (!HasSideEffect(expression) && !TypeSystemServices.IsError(expression))
  5131. {
  5132. Error(CompilerErrorFactory.ExpressionMustBeExecutedForItsSideEffects(expression));
  5133. }
  5134. }
  5135. protected virtual bool HasSideEffect(Expression node)
  5136. {
  5137. return
  5138. node.NodeType == NodeType.MethodInvocationExpression ||
  5139. AstUtil.IsAssignment(node) ||
  5140. AstUtil.IsIncDec(node);
  5141. }
  5142. bool AssertCanCreateInstance(Node sourceNode, IType type)
  5143. {
  5144. if (type.IsInterface)
  5145. {
  5146. Error(CompilerErrorFactory.CantCreateInstanceOfInterface(sourceNode, type.ToString()));
  5147. return false;
  5148. }
  5149. if (type.IsEnum)
  5150. {
  5151. Error(CompilerErrorFactory.CantCreateInstanceOfEnum(sourceNode, type.ToString()));
  5152. return false;
  5153. }
  5154. if (type.IsAbstract)
  5155. {
  5156. Error(CompilerErrorFactory.CantCreateInstanceOfAbstractType(sourceNode, type.ToString()));
  5157. return false;
  5158. }
  5159. if (!(type is GenericConstructedType)
  5160. &&
  5161. ((type.GenericInfo != null
  5162. && type.GenericInfo.GenericParameters.Length > 0)
  5163. || (type.ConstructedInfo != null
  5164. && !type.ConstructedInfo.FullyConstructed))
  5165. )
  5166. {
  5167. Error(CompilerErrorFactory.GenericTypesMustBeConstructedToBeInstantiated(sourceNode));
  5168. return false;
  5169. }
  5170. return true;
  5171. }
  5172. bool AssertDeclarationName(Declaration d)
  5173. {
  5174. if (AssertIdentifierName(d, d.Name))
  5175. {
  5176. return AssertUniqueLocal(d);
  5177. }
  5178. return false;
  5179. }
  5180. bool AssertUniqueLocal(Declaration d)
  5181. {
  5182. if (null == _currentMethod.ResolveLocal(d.Name) &&
  5183. null == _currentMethod.ResolveParameter(d.Name))
  5184. {
  5185. return true;
  5186. }
  5187. Error(CompilerErrorFactory.LocalAlreadyExists(d, d.Name));
  5188. return false;
  5189. }
  5190. void GetDeclarationType(IType defaultDeclarationType, Declaration d)
  5191. {
  5192. if (null != d.Type)
  5193. {
  5194. Visit(d.Type);
  5195. AssertTypeCompatibility(d, GetType(d.Type), defaultDeclarationType);
  5196. }
  5197. else
  5198. {
  5199. d.Type = CodeBuilder.CreateTypeReference(defaultDeclarationType);
  5200. }
  5201. }
  5202. void DeclareLocal(Declaration d, bool privateScope)
  5203. {
  5204. if (AssertIdentifierName(d, d.Name))
  5205. {
  5206. d.Entity = DeclareLocal(d, d.Name, GetType(d.Type), privateScope);
  5207. }
  5208. }
  5209. protected IType GetEnumeratorItemType(IType iteratorType)
  5210. {
  5211. return TypeSystemServices.GetEnumeratorItemType(iteratorType);
  5212. }
  5213. protected void ProcessDeclarationsForIterator(DeclarationCollection declarations, IType iteratorType)
  5214. {
  5215. IType defaultDeclType = GetEnumeratorItemType(iteratorType);
  5216. if (declarations.Count > 1)
  5217. {
  5218. // will enumerate (unpack) each item
  5219. defaultDeclType = GetEnumeratorItemType(defaultDeclType);
  5220. }
  5221. foreach (Declaration d in declarations)
  5222. {
  5223. ProcessDeclarationForIterator(d, defaultDeclType);
  5224. }
  5225. }
  5226. protected void ProcessDeclarationForIterator(Declaration d, IType defaultDeclType)
  5227. {
  5228. GetDeclarationType(defaultDeclType, d);
  5229. DeclareLocal(d, true);
  5230. }
  5231. protected virtual bool AssertLValue(Node node)
  5232. {
  5233. IEntity entity = node.Entity;
  5234. if (null != entity) return AssertLValue(node, entity);
  5235. if (IsArraySlicing(node)) return true;
  5236. Error(CompilerErrorFactory.LValueExpected(node));
  5237. return false;
  5238. }
  5239. protected virtual bool AssertLValue(Node node, IEntity entity)
  5240. {
  5241. if (null != entity)
  5242. {
  5243. switch (entity.EntityType)
  5244. {
  5245. case EntityType.Parameter:
  5246. case EntityType.Local:
  5247. {
  5248. return true;
  5249. }
  5250. case EntityType.Property:
  5251. {
  5252. if (null == ((IProperty)entity).GetSetMethod())
  5253. {
  5254. Error(CompilerErrorFactory.PropertyIsReadOnly(AstUtil.GetMemberAnchor(node), entity.FullName));
  5255. return false;
  5256. }
  5257. return true;
  5258. }
  5259. case EntityType.Field:
  5260. {
  5261. IField fld = (IField)entity;
  5262. if (TypeSystemServices.IsReadOnlyField(fld)
  5263. && !(EntityType.Constructor == _currentMethod.EntityType
  5264. && _currentMethod.DeclaringType == fld.DeclaringType
  5265. && fld.IsStatic == _currentMethod.IsStatic))
  5266. {
  5267. Error(CompilerErrorFactory.FieldIsReadonly(AstUtil.GetMemberAnchor(node), entity.FullName));
  5268. return false;
  5269. }
  5270. return true;
  5271. }
  5272. }
  5273. }
  5274. Error(CompilerErrorFactory.LValueExpected(node));
  5275. return false;
  5276. }
  5277. public static bool IsArraySlicing(Node node)
  5278. {
  5279. if (node.NodeType != NodeType.SlicingExpression) return false;
  5280. IType type = ((SlicingExpression)node).Target.ExpressionType;
  5281. return null != type && type.IsArray;
  5282. }
  5283. bool IsStandaloneReference(Node node)
  5284. {
  5285. Node parent = node.ParentNode;
  5286. if (parent is GenericReferenceExpression)
  5287. {
  5288. parent = parent.ParentNode;
  5289. }
  5290. return parent.NodeType != NodeType.MemberReferenceExpression;
  5291. }
  5292. string GetSignature(IEnumerable args)
  5293. {
  5294. StringBuilder sb = new StringBuilder("(");
  5295. foreach (Expression arg in args)
  5296. {
  5297. if (sb.Length > 1)
  5298. {
  5299. sb.Append(", ");
  5300. }
  5301. if (AstUtil.IsExplodeExpression(arg))
  5302. {
  5303. sb.Append('*');
  5304. }
  5305. sb.Append(GetExpressionType(arg));
  5306. }
  5307. sb.Append(")");
  5308. return sb.ToString();
  5309. }
  5310. void InvalidOperatorForType(UnaryExpression node)
  5311. {
  5312. Error(node, CompilerErrorFactory.InvalidOperatorForType(node,
  5313. GetUnaryOperatorText(node.Operator),
  5314. GetExpressionType(node.Operand).ToString()));
  5315. }
  5316. void InvalidOperatorForTypes(BinaryExpression node)
  5317. {
  5318. Error(node, CompilerErrorFactory.InvalidOperatorForTypes(node,
  5319. GetBinaryOperatorText(node.Operator),
  5320. GetExpressionType(node.Left).ToString(),
  5321. GetExpressionType(node.Right).ToString()));
  5322. }
  5323. void TraceReturnType(Method method, IMethod tag)
  5324. {
  5325. _context.TraceInfo("{0}: return type for method {1} bound to {2}", method.LexicalInfo, method.Name, tag.ReturnType);
  5326. }
  5327. #region Method bindings cache
  5328. IMethod _RuntimeServices_Len;
  5329. IMethod RuntimeServices_Len
  5330. {
  5331. get
  5332. {
  5333. if (null == _RuntimeServices_Len)
  5334. {
  5335. _RuntimeServices_Len = ResolveMethod(TypeSystemServices.RuntimeServicesType, "Len");
  5336. }
  5337. return _RuntimeServices_Len;
  5338. }
  5339. }
  5340. IMethod _RuntimeServices_Mid;
  5341. IMethod RuntimeServices_Mid
  5342. {
  5343. get
  5344. {
  5345. if (null == _RuntimeServices_Mid)
  5346. {
  5347. _RuntimeServices_Mid = ResolveMethod(TypeSystemServices.RuntimeServicesType, "Mid");
  5348. }
  5349. return _RuntimeServices_Mid;
  5350. }
  5351. }
  5352. IMethod _RuntimeServices_NormalizeStringIndex;
  5353. IMethod RuntimeServices_NormalizeStringIndex
  5354. {
  5355. get
  5356. {
  5357. if (null == _RuntimeServices_NormalizeStringIndex)
  5358. {
  5359. _RuntimeServices_NormalizeStringIndex = ResolveMethod(TypeSystemServices.RuntimeServicesType, "NormalizeStringIndex");
  5360. }
  5361. return _RuntimeServices_NormalizeStringIndex;
  5362. }
  5363. }
  5364. IMethod _RuntimeServices_AddArrays;
  5365. IMethod RuntimeServices_AddArrays
  5366. {
  5367. get
  5368. {
  5369. if (null == _RuntimeServices_AddArrays)
  5370. {
  5371. _RuntimeServices_AddArrays = ResolveMethod(TypeSystemServices.RuntimeServicesType, "AddArrays");
  5372. }
  5373. return _RuntimeServices_AddArrays;
  5374. }
  5375. }
  5376. IMethod _RuntimeServices_GetRange1;
  5377. IMethod RuntimeServices_GetRange1
  5378. {
  5379. get
  5380. {
  5381. if (null == _RuntimeServices_GetRange1)
  5382. {
  5383. _RuntimeServices_GetRange1 = ResolveMethod(TypeSystemServices.RuntimeServicesType, "GetRange1");
  5384. }
  5385. return _RuntimeServices_GetRange1;
  5386. }
  5387. }
  5388. IMethod _RuntimeServices_GetRange2;
  5389. IMethod RuntimeServices_GetRange2
  5390. {
  5391. get
  5392. {
  5393. if (null == _RuntimeServices_GetRange2)
  5394. {
  5395. _RuntimeServices_GetRange2 = ResolveMethod(TypeSystemServices.RuntimeServicesType, "GetRange2");
  5396. }
  5397. return _RuntimeServices_GetRange2;
  5398. }
  5399. }
  5400. IMethod _RuntimeServices_GetMultiDimensionalRange1;
  5401. IMethod RuntimeServices_GetMultiDimensionalRange1
  5402. {
  5403. get
  5404. {
  5405. if (null == _RuntimeServices_GetMultiDimensionalRange1)
  5406. {
  5407. _RuntimeServices_GetMultiDimensionalRange1 = ResolveMethod(TypeSystemServices.RuntimeServicesType, "GetMultiDimensionalRange1");
  5408. }
  5409. return _RuntimeServices_GetMultiDimensionalRange1;
  5410. }
  5411. }
  5412. IMethod _RuntimeServices_SetMultiDimensionalRange1;
  5413. IMethod RuntimeServices_SetMultiDimensionalRange1
  5414. {
  5415. get
  5416. {
  5417. if (null == _RuntimeServices_SetMultiDimensionalRange1)
  5418. {
  5419. _RuntimeServices_SetMultiDimensionalRange1 = ResolveMethod(TypeSystemServices.RuntimeServicesType, "SetMultiDimensionalRange1");
  5420. }
  5421. return _RuntimeServices_SetMultiDimensionalRange1;
  5422. }
  5423. }
  5424. IMethod _RuntimeServices_GetEnumerable;
  5425. IMethod RuntimeServices_GetEnumerable
  5426. {
  5427. get
  5428. {
  5429. if (null == _RuntimeServices_GetEnumerable)
  5430. {
  5431. _RuntimeServices_GetEnumerable = ResolveMethod(TypeSystemServices.RuntimeServicesType, "GetEnumerable");
  5432. }
  5433. return _RuntimeServices_GetEnumerable;
  5434. }
  5435. }
  5436. IMethod _RuntimeServices_EqualityOperator;
  5437. IMethod RuntimeServices_EqualityOperator
  5438. {
  5439. get
  5440. {
  5441. if (null == _RuntimeServices_EqualityOperator)
  5442. {
  5443. _RuntimeServices_EqualityOperator = TypeSystemServices.Map(Types.RuntimeServices.GetMethod("EqualityOperator", new Type[] { Types.Object, Types.Object }));
  5444. }
  5445. return _RuntimeServices_EqualityOperator;
  5446. }
  5447. }
  5448. IMethod _Array_get_Length;
  5449. IMethod Array_get_Length
  5450. {
  5451. get
  5452. {
  5453. if (null == _Array_get_Length)
  5454. {
  5455. _Array_get_Length = ResolveProperty(TypeSystemServices.ArrayType, "Length").GetGetMethod();
  5456. }
  5457. return _Array_get_Length;
  5458. }
  5459. }
  5460. IMethod _Array_GetLength;
  5461. IMethod Array_GetLength
  5462. {
  5463. get
  5464. {
  5465. if (null == _Array_GetLength)
  5466. {
  5467. _Array_GetLength = ResolveMethod(TypeSystemServices.ArrayType, "GetLength");
  5468. }
  5469. return _Array_GetLength;
  5470. }
  5471. }
  5472. IMethod _String_get_Length;
  5473. IMethod String_get_Length
  5474. {
  5475. get
  5476. {
  5477. if (null == _String_get_Length)
  5478. {
  5479. _String_get_Length = ResolveProperty(TypeSystemServices.StringType, "Length").GetGetMethod();
  5480. }
  5481. return _String_get_Length;
  5482. }
  5483. }
  5484. IMethod _String_Substring_Int;
  5485. IMethod String_Substring_Int
  5486. {
  5487. get
  5488. {
  5489. if (null == _String_Substring_Int)
  5490. {
  5491. _String_Substring_Int = TypeSystemServices.Map(Types.String.GetMethod("Substring", new Type[] { Types.Int }));
  5492. }
  5493. return _String_Substring_Int;
  5494. }
  5495. }
  5496. IMethod _ICollection_get_Count;
  5497. IMethod ICollection_get_Count
  5498. {
  5499. get
  5500. {
  5501. if (null == _ICollection_get_Count)
  5502. {
  5503. _ICollection_get_Count = ResolveProperty(TypeSystemServices.ICollectionType, "Count").GetGetMethod();
  5504. }
  5505. return _ICollection_get_Count;
  5506. }
  5507. }
  5508. IMethod _List_GetRange1;
  5509. IMethod List_GetRange1
  5510. {
  5511. get
  5512. {
  5513. if (null == _List_GetRange1)
  5514. {
  5515. _List_GetRange1 = TypeSystemServices.Map(Types.List.GetMethod("GetRange", new Type[] { typeof(int) }));
  5516. }
  5517. return _List_GetRange1;
  5518. }
  5519. }
  5520. IMethod _List_GetRange2;
  5521. IMethod List_GetRange2
  5522. {
  5523. get
  5524. {
  5525. if (null == _List_GetRange2)
  5526. {
  5527. _List_GetRange2 = TypeSystemServices.Map(Types.List.GetMethod("GetRange", new Type[] { typeof(int), typeof(int) }));
  5528. }
  5529. return _List_GetRange2;
  5530. }
  5531. }
  5532. IMethod _ICallable_Call;
  5533. IMethod ICallable_Call
  5534. {
  5535. get
  5536. {
  5537. if (null == _ICallable_Call)
  5538. {
  5539. _ICallable_Call = ResolveMethod(TypeSystemServices.ICallableType, "Call");
  5540. }
  5541. return _ICallable_Call;
  5542. }
  5543. }
  5544. IMethod _Activator_CreateInstance;
  5545. IMethod Activator_CreateInstance
  5546. {
  5547. get
  5548. {
  5549. if (null == _Activator_CreateInstance)
  5550. {
  5551. _Activator_CreateInstance = TypeSystemServices.Map(typeof(Activator).GetMethod("CreateInstance", new Type[] { Types.Type, Types.ObjectArray }));
  5552. }
  5553. return _Activator_CreateInstance;
  5554. }
  5555. }
  5556. IConstructor _Exception_StringConstructor;
  5557. IConstructor Exception_StringConstructor
  5558. {
  5559. get
  5560. {
  5561. if (null == _Exception_StringConstructor)
  5562. {
  5563. _Exception_StringConstructor = TypeSystemServices.GetStringExceptionConstructor();
  5564. }
  5565. return _Exception_StringConstructor;
  5566. }
  5567. }
  5568. IMethod _TextReaderEnumerator_lines;
  5569. IMethod TextReaderEnumerator_lines
  5570. {
  5571. get
  5572. {
  5573. if (null == _TextReaderEnumerator_lines)
  5574. {
  5575. _TextReaderEnumerator_lines = TypeSystemServices.Map(typeof(TextReaderEnumerator).GetMethod("lines"));
  5576. }
  5577. return _TextReaderEnumerator_lines;
  5578. }
  5579. }
  5580. public bool OptimizeNullComparisons
  5581. {
  5582. get { return _optimizeNullComparisons; }
  5583. set { _optimizeNullComparisons = value; }
  5584. }
  5585. #endregion
  5586. }
  5587. }