PageRenderTime 94ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 1ms

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

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