-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathASFormatter.cpp
4525 lines (4076 loc) · 144 KB
/
ASFormatter.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* ASFormatter.cpp
*
* Copyright (C) 2006-2011 by Jim Pattee <jimp03@email.com>
* Copyright (C) 1998-2002 by Tal Davidson
* <http://www.gnu.org/licenses/lgpl-3.0.html>
*
* This file is a part of Artistic Style - an indentation and
* reformatting tool for C, C++, C# and Java source files.
* <http://astyle.sourceforge.net>
*
* Artistic Style is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Artistic Style is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Artistic Style. If not, see <http://www.gnu.org/licenses/>.
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*/
#include "astyle.h"
#include <algorithm>
#include <fstream>
#include <iostream>
namespace astyle
{
/**
* Constructor of ASFormatter
*/
ASFormatter::ASFormatter()
{
sourceIterator = NULL;
enhancer = new ASEnhancer;
preBracketHeaderStack = NULL;
bracketTypeStack = NULL;
parenStack = NULL;
structStack = NULL;
lineCommentNoIndent = false;
formattingStyle = STYLE_NONE;
bracketFormatMode = NONE_MODE;
pointerAlignment = PTR_ALIGN_NONE;
referenceAlignment = REF_SAME_AS_PTR;
lineEnd = LINEEND_DEFAULT;
shouldPadOperators = false;
shouldPadParensOutside = false;
shouldPadParensInside = false;
shouldPadHeader = false;
shouldUnPadParens = false;
shouldAttachClosingBracket = false;
shouldBreakOneLineBlocks = true;
shouldBreakOneLineStatements = true;
shouldConvertTabs = false;
shouldIndentCol1Comments = false;
shouldBreakBlocks = false;
shouldBreakClosingHeaderBlocks = false;
shouldBreakClosingHeaderBrackets = false;
shouldDeleteEmptyLines = false;
shouldBreakElseIfs = false;
shouldAddBrackets = false;
shouldAddOneLineBrackets = false;
// initialize ASFormatter member vectors
formatterFileType = 9; // reset to an invalid type
headers = new vector<const string*>;
nonParenHeaders = new vector<const string*>;
preDefinitionHeaders = new vector<const string*>;
preCommandHeaders = new vector<const string*>;
operators = new vector<const string*>;
assignmentOperators = new vector<const string*>;
castOperators = new vector<const string*>;
// the following prevents warning messages with cppcheck
// it will NOT compile if activated
// init();
}
/**
* Destructor of ASFormatter
*/
ASFormatter::~ASFormatter()
{
// delete ASFormatter stack vectors
deleteContainer(preBracketHeaderStack);
deleteContainer(bracketTypeStack);
deleteContainer(parenStack);
deleteContainer(structStack);
// delete ASFormatter member vectors
formatterFileType = 9; // reset to an invalid type
delete headers;
delete nonParenHeaders;
delete preDefinitionHeaders;
delete preCommandHeaders;
delete operators;
delete assignmentOperators;
delete castOperators;
// delete ASBeautifier member vectors
// must be done when the ASFormatter object is deleted (not ASBeautifier)
ASBeautifier::deleteBeautifierVectors();
delete enhancer;
}
/**
* initialize the ASFormatter.
*
* init() should be called every time a ASFormatter object is to start
* formatting a NEW source file.
* init() recieves a pointer to a ASSourceIterator object that will be
* used to iterate through the source code.
*
* @param sourceIterator a pointer to the ASSourceIterator or ASStreamIterator object.
*/
void ASFormatter::init(ASSourceIterator* si)
{
buildLanguageVectors();
fixOptionVariableConflicts();
ASBeautifier::init(si);
enhancer->init(getFileType(),
getIndentLength(),
getIndentString(),
getCaseIndent(),
getPreprocessorIndent(),
getEmptyLineFill());
sourceIterator = si;
initContainer(preBracketHeaderStack, new vector<const string*>);
initContainer(parenStack, new vector<int>);
initContainer(structStack, new vector<bool>);
parenStack->push_back(0); // parenStack must contain this default entry
initContainer(bracketTypeStack, new vector<BracketType>);
bracketTypeStack->push_back(NULL_TYPE); // bracketTypeStack must contain this default entry
currentHeader = NULL;
currentLine = "";
readyFormattedLine = "";
formattedLine = "";
currentChar = ' ';
previousChar = ' ';
previousCommandChar = ' ';
previousNonWSChar = ' ';
quoteChar = '"';
charNum = 0;
checksumIn = 0;
checksumOut = 0;
leadingSpaces = 0;
formattedLineCommentNum = 0;
preprocBracketTypeStackSize = 0;
spacePadNum = 0;
nextLineSpacePadNum = 0;
currentLineFirstBracketNum = string::npos;
previousReadyFormattedLineLength = string::npos;
templateDepth = 0;
traceLineNumber = 0;
horstmannIndentChars = 0;
tabIncrementIn = 0;
previousBracketType = NULL_TYPE;
previousOperator = NULL;
isVirgin = true;
isInLineComment = false;
isInComment = false;
noTrimCommentContinuation = false;
isInPreprocessor = false;
isInPreprocessorBeautify = false;
doesLineStartComment = false;
lineEndsInCommentOnly = false;
lineIsLineCommentOnly = false;
lineIsEmpty = false;
isImmediatelyPostCommentOnly = false;
isImmediatelyPostEmptyLine = false;
isInQuote = false;
isInVerbatimQuote = false;
haveLineContinuationChar = false;
isInQuoteContinuation = false;
isSpecialChar = false;
isNonParenHeader = false;
foundNamespaceHeader = false;
foundClassHeader = false;
foundStructHeader = false;
foundInterfaceHeader = false;
foundPreDefinitionHeader = false;
foundPreCommandHeader = false;
foundCastOperator = false;
foundQuestionMark = false;
isInLineBreak = false;
endOfCodeReached = false;
isInExecSQL = false;
isInAsm = false;
isInAsmOneLine = false;
isInAsmBlock = false;
isLineReady = false;
isPreviousBracketBlockRelated = false;
isInPotentialCalculation = false;
shouldReparseCurrentChar = false;
needHeaderOpeningBracket = false;
shouldBreakLineAtNextChar = false;
passedSemicolon = false;
passedColon = false;
isImmediatelyPostNonInStmt = false;
isCharImmediatelyPostNonInStmt = false;
isInTemplate = false;
isImmediatelyPostComment = false;
isImmediatelyPostLineComment = false;
isImmediatelyPostEmptyBlock = false;
isImmediatelyPostPreprocessor = false;
isImmediatelyPostReturn = false;
isImmediatelyPostOperator = false;
isImmediatelyPostTemplate = false;
isImmediatelyPostPointerOrReference = false;
isCharImmediatelyPostReturn = false;
isCharImmediatelyPostOperator = false;
isCharImmediatelyPostComment = false;
isPreviousCharPostComment = false;
isCharImmediatelyPostLineComment = false;
isCharImmediatelyPostOpenBlock = false;
isCharImmediatelyPostCloseBlock = false;
isCharImmediatelyPostTemplate = false;
isCharImmediatelyPostPointerOrReference = false;
breakCurrentOneLineBlock = false;
isInHorstmannRunIn = false;
currentLineBeginsWithBracket = false;
isPrependPostBlockEmptyLineRequested = false;
isAppendPostBlockEmptyLineRequested = false;
prependEmptyLine = false;
appendOpeningBracket = false;
foundClosingHeader = false;
isImmediatelyPostHeader = false;
isInHeader = false;
isInCase = false;
isJavaStaticConstructor = false;
}
/**
* build vectors for each programing language
* depending on the file extension.
*/
void ASFormatter::buildLanguageVectors()
{
if (getFileType() == formatterFileType) // don't build unless necessary
return;
formatterFileType = getFileType();
headers->clear();
nonParenHeaders->clear();
preDefinitionHeaders->clear();
preCommandHeaders->clear();
operators->clear();
assignmentOperators->clear();
castOperators->clear();
ASResource::buildHeaders(headers, getFileType());
ASResource::buildNonParenHeaders(nonParenHeaders, getFileType());
ASResource::buildPreDefinitionHeaders(preDefinitionHeaders, getFileType());
ASResource::buildPreCommandHeaders(preCommandHeaders, getFileType());
if (operators->size() == 0)
ASResource::buildOperators(operators);
if (assignmentOperators->size() == 0)
ASResource::buildAssignmentOperators(assignmentOperators);
if (castOperators->size() == 0)
ASResource::buildCastOperators(castOperators);
}
/**
* set the variables for each preefined style.
* this will override any previous settings.
*/
void ASFormatter::fixOptionVariableConflicts()
{
if (formattingStyle == STYLE_ALLMAN) {
setBracketFormatMode(BREAK_MODE);
} else if (formattingStyle == STYLE_JAVA) {
setBracketFormatMode(ATTACH_MODE);
} else if (formattingStyle == STYLE_KR) {
setBracketFormatMode(LINUX_MODE);
} else if (formattingStyle == STYLE_STROUSTRUP) {
setBracketFormatMode(STROUSTRUP_MODE);
} else if (formattingStyle == STYLE_WHITESMITH) {
setBracketFormatMode(BREAK_MODE);
setBracketIndent(true);
setClassIndent(true);
setSwitchIndent(true);
} else if (formattingStyle == STYLE_BANNER) {
setBracketFormatMode(ATTACH_MODE);
setBracketIndent(true);
setClassIndent(true);
setSwitchIndent(true);
} else if (formattingStyle == STYLE_GNU) {
setBracketFormatMode(BREAK_MODE);
setBlockIndent(true);
} else if (formattingStyle == STYLE_LINUX) {
setBracketFormatMode(LINUX_MODE);
// always for Linux style
setMinConditionalIndentOption(MINCOND_ONEHALF);
} else if (formattingStyle == STYLE_HORSTMANN) {
setBracketFormatMode(RUN_IN_MODE);
setSwitchIndent(true);
} else if (formattingStyle == STYLE_1TBS) {
setBracketFormatMode(LINUX_MODE);
setAddBracketsMode(true);
} else if (formattingStyle == STYLE_PICO) {
setBracketFormatMode(RUN_IN_MODE);
setAttachClosingBracket(true);
setSwitchIndent(true);
setBreakOneLineBlocksMode(false);
setSingleStatementsMode(false);
// add-brackets won't work for pico, but it could be fixed if necessary
// both options should be set to true
if (shouldAddBrackets)
shouldAddOneLineBrackets = true;
} else if (formattingStyle == STYLE_LISP) {
setBracketFormatMode(ATTACH_MODE);
setAttachClosingBracket(true);
setSingleStatementsMode(false);
// add-one-line-brackets won't work for lisp
// only shouldAddBrackets should be set to true
if (shouldAddOneLineBrackets) {
shouldAddBrackets = true;
shouldAddOneLineBrackets = false;
}
}
setMinConditionalIndentLength();
// add-one-line-brackets implies keep-one-line-blocks
if (shouldAddOneLineBrackets)
setBreakOneLineBlocksMode(false);
}
/**
* get the next formatted line.
*
* @return formatted line.
*/
string ASFormatter::nextLine()
{
const string* newHeader;
bool isInVirginLine = isVirgin;
isCharImmediatelyPostComment = false;
isPreviousCharPostComment = false;
isCharImmediatelyPostLineComment = false;
isCharImmediatelyPostOpenBlock = false;
isCharImmediatelyPostCloseBlock = false;
isCharImmediatelyPostTemplate = false;
traceLineNumber++;
while (!isLineReady) {
if (shouldReparseCurrentChar)
shouldReparseCurrentChar = false;
else if (!getNextChar()) {
breakLine();
continue;
} else { // stuff to do when reading a new character...
// make sure that a virgin '{' at the begining of the file will be treated as a block...
if (isInVirginLine && currentChar == '{'
&& currentLineBeginsWithBracket // lineBeginsWith('{')
&& previousCommandChar == ' ')
previousCommandChar = '{';
if (isInHorstmannRunIn)
isInLineBreak = false;
if (!isWhiteSpace(currentChar))
isInHorstmannRunIn = false;
isPreviousCharPostComment = isCharImmediatelyPostComment;
isCharImmediatelyPostComment = false;
isCharImmediatelyPostTemplate = false;
isCharImmediatelyPostReturn = false;
isCharImmediatelyPostOperator = false;
isCharImmediatelyPostPointerOrReference = false;
isCharImmediatelyPostOpenBlock = false;
isCharImmediatelyPostCloseBlock = false;
}
// if (inLineNumber >= 7)
// int x = 1;
if (shouldBreakLineAtNextChar && !isWhiteSpace(currentChar)) {
isInLineBreak = true;
shouldBreakLineAtNextChar = false;
}
if (isInExecSQL && !passedSemicolon) {
if (currentChar == ';')
passedSemicolon = true;
appendCurrentChar();
continue;
}
if (isInLineComment) {
formatLineCommentBody();
continue;
} else if (isInComment) {
formatCommentBody();
continue;
}
// not in line comment or comment
else if (isInQuote) {
formatQuoteBody();
continue;
}
if (isSequenceReached("//")) {
formatLineCommentOpener();
continue;
} else if (isSequenceReached("/*")) {
formatCommentOpener();
continue;
} else if (currentChar == '"' || currentChar == '\'') {
formatQuoteOpener();
continue;
}
// treat these preprocessor statements as a line comment
else if (currentChar =='#') {
string preproc = trim(currentLine.c_str() + charNum + 1);
if (preproc.compare(0, 6, "region") == 0
|| preproc.compare(0, 9, "endregion") == 0
|| preproc.compare(0, 5, "error") == 0
|| preproc.compare(0, 7, "warning") == 0) {
// check for horstmann run-in
if (formattedLine.length() > 0 && formattedLine[0] == '{') {
isInLineBreak = true;
isInHorstmannRunIn = false;
}
isInLineComment = true;
appendCurrentChar();
continue;
}
}
if (isInPreprocessor) {
appendCurrentChar();
continue;
}
// handle white space - needed to simplify the rest.
if (isWhiteSpace(currentChar)) {
appendCurrentChar();
continue;
}
/* not in MIDDLE of quote or comment or SQL or white-space of any type ... */
// check if in preprocessor
// ** isInPreprocessor will be automatically reset at the begining
// of a new line in getnextChar()
if (currentChar == '#') {
isInPreprocessor = true;
// check for horstmann run-in
if (formattedLine.length() > 0 && formattedLine[0] == '{') {
isInLineBreak = true;
isInHorstmannRunIn = false;
}
processPreprocessor();
// need to fall thru here to reset the variables
}
/* not in preprocessor ... */
if (isImmediatelyPostComment) {
isImmediatelyPostComment = false;
isCharImmediatelyPostComment = true;
}
if (isImmediatelyPostLineComment) {
isImmediatelyPostLineComment = false;
isCharImmediatelyPostLineComment = true;
}
if (isImmediatelyPostReturn) {
isImmediatelyPostReturn = false;
isCharImmediatelyPostReturn = true;
}
if (isImmediatelyPostOperator) {
isImmediatelyPostOperator = false;
isCharImmediatelyPostOperator = true;
}
if (isImmediatelyPostTemplate) {
isImmediatelyPostTemplate = false;
isCharImmediatelyPostTemplate = true;
}
if (isImmediatelyPostPointerOrReference) {
isImmediatelyPostPointerOrReference = false;
isCharImmediatelyPostPointerOrReference = true;
}
// reset isImmediatelyPostHeader information
if (isImmediatelyPostHeader) {
// should brackets be added
if (currentChar != '{' && shouldAddBrackets) {
bool bracketsAdded = addBracketsToStatement();
if (bracketsAdded && !shouldAddOneLineBrackets) {
size_t firstText = currentLine.find_first_not_of(" \t");
assert(firstText != string::npos);
if ((int) firstText == charNum)
breakCurrentOneLineBlock = true;
}
}
// Make sure headers are broken from their succeeding blocks
// (e.g.
// if (isFoo) DoBar();
// should become
// if (isFoo)
// DoBar;
// )
// But treat else if() as a special case which should not be broken!
if (shouldBreakOneLineStatements
&& isOkToBreakBlock(bracketTypeStack->back())) {
// if may break 'else if()'s, then simply break the line
if (shouldBreakElseIfs)
isInLineBreak = true;
}
isImmediatelyPostHeader = false;
}
if (passedSemicolon) { // need to break the formattedLine
passedSemicolon = false;
if (parenStack->back() == 0 && currentChar != ';') { // allow ;;
// does a one-line statement have ending comments?
if (isBracketType(bracketTypeStack->back(), SINGLE_LINE_TYPE)) {
size_t blockEnd = currentLine.rfind(AS_CLOSE_BRACKET);
assert(blockEnd != string::npos);
// move ending comments to this formattedLine
if (isBeforeAnyLineEndComment(blockEnd)) {
size_t commentStart = currentLine.find_first_not_of(" \t", blockEnd + 1);
assert(commentStart != string::npos);
assert((currentLine.compare(commentStart, 2, "//") == 0)
|| (currentLine.compare(commentStart, 2, "/*") == 0));
size_t commentLength = currentLine.length() - commentStart;
formattedLine.append(getIndentLength() - 1, ' ');
formattedLine.append(currentLine, commentStart, commentLength);
currentLine.erase(commentStart, commentLength);
}
}
isInExecSQL = false;
shouldReparseCurrentChar = true;
isInLineBreak = true;
if (needHeaderOpeningBracket) {
isCharImmediatelyPostCloseBlock = true;
needHeaderOpeningBracket = false;
}
continue;
}
}
if (passedColon) {
passedColon = false;
if (parenStack->back() == 0 && !isBeforeAnyComment()) {
shouldReparseCurrentChar = true;
isInLineBreak = true;
continue;
}
}
// Check if in template declaration, e.g. foo<bar> or foo<bar,fig>
if (!isInTemplate && currentChar == '<') {
checkIfTemplateOpener();
}
// handle parenthesies
if (currentChar == '(' || currentChar == '[' || (isInTemplate && currentChar == '<')) {
parenStack->back()++;
} else if (currentChar == ')' || currentChar == ']' || (isInTemplate && currentChar == '>')) {
foundPreCommandHeader = false;
parenStack->back()--;
if (isInTemplate && currentChar == '>') {
templateDepth--;
if (templateDepth == 0) {
isInTemplate = false;
isImmediatelyPostTemplate = true;
}
}
// check if this parenthesis closes a header, e.g. if (...), while (...)
if (isInHeader && parenStack->back() == 0) {
isInHeader = false;
isImmediatelyPostHeader = true;
foundQuestionMark = false;
}
if (currentChar == ')') {
foundCastOperator = false;
if (parenStack->back() == 0)
isInAsm = false;
}
}
// handle brackets
if (currentChar == '{' || currentChar == '}') {
// if appendOpeningBracket this was already done for the original bracket
if (currentChar == '{' && !appendOpeningBracket) {
BracketType newBracketType = getBracketType();
foundNamespaceHeader = false;
foundClassHeader = false;
foundStructHeader = false;
foundInterfaceHeader = false;
foundPreDefinitionHeader = false;
foundPreCommandHeader = false;
isInPotentialCalculation = false;
isJavaStaticConstructor = false;
isCharImmediatelyPostNonInStmt = false;
needHeaderOpeningBracket = false;
isPreviousBracketBlockRelated = !isBracketType(newBracketType, ARRAY_TYPE);
bracketTypeStack->push_back(newBracketType);
preBracketHeaderStack->push_back(currentHeader);
currentHeader = NULL;
structStack->push_back(isInIndentableStruct);
if (isBracketType(newBracketType, STRUCT_TYPE) && isCStyle())
isInIndentableStruct = isStructAccessModified(currentLine, charNum);
else
isInIndentableStruct = false;
}
// this must be done before the bracketTypeStack is popped
BracketType bracketType = bracketTypeStack->back();
bool isOpeningArrayBracket = (isBracketType(bracketType, ARRAY_TYPE)
&& bracketTypeStack->size() >= 2
&& !isBracketType((*bracketTypeStack)[bracketTypeStack->size()-2], ARRAY_TYPE)
);
if (currentChar == '}') {
// if a request has been made to append a post block empty line,
// but the block exists immediately before a closing bracket,
// then there is no need for the post block empty line.
isAppendPostBlockEmptyLineRequested = false;
breakCurrentOneLineBlock = false;
isInAsmBlock = false;
// added for release 1.24
// TODO: remove at the appropriate time
assert(isInAsm == false);
assert(isInAsmOneLine == false);
assert(isInQuote == false);
isInAsm = isInAsmOneLine = isInQuote = false;
// end remove
if (bracketTypeStack->size() > 1) {
previousBracketType = bracketTypeStack->back();
bracketTypeStack->pop_back();
isPreviousBracketBlockRelated = !isBracketType(bracketType, ARRAY_TYPE);
} else {
previousBracketType = NULL_TYPE;
isPreviousBracketBlockRelated = false;
}
if (!preBracketHeaderStack->empty()) {
currentHeader = preBracketHeaderStack->back();
preBracketHeaderStack->pop_back();
} else
currentHeader = NULL;
if (!structStack->empty()) {
isInIndentableStruct = structStack->back();
structStack->pop_back();
} else
isInIndentableStruct = false;
if (isNonInStatementArray
&& (!isBracketType(bracketTypeStack->back(), ARRAY_TYPE) // check previous bracket
|| peekNextChar() == ';')) // check for "};" added V2.01
isImmediatelyPostNonInStmt = true;
}
// format brackets
appendOpeningBracket = false;
if (isBracketType(bracketType, ARRAY_TYPE)) {
formatArrayBrackets(bracketType, isOpeningArrayBracket);
} else {
if (currentChar == '{')
formatOpeningBracket(bracketType);
else
formatClosingBracket(bracketType);
}
continue;
}
if ((((previousCommandChar == '{' && isPreviousBracketBlockRelated)
|| ((previousCommandChar == '}'
&& !isImmediatelyPostEmptyBlock
&& isPreviousBracketBlockRelated
&& !isPreviousCharPostComment // Fixes wrongly appended newlines after '}' immediately after comments
&& peekNextChar() != ' '
&& !isBracketType(previousBracketType, DEFINITION_TYPE))
&& !isBracketType(bracketTypeStack->back(), DEFINITION_TYPE)))
&& isOkToBreakBlock(bracketTypeStack->back()))
// check for array
|| (previousCommandChar == '{' // added 9/30/2010
&& isBracketType(bracketTypeStack->back(), ARRAY_TYPE)
&& !isBracketType(bracketTypeStack->back(), SINGLE_LINE_TYPE)
&& isNonInStatementArray)) {
isCharImmediatelyPostOpenBlock = (previousCommandChar == '{');
isCharImmediatelyPostCloseBlock = (previousCommandChar == '}');
if (isCharImmediatelyPostOpenBlock
&& !isCharImmediatelyPostComment
&& !isCharImmediatelyPostLineComment) {
previousCommandChar = ' ';
if (bracketFormatMode == NONE_MODE) {
if (shouldBreakOneLineBlocks
&& isBracketType(bracketTypeStack->back(), SINGLE_LINE_TYPE))
isInLineBreak = true;
else if (currentLineBeginsWithBracket)
formatRunIn();
else
breakLine();
} else if (bracketFormatMode == RUN_IN_MODE
&& currentChar != '#')
formatRunIn();
else
isInLineBreak = true;
} else if (isCharImmediatelyPostCloseBlock
&& shouldBreakOneLineStatements
&& (isLegalNameChar(currentChar) && currentChar != '.')
&& !isCharImmediatelyPostComment) {
previousCommandChar = ' ';
isInLineBreak = true;
}
}
// reset block handling flags
isImmediatelyPostEmptyBlock = false;
// look for headers
bool isPotentialHeader = isCharPotentialHeader(currentLine, charNum);
if (isPotentialHeader && !isInTemplate) {
isNonParenHeader = false;
foundClosingHeader = false;
newHeader = findHeader(headers);
if (newHeader != NULL) {
const string* previousHeader;
// recognize closing headers of do..while, if..else, try..catch..finally
if ((newHeader == &AS_ELSE && currentHeader == &AS_IF)
|| (newHeader == &AS_WHILE && currentHeader == &AS_DO)
|| (newHeader == &AS_CATCH && currentHeader == &AS_TRY)
|| (newHeader == &AS_CATCH && currentHeader == &AS_CATCH)
|| (newHeader == &AS_FINALLY && currentHeader == &AS_TRY)
|| (newHeader == &AS_FINALLY && currentHeader == &AS_CATCH)
|| (newHeader == &_AS_FINALLY && currentHeader == &_AS_TRY)
|| (newHeader == &_AS_EXCEPT && currentHeader == &_AS_TRY)
|| (newHeader == &AS_SET && currentHeader == &AS_GET)
|| (newHeader == &AS_REMOVE && currentHeader == &AS_ADD))
foundClosingHeader = true;
previousHeader = currentHeader;
currentHeader = newHeader;
needHeaderOpeningBracket = true;
if (foundClosingHeader && previousNonWSChar == '}') {
if (isOkToBreakBlock(bracketTypeStack->back()))
isLineBreakBeforeClosingHeader();
// get the adjustment for a comment following the closing header
if (isInLineBreak)
nextLineSpacePadNum = getNextLineCommentAdjustment();
else
spacePadNum = getCurrentLineCommentAdjustment();
}
// check if the found header is non-paren header
isNonParenHeader = findHeader(nonParenHeaders) != NULL;
// join 'else if' statements
if (currentHeader == &AS_IF && previousHeader == &AS_ELSE && isInLineBreak
&& !shouldBreakElseIfs && !isCharImmediatelyPostLineComment) {
// 'else' must be last thing on the line, but must not be #else
size_t start = formattedLine.length() >= 6 ? formattedLine.length()-6 : 0;
if (formattedLine.find("else", start) != string::npos
&& formattedLine.find("#else", start) == string::npos) {
appendSpacePad();
isInLineBreak = false;
}
}
appendSequence(*currentHeader);
goForward(currentHeader->length() - 1);
// if a paren-header is found add a space after it, if needed
// this checks currentLine, appendSpacePad() checks formattedLine
// in 'case' and C# 'catch' can be either a paren or non-paren header
if (shouldPadHeader
&& (!isNonParenHeader
|| (currentHeader == &AS_CASE && peekNextChar() == '(')
|| (currentHeader == &AS_CATCH && peekNextChar() == '('))
&& charNum < (int) currentLine.length() - 1 && !isWhiteSpace(currentLine[charNum+1]))
appendSpacePad();
// Signal that a header has been reached
// *** But treat a closing while() (as in do...while)
// as if it were NOT a header since a closing while()
// should never have a block after it!
if (currentHeader != &AS_CASE
&& !(foundClosingHeader && currentHeader == &AS_WHILE)) {
isInHeader = true;
// in C# 'catch' and 'delegate' can be a paren or non-paren header
if (isNonParenHeader && !isSharpStyleWithParen(currentHeader)) {
isImmediatelyPostHeader = true;
isInHeader = false;
}
}
if (shouldBreakBlocks
&& isOkToBreakBlock(bracketTypeStack->back())) {
if (previousHeader == NULL
&& !foundClosingHeader
&& !isCharImmediatelyPostOpenBlock
&& !isImmediatelyPostCommentOnly) {
isPrependPostBlockEmptyLineRequested = true;
}
if (currentHeader == &AS_ELSE
|| currentHeader == &AS_CATCH
|| currentHeader == &AS_FINALLY
|| foundClosingHeader) {
isPrependPostBlockEmptyLineRequested = false;
}
if (shouldBreakClosingHeaderBlocks
&& isCharImmediatelyPostCloseBlock
&& !isImmediatelyPostCommentOnly
&& currentHeader != &AS_WHILE) { // closing do-while block
isPrependPostBlockEmptyLineRequested = true;
}
}
if (currentHeader == &AS_CASE
|| currentHeader == &AS_DEFAULT)
isInCase = true;
continue;
} else if ((newHeader = findHeader(preDefinitionHeaders)) != NULL
&& parenStack->back() == 0) {
if (newHeader == &AS_NAMESPACE)
foundNamespaceHeader = true;
if (newHeader == &AS_CLASS)
foundClassHeader = true;
if (newHeader == &AS_STRUCT)
foundStructHeader = true;
if (newHeader == &AS_INTERFACE)
foundInterfaceHeader = true;
foundPreDefinitionHeader = true;
appendSequence(*newHeader);
goForward(newHeader->length() - 1);
continue;
} else if ((newHeader = findHeader(preCommandHeaders)) != NULL) {
foundPreCommandHeader = true;
// fall thru here for a 'const' that is not a precommand header
} else if ((newHeader = findHeader(castOperators)) != NULL) {
foundCastOperator = true;
appendSequence(*newHeader);
goForward(newHeader->length() - 1);
continue;
}
} // (isPotentialHeader && !isInTemplate)
if (isInLineBreak) { // OK to break line here
breakLine();
if (isInVirginLine) { // adjust for the first line
lineCommentNoBeautify = lineCommentNoIndent;
lineCommentNoIndent = false;
}
}
if (previousNonWSChar == '}' || currentChar == ';') {
if (currentChar == ';') {
if (((shouldBreakOneLineStatements
|| isBracketType(bracketTypeStack->back(), SINGLE_LINE_TYPE))
&& isOkToBreakBlock(bracketTypeStack->back()))
&& !(shouldAttachClosingBracket && peekNextChar() == '}')) {
passedSemicolon = true;
}
// append post block empty line for unbracketed header
if (shouldBreakBlocks
&& currentHeader != NULL
&& currentHeader != &AS_CASE
&& currentHeader != &AS_DEFAULT
&& parenStack->back() == 0) {
isAppendPostBlockEmptyLineRequested = true;
}
}
// end of block if a closing bracket was found
// or an opening bracket was not found (';' closes)
if (currentChar != ';'
|| (needHeaderOpeningBracket && parenStack->back() == 0))
currentHeader = NULL;
foundQuestionMark = false;
foundNamespaceHeader = false;
foundClassHeader = false;
foundStructHeader = false;
foundInterfaceHeader = false;
foundPreDefinitionHeader = false;
foundPreCommandHeader = false;
foundCastOperator = false;
isInPotentialCalculation = false;
isSharpAccessor = false;
isSharpDelegate = false;
isInExtern = false;
nonInStatementBracket = 0;
}
if (currentChar == ':') {
if (isInCase
&& previousChar != ':' // not part of '::'
&& peekNextChar() != ':') { // not part of '::'
isInCase = false;
if (shouldBreakOneLineStatements)
passedColon = true;
} else if (isCStyle() // for C/C++ only
&& shouldBreakOneLineStatements
&& !foundQuestionMark // not in a ... ? ... : ... sequence
&& !foundPreDefinitionHeader // not in a definition block (e.g. class foo : public bar
&& previousCommandChar != ')' // not immediately after closing paren of a method header, e.g. ASFormatter::ASFormatter(...) : ASBeautifier(...)
&& previousChar != ':' // not part of '::'
&& peekNextChar() != ':' // not part of '::'
&& !isDigit(peekNextChar()) // not a bit field
&& !isInAsm // not in extended assembler
&& !isInAsmOneLine // not in extended assembler
&& !isInAsmBlock) { // not in extended assembler
passedColon = true;
}
}
if (currentChar == '?')
foundQuestionMark = true;
if (isPotentialHeader && !isInTemplate) {
if (findKeyword(currentLine, charNum, AS_NEW))
isInPotentialCalculation = false;
if (findKeyword(currentLine, charNum, AS_RETURN)) {
isInPotentialCalculation = true; // return is the same as an = sign
isImmediatelyPostReturn = true;
}
if (findKeyword(currentLine, charNum, AS_OPERATOR))
isImmediatelyPostOperator = true;
if (isCStyle() && findKeyword(currentLine, charNum, AS_EXTERN))
isInExtern = true;
if (isCStyle() && isExecSQL(currentLine, charNum))
isInExecSQL = true;
if (isCStyle()) {
if (findKeyword(currentLine, charNum, AS_ASM)
|| findKeyword(currentLine, charNum, AS__ASM__)) {
isInAsm = true;
} else if (findKeyword(currentLine, charNum, AS_MS_ASM) // microsoft specific
|| findKeyword(currentLine, charNum, AS_MS__ASM)) {
int index = 4;
if (peekNextChar() == '_') // check for __asm
index = 5;
char peekedChar = ASBase::peekNextChar(currentLine, charNum + index);
if (peekedChar == '{' || peekedChar == ' ')
isInAsmBlock = true;
else
isInAsmOneLine = true;
}
}
if (isJavaStyle()
&& (findKeyword(currentLine, charNum, AS_STATIC)
&& isNextCharOpeningBracket(charNum + 6)))
isJavaStaticConstructor = true;
if (isSharpStyle()
&& (findKeyword(currentLine, charNum, AS_DELEGATE)
|| findKeyword(currentLine, charNum, AS_UNCHECKED)))
isSharpDelegate = true;
// append the entire name
string name = getCurrentWord(currentLine, charNum);
// must pad the 'and' and 'or' operators if required
if (shouldPadOperators
&& (name == "and" || name == "or")) {
appendSpacePad();
appendSequence(name);