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