Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qqmldomreformatter.cpp
Go to the documentation of this file.
1// Copyright (C) 2021 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3
6
7#include <QtQml/private/qqmljsast_p.h>
8#include <QtQml/private/qqmljsastvisitor_p.h>
9#include <QtQml/private/qqmljsengine_p.h>
10#include <QtQml/private/qqmljslexer_p.h>
11
12#include <QString>
13#include <algorithm>
14
15QT_BEGIN_NAMESPACE
16namespace QQmlJS {
17namespace Dom {
18
19using namespace AST;
20
21bool ScriptFormatter::preVisit(Node *n)
22{
23 const CommentedElement *c = comments->commentForNode(n, CommentAnchor{});
24 if (!c)
25 return true;
26
27 if (!c->preComments().empty()) {
28 deferredSpaces = 0;
29 for (const auto &preComment : c->preComments())
30 lw.maybeWriteComment(preComment);
31 }
32
33 postOps[n].append([c, this]() {
34 if (!c->postComments().empty()) {
35 deferredSpaces = 0;
36 for (const auto &postComment : c->postComments())
37 lw.maybeWriteComment(postComment);
38 }
39 });
40 return true;
41}
42
43void ScriptFormatter::postVisit(Node *n)
44{
45 for (auto &op : postOps[n]) {
46 op();
47 }
48 postOps.remove(n);
49}
50
51void ScriptFormatter::lnAcceptIndented(Node *node)
52{
53 int indent = lw.increaseIndent(1);
54 ensureNewline();
55 accept(node);
56 lw.decreaseIndent(1, indent);
57}
58
59bool ScriptFormatter::acceptBlockOrIndented(Node *ast, bool finishWithSpaceOrNewline)
60{
61 if (auto *es = cast<EmptyStatement *>(ast)) {
62 writeOutSemicolon(es);
63 return false;
64 }
65 if (cast<Block *>(ast)) {
66 ensureSpaceIfNoComment();
67 accept(ast);
68 if (finishWithSpaceOrNewline)
69 ensureSpaceIfNoComment();
70 return true;
71 } else {
72 if (finishWithSpaceOrNewline)
73 postOps[ast].append([this]() { ensureNewline(); });
74 lnAcceptIndented(ast);
75 return false;
76 }
77}
78
79bool ScriptFormatter::visit(ThisExpression *ast)
80{
81 out(ast->thisToken);
82 return true;
83}
84
85bool ScriptFormatter::visit(NullExpression *ast)
86{
87 out(ast->nullToken);
88 return true;
89}
90bool ScriptFormatter::visit(TrueLiteral *ast)
91{
92 out(ast->trueToken);
93 return true;
94}
95bool ScriptFormatter::visit(FalseLiteral *ast)
96{
97 out(ast->falseToken);
98 return true;
99}
100
101bool ScriptFormatter::visit(IdentifierExpression *ast)
102{
103 out(ast->identifierToken);
104 return true;
105}
106bool ScriptFormatter::visit(StringLiteral *ast)
107{
108 // correctly handle multiline literals
109 if (ast->literalToken.length == 0)
110 return true;
111 QStringView str = m_script->loc2Str(ast->literalToken);
112 if (lw.indentNextlines && str.contains(QLatin1Char('\n'))) {
113 out(str.mid(0, 1));
114 lw.indentNextlines = false;
115 out(str.mid(1));
116 lw.indentNextlines = true;
117 } else {
118 out(str);
119 }
120 return true;
121}
122bool ScriptFormatter::visit(NumericLiteral *ast)
123{
124 outWithComments(ast->literalToken, ast);
125 return true;
126}
127bool ScriptFormatter::visit(RegExpLiteral *ast)
128{
129 out(ast->literalToken);
130 return true;
131}
132
133bool ScriptFormatter::visit(ArrayPattern *ast)
134{
135 outWithComments(ast->lbracketToken, ast);
136 int baseIndent = lw.increaseIndent(1);
137 if (ast->elements) {
138 accept(ast->elements);
139 outWithComments(ast->commaToken, ast);
140 auto lastElement = lastListElement(ast->elements);
141 if (lastElement->element && cast<ObjectPattern *>(lastElement->element->initializer)) {
142 ensureNewline();
143 }
144 } else {
145 outWithComments(ast->commaToken, ast);
146 }
147 lw.decreaseIndent(1, baseIndent);
148 outWithComments(ast->rbracketToken, ast);
149 return false;
150}
151
152bool ScriptFormatter::visit(ObjectPattern *ast)
153{
154 outWithComments(ast->lbraceToken, ast);
155 ++expressionDepth;
156 if (ast->properties) {
157 lnAcceptIndented(ast->properties);
158 ensureNewline();
159 }
160 --expressionDepth;
161 outWithComments(ast->rbraceToken, ast);
162 return false;
163}
164
165bool ScriptFormatter::visit(PatternElementList *ast)
166{
167 for (PatternElementList *it = ast; it; it = it->next) {
168 const bool isObjectInitializer =
169 it->element && cast<ObjectPattern *>(it->element->initializer);
170 if (isObjectInitializer)
171 ensureNewline();
172
173 if (it->elision) {
174 accept(it->elision);
175 if (it->element)
176 ensureSpaceIfNoComment();
177 }
178 if (it->element)
179 accept(it->element);
180 if (it->next) {
181 outWithComments(it->next->commaToken, it);
182 ensureSpaceIfNoComment();
183 if (isObjectInitializer)
184 ensureNewline();
185 }
186 }
187 return false;
188}
189
190bool ScriptFormatter::visit(PatternPropertyList *ast)
191{
192 for (PatternPropertyList *it = ast; it; it = it->next) {
193 accept(it->property);
194 if (it->next) {
195 out(",");
196 ensureNewline();
197 }
198 }
199 return false;
200}
201
202// https://262.ecma-international.org/7.0/#prod-PropertyDefinition
203bool ScriptFormatter::visit(AST::PatternProperty *property)
204{
205 if (property->type == PatternElement::Getter || property->type == PatternElement::Setter
206 || property->type == PatternElement::Method) {
207 // note that MethodDefinitions and FunctionDeclarations have different syntax
208 // https://262.ecma-international.org/7.0/#prod-MethodDefinition
209 // https://262.ecma-international.org/7.0/#prod-FunctionDeclaration
210 // hence visit(FunctionDeclaration*) is not quite appropriate here
211 if (property->type == PatternProperty::Getter) {
212 out("get");
213 ensureSpaceIfNoComment();
214 } else if (property->type == PatternProperty::Setter) {
215 out("set");
216 ensureSpaceIfNoComment();
217 }
218 FunctionExpression *f = AST::cast<FunctionExpression *>(property->initializer);
219 if (f->isGenerator) {
220 out("*");
221 }
222 accept(property->name);
223 out(f->lparenToken);
224 accept(f->formals);
225 out(f->rparenToken);
226 ensureSpaceIfNoComment();
227 out(f->lbraceToken);
228 const bool scoped = f->lbraceToken.isValid();
229 if (scoped)
230 ++expressionDepth;
231 if (f->body) {
232 if (f->body->next || scoped) {
233 lnAcceptIndented(f->body);
234 lw.newline();
235 } else {
236 auto baseIndent = lw.increaseIndent(1);
237 accept(f->body);
238 lw.decreaseIndent(1, baseIndent);
239 }
240 }
241 if (scoped)
242 --expressionDepth;
243 out(f->rbraceToken);
244 return false;
245 }
246
247 // IdentifierReference[?Yield]
248 accept(property->name);
249 bool useInitializer = false;
250 const bool bindingIdentifierExist = !property->bindingIdentifier.isEmpty();
251 if (property->colonToken.isValid()) {
252 // PropertyName[?Yield] : AssignmentExpression[In, ?Yield]
253 out(":");
254 ensureSpaceIfNoComment();
255 useInitializer = true;
256 if (bindingIdentifierExist)
257 out(property->bindingIdentifier);
258 if (property->bindingTarget)
259 accept(property->bindingTarget);
260 }
261
262 if (property->initializer) {
263 // CoverInitializedName[?Yield]
264 if (bindingIdentifierExist) {
265 ensureSpaceIfNoComment();
266 out("=");
267 ensureSpaceIfNoComment();
268 useInitializer = true;
269 }
270 if (useInitializer)
271 accept(property->initializer);
272 }
273 return false;
274}
275
276bool ScriptFormatter::visit(NestedExpression *ast)
277{
278 out(ast->lparenToken);
279 int baseIndent = lw.increaseIndent(1);
280 accept(ast->expression);
281 lw.decreaseIndent(1, baseIndent);
282 out(ast->rparenToken);
283 return false;
284}
285
286bool ScriptFormatter::visit(IdentifierPropertyName *ast)
287{
288 out(ast->id.toString());
289 return true;
290}
291bool ScriptFormatter::visit(StringLiteralPropertyName *ast)
292{
293 out(ast->propertyNameToken);
294 return true;
295}
296bool ScriptFormatter::visit(NumericLiteralPropertyName *ast)
297{
298 out(QString::number(ast->id));
299 return true;
300}
301
302bool ScriptFormatter::visit(TemplateLiteral *ast)
303{
304 // correctly handle multiline literals
305 if (ast->literalToken.length != 0) {
306 QStringView str = m_script->loc2Str(ast->literalToken);
307 if (lw.indentNextlines && str.contains(QLatin1Char('\n'))) {
308 out(str.mid(0, 1));
309 lw.indentNextlines = false;
310 out(str.mid(1));
311 lw.indentNextlines = true;
312 } else {
313 out(str);
314 }
315 }
316 return true;
317}
318
319bool ScriptFormatter::visit(ArrayMemberExpression *ast)
320{
321 accept(ast->base);
322 out(ast->optionalToken);
323 out(ast->lbracketToken);
324 int indent = lw.increaseIndent(1);
325 accept(ast->expression);
326 lw.decreaseIndent(1, indent);
327 out(ast->rbracketToken);
328 return false;
329}
330
331bool ScriptFormatter::visit(FieldMemberExpression *ast)
332{
333 accept(ast->base);
334 out(ast->dotToken);
335 out(ast->identifierToken);
336 return false;
337}
338
339bool ScriptFormatter::visit(NewMemberExpression *ast)
340{
341 out("new"); // ast->newToken
342 ensureSpaceIfNoComment();
343 accept(ast->base);
344 out(ast->lparenToken);
345 accept(ast->arguments);
346 out(ast->rparenToken);
347 return false;
348}
349
350bool ScriptFormatter::visit(NewExpression *ast)
351{
352 out("new"); // ast->newToken
353 ensureSpaceIfNoComment();
354 accept(ast->expression);
355 return false;
356}
357
358bool ScriptFormatter::visit(CallExpression *ast)
359{
360 accept(ast->base);
361 outWithComments(ast->optionalToken, ast);
362 outWithComments(ast->lparenToken, ast);
363 accept(ast->arguments);
364 outWithComments(ast->rparenToken, ast);
365 return false;
366}
367
368bool ScriptFormatter::visit(PostIncrementExpression *ast)
369{
370 accept(ast->base);
371 out(ast->incrementToken);
372 return false;
373}
374
375bool ScriptFormatter::visit(PostDecrementExpression *ast)
376{
377 accept(ast->base);
378 out(ast->decrementToken);
379 return false;
380}
381
382bool ScriptFormatter::visit(PreIncrementExpression *ast)
383{
384 out(ast->incrementToken);
385 accept(ast->expression);
386 return false;
387}
388
389bool ScriptFormatter::visit(PreDecrementExpression *ast)
390{
391 out(ast->decrementToken);
392 accept(ast->expression);
393 return false;
394}
395
396bool ScriptFormatter::visit(DeleteExpression *ast)
397{
398 out("delete"); // ast->deleteToken
399 ensureSpaceIfNoComment();
400 accept(ast->expression);
401 return false;
402}
403
404bool ScriptFormatter::visit(VoidExpression *ast)
405{
406 out("void"); // ast->voidToken
407 ensureSpaceIfNoComment();
408 accept(ast->expression);
409 return false;
410}
411
412bool ScriptFormatter::visit(TypeOfExpression *ast)
413{
414 out("typeof"); // ast->typeofToken
415 ensureSpaceIfNoComment();
416 accept(ast->expression);
417 return false;
418}
419
420bool ScriptFormatter::visit(UnaryPlusExpression *ast)
421{
422 out(ast->plusToken);
423 accept(ast->expression);
424 return false;
425}
426
427bool ScriptFormatter::visit(UnaryMinusExpression *ast)
428{
429 out(ast->minusToken);
430 accept(ast->expression);
431 return false;
432}
433
434bool ScriptFormatter::visit(TildeExpression *ast)
435{
436 out(ast->tildeToken);
437 accept(ast->expression);
438 return false;
439}
440
441bool ScriptFormatter::visit(NotExpression *ast)
442{
443 out(ast->notToken);
444 accept(ast->expression);
445 return false;
446}
447
448bool ScriptFormatter::visit(BinaryExpression *ast)
449{
450 accept(ast->left);
451 ensureSpaceIfNoComment();
452 out(ast->operatorToken);
453 ensureSpaceIfNoComment();
454 accept(ast->right);
455 return false;
456}
457
458bool ScriptFormatter::visit(ConditionalExpression *ast)
459{
460 accept(ast->expression);
461 ensureSpaceIfNoComment();
462 out("?"); // ast->questionToken
463 ensureSpaceIfNoComment();
464 accept(ast->ok);
465 ensureSpaceIfNoComment();
466 out(":"); // ast->colonToken
467 ensureSpaceIfNoComment();
468 accept(ast->ko);
469 return false;
470}
471
472bool ScriptFormatter::visit(Block *ast)
473{
474 // write comments manually because we need to indent before writing a potential post comment
475 const CommentedElement *c =
476 comments->commentForNode(ast, CommentAnchor::from(ast->lbraceToken));
477 if (c)
478 writePreComment(c);
479 out(ast->lbraceToken);
480 const int indent = lw.increaseIndent();
481 if (c)
482 writePostComment(c);
483
484 if (ast->statements) {
485 ++expressionDepth;
486 ensureNewline();
487 accept(ast->statements);
488 ensureNewline();
489 --expressionDepth;
490 }
491
492 // write comments manually because we need to write a potential pre-comment before decreasing
493 // the indentation
494 c = comments->commentForNode(ast, CommentAnchor::from(ast->rbraceToken));
495 if (c)
496 writePreComment(c);
497 lw.decreaseIndent(1, indent);
498 out(ast->rbraceToken);
499 if (c)
500 writePostComment(c);
501 return false;
502}
503
504bool ScriptFormatter::visit(VariableStatement *ast)
505{
506 out(ast->declarationKindToken);
507 ensureSpaceIfNoComment();
508 accept(ast->declarations);
509 if (addSemicolons())
510 writeOutSemicolon(ast);
511 return false;
512}
513
514bool ScriptFormatter::visit(PatternElement *ast)
515{
516 switch (ast->type) {
517 case PatternElement::Literal:
518 case PatternElement::Method:
519 case PatternElement::Binding:
520 break;
521 case PatternElement::Getter:
522 out("get");
523 ensureSpaceIfNoComment();
524 break;
525 case PatternElement::Setter:
526 out("set");
527 ensureSpaceIfNoComment();
528 break;
529 case PatternElement::SpreadElement:
530 out("...");
531 break;
532 }
533
534 accept(ast->bindingTarget);
535 if (!ast->destructuringPattern())
536 out(ast->identifierToken);
537 if (ast->initializer) {
538 if (ast->isVariableDeclaration() || ast->type == AST::PatternElement::Binding) {
539 ensureSpaceIfNoComment();
540 outWithComments(ast->equalToken, ast);
541 ensureSpaceIfNoComment();
542 }
543 accept(ast->initializer);
544 }
545 accept(ast->typeAnnotation);
546 return false;
547}
548
549bool ScriptFormatter::visit(TypeAnnotation *ast)
550{
551 out(ast->colonToken);
552 ensureSpaceIfNoComment();
553 accept(ast->type);
554 return false;
555}
556
557bool ScriptFormatter::visit(Type *ast)
558{
559 accept(ast->typeId);
560 if (ast->typeArgument) {
561 outWithComments(ast->lAngleBracketToken, ast);
562 accept(ast->typeArgument);
563 outWithComments(ast->rAngleBracketToken, ast);
564 }
565 return false;
566}
567
568bool ScriptFormatter::visit(UiQualifiedId *ast)
569{
570 for (UiQualifiedId *it = ast; it; it = it->next) {
571 outWithComments(it->dotToken, it);
572 outWithComments(it->identifierToken, it);
573 }
574 return false;
575}
576
577bool ScriptFormatter::visit(EmptyStatement *)
578{
579 lw.lineWriter.ensureSemicolon();
580 return false;
581}
582
583bool ScriptFormatter::visit(IfStatement *ast)
584{
585 out(ast->ifToken);
586 ensureSpaceIfNoComment();
587 out(ast->lparenToken);
588 preVisit(ast->expression);
589 ast->expression->accept0(this);
590 out(ast->rparenToken);
591 postVisit(ast->expression);
592 acceptBlockOrIndented(ast->ok, ast->ko);
593 if (ast->ko) {
594 out(ast->elseToken);
595 if (cast<Block *>(ast->ko) || cast<IfStatement *>(ast->ko)) {
596 ensureSpaceIfNoComment();
597 accept(ast->ko);
598 } else {
599 lnAcceptIndented(ast->ko);
600 }
601 }
602 return false;
603}
604
605bool ScriptFormatter::visit(DoWhileStatement *ast)
606{
607 out(ast->doToken);
608 acceptBlockOrIndented(ast->statement, true);
609 out(ast->whileToken);
610 ensureSpaceIfNoComment();
611 outWithComments(ast->lparenToken, ast);
612 accept(ast->expression);
613 outWithComments(ast->rparenToken, ast);
614 return false;
615}
616
617bool ScriptFormatter::visit(WhileStatement *ast)
618{
619 out(ast->whileToken);
620 ensureSpaceIfNoComment();
621 outWithComments(ast->lparenToken, ast);
622 accept(ast->expression);
623 outWithComments(ast->rparenToken, ast);
624 acceptBlockOrIndented(ast->statement);
625 return false;
626}
627
628bool ScriptFormatter::visit(ForStatement *ast)
629{
630 out(ast->forToken);
631 ensureSpaceIfNoComment();
632 outWithComments(ast->lparenToken, ast);
633 if (ast->initialiser) {
634 accept(ast->initialiser);
635 } else if (ast->declarations) {
636 if (auto pe = ast->declarations->declaration) {
637 out(pe->declarationKindToken);
638 ensureSpaceIfNoComment();
639 }
640 bool first = true;
641 for (VariableDeclarationList *it = ast->declarations; it; it = it->next) {
642 if (!std::exchange(first, false)) {
643 out(",");
644 ensureSpaceIfNoComment();
645 }
646 accept(it->declaration);
647 }
648 }
649 // We don't use writeOutSemicolon() here because we need a semicolon unconditionally.
650 // Repeats for the second semicolon token below.
651 out(u";"); // ast->firstSemicolonToken
652 ensureSpaceIfNoComment();
653 accept(ast->condition);
654 out(u";"); // ast->secondSemicolonToken
655 ensureSpaceIfNoComment();
656 accept(ast->expression);
657 outWithComments(ast->rparenToken, ast);
658 acceptBlockOrIndented(ast->statement);
659 return false;
660}
661
662bool ScriptFormatter::visit(ForEachStatement *ast)
663{
664 out(ast->forToken);
665 ensureSpaceIfNoComment();
666 out(ast->lparenToken);
667 if (auto pe = AST::cast<PatternElement *>(ast->lhs)) {
668 out(pe->declarationKindToken);
669 ensureSpaceIfNoComment();
670 }
671 accept(ast->lhs);
672 ensureSpaceIfNoComment();
673 out(ast->inOfToken);
674 ensureSpaceIfNoComment();
675 accept(ast->expression);
676 out(ast->rparenToken);
677 acceptBlockOrIndented(ast->statement);
678 return false;
679}
680
681bool ScriptFormatter::visit(ContinueStatement *ast)
682{
683 out(ast->continueToken);
684 if (!ast->label.isNull()) {
685 ensureSpaceIfNoComment();
686 out(ast->identifierToken);
687 }
688 if (addSemicolons())
689 writeOutSemicolon(ast);
690 return false;
691}
692
693bool ScriptFormatter::visit(BreakStatement *ast)
694{
695 out(ast->breakToken);
696 if (!ast->label.isNull()) {
697 ensureSpaceIfNoComment();
698 out(ast->identifierToken);
699 }
700 if (addSemicolons())
701 writeOutSemicolon(ast);
702 return false;
703}
704
705bool ScriptFormatter::visit(ReturnStatement *ast)
706{
707 out(ast->returnToken);
708 if (ast->expression) {
709 if (ast->returnToken.length != 0)
710 ensureSpaceIfNoComment();
711 accept(ast->expression);
712 }
713 if (ast->returnToken.length > 0 && addSemicolons())
714 writeOutSemicolon(ast);
715 return false;
716}
717
718bool ScriptFormatter::visit(YieldExpression *ast)
719{
720 out(ast->yieldToken);
721 if (ast->isYieldStar)
722 out("*");
723 if (ast->expression) {
724 if (ast->yieldToken.isValid())
725 ensureSpaceIfNoComment();
726 accept(ast->expression);
727 }
728 return false;
729}
730
731bool ScriptFormatter::visit(ThrowStatement *ast)
732{
733 out(ast->throwToken);
734 if (ast->expression) {
735 ensureSpaceIfNoComment();
736 accept(ast->expression);
737 }
738 if (addSemicolons())
739 writeOutSemicolon(ast);
740 return false;
741}
742
743bool ScriptFormatter::visit(WithStatement *ast)
744{
745 out(ast->withToken);
746 ensureSpaceIfNoComment();
747 out(ast->lparenToken);
748 accept(ast->expression);
749 out(ast->rparenToken);
750 acceptBlockOrIndented(ast->statement);
751 return false;
752}
753
754bool ScriptFormatter::visit(SwitchStatement *ast)
755{
756 out(ast->switchToken);
757 ensureSpaceIfNoComment();
758 out(ast->lparenToken);
759 accept(ast->expression);
760 out(ast->rparenToken);
761 ensureSpaceIfNoComment();
762 accept(ast->block);
763 return false;
764}
765
766bool ScriptFormatter::visit(CaseBlock *ast)
767{
768 out(ast->lbraceToken);
769 ++expressionDepth;
770 ensureNewline();
771 accept(ast->clauses);
772 if (ast->clauses && ast->defaultClause)
773 ensureNewline();
774 accept(ast->defaultClause);
775 if (ast->moreClauses)
776 ensureNewline();
777 accept(ast->moreClauses);
778 ensureNewline();
779 --expressionDepth;
780 out(ast->rbraceToken);
781 return false;
782}
783
784bool ScriptFormatter::visit(CaseClause *ast)
785{
786 out("case"); // ast->caseToken
787 ensureSpaceIfNoComment();
788 accept(ast->expression);
789 outWithComments(ast->colonToken, ast);
790 if (ast->statements)
791 lnAcceptIndented(ast->statements);
792 return false;
793}
794
795bool ScriptFormatter::visit(DefaultClause *ast)
796{
797 out(ast->defaultToken);
798 out(ast->colonToken);
799 lnAcceptIndented(ast->statements);
800 return false;
801}
802
803bool ScriptFormatter::visit(LabelledStatement *ast)
804{
805 out(ast->identifierToken);
806 out(":"); // ast->colonToken
807 ensureSpaceIfNoComment();
808 accept(ast->statement);
809 return false;
810}
811
812bool ScriptFormatter::visit(TryStatement *ast)
813{
814 outWithComments(ast->tryToken, ast);
815 ensureSpaceIfNoComment();
816 accept(ast->statement);
817 if (ast->catchExpression) {
818 ensureSpaceIfNoComment();
819 accept(ast->catchExpression);
820 }
821 if (ast->finallyExpression) {
822 ensureSpaceIfNoComment();
823 accept(ast->finallyExpression);
824 }
825 return false;
826}
827
828bool ScriptFormatter::visit(Catch *ast)
829{
830 outWithComments(ast->catchToken, ast);
831 ensureSpaceIfNoComment();
832 outWithComments(ast->lparenToken, ast);
833 outWithComments(ast->identifierToken, ast);
834 outWithComments(ast->rparenToken, ast);
835 ensureSpaceIfNoComment();
836 accept(ast->statement);
837 return false;
838}
839
840bool ScriptFormatter::visit(Finally *ast)
841{
842 outWithComments(ast->finallyToken, ast);
843 ensureSpaceIfNoComment();
844 accept(ast->statement);
845 return false;
846}
847
848bool ScriptFormatter::visit(FunctionDeclaration *ast)
849{
850 return ScriptFormatter::visit(static_cast<FunctionExpression *>(ast));
851}
852
853bool ScriptFormatter::visit(FunctionExpression *ast)
854{
855 if (!ast->isArrowFunction) {
856 outWithComments(ast->functionToken, ast);
857 if (ast->isGenerator)
858 outWithComments(ast->starToken, ast);
859 ensureSpaceIfNoComment();
860 outWithComments(ast->identifierToken, ast);
861 }
862
863 const bool removeParentheses = ast->isArrowFunction && ast->formals && !ast->formals->next
864 && (ast->formals->element && !ast->formals->element->bindingTarget);
865
866 // note: qmlformat removes the parentheses for "(x) => x". In that case, we still need
867 // to print potential comments attached to `(` or `)` via `OnlyComments` option.
868 outWithComments(ast->lparenToken, ast, removeParentheses ? OnlyComments : TokenAndComment);
869 int baseIndent = lw.increaseIndent(1);
870 accept(ast->formals);
871 lw.decreaseIndent(1, baseIndent);
872 outWithComments(ast->rparenToken, ast, removeParentheses ? OnlyComments : TokenAndComment);
873 accept(ast->typeAnnotation);
874 ensureSpaceIfNoComment();
875 if (ast->isArrowFunction) {
876 out("=>");
877 ensureSpaceIfNoComment();
878 }
879 outWithComments(ast->lbraceToken, ast);
880 if (ast->lbraceToken.length != 0)
881 ++expressionDepth;
882 if (ast->body) {
883 if (ast->body->next || ast->lbraceToken.length != 0) {
884 lnAcceptIndented(ast->body);
885 ensureNewline();
886 } else {
887 // print a single statement in one line. E.g. x => x * 2
888 baseIndent = lw.increaseIndent(1);
889 accept(ast->body);
890 lw.decreaseIndent(1, baseIndent);
891 }
892 }
893 if (ast->lbraceToken.length != 0)
894 --expressionDepth;
895 outWithComments(ast->rbraceToken, ast);
896 return false;
897}
898
899bool ScriptFormatter::visit(Elision *ast)
900{
901 for (Elision *it = ast; it; it = it->next) {
902 if (!it->commaToken.isValid())
903 continue;
904 outWithComments(it->commaToken, it);
905 if (it->next)
906 ensureSpaceIfNoComment();
907 }
908 return false;
909}
910
911bool ScriptFormatter::visit(ArgumentList *ast)
912{
913 for (ArgumentList *it = ast; it; it = it->next) {
914 if (it->commaToken.isValid()) {
915 outWithComments(it->commaToken, it);
916 ensureSpaceIfNoComment();
917 }
918 if (it->spreadToken.isValid())
919 outWithComments(it->spreadToken, it);
920 accept(it->expression);
921 }
922 return false;
923}
924
925bool ScriptFormatter::visit(StatementList *ast)
926{
927 ++expressionDepth;
928 for (StatementList *it = ast; it; it = it->next) {
929 // ### work around parser bug: skip empty statements with wrong tokens
930 if (EmptyStatement *emptyStatement = cast<EmptyStatement *>(it->statement)) {
931 if (m_script->loc2Str(emptyStatement->semicolonToken) != QLatin1String(";"))
932 continue;
933 }
934
935 accept(it->statement);
936 if (it->next) {
937 // There might be a post-comment attached to the current
938 // statement or a pre-comment attached to the next
939 // statmente or both.
940 // If any of those are present they will take care of
941 // handling the spacing between the statements so we
942 // don't need to push any newline.
943 auto *commentForCurrentStatement =
944 comments->commentForNode(it->statement, CommentAnchor{});
945 auto *commentForNextStatement =
946 comments->commentForNode(it->next->statement, CommentAnchor{});
947
948 if (
949 (commentForCurrentStatement && !commentForCurrentStatement->postComments().empty())
950 || (commentForNextStatement && !commentForNextStatement->preComments().empty())
951 ) continue;
952
953 quint32 lineDelta = it->next->firstSourceLocation().startLine
954 - it->statement->lastSourceLocation().startLine;
955 lineDelta = std::clamp(lineDelta, quint32{ 1 }, quint32{ 2 });
956
957 ensureNewline(lineDelta);
958 }
959 }
960 --expressionDepth;
961 return false;
962}
963
964bool ScriptFormatter::visit(VariableDeclarationList *ast)
965{
966 for (VariableDeclarationList *it = ast; it; it = it->next) {
967 accept(it->declaration);
968 if (it->next) {
969 out(","); // it->commaToken
970 ensureSpaceIfNoComment();
971 }
972 }
973 return false;
974}
975
976bool ScriptFormatter::visit(CaseClauses *ast)
977{
978 for (CaseClauses *it = ast; it; it = it->next) {
979 accept(it->clause);
980 if (it->next)
981 ensureNewline();
982 }
983 return false;
984}
985
986bool ScriptFormatter::visit(FormalParameterList *ast)
987{
988 for (FormalParameterList *it = ast; it; it = it->next) {
989 accept(it->element);
990 if (it->commaToken.isValid()) {
991 outWithComments(it->commaToken, it);
992 ensureSpaceIfNoComment();
993 }
994 }
995 return false;
996}
997
998// to check
999bool ScriptFormatter::visit(SuperLiteral *)
1000{
1001 out("super");
1002 return true;
1003}
1004bool ScriptFormatter::visit(ComputedPropertyName *)
1005{
1006 out("[");
1007 return true;
1008}
1009bool ScriptFormatter::visit(CommaExpression *el)
1010{
1011 accept(el->left);
1012 out(",");
1013 ensureSpaceIfNoComment();
1014 accept(el->right);
1015 return false;
1016}
1017bool ScriptFormatter::visit(ExpressionStatement *el)
1018{
1019 if (addSemicolons())
1020 postOps[el->expression].append([this, el]() { writeOutSemicolon(el); });
1021 return true;
1022}
1023
1024// Return false because we want to omit default function calls in accept0 implementation.
1025bool ScriptFormatter::visit(ClassDeclaration *ast)
1026{
1027 out(ast->classToken);
1028 ensureSpaceIfNoComment();
1029 outWithComments(ast->identifierToken, ast);
1030 if (ast->heritage) {
1031 ensureSpaceIfNoComment();
1032 out("extends");
1033 ensureSpaceIfNoComment();
1034 accept(ast->heritage);
1035 }
1036 ensureSpaceIfNoComment();
1037 outWithComments(ast->lbraceToken, ast);
1038 int baseIndent = lw.increaseIndent();
1039 for (ClassElementList *it = ast->elements; it; it = it->next) {
1040 lw.newline();
1041 if (it->isStatic) {
1042 out("static");
1043 ensureSpaceIfNoComment();
1044 }
1045 accept(it->property);
1046 lw.newline();
1047 }
1048 lw.decreaseIndent(1, baseIndent);
1049 outWithComments(ast->rbraceToken, ast);
1050 return false;
1051}
1052
1053bool ScriptFormatter::visit(AST::ImportDeclaration *ast)
1054{
1055 out(ast->importToken);
1056 ensureSpaceIfNoComment();
1057 if (!ast->moduleSpecifier.isNull()) {
1058 out(ast->moduleSpecifierToken);
1059 }
1060 return true;
1061}
1062
1063bool ScriptFormatter::visit(AST::ImportSpecifier *ast)
1064{
1065 if (!ast->identifier.isNull()) {
1066 out(ast->identifierToken);
1067 ensureSpaceIfNoComment();
1068 out("as");
1069 ensureSpaceIfNoComment();
1070 }
1071 out(ast->importedBindingToken);
1072 return true;
1073}
1074
1075bool ScriptFormatter::visit(AST::NameSpaceImport *ast)
1076{
1077 out(ast->starToken);
1078 ensureSpaceIfNoComment();
1079 out("as");
1080 ensureSpaceIfNoComment();
1081 out(ast->importedBindingToken);
1082 return true;
1083}
1084
1085bool ScriptFormatter::visit(AST::ImportsList *ast)
1086{
1087 for (ImportsList *it = ast; it; it = it->next) {
1088 accept(it->importSpecifier);
1089 if (it->next) {
1090 out(",");
1091 ensureSpaceIfNoComment();
1092 }
1093 }
1094 return false;
1095}
1096bool ScriptFormatter::visit(AST::NamedImports *ast)
1097{
1098 out(ast->leftBraceToken);
1099 if (ast->importsList) {
1100 ensureSpaceIfNoComment();
1101 }
1102 return true;
1103}
1104
1105bool ScriptFormatter::visit(AST::ImportClause *ast)
1106{
1107 if (!ast->importedDefaultBinding.isNull()) {
1108 out(ast->importedDefaultBindingToken);
1109 if (ast->nameSpaceImport || ast->namedImports) {
1110 out(",");
1111 ensureSpaceIfNoComment();
1112 }
1113 }
1114 return true;
1115}
1116
1117bool ScriptFormatter::visit(AST::ExportDeclaration *ast)
1118{
1119 out(ast->exportToken);
1120 ensureSpaceIfNoComment();
1121 if (ast->exportDefault) {
1122 out("default");
1123 ensureSpaceIfNoComment();
1124 }
1125 if (ast->exportsAll()) {
1126 out("*");
1127 }
1128 return true;
1129}
1130
1131bool ScriptFormatter::visit(AST::ExportClause *ast)
1132{
1133 out(ast->leftBraceToken);
1134 if (ast->exportsList) {
1135 ensureSpaceIfNoComment();
1136 }
1137 return true;
1138}
1139
1140bool ScriptFormatter::visit(AST::ExportSpecifier *ast)
1141{
1142 out(ast->identifier);
1143 if (ast->exportedIdentifierToken.isValid()) {
1144 ensureSpaceIfNoComment();
1145 out("as");
1146 ensureSpaceIfNoComment();
1147 out(ast->exportedIdentifier);
1148 }
1149 return true;
1150}
1151
1152bool ScriptFormatter::visit(AST::ExportsList *ast)
1153{
1154 for (ExportsList *it = ast; it; it = it->next) {
1155 accept(it->exportSpecifier);
1156 if (it->next) {
1157 out(",");
1158 ensureSpaceIfNoComment();
1159 }
1160 }
1161 return false;
1162}
1163
1164bool ScriptFormatter::visit(AST::FromClause *ast)
1165{
1166 ensureSpaceIfNoComment();
1167 out(ast->fromToken);
1168 ensureSpaceIfNoComment();
1169 out(ast->moduleSpecifierToken);
1170 return true;
1171}
1172
1173void ScriptFormatter::endVisit(ComputedPropertyName *)
1174{
1175 out("]");
1176}
1177
1178void ScriptFormatter::endVisit(AST::ExportDeclaration *ast)
1179{
1180 // add a semicolon at the end of the following expressions
1181 // export * FromClause
1182 // export ExportClause FromClause ;
1183 if (ast->fromClause) {
1184 writeOutSemicolon(ast);
1185 }
1186
1187 // add a semicolon at the end of the following expressions
1188 // export ExportClause ;
1189 if (ast->exportClause && !ast->fromClause) {
1190 writeOutSemicolon(ast);
1191 }
1192
1193 // add a semicolon at the end of the following expressions
1194 // export default [lookahead ∉ { function, class }] AssignmentExpression;
1195 if (ast->exportDefault && ast->variableStatementOrDeclaration) {
1196 // lookahead ∉ { function, class }
1197 if (!(ast->variableStatementOrDeclaration->kind == Node::Kind_FunctionDeclaration
1198 || ast->variableStatementOrDeclaration->kind == Node::Kind_ClassDeclaration)) {
1199 writeOutSemicolon(ast);
1200 }
1201 // ArrowFunction in QQmlJS::AST is handled with the help of FunctionDeclaration
1202 // and not as part of AssignmentExpression (as per ECMA
1203 // https://262.ecma-international.org/7.0/#prod-AssignmentExpression)
1204 if (ast->variableStatementOrDeclaration->kind == Node::Kind_FunctionDeclaration
1205 && static_cast<AST::FunctionDeclaration *>(ast->variableStatementOrDeclaration)
1206 ->isArrowFunction) {
1207 writeOutSemicolon(ast);
1208 }
1209 }
1210}
1211
1212void ScriptFormatter::endVisit(AST::ExportClause *ast)
1213{
1214 if (ast->exportsList) {
1215 ensureSpaceIfNoComment();
1216 }
1217 out(ast->rightBraceToken);
1218}
1219
1220void ScriptFormatter::endVisit(AST::NamedImports *ast)
1221{
1222 if (ast->importsList) {
1223 ensureSpaceIfNoComment();
1224 }
1225 out(ast->rightBraceToken);
1226}
1227
1228void ScriptFormatter::endVisit(AST::ImportDeclaration *id)
1229{
1230 writeOutSemicolon(id);
1231}
1232
1233void ScriptFormatter::throwRecursionDepthError()
1234{
1235 out("/* ERROR: Hit recursion limit ScriptFormatter::visiting AST, rewrite failed */");
1236}
1237
1238// Given an existing semicolon, can we safely remove it without changing
1239// behavior Restricted characters (, [, +, - and / are the only ones that can
1240// cause issues when removing a semicolon. The / is a special case because it
1241// can be the start of a comment or a division operator.
1242bool ScriptFormatter::canRemoveSemicolon(AST::Node *node)
1243{
1244 const auto canRelyOnASI = [this](Node *node) {
1245 auto nodeLoc = node->lastSourceLocation().offset + 1;
1246 auto code = m_script->engine()->code();
1247 auto it = code.begin() + nodeLoc;
1248 auto end = code.end();
1249 // Scan through code, skipping comments and whitespace
1250 // until we find the next real token to determine if ASI will work.
1251 while (it != end) {
1252 QChar c = *it;
1253 // Skip all whitespace and semicolons
1254 if (c.isSpace() || c == u';') {
1255 ++it;
1256 continue;
1257 }
1258 // Skip comments
1259 if (c == u'/' && it + 1 != end) {
1260 auto next = it + 1;
1261 if (*next == u'/') {
1262 // Single-line comment, skip to end of line
1263 it = std::find(next, end, u'\n');
1264 if (it != end)
1265 ++it;
1266 continue;
1267 } else if (*next == u'*') {
1268 // Multi-line comment, skip to */
1269 it = next + 1;
1270 while (it != end) {
1271 if (*it == u'*' && it + 1 != end && *(it + 1) == u'/') {
1272 it += 2;
1273 break;
1274 }
1275 ++it;
1276 }
1277 continue;
1278 }
1279 // If / is not followed by / or *, it's a division operator
1280 return false;
1281 }
1282 // Check for restricted characters that can continue the expression
1283 if (c == u'(' || c == u'[' || c == u'+' || c == u'-') {
1284 // Cannot remove semicolon; restricted char follows
1285 return false;
1286 }
1287 // Found any other token, safe to remove semicolon
1288 return true;
1289 }
1290 // Reached end of code, safe to remove semicolon
1291 return true;
1292 };
1293
1294 // Check if the node is a statement that requires a semicolon to avoid ASI issues
1295 switch (node->kind) {
1296 case AST::Node::Kind_ExpressionStatement:
1297 return canRelyOnASI(cast<ExpressionStatement *>(node));
1298 case AST::Node::Kind_VariableStatement:
1299 return canRelyOnASI(cast<VariableStatement *>(node));
1300 case AST::Node::Kind_EmptyStatement:
1301 return false;
1302 case AST::Node::Kind_ContinueStatement:
1303 case AST::Node::Kind_BreakStatement:
1304 case AST::Node::Kind_ReturnStatement:
1305 case AST::Node::Kind_ThrowStatement:
1306 case AST::Node::Kind_ExportDeclaration:
1307 case AST::Node::Kind_ImportDeclaration:
1308 case AST::Node::Kind_FromClause:
1309 case AST::Node::Kind_ExportClause:
1310 default:
1311 return true;
1312 }
1313}
1314
1315OutWriter &ScriptFormatter::writeOutSemicolon(AST::Node *node)
1316{
1317 if (!node)
1318 return lw;
1319 switch (lw.lineWriter.options().semicolonRule) {
1320 case LineWriterOptions::SemicolonRule::Essential:
1321 if (!canRemoveSemicolon(node))
1322 out(u";");
1323 ensureNewline();
1324 return lw;
1325 case LineWriterOptions::SemicolonRule::Always:
1326 out(u";");
1327 return lw;
1328 default:
1329 Q_UNREACHABLE_RETURN(lw);
1330 }
1331}
1332
1333void reformatAst(OutWriter &lw, const QQmlJS::Dom::ScriptExpression *const script)
1334{
1335 if (script)
1336 ScriptFormatter formatter(lw, script);
1337}
1338
1339} // namespace Dom
1340} // namespace QQmlJS
1341QT_END_NAMESPACE