Add mechanisms to reformant and check code style (#128)
[openjpeg.git] / thirdparty / astyle / astyle.h
1 // astyle.h
2 // Copyright (c) 2017 by Jim Pattee <jimp03@email.com>.
3 // This code is licensed under the MIT License.
4 // License.md describes the conditions under which this software may be distributed.
5
6 #ifndef ASTYLE_H
7 #define ASTYLE_H
8
9 //-----------------------------------------------------------------------------
10 // headers
11 //-----------------------------------------------------------------------------
12
13 #ifdef __VMS
14         #define __USE_STD_IOSTREAM 1
15         #include <assert>
16 #else
17         #include <cassert>
18 #endif
19
20 #include <cctype>
21 #include <iostream>             // for cout
22 #include <memory>
23 #include <string>
24 #include <vector>
25
26 #ifdef __GNUC__
27         #include <cstring>              // need both string and cstring for GCC
28 #endif
29
30 //-----------------------------------------------------------------------------
31 // declarations
32 //-----------------------------------------------------------------------------
33
34 #ifdef _MSC_VER
35         #pragma warning(disable: 4267)  // conversion from size_t to int
36 #endif
37
38 #ifdef __BORLANDC__
39         #pragma warn -8004                  // variable is assigned a value that is never used
40 #endif
41
42 #ifdef __INTEL_COMPILER
43         #pragma warning(disable:  383)  // value copied to temporary, reference to temporary used
44         #pragma warning(disable:  981)  // operands are evaluated in unspecified order
45 #endif
46
47 #ifdef __clang__
48         #pragma clang diagnostic ignored "-Wshorten-64-to-32"
49 #endif
50
51 //-----------------------------------------------------------------------------
52 // astyle namespace
53 //-----------------------------------------------------------------------------
54
55 namespace astyle {
56 //
57 using namespace std;
58
59 //----------------------------------------------------------------------------
60 // definitions
61 //----------------------------------------------------------------------------
62
63 enum FileType { C_TYPE = 0, JAVA_TYPE = 1, SHARP_TYPE = 2 };
64
65 /* The enums below are not recognized by 'vectors' in Microsoft Visual C++
66    V5 when they are part of a namespace!!!  Use Visual C++ V6 or higher.
67 */
68 enum FormatStyle
69 {
70         STYLE_NONE,
71         STYLE_ALLMAN,
72         STYLE_JAVA,
73         STYLE_KR,
74         STYLE_STROUSTRUP,
75         STYLE_WHITESMITH,
76         STYLE_VTK,
77         STYLE_BANNER,
78         STYLE_GNU,
79         STYLE_LINUX,
80         STYLE_HORSTMANN,
81         STYLE_1TBS,
82         STYLE_GOOGLE,
83         STYLE_MOZILLA,
84         STYLE_PICO,
85         STYLE_LISP
86 };
87
88 enum BraceMode
89 {
90         NONE_MODE,
91         ATTACH_MODE,
92         BREAK_MODE,
93         LINUX_MODE,
94         RUN_IN_MODE             // broken braces
95 };
96
97 // maximun value for int is 16,384 (total value of 32,767)
98 enum BraceType
99 {
100         NULL_TYPE        = 0,
101         NAMESPACE_TYPE   = 1,           // also a DEFINITION_TYPE
102         CLASS_TYPE       = 2,           // also a DEFINITION_TYPE
103         STRUCT_TYPE      = 4,           // also a DEFINITION_TYPE
104         INTERFACE_TYPE   = 8,           // also a DEFINITION_TYPE
105         DEFINITION_TYPE  = 16,
106         COMMAND_TYPE     = 32,
107         ARRAY_NIS_TYPE   = 64,          // also an ARRAY_TYPE
108         ENUM_TYPE        = 128,         // also an ARRAY_TYPE
109         INIT_TYPE        = 256,         // also an ARRAY_TYPE
110         ARRAY_TYPE       = 512,
111         EXTERN_TYPE      = 1024,        // extern "C", not a command type extern
112         EMPTY_BLOCK_TYPE = 2048,        // also a SINGLE_LINE_TYPE
113         BREAK_BLOCK_TYPE = 4096,        // also a SINGLE_LINE_TYPE
114         SINGLE_LINE_TYPE = 8192
115 };
116
117 enum MinConditional
118 {
119         MINCOND_ZERO,
120         MINCOND_ONE,
121         MINCOND_TWO,
122         MINCOND_ONEHALF,
123         MINCOND_END
124 };
125
126 enum ObjCColonPad
127 {
128         COLON_PAD_NO_CHANGE,
129         COLON_PAD_NONE,
130         COLON_PAD_ALL,
131         COLON_PAD_AFTER,
132         COLON_PAD_BEFORE
133 };
134
135 enum PointerAlign
136 {
137         PTR_ALIGN_NONE,
138         PTR_ALIGN_TYPE,
139         PTR_ALIGN_MIDDLE,
140         PTR_ALIGN_NAME
141 };
142
143 enum ReferenceAlign
144 {
145         REF_ALIGN_NONE   = PTR_ALIGN_NONE,
146         REF_ALIGN_TYPE   = PTR_ALIGN_TYPE,
147         REF_ALIGN_MIDDLE = PTR_ALIGN_MIDDLE,
148         REF_ALIGN_NAME   = PTR_ALIGN_NAME,
149         REF_SAME_AS_PTR
150 };
151
152 enum FileEncoding
153 {
154         ENCODING_8BIT,
155         UTF_16BE,
156         UTF_16LE,     // Windows default
157         UTF_32BE,
158         UTF_32LE
159 };
160
161 enum LineEndFormat
162 {
163         LINEEND_DEFAULT,        // Use line break that matches most of the file
164         LINEEND_WINDOWS,
165         LINEEND_LINUX,
166         LINEEND_MACOLD,
167         LINEEND_CRLF = LINEEND_WINDOWS,
168         LINEEND_LF   = LINEEND_LINUX,
169         LINEEND_CR   = LINEEND_MACOLD
170 };
171
172 //-----------------------------------------------------------------------------
173 // Class ASSourceIterator
174 // A pure virtual class is used by ASFormatter and ASBeautifier instead of
175 // ASStreamIterator. This allows programs using AStyle as a plug-in to define
176 // their own ASStreamIterator. The ASStreamIterator class must inherit
177 // this class.
178 //-----------------------------------------------------------------------------
179
180 class ASSourceIterator
181 {
182 public:
183         ASSourceIterator() {}
184         virtual ~ASSourceIterator() {}
185         virtual int getStreamLength() const = 0;
186         virtual bool hasMoreLines() const = 0;
187         virtual string nextLine(bool emptyLineWasDeleted = false) = 0;
188         virtual string peekNextLine() = 0;
189         virtual void peekReset() = 0;
190         virtual streamoff tellg() = 0;
191 };
192
193 //-----------------------------------------------------------------------------
194 // Class ASPeekStream
195 // A small class using RAII to peek ahead in the ASSourceIterator stream
196 // and to reset the ASSourceIterator pointer in the destructor.
197 // It enables a return from anywhere in the method.
198 //-----------------------------------------------------------------------------
199
200 class ASPeekStream
201 {
202 private:
203         ASSourceIterator* sourceIterator;
204         bool needReset;         // reset sourceIterator to the original position
205
206 public:
207         explicit ASPeekStream(ASSourceIterator* sourceIterator_)
208         { sourceIterator = sourceIterator_; needReset = false; }
209
210         ~ASPeekStream()
211         { if (needReset) sourceIterator->peekReset(); }
212
213         bool hasMoreLines() const
214         { return sourceIterator->hasMoreLines(); }
215
216         string peekNextLine()
217         { needReset = true; return sourceIterator->peekNextLine(); }
218 };
219
220
221 //-----------------------------------------------------------------------------
222 // Class ASResource
223 //-----------------------------------------------------------------------------
224
225 class ASResource
226 {
227 public:
228         void buildAssignmentOperators(vector<const string*>* assignmentOperators);
229         void buildCastOperators(vector<const string*>* castOperators);
230         void buildHeaders(vector<const string*>* headers, int fileType, bool beautifier = false);
231         void buildIndentableMacros(vector<const pair<const string, const string>* >* indentableMacros);
232         void buildIndentableHeaders(vector<const string*>* indentableHeaders);
233         void buildNonAssignmentOperators(vector<const string*>* nonAssignmentOperators);
234         void buildNonParenHeaders(vector<const string*>* nonParenHeaders, int fileType, bool beautifier = false);
235         void buildOperators(vector<const string*>* operators, int fileType);
236         void buildPreBlockStatements(vector<const string*>* preBlockStatements, int fileType);
237         void buildPreCommandHeaders(vector<const string*>* preCommandHeaders, int fileType);
238         void buildPreDefinitionHeaders(vector<const string*>* preDefinitionHeaders, int fileType);
239
240 public:
241         static const string AS_IF, AS_ELSE;
242         static const string AS_DO, AS_WHILE;
243         static const string AS_FOR;
244         static const string AS_SWITCH, AS_CASE, AS_DEFAULT;
245         static const string AS_TRY, AS_CATCH, AS_THROW, AS_THROWS, AS_FINALLY, AS_USING;
246         static const string _AS_TRY, _AS_FINALLY, _AS_EXCEPT;
247         static const string AS_PUBLIC, AS_PROTECTED, AS_PRIVATE;
248         static const string AS_CLASS, AS_STRUCT, AS_UNION, AS_INTERFACE, AS_NAMESPACE;
249         static const string AS_MODULE;
250         static const string AS_END;
251         static const string AS_SELECTOR;
252         static const string AS_EXTERN, AS_ENUM;
253         static const string AS_STATIC, AS_CONST, AS_SEALED, AS_OVERRIDE, AS_VOLATILE, AS_NEW, AS_DELETE;
254         static const string AS_NOEXCEPT, AS_INTERRUPT, AS_AUTORELEASEPOOL;
255         static const string AS_WHERE, AS_LET, AS_SYNCHRONIZED;
256         static const string AS_OPERATOR, AS_TEMPLATE;
257         static const string AS_OPEN_BRACE, AS_CLOSE_BRACE;
258         static const string AS_OPEN_LINE_COMMENT, AS_OPEN_COMMENT, AS_CLOSE_COMMENT;
259         static const string AS_BAR_DEFINE, AS_BAR_INCLUDE, AS_BAR_IF, AS_BAR_EL, AS_BAR_ENDIF;
260         static const string AS_AUTO, AS_RETURN;
261         static const string AS_CIN, AS_COUT, AS_CERR;
262         static const string AS_ASSIGN, AS_PLUS_ASSIGN, AS_MINUS_ASSIGN, AS_MULT_ASSIGN;
263         static const string AS_DIV_ASSIGN, AS_MOD_ASSIGN, AS_XOR_ASSIGN, AS_OR_ASSIGN, AS_AND_ASSIGN;
264         static const string AS_GR_GR_ASSIGN, AS_LS_LS_ASSIGN, AS_GR_GR_GR_ASSIGN, AS_LS_LS_LS_ASSIGN;
265         static const string AS_GCC_MIN_ASSIGN, AS_GCC_MAX_ASSIGN;
266         static const string AS_EQUAL, AS_PLUS_PLUS, AS_MINUS_MINUS, AS_NOT_EQUAL, AS_GR_EQUAL;
267         static const string AS_LS_EQUAL, AS_LS_LS_LS, AS_LS_LS, AS_GR_GR_GR, AS_GR_GR;
268         static const string AS_QUESTION_QUESTION, AS_LAMBDA;
269         static const string AS_ARROW, AS_AND, AS_OR;
270         static const string AS_SCOPE_RESOLUTION;
271         static const string AS_PLUS, AS_MINUS, AS_MULT, AS_DIV, AS_MOD, AS_GR, AS_LS;
272         static const string AS_NOT, AS_BIT_XOR, AS_BIT_OR, AS_BIT_AND, AS_BIT_NOT;
273         static const string AS_QUESTION, AS_COLON, AS_SEMICOLON, AS_COMMA;
274         static const string AS_ASM, AS__ASM__, AS_MS_ASM, AS_MS__ASM;
275         static const string AS_QFOREACH, AS_QFOREVER, AS_FOREVER;
276         static const string AS_FOREACH, AS_LOCK, AS_UNSAFE, AS_FIXED;
277         static const string AS_GET, AS_SET, AS_ADD, AS_REMOVE;
278         static const string AS_DELEGATE, AS_UNCHECKED;
279         static const string AS_CONST_CAST, AS_DYNAMIC_CAST, AS_REINTERPRET_CAST, AS_STATIC_CAST;
280         static const string AS_NS_DURING, AS_NS_HANDLER;
281 };  // Class ASResource
282
283 //-----------------------------------------------------------------------------
284 // Class ASBase
285 // Functions definitions are at the end of ASResource.cpp.
286 //-----------------------------------------------------------------------------
287
288 class ASBase : protected ASResource
289 {
290 private:
291         // all variables should be set by the "init" function
292         int baseFileType;      // a value from enum FileType
293
294 protected:
295         ASBase() : baseFileType(C_TYPE) { }
296
297 protected:  // inline functions
298         void init(int fileTypeArg) { baseFileType = fileTypeArg; }
299         bool isCStyle() const { return (baseFileType == C_TYPE); }
300         bool isJavaStyle() const { return (baseFileType == JAVA_TYPE); }
301         bool isSharpStyle() const { return (baseFileType == SHARP_TYPE); }
302         bool isWhiteSpace(char ch) const { return (ch == ' ' || ch == '\t'); }
303
304 protected:  // functions definitions are at the end of ASResource.cpp
305         const string* findHeader(const string& line, int i,
306                                  const vector<const string*>* possibleHeaders) const;
307         bool findKeyword(const string& line, int i, const string& keyword) const;
308         const string* findOperator(const string& line, int i,
309                                    const vector<const string*>* possibleOperators) const;
310         string getCurrentWord(const string& line, size_t index) const;
311         bool isDigit(char ch) const;
312         bool isLegalNameChar(char ch) const;
313         bool isCharPotentialHeader(const string& line, size_t i) const;
314         bool isCharPotentialOperator(char ch) const;
315         bool isDigitSeparator(const string& line, int i) const;
316         char peekNextChar(const string& line, int i) const;
317
318 };  // Class ASBase
319
320 //-----------------------------------------------------------------------------
321 // Class ASBeautifier
322 //-----------------------------------------------------------------------------
323
324 class ASBeautifier : protected ASBase
325 {
326 public:
327         ASBeautifier();
328         virtual ~ASBeautifier();
329         virtual void init(ASSourceIterator* iter);
330         virtual string beautify(const string& originalLine);
331         void setCaseIndent(bool state);
332         void setClassIndent(bool state);
333         void setContinuationIndentation(int indent = 1);
334         void setCStyle();
335         void setDefaultTabLength();
336         void setEmptyLineFill(bool state);
337         void setForceTabXIndentation(int length);
338         void setAfterParenIndent(bool state);
339         void setJavaStyle();
340         void setLabelIndent(bool state);
341         void setMaxContinuationIndentLength(int max);
342         void setMaxInStatementIndentLength(int max);
343         void setMinConditionalIndentOption(int min);
344         void setMinConditionalIndentLength();
345         void setModeManuallySet(bool state);
346         void setModifierIndent(bool state);
347         void setNamespaceIndent(bool state);
348         void setAlignMethodColon(bool state);
349         void setSharpStyle();
350         void setSpaceIndentation(int length = 4);
351         void setSwitchIndent(bool state);
352         void setTabIndentation(int length = 4, bool forceTabs = false);
353         void setPreprocDefineIndent(bool state);
354         void setPreprocConditionalIndent(bool state);
355         int  getBeautifierFileType() const;
356         int  getFileType() const;
357         int  getIndentLength() const;
358         int  getTabLength() const;
359         string getIndentString() const;
360         string getNextWord(const string& line, size_t currPos) const;
361         bool getAlignMethodColon() const;
362         bool getBraceIndent() const;
363         bool getBlockIndent() const;
364         bool getCaseIndent() const;
365         bool getClassIndent() const;
366         bool getEmptyLineFill() const;
367         bool getForceTabIndentation() const;
368         bool getModeManuallySet() const;
369         bool getModifierIndent() const;
370         bool getNamespaceIndent() const;
371         bool getPreprocDefineIndent() const;
372         bool getSwitchIndent() const;
373
374 protected:
375         void deleteBeautifierVectors();
376         int  getNextProgramCharDistance(const string& line, int i) const;
377         int  indexOf(const vector<const string*>& container, const string* element) const;
378         void setBlockIndent(bool state);
379         void setBraceIndent(bool state);
380         void setBraceIndentVtk(bool state);
381         string extractPreprocessorStatement(const string& line) const;
382         string trim(const string& str) const;
383         string rtrim(const string& str) const;
384
385         // variables set by ASFormatter - must be updated in activeBeautifierStack
386         int  inLineNumber;
387         int  runInIndentContinuation;
388         int  nonInStatementBrace;
389         int  objCColonAlignSubsequent;          // for subsequent lines not counting indent
390         bool lineCommentNoBeautify;
391         bool isElseHeaderIndent;
392         bool isCaseHeaderCommentIndent;
393         bool isNonInStatementArray;
394         bool isSharpAccessor;
395         bool isSharpDelegate;
396         bool isInExternC;
397         bool isInBeautifySQL;
398         bool isInIndentableStruct;
399         bool isInIndentablePreproc;
400
401 private:  // functions
402         ASBeautifier(const ASBeautifier& other);     // inline functions
403         ASBeautifier& operator=(ASBeautifier&);      // not to be implemented
404
405         void adjustObjCMethodDefinitionIndentation(const string& line_);
406         void adjustObjCMethodCallIndentation(const string& line_);
407         void adjustParsedLineIndentation(size_t iPrelim, bool isInExtraHeaderIndent);
408         void computePreliminaryIndentation();
409         void parseCurrentLine(const string& line);
410         void popLastContinuationIndent();
411         void processPreprocessor(const string& preproc, const string& line);
412         void registerContinuationIndent(const string& line, int i, int spaceIndentCount_,
413                                         int tabIncrementIn, int minIndent, bool updateParenStack);
414         void registerContinuationIndentColon(const string& line, int i, int tabIncrementIn);
415         void initVectors();
416         void initTempStacksContainer(vector<vector<const string*>*>*& container,
417                                      vector<vector<const string*>*>* value);
418         void clearObjCMethodDefinitionAlignment();
419         void deleteBeautifierContainer(vector<ASBeautifier*>*& container);
420         void deleteTempStacksContainer(vector<vector<const string*>*>*& container);
421         int  adjustIndentCountForBreakElseIfComments() const;
422         int  computeObjCColonAlignment(const string& line, int colonAlignPosition) const;
423         int  convertTabToSpaces(int i, int tabIncrementIn) const;
424         int  getContinuationIndentAssign(const string& line, size_t currPos) const;
425         int  getContinuationIndentComma(const string& line, size_t currPos) const;
426         int  getObjCFollowingKeyword(const string& line, int bracePos) const;
427         bool isIndentedPreprocessor(const string& line, size_t currPos) const;
428         bool isLineEndComment(const string& line, int startPos) const;
429         bool isPreprocessorConditionalCplusplus(const string& line) const;
430         bool isInPreprocessorUnterminatedComment(const string& line);
431         bool statementEndsWithComma(const string& line, int index) const;
432         const string& getIndentedLineReturn(const string& newLine, const string& originalLine) const;
433         string getIndentedSpaceEquivalent(const string& line_) const;
434         string preLineWS(int lineIndentCount, int lineSpaceIndentCount) const;
435         template<typename T> void deleteContainer(T& container);
436         template<typename T> void initContainer(T& container, T value);
437         vector<vector<const string*>*>* copyTempStacks(const ASBeautifier& other) const;
438         pair<int, int> computePreprocessorIndent();
439
440 private:  // variables
441         int beautifierFileType;
442         vector<const string*>* headers;
443         vector<const string*>* nonParenHeaders;
444         vector<const string*>* preBlockStatements;
445         vector<const string*>* preCommandHeaders;
446         vector<const string*>* assignmentOperators;
447         vector<const string*>* nonAssignmentOperators;
448         vector<const string*>* indentableHeaders;
449
450         vector<ASBeautifier*>* waitingBeautifierStack;
451         vector<ASBeautifier*>* activeBeautifierStack;
452         vector<int>* waitingBeautifierStackLengthStack;
453         vector<int>* activeBeautifierStackLengthStack;
454         vector<const string*>* headerStack;
455         vector<vector<const string*>* >* tempStacks;
456         vector<int>* squareBracketDepthStack;
457         vector<bool>* blockStatementStack;
458         vector<bool>* parenStatementStack;
459         vector<bool>* braceBlockStateStack;
460         vector<int>* continuationIndentStack;
461         vector<int>* continuationIndentStackSizeStack;
462         vector<int>* parenIndentStack;
463         vector<pair<int, int> >* preprocIndentStack;
464
465         ASSourceIterator* sourceIterator;
466         const string* currentHeader;
467         const string* previousLastLineHeader;
468         const string* probationHeader;
469         const string* lastLineHeader;
470         string indentString;
471         string verbatimDelimiter;
472         bool isInQuote;
473         bool isInVerbatimQuote;
474         bool haveLineContinuationChar;
475         bool isInAsm;
476         bool isInAsmOneLine;
477         bool isInAsmBlock;
478         bool isInComment;
479         bool isInPreprocessorComment;
480         bool isInRunInComment;
481         bool isInCase;
482         bool isInQuestion;
483         bool isContinuation;
484         bool isInHeader;
485         bool isInTemplate;
486         bool isInDefine;
487         bool isInDefineDefinition;
488         bool classIndent;
489         bool isIndentModeOff;
490         bool isInClassHeader;                   // is in a class before the opening brace
491         bool isInClassHeaderTab;                // is in an indentable class header line
492         bool isInClassInitializer;              // is in a class after the ':' initializer
493         bool isInClass;                                 // is in a class after the opening brace
494         bool isInObjCMethodDefinition;
495         bool isInObjCMethodCall;
496         bool isInObjCMethodCallFirst;
497         bool isImmediatelyPostObjCMethodDefinition;
498         bool isImmediatelyPostObjCMethodCall;
499         bool isInIndentablePreprocBlock;
500         bool isInObjCInterface;
501         bool isInEnum;
502         bool isInEnumTypeID;
503         bool isInLet;
504         bool modifierIndent;
505         bool switchIndent;
506         bool caseIndent;
507         bool namespaceIndent;
508         bool blockIndent;
509         bool braceIndent;
510         bool braceIndentVtk;
511         bool shouldIndentAfterParen;
512         bool labelIndent;
513         bool shouldIndentPreprocDefine;
514         bool isInConditional;
515         bool isModeManuallySet;
516         bool shouldForceTabIndentation;
517         bool emptyLineFill;
518         bool backslashEndsPrevLine;
519         bool lineOpensWithLineComment;
520         bool lineOpensWithComment;
521         bool lineStartsInComment;
522         bool blockCommentNoIndent;
523         bool blockCommentNoBeautify;
524         bool previousLineProbationTab;
525         bool lineBeginsWithOpenBrace;
526         bool lineBeginsWithCloseBrace;
527         bool lineBeginsWithComma;
528         bool lineIsCommentOnly;
529         bool lineIsLineCommentOnly;
530         bool shouldIndentBracedLine;
531         bool isInSwitch;
532         bool foundPreCommandHeader;
533         bool foundPreCommandMacro;
534         bool shouldAlignMethodColon;
535         bool shouldIndentPreprocConditional;
536         int  indentCount;
537         int  spaceIndentCount;
538         int  spaceIndentObjCMethodAlignment;
539         int  bracePosObjCMethodAlignment;
540         int  colonIndentObjCMethodAlignment;
541         int  lineOpeningBlocksNum;
542         int  lineClosingBlocksNum;
543         int  fileType;
544         int  minConditionalOption;
545         int  minConditionalIndent;
546         int  parenDepth;
547         int  indentLength;
548         int  tabLength;
549         int  continuationIndent;
550         int  blockTabCount;
551         int  maxContinuationIndent;
552         int  classInitializerIndents;
553         int  templateDepth;
554         int  squareBracketCount;
555         int  prevFinalLineSpaceIndentCount;
556         int  prevFinalLineIndentCount;
557         int  defineIndentCount;
558         int  preprocBlockIndent;
559         char quoteChar;
560         char prevNonSpaceCh;
561         char currentNonSpaceCh;
562         char currentNonLegalCh;
563         char prevNonLegalCh;
564 };  // Class ASBeautifier
565
566 //-----------------------------------------------------------------------------
567 // Class ASEnhancer
568 //-----------------------------------------------------------------------------
569
570 class ASEnhancer : protected ASBase
571 {
572 public:  // functions
573         ASEnhancer();
574         virtual ~ASEnhancer();
575         void init(int, int, int, bool, bool, bool, bool, bool, bool, bool,
576                   vector<const pair<const string, const string>* >*);
577         void enhance(string& line, bool isInNamespace, bool isInPreprocessor, bool isInSQL);
578
579 private:  // functions
580         void   convertForceTabIndentToSpaces(string&  line) const;
581         void   convertSpaceIndentToForceTab(string& line) const;
582         size_t findCaseColon(const string&  line, size_t caseIndex) const;
583         int    indentLine(string&  line, int indent) const;
584         bool   isBeginDeclareSectionSQL(const string&  line, size_t index) const;
585         bool   isEndDeclareSectionSQL(const string&  line, size_t index) const;
586         bool   isOneLineBlockReached(const string& line, int startChar) const;
587         void   parseCurrentLine(string& line, bool isInPreprocessor, bool isInSQL);
588         size_t processSwitchBlock(string&  line, size_t index);
589         int    unindentLine(string&  line, int unindent) const;
590
591 private:
592         // options from command line or options file
593         int  indentLength;
594         int  tabLength;
595         bool useTabs;
596         bool forceTab;
597         bool namespaceIndent;
598         bool caseIndent;
599         bool preprocBlockIndent;
600         bool preprocDefineIndent;
601         bool emptyLineFill;
602
603         // parsing variables
604         int  lineNumber;
605         bool isInQuote;
606         bool isInComment;
607         char quoteChar;
608
609         // unindent variables
610         int  braceCount;
611         int  switchDepth;
612         int  eventPreprocDepth;
613         bool lookingForCaseBrace;
614         bool unindentNextLine;
615         bool shouldUnindentLine;
616         bool shouldUnindentComment;
617
618         // struct used by ParseFormattedLine function
619         // contains variables used to unindent the case blocks
620         struct SwitchVariables
621         {
622                 int  switchBraceCount;
623                 int  unindentDepth;
624                 bool unindentCase;
625         };
626
627         SwitchVariables sw;                      // switch variables struct
628         vector<SwitchVariables> switchStack;     // stack vector of switch variables
629
630         // event table variables
631         bool nextLineIsEventIndent;             // begin event table indent is reached
632         bool isInEventTable;                    // need to indent an event table
633         vector<const pair<const string, const string>* >* indentableMacros;
634
635         // SQL variables
636         bool nextLineIsDeclareIndent;           // begin declare section indent is reached
637         bool isInDeclareSection;                // need to indent a declare section
638
639 };  // Class ASEnhancer
640
641 //-----------------------------------------------------------------------------
642 // Class ASFormatter
643 //-----------------------------------------------------------------------------
644
645 class ASFormatter : public ASBeautifier
646 {
647 public: // functions
648         ASFormatter();
649         virtual ~ASFormatter();
650         virtual void init(ASSourceIterator* si);
651         virtual bool hasMoreLines() const;
652         virtual string nextLine();
653         LineEndFormat getLineEndFormat() const;
654         bool getIsLineReady() const;
655         void setFormattingStyle(FormatStyle style);
656         void setAddBracesMode(bool state);
657         void setAddOneLineBracesMode(bool state);
658         void setRemoveBracesMode(bool state);
659         void setAttachClass(bool state);
660         void setAttachClosingWhile(bool state);
661         void setAttachExternC(bool state);
662         void setAttachNamespace(bool state);
663         void setAttachInline(bool state);
664         void setBraceFormatMode(BraceMode mode);
665         void setBreakAfterMode(bool state);
666         void setBreakClosingHeaderBracesMode(bool state);
667         void setBreakBlocksMode(bool state);
668         void setBreakClosingHeaderBlocksMode(bool state);
669         void setBreakElseIfsMode(bool state);
670         void setBreakOneLineBlocksMode(bool state);
671         void setBreakOneLineHeadersMode(bool state);
672         void setBreakOneLineStatementsMode(bool state);
673         void setMethodPrefixPaddingMode(bool state);
674         void setMethodPrefixUnPaddingMode(bool state);
675         void setReturnTypePaddingMode(bool state);
676         void setReturnTypeUnPaddingMode(bool state);
677         void setParamTypePaddingMode(bool state);
678         void setParamTypeUnPaddingMode(bool state);
679         void setCloseTemplatesMode(bool state);
680         void setCommaPaddingMode(bool state);
681         void setDeleteEmptyLinesMode(bool state);
682         void setIndentCol1CommentsMode(bool state);
683         void setLineEndFormat(LineEndFormat fmt);
684         void setMaxCodeLength(int max);
685         void setObjCColonPaddingMode(ObjCColonPad mode);
686         void setOperatorPaddingMode(bool state);
687         void setParensOutsidePaddingMode(bool state);
688         void setParensFirstPaddingMode(bool state);
689         void setParensInsidePaddingMode(bool state);
690         void setParensHeaderPaddingMode(bool state);
691         void setParensUnPaddingMode(bool state);
692         void setPointerAlignment(PointerAlign alignment);
693         void setPreprocBlockIndent(bool state);
694         void setReferenceAlignment(ReferenceAlign alignment);
695         void setStripCommentPrefix(bool state);
696         void setTabSpaceConversionMode(bool state);
697         size_t getChecksumIn() const;
698         size_t getChecksumOut() const;
699         int  getChecksumDiff() const;
700         int  getFormatterFileType() const;
701         // retained for compatability with release 2.06
702         // "Brackets" have been changed to "Braces" in 3.0
703         // they are referenced only by the old "bracket" options
704         void setAddBracketsMode(bool state);
705         void setAddOneLineBracketsMode(bool state);
706         void setRemoveBracketsMode(bool state);
707         void setBreakClosingHeaderBracketsMode(bool state);
708
709
710 private:  // functions
711         ASFormatter(const ASFormatter& copy);       // not to be implemented
712         ASFormatter& operator=(ASFormatter&);       // not to be implemented
713         template<typename T> void deleteContainer(T& container);
714         template<typename T> void initContainer(T& container, T value);
715         char peekNextChar() const;
716         BraceType getBraceType();
717         bool adjustChecksumIn(int adjustment);
718         bool computeChecksumIn(const string& currentLine_);
719         bool computeChecksumOut(const string& beautifiedLine);
720         bool addBracesToStatement();
721         bool removeBracesFromStatement();
722         bool commentAndHeaderFollows();
723         bool getNextChar();
724         bool getNextLine(bool emptyLineWasDeleted = false);
725         bool isArrayOperator() const;
726         bool isBeforeComment() const;
727         bool isBeforeAnyComment() const;
728         bool isBeforeAnyLineEndComment(int startPos) const;
729         bool isBeforeMultipleLineEndComments(int startPos) const;
730         bool isBraceType(BraceType a, BraceType b) const;
731         bool isClassInitializer() const;
732         bool isClosingHeader(const string* header) const;
733         bool isCurrentBraceBroken() const;
734         bool isDereferenceOrAddressOf() const;
735         bool isExecSQL(const string& line, size_t index) const;
736         bool isEmptyLine(const string& line) const;
737         bool isExternC() const;
738         bool isMultiStatementLine() const;
739         bool isNextWordSharpNonParenHeader(int startChar) const;
740         bool isNonInStatementArrayBrace() const;
741         bool isOkToSplitFormattedLine();
742         bool isPointerOrReference() const;
743         bool isPointerOrReferenceCentered() const;
744         bool isPointerOrReferenceVariable(const string& word) const;
745         bool isSharpStyleWithParen(const string* header) const;
746         bool isStructAccessModified(const string& firstLine, size_t index) const;
747         bool isIndentablePreprocessorBlock(const string& firstLine, size_t index);
748         bool isNDefPreprocStatement(const string& nextLine_, const string& preproc) const;
749         bool isUnaryOperator() const;
750         bool isUniformInitializerBrace() const;
751         bool isImmediatelyPostCast() const;
752         bool isInExponent() const;
753         bool isInSwitchStatement() const;
754         bool isNextCharOpeningBrace(int startChar) const;
755         bool isOkToBreakBlock(BraceType braceType) const;
756         bool isOperatorPaddingDisabled() const;
757         bool pointerSymbolFollows() const;
758         int  findObjCColonAlignment() const;
759         int  getCurrentLineCommentAdjustment();
760         int  getNextLineCommentAdjustment();
761         int  isOneLineBlockReached(const string& line, int startChar) const;
762         void adjustComments();
763         void appendChar(char ch, bool canBreakLine);
764         void appendCharInsideComments();
765         void appendClosingHeader();
766         void appendOperator(const string& sequence, bool canBreakLine = true);
767         void appendSequence(const string& sequence, bool canBreakLine = true);
768         void appendSpacePad();
769         void appendSpaceAfter();
770         void breakLine(bool isSplitLine = false);
771         void buildLanguageVectors();
772         void updateFormattedLineSplitPoints(char appendedChar);
773         void updateFormattedLineSplitPointsOperator(const string& sequence);
774         void checkIfTemplateOpener();
775         void clearFormattedLineSplitPoints();
776         void convertTabToSpaces();
777         void deleteContainer(vector<BraceType>*& container);
778         void formatArrayRunIn();
779         void formatRunIn();
780         void formatArrayBraces(BraceType braceType, bool isOpeningArrayBrace);
781         void formatClosingBrace(BraceType braceType);
782         void formatCommentBody();
783         void formatCommentOpener();
784         void formatCommentCloser();
785         void formatLineCommentBody();
786         void formatLineCommentOpener();
787         void formatOpeningBrace(BraceType braceType);
788         void formatQuoteBody();
789         void formatQuoteOpener();
790         void formatPointerOrReference();
791         void formatPointerOrReferenceCast();
792         void formatPointerOrReferenceToMiddle();
793         void formatPointerOrReferenceToName();
794         void formatPointerOrReferenceToType();
795         void fixOptionVariableConflicts();
796         void goForward(int i);
797         void isLineBreakBeforeClosingHeader();
798         void initContainer(vector<BraceType>*& container, vector<BraceType>* value);
799         void initNewLine();
800         void padObjCMethodColon();
801         void padObjCMethodPrefix();
802         void padObjCParamType();
803         void padObjCReturnType();
804         void padOperators(const string* newOperator);
805         void padParens();
806         void processPreprocessor();
807         void resetEndOfStatement();
808         void setAttachClosingBraceMode(bool state);
809         void stripCommentPrefix();
810         void testForTimeToSplitFormattedLine();
811         void trimContinuationLine();
812         void updateFormattedLineSplitPointsPointerOrReference(size_t index);
813         size_t findFormattedLineSplitPoint() const;
814         size_t findNextChar(const string& line, char searchChar, int searchStart = 0) const;
815         const string* checkForHeaderFollowingComment(const string& firstLine) const;
816         const string* getFollowingOperator() const;
817         string getPreviousWord(const string& line, int currPos) const;
818         string peekNextText(const string& firstLine,
819                             bool endOnEmptyLine = false,
820                             shared_ptr<ASPeekStream> streamArg = nullptr) const;
821
822 private:  // variables
823         int formatterFileType;
824         vector<const string*>* headers;
825         vector<const string*>* nonParenHeaders;
826         vector<const string*>* preDefinitionHeaders;
827         vector<const string*>* preCommandHeaders;
828         vector<const string*>* operators;
829         vector<const string*>* assignmentOperators;
830         vector<const string*>* castOperators;
831         vector<const pair<const string, const string>* >* indentableMacros;     // for ASEnhancer
832
833         ASSourceIterator* sourceIterator;
834         ASEnhancer* enhancer;
835
836         vector<const string*>* preBraceHeaderStack;
837         vector<BraceType>* braceTypeStack;
838         vector<int>* parenStack;
839         vector<bool>* structStack;
840         vector<bool>* questionMarkStack;
841
842         string currentLine;
843         string formattedLine;
844         string readyFormattedLine;
845         string verbatimDelimiter;
846         const string* currentHeader;
847         char currentChar;
848         char previousChar;
849         char previousNonWSChar;
850         char previousCommandChar;
851         char quoteChar;
852         streamoff preprocBlockEnd;
853         int  charNum;
854         int  runInIndentChars;
855         int  nextLineSpacePadNum;
856         int  objCColonAlign;
857         int  preprocBraceTypeStackSize;
858         int  spacePadNum;
859         int  tabIncrementIn;
860         int  templateDepth;
861         int  squareBracketCount;
862         size_t checksumIn;
863         size_t checksumOut;
864         size_t currentLineFirstBraceNum;        // first brace location on currentLine
865         size_t formattedLineCommentNum;     // comment location on formattedLine
866         size_t leadingSpaces;
867         size_t maxCodeLength;
868
869         // possible split points
870         size_t maxSemi;                 // probably a 'for' statement
871         size_t maxAndOr;                // probably an 'if' statement
872         size_t maxComma;
873         size_t maxParen;
874         size_t maxWhiteSpace;
875         size_t maxSemiPending;
876         size_t maxAndOrPending;
877         size_t maxCommaPending;
878         size_t maxParenPending;
879         size_t maxWhiteSpacePending;
880
881         size_t previousReadyFormattedLineLength;
882         FormatStyle formattingStyle;
883         BraceMode braceFormatMode;
884         BraceType previousBraceType;
885         PointerAlign pointerAlignment;
886         ReferenceAlign referenceAlignment;
887         ObjCColonPad objCColonPadMode;
888         LineEndFormat lineEnd;
889         bool isVirgin;
890         bool isInVirginLine;
891         bool shouldPadCommas;
892         bool shouldPadOperators;
893         bool shouldPadParensOutside;
894         bool shouldPadFirstParen;
895         bool shouldPadParensInside;
896         bool shouldPadHeader;
897         bool shouldStripCommentPrefix;
898         bool shouldUnPadParens;
899         bool shouldConvertTabs;
900         bool shouldIndentCol1Comments;
901         bool shouldIndentPreprocBlock;
902         bool shouldCloseTemplates;
903         bool shouldAttachExternC;
904         bool shouldAttachNamespace;
905         bool shouldAttachClass;
906         bool shouldAttachClosingWhile;
907         bool shouldAttachInline;
908         bool isInLineComment;
909         bool isInComment;
910         bool isInCommentStartLine;
911         bool noTrimCommentContinuation;
912         bool isInPreprocessor;
913         bool isInPreprocessorBeautify;
914         bool isInTemplate;
915         bool doesLineStartComment;
916         bool lineEndsInCommentOnly;
917         bool lineIsCommentOnly;
918         bool lineIsLineCommentOnly;
919         bool lineIsEmpty;
920         bool isImmediatelyPostCommentOnly;
921         bool isImmediatelyPostEmptyLine;
922         bool isInClassInitializer;
923         bool isInQuote;
924         bool isInVerbatimQuote;
925         bool haveLineContinuationChar;
926         bool isInQuoteContinuation;
927         bool isHeaderInMultiStatementLine;
928         bool isSpecialChar;
929         bool isNonParenHeader;
930         bool foundQuestionMark;
931         bool foundPreDefinitionHeader;
932         bool foundNamespaceHeader;
933         bool foundClassHeader;
934         bool foundStructHeader;
935         bool foundInterfaceHeader;
936         bool foundPreCommandHeader;
937         bool foundPreCommandMacro;
938         bool foundTrailingReturnType;
939         bool foundCastOperator;
940         bool isInLineBreak;
941         bool endOfAsmReached;
942         bool endOfCodeReached;
943         bool lineCommentNoIndent;
944         bool isFormattingModeOff;
945         bool isInEnum;
946         bool isInExecSQL;
947         bool isInAsm;
948         bool isInAsmOneLine;
949         bool isInAsmBlock;
950         bool isLineReady;
951         bool elseHeaderFollowsComments;
952         bool caseHeaderFollowsComments;
953         bool isPreviousBraceBlockRelated;
954         bool isInPotentialCalculation;
955         bool isCharImmediatelyPostComment;
956         bool isPreviousCharPostComment;
957         bool isCharImmediatelyPostLineComment;
958         bool isCharImmediatelyPostOpenBlock;
959         bool isCharImmediatelyPostCloseBlock;
960         bool isCharImmediatelyPostTemplate;
961         bool isCharImmediatelyPostReturn;
962         bool isCharImmediatelyPostThrow;
963         bool isCharImmediatelyPostNewDelete;
964         bool isCharImmediatelyPostOperator;
965         bool isCharImmediatelyPostPointerOrReference;
966         bool isInObjCMethodDefinition;
967         bool isInObjCInterface;
968         bool isInObjCReturnType;
969         bool isInObjCSelector;
970         bool breakCurrentOneLineBlock;
971         bool shouldRemoveNextClosingBrace;
972         bool isInBraceRunIn;
973         bool currentLineBeginsWithBrace;
974         bool attachClosingBraceMode;
975         bool shouldBreakOneLineBlocks;
976         bool shouldBreakOneLineHeaders;
977         bool shouldBreakOneLineStatements;
978         bool shouldBreakClosingHeaderBraces;
979         bool shouldBreakElseIfs;
980         bool shouldBreakLineAfterLogical;
981         bool shouldAddBraces;
982         bool shouldAddOneLineBraces;
983         bool shouldRemoveBraces;
984         bool shouldPadMethodColon;
985         bool shouldPadMethodPrefix;
986         bool shouldReparseCurrentChar;
987         bool shouldUnPadMethodPrefix;
988         bool shouldPadReturnType;
989         bool shouldUnPadReturnType;
990         bool shouldPadParamType;
991         bool shouldUnPadParamType;
992         bool shouldDeleteEmptyLines;
993         bool needHeaderOpeningBrace;
994         bool shouldBreakLineAtNextChar;
995         bool shouldKeepLineUnbroken;
996         bool passedSemicolon;
997         bool passedColon;
998         bool isImmediatelyPostNonInStmt;
999         bool isCharImmediatelyPostNonInStmt;
1000         bool isImmediatelyPostComment;
1001         bool isImmediatelyPostLineComment;
1002         bool isImmediatelyPostEmptyBlock;
1003         bool isImmediatelyPostObjCMethodPrefix;
1004         bool isImmediatelyPostPreprocessor;
1005         bool isImmediatelyPostReturn;
1006         bool isImmediatelyPostThrow;
1007         bool isImmediatelyPostNewDelete;
1008         bool isImmediatelyPostOperator;
1009         bool isImmediatelyPostTemplate;
1010         bool isImmediatelyPostPointerOrReference;
1011         bool shouldBreakBlocks;
1012         bool shouldBreakClosingHeaderBlocks;
1013         bool isPrependPostBlockEmptyLineRequested;
1014         bool isAppendPostBlockEmptyLineRequested;
1015         bool isIndentableProprocessor;
1016         bool isIndentableProprocessorBlock;
1017         bool prependEmptyLine;
1018         bool appendOpeningBrace;
1019         bool foundClosingHeader;
1020         bool isInHeader;
1021         bool isImmediatelyPostHeader;
1022         bool isInCase;
1023         bool isFirstPreprocConditional;
1024         bool processedFirstConditional;
1025         bool isJavaStaticConstructor;
1026
1027 private:  // inline functions
1028         // append the CURRENT character (curentChar) to the current formatted line.
1029         void appendCurrentChar(bool canBreakLine = true)
1030         { appendChar(currentChar, canBreakLine); }
1031
1032         // check if a specific sequence exists in the current placement of the current line
1033         bool isSequenceReached(const char* sequence) const
1034         { return currentLine.compare(charNum, strlen(sequence), sequence) == 0; }
1035
1036         // call ASBase::findHeader for the current character
1037         const string* findHeader(const vector<const string*>* headers_)
1038         { return ASBase::findHeader(currentLine, charNum, headers_); }
1039
1040         // call ASBase::findOperator for the current character
1041         const string* findOperator(const vector<const string*>* operators_)
1042         { return ASBase::findOperator(currentLine, charNum, operators_); }
1043 };  // Class ASFormatter
1044
1045 //-----------------------------------------------------------------------------
1046 // astyle namespace global declarations
1047 //-----------------------------------------------------------------------------
1048 // sort comparison functions for ASResource
1049 bool sortOnLength(const string* a, const string* b);
1050 bool sortOnName(const string* a, const string* b);
1051
1052 }   // namespace astyle
1053
1054 // end of astyle namespace  --------------------------------------------------
1055
1056 #endif // closes ASTYLE_H