Debian Codegraph @

vendor/mck89/peast/lib/Peast/Renderer.php

raw
1 <?php
2 /**
3 * This file is part of the Peast package
4 *
5 * (c) Marco Marchiò <[email protected]>
6 *
7 * For the full copyright and license information refer to the LICENSE file
8 * distributed with this source code
9 */
10 namespace Peast;
11
12 use Peast\Syntax\Node\Comment;
13
14 /**
15 * Nodes renderer class
16 *
17 * @author Marco Marchiò <[email protected]>
18 */
19 class Renderer
20 {
21 /**
22 * Formatter to use for the rendering
23 *
24 * @var Formatter\Base
25 */
26 protected $formatter;
27
28 /**
29 * Rendering options taken from the formatter
30 *
31 * @var object
32 */
33 protected $renderOpts;
34
35 /**
36 * Node types that does not require semicolon insertion
37 *
38 * @var array
39 */
40 protected $noSemicolon = array(
41 "ClassDeclaration",
42 "ExportDefaultDeclaration",
43 "ForInStatement",
44 "ForOfStatement",
45 "ForStatement",
46 "FunctionDeclaration",
47 "IfStatement",
48 "LabeledStatement",
49 "StaticBlock",
50 "SwitchStatement",
51 "TryStatement",
52 "WhileStatement",
53 "WithStatement",
54 "MethodDefinition"
55 );
56
57 /**
58 * Sets the formatter to use for the rendering
59 *
60 * @param Formatter\Base $formatter Formatter
61 *
62 * @return $this
63 */
64 public function setFormatter(Formatter\Base $formatter)
65 {
66 $this->formatter = $formatter;
67
68 $this->renderOpts = (object) array(
69 "nl" => $this->formatter->getNewLine(),
70 "ind" => $this->formatter->getIndentation(),
71 "nlbc" => $this->formatter->getNewLineBeforeCurlyBracket(),
72 "sao" => $this->formatter->getSpacesAroundOperator() ? " " : "",
73 "sirb" => $this->formatter->getSpacesInsideRoundBrackets() ? " " : "",
74 "awb" => $this->formatter->getAlwaysWrapBlocks(),
75 "com" => $this->formatter->getRenderComments(),
76 "rci" => $this->formatter->getRecalcCommentsIndent()
77 );
78
79 return $this;
80 }
81
82 /**
83 * Returns the formatter to use for the rendering
84 *
85 * @return Formatter\Base
86 */
87 public function getFormatter()
88 {
89 return $this->formatter;
90 }
91
92 /**
93 * Renders the given node
94 *
95 * @param Syntax\Node\Node $node Node to render
96 *
97 * @return string
98 *
99 * @throws \Exception
100 */
101 public function render(Syntax\Node\Node $node)
102 {
103 //Throw exception if no formatter has been specified
104 if (!$this->formatter) {
105 throw new \Exception("Formatter not set");
106 }
107
108 //Reset indentation level
109 $this->renderOpts->indLevel = 0;
110
111 //Start rendering
112 return $this->renderNode($node);
113 }
114
115 /**
116 * Renders a node
117 *
118 * @param Syntax\Node\Node $node Node to render
119 * @param bool $addSemicolon True to add semicolon after node
120 * rendered code
121 *
122 * @return string
123 */
124 protected function renderNode(Syntax\Node\Node $node, $addSemicolon = false)
125 {
126 $code = "";
127 if ($this->renderOpts->com) {
128 $code .= $this->renderComments($node);
129 }
130 $type = $node->getType();
131 switch ($type) {
132 case "ArrayExpression":
133 case "ArrayPattern":
134 $code .= "[" .
135 $this->joinNodes(
136 $node->getElements(),
137 "," . $this->renderOpts->sao
138 ) .
139 "]";
140 break;
141 case "ArrowFunctionExpression":
142 if ($node->getAsync()) {
143 $code .= "async" . $this->renderOpts->sao;
144 }
145 $code .= "(" .
146 $this->renderOpts->sirb .
147 $this->joinNodes(
148 $node->getParams(),
149 "," . $this->renderOpts->sao
150 ) .
151 $this->renderOpts->sirb .
152 ")" .
153 $this->renderOpts->sao .
154 "=>";
155 $body = $node->getBody();
156 if ($body->getType() !== "BlockStatement") {
157 $code .= $this->renderOpts->sao . $this->renderNode($body);
158 } else {
159 $code .= $this->renderStatementBlock($node, $body, true);
160 }
161 break;
162 case "AwaitExpression":
163 $code .= "await " . $this->renderNode($node->getArgument());
164 break;
165 case "AssignmentExpression":
166 case "AssignmentPattern":
167 case "BinaryExpression":
168 case "LogicalExpression":
169 $operator = $type === "AssignmentPattern" ?
170 "=" :
171 $node->getOperator();
172 $code .= $this->renderNode($node->getLeft());
173 $codeRight = $this->renderNode($node->getRight());
174 if (preg_match("#^[a-z]+$#i", $operator)) {
175 $code .= " " .
176 $operator .
177 " ";
178 } else {
179 //If there's no space around the operator, additional checks must
180 //be performed to prevent errors when rendering unary and update
181 //expressions inside binary expressions
182 $checkSpace = !$this->renderOpts->sao && $type === "BinaryExpression";
183
184 //The space is mandatory if the left part ends with the same
185 //character used as operator
186 if ($checkSpace && $code && substr($code, -1) === $operator) {
187 $code .= " ";
188 }
189
190 $code .= $this->renderOpts->sao .
191 $operator .
192 $this->renderOpts->sao;
193
194 //The space is mandatory if the right part begins with the same
195 //character used as operator
196 if ($checkSpace && $codeRight && $codeRight[0] === $operator) {
197 $code .= " ";
198 }
199 }
200 $code .= $codeRight;
201 break;
202 case "BlockStatement":
203 case "ClassBody":
204 case "Program":
205 $code .= $this->renderStatementBlock(
206 $node, $node->getBody(), false, false, true, false
207 );
208 break;
209 case "BreakStatement":
210 case "ContinueStatement":
211 $code .= $type === "BreakStatement" ? "break" : "continue";
212 if ($label = $node->getLabel()) {
213 $code .= " " . $this->renderNode($label);
214 }
215 break;
216 case "CallExpression":
217 case "NewExpression":
218 if ($type === "NewExpression") {
219 $code .= "new ";
220 $optional = false;
221 } else {
222 $optional = $node->getOptional();
223 }
224 $code .= $this->renderNode($node->getCallee()) .
225 ($optional ? "?." : "") .
226 "(" .
227 $this->renderOpts->sirb .
228 $this->joinNodes(
229 $node->getArguments(),
230 "," . $this->renderOpts->sao
231 ) .
232 $this->renderOpts->sirb .
233 ")";
234 break;
235 case "CatchClause":
236 $code .= "catch";
237 if ($params = $node->getParam()) {
238 $code .= $this->renderOpts->sao .
239 "(" .
240 $this->renderOpts->sirb .
241 $this->renderNode($params) .
242 $this->renderOpts->sirb .
243 ")";
244 }
245 $code .= $this->renderStatementBlock($node, $node->getBody(), true);
246 break;
247 case "ChainExpression":
248 case "ExpressionStatement":
249 $code .= $this->renderNode($node->getExpression());
250 break;
251 case "ClassExpression":
252 case "ClassDeclaration":
253 $code .= "class";
254 if ($id = $node->getId()) {
255 $code .= " " . $this->renderNode($id);
256 }
257 if ($superClass = $node->getSuperClass()) {
258 $code .= " extends " . $this->renderNode($superClass);
259 }
260 $code .= $this->renderStatementBlock(
261 $node, $node->getBody(), true
262 );
263 break;
264 case "ConditionalExpression":
265 $code .= $this->renderNode($node->getTest()) .
266 $this->renderOpts->sao .
267 "?" .
268 $this->renderOpts->sao .
269 $this->renderNode($node->getConsequent()) .
270 $this->renderOpts->sao .
271 ":" .
272 $this->renderOpts->sao .
273 $this->renderNode($node->getAlternate());
274 break;
275 case "DebuggerStatement":
276 $code .= "debugger";
277 break;
278 case "DoWhileStatement":
279 $code .= "do" .
280 $this->renderStatementBlock(
281 $node, $node->getBody(), null, true
282 ) .
283 $this->renderOpts->sao .
284 "while" .
285 $this->renderOpts->sao .
286 "(" .
287 $this->renderOpts->sirb .
288 $this->renderNode($node->getTest()) .
289 $this->renderOpts->sirb .
290 ")";
291 break;
292 case "JSXEmptyExpression":
293 case "EmptyStatement":
294 break;
295 case "ExportAllDeclaration":
296 $code .= "export *";
297 $exported = $node->getExported();
298 if ($exported) {
299 $code .= " as " . $this->renderNode($exported);
300 }
301 $code .= " from " . $this->renderNode($node->getSource());
302 $code .= $this->renderImportAttributes($node);
303 break;
304 case "ExportDefaultDeclaration":
305 $declaration = $node->getDeclaration();
306 $code .= "export default " .
307 $this->renderNode($declaration);
308 if ($this->requiresSemicolon($declaration)) {
309 $code .= ";";
310 }
311 break;
312 case "ExportNamedDeclaration":
313 $code .= "export";
314 if ($dec = $node->getDeclaration()) {
315 $code .= " " .
316 $this->renderNode($dec);
317 } else {
318 $code .= $this->renderOpts->sao .
319 "{" .
320 $this->joinNodes(
321 $node->getSpecifiers(),
322 "," . $this->renderOpts->sao
323 ) .
324 "}";
325 if ($source = $node->getSource()) {
326 $code .= $this->renderOpts->sao .
327 "from " .
328 $this->renderNode($source);
329 }
330 $code .= $this->renderImportAttributes($node);
331 }
332 break;
333 case "ExportSpecifier":
334 $local = $this->renderNode($node->getLocal());
335 $ref = $this->renderNode($node->getExported());
336 $code .= $local === $ref ?
337 $local :
338 $local . " as " . $ref;
339 break;
340 case "ForInStatement":
341 case "ForOfStatement":
342 //Force single line mode for substatements
343 $this->renderOpts->forceSingleLine = true;
344 $code .= "for" .
345 ($type === "ForOfStatement" && $node->getAwait() ? " await" : "") .
346 $this->renderOpts->sao .
347 "(" .
348 $this->renderOpts->sirb .
349 $this->renderNode($node->getLeft()) .
350 " " . ($type === "ForInStatement" ? "in" : "of") . " " .
351 $this->renderNode($node->getRight()) .
352 $this->renderOpts->sirb .
353 ")" .
354 $this->renderStatementBlock($node, $node->getBody());
355 unset($this->renderOpts->forceSingleLine);
356 break;
357 case "ForStatement":
358 //Force single line mode for substatements
359 $this->renderOpts->forceSingleLine = true;
360 $code .= "for" .
361 $this->renderOpts->sao .
362 "(" .
363 $this->renderOpts->sirb;
364 if ($init = $node->getInit()) {
365 $code .= $this->renderNode($init);
366 }
367 $code .= ";" . $this->renderOpts->sao;
368 if ($test = $node->getTest()) {
369 $code .= $this->renderNode($test);
370 }
371 $code .= ";" . $this->renderOpts->sao;
372 if ($update = $node->getUpdate()) {
373 $code .= $this->renderNode($update);
374 }
375 $code .= $this->renderOpts->sirb .
376 ")" .
377 $this->renderStatementBlock($node, $node->getBody());
378 unset($this->renderOpts->forceSingleLine);
379 break;
380 case "FunctionDeclaration":
381 case "FunctionExpression":
382 $id = $node->getId();
383 if ($node->getAsync()) {
384 $code .= "async ";
385 }
386 $code .= "function";
387 if ($node->getGenerator()) {
388 $code .= $this->renderOpts->sao .
389 "*";
390 } elseif ($id) {
391 $code .= " ";
392 }
393 if ($id) {
394 if ($node->getGenerator()) {
395 $code .= $this->renderOpts->sao;
396 }
397 $code .= $this->renderNode($id);
398 }
399 $code .= $this->renderOpts->sao .
400 "(" .
401 $this->renderOpts->sirb .
402 $this->joinNodes(
403 $node->getParams(),
404 "," . $this->renderOpts->sao
405 ) .
406 $this->renderOpts->sirb .
407 ")" .
408 $this->renderStatementBlock($node, $node->getBody(), true);
409 break;
410 case "ImportExpression":
411 $options = $node->getOptions();
412 $code .= "import(" .
413 $this->renderOpts->sirb .
414 $this->renderNode($node->getSource()) .
415 (
416 $options ?
417 "," . $this->renderOpts->sao . $this->renderNode($options) :
418 ""
419 ) .
420 $this->renderOpts->sirb .
421 ")";
422 break;
423 case "JSXIdentifier":
424 case "Identifier":
425 $code .= $node->getRawName();
426 break;
427 case "IfStatement":
428 $code .= "if" .
429 $this->renderOpts->sao .
430 "(" .
431 $this->renderOpts->sirb .
432 $this->renderNode($node->getTest()) .
433 $this->renderOpts->sirb .
434 ")";
435
436 $code .= $this->renderStatementBlock(
437 $node, $node->getConsequent()
438 );
439 if ($alternate = $node->getAlternate()) {
440 $code .= $this->renderOpts->sao .
441 "else" .
442 $this->renderStatementBlock(
443 $node,
444 $alternate,
445 null,
446 true
447 );
448 }
449 break;
450 case "ImportAttribute":
451 $code .= $this->renderNode($node->getKey()) .
452 ":" .
453 $this->renderOpts->sao .
454 $this->renderNode($node->getValue());
455 break;
456 case "ImportDeclaration":
457 $code .= "import ";
458 $specifiers = $node->getSpecifiers();
459 if (count($specifiers)) {
460 $sep = "," . $this->renderOpts->sao;
461 $groups = $parts = array();
462 foreach ($specifiers as $spec) {
463 $specType = $spec->getType();
464 if (!isset($groups[$specType])) {
465 $groups[$specType] = array();
466 }
467 $groups[$specType][] = $spec;
468 }
469 if (isset($groups["ImportDefaultSpecifier"])) {
470 foreach ($groups["ImportDefaultSpecifier"] as $s) {
471 $parts[] = $this->renderNode($s);
472 }
473 }
474 if (isset($groups["ImportNamespaceSpecifier"])) {
475 foreach ($groups["ImportNamespaceSpecifier"] as $s) {
476 $parts[] = $this->renderNode($s);
477 }
478 }
479 if (isset($groups["ImportSpecifier"])) {
480 $impSpec = array();
481 foreach ($groups["ImportSpecifier"] as $s) {
482 $impSpec[] = $this->renderNode($s);
483 }
484 $parts[] = "{" . implode($sep, $impSpec) . "}";
485 }
486 $code .= implode($sep, $parts) . " from ";
487 }
488 $code .= $this->renderNode($node->getSource());
489 $code .= $this->renderImportAttributes($node);
490 break;
491 case "ImportDefaultSpecifier":
492 $code .= $this->renderNode($node->getLocal());
493 break;
494 case "ImportNamespaceSpecifier":
495 $code .= "* as " . $this->renderNode($node->getLocal());
496 break;
497 case "ImportSpecifier":
498 $local = $this->renderNode($node->getLocal());
499 $ref = $this->renderNode($node->getImported());
500 $code .= $local === $ref ?
501 $local :
502 $ref . " as " . $local;
503 break;
504 case "JSXAttribute":
505 $code .= $this->renderNode($node->getName());
506 if ($value = $node->getValue()) {
507 $code .= "=" . $this->renderNode($value);
508 }
509 break;
510 case "JSXClosingElement":
511 $code .= "</" . $this->renderNode($node->getName()) . ">";
512 break;
513 case "JSXClosingFragment":
514 $code .= "</>";
515 break;
516 case "JSXElement":
517 $code .= $this->renderNode($node->getOpeningElement()) .
518 $this->joinNodes($node->getChildren(), "");
519 if ($closing = $node->getClosingElement()) {
520 $code .= $this->renderNode($closing);
521 }
522 break;
523 case "JSXExpressionContainer":
524 $code .= "{" . $this->renderNode($node->getExpression()) . "}";
525 break;
526 case "JSXFragment":
527 $code .= $this->renderNode($node->getOpeningFragment()) .
528 $this->joinNodes($node->getChildren(), "") .
529 $this->renderNode($node->getClosingFragment());
530 break;
531 case "JSXNamespacedName":
532 $code .= $this->renderNode($node->getNamespace()) . ":" .
533 $this->renderNode($node->getName());
534 break;
535 case "JSXOpeningElement":
536 $code .= "<" . $this->renderNode($node->getName());
537 $attributes = $node->getAttributes();
538 if (count($attributes)) {
539 $code .= " " . $this->joinNodes($attributes, " ");
540 }
541 if ($node->getSelfClosing()) {
542 $code .= "/";
543 }
544 $code .= ">";
545 break;
546 case "JSXOpeningFragment":
547 $code .= "<>";
548 break;
549 case "JSXSpreadAttribute":
550 $code .= "{..." . $this->renderNode($node->getArgument()) . "}";
551 break;
552 case "JSXSpreadChild":
553 $code .= "{..." . $this->renderNode($node->getExpression()) . "}";
554 break;
555 case "LabeledStatement":
556 $body = $node->getBody();
557 $code .= $this->renderNode($node->getLabel()) .
558 ":";
559 if ($body->getType() === "BlockStatement") {
560 $code .= $this->renderStatementBlock($node, $body, true);
561 } else {
562 $code .= $this->renderOpts->nl .
563 $this->getIndentation() .
564 $this->renderNode($body);
565 }
566 if ($this->requiresSemicolon($body)) {
567 $code .= ";";
568 }
569 break;
570 case "JSXText":
571 case "Literal":
572 case "RegExpLiteral":
573 $code .= $node->getRaw();
574 break;
575 case "JSXMemberExpression":
576 case "MemberExpression":
577 $property = $node->getProperty();
578 $compiledProperty = $this->renderNode($property);
579 $code .= $this->renderNode($node->getObject());
580 $optional = false;
581 if ($type === "MemberExpression") {
582 $optional = $node->getOptional();
583 }
584 $propertyType = $property->getType();
585 if ($type === "MemberExpression" &&
586 ($node->getComputed() ||
587 ($propertyType !== "Identifier" && $propertyType !== "PrivateIdentifier"))) {
588 $code .= ($optional ? "?." : "") . "[" . $compiledProperty . "]";
589 } else {
590 $code .= ($optional ? "?." : ".") . $compiledProperty;
591 }
592 break;
593 case "MetaProperty":
594 $code .= $node->getMeta() . "." . $node->getProperty();
595 break;
596 case "MethodDefinition":
597 if ($node->getStatic()) {
598 $code .= "static ";
599 }
600 $value = $node->getValue();
601 $key = $node->getKey();
602 $kind = $node->getKind();
603 if ($kind === $node::KIND_GET || $kind === $node::KIND_SET) {
604 $code .= $kind . " ";
605 } else {
606 if ($value->getAsync()) {
607 $code .= "async ";
608 }
609 if ($value->getGenerator()) {
610 $code .= "*" .
611 $this->renderOpts->sao;
612 }
613 }
614 if ($node->getComputed()) {
615 $code .= "[" .
616 $this->renderNode($key) .
617 "]";
618 } else {
619 $code .= $this->renderNode($key);
620 }
621 $code .= $this->renderOpts->sao .
622 preg_replace("/^[^(]+/", "", $this->renderNode($value));
623 break;
624 case "ObjectExpression":
625 $currentIndentation = $this->getIndentation();
626 $this->renderOpts->indLevel++;
627 $indentation = $this->getIndentation();
628 //Handle single line mode
629 if (isset($this->renderOpts->forceSingleLine)) {
630 $start = $end = "";
631 $separator = "," . $this->renderOpts->sao;
632 } else {
633 $end = $this->renderOpts->nl . $currentIndentation;
634 $start = $this->renderOpts->nl . $indentation;
635 $separator = "," . $this->renderOpts->nl . $indentation;
636 }
637 $code .= "{";
638 $properties = $node->getProperties();
639 if (count($properties)) {
640 $code .= $start .
641 $this->joinNodes(
642 $properties,
643 $separator
644 ) .
645 $end;
646 }
647 $code .= "}";
648 $this->renderOpts->indLevel--;
649 break;
650 case "ObjectPattern":
651 $code .= "{" .
652 $this->joinNodes(
653 $node->getProperties(),
654 "," . $this->renderOpts->sao
655 ) .
656 "}";
657 break;
658 case "ParenthesizedExpression":
659 $code .= "(" .
660 $this->renderOpts->sirb .
661 $this->renderNode($node->getExpression()) .
662 $this->renderOpts->sirb .
663 ")";
664 break;
665 case "PrivateIdentifier":
666 $code .= "#" . $node->getName();
667 break;
668 case "Property":
669 $value = $node->getValue();
670 $key = $node->getKey();
671 $compiledKey = $this->renderNode($key);
672 $compiledValue = $this->renderNode($value);
673 $keyType = $key->getType();
674 $valueType = $value->getType();
675 if ($valueType === "AssignmentPattern" &&
676 $compiledKey === $this->renderNode($value->getLeft())) {
677 $code .= $compiledValue;
678 } else {
679 $kind = $node->getKind();
680 $getterSetter = $kind === $node::KIND_GET ||
681 $kind === $node::KIND_SET;
682 if ($getterSetter) {
683 $code .= $kind . " ";
684 } elseif ($value->getType() === "FunctionExpression" &&
685 $value->getGenerator()) {
686 $code .= "*" .
687 $this->renderOpts->sao;
688 }
689 if ($node->getMethod() && $value->getAsync()) {
690 $code .= "async ";
691 }
692 if ($node->getComputed()) {
693 $code .= "[" . $compiledKey . "]";
694 } else {
695 $code .= $compiledKey;
696 }
697 if ($node->getMethod() || $getterSetter) {
698 $code .= $this->renderOpts->sao .
699 preg_replace("/^[^(]+/", "", $compiledValue);
700 } elseif ($keyType !== "Identifier" ||
701 $valueType !== "Identifier" ||
702 $compiledKey !== $compiledValue
703 ) {
704 $code .= ($node->getShorthand() ? "=" : ":") .
705 $this->renderOpts->sao .
706 $compiledValue;
707 }
708 }
709 break;
710 case "PropertyDefinition":
711 if ($node->getStatic()) {
712 $code .= "static ";
713 }
714 $compiledKey = $this->renderNode($node->getKey());
715 if ($node->getComputed()) {
716 $code .= "[" . $compiledKey . "]";
717 } else {
718 $code .= $compiledKey;
719 }
720 if ($value = $node->getValue()) {
721 $code .= $this->renderOpts->sao .
722 "=" .
723 $this->renderOpts->sao .
724 $this->renderNode($value);
725 }
726 break;
727 case "RestElement":
728 case "SpreadElement":
729 $code .= "..." . $this->renderNode($node->getArgument());
730 break;
731 case "ReturnStatement":
732 $code .= "return";
733 if ($argument = $node->getArgument()) {
734 $code .= " " . $this->renderNode($argument);
735 }
736 break;
737 case "SequenceExpression":
738 $code .= $this->joinNodes(
739 $node->getExpressions(),
740 "," . $this->renderOpts->sao
741 );
742 break;
743 case "StaticBlock":
744 $code .= "static";
745 $code .= $this->renderStatementBlock($node, $node->getBody(), true);
746 break;
747 case "Super":
748 $code .= "super";
749 break;
750 case "SwitchCase":
751 if ($test = $node->getTest()) {
752 $code .= "case " . $this->renderNode($test);
753 } else {
754 $code .= "default";
755 }
756 $code .= ":";
757 if (count($node->getConsequent())) {
758 $code .= $this->renderStatementBlock(
759 $node,
760 $node->getConsequent()
761 );
762 }
763 break;
764 case "SwitchStatement":
765 $code .= "switch" .
766 $this->renderOpts->sao .
767 "(" .
768 $this->renderOpts->sirb .
769 $this->renderNode($node->getDiscriminant()) .
770 $this->renderOpts->sirb .
771 ")" .
772 $this->renderStatementBlock(
773 $node, $node->getCases(), true, false, false
774 );
775 break;
776 case "TaggedTemplateExpression":
777 $code .= $this->renderNode($node->getTag()) .
778 $this->renderNode($node->getQuasi());
779 break;
780 case "TemplateElement":
781 $code .= $node->getRawValue();
782 break;
783 case "TemplateLiteral":
784 $code .= "`";
785 foreach ($node->getParts() as $part) {
786 if ($part->getType() === "TemplateElement") {
787 $code .= $this->renderNode($part);
788 } else {
789 $code .= "$" . "{" . $this->renderNode($part) . "}";
790 }
791 }
792 $code .= "`";
793 break;
794 case "ThisExpression":
795 $code .= "this";
796 break;
797 case "ThrowStatement":
798 $code .= "throw " . $this->renderNode($node->getArgument());
799 break;
800 case "TryStatement":
801 $code .= "try" .
802 $this->renderStatementBlock($node, $node->getBlock(), true);
803 if ($handler = $node->getHandler()) {
804 $code .= $this->renderOpts->sao .
805 $this->renderNode($handler);
806 }
807 if ($finalizer = $node->getFinalizer()) {
808 $code .= $this->renderOpts->sao .
809 "finally" .
810 $this->renderStatementBlock($node, $finalizer, true);
811 }
812 break;
813 case "UnaryExpression":
814 case "UpdateExpression":
815 $prefix = $node->getPrefix();
816 if ($prefix) {
817 $code .= $node->getOperator();
818 if (preg_match("#^[a-z]+$#i", $node->getOperator())) {
819 $code .= " ";
820 }
821 }
822 $code .= $this->renderNode($node->getArgument());
823 if (!$prefix) {
824 $code .= $node->getOperator();
825 }
826 break;
827 case "VariableDeclaration":
828 $this->renderOpts->indLevel++;
829 $indentation = $this->getIndentation();
830 //Handle single line mode
831 if (isset($this->renderOpts->forceSingleLine)) {
832 $separator = "," . $this->renderOpts->sao;
833 } else {
834 $separator = "," . $this->renderOpts->nl . $indentation;
835 }
836 $code .= $node->getKind() .
837 " " .
838 $this->joinNodes(
839 $node->getDeclarations(),
840 $separator
841 );
842 $this->renderOpts->indLevel--;
843 break;
844 case "VariableDeclarator":
845 $code .= $this->renderNode($node->getId());
846 if ($init = $node->getInit()) {
847 $code .= $this->renderOpts->sao .
848 "=" .
849 $this->renderOpts->sao .
850 $this->renderNode($init);
851 }
852 break;
853 case "WhileStatement":
854 $code .= "while" .
855 $this->renderOpts->sao .
856 "(" .
857 $this->renderOpts->sirb .
858 $this->renderNode($node->getTest()) .
859 $this->renderOpts->sirb .
860 ")" .
861 $this->renderStatementBlock($node, $node->getBody());
862 break;
863 case "WithStatement":
864 $code .= "with" .
865 $this->renderOpts->sao .
866 "(" .
867 $this->renderOpts->sirb .
868 $this->renderNode($node->getObject()) .
869 $this->renderOpts->sirb .
870 ")" .
871 $this->renderStatementBlock($node, $node->getBody());
872 break;
873 case "YieldExpression":
874 $code .= "yield";
875 if ($node->getDelegate()) {
876 $code .= " *";
877 }
878 if ($argument = $node->getArgument()) {
879 $code .= " " . $this->renderNode($argument);
880 }
881 break;
882 }
883 if ($addSemicolon) {
884 $code .= ";";
885 }
886 if ($this->renderOpts->com) {
887 $code .= $this->renderComments($node, false);
888 }
889 return $code;
890 }
891
892 /**
893 * Renders a node as a block statement
894 *
895 * @param Syntax\Node\Node $parent Parent node
896 * @param Syntax\Node\Node|array $node Node or array of
897 * nodes to render
898 * @param bool $forceBrackets Overrides brackets
899 * inserting rules
900 * @param bool $mandatorySeparator True if a starting
901 * separator is
902 * mandatory
903 * @param bool $addSemicolons Semicolons are
904 * inserted automatically
905 * if this parameter is
906 * not false
907 * @param bool $incIndent If false indentation
908 * level won't be
909 * incremented
910 *
911 * @return string
912 */
913 protected function renderStatementBlock(
914 $parent, $node, $forceBrackets = null, $mandatorySeparator = false,
915 $addSemicolons = true, $incIndent = true
916 ) {
917 $code = "";
918
919 //If node is an array with only one element, handle it as a single node
920 if (is_array($node) && count($node) === 1) {
921 $node = $node[0];
922 }
923
924 //Special handling of BlockStatement and ClassBody nodes by rendering
925 //their child nodes
926 $origNode = null;
927 if (!is_array($node) &&
928 in_array($node->getType(), array("BlockStatement", "ClassBody"))) {
929 $origNode = $node;
930 $node = $node->getBody();
931 }
932
933 //If $forceBrackets is not null use its value to override curly brackets
934 //insertion rules
935 if ($forceBrackets !== null) {
936 $hasBrackets = $forceBrackets;
937 } else {
938 //Insert curly brackets if needed
939 $hasBrackets = $this->needsBrackets($parent, $node);
940 }
941 $currentIndentation = $this->getIndentation();
942
943 //If the node must be wrapped in curly braces a separator defined by formatter
944 //must be inserted
945 if ($hasBrackets) {
946 if ($this->renderOpts->nlbc) {
947 $code .= $this->renderOpts->nl . $currentIndentation;
948 } else {
949 $code .= $this->renderOpts->sao;
950 }
951 }
952 //Move the content of the SwitchCase content to a new line if brackets won't
953 //be inserted, in this way it's not rendered on the same line of the "case"
954 elseif ($parent->getType() === "SwitchCase") {
955 $code .= $this->renderOpts->nl;
956 }
957
958 $emptyBody = is_array($node) && !count($node);
959
960 if ($this->renderOpts->com && $origNode) {
961 $code .= $this->renderComments($origNode, true, !$emptyBody);
962 }
963
964 //Insert open curly bracket if required
965 if ($hasBrackets) {
966 $code .= "{" . $this->renderOpts->nl;
967 } elseif ($mandatorySeparator) {
968 //If bracket is not inserted but a separator is still required
969 //a space is added
970 $code .= " ";
971 }
972
973 //Increase indentation level
974 if ($incIndent) {
975 $this->renderOpts->indLevel++;
976 }
977 $subIndentation = $this->getIndentation();
978
979 //Render the node or the array of nodes
980 if (is_array($node)) {
981 if (!$emptyBody) {
982 $code .= $subIndentation .
983 $this->joinNodes(
984 $node,
985 $this->renderOpts->nl . $subIndentation,
986 $addSemicolons
987 );
988 }
989 } else {
990 $code .= $subIndentation . $this->renderNode(
991 $node,
992 $addSemicolons && $this->requiresSemicolon($node)
993 );
994 }
995
996 if ($this->renderOpts->com) {
997 //Strip last new line and indentations added by comments rendering
998 if (!$emptyBody) {
999 $code = $this->trimEmptyLine($code);
1000 }
1001 if ($origNode) {
1002 $code .= $this->renderComments($origNode, false, !$emptyBody);
1003 if (!$emptyBody) {
1004 $code = $this->trimEmptyLine($code);
1005 }
1006 }
1007 }
1008
1009 //Reset the indentation level
1010 if ($incIndent) {
1011 $this->renderOpts->indLevel--;
1012 }
1013
1014 //Insert closing curly bracket if required
1015 if ($hasBrackets) {
1016 //Add a new line if something was rendered
1017 if (!$emptyBody) {
1018 $code .= $this->renderOpts->nl;
1019 }
1020 $code .= $currentIndentation . "}";
1021 }
1022
1023 return $code;
1024 }
1025
1026 /**
1027 * Joins an array of nodes with the given separator
1028 *
1029 * @param array $nodes Nodes
1030 * @param string $separator Separator
1031 * @param bool $addSemicolons True to add semicolons after each node
1032 *
1033 * @return string
1034 */
1035 protected function joinNodes($nodes, $separator, $addSemicolons=false)
1036 {
1037 $parts = array();
1038 foreach ($nodes as $node) {
1039 if (!$node) {
1040 $code = "";
1041 } else {
1042 $code = $this->renderNode(
1043 $node,
1044 $addSemicolons && $this->requiresSemicolon($node)
1045 );
1046 }
1047 $parts[] = $code;
1048 }
1049 return implode($separator, $parts);
1050 }
1051
1052 /**
1053 * Check if the node or the array of nodes need brackets to be rendered
1054 *
1055 * @param Syntax\Node\Node $parent Parent node
1056 * @param Syntax\Node\Node|array $node Node or array of
1057 * nodes to render
1058 *
1059 * @return bool
1060 */
1061 protected function needsBrackets($parent, $node)
1062 {
1063 $parentType = $parent->getType();
1064 //The SwitchCase content needs brackets if it contains let or const declarations
1065 $inSwitchCase = $parentType === "SwitchCase";
1066 //Except for SwitchCase, brackets are needed if the formatter requires them or whenever
1067 //there are 0 or multiple nodes to render
1068 if (!$inSwitchCase && ($this->renderOpts->awb || (is_array($node) && count($node) !== 1))) {
1069 return true;
1070 }
1071 if (!is_array($node)) {
1072 $node = array($node);
1073 }
1074 $addBrackets = false;
1075 $optBracketNodes = array(
1076 "DoWhileStatement", "ForInStatement", "ForOfStatement",
1077 "ForStatement", "WhileStatement", "WithStatement"
1078 );
1079 //An IfStatement requires brackets if it contains let or const declarations and if it has the "else" part
1080 //and contains another IfStatement with "else"
1081 $inIfWithElse = $parentType === "IfStatement" && $parent->getAlternate();
1082 $checkFn = function ($n) use ($inIfWithElse, $optBracketNodes, &$addBrackets) {
1083 $type = $n->getType();
1084 if ($inIfWithElse && $type === "IfStatement") {
1085 if (!$n->getAlternate()) {
1086 $addBrackets = true;
1087 }
1088 return Traverser::DONT_TRAVERSE_CHILD_NODES;
1089 } elseif ($type === "BlockStatement") {
1090 if (count($n->getBody()) !== 1) {
1091 return Traverser::DONT_TRAVERSE_CHILD_NODES;
1092 }
1093 } elseif ($inIfWithElse && $type === "LabeledStatement") {
1094 if ($n->getBody()->getType() === "BlockStatement") {
1095 $addBrackets = true;
1096 }
1097 return Traverser::DONT_TRAVERSE_CHILD_NODES;
1098 } elseif ($type === "VariableDeclaration") {
1099 if (in_array($n->getKind(), array($n::KIND_LET, $n::KIND_CONST))) {
1100 $addBrackets = true;
1101 }
1102 return Traverser::DONT_TRAVERSE_CHILD_NODES;
1103 } elseif (!in_array($type, $optBracketNodes)) {
1104 return Traverser::DONT_TRAVERSE_CHILD_NODES;
1105 }
1106 };
1107 //Traverse every node but stop whenever the $addBrackets variable becomes true
1108 foreach ($node as $n) {
1109 $n->traverse($checkFn);
1110 if ($addBrackets) {
1111 break;
1112 }
1113 }
1114 return $addBrackets;
1115 }
1116
1117 /**
1118 * Render node's comments
1119 *
1120 * @param Syntax\Node\Node $node Node
1121 * @param bool $leading False to render trailing comments
1122 * @param bool|null $blockContent This paramater can have 3 values:
1123 * - null: the node is not a block
1124 * - false: the node is an empty block
1125 * - true: the node is a block with content
1126 *
1127 * @return string
1128 */
1129 protected function renderComments($node, $leading = true, $blockContent = null)
1130 {
1131 $code = "";
1132 $fn = $leading ? "getLeadingComments" : "getTrailingComments";
1133 $comments = $node ? $node->$fn() : array();
1134 $numComments = count($comments);
1135 if ($numComments) {
1136 $lastFormatted = $blockContent === false ? true : $leading;
1137 $refNode = $node;
1138 $refKey = $leading ? "end" : "start";
1139 $refNodeKey = $leading ? "start" : "end";
1140 $indent = $this->getIndentation();
1141 foreach ($comments as $k => $comment) {
1142 $lastComment = $k === $numComments - 1;
1143 $isMultilineComment = $comment->getKind() === Comment::KIND_MULTILINE;
1144 // Check if the comment must be formatted with new line and indentations
1145 $format = true;
1146 if (
1147 $refNode && $isMultilineComment &&
1148 $comment->location && $refNode->location &&
1149 $comment->location->$refKey->getLine() === $refNode->location->$refNodeKey->getLine()
1150 ) {
1151 $format = false;
1152 }
1153 //If the last comment wasn't formatted but this one must be formatted, add the new
1154 //line and the indentation
1155 if ($format && !$lastFormatted) {
1156 $code .= $this->renderOpts->nl . $indent;
1157 }
1158 //Leading comments on empty blocks must render the initial indentation if format
1159 //is enabled
1160 if ($format && $blockContent === false && !$k) {
1161 $code .= $indent;
1162 }
1163
1164 $commentRaw = $comment->getRawText();
1165
1166 //Reindent multiline comments if necessary
1167 if ($isMultilineComment && $indent && $this->renderOpts->rci) {
1168 $commentRaw = preg_replace("/^\s+\*/m", $indent . " *", $commentRaw);
1169 }
1170
1171 $code .= $commentRaw;
1172
1173 //If format is enabled, add the new line character and the indentation if the node
1174 //is not an empty block or the it's not the last comment
1175 if ($format && ($blockContent !== true || !$lastComment || !$isMultilineComment)) {
1176 //For non multiline comments the new line is mandatory, even if the formatter
1177 //disables it
1178 $code .= !$isMultilineComment && !$this->renderOpts->nl ? "\n" : $this->renderOpts->nl;
1179 //Last comment on blocks must not render indentation
1180 if ($blockContent === null || !$lastComment) {
1181 $code .= $indent;
1182 }
1183 }
1184 $refNode = $comment;
1185 $lastFormatted = $format;
1186 }
1187 }
1188 return $code;
1189 }
1190
1191 /**
1192 * Render import attributes of the given node
1193 *
1194 * @param Syntax\Node\Node $node Node
1195 *
1196 * @return string
1197 */
1198 protected function renderImportAttributes($node)
1199 {
1200 $code = "";
1201 if (count($node->getAttributes())) {
1202 $code .= " with" .
1203 $this->renderOpts->sao .
1204 "{" .
1205 $this->joinNodes(
1206 $node->getAttributes(),
1207 "," . $this->renderOpts->sao
1208 ) .
1209 "}";
1210 }
1211 return $code;
1212 }
1213
1214 /**
1215 * Removes an empty line at the end of the given code, if present
1216 *
1217 * @param string $code Code
1218 *
1219 * @return string
1220 */
1221 protected function trimEmptyLine($code)
1222 {
1223 if ($this->renderOpts->nl) {
1224 $nl = preg_quote($this->renderOpts->nl, "/");
1225 $indent = preg_quote($this->getIndentation(), "/");
1226 $code = preg_replace("/$nl(?:$indent)?$/", "", $code);
1227 }
1228 return $code;
1229 }
1230
1231 /**
1232 * Check if the given node requires semicolons insertion
1233 *
1234 * @param Syntax\Node\Node $node Node
1235 *
1236 * @return bool
1237 */
1238 protected function requiresSemicolon($node)
1239 {
1240 return !in_array($node->getType(), $this->noSemicolon);
1241 }
1242
1243 /**
1244 * Returns the current indentation string
1245 *
1246 * @return string
1247 */
1248 protected function getIndentation()
1249 {
1250 return str_repeat(
1251 $this->renderOpts->ind,
1252 $this->renderOpts->indLevel
1253 );
1254 }
1255 }