PrettyPrinterTest.php 13 KB

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