PrettyPrinterTest.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. <?php declare(strict_types=1);
  2. namespace PhpParser;
  3. use PhpParser\Node\Expr;
  4. use PhpParser\Node\Name;
  5. use PhpParser\Node\Scalar\DNumber;
  6. use PhpParser\Node\Scalar\Encapsed;
  7. use PhpParser\Node\Scalar\EncapsedStringPart;
  8. use PhpParser\Node\Scalar\LNumber;
  9. use PhpParser\Node\Scalar\String_;
  10. use PhpParser\Node\Stmt;
  11. use PhpParser\PrettyPrinter\Standard;
  12. class PrettyPrinterTest extends CodeTestAbstract
  13. {
  14. protected function doTestPrettyPrintMethod($method, $name, $code, $expected, $modeLine) {
  15. $lexer = new Lexer\Emulative;
  16. $parser5 = new Parser\Php5($lexer);
  17. $parser7 = new Parser\Php7($lexer);
  18. list($version, $options) = $this->parseModeLine($modeLine);
  19. $prettyPrinter = new Standard($options);
  20. try {
  21. $output5 = canonicalize($prettyPrinter->$method($parser5->parse($code)));
  22. } catch (Error $e) {
  23. $output5 = null;
  24. if ('php7' !== $version) {
  25. throw $e;
  26. }
  27. }
  28. try {
  29. $output7 = canonicalize($prettyPrinter->$method($parser7->parse($code)));
  30. } catch (Error $e) {
  31. $output7 = null;
  32. if ('php5' !== $version) {
  33. throw $e;
  34. }
  35. }
  36. if ('php5' === $version) {
  37. $this->assertSame($expected, $output5, $name);
  38. $this->assertNotSame($expected, $output7, $name);
  39. } elseif ('php7' === $version) {
  40. $this->assertSame($expected, $output7, $name);
  41. $this->assertNotSame($expected, $output5, $name);
  42. } else {
  43. $this->assertSame($expected, $output5, $name);
  44. $this->assertSame($expected, $output7, $name);
  45. }
  46. }
  47. /**
  48. * @dataProvider provideTestPrettyPrint
  49. * @covers \PhpParser\PrettyPrinter\Standard<extended>
  50. */
  51. public function testPrettyPrint($name, $code, $expected, $mode) {
  52. $this->doTestPrettyPrintMethod('prettyPrint', $name, $code, $expected, $mode);
  53. }
  54. /**
  55. * @dataProvider provideTestPrettyPrintFile
  56. * @covers \PhpParser\PrettyPrinter\Standard<extended>
  57. */
  58. public function testPrettyPrintFile($name, $code, $expected, $mode) {
  59. $this->doTestPrettyPrintMethod('prettyPrintFile', $name, $code, $expected, $mode);
  60. }
  61. public function provideTestPrettyPrint() {
  62. return $this->getTests(__DIR__ . '/../code/prettyPrinter', 'test');
  63. }
  64. public function provideTestPrettyPrintFile() {
  65. return $this->getTests(__DIR__ . '/../code/prettyPrinter', 'file-test');
  66. }
  67. public function testPrettyPrintExpr() {
  68. $prettyPrinter = new Standard;
  69. $expr = new Expr\BinaryOp\Mul(
  70. new Expr\BinaryOp\Plus(new Expr\Variable('a'), new Expr\Variable('b')),
  71. new Expr\Variable('c')
  72. );
  73. $this->assertEquals('($a + $b) * $c', $prettyPrinter->prettyPrintExpr($expr));
  74. $expr = new Expr\Closure([
  75. 'stmts' => [new Stmt\Return_(new String_("a\nb"))]
  76. ]);
  77. $this->assertEquals("function () {\n return 'a\nb';\n}", $prettyPrinter->prettyPrintExpr($expr));
  78. }
  79. public function testCommentBeforeInlineHTML() {
  80. $prettyPrinter = new PrettyPrinter\Standard;
  81. $comment = new Comment\Doc("/**\n * This is a comment\n */");
  82. $stmts = [new Stmt\InlineHTML('Hello World!', ['comments' => [$comment]])];
  83. $expected = "<?php\n\n/**\n * This is a comment\n */\n?>\nHello World!";
  84. $this->assertSame($expected, $prettyPrinter->prettyPrintFile($stmts));
  85. }
  86. private function parseModeLine($modeLine) {
  87. $parts = explode(' ', (string) $modeLine, 2);
  88. $version = $parts[0] ?? 'both';
  89. $options = isset($parts[1]) ? json_decode($parts[1], true) : [];
  90. return [$version, $options];
  91. }
  92. public function testArraySyntaxDefault() {
  93. $prettyPrinter = new Standard(['shortArraySyntax' => true]);
  94. $expr = new Expr\Array_([
  95. new Expr\ArrayItem(new String_('val'), new String_('key'))
  96. ]);
  97. $expected = "['key' => 'val']";
  98. $this->assertSame($expected, $prettyPrinter->prettyPrintExpr($expr));
  99. }
  100. /**
  101. * @dataProvider provideTestKindAttributes
  102. */
  103. public function testKindAttributes($node, $expected) {
  104. $prttyPrinter = new PrettyPrinter\Standard;
  105. $result = $prttyPrinter->prettyPrintExpr($node);
  106. $this->assertSame($expected, $result);
  107. }
  108. public function provideTestKindAttributes() {
  109. $nowdoc = ['kind' => String_::KIND_NOWDOC, 'docLabel' => 'STR'];
  110. $heredoc = ['kind' => String_::KIND_HEREDOC, 'docLabel' => 'STR'];
  111. return [
  112. // Defaults to single quoted
  113. [new String_('foo'), "'foo'"],
  114. // Explicit single/double quoted
  115. [new String_('foo', ['kind' => String_::KIND_SINGLE_QUOTED]), "'foo'"],
  116. [new String_('foo', ['kind' => String_::KIND_DOUBLE_QUOTED]), '"foo"'],
  117. // Fallback from doc string if no label
  118. [new String_('foo', ['kind' => String_::KIND_NOWDOC]), "'foo'"],
  119. [new String_('foo', ['kind' => String_::KIND_HEREDOC]), '"foo"'],
  120. // Fallback if string contains label
  121. [new String_("A\nB\nC", ['kind' => String_::KIND_NOWDOC, 'docLabel' => 'A']), "'A\nB\nC'"],
  122. [new String_("A\nB\nC", ['kind' => String_::KIND_NOWDOC, 'docLabel' => 'B']), "'A\nB\nC'"],
  123. [new String_("A\nB\nC", ['kind' => String_::KIND_NOWDOC, 'docLabel' => 'C']), "'A\nB\nC'"],
  124. [new String_("STR;", ['kind' => String_::KIND_NOWDOC, 'docLabel' => 'STR']), "'STR;'"],
  125. // Doc string if label not contained (or not in ending position)
  126. [new String_("foo", $nowdoc), "<<<'STR'\nfoo\nSTR\n"],
  127. [new String_("foo", $heredoc), "<<<STR\nfoo\nSTR\n"],
  128. [new String_("STRx", $nowdoc), "<<<'STR'\nSTRx\nSTR\n"],
  129. [new String_("xSTR", $nowdoc), "<<<'STR'\nxSTR\nSTR\n"],
  130. // Empty doc string variations (encapsed variant does not occur naturally)
  131. [new String_("", $nowdoc), "<<<'STR'\nSTR\n"],
  132. [new String_("", $heredoc), "<<<STR\nSTR\n"],
  133. [new Encapsed([new EncapsedStringPart('')], $heredoc), "<<<STR\nSTR\n"],
  134. // Encapsed doc string variations
  135. [new Encapsed([new EncapsedStringPart('foo')], $heredoc), "<<<STR\nfoo\nSTR\n"],
  136. [new Encapsed([new EncapsedStringPart('foo'), new Expr\Variable('y')], $heredoc), "<<<STR\nfoo{\$y}\nSTR\n"],
  137. [new Encapsed([new EncapsedStringPart("\nSTR"), new Expr\Variable('y')], $heredoc), "<<<STR\n\nSTR{\$y}\nSTR\n"],
  138. [new Encapsed([new EncapsedStringPart("\nSTR"), new Expr\Variable('y')], $heredoc), "<<<STR\n\nSTR{\$y}\nSTR\n"],
  139. [new Encapsed([new Expr\Variable('y'), new EncapsedStringPart("STR\n")], $heredoc), "<<<STR\n{\$y}STR\n\nSTR\n"],
  140. // Encapsed doc string fallback
  141. [new Encapsed([new Expr\Variable('y'), new EncapsedStringPart("\nSTR")], $heredoc), '"{$y}\\nSTR"'],
  142. [new Encapsed([new EncapsedStringPart("STR\n"), new Expr\Variable('y')], $heredoc), '"STR\\n{$y}"'],
  143. [new Encapsed([new EncapsedStringPart("STR")], $heredoc), '"STR"'],
  144. ];
  145. }
  146. /** @dataProvider provideTestUnnaturalLiterals */
  147. public function testUnnaturalLiterals($node, $expected) {
  148. $prttyPrinter = new PrettyPrinter\Standard;
  149. $result = $prttyPrinter->prettyPrintExpr($node);
  150. $this->assertSame($expected, $result);
  151. }
  152. public function provideTestUnnaturalLiterals() {
  153. return [
  154. [new LNumber(-1), '-1'],
  155. [new LNumber(-PHP_INT_MAX - 1), '(-' . PHP_INT_MAX . '-1)'],
  156. [new LNumber(-1, ['kind' => LNumber::KIND_BIN]), '-0b1'],
  157. [new LNumber(-1, ['kind' => LNumber::KIND_OCT]), '-01'],
  158. [new LNumber(-1, ['kind' => LNumber::KIND_HEX]), '-0x1'],
  159. [new DNumber(\INF), '\INF'],
  160. [new DNumber(-\INF), '-\INF'],
  161. [new DNumber(-\NAN), '\NAN'],
  162. ];
  163. }
  164. public function testPrettyPrintWithError() {
  165. $this->expectException(\LogicException::class);
  166. $this->expectExceptionMessage('Cannot pretty-print AST with Error nodes');
  167. $stmts = [new Stmt\Expression(
  168. new Expr\PropertyFetch(new Expr\Variable('a'), new Expr\Error())
  169. )];
  170. $prettyPrinter = new PrettyPrinter\Standard;
  171. $prettyPrinter->prettyPrint($stmts);
  172. }
  173. public function testPrettyPrintWithErrorInClassConstFetch() {
  174. $this->expectException(\LogicException::class);
  175. $this->expectExceptionMessage('Cannot pretty-print AST with Error nodes');
  176. $stmts = [new Stmt\Expression(
  177. new Expr\ClassConstFetch(new Name('Foo'), new Expr\Error())
  178. )];
  179. $prettyPrinter = new PrettyPrinter\Standard;
  180. $prettyPrinter->prettyPrint($stmts);
  181. }
  182. public function testPrettyPrintEncapsedStringPart() {
  183. $this->expectException(\LogicException::class);
  184. $this->expectExceptionMessage('Cannot directly print EncapsedStringPart');
  185. $expr = new Node\Scalar\EncapsedStringPart('foo');
  186. $prettyPrinter = new PrettyPrinter\Standard;
  187. $prettyPrinter->prettyPrintExpr($expr);
  188. }
  189. /**
  190. * @dataProvider provideTestFormatPreservingPrint
  191. * @covers \PhpParser\PrettyPrinter\Standard<extended>
  192. */
  193. public function testFormatPreservingPrint($name, $code, $modification, $expected, $modeLine) {
  194. $lexer = new Lexer\Emulative([
  195. 'usedAttributes' => [
  196. 'comments',
  197. 'startLine', 'endLine',
  198. 'startTokenPos', 'endTokenPos',
  199. ],
  200. ]);
  201. $parser = new Parser\Php7($lexer);
  202. $traverser = new NodeTraverser();
  203. $traverser->addVisitor(new NodeVisitor\CloningVisitor());
  204. $printer = new PrettyPrinter\Standard();
  205. $oldStmts = $parser->parse($code);
  206. $oldTokens = $lexer->getTokens();
  207. $newStmts = $traverser->traverse($oldStmts);
  208. /** @var callable $fn */
  209. eval(<<<CODE
  210. use PhpParser\Comment;
  211. use PhpParser\Node;
  212. use PhpParser\Node\Expr;
  213. use PhpParser\Node\Scalar;
  214. use PhpParser\Node\Stmt;
  215. \$fn = function(&\$stmts) { $modification };
  216. CODE
  217. );
  218. $fn($newStmts);
  219. $newCode = $printer->printFormatPreserving($newStmts, $oldStmts, $oldTokens);
  220. $this->assertSame(canonicalize($expected), canonicalize($newCode), $name);
  221. }
  222. public function provideTestFormatPreservingPrint() {
  223. return $this->getTests(__DIR__ . '/../code/formatPreservation', 'test', 3);
  224. }
  225. /**
  226. * @dataProvider provideTestRoundTripPrint
  227. * @covers \PhpParser\PrettyPrinter\Standard<extended>
  228. */
  229. public function testRoundTripPrint($name, $code, $expected, $modeLine) {
  230. /**
  231. * This test makes sure that the format-preserving pretty printer round-trips for all
  232. * the pretty printer tests (i.e. returns the input if no changes occurred).
  233. */
  234. list($version) = $this->parseModeLine($modeLine);
  235. $lexer = new Lexer\Emulative([
  236. 'usedAttributes' => [
  237. 'comments',
  238. 'startLine', 'endLine',
  239. 'startTokenPos', 'endTokenPos',
  240. ],
  241. ]);
  242. $parserClass = $version === 'php5' ? Parser\Php5::class : Parser\Php7::class;
  243. /** @var Parser $parser */
  244. $parser = new $parserClass($lexer);
  245. $traverser = new NodeTraverser();
  246. $traverser->addVisitor(new NodeVisitor\CloningVisitor());
  247. $printer = new PrettyPrinter\Standard();
  248. try {
  249. $oldStmts = $parser->parse($code);
  250. } catch (Error $e) {
  251. // Can't do a format-preserving print on a file with errors
  252. return;
  253. }
  254. $oldTokens = $lexer->getTokens();
  255. $newStmts = $traverser->traverse($oldStmts);
  256. $newCode = $printer->printFormatPreserving($newStmts, $oldStmts, $oldTokens);
  257. $this->assertSame(canonicalize($code), canonicalize($newCode), $name);
  258. }
  259. public function provideTestRoundTripPrint() {
  260. return array_merge(
  261. $this->getTests(__DIR__ . '/../code/prettyPrinter', 'test'),
  262. $this->getTests(__DIR__ . '/../code/parser', 'test')
  263. );
  264. }
  265. }