PageRenderTime 70ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 2ms

/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

Large files files are truncated, but you can click here to view the full file

  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. paren

Large files files are truncated, but you can click here to view the full file