/NRefactory/ICSharpCode.NRefactory.VB/OutputVisitor/OutputVisitor.cs

http://github.com/icsharpcode/ILSpy · C# · 2676 lines · 2265 code · 334 blank · 77 comment · 205 complexity · 1f3be533fe71a888134d1aa409a74358 MD5 · raw file

Large files are truncated click here to view the full file

  1. // Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
  2. // This code is distributed under MIT X11 license (for details please see \doc\license.txt)
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.Globalization;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Text;
  10. using ICSharpCode.NRefactory.PatternMatching;
  11. using ICSharpCode.NRefactory.VB.Ast;
  12. namespace ICSharpCode.NRefactory.VB
  13. {
  14. /// <summary>
  15. /// Description of OutputVisitor.
  16. /// </summary>
  17. public class OutputVisitor : IAstVisitor<object, object>
  18. {
  19. readonly IOutputFormatter formatter;
  20. readonly VBFormattingOptions policy;
  21. readonly Stack<AstNode> containerStack = new Stack<AstNode>();
  22. readonly Stack<AstNode> positionStack = new Stack<AstNode>();
  23. /// <summary>
  24. /// Used to insert the minimal amount of spaces so that the lexer recognizes the tokens that were written.
  25. /// </summary>
  26. LastWritten lastWritten;
  27. enum LastWritten
  28. {
  29. Whitespace,
  30. Other,
  31. KeywordOrIdentifier
  32. }
  33. public OutputVisitor(TextWriter textWriter, VBFormattingOptions formattingPolicy)
  34. {
  35. if (textWriter == null)
  36. throw new ArgumentNullException("textWriter");
  37. if (formattingPolicy == null)
  38. throw new ArgumentNullException("formattingPolicy");
  39. this.formatter = new TextWriterOutputFormatter(textWriter);
  40. this.policy = formattingPolicy;
  41. }
  42. public OutputVisitor(IOutputFormatter formatter, VBFormattingOptions formattingPolicy)
  43. {
  44. if (formatter == null)
  45. throw new ArgumentNullException("formatter");
  46. if (formattingPolicy == null)
  47. throw new ArgumentNullException("formattingPolicy");
  48. this.formatter = formatter;
  49. this.policy = formattingPolicy;
  50. }
  51. public object VisitCompilationUnit(CompilationUnit compilationUnit, object data)
  52. {
  53. // don't do node tracking as we visit all children directly
  54. foreach (AstNode node in compilationUnit.Children)
  55. node.AcceptVisitor(this, data);
  56. return null;
  57. }
  58. public object VisitBlockStatement(BlockStatement blockStatement, object data)
  59. {
  60. StartNode(blockStatement);
  61. foreach (var stmt in blockStatement) {
  62. stmt.AcceptVisitor(this, data);
  63. NewLine();
  64. }
  65. return EndNode(blockStatement);
  66. }
  67. public object VisitPatternPlaceholder(AstNode placeholder, Pattern pattern, object data)
  68. {
  69. throw new NotImplementedException();
  70. }
  71. public object VisitTypeParameterDeclaration(TypeParameterDeclaration typeParameterDeclaration, object data)
  72. {
  73. StartNode(typeParameterDeclaration);
  74. switch (typeParameterDeclaration.Variance) {
  75. case ICSharpCode.NRefactory.TypeSystem.VarianceModifier.Invariant:
  76. break;
  77. case ICSharpCode.NRefactory.TypeSystem.VarianceModifier.Covariant:
  78. WriteKeyword("Out");
  79. break;
  80. case ICSharpCode.NRefactory.TypeSystem.VarianceModifier.Contravariant:
  81. WriteKeyword("In");
  82. break;
  83. default:
  84. throw new Exception("Invalid value for VarianceModifier");
  85. }
  86. WriteIdentifier(typeParameterDeclaration.Name);
  87. if (typeParameterDeclaration.Constraints.Any()) {
  88. WriteKeyword("As");
  89. if (typeParameterDeclaration.Constraints.Count > 1)
  90. WriteToken("{", TypeParameterDeclaration.Roles.LBrace);
  91. WriteCommaSeparatedList(typeParameterDeclaration.Constraints);
  92. if (typeParameterDeclaration.Constraints.Count > 1)
  93. WriteToken("}", TypeParameterDeclaration.Roles.RBrace);
  94. }
  95. return EndNode(typeParameterDeclaration);
  96. }
  97. public object VisitParameterDeclaration(ParameterDeclaration parameterDeclaration, object data)
  98. {
  99. StartNode(parameterDeclaration);
  100. WriteAttributes(parameterDeclaration.Attributes);
  101. WriteModifiers(parameterDeclaration.ModifierTokens);
  102. WriteIdentifier(parameterDeclaration.Name.Name);
  103. if (!parameterDeclaration.Type.IsNull) {
  104. WriteKeyword("As");
  105. parameterDeclaration.Type.AcceptVisitor(this, data);
  106. }
  107. if (!parameterDeclaration.OptionalValue.IsNull) {
  108. WriteToken("=", ParameterDeclaration.Roles.Assign);
  109. parameterDeclaration.OptionalValue.AcceptVisitor(this, data);
  110. }
  111. return EndNode(parameterDeclaration);
  112. }
  113. public object VisitVBTokenNode(VBTokenNode vBTokenNode, object data)
  114. {
  115. var mod = vBTokenNode as VBModifierToken;
  116. if (mod != null) {
  117. StartNode(vBTokenNode);
  118. WriteKeyword(VBModifierToken.GetModifierName(mod.Modifier));
  119. return EndNode(vBTokenNode);
  120. } else {
  121. throw new NotSupportedException("Should never visit individual tokens");
  122. }
  123. }
  124. public object VisitAliasImportsClause(AliasImportsClause aliasImportsClause, object data)
  125. {
  126. throw new NotImplementedException();
  127. }
  128. public object VisitAttribute(ICSharpCode.NRefactory.VB.Ast.Attribute attribute, object data)
  129. {
  130. StartNode(attribute);
  131. if (attribute.Target != AttributeTarget.None) {
  132. switch (attribute.Target) {
  133. case AttributeTarget.None:
  134. break;
  135. case AttributeTarget.Assembly:
  136. WriteKeyword("Assembly");
  137. break;
  138. case AttributeTarget.Module:
  139. WriteKeyword("Module");
  140. break;
  141. default:
  142. throw new Exception("Invalid value for AttributeTarget");
  143. }
  144. WriteToken(":", Ast.Attribute.Roles.Colon);
  145. Space();
  146. }
  147. attribute.Type.AcceptVisitor(this, data);
  148. WriteCommaSeparatedListInParenthesis(attribute.Arguments, false);
  149. return EndNode(attribute);
  150. }
  151. public object VisitAttributeBlock(AttributeBlock attributeBlock, object data)
  152. {
  153. StartNode(attributeBlock);
  154. WriteToken("<", AttributeBlock.Roles.LChevron);
  155. WriteCommaSeparatedList(attributeBlock.Attributes);
  156. WriteToken(">", AttributeBlock.Roles.RChevron);
  157. if (attributeBlock.Parent is ParameterDeclaration)
  158. Space();
  159. else
  160. NewLine();
  161. return EndNode(attributeBlock);
  162. }
  163. public object VisitImportsStatement(ImportsStatement importsStatement, object data)
  164. {
  165. StartNode(importsStatement);
  166. WriteKeyword("Imports", AstNode.Roles.Keyword);
  167. Space();
  168. WriteCommaSeparatedList(importsStatement.ImportsClauses);
  169. NewLine();
  170. return EndNode(importsStatement);
  171. }
  172. public object VisitMemberImportsClause(MemberImportsClause memberImportsClause, object data)
  173. {
  174. StartNode(memberImportsClause);
  175. memberImportsClause.Member.AcceptVisitor(this, data);
  176. return EndNode(memberImportsClause);
  177. }
  178. public object VisitNamespaceDeclaration(NamespaceDeclaration namespaceDeclaration, object data)
  179. {
  180. StartNode(namespaceDeclaration);
  181. NewLine();
  182. WriteKeyword("Namespace");
  183. bool isFirst = true;
  184. foreach (Identifier node in namespaceDeclaration.Identifiers) {
  185. if (isFirst) {
  186. isFirst = false;
  187. } else {
  188. WriteToken(".", NamespaceDeclaration.Roles.Dot);
  189. }
  190. node.AcceptVisitor(this, null);
  191. }
  192. NewLine();
  193. WriteMembers(namespaceDeclaration.Members);
  194. WriteKeyword("End");
  195. WriteKeyword("Namespace");
  196. NewLine();
  197. return EndNode(namespaceDeclaration);
  198. }
  199. public object VisitOptionStatement(OptionStatement optionStatement, object data)
  200. {
  201. throw new NotImplementedException();
  202. }
  203. public object VisitTypeDeclaration(TypeDeclaration typeDeclaration, object data)
  204. {
  205. StartNode(typeDeclaration);
  206. WriteAttributes(typeDeclaration.Attributes);
  207. WriteModifiers(typeDeclaration.ModifierTokens);
  208. WriteClassTypeKeyword(typeDeclaration);
  209. WriteIdentifier(typeDeclaration.Name.Name);
  210. MarkFoldStart();
  211. NewLine();
  212. if (!typeDeclaration.InheritsType.IsNull) {
  213. Indent();
  214. WriteKeyword("Inherits");
  215. typeDeclaration.InheritsType.AcceptVisitor(this, data);
  216. Unindent();
  217. NewLine();
  218. }
  219. if (typeDeclaration.ImplementsTypes.Any()) {
  220. Indent();
  221. WriteImplementsClause(typeDeclaration.ImplementsTypes);
  222. Unindent();
  223. NewLine();
  224. }
  225. if (!typeDeclaration.InheritsType.IsNull || typeDeclaration.ImplementsTypes.Any())
  226. NewLine();
  227. WriteMembers(typeDeclaration.Members);
  228. WriteKeyword("End");
  229. WriteClassTypeKeyword(typeDeclaration);
  230. MarkFoldEnd();
  231. NewLine();
  232. return EndNode(typeDeclaration);
  233. }
  234. void WriteClassTypeKeyword(TypeDeclaration typeDeclaration)
  235. {
  236. switch (typeDeclaration.ClassType) {
  237. case ClassType.Class:
  238. WriteKeyword("Class");
  239. break;
  240. case ClassType.Interface:
  241. WriteKeyword("Interface");
  242. break;
  243. case ClassType.Struct:
  244. WriteKeyword("Structure");
  245. break;
  246. case ClassType.Module:
  247. WriteKeyword("Module");
  248. break;
  249. default:
  250. throw new Exception("Invalid value for ClassType");
  251. }
  252. }
  253. public object VisitXmlNamespaceImportsClause(XmlNamespaceImportsClause xmlNamespaceImportsClause, object data)
  254. {
  255. throw new NotImplementedException();
  256. }
  257. public object VisitEnumDeclaration(EnumDeclaration enumDeclaration, object data)
  258. {
  259. StartNode(enumDeclaration);
  260. WriteAttributes(enumDeclaration.Attributes);
  261. WriteModifiers(enumDeclaration.ModifierTokens);
  262. WriteKeyword("Enum");
  263. WriteIdentifier(enumDeclaration.Name.Name);
  264. if (!enumDeclaration.UnderlyingType.IsNull) {
  265. Space();
  266. WriteKeyword("As");
  267. enumDeclaration.UnderlyingType.AcceptVisitor(this, data);
  268. }
  269. MarkFoldStart();
  270. NewLine();
  271. Indent();
  272. foreach (var member in enumDeclaration.Members) {
  273. member.AcceptVisitor(this, null);
  274. }
  275. Unindent();
  276. WriteKeyword("End");
  277. WriteKeyword("Enum");
  278. MarkFoldEnd();
  279. NewLine();
  280. return EndNode(enumDeclaration);
  281. }
  282. public object VisitEnumMemberDeclaration(EnumMemberDeclaration enumMemberDeclaration, object data)
  283. {
  284. StartNode(enumMemberDeclaration);
  285. WriteAttributes(enumMemberDeclaration.Attributes);
  286. WriteIdentifier(enumMemberDeclaration.Name.Name);
  287. if (!enumMemberDeclaration.Value.IsNull) {
  288. Space();
  289. WriteToken("=", EnumMemberDeclaration.Roles.Assign);
  290. Space();
  291. enumMemberDeclaration.Value.AcceptVisitor(this, data);
  292. }
  293. NewLine();
  294. return EndNode(enumMemberDeclaration);
  295. }
  296. public object VisitDelegateDeclaration(DelegateDeclaration delegateDeclaration, object data)
  297. {
  298. StartNode(delegateDeclaration);
  299. WriteAttributes(delegateDeclaration.Attributes);
  300. WriteModifiers(delegateDeclaration.ModifierTokens);
  301. WriteKeyword("Delegate");
  302. if (delegateDeclaration.IsSub)
  303. WriteKeyword("Sub");
  304. else
  305. WriteKeyword("Function");
  306. WriteIdentifier(delegateDeclaration.Name.Name);
  307. WriteTypeParameters(delegateDeclaration.TypeParameters);
  308. WriteCommaSeparatedListInParenthesis(delegateDeclaration.Parameters, false);
  309. if (!delegateDeclaration.IsSub) {
  310. Space();
  311. WriteKeyword("As");
  312. WriteAttributes(delegateDeclaration.ReturnTypeAttributes);
  313. delegateDeclaration.ReturnType.AcceptVisitor(this, data);
  314. }
  315. NewLine();
  316. return EndNode(delegateDeclaration);
  317. }
  318. public object VisitIdentifier(Identifier identifier, object data)
  319. {
  320. StartNode(identifier);
  321. WriteIdentifier(identifier.Name);
  322. WriteTypeCharacter(identifier.TypeCharacter);
  323. return EndNode(identifier);
  324. }
  325. public object VisitXmlIdentifier(XmlIdentifier xmlIdentifier, object data)
  326. {
  327. throw new NotImplementedException();
  328. }
  329. public object VisitXmlLiteralString(XmlLiteralString xmlLiteralString, object data)
  330. {
  331. throw new NotImplementedException();
  332. }
  333. public object VisitSimpleNameExpression(SimpleNameExpression simpleNameExpression, object data)
  334. {
  335. StartNode(simpleNameExpression);
  336. simpleNameExpression.Identifier.AcceptVisitor(this, data);
  337. WriteTypeArguments(simpleNameExpression.TypeArguments);
  338. return EndNode(simpleNameExpression);
  339. }
  340. public object VisitPrimitiveExpression(PrimitiveExpression primitiveExpression, object data)
  341. {
  342. StartNode(primitiveExpression);
  343. if (lastWritten == LastWritten.KeywordOrIdentifier)
  344. Space();
  345. WritePrimitiveValue(primitiveExpression.Value);
  346. return EndNode(primitiveExpression);
  347. }
  348. public object VisitInstanceExpression(InstanceExpression instanceExpression, object data)
  349. {
  350. StartNode(instanceExpression);
  351. switch (instanceExpression.Type) {
  352. case InstanceExpressionType.Me:
  353. WriteKeyword("Me");
  354. break;
  355. case InstanceExpressionType.MyBase:
  356. WriteKeyword("MyBase");
  357. break;
  358. case InstanceExpressionType.MyClass:
  359. WriteKeyword("MyClass");
  360. break;
  361. default:
  362. throw new Exception("Invalid value for InstanceExpressionType");
  363. }
  364. return EndNode(instanceExpression);
  365. }
  366. public object VisitParenthesizedExpression(ParenthesizedExpression parenthesizedExpression, object data)
  367. {
  368. StartNode(parenthesizedExpression);
  369. LPar();
  370. parenthesizedExpression.Expression.AcceptVisitor(this, data);
  371. RPar();
  372. return EndNode(parenthesizedExpression);
  373. }
  374. public object VisitGetTypeExpression(GetTypeExpression getTypeExpression, object data)
  375. {
  376. StartNode(getTypeExpression);
  377. WriteKeyword("GetType");
  378. LPar();
  379. getTypeExpression.Type.AcceptVisitor(this, data);
  380. RPar();
  381. return EndNode(getTypeExpression);
  382. }
  383. public object VisitTypeOfIsExpression(TypeOfIsExpression typeOfIsExpression, object data)
  384. {
  385. StartNode(typeOfIsExpression);
  386. WriteKeyword("TypeOf");
  387. typeOfIsExpression.TypeOfExpression.AcceptVisitor(this, data);
  388. WriteKeyword("Is");
  389. typeOfIsExpression.Type.AcceptVisitor(this, data);
  390. return EndNode(typeOfIsExpression);
  391. }
  392. public object VisitGetXmlNamespaceExpression(GetXmlNamespaceExpression getXmlNamespaceExpression, object data)
  393. {
  394. throw new NotImplementedException();
  395. }
  396. public object VisitMemberAccessExpression(MemberAccessExpression memberAccessExpression, object data)
  397. {
  398. StartNode(memberAccessExpression);
  399. memberAccessExpression.Target.AcceptVisitor(this, data);
  400. WriteToken(".", MemberAccessExpression.Roles.Dot);
  401. memberAccessExpression.MemberName.AcceptVisitor(this, data);
  402. WriteTypeArguments(memberAccessExpression.TypeArguments);
  403. return EndNode(memberAccessExpression);
  404. }
  405. public object VisitTypeReferenceExpression(TypeReferenceExpression typeReferenceExpression, object data)
  406. {
  407. StartNode(typeReferenceExpression);
  408. typeReferenceExpression.Type.AcceptVisitor(this, data);
  409. return EndNode(typeReferenceExpression);
  410. }
  411. public object VisitEventMemberSpecifier(EventMemberSpecifier eventMemberSpecifier, object data)
  412. {
  413. StartNode(eventMemberSpecifier);
  414. eventMemberSpecifier.Target.AcceptVisitor(this, data);
  415. WriteToken(".", EventMemberSpecifier.Roles.Dot);
  416. eventMemberSpecifier.Member.AcceptVisitor(this, data);
  417. return EndNode(eventMemberSpecifier);
  418. }
  419. public object VisitInterfaceMemberSpecifier(InterfaceMemberSpecifier interfaceMemberSpecifier, object data)
  420. {
  421. StartNode(interfaceMemberSpecifier);
  422. interfaceMemberSpecifier.Target.AcceptVisitor(this, data);
  423. WriteToken(".", EventMemberSpecifier.Roles.Dot);
  424. interfaceMemberSpecifier.Member.AcceptVisitor(this, data);
  425. return EndNode(interfaceMemberSpecifier);
  426. }
  427. #region TypeMembers
  428. public object VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration, object data)
  429. {
  430. StartNode(constructorDeclaration);
  431. WriteAttributes(constructorDeclaration.Attributes);
  432. WriteModifiers(constructorDeclaration.ModifierTokens);
  433. WriteKeyword("Sub");
  434. WriteKeyword("New");
  435. WriteCommaSeparatedListInParenthesis(constructorDeclaration.Parameters, false);
  436. MarkFoldStart();
  437. NewLine();
  438. Indent();
  439. WriteBlock(constructorDeclaration.Body);
  440. Unindent();
  441. WriteKeyword("End");
  442. WriteKeyword("Sub");
  443. MarkFoldEnd();
  444. NewLine();
  445. return EndNode(constructorDeclaration);
  446. }
  447. public object VisitMethodDeclaration(MethodDeclaration methodDeclaration, object data)
  448. {
  449. StartNode(methodDeclaration);
  450. WriteAttributes(methodDeclaration.Attributes);
  451. WriteModifiers(methodDeclaration.ModifierTokens);
  452. if (methodDeclaration.IsSub)
  453. WriteKeyword("Sub");
  454. else
  455. WriteKeyword("Function");
  456. methodDeclaration.Name.AcceptVisitor(this, data);
  457. WriteTypeParameters(methodDeclaration.TypeParameters);
  458. WriteCommaSeparatedListInParenthesis(methodDeclaration.Parameters, false);
  459. if (!methodDeclaration.IsSub && !methodDeclaration.ReturnType.IsNull) {
  460. Space();
  461. WriteKeyword("As");
  462. WriteAttributes(methodDeclaration.ReturnTypeAttributes);
  463. methodDeclaration.ReturnType.AcceptVisitor(this, data);
  464. }
  465. WriteHandlesClause(methodDeclaration.HandlesClause);
  466. WriteImplementsClause(methodDeclaration.ImplementsClause);
  467. if (!methodDeclaration.Body.IsNull) {
  468. MarkFoldStart();
  469. NewLine();
  470. Indent();
  471. WriteBlock(methodDeclaration.Body);
  472. Unindent();
  473. WriteKeyword("End");
  474. if (methodDeclaration.IsSub)
  475. WriteKeyword("Sub");
  476. else
  477. WriteKeyword("Function");
  478. MarkFoldEnd();
  479. }
  480. NewLine();
  481. return EndNode(methodDeclaration);
  482. }
  483. public object VisitFieldDeclaration(FieldDeclaration fieldDeclaration, object data)
  484. {
  485. StartNode(fieldDeclaration);
  486. WriteAttributes(fieldDeclaration.Attributes);
  487. WriteModifiers(fieldDeclaration.ModifierTokens);
  488. WriteCommaSeparatedList(fieldDeclaration.Variables);
  489. NewLine();
  490. return EndNode(fieldDeclaration);
  491. }
  492. public object VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration, object data)
  493. {
  494. StartNode(propertyDeclaration);
  495. WriteAttributes(propertyDeclaration.Attributes);
  496. WriteModifiers(propertyDeclaration.ModifierTokens);
  497. WriteKeyword("Property");
  498. WriteIdentifier(propertyDeclaration.Name.Name);
  499. WriteCommaSeparatedListInParenthesis(propertyDeclaration.Parameters, false);
  500. if (!propertyDeclaration.ReturnType.IsNull) {
  501. Space();
  502. WriteKeyword("As");
  503. WriteAttributes(propertyDeclaration.ReturnTypeAttributes);
  504. propertyDeclaration.ReturnType.AcceptVisitor(this, data);
  505. }
  506. bool needsBody = !propertyDeclaration.Getter.Body.IsNull || !propertyDeclaration.Setter.Body.IsNull;
  507. if (needsBody) {
  508. MarkFoldStart();
  509. NewLine();
  510. Indent();
  511. if (!propertyDeclaration.Getter.Body.IsNull) {
  512. propertyDeclaration.Getter.AcceptVisitor(this, data);
  513. }
  514. if (!propertyDeclaration.Setter.Body.IsNull) {
  515. propertyDeclaration.Setter.AcceptVisitor(this, data);
  516. }
  517. Unindent();
  518. WriteKeyword("End");
  519. WriteKeyword("Property");
  520. MarkFoldEnd();
  521. }
  522. NewLine();
  523. return EndNode(propertyDeclaration);
  524. }
  525. #endregion
  526. #region TypeName
  527. public object VisitPrimitiveType(PrimitiveType primitiveType, object data)
  528. {
  529. StartNode(primitiveType);
  530. WriteKeyword(primitiveType.Keyword);
  531. return EndNode(primitiveType);
  532. }
  533. public object VisitQualifiedType(QualifiedType qualifiedType, object data)
  534. {
  535. StartNode(qualifiedType);
  536. qualifiedType.Target.AcceptVisitor(this, data);
  537. WriteToken(".", AstNode.Roles.Dot);
  538. WriteIdentifier(qualifiedType.Name);
  539. WriteTypeArguments(qualifiedType.TypeArguments);
  540. return EndNode(qualifiedType);
  541. }
  542. public object VisitComposedType(ComposedType composedType, object data)
  543. {
  544. StartNode(composedType);
  545. composedType.BaseType.AcceptVisitor(this, data);
  546. if (composedType.HasNullableSpecifier)
  547. WriteToken("?", ComposedType.Roles.QuestionMark);
  548. WriteArraySpecifiers(composedType.ArraySpecifiers);
  549. return EndNode(composedType);
  550. }
  551. public object VisitArraySpecifier(ArraySpecifier arraySpecifier, object data)
  552. {
  553. StartNode(arraySpecifier);
  554. LPar();
  555. for (int i = 0; i < arraySpecifier.Dimensions - 1; i++) {
  556. WriteToken(",", ArraySpecifier.Roles.Comma);
  557. }
  558. RPar();
  559. return EndNode(arraySpecifier);
  560. }
  561. public object VisitSimpleType(SimpleType simpleType, object data)
  562. {
  563. StartNode(simpleType);
  564. WriteIdentifier(simpleType.Identifier);
  565. WriteTypeArguments(simpleType.TypeArguments);
  566. return EndNode(simpleType);
  567. }
  568. #endregion
  569. #region StartNode/EndNode
  570. void StartNode(AstNode node)
  571. {
  572. // Ensure that nodes are visited in the proper nested order.
  573. // Jumps to different subtrees are allowed only for the child of a placeholder node.
  574. Debug.Assert(containerStack.Count == 0 || node.Parent == containerStack.Peek());
  575. if (positionStack.Count > 0)
  576. WriteSpecialsUpToNode(node);
  577. containerStack.Push(node);
  578. positionStack.Push(node.FirstChild);
  579. formatter.StartNode(node);
  580. }
  581. object EndNode(AstNode node)
  582. {
  583. Debug.Assert(node == containerStack.Peek());
  584. AstNode pos = positionStack.Pop();
  585. Debug.Assert(pos == null || pos.Parent == node);
  586. WriteSpecials(pos, null);
  587. containerStack.Pop();
  588. formatter.EndNode(node);
  589. return null;
  590. }
  591. #endregion
  592. #region WriteSpecials
  593. /// <summary>
  594. /// Writes all specials from start to end (exclusive). Does not touch the positionStack.
  595. /// </summary>
  596. void WriteSpecials(AstNode start, AstNode end)
  597. {
  598. for (AstNode pos = start; pos != end; pos = pos.NextSibling) {
  599. if (pos.Role == AstNode.Roles.Comment) {
  600. pos.AcceptVisitor(this, null);
  601. }
  602. }
  603. }
  604. /// <summary>
  605. /// Writes all specials between the current position (in the positionStack) and the next
  606. /// node with the specified role. Advances the current position.
  607. /// </summary>
  608. void WriteSpecialsUpToRole(Role role)
  609. {
  610. for (AstNode pos = positionStack.Peek(); pos != null; pos = pos.NextSibling) {
  611. if (pos.Role == role) {
  612. WriteSpecials(positionStack.Pop(), pos);
  613. positionStack.Push(pos);
  614. break;
  615. }
  616. }
  617. }
  618. /// <summary>
  619. /// Writes all specials between the current position (in the positionStack) and the specified node.
  620. /// Advances the current position.
  621. /// </summary>
  622. void WriteSpecialsUpToNode(AstNode node)
  623. {
  624. for (AstNode pos = positionStack.Peek(); pos != null; pos = pos.NextSibling) {
  625. if (pos == node) {
  626. WriteSpecials(positionStack.Pop(), pos);
  627. positionStack.Push(pos);
  628. break;
  629. }
  630. }
  631. }
  632. void WriteSpecialsUpToRole(Role role, AstNode nextNode)
  633. {
  634. // Look for the role between the current position and the nextNode.
  635. for (AstNode pos = positionStack.Peek(); pos != null && pos != nextNode; pos = pos.NextSibling) {
  636. if (pos.Role == AstNode.Roles.Comma) {
  637. WriteSpecials(positionStack.Pop(), pos);
  638. positionStack.Push(pos);
  639. break;
  640. }
  641. }
  642. }
  643. #endregion
  644. #region Comma
  645. /// <summary>
  646. /// Writes a comma.
  647. /// </summary>
  648. /// <param name="nextNode">The next node after the comma.</param>
  649. /// <param name="noSpacesAfterComma">When set prevents printing a space after comma.</param>
  650. void Comma(AstNode nextNode, bool noSpaceAfterComma = false)
  651. {
  652. WriteSpecialsUpToRole(AstNode.Roles.Comma, nextNode);
  653. formatter.WriteToken(",");
  654. lastWritten = LastWritten.Other;
  655. Space(!noSpaceAfterComma); // TODO: Comma policy has changed.
  656. }
  657. void WriteCommaSeparatedList(IEnumerable<AstNode> list)
  658. {
  659. bool isFirst = true;
  660. foreach (AstNode node in list) {
  661. if (isFirst) {
  662. isFirst = false;
  663. } else {
  664. Comma(node);
  665. }
  666. node.AcceptVisitor(this, null);
  667. }
  668. }
  669. void WriteCommaSeparatedListInParenthesis(IEnumerable<AstNode> list, bool spaceWithin)
  670. {
  671. LPar();
  672. if (list.Any()) {
  673. Space(spaceWithin);
  674. WriteCommaSeparatedList(list);
  675. Space(spaceWithin);
  676. }
  677. RPar();
  678. }
  679. #if DOTNET35
  680. void WriteCommaSeparatedList(IEnumerable<VariableInitializer> list)
  681. {
  682. WriteCommaSeparatedList(list);
  683. }
  684. void WriteCommaSeparatedList(IEnumerable<AstType> list)
  685. {
  686. WriteCommaSeparatedList(list);
  687. }
  688. void WriteCommaSeparatedListInParenthesis(IEnumerable<Expression> list, bool spaceWithin)
  689. {
  690. WriteCommaSeparatedListInParenthesis(list.SafeCast<Expression, AstNode>(), spaceWithin);
  691. }
  692. void WriteCommaSeparatedListInParenthesis(IEnumerable<ParameterDeclaration> list, bool spaceWithin)
  693. {
  694. WriteCommaSeparatedListInParenthesis(list.SafeCast<ParameterDeclaration, AstNode>(), spaceWithin);
  695. }
  696. #endif
  697. void WriteCommaSeparatedListInBrackets(IEnumerable<ParameterDeclaration> list, bool spaceWithin)
  698. {
  699. WriteToken("[", AstNode.Roles.LBracket);
  700. if (list.Any()) {
  701. Space(spaceWithin);
  702. WriteCommaSeparatedList(list);
  703. Space(spaceWithin);
  704. }
  705. WriteToken("]", AstNode.Roles.RBracket);
  706. }
  707. #endregion
  708. #region Write tokens
  709. /// <summary>
  710. /// Writes a keyword, and all specials up to
  711. /// </summary>
  712. void WriteKeyword(string keyword, Role<VBTokenNode> tokenRole = null)
  713. {
  714. WriteSpecialsUpToRole(tokenRole ?? AstNode.Roles.Keyword);
  715. if (lastWritten == LastWritten.KeywordOrIdentifier)
  716. formatter.Space();
  717. formatter.WriteKeyword(keyword);
  718. lastWritten = LastWritten.KeywordOrIdentifier;
  719. }
  720. void WriteIdentifier(string identifier, Role<Identifier> identifierRole = null)
  721. {
  722. WriteSpecialsUpToRole(identifierRole ?? AstNode.Roles.Identifier);
  723. if (IsKeyword(identifier, containerStack.Peek())) {
  724. if (lastWritten == LastWritten.KeywordOrIdentifier)
  725. Space(); // this space is not strictly required, so we call Space()
  726. formatter.WriteToken("[");
  727. } else if (lastWritten == LastWritten.KeywordOrIdentifier) {
  728. formatter.Space(); // this space is strictly required, so we directly call the formatter
  729. }
  730. formatter.WriteIdentifier(identifier);
  731. if (IsKeyword(identifier, containerStack.Peek())) {
  732. formatter.WriteToken("]");
  733. }
  734. lastWritten = LastWritten.KeywordOrIdentifier;
  735. }
  736. void WriteToken(string token, Role<VBTokenNode> tokenRole)
  737. {
  738. WriteSpecialsUpToRole(tokenRole);
  739. // Avoid that two +, - or ? tokens are combined into a ++, -- or ?? token.
  740. // Note that we don't need to handle tokens like = because there's no valid
  741. // C# program that contains the single token twice in a row.
  742. // (for +, - and &, this can happen with unary operators;
  743. // for ?, this can happen in "a is int? ? b : c" or "a as int? ?? 0";
  744. // and for /, this can happen with "1/ *ptr" or "1/ //comment".)
  745. // if (lastWritten == LastWritten.Plus && token[0] == '+'
  746. // || lastWritten == LastWritten.Minus && token[0] == '-'
  747. // || lastWritten == LastWritten.Ampersand && token[0] == '&'
  748. // || lastWritten == LastWritten.QuestionMark && token[0] == '?'
  749. // || lastWritten == LastWritten.Division && token[0] == '*')
  750. // {
  751. // formatter.Space();
  752. // }
  753. formatter.WriteToken(token);
  754. // if (token == "+")
  755. // lastWritten = LastWritten.Plus;
  756. // else if (token == "-")
  757. // lastWritten = LastWritten.Minus;
  758. // else if (token == "&")
  759. // lastWritten = LastWritten.Ampersand;
  760. // else if (token == "?")
  761. // lastWritten = LastWritten.QuestionMark;
  762. // else if (token == "/")
  763. // lastWritten = LastWritten.Division;
  764. // else
  765. lastWritten = LastWritten.Other;
  766. }
  767. void WriteTypeCharacter(TypeCode typeCharacter)
  768. {
  769. switch (typeCharacter) {
  770. case TypeCode.Empty:
  771. case TypeCode.Object:
  772. case TypeCode.DBNull:
  773. case TypeCode.Boolean:
  774. case TypeCode.Char:
  775. break;
  776. case TypeCode.SByte:
  777. break;
  778. case TypeCode.Byte:
  779. break;
  780. case TypeCode.Int16:
  781. break;
  782. case TypeCode.UInt16:
  783. break;
  784. case TypeCode.Int32:
  785. WriteToken("%", null);
  786. break;
  787. case TypeCode.UInt32:
  788. break;
  789. case TypeCode.Int64:
  790. WriteToken("&", null);
  791. break;
  792. case TypeCode.UInt64:
  793. break;
  794. case TypeCode.Single:
  795. WriteToken("!", null);
  796. break;
  797. case TypeCode.Double:
  798. WriteToken("#", null);
  799. break;
  800. case TypeCode.Decimal:
  801. WriteToken("@", null);
  802. break;
  803. case TypeCode.DateTime:
  804. break;
  805. case TypeCode.String:
  806. WriteToken("$", null);
  807. break;
  808. default:
  809. throw new Exception("Invalid value for TypeCode");
  810. }
  811. }
  812. void LPar()
  813. {
  814. WriteToken("(", AstNode.Roles.LPar);
  815. }
  816. void RPar()
  817. {
  818. WriteToken(")", AstNode.Roles.LPar);
  819. }
  820. /// <summary>
  821. /// Writes a space depending on policy.
  822. /// </summary>
  823. void Space(bool addSpace = true)
  824. {
  825. if (addSpace) {
  826. formatter.Space();
  827. lastWritten = LastWritten.Whitespace;
  828. }
  829. }
  830. void NewLine()
  831. {
  832. formatter.NewLine();
  833. lastWritten = LastWritten.Whitespace;
  834. }
  835. void Indent()
  836. {
  837. formatter.Indent();
  838. }
  839. void Unindent()
  840. {
  841. formatter.Unindent();
  842. }
  843. void MarkFoldStart()
  844. {
  845. formatter.MarkFoldStart();
  846. }
  847. void MarkFoldEnd()
  848. {
  849. formatter.MarkFoldEnd();
  850. }
  851. #endregion
  852. #region IsKeyword Test
  853. static readonly HashSet<string> unconditionalKeywords = new HashSet<string>(StringComparer.OrdinalIgnoreCase) {
  854. "AddHandler", "AddressOf", "Alias", "And", "AndAlso", "As", "Boolean", "ByRef", "Byte",
  855. "ByVal", "Call", "Case", "Catch", "CBool", "CByte", "CChar", "CInt", "Class", "CLng",
  856. "CObj", "Const", "Continue", "CSByte", "CShort", "CSng", "CStr", "CType", "CUInt",
  857. "CULng", "CUShort", "Date", "Decimal", "Declare", "Default", "Delegate", "Dim",
  858. "DirectCast", "Do", "Double", "Each", "Else", "ElseIf", "End", "EndIf", "Enum", "Erase",
  859. "Error", "Event", "Exit", "False", "Finally", "For", "Friend", "Function", "Get",
  860. "GetType", "GetXmlNamespace", "Global", "GoSub", "GoTo", "Handles", "If", "Implements",
  861. "Imports", "In", "Inherits", "Integer", "Interface", "Is", "IsNot", "Let", "Lib", "Like",
  862. "Long", "Loop", "Me", "Mod", "Module", "MustInherit", "MustOverride", "MyBase", "MyClass",
  863. "Namespace", "Narrowing", "New", "Next", "Not", "Nothing", "NotInheritable", "NotOverridable",
  864. "Object", "Of", "On", "Operator", "Option", "Optional", "Or", "OrElse", "Overloads",
  865. "Overridable", "Overrides", "ParamArray", "Partial", "Private", "Property", "Protected",
  866. "Public", "RaiseEvent", "ReadOnly", "ReDim", "REM", "RemoveHandler", "Resume", "Return",
  867. "SByte", "Select", "Set", "Shadows", "Shared", "Short", "Single", "Static", "Step", "Stop",
  868. "String", "Structure", "Sub", "SyncLock", "Then", "Throw", "To", "True", "Try", "TryCast",
  869. "TypeOf", "UInteger", "ULong", "UShort", "Using", "Variant", "Wend", "When", "While",
  870. "Widening", "With", "WithEvents", "WriteOnly", "Xor"
  871. };
  872. static readonly HashSet<string> queryKeywords = new HashSet<string> {
  873. };
  874. /// <summary>
  875. /// Determines whether the specified identifier is a keyword in the given context.
  876. /// </summary>
  877. public static bool IsKeyword(string identifier, AstNode context)
  878. {
  879. if (unconditionalKeywords.Contains(identifier))
  880. return true;
  881. // if (context.Ancestors.Any(a => a is QueryExpression)) {
  882. // if (queryKeywords.Contains(identifier))
  883. // return true;
  884. // }
  885. return false;
  886. }
  887. #endregion
  888. #region Write constructs
  889. void WriteTypeArguments(IEnumerable<AstType> typeArguments)
  890. {
  891. if (typeArguments.Any()) {
  892. LPar();
  893. WriteKeyword("Of");
  894. WriteCommaSeparatedList(typeArguments);
  895. RPar();
  896. }
  897. }
  898. void WriteTypeParameters(IEnumerable<TypeParameterDeclaration> typeParameters)
  899. {
  900. if (typeParameters.Any()) {
  901. LPar();
  902. WriteKeyword("Of");
  903. WriteCommaSeparatedList(typeParameters);
  904. RPar();
  905. }
  906. }
  907. void WriteModifiers(IEnumerable<VBModifierToken> modifierTokens)
  908. {
  909. foreach (VBModifierToken modifier in modifierTokens) {
  910. modifier.AcceptVisitor(this, null);
  911. }
  912. }
  913. void WriteArraySpecifiers(IEnumerable<ArraySpecifier> arraySpecifiers)
  914. {
  915. foreach (ArraySpecifier specifier in arraySpecifiers) {
  916. specifier.AcceptVisitor(this, null);
  917. }
  918. }
  919. void WriteQualifiedIdentifier(IEnumerable<Identifier> identifiers)
  920. {
  921. bool first = true;
  922. foreach (Identifier ident in identifiers) {
  923. if (first) {
  924. first = false;
  925. if (lastWritten == LastWritten.KeywordOrIdentifier)
  926. formatter.Space();
  927. } else {
  928. WriteSpecialsUpToRole(AstNode.Roles.Dot, ident);
  929. formatter.WriteToken(".");
  930. lastWritten = LastWritten.Other;
  931. }
  932. WriteSpecialsUpToNode(ident);
  933. formatter.WriteIdentifier(ident.Name);
  934. lastWritten = LastWritten.KeywordOrIdentifier;
  935. }
  936. }
  937. void WriteEmbeddedStatement(Statement embeddedStatement)
  938. {
  939. if (embeddedStatement.IsNull)
  940. return;
  941. BlockStatement block = embeddedStatement as BlockStatement;
  942. if (block != null)
  943. VisitBlockStatement(block, null);
  944. else
  945. embeddedStatement.AcceptVisitor(this, null);
  946. }
  947. void WriteBlock(BlockStatement body)
  948. {
  949. if (body.IsNull)
  950. NewLine();
  951. else
  952. VisitBlockStatement(body, null);
  953. }
  954. void WriteMembers(IEnumerable<AstNode> members)
  955. {
  956. Indent();
  957. bool isFirst = true;
  958. foreach (var member in members) {
  959. if (isFirst) {
  960. isFirst = false;
  961. } else {
  962. NewLine();
  963. }
  964. member.AcceptVisitor(this, null);
  965. }
  966. Unindent();
  967. }
  968. void WriteAttributes(IEnumerable<AttributeBlock> attributes)
  969. {
  970. foreach (AttributeBlock attr in attributes) {
  971. attr.AcceptVisitor(this, null);
  972. }
  973. }
  974. void WritePrivateImplementationType(AstType privateImplementationType)
  975. {
  976. if (!privateImplementationType.IsNull) {
  977. privateImplementationType.AcceptVisitor(this, null);
  978. WriteToken(".", AstNode.Roles.Dot);
  979. }
  980. }
  981. void WriteImplementsClause(AstNodeCollection<InterfaceMemberSpecifier> implementsClause)
  982. {
  983. if (implementsClause.Any()) {
  984. Space();
  985. WriteKeyword("Implements");
  986. WriteCommaSeparatedList(implementsClause);
  987. }
  988. }
  989. void WriteImplementsClause(AstNodeCollection<AstType> implementsClause)
  990. {
  991. if (implementsClause.Any()) {
  992. WriteKeyword("Implements");
  993. WriteCommaSeparatedList(implementsClause);
  994. }
  995. }
  996. void WriteHandlesClause(AstNodeCollection<EventMemberSpecifier> handlesClause)
  997. {
  998. if (handlesClause.Any()) {
  999. Space();
  1000. WriteKeyword("Handles");
  1001. WriteCommaSeparatedList(handlesClause);
  1002. }
  1003. }
  1004. void WritePrimitiveValue(object val)
  1005. {
  1006. if (val == null) {
  1007. WriteKeyword("Nothing");
  1008. return;
  1009. }
  1010. if (val is bool) {
  1011. if ((bool)val) {
  1012. WriteKeyword("True");
  1013. } else {
  1014. WriteKeyword("False");
  1015. }
  1016. return;
  1017. }
  1018. if (val is string) {
  1019. formatter.WriteToken("\"" + ConvertString(val.ToString()) + "\"");
  1020. lastWritten = LastWritten.Other;
  1021. } else if (val is char) {
  1022. formatter.WriteToken("\"" + ConvertCharLiteral((char)val) + "\"c");
  1023. lastWritten = LastWritten.Other;
  1024. } else if (val is decimal) {
  1025. formatter.WriteToken(((decimal)val).ToString(NumberFormatInfo.InvariantInfo) + "D");
  1026. lastWritten = LastWritten.Other;
  1027. } else if (val is float) {
  1028. float f = (float)val;
  1029. if (float.IsInfinity(f) || float.IsNaN(f)) {
  1030. // Strictly speaking, these aren't PrimitiveExpressions;
  1031. // but we still support writing these to make life easier for code generators.
  1032. WriteKeyword("Single");
  1033. WriteToken(".", AstNode.Roles.Dot);
  1034. if (float.IsPositiveInfinity(f))
  1035. WriteIdentifier("PositiveInfinity");
  1036. else if (float.IsNegativeInfinity(f))
  1037. WriteIdentifier("NegativeInfinity");
  1038. else
  1039. WriteIdentifier("NaN");
  1040. return;
  1041. }
  1042. formatter.WriteToken(f.ToString("R", NumberFormatInfo.InvariantInfo) + "F");
  1043. lastWritten = LastWritten.Other;
  1044. } else if (val is double) {
  1045. double f = (double)val;
  1046. if (double.IsInfinity(f) || double.IsNaN(f)) {
  1047. // Strictly speaking, these aren't PrimitiveExpressions;
  1048. // but we still support writing these to make life easier for code generators.
  1049. WriteKeyword("Double");
  1050. WriteToken(".", AstNode.Roles.Dot);
  1051. if (double.IsPositiveInfinity(f))
  1052. WriteIdentifier("PositiveInfinity");
  1053. else if (double.IsNegativeInfinity(f))
  1054. WriteIdentifier("NegativeInfinity");
  1055. else
  1056. WriteIdentifier("NaN");
  1057. return;
  1058. }
  1059. string number = f.ToString("R", NumberFormatInfo.InvariantInfo);
  1060. if (number.IndexOf('.') < 0 && number.IndexOf('E') < 0)
  1061. number += ".0";
  1062. formatter.WriteToken(number);
  1063. // needs space if identifier follows number; this avoids mistaking the following identifier as type suffix
  1064. lastWritten = LastWritten.KeywordOrIdentifier;
  1065. } else if (val is IFormattable) {
  1066. StringBuilder b = new StringBuilder();
  1067. // if (primitiveExpression.LiteralFormat == LiteralFormat.HexadecimalNumber) {
  1068. // b.Append("0x");
  1069. // b.Append(((IFormattable)val).ToString("x", NumberFormatInfo.InvariantInfo));
  1070. // } else {
  1071. b.Append(((IFormattable)val).ToString(null, NumberFormatInfo.InvariantInfo));
  1072. // }
  1073. if (val is uint || val is ulong) {
  1074. b.Append("U");
  1075. }
  1076. if (val is long || val is ulong) {
  1077. b.Append("L");
  1078. }
  1079. formatter.WriteToken(b.ToString());
  1080. // needs space if identifier follows number; this avoids mistaking the following identifier as type suffix
  1081. lastWritten = LastWritten.KeywordOrIdentifier;
  1082. } else {
  1083. formatter.WriteToken(val.ToString());
  1084. lastWritten = LastWritten.Other;
  1085. }
  1086. }
  1087. #endregion
  1088. #region ConvertLiteral
  1089. static string ConvertCharLiteral(char ch)
  1090. {
  1091. if (ch == '"') return "\"\"";
  1092. return ch.ToString();
  1093. }
  1094. static string ConvertString(string str)
  1095. {
  1096. StringBuilder sb = new StringBuilder();
  1097. foreach (char ch in str) {
  1098. sb.Append(ConvertCharLiteral(ch));
  1099. }
  1100. return sb.ToString();
  1101. }
  1102. #endregion
  1103. public object VisitVariableIdentifier(VariableIdentifier variableIdentifier, object data)
  1104. {
  1105. StartNode(variableIdentifier);
  1106. WriteIdentifier(variableIdentifier.Name.Name);
  1107. if (variableIdentifier.HasNullableSpecifier)
  1108. WriteToken("?", VariableIdentifier.Roles.QuestionMark);
  1109. if (variableIdentifier.ArraySizeSpecifiers.Count > 0)
  1110. WriteCommaSeparatedListInParenthesis(variableIdentifier.ArraySizeSpecifiers, false);
  1111. WriteArraySpecifiers(variableIdentifier.ArraySpecifiers);
  1112. return EndNode(variableIdentifier);
  1113. }
  1114. public object VisitAccessor(Accessor accessor, object data)
  1115. {
  1116. StartNode(accessor);
  1117. WriteAttributes(accessor.Attributes);
  1118. WriteModifiers(accessor.ModifierTokens);
  1119. if (accessor.Role == PropertyDeclaration.GetterRole) {
  1120. WriteKeyword("Get");
  1121. } else if (accessor.Role == PropertyDeclaration.SetterRole) {
  1122. WriteKeyword("Set");
  1123. } else if (accessor.Role == EventDeclaration.AddHandlerRole) {
  1124. WriteKeyword("AddHandler");
  1125. } else if (accessor.Role == EventDeclaration.RemoveHandlerRole) {
  1126. WriteKeyword("RemoveHandler");
  1127. } else if (accessor.Role == EventDeclaration.RaiseEventRole) {
  1128. WriteKeyword("RaiseEvent");
  1129. }
  1130. if (accessor.Parameters.Any())
  1131. WriteCommaSeparatedListInParenthesis(accessor.Parameters, false);
  1132. NewLine();
  1133. Indent();
  1134. WriteBlock(accessor.Body);
  1135. Unindent();
  1136. WriteKeyword("End");
  1137. if (accessor.Role == PropertyDeclaration.GetterRole) {
  1138. WriteKeyword("Get");
  1139. } else if (accessor.Role == PropertyDeclaration.SetterRole) {
  1140. WriteKeyword("Set");
  1141. } else if (accessor.Role == EventDeclaration.AddHandlerRole) {
  1142. WriteKeyword("AddHandler");
  1143. } else if (accessor.Role == EventDeclaration.RemoveHandlerRole) {
  1144. WriteKeyword("RemoveHandler");
  1145. } else if (accessor.Role == EventDeclaration.RaiseEventRole) {
  1146. WriteKeyword("RaiseEvent");
  1147. }
  1148. NewLine();
  1149. return EndNode(accessor);
  1150. }
  1151. public object VisitLabelDeclarationStatement(LabelDeclarationStatement labelDeclarationStatement, object data)
  1152. {
  1153. StartNode(labelDeclarationStatement);
  1154. labelDeclarationStatement.Label.AcceptVisitor(this, data);
  1155. WriteToken(":", LabelDeclarationStatement.Roles.Colon);
  1156. return EndNode(labelDeclarationStatement);
  1157. }
  1158. public object VisitLocalDeclarationStatement(LocalDeclarationStatement localDeclarationStatement, object data)
  1159. {
  1160. StartNode(localDeclarationStatement);
  1161. if (localDeclarationStatement.ModifierToken != null && !localDeclarationStatement.ModifierToken.IsNull)
  1162. WriteModifiers(new [] { localDeclarationStatement.ModifierToken });
  1163. WriteCommaSeparatedList(localDeclarationStatement.Variables);
  1164. return EndNode(localDeclarationStatement);
  1165. }
  1166. public object VisitWithStatement(WithStatement withStatement, object data)
  1167. {
  1168. StartNode(withStatement);
  1169. WriteKeyword("With");
  1170. withStatement.Expression.AcceptVisitor(this, data);
  1171. NewLine();
  1172. Indent();
  1173. withStatement.Body.AcceptVisitor(this, data);
  1174. Unindent();
  1175. WriteKeyword("End");
  1176. WriteKeyword("With");
  1177. return EndNode(withStatement);
  1178. }
  1179. public object VisitSyncLockStatement(SyncLockStatement syncLockStatement, object data)
  1180. {
  1181. StartNode(syncLockStatement);
  1182. WriteKeyword("SyncLock");
  1183. syncLockStatement.Expression.AcceptVisitor(this, data);
  1184. NewLine();
  1185. Indent();
  1186. syncLockStatement.Body.AcceptVisitor(this, data);
  1187. Unindent();
  1188. WriteKeyword("End");
  1189. WriteKeyword("SyncLock");
  1190. return EndNode(syncLockStatement);
  1191. }
  1192. public object VisitTryStatement(TryStatement tryStatement, object data)
  1193. {
  1194. StartNode(tryStatement);
  1195. WriteKeyword("Try");
  1196. NewLine();
  1197. Indent();
  1198. tryStatement.Body.AcceptVisitor(this, data);
  1199. Unindent();
  1200. foreach (var clause in tryStatement.CatchBlocks) {
  1201. clause.AcceptVisitor(this, data);
  1202. }
  1203. if (!tryStatement.FinallyBlock.IsNull) {
  1204. WriteKeyword("Finally");
  1205. NewLine();
  1206. Indent();
  1207. tryStatement.FinallyBlock.AcceptVisitor(this, data);
  1208. Unindent();
  1209. }
  1210. WriteKeyword("End");
  1211. WriteKeyword("Try");
  1212. return EndNode(tryStatement);
  1213. }
  1214. public object VisitCatchBlock(CatchBlock catchBlock, object data)
  1215. {
  1216. StartNode(catchBlock);
  1217. WriteKeyword("Catch");
  1218. catchBlock.ExceptionVariable.AcceptVisitor(this, data);
  1219. if (!catchBlock.ExceptionType.IsNull) {
  1220. WriteKeyword("As");
  1221. catchBlock.ExceptionType.AcceptVisitor(this, data);
  1222. }
  1223. NewLine();
  1224. Indent();
  1225. foreach (var stmt in catchBlock) {
  1226. stmt.AcceptVisitor(this, data);
  1227. NewLine();
  1228. }
  1229. Unindent();
  1230. return EndNode(catchBlock);
  1231. }
  1232. public object VisitExpressionStatement(ExpressionStatement expressionStatement, object data)
  1233. {
  1234. StartNode(expressionStatement);
  1235. expressionStatement.Expression.AcceptVisitor(this, data);
  1236. return EndNode(expressionStatement);
  1237. }
  1238. public object VisitThrowStatement(ThrowStatement throwStatement, object data)
  1239. {
  1240. StartNode(throwStatement);
  1241. WriteKeyword("Throw");
  1242. throwStatement.Expression.AcceptVisitor(this, data);
  1243. return EndNode(throwStatement);
  1244. }
  1245. public object VisitIfElseStatement(IfElseStatement ifElseStatement, object data)
  1246. {
  1247. StartNode(ifElseStatement);
  1248. WriteKeyword("If");
  1249. ifElseStatement.Condition.AcceptVisitor(this, data);
  1250. Space();
  1251. WriteKeyword("Then");
  1252. NewLine();
  1253. Indent();
  1254. ifElseStatement.Body.AcceptVisitor(this, data);
  1255. Unindent();
  1256. if (!ifElseStatement.ElseBlock.IsNull) {
  1257. WriteKeyword("Else");
  1258. NewLine();
  1259. Indent();
  1260. ifElseStatement.ElseBlock.AcceptVisitor(this, data);
  1261. Unindent();
  1262. }
  1263. WriteKeyword("End");
  1264. WriteKeyword("If");
  1265. return EndNode(ifElseStatement);
  1266. }
  1267. public object VisitReturnStatement(ReturnStatement returnStatement, object data)
  1268. {
  1269. StartNode(returnStatement);
  1270. WriteKeyword("Return");
  1271. returnStatement.Expression.AcceptVisitor(this, data);
  1272. return EndNode(returnStatement);
  1273. }
  1274. public object VisitBinaryOperatorExpression(BinaryOperatorExpression binaryOperatorExpression, object data)
  1275. {
  1276. StartNode(binaryOperatorExpression);
  1277. binaryOperatorExpression.Left.AcceptVisitor(this, data);
  1278. Space();
  1279. switch (binaryOperatorExpression.Operator) {
  1280. case BinaryOperatorType.BitwiseAnd:
  1281. WriteKeyword("And");
  1282. break;
  1283. case BinaryOperatorType.BitwiseOr:
  1284. WriteKeyword("Or");
  1285. break;
  1286. case BinaryOperatorType.LogicalAnd:
  1287. WriteKeyword("AndAlso");
  1288. break;
  1289. case BinaryOperatorType.LogicalOr:
  1290. WriteKeyword("OrElse");
  1291. break;
  1292. case BinaryOperatorType.ExclusiveOr:
  1293. WriteKeyword("Xor");
  1294. break;
  1295. case BinaryOperatorType.GreaterThan:
  1296. WriteToken(">", BinaryOperatorExpression.OperatorRole);
  1297. break;
  1298. case BinaryOperatorType.GreaterThanOrEqual:
  1299. WriteToken(">=", BinaryOperatorExpression.OperatorRole);
  1300. break;
  1301. case BinaryOperatorType.Equality:
  1302. WriteToken("=", BinaryOperatorExpression.OperatorRole);
  1303. break;
  1304. case BinaryOperatorType.InEquality:
  1305. WriteToken("<>", BinaryOperatorExpression.OperatorRole);
  1306. break;
  1307. case BinaryOperatorType.LessThan:
  1308. WriteToken("<", BinaryOperatorExpression.OperatorRole);
  1309. break;
  1310. case BinaryOperatorType.LessThanOrEqual:
  1311. WriteToken("<=", BinaryOperatorExpression.OperatorRole);
  1312. break;
  1313. case BinaryOperatorType.Add:
  1314. WriteToken("+", BinaryOperatorExpression.OperatorRole);
  1315. break;
  1316. case BinaryOperatorType.Subtract:
  1317. WriteToken("-", BinaryOperatorExpression.OperatorRole);
  1318. break;
  1319. case BinaryOperatorType.Multiply:
  1320. WriteToken("*", BinaryOperatorExpression.OperatorRole);
  1321. break;
  1322. case BinaryOperatorType.Divide:
  1323. WriteToken("/", BinaryOperatorExpression.OperatorRole);
  1324. break;
  1325. case BinaryOperatorType.Modulus:
  1326. WriteKeyword("Mod");
  1327. break;
  1328. case BinaryOperatorType.DivideInteger:
  1329. WriteToken("\\", BinaryOperatorExpression.OperatorRole);
  1330. break;
  1331. case BinaryOperatorType.Power:
  1332. WriteToken("*", BinaryOperatorExpression.OperatorRole);
  1333. break;
  1334. case BinaryOperatorType.Concat:
  1335. WriteToken("&", BinaryOperatorExpression.OperatorRole);
  1336. break;
  1337. case BinaryOperatorType.ShiftLeft:
  1338. WriteToken("<<", BinaryOperatorExpression.OperatorRole);
  1339. break;
  1340. case BinaryOperatorType.ShiftRight:
  1341. WriteToken(">>", BinaryOperatorExpression.OperatorRole);
  1342. break;
  1343. case BinaryOperatorType.ReferenceEquality:
  1344. WriteKeyword("Is");
  1345. break;
  1346. case BinaryOperatorType.ReferenceInequality:
  1347. WriteKeyword("IsNot");
  1348. break;
  1349. case BinaryOperatorType.Like:
  1350. WriteKeyword("Like");
  1351. break;
  1352. case BinaryOperatorType.DictionaryAccess:
  1353. WriteToken("!", BinaryOperatorExpression.OperatorRole);
  1354. break;
  1355. default:
  1356. throw new Exception("Invalid value for BinaryOperatorType: " + binaryOperatorExpression.Operator);
  1357. }
  1358. Space();
  1359. binaryOperatorExpression.Right.AcceptVisitor(this, data);
  1360. return EndNode(binaryOperatorExpression);
  1361. }
  1362. public object VisitIdentifierExpression(IdentifierExpression identifierExpression, object data)
  1363. {
  1364. StartNode(identifierExpression);
  1365. identifierExpression.Identifier.AcceptVisitor(this, data);
  1366. WriteTypeArguments(identifierExpression.TypeArguments);
  1367. return EndNode(identifierExpression);
  1368. }
  1369. public object VisitAssignmentExpression(AssignmentExpression assignmentExpression, object data)
  1370. {
  1371. StartNode(assignmentExpression);
  1372. assignmentExpression.Left.AcceptVisitor(this, data);
  1373. Space();
  1374. switch (assignmentExpression.Operator) {
  1375. case AssignmentOperatorType.Assign:
  1376. WriteToken("=", AssignmentExpression.OperatorRole);
  1377. break;
  1378. case AssignmentOperatorType.Add:
  1379. WriteToken("+=", AssignmentExpression.OperatorRole);
  1380. break;
  1381. case AssignmentOperatorType.Subtract:
  1382. WriteToken("-=", AssignmentExpression.OperatorRole);
  1383. break;
  1384. case AssignmentOperatorType.Multiply:
  1385. WriteToken("*=", AssignmentExpression.OperatorRole);
  1386. break;
  1387. case AssignmentOperatorType.Divide:
  1388. WriteToken("/=", AssignmentExpression.OperatorRole);
  1389. break;
  1390. case AssignmentOperatorType.Power:
  1391. WriteToken("^=", AssignmentExpression.OperatorRole);
  1392. break;
  1393. case AssignmentOperatorType.DivideInteger:
  1394. WriteToken("\\=", AssignmentExpression.OperatorRole);
  1395. break;
  1396. case AssignmentOperatorType.ConcatString:
  1397. WriteToken("&=", AssignmentExpression.OperatorRole);
  1398. break;
  1399. case AssignmentOperatorType.ShiftLeft:
  1400. WriteToken("<<=", AssignmentExpression.OperatorRole);
  1401. break;
  1402. case AssignmentOperatorType.ShiftRight:
  1403. WriteToken(">>=", AssignmentExpression.OperatorRole);
  1404. break;
  1405. default:
  1406. throw new Exception("Invalid value for AssignmentOperatorType: " + assignmentExpression.Operator);
  1407. }
  1408. Space();
  1409. assignmentExpression.Right.AcceptVisitor(this, data);
  1410. return EndNode(assignmentExpression);
  1411. }
  1412. public object VisitInvocationExpression(InvocationExpression invocationExpression, object data)
  1413. {
  1414. StartNode(invocationExpression);
  1415. invocationExpression.Target.AcceptVisitor(this, data);
  1416. WriteCommaSeparatedListInParenthesis(invocationExpression.Arguments, false);
  1417. return EndNode(invocationExpression);
  1418. }
  1419. public object VisitArrayInitializerExpression(ArrayInitializerExpression arrayInitializerExpression, object data)
  1420. {
  1421. StartNode(arrayInitializerExpression);
  1422. WriteToken("{", ArrayInitializerExpression.Roles.LBrace);
  1423. Space();
  1424. WriteCommaSeparatedList(arrayInitializerExpression.Elements);
  1425. Space();
  1426. WriteToken("}", ArrayInitializerExpression.Roles.RBrace);
  1427. return EndNode(arrayInitializerExpression);
  1428. }
  1429. public object VisitArrayCreateExpression(ArrayCreateExpression arrayCreateExpression, object data)
  1430. {
  1431. StartNode(arrayCreateExpression);
  1432. WriteKeyword("New");
  1433. Space();
  1434. arrayCreateExpression.Type.AcceptVisitor(this, data);
  1435. WriteCommaSeparatedListInParenthesis(arrayCreateExpression.Arguments, false);
  1436. foreach (var specifier in arrayCreateExpression.AdditionalArraySpecifiers) {
  1437. specifier.AcceptVisitor(this, data);
  1438. }
  1439. if (lastWritten != LastWritten.Whitespace)
  1440. Space();
  1441. if (arrayCreateExpression.Initializer.IsNull) {
  1442. WriteToken("{", ArrayInitializerExpression.Roles.LBrace);
  1443. WriteToken("}", ArrayInitializerExpression.Roles.RBrace);
  1444. } else {
  1445. arrayCreateExpression.Initializer.AcceptVisitor(this, data);
  1446. }
  1447. return EndNode(arrayCreateExpression);
  1448. }
  1449. public object VisitObjectCreationExpression(ObjectCreationExpression objectCreationExpression, object data)
  1450. {
  1451. StartNode(objectCreationExpression);
  1452. WriteKeyword("New");
  1453. objectCreationExpression.Type.AcceptVisitor(this, data);
  1454. WriteCommaSeparatedListInParenthesis(objectCreationExpression.Arguments, false);
  1455. if (!objectCreationExpression.Initializer.IsNull) {
  1456. Space();
  1457. if (objectCreationExpression.Initializer.Elements.Any(x =