diff --git a/plugins/astyle/3rdparty/libastyle/ASBeautifier.cpp b/plugins/astyle/3rdparty/libastyle/ASBeautifier.cpp --- a/plugins/astyle/3rdparty/libastyle/ASBeautifier.cpp +++ b/plugins/astyle/3rdparty/libastyle/ASBeautifier.cpp @@ -1,7 +1,7 @@ // ASBeautifier.cpp -// Copyright (c) 2016 by Jim Pattee . +// Copyright (c) 2018 by Jim Pattee . // This code is licensed under the MIT License. -// License.txt describes the conditions under which this software may be distributed. +// License.md describes the conditions under which this software may be distributed. //----------------------------------------------------------------------------- // headers @@ -18,7 +18,7 @@ namespace astyle { // // this must be global -static int g_preprocessorCppExternCBracket; +static int g_preprocessorCppExternCBrace; //----------------------------------------------------------------------------- // ASBeautifier class @@ -31,38 +31,39 @@ */ ASBeautifier::ASBeautifier() { - waitingBeautifierStack = NULL; - activeBeautifierStack = NULL; - waitingBeautifierStackLengthStack = NULL; - activeBeautifierStackLengthStack = NULL; - - headerStack = NULL; - tempStacks = NULL; - blockParenDepthStack = NULL; - blockStatementStack = NULL; - parenStatementStack = NULL; - bracketBlockStateStack = NULL; - inStatementIndentStack = NULL; - inStatementIndentStackSizeStack = NULL; - parenIndentStack = NULL; - preprocIndentStack = NULL; - sourceIterator = NULL; + waitingBeautifierStack = nullptr; + activeBeautifierStack = nullptr; + waitingBeautifierStackLengthStack = nullptr; + activeBeautifierStackLengthStack = nullptr; + + headerStack = nullptr; + tempStacks = nullptr; + parenDepthStack = nullptr; + blockStatementStack = nullptr; + parenStatementStack = nullptr; + braceBlockStateStack = nullptr; + continuationIndentStack = nullptr; + continuationIndentStackSizeStack = nullptr; + parenIndentStack = nullptr; + preprocIndentStack = nullptr; + sourceIterator = nullptr; isModeManuallySet = false; shouldForceTabIndentation = false; setSpaceIndentation(4); setContinuationIndentation(1); setMinConditionalIndentOption(MINCOND_TWO); - setMaxInStatementIndentLength(40); + setMaxContinuationIndentLength(40); classInitializerIndents = 1; tabLength = 0; setClassIndent(false); setModifierIndent(false); setSwitchIndent(false); setCaseIndent(false); setBlockIndent(false); - setBracketIndent(false); - setBracketIndentVtk(false); + setBraceIndent(false); + setBraceIndentVtk(false); setNamespaceIndent(false); + setAfterParenIndent(false); setLabelIndent(false); setEmptyLineFill(false); setCStyle(); @@ -93,35 +94,35 @@ ASBeautifier::ASBeautifier(const ASBeautifier& other) : ASBase(other) { // these don't need to copy the stack - waitingBeautifierStack = NULL; - activeBeautifierStack = NULL; - waitingBeautifierStackLengthStack = NULL; - activeBeautifierStackLengthStack = NULL; + waitingBeautifierStack = nullptr; + activeBeautifierStack = nullptr; + waitingBeautifierStackLengthStack = nullptr; + activeBeautifierStackLengthStack = nullptr; // vector '=' operator performs a DEEP copy of all elements in the vector headerStack = new vector; *headerStack = *other.headerStack; tempStacks = copyTempStacks(other); - blockParenDepthStack = new vector; - *blockParenDepthStack = *other.blockParenDepthStack; + parenDepthStack = new vector; + *parenDepthStack = *other.parenDepthStack; blockStatementStack = new vector; *blockStatementStack = *other.blockStatementStack; parenStatementStack = new vector; *parenStatementStack = *other.parenStatementStack; - bracketBlockStateStack = new vector; - *bracketBlockStateStack = *other.bracketBlockStateStack; + braceBlockStateStack = new vector; + *braceBlockStateStack = *other.braceBlockStateStack; - inStatementIndentStack = new vector; - *inStatementIndentStack = *other.inStatementIndentStack; + continuationIndentStack = new vector; + *continuationIndentStack = *other.continuationIndentStack; - inStatementIndentStackSizeStack = new vector; - *inStatementIndentStackSizeStack = *other.inStatementIndentStackSizeStack; + continuationIndentStackSizeStack = new vector; + *continuationIndentStackSizeStack = *other.continuationIndentStackSizeStack; parenIndentStack = new vector; *parenIndentStack = *other.parenIndentStack; @@ -145,8 +146,8 @@ // variables set by ASFormatter // must also be updated in activeBeautifierStack inLineNumber = other.inLineNumber; - horstmannIndentInStatement = other.horstmannIndentInStatement; - nonInStatementBracket = other.nonInStatementBracket; + runInIndentContinuation = other.runInIndentContinuation; + nonInStatementBrace = other.nonInStatementBrace; objCColonAlignSubsequent = other.objCColonAlignSubsequent; lineCommentNoBeautify = other.lineCommentNoBeautify; isElseHeaderIndent = other.isElseHeaderIndent; @@ -175,10 +176,10 @@ isInAsmBlock = other.isInAsmBlock; isInComment = other.isInComment; isInPreprocessorComment = other.isInPreprocessorComment; - isInHorstmannComment = other.isInHorstmannComment; + isInRunInComment = other.isInRunInComment; isInCase = other.isInCase; isInQuestion = other.isInQuestion; - isInStatement = other.isInStatement; + isContinuation = other.isContinuation; isInHeader = other.isInHeader; isInTemplate = other.isInTemplate; isInDefine = other.isInDefine; @@ -199,13 +200,15 @@ isInEnum = other.isInEnum; isInEnumTypeID = other.isInEnumTypeID; isInLet = other.isInLet; + isInTrailingReturnType = other.isInTrailingReturnType; modifierIndent = other.modifierIndent; switchIndent = other.switchIndent; caseIndent = other.caseIndent; namespaceIndent = other.namespaceIndent; - bracketIndent = other.bracketIndent; - bracketIndentVtk = other.bracketIndentVtk; + braceIndent = other.braceIndent; + braceIndentVtk = other.braceIndentVtk; blockIndent = other.blockIndent; + shouldIndentAfterParen = other.shouldIndentAfterParen; labelIndent = other.labelIndent; isInConditional = other.isInConditional; isModeManuallySet = other.isModeManuallySet; @@ -218,12 +221,12 @@ blockCommentNoIndent = other.blockCommentNoIndent; blockCommentNoBeautify = other.blockCommentNoBeautify; previousLineProbationTab = other.previousLineProbationTab; - lineBeginsWithOpenBracket = other.lineBeginsWithOpenBracket; - lineBeginsWithCloseBracket = other.lineBeginsWithCloseBracket; + lineBeginsWithOpenBrace = other.lineBeginsWithOpenBrace; + lineBeginsWithCloseBrace = other.lineBeginsWithCloseBrace; lineBeginsWithComma = other.lineBeginsWithComma; lineIsCommentOnly = other.lineIsCommentOnly; lineIsLineCommentOnly = other.lineIsLineCommentOnly; - shouldIndentBrackettedLine = other.shouldIndentBrackettedLine; + shouldIndentBracedLine = other.shouldIndentBracedLine; isInSwitch = other.isInSwitch; foundPreCommandHeader = other.foundPreCommandHeader; foundPreCommandMacro = other.foundPreCommandMacro; @@ -233,7 +236,7 @@ indentCount = other.indentCount; spaceIndentCount = other.spaceIndentCount; spaceIndentObjCMethodAlignment = other.spaceIndentObjCMethodAlignment; - bracketPosObjCMethodAlignment = other.bracketPosObjCMethodAlignment; + bracePosObjCMethodAlignment = other.bracePosObjCMethodAlignment; colonIndentObjCMethodAlignment = other.colonIndentObjCMethodAlignment; lineOpeningBlocksNum = other.lineOpeningBlocksNum; lineClosingBlocksNum = other.lineClosingBlocksNum; @@ -245,10 +248,10 @@ tabLength = other.tabLength; continuationIndent = other.continuationIndent; blockTabCount = other.blockTabCount; - maxInStatementIndent = other.maxInStatementIndent; + maxContinuationIndent = other.maxContinuationIndent; classInitializerIndents = other.classInitializerIndents; templateDepth = other.templateDepth; - blockParenCount = other.blockParenCount; + squareBracketCount = other.squareBracketCount; prevFinalLineSpaceIndentCount = other.prevFinalLineSpaceIndentCount; prevFinalLineIndentCount = other.prevFinalLineIndentCount; defineIndentCount = other.defineIndentCount; @@ -271,12 +274,12 @@ deleteContainer(activeBeautifierStackLengthStack); deleteContainer(headerStack); deleteTempStacksContainer(tempStacks); - deleteContainer(blockParenDepthStack); + deleteContainer(parenDepthStack); deleteContainer(blockStatementStack); deleteContainer(parenStatementStack); - deleteContainer(bracketBlockStateStack); - deleteContainer(inStatementIndentStack); - deleteContainer(inStatementIndentStackSizeStack); + deleteContainer(braceBlockStateStack); + deleteContainer(continuationIndentStack); + deleteContainer(continuationIndentStackSizeStack); deleteContainer(parenIndentStack); deleteContainer(preprocIndentStack); } @@ -297,7 +300,7 @@ sourceIterator = iter; initVectors(); ASBase::init(getFileType()); - g_preprocessorCppExternCBracket = 0; + g_preprocessorCppExternCBrace = 0; initContainer(waitingBeautifierStack, new vector); initContainer(activeBeautifierStack, new vector); @@ -308,21 +311,21 @@ initContainer(headerStack, new vector); initTempStacksContainer(tempStacks, new vector*>); - tempStacks->push_back(new vector); + tempStacks->emplace_back(new vector); - initContainer(blockParenDepthStack, new vector); + initContainer(parenDepthStack, new vector); initContainer(blockStatementStack, new vector); initContainer(parenStatementStack, new vector); - initContainer(bracketBlockStateStack, new vector); - bracketBlockStateStack->push_back(true); - initContainer(inStatementIndentStack, new vector); - initContainer(inStatementIndentStackSizeStack, new vector); - inStatementIndentStackSizeStack->push_back(0); + initContainer(braceBlockStateStack, new vector); + braceBlockStateStack->push_back(true); + initContainer(continuationIndentStack, new vector); + initContainer(continuationIndentStackSizeStack, new vector); + continuationIndentStackSizeStack->emplace_back(0); initContainer(parenIndentStack, new vector); initContainer(preprocIndentStack, new vector >); - previousLastLineHeader = NULL; - currentHeader = NULL; + previousLastLineHeader = nullptr; + currentHeader = nullptr; isInQuote = false; isInVerbatimQuote = false; @@ -332,8 +335,8 @@ isInAsmBlock = false; isInComment = false; isInPreprocessorComment = false; - isInHorstmannComment = false; - isInStatement = false; + isInRunInComment = false; + isContinuation = false; isInCase = false; isInQuestion = false; isIndentModeOff = false; @@ -354,16 +357,17 @@ isInHeader = false; isInTemplate = false; isInConditional = false; + isInTrailingReturnType = false; indentCount = 0; spaceIndentCount = 0; spaceIndentObjCMethodAlignment = 0; - bracketPosObjCMethodAlignment = 0; + bracePosObjCMethodAlignment = 0; colonIndentObjCMethodAlignment = 0; lineOpeningBlocksNum = 0; lineClosingBlocksNum = 0; templateDepth = 0; - blockParenCount = 0; + squareBracketCount = 0; parenDepth = 0; blockTabCount = 0; prevFinalLineSpaceIndentCount = 0; @@ -375,8 +379,8 @@ prevNonLegalCh = '{'; currentNonLegalCh = '{'; quoteChar = ' '; - probationHeader = NULL; - lastLineHeader = NULL; + probationHeader = nullptr; + lastLineHeader = nullptr; backslashEndsPrevLine = false; lineOpensWithLineComment = false; lineOpensWithComment = false; @@ -389,12 +393,12 @@ blockCommentNoIndent = false; blockCommentNoBeautify = false; previousLineProbationTab = false; - lineBeginsWithOpenBracket = false; - lineBeginsWithCloseBracket = false; + lineBeginsWithOpenBrace = false; + lineBeginsWithCloseBrace = false; lineBeginsWithComma = false; lineIsCommentOnly = false; lineIsLineCommentOnly = false; - shouldIndentBrackettedLine = true; + shouldIndentBracedLine = true; isInSwitch = false; foundPreCommandHeader = false; foundPreCommandMacro = false; @@ -407,8 +411,8 @@ isInIndentableStruct = false; isInIndentablePreproc = false; inLineNumber = 0; - horstmannIndentInStatement = 0; - nonInStatementBracket = 0; + runInIndentContinuation = 0; + nonInStatementBrace = 0; objCColonAlignSubsequent = 0; } @@ -531,9 +535,17 @@ * * @param max maximum indentation length. */ +void ASBeautifier::setMaxContinuationIndentLength(int max) +{ + maxContinuationIndent = max; +} + +// retained for compatibility with release 2.06 +// "MaxInStatementIndent" has been changed to "MaxContinuationIndent" in 3.0 +// it is referenced only by the old "MaxInStatementIndent" options void ASBeautifier::setMaxInStatementIndentLength(int max) { - maxInStatementIndent = max; + setMaxContinuationIndentLength(max); } /** @@ -563,27 +575,27 @@ } /** - * set the state of the bracket indent option. If true, brackets will + * set the state of the brace indent option. If true, braces will * be indented one additional indent. * * @param state state of option. */ -void ASBeautifier::setBracketIndent(bool state) +void ASBeautifier::setBraceIndent(bool state) { - bracketIndent = state; + braceIndent = state; } /** -* set the state of the bracket indent VTK option. If true, brackets will -* be indented one additional indent, except for the opening bracket. +* set the state of the brace indent VTK option. If true, braces will +* be indented one additional indent, except for the opening brace. * * @param state state of option. */ -void ASBeautifier::setBracketIndentVtk(bool state) +void ASBeautifier::setBraceIndentVtk(bool state) { // need to set both of these - setBracketIndent(state); - bracketIndentVtk = state; + setBraceIndent(state); + braceIndentVtk = state; } /** @@ -653,6 +665,16 @@ namespaceIndent = state; } +/** +* set the state of the indent after parens option. +* +* @param state state of option. +*/ +void ASBeautifier::setAfterParenIndent(bool state) +{ + shouldIndentAfterParen = state; +} + /** * set the state of the label indentation option. * If true, labels will be indented one indent LESS than the @@ -768,13 +790,13 @@ } /** - * get the state of the bracket indentation option. + * get the state of the brace indentation option. * - * @return state of bracketIndent option. + * @return state of braceIndent option. */ -bool ASBeautifier::getBracketIndent() const +bool ASBeautifier::getBraceIndent() const { - return bracketIndent; + return braceIndent; } /** @@ -880,17 +902,17 @@ string line; bool isInQuoteContinuation = isInVerbatimQuote || haveLineContinuationChar; - currentHeader = NULL; - lastLineHeader = NULL; + currentHeader = nullptr; + lastLineHeader = nullptr; blockCommentNoBeautify = blockCommentNoIndent; isInClass = false; isInSwitch = false; - lineBeginsWithOpenBracket = false; - lineBeginsWithCloseBracket = false; + lineBeginsWithOpenBrace = false; + lineBeginsWithCloseBrace = false; lineBeginsWithComma = false; lineIsCommentOnly = false; lineIsLineCommentOnly = false; - shouldIndentBrackettedLine = true; + shouldIndentBracedLine = true; isInAsmOneLine = false; lineOpensWithLineComment = false; lineOpensWithComment = false; @@ -928,14 +950,14 @@ trimEnd++; if (trimEnd < line.length()) line.erase(trimEnd); - // does a bracket open the line + // does a brace open the line size_t firstChar = line.find_first_not_of(" \t"); if (firstChar != string::npos) { if (line[firstChar] == '{') - lineBeginsWithOpenBracket = true; + lineBeginsWithOpenBrace = true; else if (line[firstChar] == '}') - lineBeginsWithCloseBracket = true; + lineBeginsWithCloseBrace = true; else if (line[firstChar] == ',') lineBeginsWithComma = true; } @@ -946,9 +968,9 @@ if (line.length() > 0) { if (line[0] == '{') - lineBeginsWithOpenBracket = true; + lineBeginsWithOpenBrace = true; else if (line[0] == '}') - lineBeginsWithCloseBracket = true; + lineBeginsWithCloseBrace = true; else if (line[0] == ',') lineBeginsWithComma = true; else if (line.compare(0, 2, "//") == 0) @@ -960,16 +982,16 @@ } } - isInHorstmannComment = false; + isInRunInComment = false; size_t j = line.find_first_not_of(" \t{"); if (j != string::npos && line.compare(j, 2, "//") == 0) lineOpensWithLineComment = true; if (j != string::npos && line.compare(j, 2, "/*") == 0) { lineOpensWithComment = true; size_t k = line.find_first_not_of(" \t"); if (k != string::npos && line.compare(k, 1, "{") == 0) - isInHorstmannComment = true; + isInRunInComment = true; } } @@ -984,8 +1006,19 @@ if (backslashEndsPrevLine) { backslashEndsPrevLine = false; - isInDefine = false; - isInDefineDefinition = false; + // check if this line ends a multi-line #define + // if so, remove the #define's cloned beautifier from the active + // beautifier stack and delete it. + if (isInDefineDefinition && !isInDefine) + { + isInDefineDefinition = false; + if (!activeBeautifierStack->empty()) + { + ASBeautifier* defineBeautifier = activeBeautifierStack->back(); + activeBeautifierStack->pop_back(); + delete defineBeautifier; + } + } } if (emptyLineFill && !isInQuoteContinuation) { @@ -1056,11 +1089,11 @@ if (preproc.length() >= 2 && preproc.substr(0, 2) == "if") // #if, #ifdef, #ifndef { pair entry; // indentCount, spaceIndentCount - if (!isInDefine && activeBeautifierStack != NULL && !activeBeautifierStack->empty()) + if (!isInDefine && activeBeautifierStack != nullptr && !activeBeautifierStack->empty()) entry = activeBeautifierStack->back()->computePreprocessorIndent(); else entry = computePreprocessorIndent(); - preprocIndentStack->push_back(entry); + preprocIndentStack->emplace_back(entry); indentedLine = preLineWS(preprocIndentStack->back().first, preprocIndentStack->back().second) + line; return getIndentedLineReturn(indentedLine, originalLine); @@ -1100,6 +1133,9 @@ if (!backslashEndsPrevLine && isInDefineDefinition && !isInDefine) { isInDefineDefinition = false; + // this could happen with invalid input + if (activeBeautifierStack->empty()) + return originalLine; ASBeautifier* defineBeautifier = activeBeautifierStack->back(); activeBeautifierStack->pop_back(); @@ -1116,11 +1152,11 @@ // if there exists any worker beautifier in the activeBeautifierStack, // then use it instead of me to indent the current line. // variables set by ASFormatter must be updated. - if (!isInDefine && activeBeautifierStack != NULL && !activeBeautifierStack->empty()) + if (!isInDefine && activeBeautifierStack != nullptr && !activeBeautifierStack->empty()) { activeBeautifierStack->back()->inLineNumber = inLineNumber; - activeBeautifierStack->back()->horstmannIndentInStatement = horstmannIndentInStatement; - activeBeautifierStack->back()->nonInStatementBracket = nonInStatementBracket; + activeBeautifierStack->back()->runInIndentContinuation = runInIndentContinuation; + activeBeautifierStack->back()->nonInStatementBrace = nonInStatementBrace; activeBeautifierStack->back()->objCColonAlignSubsequent = objCColonAlignSubsequent; activeBeautifierStack->back()->lineCommentNoBeautify = lineCommentNoBeautify; activeBeautifierStack->back()->isElseHeaderIndent = isElseHeaderIndent; @@ -1140,9 +1176,9 @@ // The header in the header stack will be deleted by a one-line block. bool isInExtraHeaderIndent = false; if (!headerStack->empty() - && lineBeginsWithOpenBracket - && (headerStack->back() != &AS_OPEN_BRACKET - || probationHeader != NULL)) + && lineBeginsWithOpenBrace + && (headerStack->back() != &AS_OPEN_BRACE + || probationHeader != nullptr)) isInExtraHeaderIndent = true; size_t iPrelim = headerStack->size(); @@ -1170,8 +1206,8 @@ string preproc = trim(line.substr(1)); if (preproc.compare(0, 6, "define") == 0) { - if (!inStatementIndentStack->empty() - && inStatementIndentStack->back() > 0) + if (!continuationIndentStack->empty() + && continuationIndentStack->back() > 0) { defineIndentCount = indentCount; } @@ -1200,7 +1236,7 @@ prevFinalLineSpaceIndentCount = spaceIndentCount; prevFinalLineIndentCount = indentCount; - if (lastLineHeader != NULL) + if (lastLineHeader != nullptr) previousLastLineHeader = lastLineHeader; if ((lineIsLineCommentOnly || lineIsCommentOnly) @@ -1210,10 +1246,10 @@ return indentedLine; } -string& ASBeautifier::getIndentedLineReturn(string& newLine, const string& originalLine) const +const string& ASBeautifier::getIndentedLineReturn(const string& newLine, const string& originalLine) const { if (isIndentModeOff) - return const_cast(originalLine); + return originalLine; return newLine; } @@ -1245,32 +1281,37 @@ } /** - * register an in-statement indent. + * register a continuation indent. */ -void ASBeautifier::registerInStatementIndent(const string& line, int i, int spaceIndentCount_, - int tabIncrementIn, int minIndent, bool updateParenStack) +void ASBeautifier::registerContinuationIndent(const string& line, int i, int spaceIndentCount_, + int tabIncrementIn, int minIndent, bool updateParenStack) { + assert(i >= -1); int remainingCharNum = line.length() - i; int nextNonWSChar = getNextProgramCharDistance(line, i); - // if indent is around the last char in the line, indent with the continuation indent - if (nextNonWSChar == remainingCharNum) + // if indent is around the last char in the line OR indent-after-paren is requested, + // indent with the continuation indent + if (nextNonWSChar == remainingCharNum || shouldIndentAfterParen) { int previousIndent = spaceIndentCount_; - if (!inStatementIndentStack->empty()) - previousIndent = inStatementIndentStack->back(); + if (!continuationIndentStack->empty()) + previousIndent = continuationIndentStack->back(); int currIndent = continuationIndent * indentLength + previousIndent; - if (currIndent > maxInStatementIndent - && line[i] != '{') + if (currIndent > maxContinuationIndent && line[i] != '{') currIndent = indentLength * 2 + spaceIndentCount_; - inStatementIndentStack->push_back(currIndent); + continuationIndentStack->emplace_back(currIndent); if (updateParenStack) - parenIndentStack->push_back(previousIndent); + parenIndentStack->emplace_back(previousIndent); return; } if (updateParenStack) - parenIndentStack->push_back(i + spaceIndentCount_ - horstmannIndentInStatement); + { + parenIndentStack->emplace_back(i + spaceIndentCount_ - runInIndentContinuation); + if (parenIndentStack->back() < 0) + parenIndentStack->back() = 0; + } int tabIncrement = tabIncrementIn; @@ -1281,35 +1322,36 @@ tabIncrement += convertTabToSpaces(j, tabIncrement); } - int inStatementIndent = i + nextNonWSChar + spaceIndentCount_ + tabIncrement; + int continuationIndentCount = i + nextNonWSChar + spaceIndentCount_ + tabIncrement; // check for run-in statement if (i > 0 && line[0] == '{') - inStatementIndent -= indentLength; + continuationIndentCount -= indentLength; - if (inStatementIndent < minIndent) - inStatementIndent = minIndent + spaceIndentCount_; + if (continuationIndentCount < minIndent) + continuationIndentCount = minIndent + spaceIndentCount_; // this is not done for an in-statement array - if (inStatementIndent > maxInStatementIndent + if (continuationIndentCount > maxContinuationIndent && !(prevNonLegalCh == '=' && currentNonLegalCh == '{')) - inStatementIndent = indentLength * 2 + spaceIndentCount_; + continuationIndentCount = indentLength * 2 + spaceIndentCount_; - if (!inStatementIndentStack->empty() - && inStatementIndent < inStatementIndentStack->back()) - inStatementIndent = inStatementIndentStack->back(); + if (!continuationIndentStack->empty() + && continuationIndentCount < continuationIndentStack->back()) + continuationIndentCount = continuationIndentStack->back(); // the block opener is not indented for a NonInStatementArray - if (isNonInStatementArray && !isInEnum && !bracketBlockStateStack->empty() && bracketBlockStateStack->back()) - inStatementIndent = 0; + if ((isNonInStatementArray && i >= 0 && line[i] == '{') + && !isInEnum && !braceBlockStateStack->empty() && braceBlockStateStack->back()) + continuationIndentCount = 0; - inStatementIndentStack->push_back(inStatementIndent); + continuationIndentStack->emplace_back(continuationIndentCount); } /** -* Register an in-statement indent for a class header or a class initializer colon. +* Register a continuation indent for a class header or a class initializer colon. */ -void ASBeautifier::registerInStatementIndentColon(const string& line, int i, int tabIncrementIn) +void ASBeautifier::registerContinuationIndentColon(const string& line, int i, int tabIncrementIn) { assert(line[i] == ':'); assert(isInClassInitializer || isInClassHeaderTab); @@ -1319,11 +1361,11 @@ if (firstChar == (size_t) i) // firstChar is ':' { size_t firstWord = line.find_first_not_of(" \t", firstChar + 1); - if (firstChar != string::npos) + if (firstWord != string::npos) { - int inStatementIndent = firstWord + spaceIndentCount + tabIncrementIn; - inStatementIndentStack->push_back(inStatementIndent); - isInStatement = true; + int continuationIndentCount = firstWord + spaceIndentCount + tabIncrementIn; + continuationIndentStack->emplace_back(continuationIndentCount); + isContinuation = true; } } } @@ -1389,72 +1431,14 @@ return charDistance; } -// check if a specific line position contains a header. -const string* ASBeautifier::findHeader(const string& line, int i, - const vector* possibleHeaders) const -{ - assert(isCharPotentialHeader(line, i)); - // check the word - size_t maxHeaders = possibleHeaders->size(); - for (size_t p = 0; p < maxHeaders; p++) - { - const string* header = (*possibleHeaders)[p]; - const size_t wordEnd = i + header->length(); - if (wordEnd > line.length()) - continue; - int result = (line.compare(i, header->length(), *header)); - if (result > 0) - continue; - if (result < 0) - break; - // check that this is not part of a longer word - if (wordEnd == line.length()) - return header; - if (isLegalNameChar(line[wordEnd])) - continue; - const char peekChar = peekNextChar(line, wordEnd - 1); - // is not a header if part of a definition - if (peekChar == ',' || peekChar == ')') - break; - // the following accessor definitions are NOT headers - // goto default; is NOT a header - // default(int) keyword in C# is NOT a header - else if ((header == &AS_GET || header == &AS_SET || header == &AS_DEFAULT) - && (peekChar == ';' || peekChar == '(' || peekChar == '=')) - break; - return header; - } - return NULL; -} - -// check if a specific line position contains an operator. -const string* ASBeautifier::findOperator(const string& line, int i, - const vector* possibleOperators) const -{ - assert(isCharPotentialOperator(line[i])); - // find the operator in the vector - // the vector contains the LONGEST operators first - // must loop thru the entire vector - size_t maxOperators = possibleOperators->size(); - for (size_t p = 0; p < maxOperators; p++) - { - const size_t wordEnd = i + (*(*possibleOperators)[p]).length(); - if (wordEnd > line.length()) - continue; - if (line.compare(i, (*(*possibleOperators)[p]).length(), *(*possibleOperators)[p]) == 0) - return (*possibleOperators)[p]; - } - return NULL; -} - /** * find the index number of a string element in a container of strings * * @return the index number of element in the container. -1 if element not found. * @param container a vector of strings. * @param element the element to find . */ -int ASBeautifier::indexOf(vector& container, const string* element) const +int ASBeautifier::indexOf(const vector& container, const string* element) const { vector::const_iterator where; @@ -1532,7 +1516,7 @@ { vector* newVec = new vector; *newVec = **iter; - tempStacksNew->push_back(newVec); + tempStacksNew->emplace_back(newVec); } return tempStacksNew; } @@ -1560,11 +1544,11 @@ template void ASBeautifier::deleteContainer(T& container) { - if (container != NULL) + if (container != nullptr) { container->clear(); delete (container); - container = NULL; + container = nullptr; } } @@ -1576,7 +1560,7 @@ */ void ASBeautifier::deleteBeautifierContainer(vector*& container) { - if (container != NULL) + if (container != nullptr) { vector::iterator iter = container->begin(); while (iter < container->end()) @@ -1586,7 +1570,7 @@ } container->clear(); delete (container); - container = NULL; + container = nullptr; } } @@ -1597,7 +1581,7 @@ */ void ASBeautifier::deleteTempStacksContainer(vector*>*& container) { - if (container != NULL) + if (container != nullptr) { vector*>::iterator iter = container->begin(); while (iter < container->end()) @@ -1607,7 +1591,7 @@ } container->clear(); delete (container); - container = NULL; + container = nullptr; } } @@ -1620,7 +1604,7 @@ { // since the ASFormatter object is never deleted, // the existing vectors must be deleted before creating new ones - if (container != NULL) + if (container != nullptr) deleteContainer(container); container = value; } @@ -1633,7 +1617,7 @@ void ASBeautifier::initTempStacksContainer(vector*>*& container, vector*>* value) { - if (container != NULL) + if (container != nullptr) deleteTempStacksContainer(container); container = value; } @@ -1749,7 +1733,7 @@ * * @return is the index to the previous word (the in statement indent). */ -int ASBeautifier::getInStatementIndentAssign(const string& line, size_t currPos) const +int ASBeautifier::getContinuationIndentAssign(const string& line, size_t currPos) const { assert(line[currPos] == '='); @@ -1764,7 +1748,7 @@ int start; // start of the previous word for (start = end; start > -1; start--) { - if (!isLegalNameChar(line[start]) || line[start] == '.') + if (!isLegalNameChar(line[start])) break; } start++; @@ -1777,7 +1761,7 @@ * * @return is the indent to the second word on the line (the in statement indent). */ -int ASBeautifier::getInStatementIndentComma(const string& line, size_t currPos) const +int ASBeautifier::getContinuationIndentComma(const string& line, size_t currPos) const { assert(line[currPos] == ','); @@ -1894,15 +1878,15 @@ // check for " #if defined(__cplusplus)" size_t charNum = 2; charNum = preproc.find_first_not_of(" \t", charNum); - if (preproc.compare(charNum, 7, "defined") == 0) + if (charNum != string::npos && preproc.compare(charNum, 7, "defined") == 0) { charNum += 7; charNum = preproc.find_first_not_of(" \t", charNum); - if (preproc.compare(charNum, 1, "(") == 0) + if (charNum != string::npos && preproc.compare(charNum, 1, "(") == 0) { ++charNum; charNum = preproc.find_first_not_of(" \t", charNum); - if (preproc.compare(charNum, 11, "__cplusplus") == 0) + if (charNum != string::npos && preproc.compare(charNum, 11, "__cplusplus") == 0) return true; } } @@ -1934,14 +1918,14 @@ return true; } -void ASBeautifier::popLastInStatementIndent() +void ASBeautifier::popLastContinuationIndent() { - assert(!inStatementIndentStackSizeStack->empty()); - int previousIndentStackSize = inStatementIndentStackSizeStack->back(); - if (inStatementIndentStackSizeStack->size() > 1) - inStatementIndentStackSizeStack->pop_back(); - while (previousIndentStackSize < (int) inStatementIndentStack->size()) - inStatementIndentStack->pop_back(); + assert(!continuationIndentStackSizeStack->empty()); + int previousIndentStackSize = continuationIndentStackSizeStack->back(); + if (continuationIndentStackSizeStack->size() > 1) + continuationIndentStackSizeStack->pop_back(); + while (previousIndentStackSize < (int) continuationIndentStack->size()) + continuationIndentStack->pop_back(); } // for unit testing @@ -1970,7 +1954,7 @@ // push a new beautifier into the active stack // this beautifier will be used for the indentation of this define ASBeautifier* defineBeautifier = new ASBeautifier(*this); - activeBeautifierStack->push_back(defineBeautifier); + activeBeautifierStack->emplace_back(defineBeautifier); } else { @@ -1980,39 +1964,39 @@ } else if (preproc.length() >= 2 && preproc.substr(0, 2) == "if") { - if (isPreprocessorConditionalCplusplus(line) && !g_preprocessorCppExternCBracket) - g_preprocessorCppExternCBracket = 1; + if (isPreprocessorConditionalCplusplus(line) && !g_preprocessorCppExternCBrace) + g_preprocessorCppExternCBrace = 1; // push a new beautifier into the stack waitingBeautifierStackLengthStack->push_back(waitingBeautifierStack->size()); activeBeautifierStackLengthStack->push_back(activeBeautifierStack->size()); if (activeBeautifierStackLengthStack->back() == 0) - waitingBeautifierStack->push_back(new ASBeautifier(*this)); + waitingBeautifierStack->emplace_back(new ASBeautifier(*this)); else - waitingBeautifierStack->push_back(new ASBeautifier(*activeBeautifierStack->back())); + waitingBeautifierStack->emplace_back(new ASBeautifier(*activeBeautifierStack->back())); } else if (preproc == "else") { - if (waitingBeautifierStack && !waitingBeautifierStack->empty()) + if ((waitingBeautifierStack != nullptr) && !waitingBeautifierStack->empty()) { // MOVE current waiting beautifier to active stack. - activeBeautifierStack->push_back(waitingBeautifierStack->back()); + activeBeautifierStack->emplace_back(waitingBeautifierStack->back()); waitingBeautifierStack->pop_back(); } } else if (preproc == "elif") { - if (waitingBeautifierStack && !waitingBeautifierStack->empty()) + if ((waitingBeautifierStack != nullptr) && !waitingBeautifierStack->empty()) { // append a COPY current waiting beautifier to active stack, WITHOUT deleting the original. - activeBeautifierStack->push_back(new ASBeautifier(*(waitingBeautifierStack->back()))); + activeBeautifierStack->emplace_back(new ASBeautifier(*(waitingBeautifierStack->back()))); } } else if (preproc == "endif") { int stackLength = 0; - ASBeautifier* beautifier = NULL; + ASBeautifier* beautifier = nullptr; - if (waitingBeautifierStackLengthStack != NULL && !waitingBeautifierStackLengthStack->empty()) + if (waitingBeautifierStackLengthStack != nullptr && !waitingBeautifierStackLengthStack->empty()) { stackLength = waitingBeautifierStackLengthStack->back(); waitingBeautifierStackLengthStack->pop_back(); @@ -2047,11 +2031,11 @@ spaceIndentCount = 0; isInClassHeaderTab = false; - if (isInObjCMethodDefinition && !inStatementIndentStack->empty()) - spaceIndentObjCMethodAlignment = inStatementIndentStack->back(); + if (isInObjCMethodDefinition && !continuationIndentStack->empty()) + spaceIndentObjCMethodAlignment = continuationIndentStack->back(); - if (!inStatementIndentStack->empty()) - spaceIndentCount = inStatementIndentStack->back(); + if (!continuationIndentStack->empty()) + spaceIndentCount = continuationIndentStack->back(); for (size_t i = 0; i < headerStack->size(); i++) { @@ -2070,19 +2054,19 @@ || (*headerStack)[i] == &AS_STATIC)) ++indentCount; } - else if (!(i > 0 && (*headerStack)[i - 1] != &AS_OPEN_BRACKET - && (*headerStack)[i] == &AS_OPEN_BRACKET)) + else if (!(i > 0 && (*headerStack)[i - 1] != &AS_OPEN_BRACE + && (*headerStack)[i] == &AS_OPEN_BRACE)) ++indentCount; if (!isJavaStyle() && !namespaceIndent && i > 0 && ((*headerStack)[i - 1] == &AS_NAMESPACE || (*headerStack)[i - 1] == &AS_MODULE) - && (*headerStack)[i] == &AS_OPEN_BRACKET) + && (*headerStack)[i] == &AS_OPEN_BRACE) --indentCount; if (isCStyle() && i >= 1 && (*headerStack)[i - 1] == &AS_CLASS - && (*headerStack)[i] == &AS_OPEN_BRACKET) + && (*headerStack)[i] == &AS_OPEN_BRACE) { if (classIndent) ++indentCount; @@ -2092,7 +2076,7 @@ // is the switchIndent option is on, indent switch statements an additional indent. else if (switchIndent && i > 1 && (*headerStack)[i - 1] == &AS_SWITCH - && (*headerStack)[i] == &AS_OPEN_BRACKET) + && (*headerStack)[i] == &AS_OPEN_BRACE) { ++indentCount; isInSwitch = true; @@ -2106,14 +2090,14 @@ isInClassHeaderTab = true; if (lineOpensWithLineComment || lineStartsInComment || lineOpensWithComment) { - if (!lineBeginsWithOpenBracket) + if (!lineBeginsWithOpenBrace) --indentCount; - if (!inStatementIndentStack->empty()) - spaceIndentCount -= inStatementIndentStack->back(); + if (!continuationIndentStack->empty()) + spaceIndentCount -= continuationIndentStack->back(); } else if (blockIndent) { - if (!lineBeginsWithOpenBracket) + if (!lineBeginsWithOpenBrace) ++indentCount; } } @@ -2123,52 +2107,52 @@ indentCount += classInitializerIndents; } - if (isInEnum && lineBeginsWithComma && !inStatementIndentStack->empty()) + if (isInEnum && lineBeginsWithComma && !continuationIndentStack->empty()) { // unregister '=' indent from the previous line - inStatementIndentStack->pop_back(); - isInStatement = false; + continuationIndentStack->pop_back(); + isContinuation = false; spaceIndentCount = 0; } // Objective-C interface continuation line if (isInObjCInterface) ++indentCount; - // unindent a class closing bracket... + // unindent a class closing brace... if (!lineStartsInComment && isCStyle() && isInClass && classIndent && headerStack->size() >= 2 && (*headerStack)[headerStack->size() - 2] == &AS_CLASS - && (*headerStack)[headerStack->size() - 1] == &AS_OPEN_BRACKET - && lineBeginsWithCloseBracket - && bracketBlockStateStack->back()) + && (*headerStack)[headerStack->size() - 1] == &AS_OPEN_BRACE + && lineBeginsWithCloseBrace + && braceBlockStateStack->back()) --indentCount; - // unindent an indented switch closing bracket... + // unindent an indented switch closing brace... else if (!lineStartsInComment && isInSwitch && switchIndent && headerStack->size() >= 2 && (*headerStack)[headerStack->size() - 2] == &AS_SWITCH - && (*headerStack)[headerStack->size() - 1] == &AS_OPEN_BRACKET - && lineBeginsWithCloseBracket) + && (*headerStack)[headerStack->size() - 1] == &AS_OPEN_BRACE + && lineBeginsWithCloseBrace) --indentCount; - // handle special case of horstmann comment in an indented class statement + // handle special case of run-in comment in an indented class statement if (isInClass && classIndent - && isInHorstmannComment + && isInRunInComment && !lineOpensWithComment && headerStack->size() > 1 && (*headerStack)[headerStack->size() - 2] == &AS_CLASS) --indentCount; if (isInConditional) --indentCount; - if (g_preprocessorCppExternCBracket >= 4) + if (g_preprocessorCppExternCBrace >= 4) --indentCount; } @@ -2179,37 +2163,37 @@ // unindent a one-line statement in a header indent if (!blockIndent - && lineBeginsWithOpenBracket + && lineBeginsWithOpenBrace && headerStack->size() < iPrelim && isInExtraHeaderIndent && (lineOpeningBlocksNum > 0 && lineOpeningBlocksNum <= lineClosingBlocksNum) - && shouldIndentBrackettedLine) + && shouldIndentBracedLine) --indentCount; /* * if '{' doesn't follow an immediately previous '{' in the headerStack * (but rather another header such as "for" or "if", then unindent it * by one indentation relative to its block. */ else if (!blockIndent - && lineBeginsWithOpenBracket + && lineBeginsWithOpenBrace && !(lineOpeningBlocksNum > 0 && lineOpeningBlocksNum <= lineClosingBlocksNum) - && (headerStack->size() > 1 && (*headerStack)[headerStack->size() - 2] != &AS_OPEN_BRACKET) - && shouldIndentBrackettedLine) + && (headerStack->size() > 1 && (*headerStack)[headerStack->size() - 2] != &AS_OPEN_BRACE) + && shouldIndentBracedLine) --indentCount; // must check one less in headerStack if more than one header on a line (allow-addins)... else if (headerStack->size() > iPrelim + 1 && !blockIndent - && lineBeginsWithOpenBracket + && lineBeginsWithOpenBrace && !(lineOpeningBlocksNum > 0 && lineOpeningBlocksNum <= lineClosingBlocksNum) - && (headerStack->size() > 2 && (*headerStack)[headerStack->size() - 3] != &AS_OPEN_BRACKET) - && shouldIndentBrackettedLine) + && (headerStack->size() > 2 && (*headerStack)[headerStack->size() - 3] != &AS_OPEN_BRACE) + && shouldIndentBracedLine) --indentCount; - // unindent a closing bracket... - else if (lineBeginsWithCloseBracket - && shouldIndentBrackettedLine) + // unindent a closing brace... + else if (lineBeginsWithCloseBrace + && shouldIndentBracedLine) --indentCount; // correctly indent one-line-blocks... @@ -2221,38 +2205,38 @@ if (indentCount < 0) indentCount = 0; - // take care of extra bracket indentation option... + // take care of extra brace indentation option... if (!lineStartsInComment - && bracketIndent - && shouldIndentBrackettedLine - && (lineBeginsWithOpenBracket || lineBeginsWithCloseBracket)) + && braceIndent + && shouldIndentBracedLine + && (lineBeginsWithOpenBrace || lineBeginsWithCloseBrace)) { - if (!bracketIndentVtk) + if (!braceIndentVtk) ++indentCount; else { - // determine if a style VTK bracket is indented - bool haveUnindentedBracket = false; + // determine if a style VTK brace is indented + bool haveUnindentedBrace = false; for (size_t i = 0; i < headerStack->size(); i++) { if (((*headerStack)[i] == &AS_NAMESPACE || (*headerStack)[i] == &AS_MODULE || (*headerStack)[i] == &AS_CLASS || (*headerStack)[i] == &AS_STRUCT) && i + 1 < headerStack->size() - && (*headerStack)[i + 1] == &AS_OPEN_BRACKET) + && (*headerStack)[i + 1] == &AS_OPEN_BRACE) i++; - else if (lineBeginsWithOpenBracket) + else if (lineBeginsWithOpenBrace) { - // don't double count the current bracket + // don't double count the current brace if (i + 1 < headerStack->size() - && (*headerStack)[i] == &AS_OPEN_BRACKET) - haveUnindentedBracket = true; + && (*headerStack)[i] == &AS_OPEN_BRACE) + haveUnindentedBrace = true; } - else if ((*headerStack)[i] == &AS_OPEN_BRACKET) - haveUnindentedBracket = true; + else if ((*headerStack)[i] == &AS_OPEN_BRACE) + haveUnindentedBrace = true; } // end of for loop - if (haveUnindentedBracket) + if (haveUnindentedBrace) ++indentCount; } } @@ -2268,7 +2252,7 @@ assert(isElseHeaderIndent && !tempStacks->empty()); int indentCountIncrement = 0; vector* lastTempStack = tempStacks->back(); - if (lastTempStack != NULL) + if (lastTempStack != nullptr) { for (size_t i = 0; i < lastTempStack->size(); i++) { @@ -2305,24 +2289,24 @@ if (shouldAlignMethodColon && objCColonAlignSubsequent != -1) { string convertedLine = getIndentedSpaceEquivalent(line_); - colonIndentObjCMethodAlignment = convertedLine.find(':'); + colonIndentObjCMethodAlignment = findObjCColonAlignment(convertedLine); int objCColonAlignSubsequentIndent = objCColonAlignSubsequent + indentLength; if (objCColonAlignSubsequentIndent > colonIndentObjCMethodAlignment) colonIndentObjCMethodAlignment = objCColonAlignSubsequentIndent; } - else if (inStatementIndentStack->empty() - || inStatementIndentStack->back() == 0) + else if (continuationIndentStack->empty() + || continuationIndentStack->back() == 0) { - inStatementIndentStack->push_back(indentLength); - isInStatement = true; + continuationIndentStack->emplace_back(indentLength); + isContinuation = true; } } // set indent for last definition line - else if (!lineBeginsWithOpenBracket) + else if (!lineBeginsWithOpenBrace) { if (shouldAlignMethodColon) spaceIndentCount = computeObjCColonAlignment(line_, colonIndentObjCMethodAlignment); - else if (inStatementIndentStack->empty()) + else if (continuationIndentStack->empty()) spaceIndentCount = spaceIndentObjCMethodAlignment; } } @@ -2336,22 +2320,22 @@ { isInObjCMethodCallFirst = false; string convertedLine = getIndentedSpaceEquivalent(line_); - bracketPosObjCMethodAlignment = convertedLine.find('['); + bracePosObjCMethodAlignment = convertedLine.find('['); keywordIndentObjCMethodAlignment = - getObjCFollowingKeyword(convertedLine, bracketPosObjCMethodAlignment); - colonIndentObjCMethodAlignment = convertedLine.find(':'); + getObjCFollowingKeyword(convertedLine, bracePosObjCMethodAlignment); + colonIndentObjCMethodAlignment = findObjCColonAlignment(convertedLine); if (colonIndentObjCMethodAlignment >= 0) { int objCColonAlignSubsequentIndent = objCColonAlignSubsequent + indentLength; if (objCColonAlignSubsequentIndent > colonIndentObjCMethodAlignment) colonIndentObjCMethodAlignment = objCColonAlignSubsequentIndent; - if (lineBeginsWithOpenBracket) + if (lineBeginsWithOpenBrace) colonIndentObjCMethodAlignment -= indentLength; } } else { - if (line_.find(':') != string::npos) + if (findObjCColonAlignment(line_) != -1) { if (colonIndentObjCMethodAlignment < 0) spaceIndentCount += computeObjCColonAlignment(line_, objCColonAlignSubsequent); @@ -2373,13 +2357,13 @@ { isInObjCMethodCallFirst = false; string convertedLine = getIndentedSpaceEquivalent(line_); - bracketPosObjCMethodAlignment = convertedLine.find('['); + bracePosObjCMethodAlignment = convertedLine.find('['); keywordIndentObjCMethodAlignment = - getObjCFollowingKeyword(convertedLine, bracketPosObjCMethodAlignment); + getObjCFollowingKeyword(convertedLine, bracePosObjCMethodAlignment); } else { - if (spaceIndentCount < keywordIndentObjCMethodAlignment + bracketPosObjCMethodAlignment) + if (spaceIndentCount < keywordIndentObjCMethodAlignment + bracePosObjCMethodAlignment) spaceIndentCount += keywordIndentObjCMethodAlignment; } } @@ -2396,8 +2380,36 @@ colonIndentObjCMethodAlignment = 0; isInObjCMethodDefinition = false; isImmediatelyPostObjCMethodDefinition = false; - if (!inStatementIndentStack->empty()) - inStatementIndentStack->pop_back(); + if (!continuationIndentStack->empty()) + continuationIndentStack->pop_back(); +} + +/** + * Find the first alignment colon on a line. + * Ternary operators (?) are bypassed. + */ +int ASBeautifier::findObjCColonAlignment(const string& line) const +{ + bool haveTernary = false; + for (size_t i = 0; i < line.length(); i++) + { + i = line.find_first_of(":?", i); + if (i == string::npos) + break; + + if (line[i] == '?') + { + haveTernary = true; + continue; + } + if (haveTernary) + { + haveTernary = false; + continue; + } + return i; + } + return -1; } /** @@ -2408,19 +2420,22 @@ */ int ASBeautifier::computeObjCColonAlignment(const string& line, int colonAlignPosition) const { - int colonPosition = line.find(':'); + int colonPosition = findObjCColonAlignment(line); if (colonPosition < 0 || colonPosition > colonAlignPosition) return indentLength; return (colonAlignPosition - colonPosition); } /* - * Compute postition of the keyword following the method call object. + * Compute position of the keyword following the method call object. + * This is oversimplified to find unusual method calls. + * Use for now and see what happens. + * Most programmers will probably use align-method-colon anyway. */ -int ASBeautifier::getObjCFollowingKeyword(const string& line, int bracketPos) const +int ASBeautifier::getObjCFollowingKeyword(const string& line, int bracePos) const { - assert(line[bracketPos] == '['); - size_t firstText = line.find_first_not_of(" \t", bracketPos + 1); + assert(line[bracePos] == '['); + size_t firstText = line.find_first_not_of(" \t", bracePos + 1); if (firstText == string::npos) return -(indentCount * indentLength - 1); size_t searchBeg = firstText; @@ -2473,6 +2488,34 @@ return convertedLine; } +/** + * Determine if an item is at a top level. + */ +bool ASBeautifier::isTopLevel() const +{ + if (headerStack->empty()) + return true; + else if (headerStack->back() == &AS_OPEN_BRACE + && headerStack->size() >= 2) + { + if ((*headerStack)[headerStack->size() - 2] == &AS_NAMESPACE + || (*headerStack)[headerStack->size() - 2] == &AS_MODULE + || (*headerStack)[headerStack->size() - 2] == &AS_CLASS + || (*headerStack)[headerStack->size() - 2] == &AS_INTERFACE + || (*headerStack)[headerStack->size() - 2] == &AS_STRUCT + || (*headerStack)[headerStack->size() - 2] == &AS_UNION) + return true; + } + else if (headerStack->back() == &AS_NAMESPACE + || headerStack->back() == &AS_MODULE + || headerStack->back() == &AS_CLASS + || headerStack->back() == &AS_INTERFACE + || headerStack->back() == &AS_STRUCT + || headerStack->back() == &AS_UNION) + return true; + return false; +} + /** * Parse the current line to update indentCount and spaceIndentCount. */ @@ -2483,8 +2526,8 @@ bool isSpecialChar = false; bool haveCaseIndent = false; bool haveAssignmentThisLine = false; - bool closingBracketReached = false; - bool previousLineProbation = (probationHeader != NULL); + bool closingBraceReached = false; + bool previousLineProbation = (probationHeader != nullptr); char ch = ' '; int tabIncrementIn = 0; if (isInQuote @@ -2556,8 +2599,8 @@ else if (isSharpStyle() && prevCh == '@') isInVerbatimQuote = true; // check for "C" following "extern" - else if (g_preprocessorCppExternCBracket == 2 && line.compare(i, 3, "\"C\"") == 0) - ++g_preprocessorCppExternCBracket; + else if (g_preprocessorCppExternCBrace == 2 && line.compare(i, 3, "\"C\"") == 0) + ++g_preprocessorCppExternCBrace; } else if (isInVerbatimQuote && ch == '"') { @@ -2586,7 +2629,7 @@ else if (quoteChar == ch) { isInQuote = false; - isInStatement = true; + isContinuation = true; continue; } } @@ -2676,19 +2719,19 @@ // if we have reached this far then we are NOT in a comment or string of special character... - if (probationHeader != NULL) + if (probationHeader != nullptr) { if ((probationHeader == &AS_STATIC && ch == '{') || (probationHeader == &AS_SYNCHRONIZED && ch == '(')) { // insert the probation header as a new header isInHeader = true; - headerStack->push_back(probationHeader); + headerStack->emplace_back(probationHeader); // handle the specific probation header isInConditional = (probationHeader == &AS_SYNCHRONIZED); - isInStatement = false; + isContinuation = false; // if the probation comes from the previous line, then indent by 1 tab count. if (previousLineProbation && ch == '{' @@ -2701,7 +2744,7 @@ } // dismiss the probation header - probationHeader = NULL; + probationHeader = nullptr; } prevNonSpaceCh = currentNonSpaceCh; @@ -2718,21 +2761,21 @@ currentHeader = headerStack->back(); } else - currentHeader = NULL; + currentHeader = nullptr; if (isCStyle() && isInTemplate && (ch == '<' || ch == '>') && !(line.length() > i + 1 && line.compare(i, 2, ">=") == 0)) { if (ch == '<') { ++templateDepth; - inStatementIndentStackSizeStack->push_back(inStatementIndentStack->size()); - registerInStatementIndent(line, i, spaceIndentCount, tabIncrementIn, 0, true); + continuationIndentStackSizeStack->push_back(continuationIndentStack->size()); + registerContinuationIndent(line, i, spaceIndentCount, tabIncrementIn, 0, true); } else if (ch == '>') { - popLastInStatementIndent(); + popLastContinuationIndent(); if (--templateDepth <= 0) { ch = ';'; @@ -2763,34 +2806,34 @@ if (parenDepth == 0) { - parenStatementStack->push_back(isInStatement); - isInStatement = true; + parenStatementStack->push_back(isContinuation); + isContinuation = true; } parenDepth++; if (ch == '[') { - ++blockParenCount; - if (blockParenCount == 1 && isCStyle()) + ++squareBracketCount; + if (squareBracketCount == 1 && isCStyle()) { isInObjCMethodCall = true; isInObjCMethodCallFirst = true; } } - inStatementIndentStackSizeStack->push_back(inStatementIndentStack->size()); + continuationIndentStackSizeStack->push_back(continuationIndentStack->size()); - if (currentHeader != NULL) - registerInStatementIndent(line, i, spaceIndentCount, tabIncrementIn, minConditionalIndent/*indentLength*2*/, true); - else - registerInStatementIndent(line, i, spaceIndentCount, tabIncrementIn, 0, true); + if (currentHeader != nullptr) + registerContinuationIndent(line, i, spaceIndentCount, tabIncrementIn, minConditionalIndent, true); + else if (!isInObjCMethodDefinition) + registerContinuationIndent(line, i, spaceIndentCount, tabIncrementIn, 0, true); } else if (ch == ')' || ch == ']') { if (ch == ']') - --blockParenCount; - if (blockParenCount <= 0) + --squareBracketCount; + if (squareBracketCount <= 0) { - blockParenCount = 0; + squareBracketCount = 0; if (isInObjCMethodCall) isImmediatelyPostObjCMethodCall = true; } @@ -2800,16 +2843,16 @@ { if (!parenStatementStack->empty()) // in case of unmatched closing parens { - isInStatement = parenStatementStack->back(); + isContinuation = parenStatementStack->back(); parenStatementStack->pop_back(); } isInAsm = false; isInConditional = false; } - if (!inStatementIndentStackSizeStack->empty()) + if (!continuationIndentStackSizeStack->empty()) { - popLastInStatementIndent(); + popLastContinuationIndent(); if (!parenIndentStack->empty()) { @@ -2827,11 +2870,12 @@ if (ch == '{') { // first, check if '{' is a block-opener or a static-array opener - bool isBlockOpener = ((prevNonSpaceCh == '{' && bracketBlockStateStack->back()) + bool isBlockOpener = ((prevNonSpaceCh == '{' && braceBlockStateStack->back()) || prevNonSpaceCh == '}' || prevNonSpaceCh == ')' || prevNonSpaceCh == ';' || peekNextChar(line, i) == '{' + || isInTrailingReturnType || foundPreCommandHeader || foundPreCommandMacro || isInClassHeader @@ -2852,24 +2896,17 @@ { objCColonAlignSubsequent = 0; isImmediatelyPostObjCMethodDefinition = true; - if (lineBeginsWithOpenBracket) // for horstmann brackets + if (lineBeginsWithOpenBrace) // for run-in braces clearObjCMethodDefinitionAlignment(); } - if (!isBlockOpener && !isInStatement && !isInClassInitializer && !isInEnum) + if (!isBlockOpener && !isContinuation && !isInClassInitializer && !isInEnum) { - if (headerStack->empty()) - isBlockOpener = true; - else if (headerStack->back() == &AS_NAMESPACE - || headerStack->back() == &AS_MODULE - || headerStack->back() == &AS_CLASS - || headerStack->back() == &AS_INTERFACE - || headerStack->back() == &AS_STRUCT - || headerStack->back() == &AS_UNION) + if (isTopLevel()) isBlockOpener = true; } - if (!isBlockOpener && currentHeader != NULL) + if (!isBlockOpener && currentHeader != nullptr) { for (size_t n = 0; n < nonParenHeaders->size(); n++) if (currentHeader == (*nonParenHeaders)[n]) @@ -2879,28 +2916,28 @@ } } - bracketBlockStateStack->push_back(isBlockOpener); + braceBlockStateStack->push_back(isBlockOpener); if (!isBlockOpener) { - inStatementIndentStackSizeStack->push_back(inStatementIndentStack->size()); - registerInStatementIndent(line, i, spaceIndentCount, tabIncrementIn, 0, true); + continuationIndentStackSizeStack->push_back(continuationIndentStack->size()); + registerContinuationIndent(line, i, spaceIndentCount, tabIncrementIn, 0, true); parenDepth++; if (i == 0) - shouldIndentBrackettedLine = false; + shouldIndentBracedLine = false; isInEnumTypeID = false; continue; } - // this bracket is a block opener... + // this brace is a block opener... ++lineOpeningBlocksNum; if (isInClassInitializer || isInEnumTypeID) { - // decrease tab count if bracket is broken - if (lineBeginsWithOpenBracket) + // decrease tab count if brace is broken + if (lineBeginsWithOpenBrace) { indentCount -= classInitializerIndents; // decrease one more if an empty class @@ -2917,15 +2954,15 @@ if (isInObjCInterface) { isInObjCInterface = false; - if (lineBeginsWithOpenBracket) + if (lineBeginsWithOpenBrace) --indentCount; } - if (bracketIndent && !namespaceIndent && !headerStack->empty() + if (braceIndent && !namespaceIndent && !headerStack->empty() && ((*headerStack).back() == &AS_NAMESPACE || (*headerStack).back() == &AS_MODULE)) { - shouldIndentBrackettedLine = false; + shouldIndentBracedLine = false; --indentCount; } @@ -2935,71 +2972,83 @@ && isInIndentableStruct) (*headerStack).back() = &AS_CLASS; - blockParenDepthStack->push_back(parenDepth); - blockStatementStack->push_back(isInStatement); + // is a brace inside a paren? + parenDepthStack->emplace_back(parenDepth); + blockStatementStack->push_back(isContinuation); - if (!inStatementIndentStack->empty()) + if (!continuationIndentStack->empty()) { - // completely purge the inStatementIndentStack - while (!inStatementIndentStack->empty()) - popLastInStatementIndent(); + // completely purge the continuationIndentStack + while (!continuationIndentStack->empty()) + popLastContinuationIndent(); if (isInClassInitializer || isInClassHeaderTab) { - if (lineBeginsWithOpenBracket || lineBeginsWithComma) + if (lineBeginsWithOpenBrace || lineBeginsWithComma) spaceIndentCount = 0; } else spaceIndentCount = 0; } - blockTabCount += (isInStatement ? 1 : 0); - if (g_preprocessorCppExternCBracket == 3) - ++g_preprocessorCppExternCBracket; + blockTabCount += (isContinuation ? 1 : 0); + if (g_preprocessorCppExternCBrace == 3) + ++g_preprocessorCppExternCBrace; parenDepth = 0; + isInTrailingReturnType = false; isInClassHeader = false; isInClassHeaderTab = false; isInClassInitializer = false; isInEnumTypeID = false; - isInStatement = false; + isContinuation = false; isInQuestion = false; isInLet = false; foundPreCommandHeader = false; foundPreCommandMacro = false; isInExternC = false; - tempStacks->push_back(new vector); - headerStack->push_back(&AS_OPEN_BRACKET); - lastLineHeader = &AS_OPEN_BRACKET; + tempStacks->emplace_back(new vector); + headerStack->emplace_back(&AS_OPEN_BRACE); + lastLineHeader = &AS_OPEN_BRACE; continue; } // end '{' //check if a header has been reached bool isPotentialHeader = isCharPotentialHeader(line, i); - if (isPotentialHeader && !blockParenCount) + if (isPotentialHeader && squareBracketCount == 0) { const string* newHeader = findHeader(line, i, headers); + // java can have a 'default' not in a switch + if (newHeader == &AS_DEFAULT + && peekNextChar(line, (i + (*newHeader).length() - 1)) != ':') + newHeader = nullptr; // Qt headers may be variables in C++ if (isCStyle() && (newHeader == &AS_FOREVER || newHeader == &AS_FOREACH)) { if (line.find_first_of("=;", i) != string::npos) - newHeader = NULL; + newHeader = nullptr; + } + else if (isSharpStyle() + && (newHeader == &AS_GET || newHeader == &AS_SET)) + { + if (getNextWord(line, i + (*newHeader).length()) == "is") + newHeader = nullptr; } else if (newHeader == &AS_USING - && ASBeautifier::peekNextChar(line, i + (*newHeader).length() - 1) != '(') - newHeader = NULL; + && peekNextChar(line, i + (*newHeader).length() - 1) != '(') + newHeader = nullptr; - if (newHeader != NULL) + if (newHeader != nullptr) { // if we reached here, then this is a header... bool isIndentableHeader = true; isInHeader = true; - vector* lastTempStack = NULL;; + vector* lastTempStack = nullptr;; if (!tempStacks->empty()) lastTempStack = tempStacks->back(); @@ -3009,13 +3058,14 @@ // take care of the special case: 'else if (...)' if (newHeader == &AS_IF && lastLineHeader == &AS_ELSE) { - headerStack->pop_back(); + if (!headerStack->empty()) + headerStack->pop_back(); } // take care of 'else' else if (newHeader == &AS_ELSE) { - if (lastTempStack != NULL) + if (lastTempStack != nullptr) { int indexOfIf = indexOf(*lastTempStack, &AS_IF); if (indexOfIf != -1) @@ -3025,10 +3075,10 @@ int restackSize = lastTempStack->size() - indexOfIf - 1; for (int r = 0; r < restackSize; r++) { - headerStack->push_back(lastTempStack->back()); + headerStack->emplace_back(lastTempStack->back()); lastTempStack->pop_back(); } - if (!closingBracketReached) + if (!closingBraceReached) indentCount += restackSize; } /* @@ -3042,7 +3092,7 @@ // check if 'while' closes a previous 'do' else if (newHeader == &AS_WHILE) { - if (lastTempStack != NULL) + if (lastTempStack != nullptr) { int indexOfDo = indexOf(*lastTempStack, &AS_DO); if (indexOfDo != -1) @@ -3052,18 +3102,18 @@ int restackSize = lastTempStack->size() - indexOfDo - 1; for (int r = 0; r < restackSize; r++) { - headerStack->push_back(lastTempStack->back()); + headerStack->emplace_back(lastTempStack->back()); lastTempStack->pop_back(); } - if (!closingBracketReached) + if (!closingBraceReached) indentCount += restackSize; } } } // check if 'catch' closes a previous 'try' or 'catch' else if (newHeader == &AS_CATCH || newHeader == &AS_FINALLY) { - if (lastTempStack != NULL) + if (lastTempStack != nullptr) { int indexOfTry = indexOf(*lastTempStack, &AS_TRY); if (indexOfTry == -1) @@ -3075,11 +3125,11 @@ int restackSize = lastTempStack->size() - indexOfTry - 1; for (int r = 0; r < restackSize; r++) { - headerStack->push_back(lastTempStack->back()); + headerStack->emplace_back(lastTempStack->back()); lastTempStack->pop_back(); } - if (!closingBracketReached) + if (!closingBraceReached) indentCount += restackSize; } } @@ -3090,7 +3140,7 @@ if (!haveCaseIndent) { haveCaseIndent = true; - if (!lineBeginsWithOpenBracket) + if (!lineBeginsWithOpenBrace) --indentCount; } } @@ -3122,8 +3172,8 @@ if (isIndentableHeader) { - headerStack->push_back(newHeader); - isInStatement = false; + headerStack->emplace_back(newHeader); + isContinuation = false; if (indexOf(*nonParenHeaders, newHeader) == -1) { isInConditional = true; @@ -3136,10 +3186,12 @@ i += newHeader->length() - 1; continue; - } // newHeader != NULL + } // newHeader != nullptr - if (findHeader(line, i, preCommandHeaders)) - foundPreCommandHeader = true; + if (findHeader(line, i, preCommandHeaders) != nullptr) + // must be after function arguments + if (prevNonSpaceCh == ')') + foundPreCommandHeader = true; // Objective-C NSException macros are preCommandHeaders if (isCStyle() && findKeyword(line, i, AS_NS_DURING)) @@ -3182,21 +3234,21 @@ if (i == 0) indentCount += classInitializerIndents; } - else if (isCStyle() + else if ((isCStyle() || isSharpStyle()) && !isInCase && (prevNonSpaceCh == ')' || foundPreCommandHeader)) { // found a 'class' c'tor initializer isInClassInitializer = true; - registerInStatementIndentColon(line, i, tabIncrementIn); + registerContinuationIndentColon(line, i, tabIncrementIn); if (i == 0) indentCount += classInitializerIndents; } else if (isInClassHeader || isInObjCInterface) { // is in a 'class A : public B' definition isInClassHeaderTab = true; - registerInStatementIndentColon(line, i, tabIncrementIn); + registerContinuationIndentColon(line, i, tabIncrementIn); } else if (isInAsm || isInAsmOneLine || isInAsmBlock) { @@ -3216,10 +3268,10 @@ else if (isCStyle() && !isInClass && headerStack->size() >= 2 && (*headerStack)[headerStack->size() - 2] == &AS_CLASS - && (*headerStack)[headerStack->size() - 1] == &AS_OPEN_BRACKET) + && (*headerStack)[headerStack->size() - 1] == &AS_OPEN_BRACE) { // found a 'private:' or 'public:' inside a class definition - // and on the same line as the class opening bracket + // and on the same line as the class opening brace // do nothing } else if (isJavaStyle() && lastLineHeader == &AS_FOR) @@ -3229,7 +3281,7 @@ } else { - currentNonSpaceCh = ';'; // so that brackets after the ':' will appear as block-openers + currentNonSpaceCh = ';'; // so that braces after the ':' will appear as block-openers char peekedChar = peekNextChar(line, i); if (isInCase) { @@ -3241,23 +3293,23 @@ // is in a label (e.g. 'label1:') if (labelIndent) --indentCount; // unindent label by one indent - else if (!lineBeginsWithOpenBracket) + else if (!lineBeginsWithOpenBrace) indentCount = 0; // completely flush indent to left } } } - if ((ch == ';' || (parenDepth > 0 && ch == ',')) && !inStatementIndentStackSizeStack->empty()) - while ((int) inStatementIndentStackSizeStack->back() + (parenDepth > 0 ? 1 : 0) - < (int) inStatementIndentStack->size()) - inStatementIndentStack->pop_back(); + if ((ch == ';' || (parenDepth > 0 && ch == ',')) && !continuationIndentStackSizeStack->empty()) + while ((int) continuationIndentStackSizeStack->back() + (parenDepth > 0 ? 1 : 0) + < (int) continuationIndentStack->size()) + continuationIndentStack->pop_back(); - else if (ch == ',' && isInEnum && isNonInStatementArray && !inStatementIndentStack->empty()) - inStatementIndentStack->pop_back(); + else if (ch == ',' && isInEnum && isNonInStatementArray && !continuationIndentStack->empty()) + continuationIndentStack->pop_back(); // handle commas // previous "isInStatement" will be from an assignment operator or class initializer - if (ch == ',' && parenDepth == 0 && !isInStatement && !isNonInStatementArray) + if (ch == ',' && parenDepth == 0 && !isContinuation && !isNonInStatementArray) { // is comma at end of line size_t nextChar = line.find_first_not_of(" \t", i + 1); @@ -3278,10 +3330,10 @@ // register indent at second word on the line else if (!isInTemplate && !isInClassHeaderTab && !isInClassInitializer) { - int prevWord = getInStatementIndentComma(line, i); - int inStatementIndent = prevWord + spaceIndentCount + tabIncrementIn; - inStatementIndentStack->push_back(inStatementIndent); - isInStatement = true; + int prevWord = getContinuationIndentComma(line, i); + int continuationIndentCount = prevWord + spaceIndentCount + tabIncrementIn; + continuationIndentStack->emplace_back(continuationIndentCount); + isContinuation = true; } } } @@ -3296,19 +3348,19 @@ if (ch == '}') { // first check if this '}' closes a previous block, or a static array... - if (bracketBlockStateStack->size() > 1) + if (braceBlockStateStack->size() > 1) { - bool bracketBlockState = bracketBlockStateStack->back(); - bracketBlockStateStack->pop_back(); - if (!bracketBlockState) + bool braceBlockState = braceBlockStateStack->back(); + braceBlockStateStack->pop_back(); + if (!braceBlockState) { - if (!inStatementIndentStackSizeStack->empty()) + if (!continuationIndentStackSizeStack->empty()) { - // this bracket is a static array - popLastInStatementIndent(); + // this brace is a static array + popLastContinuationIndent(); parenDepth--; if (i == 0) - shouldIndentBrackettedLine = false; + shouldIndentBracedLine = false; if (!parenIndentStack->empty()) { @@ -3322,50 +3374,50 @@ } } - // this bracket is block closer... + // this brace is block closer... ++lineClosingBlocksNum; - if (!inStatementIndentStackSizeStack->empty()) - popLastInStatementIndent(); + if (!continuationIndentStackSizeStack->empty()) + popLastContinuationIndent(); - if (!blockParenDepthStack->empty()) + if (!parenDepthStack->empty()) { - parenDepth = blockParenDepthStack->back(); - blockParenDepthStack->pop_back(); - isInStatement = blockStatementStack->back(); + parenDepth = parenDepthStack->back(); + parenDepthStack->pop_back(); + isContinuation = blockStatementStack->back(); blockStatementStack->pop_back(); - if (isInStatement) + if (isContinuation) blockTabCount--; } - closingBracketReached = true; + closingBraceReached = true; if (i == 0) spaceIndentCount = 0; isInAsmBlock = false; isInAsm = isInAsmOneLine = isInQuote = false; // close these just in case - int headerPlace = indexOf(*headerStack, &AS_OPEN_BRACKET); + int headerPlace = indexOf(*headerStack, &AS_OPEN_BRACE); if (headerPlace != -1) { const string* popped = headerStack->back(); - while (popped != &AS_OPEN_BRACKET) + while (popped != &AS_OPEN_BRACE) { headerStack->pop_back(); popped = headerStack->back(); } headerStack->pop_back(); if (headerStack->empty()) - g_preprocessorCppExternCBracket = 0; + g_preprocessorCppExternCBrace = 0; - // do not indent namespace bracket unless namespaces are indented + // do not indent namespace brace unless namespaces are indented if (!namespaceIndent && !headerStack->empty() && ((*headerStack).back() == &AS_NAMESPACE || (*headerStack).back() == &AS_MODULE) - && i == 0) // must be the first bracket on the line - shouldIndentBrackettedLine = false; + && i == 0) // must be the first brace on the line + shouldIndentBracedLine = false; if (!tempStacks->empty()) { @@ -3390,31 +3442,34 @@ if (!tempStacks->back()->empty()) while (!tempStacks->back()->empty()) tempStacks->back()->pop_back(); - while (!headerStack->empty() && headerStack->back() != &AS_OPEN_BRACKET) + while (!headerStack->empty() && headerStack->back() != &AS_OPEN_BRACE) { - tempStacks->back()->push_back(headerStack->back()); + tempStacks->back()->emplace_back(headerStack->back()); headerStack->pop_back(); } if (parenDepth == 0 && ch == ';') - isInStatement = false; + { + isContinuation = false; + isInClassInitializer = false; + } if (isInObjCMethodDefinition) { objCColonAlignSubsequent = 0; isImmediatelyPostObjCMethodDefinition = true; } - previousLastLineHeader = NULL; + previousLastLineHeader = nullptr; isInClassHeader = false; // for 'friend' class isInEnum = false; isInEnumTypeID = false; isInQuestion = false; isInTemplate = false; isInObjCInterface = false; foundPreCommandHeader = false; foundPreCommandMacro = false; - blockParenCount = 0; + squareBracketCount = 0; continue; } @@ -3426,25 +3481,29 @@ if (!isInTemplate && !(isCStyle() && parenDepth > 0)) { const string* newHeader = findHeader(line, i, preBlockStatements); - // handle CORBA IDL module + // CORBA IDL module if (newHeader == &AS_MODULE) { char nextChar = peekNextChar(line, i + newHeader->length() - 1); if (prevNonSpaceCh == ')' || !isalpha(nextChar)) - newHeader = NULL; + newHeader = nullptr; } - if (newHeader != NULL - && !(isCStyle() && newHeader == &AS_CLASS && isInEnum)) // is not 'enum class' + if (newHeader != nullptr + && !(isCStyle() && newHeader == &AS_CLASS && isInEnum) // is not 'enum class' + && !(isCStyle() && newHeader == &AS_INTERFACE // CORBA IDL interface + && (headerStack->empty() + || headerStack->back() != &AS_OPEN_BRACE))) { if (!isSharpStyle()) - headerStack->push_back(newHeader); + headerStack->emplace_back(newHeader); // do not need 'where' in the headerStack // do not need second 'class' statement in a row else if (!(newHeader == &AS_WHERE - || (newHeader == &AS_CLASS + || ((newHeader == &AS_CLASS || newHeader == &AS_STRUCT) && !headerStack->empty() - && headerStack->back() == &AS_CLASS))) - headerStack->push_back(newHeader); + && (headerStack->back() == &AS_CLASS + || headerStack->back() == &AS_STRUCT)))) + headerStack->emplace_back(newHeader); if (!headerStack->empty()) { @@ -3457,10 +3516,10 @@ else if ((*headerStack).back() == &AS_NAMESPACE || (*headerStack).back() == &AS_MODULE) { - // remove inStatementIndent from namespace - if (!inStatementIndentStack->empty()) - inStatementIndentStack->pop_back(); - isInStatement = false; + // remove continuationIndent from namespace + if (!continuationIndentStack->empty()) + continuationIndentStack->pop_back(); + isContinuation = false; } } @@ -3470,32 +3529,37 @@ } const string* foundIndentableHeader = findHeader(line, i, indentableHeaders); - if (foundIndentableHeader != NULL) + if (foundIndentableHeader != nullptr) { // must bypass the header before registering the in statement i += foundIndentableHeader->length() - 1; if (!isInOperator && !isInTemplate && !isNonInStatementArray) { - registerInStatementIndent(line, i, spaceIndentCount, tabIncrementIn, 0, false); - isInStatement = true; + registerContinuationIndent(line, i, spaceIndentCount, tabIncrementIn, 0, false); + isContinuation = true; } continue; } if (isCStyle() && findKeyword(line, i, AS_OPERATOR)) isInOperator = true; - if (g_preprocessorCppExternCBracket == 1 && findKeyword(line, i, AS_EXTERN)) - ++g_preprocessorCppExternCBracket; + if (g_preprocessorCppExternCBrace == 1 && findKeyword(line, i, AS_EXTERN)) + ++g_preprocessorCppExternCBrace; - if (g_preprocessorCppExternCBracket == 3) // extern "C" is not followed by a '{' - g_preprocessorCppExternCBracket = 0; + if (g_preprocessorCppExternCBrace == 3) // extern "C" is not followed by a '{' + g_preprocessorCppExternCBrace = 0; // "new" operator is a pointer, not a calculation if (findKeyword(line, i, AS_NEW)) { - if (isInStatement && !inStatementIndentStack->empty() && prevNonSpaceCh == '=') - inStatementIndentStack->back() = 0; + if (isContinuation && !continuationIndentStack->empty() && prevNonSpaceCh == '=') + continuationIndentStack->back() = 0; + } + + if (isCStyle() && findKeyword(line, i, AS_AUTO) && isTopLevel()) + { + isInTrailingReturnType = true; } if (isCStyle()) @@ -3528,11 +3592,13 @@ // Handle Objective-C statements - if (ch == '@' && !isWhiteSpace(line[i + 1]) + if (ch == '@' + && line.length() > i + 1 + && !isWhiteSpace(line[i + 1]) && isCharPotentialHeader(line, i + 1)) { string curWord = getCurrentWord(line, i + 1); - if (curWord == AS_INTERFACE && headerStack->empty()) + if (curWord == AS_INTERFACE) { isInObjCInterface = true; string name = '@' + curWord; @@ -3558,17 +3624,19 @@ } else if (curWord == AS_END) { - popLastInStatementIndent(); + popLastContinuationIndent(); spaceIndentCount = 0; isInObjCMethodDefinition = false; string name = '@' + curWord; i += name.length() - 1; continue; } } else if ((ch == '-' || ch == '+') - && peekNextChar(line, i) == '(' - && headerStack->empty() + && (prevNonSpaceCh == ';' || prevNonSpaceCh == '{' + || headerStack->empty() || isInObjCInterface) + && ASBase::peekNextChar(line, i) != '-' + && ASBase::peekNextChar(line, i) != '+' && line.find_first_not_of(" \t") == i) { if (isInObjCInterface) @@ -3588,47 +3656,49 @@ const string* foundAssignmentOp = findOperator(line, i, assignmentOperators); const string* foundNonAssignmentOp = findOperator(line, i, nonAssignmentOperators); - if (foundNonAssignmentOp == &AS_LAMBDA) - foundPreCommandHeader = true; - - if (isInTemplate && foundNonAssignmentOp == &AS_GR_GR) - foundNonAssignmentOp = NULL; + if (foundNonAssignmentOp != nullptr) + { + if (foundNonAssignmentOp == &AS_LAMBDA) + foundPreCommandHeader = true; + if (isInTemplate && foundNonAssignmentOp == &AS_GR_GR) + foundNonAssignmentOp = nullptr; + } // Since findHeader's boundary checking was not used above, it is possible // that both an assignment op and a non-assignment op where found, // e.g. '>>' and '>>='. If this is the case, treat the LONGER one as the // found operator. - if (foundAssignmentOp != NULL && foundNonAssignmentOp != NULL) + if (foundAssignmentOp != nullptr && foundNonAssignmentOp != nullptr) { if (foundAssignmentOp->length() < foundNonAssignmentOp->length()) - foundAssignmentOp = NULL; + foundAssignmentOp = nullptr; else - foundNonAssignmentOp = NULL; + foundNonAssignmentOp = nullptr; } - if (foundNonAssignmentOp != NULL) + if (foundNonAssignmentOp != nullptr) { if (foundNonAssignmentOp->length() > 1) i += foundNonAssignmentOp->length() - 1; // For C++ input/output, operator<< and >> should be // aligned, if we are not in a statement already and // also not in the "operator<<(...)" header line if (!isInOperator - && inStatementIndentStack->empty() + && continuationIndentStack->empty() && isCStyle() && (foundNonAssignmentOp == &AS_GR_GR || foundNonAssignmentOp == &AS_LS_LS)) { // this will be true if the line begins with the operator - if (i < 2 && spaceIndentCount == 0) + if (i < foundNonAssignmentOp->length() && spaceIndentCount == 0) spaceIndentCount += 2 * indentLength; // align to the beginning column of the operator - registerInStatementIndent(line, i - foundNonAssignmentOp->length(), spaceIndentCount, tabIncrementIn, 0, false); + registerContinuationIndent(line, i - foundNonAssignmentOp->length(), spaceIndentCount, tabIncrementIn, 0, false); } } - else if (foundAssignmentOp != NULL) + else if (foundAssignmentOp != nullptr) { foundPreCommandHeader = false; // clears this for array assignments foundPreCommandMacro = false; @@ -3647,10 +3717,10 @@ { // register indent at previous word haveAssignmentThisLine = true; - int prevWordIndex = getInStatementIndentAssign(line, i); - int inStatementIndent = prevWordIndex + spaceIndentCount + tabIncrementIn; - inStatementIndentStack->push_back(inStatementIndent); - isInStatement = true; + int prevWordIndex = getContinuationIndentAssign(line, i); + int continuationIndentCount = prevWordIndex + spaceIndentCount + tabIncrementIn; + continuationIndentStack->emplace_back(continuationIndentCount); + isContinuation = true; } } // don't indent an assignment if 'let' @@ -3662,8 +3732,8 @@ { if (i == 0 && spaceIndentCount == 0) spaceIndentCount += indentLength; - registerInStatementIndent(line, i, spaceIndentCount, tabIncrementIn, 0, false); - isInStatement = true; + registerContinuationIndent(line, i, spaceIndentCount, tabIncrementIn, 0, false); + isContinuation = true; } } } diff --git a/plugins/astyle/3rdparty/libastyle/ASEnhancer.cpp b/plugins/astyle/3rdparty/libastyle/ASEnhancer.cpp --- a/plugins/astyle/3rdparty/libastyle/ASEnhancer.cpp +++ b/plugins/astyle/3rdparty/libastyle/ASEnhancer.cpp @@ -1,7 +1,7 @@ // ASEnhancer.cpp -// Copyright (c) 2016 by Jim Pattee . +// Copyright (c) 2018 by Jim Pattee . // This code is licensed under the MIT License. -// License.txt describes the conditions under which this software may be distributed. +// License.md describes the conditions under which this software may be distributed. //----------------------------------------------------------------------------- // headers @@ -66,18 +66,18 @@ // unindent variables lineNumber = 0; - bracketCount = 0; + braceCount = 0; isInComment = false; isInQuote = false; switchDepth = 0; eventPreprocDepth = 0; - lookingForCaseBracket = false; + lookingForCaseBrace = false; unindentNextLine = false; shouldUnindentLine = false; shouldUnindentComment = false; // switch struct and vector - sw.switchBracketCount = 0; + sw.switchBraceCount = 0; sw.unindentDepth = 0; sw.unindentCase = false; switchStack.clear(); @@ -124,7 +124,7 @@ && !emptyLineFill) return; - // test for unindent on attached brackets + // test for unindent on attached braces if (unindentNextLine) { sw.unindentDepth++; @@ -202,7 +202,7 @@ * @param caseIndex the line index of the case statement. * @return the line index of the colon. */ -size_t ASEnhancer::findCaseColon(string& line, size_t caseIndex) const +size_t ASEnhancer::findCaseColon(const string& line, size_t caseIndex) const { size_t i = caseIndex; bool isInQuote_ = false; @@ -293,7 +293,7 @@ * @param index the current line index. * @return true if a hit. */ -bool ASEnhancer::isBeginDeclareSectionSQL(string& line, size_t index) const +bool ASEnhancer::isBeginDeclareSectionSQL(const string& line, size_t index) const { string word; size_t hits = 0; @@ -342,7 +342,7 @@ * @param index the current line index. * @return true if a hit. */ -bool ASEnhancer::isEndDeclareSectionSQL(string& line, size_t index) const +bool ASEnhancer::isEndDeclareSectionSQL(const string& line, size_t index) const { string word; size_t hits = 0; @@ -384,20 +384,20 @@ } /** - * check if a one-line bracket has been reached, + * check if a one-line brace has been reached, * i.e. if the currently reached '{' character is closed * with a complimentary '}' elsewhere on the current line, *. - * @return false = one-line bracket has not been reached. - * true = one-line bracket has been reached. + * @return false = one-line brace has not been reached. + * true = one-line brace has been reached. */ bool ASEnhancer::isOneLineBlockReached(const string& line, int startChar) const { assert(line[startChar] == '{'); bool isInComment_ = false; bool isInQuote_ = false; - int _bracketCount = 1; + int _braceCount = 1; int lineLength = line.length(); char quoteChar_ = ' '; char ch = ' '; @@ -448,11 +448,11 @@ } if (ch == '{') - ++_bracketCount; + ++_braceCount; else if (ch == '}') - --_bracketCount; + --_braceCount; - if (_bracketCount == 0) + if (_braceCount == 0) return true; } @@ -519,17 +519,17 @@ // check for windows line markers if (line.compare(i + 2, 1, "\xf0") > 0) lineNumber--; - // unindent if not in case brackets + // unindent if not in case braces if (line.find_first_not_of(" \t") == i - && sw.switchBracketCount == 1 + && sw.switchBraceCount == 1 && sw.unindentCase) shouldUnindentComment = true; break; // finished with the line } else if (!(isInComment) && line.compare(i, 2, "/*") == 0) { - // unindent if not in case brackets - if (sw.switchBracketCount == 1 && sw.unindentCase) + // unindent if not in case braces + if (sw.switchBraceCount == 1 && sw.unindentCase) shouldUnindentComment = true; isInComment = true; size_t commentEnd = line.find("*/", i); @@ -541,18 +541,18 @@ } else if ((isInComment) && line.compare(i, 2, "*/") == 0) { - // unindent if not in case brackets - if (sw.switchBracketCount == 1 && sw.unindentCase) + // unindent if not in case braces + if (sw.switchBraceCount == 1 && sw.unindentCase) shouldUnindentComment = true; isInComment = false; i++; continue; } if (isInComment) { - // unindent if not in case brackets - if (sw.switchBracketCount == 1 && sw.unindentCase) + // unindent if not in case braces + if (sw.switchBraceCount == 1 && sw.unindentCase) shouldUnindentComment = true; size_t commentEnd = line.find("*/", i); if (commentEnd == string::npos) @@ -565,10 +565,10 @@ // if we have reached this far then we are NOT in a comment or string of special characters if (line[i] == '{') - bracketCount++; + braceCount++; if (line[i] == '}') - bracketCount--; + braceCount--; // check for preprocessor within an event table if (isInEventTable && line[i] == '#' && preprocBlockIndent) @@ -621,11 +621,11 @@ // ---------------- process switch statements --------------------------------- - if (isPotentialKeyword && findKeyword(line, i, "switch")) + if (isPotentialKeyword && findKeyword(line, i, ASResource::AS_SWITCH)) { switchDepth++; - switchStack.push_back(sw); // save current variables - sw.switchBracketCount = 0; + switchStack.emplace_back(sw); // save current variables + sw.switchBraceCount = 0; sw.unindentCase = false; // don't clear case until end of switch i += 5; // bypass switch statement continue; @@ -665,22 +665,21 @@ if (line[i] == '{') { - sw.switchBracketCount++; - if (lookingForCaseBracket) // if 1st after case statement + sw.switchBraceCount++; + if (lookingForCaseBrace) // if 1st after case statement { sw.unindentCase = true; // unindenting this case sw.unindentDepth++; - lookingForCaseBracket = false; // not looking now + lookingForCaseBrace = false; // not looking now } return i; } - lookingForCaseBracket = false; // no opening bracket, don't indent + lookingForCaseBrace = false; // no opening brace, don't indent if (line[i] == '}') { - sw.switchBracketCount--; - assert(sw.switchBracketCount <= bracketCount); - if (sw.switchBracketCount == 0) // if end of switch statement + sw.switchBraceCount--; + if (sw.switchBraceCount == 0) // if end of switch statement { int lineUnindent = sw.unindentDepth; if (line.find_first_not_of(" \t") == i @@ -700,7 +699,8 @@ } if (isPotentialKeyword - && (findKeyword(line, i, "case") || findKeyword(line, i, "default"))) + && (findKeyword(line, i, ASResource::AS_CASE) + || findKeyword(line, i, ASResource::AS_DEFAULT))) { if (sw.unindentCase) // if unindented last case { @@ -720,14 +720,14 @@ { if (line[i] == '{') { - bracketCount++; - sw.switchBracketCount++; + braceCount++; + sw.switchBraceCount++; if (!isOneLineBlockReached(line, i)) unindentNextLine = true; return i; } } - lookingForCaseBracket = true; + lookingForCaseBrace = true; i--; // need to process this char return i; } diff --git a/plugins/astyle/3rdparty/libastyle/ASFormatter.cpp b/plugins/astyle/3rdparty/libastyle/ASFormatter.cpp --- a/plugins/astyle/3rdparty/libastyle/ASFormatter.cpp +++ b/plugins/astyle/3rdparty/libastyle/ASFormatter.cpp @@ -1,7 +1,7 @@ // ASFormatter.cpp -// Copyright (c) 2016 by Jim Pattee . +// Copyright (c) 2018 by Jim Pattee . // This code is licensed under the MIT License. -// License.txt describes the conditions under which this software may be distributed. +// License.md describes the conditions under which this software may be distributed. //----------------------------------------------------------------------------- // headers @@ -27,16 +27,16 @@ */ ASFormatter::ASFormatter() { - sourceIterator = NULL; + sourceIterator = nullptr; enhancer = new ASEnhancer; - preBracketHeaderStack = NULL; - bracketTypeStack = NULL; - parenStack = NULL; - structStack = NULL; - questionMarkStack = NULL; + preBraceHeaderStack = nullptr; + braceTypeStack = nullptr; + parenStack = nullptr; + structStack = nullptr; + questionMarkStack = nullptr; lineCommentNoIndent = false; formattingStyle = STYLE_NONE; - bracketFormatMode = NONE_MODE; + braceFormatMode = NONE_MODE; pointerAlignment = PTR_ALIGN_NONE; referenceAlignment = REF_SAME_AS_PTR; objCColonPadMode = COLON_PAD_NO_CHANGE; @@ -50,7 +50,7 @@ shouldPadHeader = false; shouldStripCommentPrefix = false; shouldUnPadParens = false; - attachClosingBracketMode = false; + attachClosingBraceMode = false; shouldBreakOneLineBlocks = true; shouldBreakOneLineHeaders = false; shouldBreakOneLineStatements = true; @@ -61,16 +61,21 @@ shouldAttachExternC = false; shouldAttachNamespace = false; shouldAttachClass = false; + shouldAttachClosingWhile = false; shouldAttachInline = false; shouldBreakBlocks = false; shouldBreakClosingHeaderBlocks = false; - shouldBreakClosingHeaderBrackets = false; + shouldBreakClosingHeaderBraces = false; shouldDeleteEmptyLines = false; + shouldBreakReturnType = false; + shouldBreakReturnTypeDecl = false; + shouldAttachReturnType = false; + shouldAttachReturnTypeDecl = false; shouldBreakElseIfs = false; shouldBreakLineAfterLogical = false; - shouldAddBrackets = false; - shouldAddOneLineBrackets = false; - shouldRemoveBrackets = false; + shouldAddBraces = false; + shouldAddOneLineBraces = false; + shouldRemoveBraces = false; shouldPadMethodColon = false; shouldPadMethodPrefix = false; shouldUnPadMethodPrefix = false; @@ -99,8 +104,8 @@ ASFormatter::~ASFormatter() { // delete ASFormatter stack vectors - deleteContainer(preBracketHeaderStack); - deleteContainer(bracketTypeStack); + deleteContainer(preBraceHeaderStack); + deleteContainer(braceTypeStack); deleteContainer(parenStack); deleteContainer(structStack); deleteContainer(questionMarkStack); @@ -118,8 +123,8 @@ // delete ASEnhancer member vectors delete indentableMacros; - // delete ASBeautifier member vectors // must be done when the ASFormatter object is deleted (not ASBeautifier) + // delete ASBeautifier member vectors ASBeautifier::deleteBeautifierVectors(); delete enhancer; @@ -154,43 +159,46 @@ getEmptyLineFill(), indentableMacros); - initContainer(preBracketHeaderStack, new vector); + initContainer(preBraceHeaderStack, new vector); initContainer(parenStack, new vector); initContainer(structStack, new vector); initContainer(questionMarkStack, new vector); - parenStack->push_back(0); // parenStack must contain this default entry - initContainer(bracketTypeStack, new vector); - bracketTypeStack->push_back(NULL_TYPE); // bracketTypeStack must contain this default entry + parenStack->emplace_back(0); // parenStack must contain this default entry + initContainer(braceTypeStack, new vector); + braceTypeStack->emplace_back(NULL_TYPE); // braceTypeStack must contain this default entry clearFormattedLineSplitPoints(); - currentHeader = NULL; + currentHeader = nullptr; currentLine = ""; readyFormattedLine = ""; formattedLine = ""; verbatimDelimiter = ""; currentChar = ' '; previousChar = ' '; previousCommandChar = ' '; - previousNonWSChar = ' '; + previousNonWSChar = ','; // not a potential name or operator quoteChar = '"'; preprocBlockEnd = 0; charNum = 0; checksumIn = 0; checksumOut = 0; - currentLineFirstBracketNum = string::npos; + currentLineFirstBraceNum = string::npos; formattedLineCommentNum = 0; leadingSpaces = 0; previousReadyFormattedLineLength = string::npos; - preprocBracketTypeStackSize = 0; + preprocBraceTypeStackSize = 0; spacePadNum = 0; + methodAttachCharNum = string::npos; + methodAttachLineNum = 0; + methodBreakCharNum = string::npos; + methodBreakLineNum = 0; nextLineSpacePadNum = 0; objCColonAlign = 0; templateDepth = 0; - blockParenCount = 0; - horstmannIndentChars = 0; + squareBracketCount = 0; + runInIndentChars = 0; tabIncrementIn = 0; - previousBracketType = NULL_TYPE; - previousOperator = NULL; + previousBraceType = NULL_TYPE; isVirgin = true; isInVirginLine = true; @@ -222,6 +230,7 @@ foundPreDefinitionHeader = false; foundPreCommandHeader = false; foundPreCommandMacro = false; + foundTrailingReturnType = false; foundCastOperator = false; foundQuestionMark = false; isInLineBreak = false; @@ -236,9 +245,9 @@ isLineReady = false; elseHeaderFollowsComments = false; caseHeaderFollowsComments = false; - isPreviousBracketBlockRelated = false; + isPreviousBraceBlockRelated = false; isInPotentialCalculation = false; - needHeaderOpeningBracket = false; + needHeaderOpeningBrace = false; shouldBreakLineAtNextChar = false; shouldKeepLineUnbroken = false; shouldReparseCurrentChar = false; @@ -272,17 +281,19 @@ isInObjCInterface = false; isInObjCMethodDefinition = false; isInObjCReturnType = false; + isInObjCParam = false; isInObjCSelector = false; breakCurrentOneLineBlock = false; - shouldRemoveNextClosingBracket = false; - isInBracketRunIn = false; - currentLineBeginsWithBracket = false; + shouldRemoveNextClosingBrace = false; + isInBraceRunIn = false; + returnTypeChecked = false; + currentLineBeginsWithBrace = false; isPrependPostBlockEmptyLineRequested = false; isAppendPostBlockEmptyLineRequested = false; isIndentableProprocessor = false; isIndentableProprocessorBlock = false; prependEmptyLine = false; - appendOpeningBracket = false; + appendOpeningBrace = false; foundClosingHeader = false; isImmediatelyPostHeader = false; isInHeader = false; @@ -330,109 +341,115 @@ { if (formattingStyle == STYLE_ALLMAN) { - setBracketFormatMode(BREAK_MODE); + setBraceFormatMode(BREAK_MODE); } else if (formattingStyle == STYLE_JAVA) { - setBracketFormatMode(ATTACH_MODE); + setBraceFormatMode(ATTACH_MODE); } else if (formattingStyle == STYLE_KR) { - setBracketFormatMode(LINUX_MODE); + setBraceFormatMode(LINUX_MODE); } else if (formattingStyle == STYLE_STROUSTRUP) { - setBracketFormatMode(LINUX_MODE); + setBraceFormatMode(LINUX_MODE); + setBreakClosingHeaderBracesMode(true); } else if (formattingStyle == STYLE_WHITESMITH) { - setBracketFormatMode(BREAK_MODE); - setBracketIndent(true); + setBraceFormatMode(BREAK_MODE); + setBraceIndent(true); setClassIndent(true); // avoid hanging indent with access modifiers setSwitchIndent(true); // avoid hanging indent with case statements } else if (formattingStyle == STYLE_VTK) { - // the unindented class bracket does NOT cause a hanging indent like Whitesmith - setBracketFormatMode(BREAK_MODE); - setBracketIndentVtk(true); // sets both bracketIndent and bracketIndentVtk + // the unindented class brace does NOT cause a hanging indent like Whitesmith + setBraceFormatMode(BREAK_MODE); + setBraceIndentVtk(true); // sets both braceIndent and braceIndentVtk setSwitchIndent(true); // avoid hanging indent with case statements } - else if (formattingStyle == STYLE_BANNER) + else if (formattingStyle == STYLE_RATLIFF) { - // attached brackets can have hanging indents with the closing bracket - setBracketFormatMode(ATTACH_MODE); - setBracketIndent(true); + // attached braces can have hanging indents with the closing brace + setBraceFormatMode(ATTACH_MODE); + setBraceIndent(true); setClassIndent(true); // avoid hanging indent with access modifiers setSwitchIndent(true); // avoid hanging indent with case statements } else if (formattingStyle == STYLE_GNU) { - setBracketFormatMode(BREAK_MODE); + setBraceFormatMode(BREAK_MODE); setBlockIndent(true); } else if (formattingStyle == STYLE_LINUX) { - setBracketFormatMode(LINUX_MODE); + setBraceFormatMode(LINUX_MODE); // always for Linux style setMinConditionalIndentOption(MINCOND_ONEHALF); } else if (formattingStyle == STYLE_HORSTMANN) { - setBracketFormatMode(RUN_IN_MODE); + setBraceFormatMode(RUN_IN_MODE); setSwitchIndent(true); } else if (formattingStyle == STYLE_1TBS) { - setBracketFormatMode(LINUX_MODE); - setAddBracketsMode(true); - setRemoveBracketsMode(false); + setBraceFormatMode(LINUX_MODE); + setAddBracesMode(true); + setRemoveBracesMode(false); } else if (formattingStyle == STYLE_GOOGLE) { - setBracketFormatMode(ATTACH_MODE); + setBraceFormatMode(ATTACH_MODE); setModifierIndent(true); setClassIndent(false); } else if (formattingStyle == STYLE_MOZILLA) { - setBracketFormatMode(LINUX_MODE); + setBraceFormatMode(LINUX_MODE); } else if (formattingStyle == STYLE_PICO) { - setBracketFormatMode(RUN_IN_MODE); - setAttachClosingBracketMode(true); + setBraceFormatMode(RUN_IN_MODE); + setAttachClosingBraceMode(true); setSwitchIndent(true); setBreakOneLineBlocksMode(false); setBreakOneLineStatementsMode(false); - // add-brackets won't work for pico, but it could be fixed if necessary + // add-braces won't work for pico, but it could be fixed if necessary // both options should be set to true - if (shouldAddBrackets) - shouldAddOneLineBrackets = true; + if (shouldAddBraces) + shouldAddOneLineBraces = true; } else if (formattingStyle == STYLE_LISP) { - setBracketFormatMode(ATTACH_MODE); - setAttachClosingBracketMode(true); + setBraceFormatMode(ATTACH_MODE); + setAttachClosingBraceMode(true); setBreakOneLineStatementsMode(false); - // add-one-line-brackets won't work for lisp - // only shouldAddBrackets should be set to true - if (shouldAddOneLineBrackets) + // add-one-line-braces won't work for lisp + // only shouldAddBraces should be set to true + if (shouldAddOneLineBraces) { - shouldAddBrackets = true; - shouldAddOneLineBrackets = false; + shouldAddBraces = true; + shouldAddOneLineBraces = false; } } setMinConditionalIndentLength(); // if not set by indent=force-tab-x set equal to indentLength - if (!getTabLength()) + if (getTabLength() == 0) setDefaultTabLength(); - // add-one-line-brackets implies keep-one-line-blocks - if (shouldAddOneLineBrackets) + // add-one-line-braces implies keep-one-line-blocks + if (shouldAddOneLineBraces) setBreakOneLineBlocksMode(false); - // don't allow add-brackets and remove-brackets - if (shouldAddBrackets || shouldAddOneLineBrackets) - setRemoveBracketsMode(false); + // don't allow add-braces and remove-braces + if (shouldAddBraces || shouldAddOneLineBraces) + setRemoveBracesMode(false); + // don't allow break-return-type and attach-return-type + if (shouldBreakReturnType) + shouldAttachReturnType = false; + if (shouldBreakReturnTypeDecl) + shouldAttachReturnTypeDecl = false; // don't allow indent-classes and indent-modifiers if (getClassIndent()) setModifierIndent(false); @@ -445,7 +462,7 @@ */ string ASFormatter::nextLine() { - const string* newHeader = NULL; + const string* newHeader = nullptr; isInVirginLine = isVirgin; isCharImmediatelyPostComment = false; isPreviousCharPostComment = false; @@ -467,16 +484,16 @@ { // make sure that a virgin '{' at the beginning of the file will be treated as a block... if (isInVirginLine && currentChar == '{' - && currentLineBeginsWithBracket + && currentLineBeginsWithBrace && previousCommandChar == ' ') previousCommandChar = '{'; if (isInClassInitializer - && isBracketType(bracketTypeStack->back(), COMMAND_TYPE)) + && isBraceType(braceTypeStack->back(), COMMAND_TYPE)) isInClassInitializer = false; - if (isInBracketRunIn) + if (isInBraceRunIn) isInLineBreak = false; if (!isWhiteSpace(currentChar)) - isInBracketRunIn = false; + isInBraceRunIn = false; isPreviousCharPostComment = isCharImmediatelyPostComment; isCharImmediatelyPostComment = false; isCharImmediatelyPostTemplate = false; @@ -513,7 +530,7 @@ if (isInLineBreak) // is true if not the first line breakLine(); formattedLine = currentLine; - charNum = (int)currentLine.length() - 1; + charNum = (int) currentLine.length() - 1; continue; } @@ -585,14 +602,14 @@ || findKeyword(preproc, 0, "line"))) { currentLine = rtrim(currentLine); // trim the end only - // check for horstmann run-in + // check for run-in if (formattedLine.length() > 0 && formattedLine[0] == '{') { isInLineBreak = true; - isInBracketRunIn = false; + isInBraceRunIn = false; } if (previousCommandChar == '}') - currentHeader = NULL; + currentHeader = nullptr; isInLineComment = true; appendCurrentChar(); continue; @@ -611,10 +628,10 @@ continue; } - if (shouldRemoveNextClosingBracket && currentChar == '}') + if (shouldRemoveNextClosingBrace && currentChar == '}') { currentLine[charNum] = currentChar = ' '; - shouldRemoveNextClosingBracket = false; + shouldRemoveNextClosingBrace = false; assert(adjustChecksumIn(-'}')); if (isEmptyLine(currentLine)) continue; @@ -632,20 +649,22 @@ // check if in preprocessor // ** isInPreprocessor will be automatically reset at the beginning // of a new line in getnextChar() - if (currentChar == '#') + if (currentChar == '#' + && currentLine.find_first_not_of(" \t") == (size_t) charNum + && !isBraceType(braceTypeStack->back(), SINGLE_LINE_TYPE)) { isInPreprocessor = true; - // check for horstmann run-in + // check for run-in if (formattedLine.length() > 0 && formattedLine[0] == '{') { isInLineBreak = true; - isInBracketRunIn = false; + isInBraceRunIn = false; } processPreprocessor(); // if top level it is potentially indentable if (shouldIndentPreprocBlock - && (isBracketType(bracketTypeStack->back(), NULL_TYPE) - || isBracketType(bracketTypeStack->back(), NAMESPACE_TYPE)) + && (isBraceType(braceTypeStack->back(), NULL_TYPE) + || isBraceType(braceTypeStack->back(), NAMESPACE_TYPE)) && !foundClassHeader && !isInClassInitializer && sourceIterator->tellg() > preprocBlockEnd) @@ -727,32 +746,33 @@ // reset isImmediatelyPostHeader information if (isImmediatelyPostHeader) { - // should brackets be added + // should braces be added if (currentChar != '{' - && shouldAddBrackets + && shouldAddBraces + && currentChar != '#' // don't add to preprocessor && (shouldBreakOneLineStatements || !isHeaderInMultiStatementLine) - && isOkToBreakBlock(bracketTypeStack->back())) + && isOkToBreakBlock(braceTypeStack->back())) { - bool bracketsAdded = addBracketsToStatement(); - if (bracketsAdded && !shouldAddOneLineBrackets) + bool bracesAdded = addBracesToStatement(); + if (bracesAdded && !shouldAddOneLineBraces) { size_t firstText = currentLine.find_first_not_of(" \t"); assert(firstText != string::npos); if ((int) firstText == charNum || shouldBreakOneLineHeaders) breakCurrentOneLineBlock = true; } } - // should brackets be removed - else if (currentChar == '{' && shouldRemoveBrackets) + // should braces be removed + else if (currentChar == '{' && shouldRemoveBraces) { - bool bracketsRemoved = removeBracketsFromStatement(); - if (bracketsRemoved) + bool bracesRemoved = removeBracesFromStatement(); + if (bracesRemoved) { - shouldRemoveNextClosingBracket = true; + shouldRemoveNextClosingBrace = true; if (isBeforeAnyLineEndComment(charNum)) spacePadNum--; else if (shouldBreakOneLineBlocks - || (currentLineBeginsWithBracket + || (currentLineBeginsWithBrace && currentLine.find_first_not_of(" \t") != string::npos)) shouldBreakLineAtNextChar = true; continue; @@ -762,14 +782,14 @@ // break 'else-if' if shouldBreakElseIfs is requested if (shouldBreakElseIfs && currentHeader == &AS_ELSE - && isOkToBreakBlock(bracketTypeStack->back()) + && isOkToBreakBlock(braceTypeStack->back()) && !isBeforeAnyComment() && (shouldBreakOneLineStatements || !isHeaderInMultiStatementLine)) { string nextText = peekNextText(currentLine.substr(charNum)); if (nextText.length() > 0 && isCharPotentialHeader(nextText, 0) - && ASBeautifier::findHeader(nextText, 0, headers) == &AS_IF) + && ASBase::findHeader(nextText, 0, headers) == &AS_IF) { isInLineBreak = true; } @@ -781,12 +801,12 @@ && (shouldBreakOneLineStatements || (!isHeaderInMultiStatementLine && !isMultiStatementLine())) - && isOkToBreakBlock(bracketTypeStack->back()) + && isOkToBreakBlock(braceTypeStack->back()) && !isBeforeAnyComment()) { if (currentChar == '{') { - if (!currentLineBeginsWithBracket) + if (!currentLineBeginsWithBrace) { if (isOneLineBlockReached(currentLine, charNum) == 3) isInLineBreak = false; @@ -799,7 +819,7 @@ string nextText = peekNextText(currentLine.substr(charNum), true); if (nextText.length() > 0 && ((isCharPotentialHeader(nextText, 0) - && ASBeautifier::findHeader(nextText, 0, headers) != &AS_IF) + && ASBase::findHeader(nextText, 0, headers) != &AS_IF) || nextText[0] == '{')) isInLineBreak = true; } @@ -818,9 +838,9 @@ if (parenStack->back() == 0 && !isCharImmediatelyPostComment && currentChar != ';') // allow ;; { // does a one-line block have ending comments? - if (isBracketType(bracketTypeStack->back(), SINGLE_LINE_TYPE)) + if (isBraceType(braceTypeStack->back(), SINGLE_LINE_TYPE)) { - size_t blockEnd = currentLine.rfind(AS_CLOSE_BRACKET); + size_t blockEnd = currentLine.rfind(AS_CLOSE_BRACE); assert(blockEnd != string::npos); // move ending comments to this formattedLine if (isBeforeAnyLineEndComment(blockEnd)) @@ -852,10 +872,10 @@ shouldReparseCurrentChar = true; if (formattedLine.find_first_not_of(" \t") != string::npos) isInLineBreak = true; - if (needHeaderOpeningBracket) + if (needHeaderOpeningBrace) { isCharImmediatelyPostCloseBlock = true; - needHeaderOpeningBracket = false; + needHeaderOpeningBrace = false; } continue; } @@ -880,16 +900,68 @@ checkIfTemplateOpener(); } + // Check for break return type + if ((size_t) charNum >= methodBreakCharNum && methodBreakLineNum == 0) + { + if ((size_t) charNum == methodBreakCharNum) + isInLineBreak = true; + methodBreakCharNum = string::npos; + methodBreakLineNum = 0; + } + // Check for attach return type + if ((size_t) charNum >= methodAttachCharNum && methodAttachLineNum == 0) + { + if ((size_t) charNum == methodAttachCharNum) + { + int pa = pointerAlignment; + int ra = referenceAlignment; + int itemAlignment = (previousNonWSChar == '*' || previousNonWSChar == '^') + ? pa : ((ra == REF_SAME_AS_PTR) ? pa : ra); + isInLineBreak = false; + if (previousNonWSChar == '*' || previousNonWSChar == '&' || previousNonWSChar == '^') + { + if (itemAlignment == REF_ALIGN_TYPE) + { + if (formattedLine.length() > 0 + && !isWhiteSpace(formattedLine[formattedLine.length() - 1])) + formattedLine.append(1, ' '); + } + else if (itemAlignment == REF_ALIGN_MIDDLE) + { + if (formattedLine.length() > 0 + && !isWhiteSpace(formattedLine[formattedLine.length() - 1])) + formattedLine.append(1, ' '); + } + else if (itemAlignment == REF_ALIGN_NAME) + { + if (formattedLine.length() > 0 + && isWhiteSpace(formattedLine[formattedLine.length() - 1])) + formattedLine.erase(formattedLine.length() - 1); + } + else + { + if (formattedLine.length() > 1 + && !isWhiteSpace(formattedLine[formattedLine.length() - 2])) + formattedLine.append(1, ' '); + } + } + else + formattedLine.append(1, ' '); + } + methodAttachCharNum = string::npos; + methodAttachLineNum = 0; + } + // handle parens if (currentChar == '(' || currentChar == '[' || (isInTemplate && currentChar == '<')) { questionMarkStack->push_back(foundQuestionMark); foundQuestionMark = false; parenStack->back()++; if (currentChar == '[') { - ++blockParenCount; - if (getAlignMethodColon() && blockParenCount == 1 && isCStyle()) + ++squareBracketCount; + if (getAlignMethodColon() && squareBracketCount == 1 && isCStyle()) objCColonAlign = findObjCColonAlignment(); } } @@ -924,10 +996,10 @@ } if (currentChar == ']') { - --blockParenCount; - if (blockParenCount <= 0) + --squareBracketCount; + if (squareBracketCount <= 0) { - blockParenCount = 0; + squareBracketCount = 0; objCColonAlign = 0; } } @@ -939,80 +1011,89 @@ } } - // handle brackets + // handle braces if (currentChar == '{' || currentChar == '}') { - // if appendOpeningBracket this was already done for the original bracket - if (currentChar == '{' && !appendOpeningBracket) + // if appendOpeningBrace this was already done for the original brace + if (currentChar == '{' && !appendOpeningBrace) { - BracketType newBracketType = getBracketType(); + BraceType newBraceType = getBraceType(); breakCurrentOneLineBlock = false; foundNamespaceHeader = false; foundClassHeader = false; foundStructHeader = false; foundInterfaceHeader = false; foundPreDefinitionHeader = false; foundPreCommandHeader = false; foundPreCommandMacro = false; + foundTrailingReturnType = false; isInPotentialCalculation = false; isInObjCMethodDefinition = false; + isImmediatelyPostObjCMethodPrefix = false; isInObjCInterface = false; isInEnum = false; isJavaStaticConstructor = false; isCharImmediatelyPostNonInStmt = false; - needHeaderOpeningBracket = false; + needHeaderOpeningBrace = false; shouldKeepLineUnbroken = false; + returnTypeChecked = false; objCColonAlign = 0; - - isPreviousBracketBlockRelated = !isBracketType(newBracketType, ARRAY_TYPE); - bracketTypeStack->push_back(newBracketType); - preBracketHeaderStack->push_back(currentHeader); - currentHeader = NULL; + //assert(methodBreakCharNum == string::npos); // comment out + //assert(methodBreakLineNum == 0); // comment out + methodBreakCharNum = string::npos; + methodBreakLineNum = 0; + methodAttachCharNum = string::npos; + methodAttachLineNum = 0; + + isPreviousBraceBlockRelated = !isBraceType(newBraceType, ARRAY_TYPE); + braceTypeStack->emplace_back(newBraceType); + preBraceHeaderStack->emplace_back(currentHeader); + currentHeader = nullptr; structStack->push_back(isInIndentableStruct); - if (isBracketType(newBracketType, STRUCT_TYPE) && isCStyle()) + if (isBraceType(newBraceType, 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) - ); + // this must be done before the braceTypeStack is popped + BraceType braceType = braceTypeStack->back(); + bool isOpeningArrayBrace = (isBraceType(braceType, ARRAY_TYPE) + && braceTypeStack->size() >= 2 + && !isBraceType((*braceTypeStack)[braceTypeStack->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, + // but the block exists immediately before a closing brace, // then there is no need for the post block empty line. isAppendPostBlockEmptyLineRequested = false; if (isInAsm) endOfAsmReached = true; isInAsmOneLine = isInQuote = false; shouldKeepLineUnbroken = false; - blockParenCount = 0; + squareBracketCount = 0; - if (bracketTypeStack->size() > 1) + if (braceTypeStack->size() > 1) { - previousBracketType = bracketTypeStack->back(); - bracketTypeStack->pop_back(); - isPreviousBracketBlockRelated = !isBracketType(bracketType, ARRAY_TYPE); + previousBraceType = braceTypeStack->back(); + braceTypeStack->pop_back(); + isPreviousBraceBlockRelated = !isBraceType(braceType, ARRAY_TYPE); } else { - previousBracketType = NULL_TYPE; - isPreviousBracketBlockRelated = false; + previousBraceType = NULL_TYPE; + isPreviousBraceBlockRelated = false; } - if (!preBracketHeaderStack->empty()) + if (!preBraceHeaderStack->empty()) { - currentHeader = preBracketHeaderStack->back(); - preBracketHeaderStack->pop_back(); + currentHeader = preBraceHeaderStack->back(); + preBraceHeaderStack->pop_back(); } else - currentHeader = NULL; + currentHeader = nullptr; if (!structStack->empty()) { @@ -1023,8 +1104,8 @@ isInIndentableStruct = false; if (isNonInStatementArray - && (!isBracketType(bracketTypeStack->back(), ARRAY_TYPE) // check previous bracket - || peekNextChar() == ';')) // check for "};" added V2.01 + && (!isBraceType(braceTypeStack->back(), ARRAY_TYPE) // check previous brace + || peekNextChar() == ';')) // check for "};" added V2.01 isImmediatelyPostNonInStmt = true; if (!shouldBreakOneLineStatements @@ -1037,42 +1118,42 @@ } } - // format brackets - appendOpeningBracket = false; - if (isBracketType(bracketType, ARRAY_TYPE)) + // format braces + appendOpeningBrace = false; + if (isBraceType(braceType, ARRAY_TYPE)) { - formatArrayBrackets(bracketType, isOpeningArrayBracket); + formatArrayBraces(braceType, isOpeningArrayBrace); } else { if (currentChar == '{') - formatOpeningBracket(bracketType); + formatOpeningBrace(braceType); else - formatClosingBracket(bracketType); + formatClosingBrace(braceType); } continue; } - if ((((previousCommandChar == '{' && isPreviousBracketBlockRelated) + if ((((previousCommandChar == '{' && isPreviousBraceBlockRelated) || ((previousCommandChar == '}' && !isImmediatelyPostEmptyBlock - && isPreviousBracketBlockRelated + && isPreviousBraceBlockRelated && !isPreviousCharPostComment // Fixes wrongly appended newlines after '}' immediately after comments && peekNextChar() != ' ' - && !isBracketType(previousBracketType, DEFINITION_TYPE)) - && !isBracketType(bracketTypeStack->back(), DEFINITION_TYPE))) - && isOkToBreakBlock(bracketTypeStack->back())) + && !isBraceType(previousBraceType, DEFINITION_TYPE)) + && !isBraceType(braceTypeStack->back(), DEFINITION_TYPE))) + && isOkToBreakBlock(braceTypeStack->back())) // check for array || (previousCommandChar == '{' // added 9/30/2010 - && isBracketType(bracketTypeStack->back(), ARRAY_TYPE) - && !isBracketType(bracketTypeStack->back(), SINGLE_LINE_TYPE) + && isBraceType(braceTypeStack->back(), ARRAY_TYPE) + && !isBraceType(braceTypeStack->back(), SINGLE_LINE_TYPE) && isNonInStatementArray) - // check for pico one line brackets + // check for pico one line braces || (formattingStyle == STYLE_PICO - && (previousCommandChar == '{' && isPreviousBracketBlockRelated) - && isBracketType(bracketTypeStack->back(), COMMAND_TYPE) - && isBracketType(bracketTypeStack->back(), SINGLE_LINE_TYPE) - && bracketFormatMode == RUN_IN_MODE) + && (previousCommandChar == '{' && isPreviousBraceBlockRelated) + && isBraceType(braceTypeStack->back(), COMMAND_TYPE) + && isBraceType(braceTypeStack->back(), SINGLE_LINE_TYPE) + && braceFormatMode == RUN_IN_MODE) ) { isCharImmediatelyPostOpenBlock = (previousCommandChar == '{'); @@ -1084,27 +1165,32 @@ { previousCommandChar = ' '; - if (bracketFormatMode == NONE_MODE) + if (braceFormatMode == NONE_MODE) { - if (isBracketType(bracketTypeStack->back(), SINGLE_LINE_TYPE) - && (isBracketType(bracketTypeStack->back(), BREAK_BLOCK_TYPE) + if (isBraceType(braceTypeStack->back(), SINGLE_LINE_TYPE) + && (isBraceType(braceTypeStack->back(), BREAK_BLOCK_TYPE) || shouldBreakOneLineBlocks)) isInLineBreak = true; - else if (currentLineBeginsWithBracket) + else if (currentLineBeginsWithBrace) formatRunIn(); else breakLine(); } - else if (bracketFormatMode == RUN_IN_MODE + else if (braceFormatMode == RUN_IN_MODE && currentChar != '#') formatRunIn(); else isInLineBreak = true; } else if (isCharImmediatelyPostCloseBlock && shouldBreakOneLineStatements - && (isLegalNameChar(currentChar) && currentChar != '.') - && !isCharImmediatelyPostComment) + && !isCharImmediatelyPostComment + && ((isLegalNameChar(currentChar) && currentChar != '.') + || currentChar == '+' + || currentChar == '-' + || currentChar == '*' + || currentChar == '&' + || currentChar == '(')) { previousCommandChar = ' '; isInLineBreak = true; @@ -1114,55 +1200,86 @@ // reset block handling flags isImmediatelyPostEmptyBlock = false; + // Objective-C method prefix with no return type + if (isImmediatelyPostObjCMethodPrefix && currentChar != '(') + { + if (shouldPadMethodPrefix || shouldUnPadMethodPrefix) + padObjCMethodPrefix(); + isImmediatelyPostObjCMethodPrefix = false; + } + // look for headers bool isPotentialHeader = isCharPotentialHeader(currentLine, charNum); - if (isPotentialHeader && !isInTemplate && !blockParenCount) + if (isPotentialHeader && !isInTemplate && squareBracketCount == 0) { isNonParenHeader = false; foundClosingHeader = false; newHeader = findHeader(headers); + // java can have a 'default' not in a switch + if (newHeader == &AS_DEFAULT + && ASBeautifier::peekNextChar( + currentLine, charNum + (*newHeader).length() - 1) != ':') + newHeader = nullptr; // Qt headers may be variables in C++ if (isCStyle() && (newHeader == &AS_FOREVER || newHeader == &AS_FOREACH)) { if (currentLine.find_first_of("=;", charNum) != string::npos) - newHeader = NULL; + newHeader = nullptr; } if (isJavaStyle() && (newHeader == &AS_SYNCHRONIZED)) { // want synchronized statements not synchronized methods - if (!isBracketType(bracketTypeStack->back(), COMMAND_TYPE)) - newHeader = NULL; + if (!isBraceType(braceTypeStack->back(), COMMAND_TYPE)) + newHeader = nullptr; } else if (newHeader == &AS_USING && ASBeautifier::peekNextChar( currentLine, charNum + (*newHeader).length() - 1) != '(') - newHeader = NULL; + newHeader = nullptr; - if (newHeader != NULL) + if (newHeader != nullptr) { foundClosingHeader = isClosingHeader(newHeader); - if (!foundClosingHeader - && ((newHeader == &AS_WHILE && currentHeader == &AS_DO) - || (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; + if (!foundClosingHeader) + { + // these are closing headers + if ((newHeader == &AS_WHILE && currentHeader == &AS_DO) + || (newHeader == &_AS_FINALLY && currentHeader == &_AS_TRY) + || (newHeader == &_AS_EXCEPT && currentHeader == &_AS_TRY)) + foundClosingHeader = true; + // don't append empty block for these related headers + else if (isSharpStyle() + && previousNonWSChar == '}' + && ((newHeader == &AS_SET && currentHeader == &AS_GET) + || (newHeader == &AS_REMOVE && currentHeader == &AS_ADD)) + && isOkToBreakBlock(braceTypeStack->back())) + isAppendPostBlockEmptyLineRequested = false; + } + + // TODO: this can be removed in a future release + // version 3.0 - break erroneous attached header from previous versions + if (isSharpStyle() + && ((newHeader == &AS_SET && currentHeader == &AS_GET) + || (newHeader == &AS_REMOVE && currentHeader == &AS_ADD)) + && !isBraceType(braceTypeStack->back(), SINGLE_LINE_TYPE) + && currentLine[currentLine.find_first_not_of(" \t")] == '}') + isInLineBreak = true; + // END TODO const string* previousHeader = currentHeader; currentHeader = newHeader; - needHeaderOpeningBracket = true; + needHeaderOpeningBrace = true; // is the previous statement on the same line? if ((previousNonWSChar == ';' || previousNonWSChar == ':') && !isInLineBreak - && isOkToBreakBlock(bracketTypeStack->back())) + && isOkToBreakBlock(braceTypeStack->back())) { // if breaking lines, break the line at the header // except for multiple 'case' statements on a line @@ -1175,7 +1292,7 @@ if (foundClosingHeader && previousNonWSChar == '}') { - if (isOkToBreakBlock(bracketTypeStack->back())) + if (isOkToBreakBlock(braceTypeStack->back())) isLineBreakBeforeClosingHeader(); // get the adjustment for a comment following the closing header @@ -1186,7 +1303,7 @@ } // check if the found header is non-paren header - isNonParenHeader = findHeader(nonParenHeaders) != NULL; + isNonParenHeader = findHeader(nonParenHeaders) != nullptr; if (isNonParenHeader && (currentHeader == &AS_CATCH @@ -1242,10 +1359,10 @@ } if (shouldBreakBlocks - && isOkToBreakBlock(bracketTypeStack->back()) + && isOkToBreakBlock(braceTypeStack->back()) && !isHeaderInMultiStatementLine) { - if (previousHeader == NULL + if (previousHeader == nullptr && !foundClosingHeader && !isCharImmediatelyPostOpenBlock && !isImmediatelyPostCommentOnly) @@ -1275,7 +1392,7 @@ continue; } - else if ((newHeader = findHeader(preDefinitionHeaders)) != NULL + else if ((newHeader = findHeader(preDefinitionHeaders)) != nullptr && parenStack->back() == 0 && !isInEnum) // not C++11 enum class { @@ -1285,21 +1402,21 @@ foundClassHeader = true; if (newHeader == &AS_STRUCT) foundStructHeader = true; - if (newHeader == &AS_INTERFACE) + if (newHeader == &AS_INTERFACE && !foundNamespaceHeader && !foundClassHeader) foundInterfaceHeader = true; foundPreDefinitionHeader = true; appendSequence(*newHeader); goForward(newHeader->length() - 1); continue; } - else if ((newHeader = findHeader(preCommandHeaders)) != NULL) + else if ((newHeader = findHeader(preCommandHeaders)) != nullptr) { - // a 'const' variable is not a preCommandHeader + // must be after function arguments if (previousNonWSChar == ')') foundPreCommandHeader = true; } - else if ((newHeader = findHeader(castOperators)) != NULL) + else if ((newHeader = findHeader(castOperators)) != nullptr) { foundCastOperator = true; appendSequence(*newHeader); @@ -1327,12 +1444,18 @@ { if (currentChar == ';') { - blockParenCount = 0; + squareBracketCount = 0; + //assert(methodBreakCharNum == string::npos); // comment out + //assert(methodBreakLineNum == 0); // comment out + methodBreakCharNum = string::npos; + methodBreakLineNum = 0; + methodAttachCharNum = string::npos; + methodAttachLineNum = 0; if (((shouldBreakOneLineStatements - || isBracketType(bracketTypeStack->back(), SINGLE_LINE_TYPE)) - && isOkToBreakBlock(bracketTypeStack->back())) - && !(attachClosingBracketMode && peekNextChar() == '}')) + || isBraceType(braceTypeStack->back(), SINGLE_LINE_TYPE)) + && isOkToBreakBlock(braceTypeStack->back())) + && !(attachClosingBraceMode && peekNextChar() == '}')) { passedSemicolon = true; } @@ -1346,7 +1469,7 @@ } if (shouldBreakBlocks - && currentHeader != NULL + && currentHeader != nullptr && currentHeader != &AS_CASE && currentHeader != &AS_DEFAULT && !isHeaderInMultiStatementLine @@ -1356,8 +1479,9 @@ } } if (currentChar != ';' - || (needHeaderOpeningBracket && parenStack->back() == 0)) - currentHeader = NULL; + || (needHeaderOpeningBrace && parenStack->back() == 0)) + currentHeader = nullptr; + resetEndOfStatement(); } @@ -1372,13 +1496,13 @@ passedColon = true; } else if (isCStyle() // for C/C++ only - && isOkToBreakBlock(bracketTypeStack->back()) + && isOkToBreakBlock(braceTypeStack->back()) && shouldBreakOneLineStatements && !foundQuestionMark // not in a ?: sequence && !foundPreDefinitionHeader // not in a definition block && previousCommandChar != ')' // not after closing paren of a method header && !foundPreCommandHeader // not after a 'noexcept' - && !blockParenCount // not in objC method call + && squareBracketCount == 0 // not in objC method call && !isInObjCMethodDefinition // not objC '-' or '+' method && !isInObjCInterface // not objC @interface && !isInObjCSelector // not objC @selector @@ -1392,10 +1516,15 @@ } if (isCStyle() - && shouldPadMethodColon - && (blockParenCount > 0 || isInObjCMethodDefinition || isInObjCSelector) + && (squareBracketCount > 0 || isInObjCMethodDefinition || isInObjCSelector) && !foundQuestionMark) // not in a ?: sequence - padObjCMethodColon(); + { + isImmediatelyPostObjCMethodPrefix = false; + isInObjCReturnType = false; + isInObjCParam = true; + if (shouldPadMethodColon) + padObjCMethodColon(); + } if (isInObjCInterface) { @@ -1423,8 +1552,8 @@ if (findKeyword(currentLine, charNum, AS_RETURN)) { - isInPotentialCalculation = true; // return is the same as an = sign - isImmediatelyPostReturn = true; + isInPotentialCalculation = true; + isImmediatelyPostReturn = true; // return is the same as an = sign } if (findKeyword(currentLine, charNum, AS_OPERATOR)) @@ -1448,6 +1577,33 @@ if (isCStyle() && findKeyword(currentLine, charNum, AS_EXTERN) && isExternC()) isInExternC = true; + if (isCStyle() && findKeyword(currentLine, charNum, AS_AUTO) + && (isBraceType(braceTypeStack->back(), NULL_TYPE) + || isBraceType(braceTypeStack->back(), DEFINITION_TYPE))) + foundTrailingReturnType = true; + + // check for break/attach return type + if (shouldBreakReturnType || shouldBreakReturnTypeDecl + || shouldAttachReturnType || shouldAttachReturnTypeDecl) + { + if ((isBraceType(braceTypeStack->back(), NULL_TYPE) + || isBraceType(braceTypeStack->back(), DEFINITION_TYPE)) + && !returnTypeChecked + && !foundNamespaceHeader + && !foundClassHeader + && !isInObjCMethodDefinition + // bypass objective-C and java @ character + && charNum == (int) currentLine.find_first_not_of(" \t") + && !(isCStyle() && isCharPotentialHeader(currentLine, charNum) + && (findKeyword(currentLine, charNum, AS_PUBLIC) + || findKeyword(currentLine, charNum, AS_PRIVATE) + || findKeyword(currentLine, charNum, AS_PROTECTED)))) + { + findReturnTypeSplitPoint(currentLine); + returnTypeChecked = true; + } + } + // Objective-C NSException macros are preCommandHeaders if (isCStyle() && findKeyword(currentLine, charNum, AS_NS_DURING)) foundPreCommandMacro = true; @@ -1481,7 +1637,7 @@ if (isJavaStyle() && (findKeyword(currentLine, charNum, AS_STATIC) - && isNextCharOpeningBracket(charNum + 6))) + && isNextCharOpeningBrace(charNum + 6))) isJavaStaticConstructor = true; if (isSharpStyle() @@ -1523,17 +1679,23 @@ // determine if this is an Objective-C statement if (currentChar == '@' + && isCStyle() + && (int) currentLine.length() > charNum + 1 + && !isWhiteSpace(currentLine[charNum + 1]) && isCharPotentialHeader(currentLine, charNum + 1) && findKeyword(currentLine, charNum + 1, AS_INTERFACE) - && isBracketType(bracketTypeStack->back(), NULL_TYPE)) + && isBraceType(braceTypeStack->back(), NULL_TYPE)) { isInObjCInterface = true; string name = '@' + AS_INTERFACE; appendSequence(name); goForward(name.length() - 1); continue; } else if (currentChar == '@' + && isCStyle() + && (int) currentLine.length() > charNum + 1 + && !isWhiteSpace(currentLine[charNum + 1]) && isCharPotentialHeader(currentLine, charNum + 1) && findKeyword(currentLine, charNum + 1, AS_SELECTOR)) { @@ -1544,13 +1706,16 @@ continue; } else if ((currentChar == '-' || currentChar == '+') + && isCStyle() && (int) currentLine.find_first_not_of(" \t") == charNum - && peekNextChar() == '(' - && isBracketType(bracketTypeStack->back(), NULL_TYPE) - && !isInPotentialCalculation) + && !isInPotentialCalculation + && !isInObjCMethodDefinition + && (isBraceType(braceTypeStack->back(), NULL_TYPE) + || (isBraceType(braceTypeStack->back(), EXTERN_TYPE)))) { isInObjCMethodDefinition = true; isImmediatelyPostObjCMethodPrefix = true; + isInObjCParam = false; isInObjCInterface = false; if (getAlignMethodColon()) objCColonAlign = findObjCColonAlignment(); @@ -1561,17 +1726,20 @@ // determine if this is a potential calculation bool isPotentialOperator = isCharPotentialOperator(currentChar); - newHeader = NULL; + newHeader = nullptr; if (isPotentialOperator) { newHeader = findOperator(operators); // check for Java ? wildcard - if (newHeader == &AS_GCC_MIN_ASSIGN && isJavaStyle() && isInTemplate) - newHeader = NULL; + if (newHeader != nullptr + && newHeader == &AS_GCC_MIN_ASSIGN + && isJavaStyle() + && isInTemplate) + newHeader = nullptr; - if (newHeader != NULL) + if (newHeader != nullptr) { if (newHeader == &AS_LAMBDA) foundPreCommandHeader = true; @@ -1583,9 +1751,9 @@ if (!isInPotentialCalculation) { // must determine if newHeader is an assignment operator - // do NOT use findOperator!!! - if (find(assignmentOperators->begin(), assignmentOperators->end(), newHeader) - != assignmentOperators->end()) + // do NOT use findOperator - the length must be exact!!! + if (find(begin(*assignmentOperators), end(*assignmentOperators), newHeader) + != end(*assignmentOperators)) { foundPreCommandHeader = false; char peekedChar = peekNextChar(); @@ -1599,7 +1767,7 @@ // process pointers and references // check newHeader to eliminate things like '&&' sequence - if (!isJavaStyle() + if (newHeader != nullptr && !isJavaStyle() && (newHeader == &AS_MULT || newHeader == &AS_BIT_AND || newHeader == &AS_BIT_XOR @@ -1617,7 +1785,7 @@ continue; } - if (shouldPadOperators && newHeader != NULL && !isOperatorPaddingDisabled()) + if (shouldPadOperators && newHeader != nullptr && !isOperatorPaddingDisabled()) { padOperators(newHeader); continue; @@ -1650,7 +1818,7 @@ && nextChar != '>' && nextChar != ';' && !isBeforeAnyComment() - /* && !(isBracketType(bracketTypeStack->back(), ARRAY_TYPE)) */ + /* && !(isBraceType(braceTypeStack->back(), ARRAY_TYPE)) */ ) { appendCurrentChar(); @@ -1691,14 +1859,15 @@ padObjCReturnType(); isInObjCReturnType = false; } - else if (shouldPadParamType || shouldUnPadParamType) + else if (isInObjCParam + && (shouldPadParamType || shouldUnPadParamType)) padObjCParamType(); } continue; } // bypass the entire operator - if (newHeader != NULL) + if (newHeader != nullptr) { appendOperator(*newHeader); goForward(newHeader->length() - 1); @@ -1713,7 +1882,7 @@ string beautifiedLine; size_t readyFormattedLineLength = trim(readyFormattedLine).length(); - bool isInNamespace = isBracketType(bracketTypeStack->back(), NAMESPACE_TYPE); + bool isInNamespace = isBraceType(braceTypeStack->back(), NAMESPACE_TYPE); if (prependEmptyLine // prepend a blank line before this formatted line && readyFormattedLineLength > 0 @@ -1728,13 +1897,13 @@ else // format the current formatted line { isLineReady = false; - horstmannIndentInStatement = horstmannIndentChars; + runInIndentContinuation = runInIndentChars; beautifiedLine = beautify(readyFormattedLine); previousReadyFormattedLineLength = readyFormattedLineLength; // the enhancer is not called for no-indent line comments if (!lineCommentNoBeautify && !isFormattingModeOff) enhancer->enhance(beautifiedLine, isInNamespace, isInPreprocessorBeautify, isInBeautifySQL); - horstmannIndentChars = 0; + runInIndentChars = 0; lineCommentNoBeautify = lineCommentNoIndent; lineCommentNoIndent = false; isInIndentablePreproc = isIndentableProprocessor; @@ -1767,9 +1936,9 @@ } /** - * comparison function for BracketType enum + * comparison function for BraceType enum */ -bool ASFormatter::isBracketType(BracketType a, BracketType b) const +bool ASFormatter::isBraceType(BraceType a, BraceType b) const { if (a == NULL_TYPE || b == NULL_TYPE) return (a == b); @@ -1787,54 +1956,86 @@ } /** - * set the add brackets mode. + * set the add braces mode. * options: - * true brackets added to headers for single line statements. - * false brackets NOT added to headers for single line statements. + * true braces added to headers for single line statements. + * false braces NOT added to headers for single line statements. * - * @param state the add brackets state. + * @param state the add braces state. */ -void ASFormatter::setAddBracketsMode(bool state) +void ASFormatter::setAddBracesMode(bool state) { - shouldAddBrackets = state; + shouldAddBraces = state; } /** - * set the add one line brackets mode. + * set the add one line braces mode. * options: - * true one line brackets added to headers for single line statements. - * false one line brackets NOT added to headers for single line statements. + * true one line braces added to headers for single line statements. + * false one line braces NOT added to headers for single line statements. * - * @param state the add one line brackets state. + * @param state the add one line braces state. */ -void ASFormatter::setAddOneLineBracketsMode(bool state) +void ASFormatter::setAddOneLineBracesMode(bool state) { - shouldAddBrackets = state; - shouldAddOneLineBrackets = state; + shouldAddBraces = state; + shouldAddOneLineBraces = state; } /** - * set the remove brackets mode. + * set the remove braces mode. * options: - * true brackets removed from headers for single line statements. - * false brackets NOT removed from headers for single line statements. + * true braces removed from headers for single line statements. + * false braces NOT removed from headers for single line statements. * - * @param state the remove brackets state. + * @param state the remove braces state. */ +void ASFormatter::setRemoveBracesMode(bool state) +{ + shouldRemoveBraces = state; +} + +// retained for compatibility with release 2.06 +// "Brackets" have been changed to "Braces" in 3.0 +// it is referenced only by the old "bracket" options +void ASFormatter::setAddBracketsMode(bool state) +{ + setAddBracesMode(state); +} + +// retained for compatibility with release 2.06 +// "Brackets" have been changed to "Braces" in 3.0 +// it is referenced only by the old "bracket" options +void ASFormatter::setAddOneLineBracketsMode(bool state) +{ + setAddOneLineBracesMode(state); +} + +// retained for compatibility with release 2.06 +// "Brackets" have been changed to "Braces" in 3.0 +// it is referenced only by the old "bracket" options void ASFormatter::setRemoveBracketsMode(bool state) { - shouldRemoveBrackets = state; + setRemoveBracesMode(state); +} + +// retained for compatibility with release 2.06 +// "Brackets" have been changed to "Braces" in 3.0 +// it is referenced only by the old "bracket" options +void ASFormatter::setBreakClosingHeaderBracketsMode(bool state) +{ + setBreakClosingHeaderBracesMode(state); } /** - * set the bracket formatting mode. + * set the brace formatting mode. * options: * - * @param mode the bracket formatting mode. + * @param mode the brace formatting mode. */ -void ASFormatter::setBracketFormatMode(BracketMode mode) +void ASFormatter::setBraceFormatMode(BraceMode mode) { - bracketFormatMode = mode; + braceFormatMode = mode; } /** @@ -1848,17 +2049,17 @@ } /** - * set closing header bracket breaking mode + * set closing header brace breaking mode * options: - * true brackets just before closing headers (e.g. 'else', 'catch') - * will be broken, even if standard brackets are attached. - * false closing header brackets will be treated as standard brackets. + * true braces just before closing headers (e.g. 'else', 'catch') + * will be broken, even if standard braces are attached. + * false closing header braces will be treated as standard braces. * - * @param state the closing header bracket breaking mode. + * @param state the closing header brace breaking mode. */ -void ASFormatter::setBreakClosingHeaderBracketsMode(bool state) +void ASFormatter::setBreakClosingHeaderBracesMode(bool state) { - shouldBreakClosingHeaderBrackets = state; + shouldBreakClosingHeaderBraces = state; } /** @@ -2061,17 +2262,17 @@ } /** - * set option to attach closing brackets + * set option to attach closing braces * * @param state true = attach, false = don't attach. */ -void ASFormatter::setAttachClosingBracketMode(bool state) +void ASFormatter::setAttachClosingBraceMode(bool state) { - attachClosingBracketMode = state; + attachClosingBraceMode = state; } /** - * set option to attach class brackets + * set option to attach class braces * * @param state true = attach, false = use style default. */ @@ -2081,7 +2282,7 @@ } /** - * set option to attach extern "C" brackets + * set option to attach extern "C" braces * * @param state true = attach, false = use style default. */ @@ -2091,7 +2292,7 @@ } /** - * set option to attach namespace brackets + * set option to attach namespace braces * * @param state true = attach, false = use style default. */ @@ -2101,15 +2302,20 @@ } /** - * set option to attach inline brackets + * set option to attach inline braces * * @param state true = attach, false = use style default. */ void ASFormatter::setAttachInline(bool state) { shouldAttachInline = state; } +void ASFormatter::setAttachClosingWhile(bool state) +{ + shouldAttachClosingWhile = state; +} + /** * set option to break/not break one-line blocks * @@ -2203,6 +2409,26 @@ shouldDeleteEmptyLines = state; } +void ASFormatter::setBreakReturnType(bool state) +{ + shouldBreakReturnType = state; +} + +void ASFormatter::setBreakReturnTypeDecl(bool state) +{ + shouldBreakReturnTypeDecl = state; +} + +void ASFormatter::setAttachReturnType(bool state) +{ + shouldAttachReturnType = state; +} + +void ASFormatter::setAttachReturnTypeDecl(bool state) +{ + shouldAttachReturnTypeDecl = state; +} + /** * set the pointer alignment. * @@ -2393,8 +2619,8 @@ endOfCodeReached = true; return false; } - if (appendOpeningBracket) - currentLine = "{"; // append bracket that was removed from the previous line + if (appendOpeningBrace) + currentLine = "{"; // append brace that was removed from the previous line else { currentLine = sourceIterator->nextLine(emptyLineWasDeleted); @@ -2417,6 +2643,11 @@ if (currentLine.length() == 0) currentLine = string(" "); // a null is inserted if this is not done + if (methodBreakLineNum > 0) + --methodBreakLineNum; + if (methodAttachLineNum > 0) + --methodAttachLineNum; + // unless reading in the first line of the file, break a new line. if (!isVirgin) isInLineBreak = true; @@ -2442,19 +2673,19 @@ initNewLine(); currentChar = currentLine[charNum]; - if (isInBracketRunIn && previousNonWSChar == '{' && !isInComment) + if (isInBraceRunIn && previousNonWSChar == '{' && !isInComment) isInLineBreak = false; - isInBracketRunIn = false; + isInBraceRunIn = false; if (currentChar == '\t' && shouldConvertTabs) convertTabToSpaces(); - // check for an empty line inside a command bracket. + // check for an empty line inside a command brace. // if yes then read the next line (calls getNextLine recursively). // must be after initNewLine. if (shouldDeleteEmptyLines && lineIsEmpty - && isBracketType((*bracketTypeStack)[bracketTypeStack->size() - 1], COMMAND_TYPE)) + && isBraceType((*braceTypeStack)[braceTypeStack->size() - 1], COMMAND_TYPE)) { if (!shouldBreakBlocks || previousNonWSChar == '{' || !commentAndHeaderFollows()) { @@ -2522,9 +2753,9 @@ lineIsLineCommentOnly = false; lineEndsInCommentOnly = false; doesLineStartComment = false; - currentLineBeginsWithBracket = false; + currentLineBeginsWithBrace = false; lineIsEmpty = false; - currentLineFirstBracketNum = string::npos; + currentLineFirstBraceNum = string::npos; tabIncrementIn = 0; // bypass whitespace at the start of a line @@ -2549,8 +2780,8 @@ } else if (isSequenceReached("{")) { - currentLineBeginsWithBracket = true; - currentLineFirstBracketNum = charNum; + currentLineBeginsWithBrace = true; + currentLineFirstBraceNum = charNum; size_t firstText = currentLine.find_first_not_of(" \t", charNum + 1); if (firstText != string::npos) { @@ -2723,55 +2954,57 @@ } /** - * check if the currently reached open-bracket (i.e. '{') + * check if the currently reached open-brace (i.e. '{') * opens a: * - a definition type block (such as a class or namespace), * - a command block (such as a method block) * - a static array * this method takes for granted that the current character - * is an opening bracket. + * is an opening brace. * * @return the type of the opened block. */ -BracketType ASFormatter::getBracketType() +BraceType ASFormatter::getBraceType() { assert(currentChar == '{'); - BracketType returnVal = NULL_TYPE; + BraceType returnVal = NULL_TYPE; if ((previousNonWSChar == '=' - || isBracketType(bracketTypeStack->back(), ARRAY_TYPE)) + || isBraceType(braceTypeStack->back(), ARRAY_TYPE)) && previousCommandChar != ')' && !isNonParenHeader) returnVal = ARRAY_TYPE; else if (foundPreDefinitionHeader && previousCommandChar != ')') { returnVal = DEFINITION_TYPE; if (foundNamespaceHeader) - returnVal = (BracketType)(returnVal | NAMESPACE_TYPE); + returnVal = (BraceType)(returnVal | NAMESPACE_TYPE); else if (foundClassHeader) - returnVal = (BracketType)(returnVal | CLASS_TYPE); + returnVal = (BraceType)(returnVal | CLASS_TYPE); else if (foundStructHeader) - returnVal = (BracketType)(returnVal | STRUCT_TYPE); + returnVal = (BraceType)(returnVal | STRUCT_TYPE); else if (foundInterfaceHeader) - returnVal = (BracketType)(returnVal | INTERFACE_TYPE); + returnVal = (BraceType)(returnVal | INTERFACE_TYPE); } else if (isInEnum) { - returnVal = (BracketType)(ARRAY_TYPE | ENUM_TYPE); + returnVal = (BraceType)(ARRAY_TYPE | ENUM_TYPE); } else { bool isCommandType = (foundPreCommandHeader || foundPreCommandMacro - || (currentHeader != NULL && isNonParenHeader) + || (currentHeader != nullptr && isNonParenHeader) || (previousCommandChar == ')') || (previousCommandChar == ':' && !foundQuestionMark) || (previousCommandChar == ';') || ((previousCommandChar == '{' || previousCommandChar == '}') - && isPreviousBracketBlockRelated) + && isPreviousBraceBlockRelated) || (isInClassInitializer - && (!isLegalNameChar(previousNonWSChar) || foundPreCommandHeader)) + && ((!isLegalNameChar(previousNonWSChar) && previousNonWSChar != '(') + || foundPreCommandHeader)) + || foundTrailingReturnType || isInObjCMethodDefinition || isInObjCInterface || isJavaStaticConstructor @@ -2797,29 +3030,59 @@ if (foundOneLineBlock > 0) { - returnVal = (BracketType) (returnVal | SINGLE_LINE_TYPE); + returnVal = (BraceType) (returnVal | SINGLE_LINE_TYPE); if (breakCurrentOneLineBlock) - returnVal = (BracketType) (returnVal | BREAK_BLOCK_TYPE); + returnVal = (BraceType) (returnVal | BREAK_BLOCK_TYPE); if (foundOneLineBlock == 3) - returnVal = (BracketType)(returnVal | EMPTY_BLOCK_TYPE); + returnVal = (BraceType)(returnVal | EMPTY_BLOCK_TYPE); } - if (isBracketType(returnVal, ARRAY_TYPE)) + if (isBraceType(returnVal, ARRAY_TYPE)) { - if (isNonInStatementArrayBracket()) + if (isNonInStatementArrayBrace()) { - returnVal = (BracketType)(returnVal | ARRAY_NIS_TYPE); + returnVal = (BraceType)(returnVal | ARRAY_NIS_TYPE); isNonInStatementArray = true; isImmediatelyPostNonInStmt = false; // in case of "},{" - nonInStatementBracket = formattedLine.length() - 1; + nonInStatementBrace = formattedLine.length() - 1; } - if (isUniformInitializerBracket()) - returnVal = (BracketType)(returnVal | INIT_TYPE); + if (isUniformInitializerBrace()) + returnVal = (BraceType)(returnVal | INIT_TYPE); } return returnVal; } +bool ASFormatter::isNumericVariable(string word) const +{ + if (word == "bool" + || word == "int" + || word == "void" + || word == "char" + || word == "long" + || word == "short" + || word == "double" + || word == "float" + || (word.length() >= 4 // check end of word for _t + && word.compare(word.length() - 2, 2, "_t") == 0) +// removed release 3.1 +// || word == "Int32" +// || word == "UInt32" +// || word == "Int64" +// || word == "UInt64" + || word == "BOOL" + || word == "DWORD" + || word == "HWND" + || word == "INT" + || word == "LPSTR" + || word == "VOID" + || word == "LPVOID" + || word == "wxFontEncoding" + ) + return true; + return false; +} + /** * check if a colon is a class initializer separator * @@ -2914,18 +3177,17 @@ string nextText = peekNextText(currentLine.substr(charNum + 1)); if (nextText.length() == 0) nextText = " "; - char nextChar = nextText[0]; if (isDigit(lastWord[0]) - || isDigit(nextChar) - || nextChar == '!' - || nextChar == '~') + || isDigit(nextText[0]) + || nextText[0] == '!' + || nextText[0] == '~') return false; // check for multiply then a dereference (a * *b) + char nextChar = peekNextChar(); if (currentChar == '*' - && charNum < (int) currentLine.length() - 1 - && isWhiteSpace(currentLine[charNum + 1]) - && nextChar == '*') + && nextChar == '*' + && !isPointerToPointer(currentLine, charNum)) return false; if ((foundCastOperator && nextChar == '>') @@ -2943,14 +3205,18 @@ //check for rvalue reference if (currentChar == '&' && nextChar == '&') { + if (lastWord == AS_AUTO) + return true; if (previousNonWSChar == '>') return true; - string followingText = peekNextText(currentLine.substr(charNum + 2)); + string followingText; + if ((int) currentLine.length() > charNum + 2) + followingText = peekNextText(currentLine.substr(charNum + 2)); if (followingText.length() > 0 && followingText[0] == ')') return true; - if (currentHeader != NULL || isInPotentialCalculation) + if (currentHeader != nullptr || isInPotentialCalculation) return false; - if (parenStack->back() > 0 && isBracketType(bracketTypeStack->back(), COMMAND_TYPE)) + if (parenStack->back() > 0 && isBraceType(braceTypeStack->back(), COMMAND_TYPE)) return false; return true; } @@ -2966,7 +3232,7 @@ || currentHeader == &AS_QFOREACH) return true; - if (isBracketType(bracketTypeStack->back(), ARRAY_TYPE) + if (isBraceType(braceTypeStack->back(), ARRAY_TYPE) && isLegalNameChar(lastWord[0]) && isLegalNameChar(nextChar) && previousNonWSChar != ')') @@ -2983,17 +3249,17 @@ // if followed by an assignment it is a pointer or reference // if followed by semicolon it is a pointer or reference in range-based for const string* followingOperator = getFollowingOperator(); - if (followingOperator + if (followingOperator != nullptr && followingOperator != &AS_MULT && followingOperator != &AS_BIT_AND) { if (followingOperator == &AS_ASSIGN || followingOperator == &AS_COLON) return true; return false; } - if (isBracketType(bracketTypeStack->back(), COMMAND_TYPE) - || blockParenCount > 0) + if (isBraceType(braceTypeStack->back(), COMMAND_TYPE) + || squareBracketCount > 0) return false; return true; } @@ -3083,7 +3349,7 @@ // check first char on the line if (charNum == (int) currentLine.find_first_not_of(" \t") - && (isBracketType(bracketTypeStack->back(), COMMAND_TYPE) + && (isBraceType(braceTypeStack->back(), COMMAND_TYPE) || parenStack->back() != 0)) return true; @@ -3097,12 +3363,12 @@ return true; } - // check for reference to a pointer *& (cannot have &*) + // check for reference to a pointer *& if ((currentChar == '*' && nextChar == '&') || (previousNonWSChar == '*' && currentChar == '&')) return false; - if (!isBracketType(bracketTypeStack->back(), COMMAND_TYPE) + if (!isBraceType(braceTypeStack->back(), COMMAND_TYPE) && parenStack->back() == 0) return false; @@ -3173,7 +3439,7 @@ * * @return whether word is a pointer or reference variable. */ -bool ASFormatter::isPointerOrReferenceVariable(string& word) const +bool ASFormatter::isPointerOrReferenceVariable(const string& word) const { return (word == "char" || word == "int" @@ -3184,6 +3450,27 @@ || word == "VOID"); } +/** + * Check if * * is a pointer to a pointer or a multiply then a dereference. + * + * @return true if a pointer *. + */ +bool ASFormatter::isPointerToPointer(const string& line, int currPos) const +{ + assert(line[currPos] == '*' && peekNextChar() == '*'); + if ((int) line.length() > currPos + 1 && line[currPos + 1] == '*') + return true; + size_t nextText = line.find_first_not_of(" \t", currPos + 1); + if (nextText == string::npos || line[nextText] != '*') + return false; + size_t nextText2 = line.find_first_not_of(" \t", nextText + 1); + if (nextText == string::npos) + return false; + if (line[nextText2] == ')' || line[nextText2] == '*') + return true; + return false; +} + /** * check if the currently reached '+' or '-' character is a unary operator * this method takes for granted that the current character @@ -3195,11 +3482,31 @@ { assert(currentChar == '+' || currentChar == '-'); + // does a digit follow a c-style cast + if (previousCommandChar == ')') + { + if (!isdigit(peekNextChar())) + return false; + size_t end = currentLine.rfind(')', charNum); + if (end == string::npos) + return false; + size_t lastChar = currentLine.find_last_not_of(" \t", end - 1); + if (lastChar == string::npos) + return false; + if (currentLine[lastChar] == '*') + end = lastChar; + string prevWord = getPreviousWord(currentLine, end); + if (prevWord.empty()) + return false; + if (!isNumericVariable(prevWord)) + return false; + return true; + } + return ((isCharImmediatelyPostReturn || !isLegalNameChar(previousCommandChar)) && previousCommandChar != '.' && previousCommandChar != '\"' && previousCommandChar != '\'' - && previousCommandChar != ')' && previousCommandChar != ']'); } @@ -3211,9 +3518,9 @@ bool ASFormatter::isInSwitchStatement() const { assert(isInLineComment || isInComment); - if (!preBracketHeaderStack->empty()) - for (size_t i = 1; i < preBracketHeaderStack->size(); i++) - if (preBracketHeaderStack->at(i) == &AS_SWITCH) + if (!preBraceHeaderStack->empty()) + for (size_t i = 1; i < preBraceHeaderStack->size(); i++) + if (preBraceHeaderStack->at(i) == &AS_SWITCH) return true; return false; } @@ -3239,20 +3546,20 @@ } /** - * check if an array bracket should NOT have an in-statement indent + * check if an array brace should NOT have an in-statement indent * * @return the array is non in-statement */ -bool ASFormatter::isNonInStatementArrayBracket() const +bool ASFormatter::isNonInStatementArrayBrace() const { bool returnVal = false; char nextChar = peekNextChar(); - // if this opening bracket begins the line there will be no inStatement indent - if (currentLineBeginsWithBracket - && charNum == (int) currentLineFirstBracketNum + // if this opening brace begins the line there will be no inStatement indent + if (currentLineBeginsWithBrace + && (size_t) charNum == currentLineFirstBraceNum && nextChar != '}') returnVal = true; - // if an opening bracket ends the line there will be no inStatement indent + // if an opening brace ends the line there will be no inStatement indent if (isWhiteSpace(nextChar) || isBeforeAnyLineEndComment(charNum) || nextChar == '{') @@ -3282,7 +3589,7 @@ bool isInComment_ = false; bool isInQuote_ = false; bool hasText = false; - int bracketCount = 0; + int braceCount = 0; int lineLength = line.length(); char quoteChar_ = ' '; char ch = ' '; @@ -3302,15 +3609,11 @@ continue; } - if (ch == '\\') - { - ++i; - continue; - } - if (isInQuote_) { - if (ch == quoteChar_) + if (ch == '\\') + ++i; + else if (ch == quoteChar_) isInQuote_ = false; continue; } @@ -3335,13 +3638,13 @@ if (ch == '{') { - ++bracketCount; + ++braceCount; continue; } if (ch == '}') { - --bracketCount; - if (bracketCount == 0) + --braceCount; + if (braceCount == 0) { // is this an array? if (parenStack->back() == 0 && prevCh != '}') @@ -3391,14 +3694,14 @@ } /** - * peek at the next char to determine if it is an opening bracket. + * peek at the next char to determine if it is an opening brace. * will look ahead in the input file if necessary. * this determines a java static constructor. * * @param startChar position on currentLine to start the search - * @return true if the next word is an opening bracket. + * @return true if the next word is an opening brace. */ -bool ASFormatter::isNextCharOpeningBracket(int startChar) const +bool ASFormatter::isNextCharOpeningBrace(int startChar) const { bool retVal = false; string nextText = peekNextText(currentLine.substr(startChar)); @@ -3437,15 +3740,16 @@ } /** -* Determine if an opening array-type bracket should have a leading space pad. +* Determine if an opening array-type brace should have a leading space pad. * This is to identify C++11 uniform initializers. */ -bool ASFormatter::isUniformInitializerBracket() const +bool ASFormatter::isUniformInitializerBrace() const { if (isCStyle() && !isInEnum && !isImmediatelyPostPreprocessor) { if (isInClassInitializer - || isLegalNameChar(previousNonWSChar)) + || isLegalNameChar(previousNonWSChar) + || previousNonWSChar == '(') return true; } return false; @@ -3461,7 +3765,7 @@ bool isInQuote_ = false; int semiCount_ = 0; int parenCount_ = 0; - int bracketCount_ = 0; + int braceCount_ = 0; for (size_t i = 0; i < currentLine.length(); i++) { @@ -3505,13 +3809,13 @@ continue; if (currentLine[i] == '{') { - ++bracketCount_; + ++braceCount_; } if (currentLine[i] == '}') { - --bracketCount_; + --braceCount_; } - if (bracketCount_ > 0) + if (braceCount_ > 0) continue; if (currentLine[i] == ';') { @@ -3530,24 +3834,26 @@ * @param firstLine the first line to check * @return the next non-whitespace substring. */ -string ASFormatter::peekNextText(const string& firstLine, bool endOnEmptyLine /*false*/, bool shouldReset /*false*/) const +string ASFormatter::peekNextText(const string& firstLine, + bool endOnEmptyLine /*false*/, + shared_ptr streamArg /*nullptr*/) const { + assert(sourceIterator->getPeekStart() == 0 || streamArg != nullptr); // Borland may need != 0 bool isFirstLine = true; - bool needReset = shouldReset; string nextLine_ = firstLine; size_t firstChar = string::npos; + shared_ptr stream = streamArg; + if (stream == nullptr) // Borland may need == 0 + stream = make_shared(sourceIterator); // find the first non-blank text, bypassing all comments. bool isInComment_ = false; - while (sourceIterator->hasMoreLines() || isFirstLine) + while (stream->hasMoreLines() || isFirstLine) { if (isFirstLine) isFirstLine = false; else - { - nextLine_ = sourceIterator->peekNextLine(); - needReset = true; - } + nextLine_ = stream->peekNextLine(); firstChar = nextLine_.find_first_not_of(" \t"); if (firstChar == string::npos) @@ -3586,8 +3892,6 @@ nextLine_ = ""; else nextLine_ = nextLine_.substr(firstChar); - if (needReset) - sourceIterator->peekReset(); return nextLine_; } @@ -3607,7 +3911,10 @@ size_t endNum = currentLine.find("*/", charNum + 2); if (endNum == string::npos) return; - if (currentLine.find_first_not_of(" \t", endNum + 2) != string::npos) + // following line comments may be a tag from AStyleWx //[[)> + size_t nextNum = currentLine.find_first_not_of(" \t", endNum + 2); + if (nextNum != string::npos + && currentLine.compare(nextNum, 2, "//") != 0) return; } @@ -3638,8 +3945,8 @@ } /** - * append the current bracket inside the end of line comments - * currentChar contains the bracket, it will be appended to formattedLine + * append the current brace inside the end of line comments + * currentChar contains the brace, it will be appended to formattedLine * formattedLineCommentNum is the comment location on formattedLine */ void ASFormatter::appendCharInsideComments() @@ -3663,7 +3970,7 @@ } beg++; - // insert the bracket + // insert the brace if (end - beg < 3) // is there room to insert? formattedLine.insert(beg, 3 - end + beg, ' '); if (formattedLine[beg] == '\t') // don't pad with a tab @@ -3687,17 +3994,18 @@ void ASFormatter::padOperators(const string* newOperator) { assert(shouldPadOperators); - assert(newOperator != NULL); + assert(newOperator != nullptr); + char nextNonWSChar = ASBase::peekNextChar(currentLine, charNum); bool shouldPad = (newOperator != &AS_SCOPE_RESOLUTION && newOperator != &AS_PLUS_PLUS && newOperator != &AS_MINUS_MINUS && newOperator != &AS_NOT && newOperator != &AS_BIT_NOT && newOperator != &AS_ARROW && !(newOperator == &AS_COLON && !foundQuestionMark // objC methods && (isInObjCMethodDefinition || isInObjCInterface - || isInObjCSelector || blockParenCount)) + || isInObjCSelector || squareBracketCount != 0)) && !(newOperator == &AS_MINUS && isInExponent()) && !(newOperator == &AS_PLUS && isInExponent()) && !((newOperator == &AS_PLUS || newOperator == &AS_MINUS) // check for unary plus or minus @@ -3707,7 +4015,6 @@ || previousNonWSChar == ',' || previousNonWSChar == ':' || previousNonWSChar == '{')) - && !isCharImmediatelyPostOperator //? // commented out in release 2.05.1 - doesn't seem to do anything??? //x && !((newOperator == &AS_MULT || newOperator == &AS_BIT_AND || newOperator == &AS_AND) //x && isPointerOrReference()) @@ -3721,9 +4028,15 @@ && ASBase::peekNextChar(currentLine, charNum + 1) == '>') && !(newOperator == &AS_GR && previousNonWSChar == '?') && !(newOperator == &AS_QUESTION // check for Java wildcard + && isJavaStyle() && (previousNonWSChar == '<' - || ASBase::peekNextChar(currentLine, charNum) == '>' - || ASBase::peekNextChar(currentLine, charNum) == '.')) + || nextNonWSChar == '>' + || nextNonWSChar == '.')) + && !(newOperator == &AS_QUESTION // check for C# null conditional operator + && isSharpStyle() + && (nextNonWSChar == '.' + || nextNonWSChar == '[')) + && !isCharImmediatelyPostOperator && !isInCase && !isInAsm && !isInAsmOneLine @@ -3755,8 +4068,6 @@ && peekNextChar() == '[') ) appendSpaceAfter(); - - previousOperator = newOperator; } /** @@ -3775,13 +4086,16 @@ int pa = pointerAlignment; int ra = referenceAlignment; - int itemAlignment = (currentChar == '*' || currentChar == '^') ? pa : ((ra == REF_SAME_AS_PTR) ? pa : ra); + int itemAlignment = (currentChar == '*' || currentChar == '^') + ? pa : ((ra == REF_SAME_AS_PTR) ? pa : ra); // check for ** and && + int ptrLength = 1; char peekedChar = peekNextChar(); if ((currentChar == '*' && peekedChar == '*') || (currentChar == '&' && peekedChar == '&')) { + ptrLength = 2; size_t nextChar = currentLine.find_first_not_of(" \t", charNum + 2); if (nextChar == string::npos) peekedChar = ' '; @@ -3819,7 +4133,9 @@ } else // pointerAlignment == PTR_ALIGN_NONE { - formattedLine.append(1, currentChar); + formattedLine.append(currentLine.substr(charNum, ptrLength)); + if (ptrLength > 1) + goForward(ptrLength - 1); } } @@ -3833,28 +4149,34 @@ // do this before bumping charNum bool isOldPRCentered = isPointerOrReferenceCentered(); - - size_t prevCh = formattedLine.find_last_not_of(" \t"); - if (prevCh == string::npos) - prevCh = 0; - if (formattedLine.length() == 0 || prevCh == formattedLine.length() - 1) - formattedLine.append(1, currentChar); - else + string sequenceToInsert(1, currentChar); + // get the sequence + if (currentChar == peekNextChar()) { - // exchange * or & with character following the type - // this may not work every time with a tab character - string charSave = formattedLine.substr(prevCh + 1, 1); - formattedLine[prevCh + 1] = currentChar; - formattedLine.append(charSave); + for (size_t i = charNum + 1; currentLine.length() > i; i++) + { + if (currentLine[i] == sequenceToInsert[0]) + { + sequenceToInsert.append(1, currentLine[i]); + goForward(1); + continue; + } + break; + } } - if (isSequenceReached("**") || isSequenceReached("&&")) + // append the seqence + string charSave; + size_t prevCh = formattedLine.find_last_not_of(" \t"); + if (prevCh < formattedLine.length()) { - if (formattedLine.length() == 1) - formattedLine.append(1, currentChar); - else - formattedLine.insert(prevCh + 2, 1, currentChar); - goForward(1); + charSave = formattedLine.substr(prevCh + 1); + formattedLine.resize(prevCh + 1); } + formattedLine.append(sequenceToInsert); + if (peekNextChar() != ')') + formattedLine.append(charSave); + else + spacePadNum -= charSave.length(); // if no space after then add one if (charNum < (int) currentLine.length() - 1 && !isWhiteSpace(currentLine[charNum + 1]) @@ -3868,7 +4190,7 @@ spacePadNum--; } // update the formattedLine split point - if (maxCodeLength != string::npos) + if (maxCodeLength != string::npos && formattedLine.length() > 0) { size_t index = formattedLine.length() - 1; if (isWhiteSpace(formattedLine[index])) @@ -3894,15 +4216,18 @@ else wsBefore = charNum - wsBefore - 1; string sequenceToInsert(1, currentChar); - if (isSequenceReached("**")) - { - sequenceToInsert = "**"; - goForward(1); - } - else if (isSequenceReached("&&")) + if (currentChar == peekNextChar()) { - sequenceToInsert = "&&"; - goForward(1); + for (size_t i = charNum + 1; currentLine.length() > i; i++) + { + if (currentLine[i] == sequenceToInsert[0]) + { + sequenceToInsert.append(1, currentLine[i]); + goForward(1); + continue; + } + break; + } } // if reference to a pointer check for conflicting alignment else if (currentChar == '*' && peekNextChar() == '&' @@ -3974,7 +4299,10 @@ // insert the pointer or reference char size_t padAfter = (wsBefore + wsAfter) / 2; size_t index = formattedLine.length() - padAfter; - formattedLine.insert(index, sequenceToInsert); + if (index < formattedLine.length()) + formattedLine.insert(index, sequenceToInsert); + else + formattedLine.append(sequenceToInsert); } else // formattedLine.length() == 0 { @@ -4012,15 +4340,18 @@ if (startNum == string::npos) startNum = 0; string sequenceToInsert(1, currentChar); - if (isSequenceReached("**")) + if (currentChar == peekNextChar()) { - sequenceToInsert = "**"; - goForward(1); - } - else if (isSequenceReached("&&")) - { - sequenceToInsert = "&&"; - goForward(1); + for (size_t i = charNum + 1; currentLine.length() > i; i++) + { + if (currentLine[i] == sequenceToInsert[0]) + { + sequenceToInsert.append(1, currentLine[i]); + goForward(1); + continue; + } + break; + } } // if reference to a pointer align both to name else if (currentChar == '*' && peekNextChar() == '&') @@ -4033,7 +4364,7 @@ char peekedChar = peekNextChar(); bool isAfterScopeResolution = previousNonWSChar == ':'; // check for :: // if this is not the last thing on the line - if (!isBeforeAnyComment() + if ((isLegalNameChar(peekedChar) || peekedChar == '(' || peekedChar == '[' || peekedChar == '=') && (int) currentLine.find_first_not_of(" \t", charNum + 1) > charNum) { // goForward() to convert tabs to spaces, if necessary, @@ -4045,13 +4376,13 @@ if (shouldPadParensOutside && peekedChar == '(' && !isOldPRCentered) { // empty parens don't count - size_t start = currentLine.find_first_not_of("( \t", charNum + 1); + size_t start = currentLine.find_first_not_of("( \t", i); if (start != string::npos && currentLine[start] != ')') break; } goForward(1); if (formattedLine.length() > 0) - formattedLine.append(1, currentLine[i]); + formattedLine.append(1, currentLine[charNum]); else spacePadNum--; } @@ -4076,6 +4407,7 @@ if (isOldPRCentered && formattedLine.length() > startNum + 1 && isWhiteSpace(formattedLine[startNum + 1]) + && peekedChar != '*' // check for '* *' && !isBeforeAnyComment()) { formattedLine.erase(startNum + 1, 1); @@ -4124,7 +4456,8 @@ int pa = pointerAlignment; int ra = referenceAlignment; - int itemAlignment = (currentChar == '*' || currentChar == '^') ? pa : ((ra == REF_SAME_AS_PTR) ? pa : ra); + int itemAlignment = (currentChar == '*' || currentChar == '^') + ? pa : ((ra == REF_SAME_AS_PTR) ? pa : ra); string sequenceToInsert(1, currentChar); if (isSequenceReached("**") || isSequenceReached("&&")) @@ -4143,9 +4476,19 @@ if (prevNum != string::npos) { prevCh = formattedLine[prevNum]; - if (prevNum + 1 < formattedLine.length() - && isWhiteSpace(formattedLine[prevNum + 1]) - && prevCh != '(') + if (itemAlignment == PTR_ALIGN_TYPE && currentChar == '*' && prevCh == '*') + { + // '* *' may be a multiply followed by a dereference + if (prevNum + 2 < formattedLine.length() + && isWhiteSpace(formattedLine[prevNum + 2])) + { + spacePadNum -= (formattedLine.length() - 2 - prevNum); + formattedLine.erase(prevNum + 2); + } + } + else if (prevNum + 1 < formattedLine.length() + && isWhiteSpace(formattedLine[prevNum + 1]) + && prevCh != '(') { spacePadNum -= (formattedLine.length() - 1 - prevNum); formattedLine.erase(prevNum + 1); @@ -4192,7 +4535,7 @@ size_t i = formattedLine.find_last_not_of(" \t"); if (i != string::npos) { - // if last char is a bracket the previous whitespace is an indent + // if last char is a brace the previous whitespace is an indent if (formattedLine[i] == '{') spacesOutsideToDelete = 0; else if (isCharImmediatelyPostPointerOrReference) @@ -4203,49 +4546,25 @@ lastChar = formattedLine[i]; // if previous word is a header, it will be a paren header string prevWord = getPreviousWord(formattedLine, formattedLine.length()); - const string* prevWordH = NULL; + const string* prevWordH = nullptr; if (shouldPadHeader && prevWord.length() > 0 && isCharPotentialHeader(prevWord, 0)) - prevWordH = ASBeautifier::findHeader(prevWord, 0, headers); - if (prevWordH != NULL) - prevIsParenHeader = true; - else if (prevWord == AS_RETURN) // don't unpad - prevIsParenHeader = true; + prevWordH = ASBase::findHeader(prevWord, 0, headers); + if (prevWordH != nullptr) + prevIsParenHeader = true; // don't unpad + else if (prevWord == AS_RETURN) + prevIsParenHeader = true; // don't unpad else if ((prevWord == AS_NEW || prevWord == AS_DELETE) - && shouldPadHeader) // don't unpad - prevIsParenHeader = true; - else if (isCStyle() && prevWord == AS_THROW && shouldPadHeader) // don't unpad - prevIsParenHeader = true; - else if (prevWord == "and" || prevWord == "or") // don't unpad - prevIsParenHeader = true; + && shouldPadHeader) + prevIsParenHeader = true; // don't unpad + else if (isCStyle() && prevWord == AS_THROW && shouldPadHeader) + prevIsParenHeader = true; // don't unpad + else if (prevWord == "and" || prevWord == "or" || prevWord == "in") + prevIsParenHeader = true; // don't unpad // don't unpad variables - else if (prevWord == "bool" - || prevWord == "int" - || prevWord == "void" - || prevWord == "void*" - || prevWord == "char" - || prevWord == "char*" - || prevWord == "long" - || prevWord == "double" - || prevWord == "float" - || (prevWord.length() >= 4 // check end of word for _t - && prevWord.compare(prevWord.length() - 2, 2, "_t") == 0) - || prevWord == "Int32" - || prevWord == "UInt32" - || prevWord == "Int64" - || prevWord == "UInt64" - || prevWord == "BOOL" - || prevWord == "DWORD" - || prevWord == "HWND" - || prevWord == "INT" - || prevWord == "LPSTR" - || prevWord == "VOID" - || prevWord == "LPVOID" - ) - { - prevIsParenHeader = true; - } + else if (isNumericVariable(prevWord)) + prevIsParenHeader = true; // don't unpad } } // do not unpad operators, but leave them if already padded @@ -4372,22 +4691,23 @@ } /** -* add or remove space padding to objective-c parens +* add or remove space padding to objective-c method prefix (- or +) +* if this is a '(' it begins a return type * these options have precedence over the padParens methods * the padParens method has already been called, this method adjusts */ void ASFormatter::padObjCMethodPrefix() { - assert(currentChar == '(' && isImmediatelyPostObjCMethodPrefix); + assert(isInObjCMethodDefinition && isImmediatelyPostObjCMethodPrefix); assert(shouldPadMethodPrefix || shouldUnPadMethodPrefix); size_t prefix = formattedLine.find_first_of("+-"); if (prefix == string::npos) return; - size_t paren = formattedLine.find_first_of('('); - if (paren == string::npos) - return; - int spaces = paren - prefix - 1; + size_t firstChar = formattedLine.find_first_not_of(" \t", prefix + 1); + if (firstChar == string::npos) + firstChar = formattedLine.length(); + int spaces = firstChar - prefix - 1; if (shouldPadMethodPrefix) { @@ -4399,6 +4719,7 @@ else if (spaces > 1) { formattedLine.erase(prefix + 1, spaces - 1); + formattedLine[prefix + 1] = ' '; // convert any tab to space spacePadNum -= spaces - 1; } } @@ -4443,6 +4764,7 @@ { // do not use goForward here currentLine.erase(charNum + 1, spaces - 1); + currentLine[charNum + 1] = ' '; // convert any tab to space spacePadNum -= spaces - 1; } } @@ -4452,16 +4774,13 @@ // this will already be padded if pad-paren is used if (formattedLine[formattedLine.length() - 1] == ' ') { - spacePadNum -= formattedLine.length() - 1 - nextText; int lastText = formattedLine.find_last_not_of(" \t"); + spacePadNum -= formattedLine.length() - lastText - 1; formattedLine.resize(lastText + 1); } - if (spaces > 0) - { - // do not use goForward here - currentLine.erase(charNum + 1, spaces); - spacePadNum -= spaces; - } + // do not use goForward here + currentLine.erase(charNum + 1, spaces); + spacePadNum -= spaces; } } @@ -4498,6 +4817,7 @@ if (spaces > 1) { formattedLine.erase(prevText + 1, spaces - 1); + formattedLine[prevText + 1] = ' '; // convert any tab to space spacePadNum -= spaces - 1; } } @@ -4535,6 +4855,7 @@ { // do not use goForward here currentLine.erase(charNum + 1, spaces - 1); + currentLine[charNum + 1] = ' '; // convert any tab to space spacePadNum -= spaces - 1; } } @@ -4559,70 +4880,70 @@ } /** - * format opening bracket as attached or broken - * currentChar contains the bracket - * the brackets will be appended to the current formattedLine or a new formattedLine as necessary + * format opening brace as attached or broken + * currentChar contains the brace + * the braces will be appended to the current formattedLine or a new formattedLine as necessary * the calling function should have a continue statement after calling this method * - * @param bracketType the type of bracket to be formatted. + * @param braceType the type of brace to be formatted. */ -void ASFormatter::formatOpeningBracket(BracketType bracketType) +void ASFormatter::formatOpeningBrace(BraceType braceType) { - assert(!isBracketType(bracketType, ARRAY_TYPE)); + assert(!isBraceType(braceType, ARRAY_TYPE)); assert(currentChar == '{'); - parenStack->push_back(0); + parenStack->emplace_back(0); - bool breakBracket = isCurrentBracketBroken(); + bool breakBrace = isCurrentBraceBroken(); - if (breakBracket) + if (breakBrace) { - if (isBeforeAnyComment() && isOkToBreakBlock(bracketType)) + if (isBeforeAnyComment() && isOkToBreakBlock(braceType) && sourceIterator->hasMoreLines()) { // if comment is at line end leave the comment on this line - if (isBeforeAnyLineEndComment(charNum) && !currentLineBeginsWithBracket) + if (isBeforeAnyLineEndComment(charNum) && !currentLineBeginsWithBrace) { - currentChar = ' '; // remove bracket from current line + currentChar = ' '; // remove brace from current line if (parenStack->size() > 1) parenStack->pop_back(); currentLine[charNum] = currentChar; - appendOpeningBracket = true; // append bracket to following line + appendOpeningBrace = true; // append brace to following line } - // else put comment after the bracket + // else put comment after the brace else if (!isBeforeMultipleLineEndComments(charNum)) breakLine(); } - else if (!isBracketType(bracketType, SINGLE_LINE_TYPE)) + else if (!isBraceType(braceType, SINGLE_LINE_TYPE)) { formattedLine = rtrim(formattedLine); breakLine(); } - else if ((shouldBreakOneLineBlocks || isBracketType(bracketType, BREAK_BLOCK_TYPE)) - && !isBracketType(bracketType, EMPTY_BLOCK_TYPE)) + else if ((shouldBreakOneLineBlocks || isBraceType(braceType, BREAK_BLOCK_TYPE)) + && !isBraceType(braceType, EMPTY_BLOCK_TYPE)) breakLine(); else if (!isInLineBreak) appendSpacePad(); appendCurrentChar(); - // should a following comment break from the bracket? - // must break the line AFTER the bracket + // should a following comment break from the brace? + // must break the line AFTER the brace if (isBeforeComment() && formattedLine.length() > 0 && formattedLine[0] == '{' - && isOkToBreakBlock(bracketType) - && (bracketFormatMode == BREAK_MODE - || bracketFormatMode == LINUX_MODE)) + && isOkToBreakBlock(braceType) + && (braceFormatMode == BREAK_MODE + || braceFormatMode == LINUX_MODE)) { shouldBreakLineAtNextChar = true; } } - else // attach bracket + else // attach brace { - // are there comments before the bracket? + // are there comments before the brace? if (isCharImmediatelyPostComment || isCharImmediatelyPostLineComment) { - if (isOkToBreakBlock(bracketType) + if (isOkToBreakBlock(braceType) && !(isCharImmediatelyPostComment && isCharImmediatelyPostLineComment) // don't attach if two comments on the line && !isImmediatelyPostPreprocessor // && peekNextChar() != '}' // don't attach { } // removed release 2.03 @@ -4648,20 +4969,20 @@ // if a blank line precedes this don't attach if (isEmptyLine(formattedLine)) appendCurrentChar(); // don't attach - else if (isOkToBreakBlock(bracketType) + else if (isOkToBreakBlock(braceType) && !(isImmediatelyPostPreprocessor - && currentLineBeginsWithBracket)) + && currentLineBeginsWithBrace)) { - if (!isBracketType(bracketType, EMPTY_BLOCK_TYPE)) + if (!isBraceType(braceType, EMPTY_BLOCK_TYPE)) { appendSpacePad(); appendCurrentChar(false); // OK to attach testForTimeToSplitFormattedLine(); // line length will have changed - // should a following comment attach with the bracket? + // should a following comment attach with the brace? // insert spaces to reposition the comment if (isBeforeComment() && !isBeforeMultipleLineEndComments(charNum) - && (!isBeforeAnyLineEndComment(charNum) || currentLineBeginsWithBracket)) + && (!isBeforeAnyLineEndComment(charNum) || currentLineBeginsWithBrace)) { shouldBreakLineAtNextChar = true; currentLine.insert(charNum + 1, charNum + 1, ' '); @@ -4673,7 +4994,7 @@ } else { - if (currentLineBeginsWithBracket && charNum == (int) currentLineFirstBracketNum) + if (currentLineBeginsWithBrace && (size_t) charNum == currentLineFirstBraceNum) { appendSpacePad(); appendCurrentChar(false); // attach @@ -4697,53 +5018,53 @@ } /** - * format closing bracket - * currentChar contains the bracket + * format closing brace + * currentChar contains the brace * the calling function should have a continue statement after calling this method * - * @param bracketType the type of the opening bracket for this closing bracket. + * @param braceType the type of the opening brace for this closing brace. */ -void ASFormatter::formatClosingBracket(BracketType bracketType) +void ASFormatter::formatClosingBrace(BraceType braceType) { - assert(!isBracketType(bracketType, ARRAY_TYPE)); + assert(!isBraceType(braceType, ARRAY_TYPE)); assert(currentChar == '}'); // parenStack must contain one entry if (parenStack->size() > 1) parenStack->pop_back(); // mark state of immediately after empty block - // this state will be used for locating brackets that appear immediately AFTER an empty block (e.g. '{} \n}'). + // this state will be used for locating braces that appear immediately AFTER an empty block (e.g. '{} \n}'). if (previousCommandChar == '{') isImmediatelyPostEmptyBlock = true; - if (attachClosingBracketMode) + if (attachClosingBraceMode) { // for now, namespaces and classes will be attached. Uncomment the lines below to break. if ((isEmptyLine(formattedLine) // if a blank line precedes this || isCharImmediatelyPostLineComment || isCharImmediatelyPostComment || (isImmediatelyPostPreprocessor && (int) currentLine.find_first_not_of(" \t") == charNum) -// || (isBracketType(bracketType, CLASS_TYPE) && isOkToBreakBlock(bracketType) && previousNonWSChar != '{') -// || (isBracketType(bracketType, NAMESPACE_TYPE) && isOkToBreakBlock(bracketType) && previousNonWSChar != '{') +// || (isBraceType(braceType, CLASS_TYPE) && isOkToBreakBlock(braceType) && previousNonWSChar != '{') +// || (isBraceType(braceType, NAMESPACE_TYPE) && isOkToBreakBlock(braceType) && previousNonWSChar != '{') ) - && (!isBracketType(bracketType, SINGLE_LINE_TYPE) || isOkToBreakBlock(bracketType))) + && (!isBraceType(braceType, SINGLE_LINE_TYPE) || isOkToBreakBlock(braceType))) { breakLine(); appendCurrentChar(); // don't attach } else { if (previousNonWSChar != '{' - && (!isBracketType(bracketType, SINGLE_LINE_TYPE) - || isOkToBreakBlock(bracketType))) + && (!isBraceType(braceType, SINGLE_LINE_TYPE) + || isOkToBreakBlock(braceType))) appendSpacePad(); appendCurrentChar(false); // attach } } - else if (!isBracketType(bracketType, EMPTY_BLOCK_TYPE) - && (isBracketType(bracketType, BREAK_BLOCK_TYPE) - || isOkToBreakBlock(bracketType))) + else if (!isBraceType(braceType, EMPTY_BLOCK_TYPE) + && (isBraceType(braceType, BREAK_BLOCK_TYPE) + || isOkToBreakBlock(braceType))) { breakLine(); appendCurrentChar(); @@ -4758,13 +5079,13 @@ appendSpaceAfter(); if (shouldBreakBlocks - && currentHeader != NULL + && currentHeader != nullptr && !isHeaderInMultiStatementLine && parenStack->back() == 0) { if (currentHeader == &AS_CASE || currentHeader == &AS_DEFAULT) { - // do not yet insert a line if "break" statement is outside the brackets + // do not yet insert a line if "break" statement is outside the braces string nextText = peekNextText(currentLine.substr(charNum + 1)); if (nextText.length() > 0 && nextText.substr(0, 5) != "break") @@ -4776,30 +5097,30 @@ } /** - * format array brackets as attached or broken - * determine if the brackets can have an inStatement indent - * currentChar contains the bracket - * the brackets will be appended to the current formattedLine or a new formattedLine as necessary + * format array braces as attached or broken + * determine if the braces can have an inStatement indent + * currentChar contains the brace + * the braces will be appended to the current formattedLine or a new formattedLine as necessary * the calling function should have a continue statement after calling this method * - * @param bracketType the type of bracket to be formatted, must be an ARRAY_TYPE. - * @param isOpeningArrayBracket indicates if this is the opening bracket for the array block. + * @param braceType the type of brace to be formatted, must be an ARRAY_TYPE. + * @param isOpeningArrayBrace indicates if this is the opening brace for the array block. */ -void ASFormatter::formatArrayBrackets(BracketType bracketType, bool isOpeningArrayBracket) +void ASFormatter::formatArrayBraces(BraceType braceType, bool isOpeningArrayBrace) { - assert(isBracketType(bracketType, ARRAY_TYPE)); + assert(isBraceType(braceType, ARRAY_TYPE)); assert(currentChar == '{' || currentChar == '}'); if (currentChar == '{') { - // is this the first opening bracket in the array? - if (isOpeningArrayBracket) + // is this the first opening brace in the array? + if (isOpeningArrayBrace) { - if (bracketFormatMode == ATTACH_MODE - || bracketFormatMode == LINUX_MODE) + if (braceFormatMode == ATTACH_MODE + || braceFormatMode == LINUX_MODE) { // break an enum if mozilla - if (isBracketType(bracketType, ENUM_TYPE) + if (isBraceType(braceType, ENUM_TYPE) && formattingStyle == STYLE_MOZILLA) { isInLineBreak = true; @@ -4809,17 +5130,17 @@ else if ((isImmediatelyPostPreprocessor || (formattedLine.length() > 0 && formattedLine[formattedLine.length() - 1] == '\\')) - && currentLineBeginsWithBracket) + && currentLineBeginsWithBrace) { isInLineBreak = true; appendCurrentChar(); // don't attach } else if (isCharImmediatelyPostComment) { - // TODO: attach bracket to line-end comment + // TODO: attach brace to line-end comment appendCurrentChar(); // don't attach } - else if (isCharImmediatelyPostLineComment && !isBracketType(bracketType, SINGLE_LINE_TYPE)) + else if (isCharImmediatelyPostLineComment && !isBraceType(braceType, SINGLE_LINE_TYPE)) { appendCharInsideComments(); } @@ -4830,122 +5151,122 @@ appendCurrentChar(); // don't attach else { - // if bracket is broken or not an assignment - if (currentLineBeginsWithBracket - && !isBracketType(bracketType, SINGLE_LINE_TYPE)) + // if brace is broken or not an assignment + if (currentLineBeginsWithBrace + && !isBraceType(braceType, SINGLE_LINE_TYPE)) { appendSpacePad(); appendCurrentChar(false); // OK to attach // TODO: debug the following line testForTimeToSplitFormattedLine(); // line length will have changed - if (currentLineBeginsWithBracket - && (int) currentLineFirstBracketNum == charNum) + if (currentLineBeginsWithBrace + && currentLineFirstBraceNum == (size_t) charNum) shouldBreakLineAtNextChar = true; } else { if (previousNonWSChar != '(') { // don't space pad C++11 uniform initialization - if (!isBracketType(bracketType, INIT_TYPE)) + if (!isBraceType(braceType, INIT_TYPE)) appendSpacePad(); } appendCurrentChar(); } } } } - else if (bracketFormatMode == BREAK_MODE) + else if (braceFormatMode == BREAK_MODE) { if (isWhiteSpace(peekNextChar()) && !isInVirginLine) breakLine(); - else if (isBeforeAnyComment()) + else if (isBeforeAnyComment() && sourceIterator->hasMoreLines()) { // do not break unless comment is at line end - if (isBeforeAnyLineEndComment(charNum) && !currentLineBeginsWithBracket) + if (isBeforeAnyLineEndComment(charNum) && !currentLineBeginsWithBrace) { - currentChar = ' '; // remove bracket from current line - appendOpeningBracket = true; // append bracket to following line + currentChar = ' '; // remove brace from current line + appendOpeningBrace = true; // append brace to following line } } if (!isInLineBreak && previousNonWSChar != '(') { // don't space pad C++11 uniform initialization - if (!isBracketType(bracketType, INIT_TYPE)) + if (!isBraceType(braceType, INIT_TYPE)) appendSpacePad(); } appendCurrentChar(); - if (currentLineBeginsWithBracket - && (int) currentLineFirstBracketNum == charNum - && !isBracketType(bracketType, SINGLE_LINE_TYPE)) + if (currentLineBeginsWithBrace + && currentLineFirstBraceNum == (size_t) charNum + && !isBraceType(braceType, SINGLE_LINE_TYPE)) shouldBreakLineAtNextChar = true; } - else if (bracketFormatMode == RUN_IN_MODE) + else if (braceFormatMode == RUN_IN_MODE) { if (isWhiteSpace(peekNextChar()) && !isInVirginLine) breakLine(); - else if (isBeforeAnyComment()) + else if (isBeforeAnyComment() && sourceIterator->hasMoreLines()) { // do not break unless comment is at line end - if (isBeforeAnyLineEndComment(charNum) && !currentLineBeginsWithBracket) + if (isBeforeAnyLineEndComment(charNum) && !currentLineBeginsWithBrace) { - currentChar = ' '; // remove bracket from current line - appendOpeningBracket = true; // append bracket to following line + currentChar = ' '; // remove brace from current line + appendOpeningBrace = true; // append brace to following line } } if (!isInLineBreak && previousNonWSChar != '(') { // don't space pad C++11 uniform initialization - if (!isBracketType(bracketType, INIT_TYPE)) + if (!isBraceType(braceType, INIT_TYPE)) appendSpacePad(); } appendCurrentChar(); } - else if (bracketFormatMode == NONE_MODE) + else if (braceFormatMode == NONE_MODE) { - if (currentLineBeginsWithBracket - && charNum == (int) currentLineFirstBracketNum) + if (currentLineBeginsWithBrace + && (size_t) charNum == currentLineFirstBraceNum) { appendCurrentChar(); // don't attach } else { if (previousNonWSChar != '(') { // don't space pad C++11 uniform initialization - if (!isBracketType(bracketType, INIT_TYPE)) + if (!isBraceType(braceType, INIT_TYPE)) appendSpacePad(); } appendCurrentChar(false); // OK to attach } } } - else // not the first opening bracket + else // not the first opening brace { - if (bracketFormatMode == RUN_IN_MODE) + if (braceFormatMode == RUN_IN_MODE) { if (previousNonWSChar == '{' - && bracketTypeStack->size() > 2 - && !isBracketType((*bracketTypeStack)[bracketTypeStack->size() - 2], - SINGLE_LINE_TYPE)) + && braceTypeStack->size() > 2 + && !isBraceType((*braceTypeStack)[braceTypeStack->size() - 2], + SINGLE_LINE_TYPE)) formatArrayRunIn(); } else if (!isInLineBreak && !isWhiteSpace(peekNextChar()) && previousNonWSChar == '{' - && bracketTypeStack->size() > 2 - && !isBracketType((*bracketTypeStack)[bracketTypeStack->size() - 2], - SINGLE_LINE_TYPE)) + && braceTypeStack->size() > 2 + && !isBraceType((*braceTypeStack)[braceTypeStack->size() - 2], + SINGLE_LINE_TYPE)) formatArrayRunIn(); appendCurrentChar(); } } else if (currentChar == '}') { - if (attachClosingBracketMode) + if (attachClosingBraceMode) { if (isEmptyLine(formattedLine) // if a blank line precedes this || isImmediatelyPostPreprocessor @@ -4960,18 +5281,18 @@ } else { - // does this close the first opening bracket in the array? + // does this close the first opening brace in the array? // must check if the block is still a single line because of anonymous statements - if (!isBracketType(bracketType, INIT_TYPE) - && (!isBracketType(bracketType, SINGLE_LINE_TYPE) + if (!isBraceType(braceType, INIT_TYPE) + && (!isBraceType(braceType, SINGLE_LINE_TYPE) || formattedLine.find('{') == string::npos)) breakLine(); appendCurrentChar(); } // if a declaration follows an enum definition, space pad char peekedChar = peekNextChar(); - if (isLegalNameChar(peekedChar) + if ((isLegalNameChar(peekedChar) && peekedChar != '.') || peekedChar == '[') appendSpaceAfter(); } @@ -4983,23 +5304,23 @@ */ void ASFormatter::formatRunIn() { - assert(bracketFormatMode == RUN_IN_MODE || bracketFormatMode == NONE_MODE); + assert(braceFormatMode == RUN_IN_MODE || braceFormatMode == NONE_MODE); // keep one line blocks returns true without indenting the run-in if (formattingStyle != STYLE_PICO - && !isOkToBreakBlock(bracketTypeStack->back())) + && !isOkToBreakBlock(braceTypeStack->back())) return; // true; - // make sure the line begins with a bracket + // make sure the line begins with a brace size_t lastText = formattedLine.find_last_not_of(" \t"); if (lastText == string::npos || formattedLine[lastText] != '{') return; // false; - // make sure the bracket is broken + // make sure the brace is broken if (formattedLine.find_first_not_of(" \t{") != string::npos) return; // false; - if (isBracketType(bracketTypeStack->back(), NAMESPACE_TYPE)) + if (isBraceType(braceTypeStack->back(), NAMESPACE_TYPE)) return; // false; bool extraIndent = false; @@ -5009,8 +5330,8 @@ // cannot attach a class modifier without indent-classes if (isCStyle() && isCharPotentialHeader(currentLine, charNum) - && (isBracketType(bracketTypeStack->back(), CLASS_TYPE) - || (isBracketType(bracketTypeStack->back(), STRUCT_TYPE) + && (isBraceType(braceTypeStack->back(), CLASS_TYPE) + || (isBraceType(braceTypeStack->back(), STRUCT_TYPE) && isInIndentableStruct))) { if (findKeyword(currentLine, charNum, AS_PUBLIC) @@ -5035,8 +5356,8 @@ // extra indent for switch statements if (getSwitchIndent() - && !preBracketHeaderStack->empty() - && preBracketHeaderStack->back() == &AS_SWITCH + && !preBraceHeaderStack->empty() + && preBraceHeaderStack->back() == &AS_SWITCH && ((isLegalNameChar(currentChar) && !findKeyword(currentLine, charNum, AS_CASE)))) extraIndent = true; @@ -5050,8 +5371,8 @@ if (extraHalfIndent) { int indentLength_ = getIndentLength(); - horstmannIndentChars = indentLength_ / 2; - formattedLine.append(horstmannIndentChars - 1, ' '); + runInIndentChars = indentLength_ / 2; + formattedLine.append(runInIndentChars - 1, ' '); } else if (getForceTabIndentation() && getIndentLength() != getTabLength()) { @@ -5065,43 +5386,43 @@ // replace spaces indents with tab indents size_t tabCount = indent.length() / tabLength_; // truncate extra spaces indent.replace(0U, tabCount * tabLength_, tabCount, '\t'); - horstmannIndentChars = indentLength_; - if (indent[0] == ' ') // allow for bracket + runInIndentChars = indentLength_; + if (indent[0] == ' ') // allow for brace indent.erase(0, 1); formattedLine.append(indent); } else if (getIndentString() == "\t") { appendChar('\t', false); - horstmannIndentChars = 2; // one for { and one for tab + runInIndentChars = 2; // one for { and one for tab if (extraIndent) { appendChar('\t', false); - horstmannIndentChars++; + runInIndentChars++; } } else // spaces { int indentLength_ = getIndentLength(); formattedLine.append(indentLength_ - 1, ' '); - horstmannIndentChars = indentLength_; + runInIndentChars = indentLength_; if (extraIndent) { formattedLine.append(indentLength_, ' '); - horstmannIndentChars += indentLength_; + runInIndentChars += indentLength_; } } - isInBracketRunIn = true; + isInBraceRunIn = true; } /** * remove whitespace and add indentation for an array run-in. */ void ASFormatter::formatArrayRunIn() { - assert(isBracketType(bracketTypeStack->back(), ARRAY_TYPE)); + assert(isBraceType(braceTypeStack->back(), ARRAY_TYPE)); - // make sure the bracket is broken + // make sure the brace is broken if (formattedLine.find_first_not_of(" \t{") != string::npos) return; @@ -5117,70 +5438,70 @@ if (getIndentString() == "\t") { appendChar('\t', false); - horstmannIndentChars = 2; // one for { and one for tab + runInIndentChars = 2; // one for { and one for tab } else { int indent = getIndentLength(); formattedLine.append(indent - 1, ' '); - horstmannIndentChars = indent; + runInIndentChars = indent; } - isInBracketRunIn = true; + isInBraceRunIn = true; isInLineBreak = false; } /** - * delete a bracketTypeStack vector object - * BracketTypeStack did not work with the DeleteContainer template + * delete a braceTypeStack vector object + * BraceTypeStack did not work with the DeleteContainer template */ -void ASFormatter::deleteContainer(vector*& container) +void ASFormatter::deleteContainer(vector*& container) { - if (container != NULL) + if (container != nullptr) { container->clear(); delete (container); - container = NULL; + container = nullptr; } } /** * delete a vector object * T is the type of vector - * used for all vectors except bracketTypeStack + * used for all vectors except braceTypeStack */ template void ASFormatter::deleteContainer(T& container) { - if (container != NULL) + if (container != nullptr) { container->clear(); delete (container); - container = NULL; + container = nullptr; } } /** - * initialize a BracketType vector object - * BracketType did not work with the DeleteContainer template + * initialize a braceType vector object + * braceType did not work with the DeleteContainer template */ -void ASFormatter::initContainer(vector*& container, vector* value) +void ASFormatter::initContainer(vector*& container, vector* value) { - if (container != NULL) + if (container != nullptr) deleteContainer(container); container = value; } /** * initialize a vector object * T is the type of vector - * used for all vectors except bracketTypeStack + * used for all vectors except braceTypeStack */ template void ASFormatter::initContainer(T& container, T value) { // since the ASFormatter object is never deleted, // the existing vectors must be deleted before creating new ones - if (container != NULL) + if (container != nullptr) deleteContainer(container); container = value; } @@ -5210,19 +5531,19 @@ /** * is it ok to break this block? */ -bool ASFormatter::isOkToBreakBlock(BracketType bracketType) const +bool ASFormatter::isOkToBreakBlock(BraceType braceType) const { - // Actually, there should not be an ARRAY_TYPE bracket here. + // Actually, there should not be an ARRAY_TYPE brace here. // But this will avoid breaking a one line block when there is. // Otherwise they will be formatted differently on consecutive runs. - if (isBracketType(bracketType, ARRAY_TYPE) - && isBracketType(bracketType, SINGLE_LINE_TYPE)) + if (isBraceType(braceType, ARRAY_TYPE) + && isBraceType(braceType, SINGLE_LINE_TYPE)) return false; - if (isBracketType(bracketType, COMMAND_TYPE) - && isBracketType(bracketType, EMPTY_BLOCK_TYPE)) + if (isBraceType(braceType, COMMAND_TYPE) + && isBraceType(braceType, EMPTY_BLOCK_TYPE)) return false; - if (!isBracketType(bracketType, SINGLE_LINE_TYPE) - || isBracketType(bracketType, BREAK_BLOCK_TYPE) + if (!isBraceType(braceType, SINGLE_LINE_TYPE) + || isBraceType(braceType, BREAK_BLOCK_TYPE) || shouldBreakOneLineBlocks) return true; return false; @@ -5241,30 +5562,30 @@ /** * Check for a following header when a comment is reached. * firstLine must contain the start of the comment. - * return value is a pointer to the header or NULL. + * return value is a pointer to the header or nullptr. */ const string* ASFormatter::checkForHeaderFollowingComment(const string& firstLine) const { assert(isInComment || isInLineComment); assert(shouldBreakElseIfs || shouldBreakBlocks || isInSwitchStatement()); // look ahead to find the next non-comment text - bool endOnEmptyLine = (currentHeader == NULL); + bool endOnEmptyLine = (currentHeader == nullptr); if (isInSwitchStatement()) endOnEmptyLine = false; string nextText = peekNextText(firstLine, endOnEmptyLine); if (nextText.length() == 0 || !isCharPotentialHeader(nextText, 0)) - return NULL; + return nullptr; - return ASBeautifier::findHeader(nextText, 0, headers); + return ASBase::findHeader(nextText, 0, headers); } /** * process preprocessor statements. * charNum should be the index of the #. * - * delete bracketTypeStack entries added by #if if a #else is found. - * prevents double entries in the bracketTypeStack. + * delete braceTypeStack entries added by #if if a #else is found. + * prevents double entries in the braceTypeStack. */ void ASFormatter::processPreprocessor() { @@ -5277,17 +5598,17 @@ if (currentLine.compare(preproc, 2, "if") == 0) { - preprocBracketTypeStackSize = bracketTypeStack->size(); + preprocBraceTypeStackSize = braceTypeStack->size(); } else if (currentLine.compare(preproc, 4, "else") == 0) { // delete stack entries added in #if // should be replaced by #else - if (preprocBracketTypeStackSize > 0) + if (preprocBraceTypeStackSize > 0) { - int addedPreproc = bracketTypeStack->size() - preprocBracketTypeStackSize; + int addedPreproc = braceTypeStack->size() - preprocBraceTypeStackSize; for (int i = 0; i < addedPreproc; i++) - bracketTypeStack->pop_back(); + braceTypeStack->pop_back(); } } } @@ -5302,26 +5623,24 @@ assert(shouldDeleteEmptyLines && shouldBreakBlocks); // is the next line a comment - if (!sourceIterator->hasMoreLines()) + auto stream = make_shared(sourceIterator); + if (!stream->hasMoreLines()) return false; - string nextLine_ = sourceIterator->peekNextLine(); + string nextLine_ = stream->peekNextLine(); size_t firstChar = nextLine_.find_first_not_of(" \t"); if (firstChar == string::npos || !(nextLine_.compare(firstChar, 2, "//") == 0 || nextLine_.compare(firstChar, 2, "/*") == 0)) - { - sourceIterator->peekReset(); return false; - } // find the next non-comment text, and reset - string nextText = peekNextText(nextLine_, false, true); + string nextText = peekNextText(nextLine_, false, stream); if (nextText.length() == 0 || !isCharPotentialHeader(nextText, 0)) return false; - const string* newHeader = ASBeautifier::findHeader(nextText, 0, headers); + const string* newHeader = ASBase::findHeader(nextText, 0, headers); - if (newHeader == NULL) + if (newHeader == nullptr) return false; // if a closing header, reset break unless break is requested @@ -5335,108 +5654,109 @@ } /** - * determine if a bracket should be attached or broken - * uses brackets in the bracketTypeStack - * the last bracket in the bracketTypeStack is the one being formatted - * returns true if the bracket should be broken + * determine if a brace should be attached or broken + * uses braces in the braceTypeStack + * the last brace in the braceTypeStack is the one being formatted + * returns true if the brace should be broken */ -bool ASFormatter::isCurrentBracketBroken() const +bool ASFormatter::isCurrentBraceBroken() const { - assert(bracketTypeStack->size() > 1); + assert(braceTypeStack->size() > 1); - bool breakBracket = false; - size_t stackEnd = bracketTypeStack->size() - 1; + bool breakBrace = false; + size_t stackEnd = braceTypeStack->size() - 1; - // check bracket modifiers + // check brace modifiers if (shouldAttachExternC - && isBracketType((*bracketTypeStack)[stackEnd], EXTERN_TYPE)) + && isBraceType((*braceTypeStack)[stackEnd], EXTERN_TYPE)) { return false; } if (shouldAttachNamespace - && isBracketType((*bracketTypeStack)[stackEnd], NAMESPACE_TYPE)) + && isBraceType((*braceTypeStack)[stackEnd], NAMESPACE_TYPE)) { return false; } if (shouldAttachClass - && (isBracketType((*bracketTypeStack)[stackEnd], CLASS_TYPE) - || isBracketType((*bracketTypeStack)[stackEnd], INTERFACE_TYPE))) + && (isBraceType((*braceTypeStack)[stackEnd], CLASS_TYPE) + || isBraceType((*braceTypeStack)[stackEnd], INTERFACE_TYPE))) { return false; } if (shouldAttachInline && isCStyle() // for C++ only - && bracketFormatMode != RUN_IN_MODE - && isBracketType((*bracketTypeStack)[stackEnd], COMMAND_TYPE)) + && braceFormatMode != RUN_IN_MODE + && !(currentLineBeginsWithBrace && peekNextChar() == '/') + && isBraceType((*braceTypeStack)[stackEnd], COMMAND_TYPE)) { size_t i; - for (i = 1; i < bracketTypeStack->size(); i++) - if (isBracketType((*bracketTypeStack)[i], CLASS_TYPE) - || isBracketType((*bracketTypeStack)[i], STRUCT_TYPE)) + for (i = 1; i < braceTypeStack->size(); i++) + if (isBraceType((*braceTypeStack)[i], CLASS_TYPE) + || isBraceType((*braceTypeStack)[i], STRUCT_TYPE)) return false; } - // check brackets - if (isBracketType((*bracketTypeStack)[stackEnd], EXTERN_TYPE)) + // check braces + if (isBraceType((*braceTypeStack)[stackEnd], EXTERN_TYPE)) { - if (currentLineBeginsWithBracket - || bracketFormatMode == RUN_IN_MODE) - breakBracket = true; + if (currentLineBeginsWithBrace + || braceFormatMode == RUN_IN_MODE) + breakBrace = true; } - else if (bracketFormatMode == NONE_MODE) + else if (braceFormatMode == NONE_MODE) { - if (currentLineBeginsWithBracket - && (int) currentLineFirstBracketNum == charNum) - breakBracket = true; + if (currentLineBeginsWithBrace + && currentLineFirstBraceNum == (size_t) charNum) + breakBrace = true; } - else if (bracketFormatMode == BREAK_MODE || bracketFormatMode == RUN_IN_MODE) + else if (braceFormatMode == BREAK_MODE || braceFormatMode == RUN_IN_MODE) { - breakBracket = true; + breakBrace = true; } - else if (bracketFormatMode == LINUX_MODE) + else if (braceFormatMode == LINUX_MODE) { // break a namespace if NOT stroustrup or mozilla - if (isBracketType((*bracketTypeStack)[stackEnd], NAMESPACE_TYPE)) + if (isBraceType((*braceTypeStack)[stackEnd], NAMESPACE_TYPE)) { if (formattingStyle != STYLE_STROUSTRUP && formattingStyle != STYLE_MOZILLA) - breakBracket = true; + breakBrace = true; } // break a class or interface if NOT stroustrup - else if (isBracketType((*bracketTypeStack)[stackEnd], CLASS_TYPE) - || isBracketType((*bracketTypeStack)[stackEnd], INTERFACE_TYPE)) + else if (isBraceType((*braceTypeStack)[stackEnd], CLASS_TYPE) + || isBraceType((*braceTypeStack)[stackEnd], INTERFACE_TYPE)) { if (formattingStyle != STYLE_STROUSTRUP) - breakBracket = true; + breakBrace = true; } - // break a struct if mozilla - an enum is processed as an array bracket - else if (isBracketType((*bracketTypeStack)[stackEnd], STRUCT_TYPE)) + // break a struct if mozilla - an enum is processed as an array brace + else if (isBraceType((*braceTypeStack)[stackEnd], STRUCT_TYPE)) { if (formattingStyle == STYLE_MOZILLA) - breakBracket = true; + breakBrace = true; } - // break the first bracket if a function - else if (isBracketType((*bracketTypeStack)[stackEnd], COMMAND_TYPE)) + // break the first brace if a function + else if (isBraceType((*braceTypeStack)[stackEnd], COMMAND_TYPE)) { if (stackEnd == 1) { - breakBracket = true; + breakBrace = true; } else if (stackEnd > 1) { - // break the first bracket after these if a function - if (isBracketType((*bracketTypeStack)[stackEnd - 1], NAMESPACE_TYPE) - || isBracketType((*bracketTypeStack)[stackEnd - 1], CLASS_TYPE) - || isBracketType((*bracketTypeStack)[stackEnd - 1], ARRAY_TYPE) - || isBracketType((*bracketTypeStack)[stackEnd - 1], STRUCT_TYPE) - || isBracketType((*bracketTypeStack)[stackEnd - 1], EXTERN_TYPE)) + // break the first brace after these if a function + if (isBraceType((*braceTypeStack)[stackEnd - 1], NAMESPACE_TYPE) + || isBraceType((*braceTypeStack)[stackEnd - 1], CLASS_TYPE) + || isBraceType((*braceTypeStack)[stackEnd - 1], ARRAY_TYPE) + || isBraceType((*braceTypeStack)[stackEnd - 1], STRUCT_TYPE) + || isBraceType((*braceTypeStack)[stackEnd - 1], EXTERN_TYPE)) { - breakBracket = true; + breakBrace = true; } } } } - return breakBracket; + return breakBrace; } /** @@ -5482,10 +5802,10 @@ // Check for a following header. // For speed do not check multiple comment lines more than once. // For speed do not check shouldBreakBlocks if previous line is empty, a comment, or a '{'. - const string* followingHeader = NULL; + const string* followingHeader = nullptr; if ((doesLineStartComment && !isImmediatelyPostCommentOnly - && isBracketType(bracketTypeStack->back(), COMMAND_TYPE)) + && isBraceType(braceTypeStack->back(), COMMAND_TYPE)) && (shouldBreakElseIfs || isInSwitchStatement() || (shouldBreakBlocks @@ -5502,25 +5822,25 @@ && !isImmediatelyPostComment && !isImmediatelyPostLineComment) { - if (isBracketType(bracketTypeStack->back(), NAMESPACE_TYPE)) + if (isBraceType(braceTypeStack->back(), NAMESPACE_TYPE)) { // namespace run-in is always broken. isInLineBreak = true; } - else if (bracketFormatMode == NONE_MODE) + else if (braceFormatMode == NONE_MODE) { // should a run-in statement be attached? - if (currentLineBeginsWithBracket) + if (currentLineBeginsWithBrace) formatRunIn(); } - else if (bracketFormatMode == ATTACH_MODE) + else if (braceFormatMode == ATTACH_MODE) { - // if the bracket was not attached? + // if the brace was not attached? if (formattedLine.length() > 0 && formattedLine[0] == '{' - && !isBracketType(bracketTypeStack->back(), SINGLE_LINE_TYPE)) + && !isBraceType(braceTypeStack->back(), SINGLE_LINE_TYPE)) isInLineBreak = true; } - else if (bracketFormatMode == RUN_IN_MODE) + else if (braceFormatMode == RUN_IN_MODE) { // should a run-in statement be attached? if (formattedLine.length() > 0 && formattedLine[0] == '{') @@ -5545,7 +5865,7 @@ // Break before the comment if a header follows the line comment. // But not break if previous line is empty, a comment, or a '{'. if (shouldBreakBlocks - && followingHeader != NULL + && followingHeader != nullptr && !isImmediatelyPostEmptyLine && previousCommandChar != '{') { @@ -5560,7 +5880,7 @@ } if (previousCommandChar == '}') - currentHeader = NULL; + currentHeader = nullptr; } /** @@ -5580,9 +5900,9 @@ lineEndsInCommentOnly = true; if (peekNextChar() == '}' && previousCommandChar != ';' - && !isBracketType(bracketTypeStack->back(), ARRAY_TYPE) + && !isBraceType(braceTypeStack->back(), ARRAY_TYPE) && !isInPreprocessor - && isOkToBreakBlock(bracketTypeStack->back())) + && isOkToBreakBlock(braceTypeStack->back())) { isInLineBreak = true; shouldBreakLineAtNextChar = true; @@ -5639,19 +5959,19 @@ // Check for a following header. // For speed do not check multiple comment lines more than once. // For speed do not check shouldBreakBlocks if previous line is empty, a comment, or a '{'. - const string* followingHeader = NULL; + const string* followingHeader = nullptr; if ((lineIsLineCommentOnly && !isImmediatelyPostCommentOnly - && isBracketType(bracketTypeStack->back(), COMMAND_TYPE)) + && isBraceType(braceTypeStack->back(), COMMAND_TYPE)) && (shouldBreakElseIfs || isInSwitchStatement() || (shouldBreakBlocks && !isImmediatelyPostEmptyLine && previousCommandChar != '{'))) followingHeader = checkForHeaderFollowingComment(currentLine.substr(charNum)); // do not indent if in column 1 or 2 - // or in a namespace before the opening bracket + // or in a namespace before the opening brace if ((!shouldIndentCol1Comments && !lineCommentNoIndent) || foundNamespaceHeader) { @@ -5671,26 +5991,26 @@ && !isImmediatelyPostComment && !isImmediatelyPostLineComment) { - if (bracketFormatMode == NONE_MODE) + if (braceFormatMode == NONE_MODE) { - if (currentLineBeginsWithBracket) + if (currentLineBeginsWithBrace) formatRunIn(); } - else if (bracketFormatMode == RUN_IN_MODE) + else if (braceFormatMode == RUN_IN_MODE) { if (!lineCommentNoIndent) formatRunIn(); else isInLineBreak = true; } - else if (bracketFormatMode == BREAK_MODE) + else if (braceFormatMode == BREAK_MODE) { if (formattedLine.length() > 0 && formattedLine[0] == '{') isInLineBreak = true; } else { - if (currentLineBeginsWithBracket) + if (currentLineBeginsWithBrace) isInLineBreak = true; } } @@ -5710,7 +6030,7 @@ // Break before the comment if a header follows the line comment. // But do not break if previous line is empty, a comment, or a '{'. if (shouldBreakBlocks - && followingHeader != NULL + && followingHeader != nullptr && !isImmediatelyPostEmptyLine && previousCommandChar != '{') { @@ -5725,7 +6045,7 @@ } if (previousCommandChar == '}') - currentHeader = NULL; + currentHeader = nullptr; // if tabbed input don't convert the immediately following tabs to spaces if (getIndentString() == "\t" && lineCommentNoIndent) @@ -5841,51 +6161,51 @@ else if (isSharpStyle() && previousChar == '@') isInVerbatimQuote = true; - // a quote following a bracket is an array + // a quote following a brace is an array if (previousCommandChar == '{' && !isImmediatelyPostComment && !isImmediatelyPostLineComment && isNonInStatementArray - && !isBracketType(bracketTypeStack->back(), SINGLE_LINE_TYPE) + && !isBraceType(braceTypeStack->back(), SINGLE_LINE_TYPE) && !isWhiteSpace(peekNextChar())) { - if (bracketFormatMode == NONE_MODE) + if (braceFormatMode == NONE_MODE) { - if (currentLineBeginsWithBracket) + if (currentLineBeginsWithBrace) formatRunIn(); } - else if (bracketFormatMode == RUN_IN_MODE) + else if (braceFormatMode == RUN_IN_MODE) { formatRunIn(); } - else if (bracketFormatMode == BREAK_MODE) + else if (braceFormatMode == BREAK_MODE) { if (formattedLine.length() > 0 && formattedLine[0] == '{') isInLineBreak = true; } else { - if (currentLineBeginsWithBracket) + if (currentLineBeginsWithBrace) isInLineBreak = true; } } previousCommandChar = ' '; appendCurrentChar(); } /** - * get the next line comment adjustment that results from breaking a closing bracket. - * the bracket must be on the same line as the closing header. + * get the next line comment adjustment that results from breaking a closing brace. + * the brace must be on the same line as the closing header. * i.e "} else" changed to "} else". */ int ASFormatter::getNextLineCommentAdjustment() { assert(foundClosingHeader && previousNonWSChar == '}'); if (charNum < 1) // "else" is in column 1 return 0; - size_t lastBracket = currentLine.rfind('}', charNum - 1); - if (lastBracket != string::npos) - return (lastBracket - charNum); // return a negative number + size_t lastBrace = currentLine.rfind('}', charNum - 1); + if (lastBrace != string::npos) + return (lastBrace - charNum); // return a negative number return 0; } @@ -5897,18 +6217,18 @@ /** * get the current line comment adjustment that results from attaching - * a closing header to a closing bracket. - * the bracket must be on the line previous to the closing header. - * the adjustment is 2 chars, one for the bracket and one for the space. + * a closing header to a closing brace. + * the brace must be on the line previous to the closing header. + * the adjustment is 2 chars, one for the brace and one for the space. * i.e "} else" changed to "} else". */ int ASFormatter::getCurrentLineCommentAdjustment() { assert(foundClosingHeader && previousNonWSChar == '}'); if (charNum < 1) return 2; - size_t lastBracket = currentLine.rfind('}', charNum - 1); - if (lastBracket == string::npos) + size_t lastBrace = currentLine.rfind('}', charNum - 1); + if (lastBrace == string::npos) return 2; return 0; } @@ -5941,75 +6261,89 @@ } /** - * check if a line break is needed when a closing bracket + * check if a line break is needed when a closing brace * is followed by a closing header. - * the break depends on the bracketFormatMode and other factors. + * the break depends on the braceFormatMode and other factors. */ void ASFormatter::isLineBreakBeforeClosingHeader() { assert(foundClosingHeader && previousNonWSChar == '}'); - if (bracketFormatMode == BREAK_MODE - || bracketFormatMode == RUN_IN_MODE - || attachClosingBracketMode) + + if (currentHeader == &AS_WHILE && shouldAttachClosingWhile) + { + appendClosingHeader(); + return; + } + + if (braceFormatMode == BREAK_MODE + || braceFormatMode == RUN_IN_MODE + || attachClosingBraceMode) { isInLineBreak = true; } - else if (bracketFormatMode == NONE_MODE) + else if (braceFormatMode == NONE_MODE) { - if (shouldBreakClosingHeaderBrackets - || getBracketIndent() || getBlockIndent()) + if (shouldBreakClosingHeaderBraces + || getBraceIndent() || getBlockIndent()) { isInLineBreak = true; } else { appendSpacePad(); - // is closing bracket broken? + // is closing brace broken? size_t i = currentLine.find_first_not_of(" \t"); if (i != string::npos && currentLine[i] == '}') isInLineBreak = false; if (shouldBreakBlocks) isAppendPostBlockEmptyLineRequested = false; } } - // bracketFormatMode == ATTACH_MODE, LINUX_MODE + // braceFormatMode == ATTACH_MODE, LINUX_MODE else { - if (shouldBreakClosingHeaderBrackets - || getBracketIndent() || getBlockIndent()) + if (shouldBreakClosingHeaderBraces + || getBraceIndent() || getBlockIndent()) { isInLineBreak = true; } else { - // if a blank line does not precede this - // or last line is not a one line block, attach header - bool previousLineIsEmpty = isEmptyLine(formattedLine); - int previousLineIsOneLineBlock = 0; - size_t firstBracket = findNextChar(formattedLine, '{'); - if (firstBracket != string::npos) - previousLineIsOneLineBlock = isOneLineBlockReached(formattedLine, firstBracket); - if (!previousLineIsEmpty - && previousLineIsOneLineBlock == 0) - { - isInLineBreak = false; - appendSpacePad(); - spacePadNum = 0; // don't count as comment padding - } - + appendClosingHeader(); if (shouldBreakBlocks) isAppendPostBlockEmptyLineRequested = false; } } } /** - * Add brackets to a single line statement following a header. - * Brackets are not added if the proper conditions are not met. - * Brackets are added to the currentLine. + * Append a closing header to the previous closing brace, if possible */ -bool ASFormatter::addBracketsToStatement() +void ASFormatter::appendClosingHeader() +{ + // if a blank line does not precede this + // or last line is not a one line block, attach header + bool previousLineIsEmpty = isEmptyLine(formattedLine); + int previousLineIsOneLineBlock = 0; + size_t firstBrace = findNextChar(formattedLine, '{'); + if (firstBrace != string::npos) + previousLineIsOneLineBlock = isOneLineBlockReached(formattedLine, firstBrace); + if (!previousLineIsEmpty + && previousLineIsOneLineBlock == 0) + { + isInLineBreak = false; + appendSpacePad(); + spacePadNum = 0; // don't count as comment padding + } +} + +/** + * Add braces to a single line statement following a header. + * braces are not added if the proper conditions are not met. + * braces are added to the currentLine. + */ +bool ASFormatter::addBracesToStatement() { assert(isImmediatelyPostHeader); @@ -6027,13 +6361,13 @@ if (currentHeader == &AS_WHILE && foundClosingHeader) // do-while return false; - // do not bracket an empty statement + // do not brace an empty statement if (currentChar == ';') return false; // do not add if a header follows if (isCharPotentialHeader(currentLine, charNum)) - if (findHeader(headers) != NULL) + if (findHeader(headers) != nullptr) return false; // find the next semi-colon @@ -6043,19 +6377,19 @@ if (nextSemiColon == string::npos) return false; - // add closing bracket before changing the line length + // add closing brace before changing the line length if (nextSemiColon == currentLine.length() - 1) currentLine.append(" }"); else currentLine.insert(nextSemiColon + 1, " }"); - // add opening bracket + // add opening brace currentLine.insert(charNum, "{ "); assert(computeChecksumIn("{}")); currentChar = '{'; if ((int) currentLine.find_first_not_of(" \t") == charNum) - currentLineBeginsWithBracket = true; + currentLineBeginsWithBrace = true; // remove extra spaces - if (!shouldAddOneLineBrackets) + if (!shouldAddOneLineBraces) { size_t lastText = formattedLine.find_last_not_of(" \t"); if ((formattedLine.length() - 1) - lastText > 1) @@ -6065,11 +6399,11 @@ } /** - * Remove brackets from a single line statement following a header. - * Brackets are not removed if the proper conditions are not met. - * The first bracket is replaced by a space. + * Remove braces from a single line statement following a header. + * braces are not removed if the proper conditions are not met. + * The first brace is replaced by a space. */ -bool ASFormatter::removeBracketsFromStatement() +bool ASFormatter::removeBracesFromStatement() { assert(isImmediatelyPostHeader); assert(currentChar == '{'); @@ -6085,81 +6419,67 @@ return false; bool isFirstLine = true; - bool needReset = false; string nextLine_; // leave nextLine_ empty if end of line comment follows - if (!isBeforeAnyLineEndComment(charNum) || currentLineBeginsWithBracket) + if (!isBeforeAnyLineEndComment(charNum) || currentLineBeginsWithBrace) nextLine_ = currentLine.substr(charNum + 1); size_t nextChar = 0; // find the first non-blank text - while (sourceIterator->hasMoreLines() || isFirstLine) + ASPeekStream stream(sourceIterator); + while (stream.hasMoreLines() || isFirstLine) { if (isFirstLine) isFirstLine = false; else { - nextLine_ = sourceIterator->peekNextLine(); + nextLine_ = stream.peekNextLine(); nextChar = 0; - needReset = true; } nextChar = nextLine_.find_first_not_of(" \t", nextChar); if (nextChar != string::npos) break; } + if (!stream.hasMoreLines()) + return false; - // don't remove if comments or a header follow the bracket + // don't remove if comments or a header follow the brace if ((nextLine_.compare(nextChar, 2, "/*") == 0) || (nextLine_.compare(nextChar, 2, "//") == 0) || (isCharPotentialHeader(nextLine_, nextChar) - && ASBeautifier::findHeader(nextLine_, nextChar, headers) != NULL)) - { - if (needReset) - sourceIterator->peekReset(); + && ASBase::findHeader(nextLine_, nextChar, headers) != nullptr)) return false; - } // find the next semi-colon size_t nextSemiColon = nextChar; if (nextLine_[nextChar] != ';') nextSemiColon = findNextChar(nextLine_, ';', nextChar + 1); if (nextSemiColon == string::npos) - { - if (needReset) - sourceIterator->peekReset(); return false; - } - // find the closing bracket + // find the closing brace isFirstLine = true; nextChar = nextSemiColon + 1; - while (sourceIterator->hasMoreLines() || isFirstLine) + while (stream.hasMoreLines() || isFirstLine) { if (isFirstLine) isFirstLine = false; else { - nextLine_ = sourceIterator->peekNextLine(); + nextLine_ = stream.peekNextLine(); nextChar = 0; - needReset = true; } nextChar = nextLine_.find_first_not_of(" \t", nextChar); if (nextChar != string::npos) break; } if (nextLine_.length() == 0 || nextLine_[nextChar] != '}') - { - if (needReset) - sourceIterator->peekReset(); return false; - } - // remove opening bracket + // remove opening brace currentLine[charNum] = currentChar = ' '; assert(adjustChecksumIn(-'{')); - if (needReset) - sourceIterator->peekReset(); return true; } @@ -6171,7 +6491,7 @@ * @param searchStart the start position on the line (default is 0). * @return the position on the line or string::npos if not found. */ -size_t ASFormatter::findNextChar(string& line, char searchChar, int searchStart /*0*/) const +size_t ASFormatter::findNextChar(const string& line, char searchChar, int searchStart /*0*/) const { // find the next searchChar size_t i; @@ -6208,7 +6528,7 @@ if (line[i] == searchChar) break; - // for now don't process C# 'delegate' brackets + // for now don't process C# 'delegate' braces // do this last in case the search char is a '{' if (line[i] == '{') return string::npos; @@ -6219,36 +6539,304 @@ return i; } +/** + * Find split point for break/attach return type. + */ +void ASFormatter::findReturnTypeSplitPoint(const string& firstLine) +{ + assert((isBraceType(braceTypeStack->back(), NULL_TYPE) + || isBraceType(braceTypeStack->back(), DEFINITION_TYPE))); + assert(shouldBreakReturnType || shouldBreakReturnTypeDecl + || shouldAttachReturnType || shouldAttachReturnTypeDecl); + + bool isFirstLine = true; + bool isInComment_ = false; + bool isInQuote_ = false; + bool foundSplitPoint = false; + bool isAlreadyBroken = false; + char quoteChar_ = ' '; + char currNonWSChar = ' '; + char prevNonWSChar = ' '; + size_t parenCount = 0; + size_t squareCount = 0; + size_t angleCount = 0; + size_t breakLineNum = 0; + size_t breakCharNum = string::npos; + string line = firstLine; + + // Process the lines until a ';' or '{'. + ASPeekStream stream(sourceIterator); + while (stream.hasMoreLines() || isFirstLine) + { + if (isFirstLine) + isFirstLine = false; + else + { + if (isInQuote_) + return; + line = stream.peekNextLine(); + if (!foundSplitPoint) + ++breakLineNum; + } + size_t firstCharNum = line.find_first_not_of(" \t"); + if (firstCharNum == string::npos) + continue; + if (line[firstCharNum] == '#') + { + // don't attach to a preprocessor + if (shouldAttachReturnType || shouldAttachReturnTypeDecl) + return; + else + continue; + } + // parse the line + for (size_t i = 0; i < line.length(); i++) + { + if (!isWhiteSpace(line[i])) + { + prevNonWSChar = currNonWSChar; + currNonWSChar = line[i]; + } + else if (line[i] == '\t' && shouldConvertTabs) + { + size_t tabSize = getTabLength(); + size_t numSpaces = tabSize - ((tabIncrementIn + i) % tabSize); + line.replace(i, 1, numSpaces, ' '); + currentChar = line[i]; + } + if (line.compare(i, 2, "/*") == 0) + isInComment_ = true; + if (isInComment_) + { + if (line.compare(i, 2, "*/") == 0) + { + isInComment_ = false; + ++i; + } + continue; + } + if (line[i] == '\\') + { + ++i; + continue; + } + + if (isInQuote_) + { + if (line[i] == quoteChar_) + isInQuote_ = false; + continue; + } + + if (line[i] == '"' + || (line[i] == '\'' && !isDigitSeparator(line, i))) + { + isInQuote_ = true; + quoteChar_ = line[i]; + continue; + } + if (line.compare(i, 2, "//") == 0) + { + i = line.length(); + continue; + } + // not in quote or comment + if (!foundSplitPoint) + { + if (line[i] == '<') + { + ++angleCount; + continue; + } + if (line[i] == '>') + { + if (angleCount) + --angleCount; + if (!angleCount) + { + size_t nextCharNum = line.find_first_not_of(" \t*&", i + 1); + if (nextCharNum == string::npos) + { + breakCharNum = string::npos; + continue; + } + if (line[nextCharNum] != ':') // scope operator + breakCharNum = nextCharNum; + } + continue; + } + if (angleCount) + continue; + if (line[i] == '[') + { + ++squareCount; + continue; + } + if (line[i] == ']') + { + if (squareCount) + --squareCount; + continue; + } + // an assignment before the parens is not a function + if (line[i] == '=') + return; + if (isWhiteSpace(line[i]) || line[i] == '*' || line[i] == '&') + { + size_t nextNum = line.find_first_not_of(" \t", i + 1); + if (nextNum == string::npos) + breakCharNum = string::npos; + else + { + if (line.length() > nextNum + 1 + && line[nextNum] == ':' && line[nextNum + 1] == ':') + i = --nextNum; + else if (line[nextNum] != '(') + breakCharNum = string::npos; + } + continue; + } + if ((isLegalNameChar(line[i]) || line[i] == '~') + && breakCharNum == string::npos) + { + breakCharNum = i; + if (isLegalNameChar(line[i]) + && findKeyword(line, i, AS_OPERATOR)) + { + if (breakCharNum == firstCharNum) + isAlreadyBroken = true; + foundSplitPoint = true; + // find the operator, may be parens + size_t parenNum = + line.find_first_not_of(" \t", i + AS_OPERATOR.length()); + if (parenNum == string::npos) + return; + // find paren after the operator + parenNum = line.find('(', parenNum + 1); + if (parenNum == string::npos) + return; + i = --parenNum; + } + continue; + } + if (line[i] == ':' + && line.length() > i + 1 + && line[i + 1] == ':') + { + size_t nextCharNum = line.find_first_not_of(" \t:", i + 1); + if (nextCharNum == string::npos) + return; + + if (isLegalNameChar(line[nextCharNum]) + && findKeyword(line, nextCharNum, AS_OPERATOR)) + { + i = nextCharNum; + if (breakCharNum == firstCharNum) + isAlreadyBroken = true; + foundSplitPoint = true; + // find the operator, may be parens + size_t parenNum = + line.find_first_not_of(" \t", i + AS_OPERATOR.length()); + if (parenNum == string::npos) + return; + // find paren after the operator + parenNum = line.find('(', parenNum + 1); + if (parenNum == string::npos) + return; + i = --parenNum; + } + else + i = --nextCharNum; + continue; + } + if (line[i] == '(' && !squareCount) + { + // is line is already broken? + if (breakCharNum == firstCharNum && breakLineNum > 0) + isAlreadyBroken = true; + ++parenCount; + foundSplitPoint = true; + continue; + } + } + // end !foundSplitPoint + if (line[i] == '(') + { + // consecutive ')(' parens is probably a function pointer + if (prevNonWSChar == ')' && !parenCount) + return; + ++parenCount; + continue; + } + if (line[i] == ')') + { + if (parenCount) + --parenCount; + continue; + } + if (line[i] == '{') + { + if (shouldBreakReturnType && foundSplitPoint && !isAlreadyBroken) + { + methodBreakCharNum = breakCharNum; + methodBreakLineNum = breakLineNum; + } + if (shouldAttachReturnType && foundSplitPoint && isAlreadyBroken) + { + methodAttachCharNum = breakCharNum; + methodAttachLineNum = breakLineNum; + } + return; + } + if (line[i] == ';') + { + if (shouldBreakReturnTypeDecl && foundSplitPoint && !isAlreadyBroken) + { + methodBreakCharNum = breakCharNum; + methodBreakLineNum = breakLineNum; + } + if ((shouldAttachReturnTypeDecl && foundSplitPoint && isAlreadyBroken)) + { + methodAttachCharNum = breakCharNum; + methodAttachLineNum = breakLineNum; + } + return; + } + if (line[i] == '}') + return; + } // end of for loop + if (!foundSplitPoint) + breakCharNum = string::npos; + } // end of while loop +} + /** * Look ahead in the file to see if a struct has access modifiers. * * @param firstLine a reference to the line to indent. * @param index the current line index. * @return true if the struct has access modifiers. */ -bool ASFormatter::isStructAccessModified(string& firstLine, size_t index) const +bool ASFormatter::isStructAccessModified(const string& firstLine, size_t index) const { assert(firstLine[index] == '{'); assert(isCStyle()); bool isFirstLine = true; - bool needReset = false; - size_t bracketCount = 1; + size_t braceCount = 1; string nextLine_ = firstLine.substr(index + 1); + ASPeekStream stream(sourceIterator); // find the first non-blank text, bypassing all comments and quotes. bool isInComment_ = false; bool isInQuote_ = false; char quoteChar_ = ' '; - while (sourceIterator->hasMoreLines() || isFirstLine) + while (stream.hasMoreLines() || isFirstLine) { if (isFirstLine) isFirstLine = false; else - { - nextLine_ = sourceIterator->peekNextLine(); - needReset = true; - } + nextLine_ = stream.peekNextLine(); // parse the line for (size_t i = 0; i < nextLine_.length(); i++) { @@ -6290,36 +6878,26 @@ i = nextLine_.length(); continue; } - // handle brackets + // handle braces if (nextLine_[i] == '{') - ++bracketCount; + ++braceCount; if (nextLine_[i] == '}') - --bracketCount; - if (bracketCount == 0) - { - if (needReset) - sourceIterator->peekReset(); + --braceCount; + if (braceCount == 0) return false; - } // check for access modifiers if (isCharPotentialHeader(nextLine_, i)) { if (findKeyword(nextLine_, i, AS_PUBLIC) || findKeyword(nextLine_, i, AS_PRIVATE) || findKeyword(nextLine_, i, AS_PROTECTED)) - { - if (needReset) - sourceIterator->peekReset(); return true; - } string name = getCurrentWord(nextLine_, i); i += name.length() - 1; } } // end of for loop } // end of while loop - if (needReset) - sourceIterator->peekReset(); return false; } @@ -6330,35 +6908,32 @@ * @param index the current line index. * @return true if the block is indentable. */ -bool ASFormatter::isIndentablePreprocessorBlock(string& firstLine, size_t index) +bool ASFormatter::isIndentablePreprocessorBlock(const string& firstLine, size_t index) { assert(firstLine[index] == '#'); bool isFirstLine = true; - bool needReset = false; bool isInIndentableBlock = false; - bool blockContainsBrackets = false; + bool blockContainsBraces = false; bool blockContainsDefineContinuation = false; bool isInClassConstructor = false; bool isPotentialHeaderGuard = false; // ifndef is first preproc statement bool isPotentialHeaderGuard2 = false; // define is within the first proproc int numBlockIndents = 0; int lineParenCount = 0; string nextLine_ = firstLine.substr(index); + auto stream = make_shared(sourceIterator); // find end of the block, bypassing all comments and quotes. bool isInComment_ = false; bool isInQuote_ = false; char quoteChar_ = ' '; - while (sourceIterator->hasMoreLines() || isFirstLine) + while (stream->hasMoreLines() || isFirstLine) { if (isFirstLine) isFirstLine = false; else - { - nextLine_ = sourceIterator->peekNextLine(); - needReset = true; - } + nextLine_ = stream->peekNextLine(); // parse the line for (size_t i = 0; i < nextLine_.length(); i++) { @@ -6437,21 +7012,21 @@ } // handle exceptions if (nextLine_[i] == '{' || nextLine_[i] == '}') - blockContainsBrackets = true; + blockContainsBraces = true; else if (nextLine_[i] == '(') ++lineParenCount; else if (nextLine_[i] == ')') --lineParenCount; else if (nextLine_[i] == ':') { // check for '::' - if (nextLine_.length() > i && nextLine_[i + 1] == ':') + if (nextLine_.length() > i + 1 && nextLine_[i + 1] == ':') ++i; else isInClassConstructor = true; } // bypass unnecessary parsing - must exit BOTH loops - if (blockContainsBrackets || isInClassConstructor || blockContainsDefineContinuation) + if (blockContainsBraces || isInClassConstructor || blockContainsDefineContinuation) goto EndOfWhileLoop; } // end of for loop, end of line if (lineParenCount != 0) @@ -6461,15 +7036,15 @@ preprocBlockEnd = sourceIterator->tellg(); if (preprocBlockEnd < 0) preprocBlockEnd = sourceIterator->getStreamLength(); - if (blockContainsBrackets + if (blockContainsBraces || isInClassConstructor || blockContainsDefineContinuation || lineParenCount != 0 || numBlockIndents != 0) isInIndentableBlock = false; // find next executable instruction // this WILL RESET the get pointer - string nextText = peekNextText("", false, needReset); + string nextText = peekNextText("", false, stream); // bypass header include guards if (isFirstPreprocConditional) { @@ -6487,7 +7062,7 @@ return isInIndentableBlock; } -bool ASFormatter::isNDefPreprocStatement(string& nextLine_, string& preproc) const +bool ASFormatter::isNDefPreprocStatement(const string& nextLine_, const string& preproc) const { if (preproc == "ifndef") return true; @@ -6511,7 +7086,7 @@ * @param index the current line index. * @return true if the statement is EXEC SQL. */ -bool ASFormatter::isExecSQL(string& line, size_t index) const +bool ASFormatter::isExecSQL(const string& line, size_t index) const { if (line[index] != 'e' && line[index] != 'E') // quick check to reject most return false; @@ -6651,25 +7226,22 @@ } bool isFirstLine = true; - bool needReset = false; int parenDepth_ = 0; int maxTemplateDepth = 0; templateDepth = 0; string nextLine_ = currentLine.substr(charNum); + ASPeekStream stream(sourceIterator); - // find the angle brackets, bypassing all comments and quotes. + // find the angle braces, bypassing all comments and quotes. bool isInComment_ = false; bool isInQuote_ = false; char quoteChar_ = ' '; - while (sourceIterator->hasMoreLines() || isFirstLine) + while (stream.hasMoreLines() || isFirstLine) { if (isFirstLine) isFirstLine = false; else - { - nextLine_ = sourceIterator->peekNextLine(); - needReset = true; - } + nextLine_ = stream.peekNextLine(); // parse the line for (size_t i = 0; i < nextLine_.length(); i++) { @@ -6731,7 +7303,7 @@ isInTemplate = true; templateDepth = maxTemplateDepth; } - goto exitFromSearch; + return; } continue; } @@ -6745,14 +7317,16 @@ continue; // this is not a template -> leave... isInTemplate = false; - goto exitFromSearch; + templateDepth = 0; + return; } else if (nextLine_.compare(i, 2, AS_AND) == 0 || nextLine_.compare(i, 2, AS_OR) == 0) { // this is not a template -> leave... isInTemplate = false; - goto exitFromSearch; + templateDepth = 0; + return; } else if (currentChar_ == ',' // comma, e.g. A || currentChar_ == '&' // reference, e.g. A @@ -6774,17 +7348,12 @@ // this is not a template -> leave... isInTemplate = false; templateDepth = 0; - goto exitFromSearch; + return; } string name = getCurrentWord(nextLine_, i); i += name.length() - 1; - } // end of for loop - } // end of while loop - - // goto needed to exit from two loops -exitFromSearch: - if (needReset) - sourceIterator->peekReset(); + } // end for loop + } // end while loop } void ASFormatter::updateFormattedLineSplitPoints(char appendedChar) @@ -6801,11 +7370,11 @@ if (nextChar == '/') return; - // don't split before or after a bracket + // don't split before or after a brace if (appendedChar == '{' || appendedChar == '}' || previousNonWSChar == '{' || previousNonWSChar == '}' || nextChar == '{' || nextChar == '}' - || currentChar == '{' || currentChar == '}') // currentChar tests for an appended bracket + || currentChar == '{' || currentChar == '}') // currentChar tests for an appended brace return; // don't split before or after a block paren @@ -6869,7 +7438,7 @@ { // if follows an operator break before size_t parenNum; - if (isCharPotentialOperator(previousNonWSChar)) + if (previousNonWSChar != ' ' && isCharPotentialOperator(previousNonWSChar)) parenNum = formattedLine.length() - 1; else parenNum = formattedLine.length(); @@ -6940,7 +7509,8 @@ else if (sequence == "+" || sequence == "-" || sequence == "?") { if (charNum > 0 - && !isInExponent() + && !(sequence == "+" && isInExponent()) + && !(sequence == "-" && isInExponent()) && (isLegalNameChar(currentLine[charNum - 1]) || currentLine[charNum - 1] == ')' || currentLine[charNum - 1] == ']' @@ -6956,7 +7526,7 @@ else if (sequence == "=" || sequence == ":") { // split BEFORE if the line is too long - // do NOT use <= here, must allow for a bracket attached to an array + // do NOT use <= here, must allow for a brace attached to an array size_t splitPoint = 0; if (formattedLine.length() < maxCodeLength) splitPoint = formattedLine.length(); @@ -7020,16 +7590,16 @@ || isInTemplate) return false; - if (!isOkToBreakBlock(bracketTypeStack->back()) && currentChar != '{') + if (!isOkToBreakBlock(braceTypeStack->back()) && currentChar != '{') { shouldKeepLineUnbroken = true; clearFormattedLineSplitPoints(); return false; } - if (isBracketType(bracketTypeStack->back(), ARRAY_TYPE)) + if (isBraceType(braceTypeStack->back(), ARRAY_TYPE)) { shouldKeepLineUnbroken = true; - if (!isBracketType(bracketTypeStack->back(), ARRAY_NIS_TYPE)) + if (!isBraceType(braceTypeStack->back(), ARRAY_NIS_TYPE)) clearFormattedLineSplitPoints(); return false; } @@ -7166,7 +7736,7 @@ { // if end of the currentLine, find a new split point size_t newCharNum; - if (isCharPotentialHeader(currentLine, charNum)) + if (!isWhiteSpace(currentChar) && isCharPotentialHeader(currentLine, charNum)) newCharNum = getCurrentWord(currentLine, charNum).length() + charNum; else newCharNum = charNum + 2; @@ -7292,10 +7862,10 @@ // find next word size_t nextNum = currentLine.find_first_not_of(" \t", charNum + 1); if (nextNum == string::npos) - return NULL; + return nullptr; if (!isLegalNameChar(currentLine[nextNum])) - return NULL; + return nullptr; // bypass next word and following spaces while (nextNum < currentLine.length()) @@ -7309,17 +7879,17 @@ if (nextNum >= currentLine.length() || !isCharPotentialOperator(currentLine[nextNum]) || currentLine[nextNum] == '/') // comment - return NULL; + return nullptr; - const string* newOperator = ASBeautifier::findOperator(currentLine, nextNum, operators); + const string* newOperator = ASBase::findOperator(currentLine, nextNum, operators); return newOperator; } // Check following data to determine if the current character is an array operator. bool ASFormatter::isArrayOperator() const { assert(currentChar == '*' || currentChar == '&' || currentChar == '^'); - assert(isBracketType(bracketTypeStack->back(), ARRAY_TYPE)); + assert(isBraceType(braceTypeStack->back(), ARRAY_TYPE)); // find next word size_t nextNum = currentLine.find_first_not_of(" \t", charNum + 1); @@ -7358,17 +7928,22 @@ foundPreDefinitionHeader = false; foundPreCommandHeader = false; foundPreCommandMacro = false; + foundTrailingReturnType = false; foundCastOperator = false; isInPotentialCalculation = false; isSharpAccessor = false; isSharpDelegate = false; isInObjCMethodDefinition = false; + isImmediatelyPostObjCMethodPrefix = false; + isInObjCReturnType = false; + isInObjCParam = false; isInObjCInterface = false; isInObjCSelector = false; isInEnum = false; isInExternC = false; elseHeaderFollowsComments = false; - nonInStatementBracket = 0; + returnTypeChecked = false; + nonInStatementBrace = 0; while (!questionMarkStack->empty()) questionMarkStack->pop_back(); } @@ -7382,23 +7957,21 @@ bool isFirstLine = true; bool haveFirstColon = false; bool foundMethodColon = false; - bool needReset = false; bool isInComment_ = false; bool isInQuote_ = false; + bool haveTernary = false; char quoteChar_ = ' '; int sqBracketCount = 0; int colonAdjust = 0; int colonAlign = 0; string nextLine_ = currentLine; + ASPeekStream stream(sourceIterator); // peek next line while (sourceIterator->hasMoreLines() || isFirstLine) { if (!isFirstLine) - { - nextLine_ = sourceIterator->peekNextLine(); - needReset = true; - } + nextLine_ = stream.peekNextLine(); // parse the line haveFirstColon = false; nextLine_ = ASBeautifier::trim(nextLine_); @@ -7448,7 +8021,7 @@ if (nextLine_[i] == ']') { --sqBracketCount; - if (!sqBracketCount) + if (sqBracketCount == 0) goto EndOfWhileLoop; // end of method call } if (nextLine_[i] == '[') @@ -7459,9 +8032,19 @@ continue; if (haveFirstColon) // multiple colons per line continue; + if (nextLine_[i] == '?') + { + haveTernary = true; + continue; + } // compute colon adjustment if (nextLine_[i] == ':') { + if (haveTernary) + { + haveTernary = false; + continue; + } haveFirstColon = true; foundMethodColon = true; if (shouldPadMethodColon) @@ -7487,8 +8070,6 @@ EndOfWhileLoop: if (!foundMethodColon) colonAlign = -1; - if (needReset) - sourceIterator->peekReset(); return colonAlign; } @@ -7518,15 +8099,19 @@ formattedLine.erase(i); --commentAdjust; } - appendSpacePad(); + if (formattedLine.length() > 0) + { + appendSpacePad(); + formattedLine.back() = ' '; // convert any tab to space + } } if (objCColonPadMode == COLON_PAD_NONE || objCColonPadMode == COLON_PAD_BEFORE || nextChar == ')') { // remove spaces after - int nextText = currentLine.find_first_not_of(" \t", charNum + 1); - if (nextText == (int)string::npos) + size_t nextText = currentLine.find_first_not_of(" \t", charNum + 1); + if (nextText == string::npos) nextText = currentLine.length(); int spaces = nextText - charNum - 1; if (spaces > 0) @@ -7539,8 +8124,8 @@ else { // pad space after - int nextText = currentLine.find_first_not_of(" \t", charNum + 1); - if (nextText == (int)string::npos) + size_t nextText = currentLine.find_first_not_of(" \t", charNum + 1); + if (nextText == string::npos) nextText = currentLine.length(); int spaces = nextText - charNum - 1; if (spaces == 0) @@ -7552,6 +8137,7 @@ { // do not use goForward here currentLine.erase(charNum + 1, spaces - 1); + currentLine[charNum + 1] = ' '; // convert any tab to space spacePadNum -= spaces - 1; } } diff --git a/plugins/astyle/3rdparty/libastyle/ASLocalizer.h b/plugins/astyle/3rdparty/libastyle/ASLocalizer.h --- a/plugins/astyle/3rdparty/libastyle/ASLocalizer.h +++ b/plugins/astyle/3rdparty/libastyle/ASLocalizer.h @@ -1,15 +1,22 @@ // ASLocalizer.h -// Copyright (c) 2016 by Jim Pattee . +// Copyright (c) 2018 by Jim Pattee . // This code is licensed under the MIT License. -// License.txt describes the conditions under which this software may be distributed. +// License.md describes the conditions under which this software may be distributed. #ifndef ASLOCALIZER_H #define ASLOCALIZER_H #include #include +// library builds do not need ASLocalizer +#ifdef ASTYLE_JNI + #ifndef ASTYLE_LIB // ASTYLE_LIB must be defined for ASTYLE_JNI + #define ASTYLE_LIB + #endif +#endif // ASTYLE_JNI + namespace astyle { using namespace std; @@ -63,6 +70,7 @@ Translation() {} virtual ~Translation() {} string convertToMultiByte(const wstring& wideStr) const; + string getTranslationString(size_t i) const; size_t getTranslationVectorSize() const; bool getWideTranslation(const string& stringIn, wstring& wideOut) const; string& translate(const string& stringIn) const; diff --git a/plugins/astyle/3rdparty/libastyle/ASLocalizer.cpp b/plugins/astyle/3rdparty/libastyle/ASLocalizer.cpp --- a/plugins/astyle/3rdparty/libastyle/ASLocalizer.cpp +++ b/plugins/astyle/3rdparty/libastyle/ASLocalizer.cpp @@ -1,7 +1,7 @@ // ASLocalizer.cpp -// Copyright (c) 2016 by Jim Pattee . +// Copyright (c) 2018 by Jim Pattee . // This code is licensed under the MIT License. -// License.txt describes the conditions under which this software may be distributed. +// License.md describes the conditions under which this software may be distributed. // // File encoding for this file is UTF-8 WITHOUT a byte order mark (BOM). // русский 中文(简体) 日本語 한국의 @@ -43,12 +43,6 @@ #include #endif -#ifdef __DMC__ - // digital mars doesn't have these - const size_t SUBLANG_CHINESE_MACAU = 5; - const size_t LANG_HINDI = 57; -#endif - #ifdef __VMS #define __USE_STD_IOSTREAM 1 #include @@ -96,11 +90,11 @@ m_langID = "en"; m_lcid = 0; m_subLangID.clear(); - m_translation = NULL; + m_translation = nullptr; // Not all compilers support the C++ function locale::global(locale("")); char* localeName = setlocale(LC_ALL, ""); - if (localeName == NULL) // use the english (ascii) defaults + if (localeName == nullptr) // use the english (ascii) defaults { fprintf(stderr, "\n%s\n\n", "Cannot set native locale, reverting to English"); setTranslationClass(); @@ -189,7 +183,7 @@ setTranslationClass(); } -#endif // _win32 +#endif // _WIN32 string ASLocalizer::getLanguageID() const // Returns the language ID in m_langID. @@ -256,10 +250,10 @@ { assert(m_langID.length()); // delete previously set (--ascii option) - if (m_translation) + if (m_translation != nullptr) { delete m_translation; - m_translation = NULL; + m_translation = nullptr; } if (m_langID == "bg") m_translation = new Bulgarian; @@ -319,16 +313,16 @@ // Add a string pair to the translation vector. { pair entry(english, translated); - m_translation.push_back(entry); + m_translation.emplace_back(entry); } string Translation::convertToMultiByte(const wstring& wideStr) const // Convert wchar_t to a multibyte string using the currently assigned locale. // Return an empty string if an error occurs. { static bool msgDisplayed = false; - // get length of the output excluding the NULL and validate the parameters - size_t mbLen = wcstombs(NULL, wideStr.c_str(), 0); + // get length of the output excluding the nullptr and validate the parameters + size_t mbLen = wcstombs(nullptr, wideStr.c_str(), 0); if (mbLen == string::npos) { if (!msgDisplayed) @@ -340,7 +334,7 @@ } // convert the characters char* mbStr = new (nothrow) char[mbLen + 1]; - if (mbStr == NULL) + if (mbStr == nullptr) { if (!msgDisplayed) { @@ -356,6 +350,14 @@ return mbTranslation; } +string Translation::getTranslationString(size_t i) const +// Return the translation ascii value. Used for testing. +{ + if (i >= m_translation.size()) + return string(); + return m_translation[i].first; +} + size_t Translation::getTranslationVectorSize() const // Return the translation vector size. Used for testing. { @@ -409,18 +411,21 @@ addPair("Formatted %s\n", L"Форматиран %s\n"); // should align with unchanged addPair("Unchanged %s\n", L"Непроменен %s\n"); // should align with formatted addPair("Directory %s\n", L"директория %s\n"); + addPair("Default option file %s\n", L"Файл с опции по подразбиране %s\n"); + addPair("Project option file %s\n", L"Файл с опции за проекта %s\n"); addPair("Exclude %s\n", L"Изключвам %s\n"); addPair("Exclude (unmatched) %s\n", L"Изключване (несравнимо) %s\n"); addPair(" %s formatted %s unchanged ", L" %s форматиран %s hепроменен "); addPair(" seconds ", L" секунди "); addPair("%d min %d sec ", L"%d мин %d сек "); addPair("%s lines\n", L"%s линии\n"); - addPair("Using default options file %s\n", L"Използване на файла възможности по подразбиране %s\n"); addPair("Opening HTML documentation %s\n", L"Откриване HTML документация %s\n"); - addPair("Invalid option file options:", L"Невалидни опции опция файлове:"); + addPair("Invalid default options:", L"Невалидни опции по подразбиране:"); + addPair("Invalid project options:", L"Невалидни опции за проекти:"); addPair("Invalid command line options:", L"Невалидни опции за командния ред:"); addPair("For help on options type 'astyle -h'", L"За помощ относно възможностите тип 'astyle -h'"); - addPair("Cannot open options file", L"Не може да се отвори файл опции"); + addPair("Cannot open default option file", L"Не може да се отвори файлът с опции по подразбиране"); + addPair("Cannot open project option file", L"Не може да се отвори файла с опции за проекта"); addPair("Cannot open directory", L"Не може да се отвори директория"); addPair("Cannot open HTML file %s\n", L"Не може да се отвори HTML файл %s\n"); addPair("Command execute failure", L"Command изпълни недостатъчност"); @@ -431,27 +436,30 @@ addPair("No file to process %s\n", L"Не файл за обработка %s\n"); addPair("Did you intend to use --recursive", L"Знаете ли възнамерявате да използвате --recursive"); addPair("Cannot process UTF-32 encoding", L"Не може да са UTF-32 кодиране"); - addPair("\nArtistic Style has terminated", L"\nArtistic Style е прекратено"); + addPair("Artistic Style has terminated\n", L"Artistic Style е прекратено\n"); } ChineseSimplified::ChineseSimplified() // 中文(简体) // build the translation vector in the Translation base class { addPair("Formatted %s\n", L"格式化 %s\n"); // should align with unchanged addPair("Unchanged %s\n", L"未改变 %s\n"); // should align with formatted addPair("Directory %s\n", L"目录 %s\n"); + addPair("Default option file %s\n", L"默认选项文件 %s\n"); + addPair("Project option file %s\n", L"项目选项文件 %s\n"); addPair("Exclude %s\n", L"排除 %s\n"); addPair("Exclude (unmatched) %s\n", L"排除(无匹配项) %s\n"); addPair(" %s formatted %s unchanged ", L" %s 格式化 %s 未改变 "); addPair(" seconds ", L" 秒 "); addPair("%d min %d sec ", L"%d 分 %d 秒 "); addPair("%s lines\n", L"%s 行\n"); - addPair("Using default options file %s\n", L"使用默认配置文件 %s\n"); addPair("Opening HTML documentation %s\n", L"打开HTML文档 %s\n"); - addPair("Invalid option file options:", L"无效的配置文件选项:"); + addPair("Invalid default options:", L"默认选项无效:"); + addPair("Invalid project options:", L"项目选项无效:"); addPair("Invalid command line options:", L"无效的命令行选项:"); addPair("For help on options type 'astyle -h'", L"输入 'astyle -h' 以获得有关命令行的帮助"); - addPair("Cannot open options file", L"无法打开配置文件"); + addPair("Cannot open default option file", L"无法打开默认选项文件"); + addPair("Cannot open project option file", L"无法打开项目选项文件"); addPair("Cannot open directory", L"无法打开目录"); addPair("Cannot open HTML file %s\n", L"无法打开HTML文件 %s\n"); addPair("Command execute failure", L"执行命令失败"); @@ -462,27 +470,30 @@ addPair("No file to process %s\n", L"没有文件可处理 %s\n"); addPair("Did you intend to use --recursive", L"你打算使用 --recursive"); addPair("Cannot process UTF-32 encoding", L"不能处理UTF-32编码"); - addPair("\nArtistic Style has terminated", L"\nArtistic Style 已经终止运行"); + addPair("Artistic Style has terminated\n", L"Artistic Style 已经终止运行\n"); } ChineseTraditional::ChineseTraditional() // 中文(繁體) // build the translation vector in the Translation base class { addPair("Formatted %s\n", L"格式化 %s\n"); // should align with unchanged addPair("Unchanged %s\n", L"未改變 %s\n"); // should align with formatted addPair("Directory %s\n", L"目錄 %s\n"); + addPair("Default option file %s\n", L"默認選項文件 %s\n"); + addPair("Project option file %s\n", L"項目選項文件 %s\n"); addPair("Exclude %s\n", L"排除 %s\n"); addPair("Exclude (unmatched) %s\n", L"排除(無匹配項) %s\n"); addPair(" %s formatted %s unchanged ", L" %s 格式化 %s 未改變 "); addPair(" seconds ", L" 秒 "); addPair("%d min %d sec ", L"%d 分 %d 秒 "); addPair("%s lines\n", L"%s 行\n"); - addPair("Using default options file %s\n", L"使用默認配置文件 %s\n"); addPair("Opening HTML documentation %s\n", L"打開HTML文檔 %s\n"); - addPair("Invalid option file options:", L"無效的配置文件選項:"); + addPair("Invalid default options:", L"默認選項無效:"); + addPair("Invalid project options:", L"項目選項無效:"); addPair("Invalid command line options:", L"無效的命令行選項:"); addPair("For help on options type 'astyle -h'", L"輸入'astyle -h'以獲得有關命令行的幫助:"); - addPair("Cannot open options file", L"無法打開配置文件"); + addPair("Cannot open default option file", L"無法打開默認選項文件"); + addPair("Cannot open project option file", L"無法打開項目選項文件"); addPair("Cannot open directory", L"無法打開目錄"); addPair("Cannot open HTML file %s\n", L"無法打開HTML文件 %s\n"); addPair("Command execute failure", L"執行命令失敗"); @@ -493,27 +504,30 @@ addPair("No file to process %s\n", L"沒有文件可處理 %s\n"); addPair("Did you intend to use --recursive", L"你打算使用 --recursive"); addPair("Cannot process UTF-32 encoding", L"不能處理UTF-32編碼"); - addPair("\nArtistic Style has terminated", L"\nArtistic Style 已經終止運行"); + addPair("Artistic Style has terminated\n", L"Artistic Style 已經終止運行\n"); } Dutch::Dutch() // Nederlandse // build the translation vector in the Translation base class { addPair("Formatted %s\n", L"Geformatteerd %s\n"); // should align with unchanged addPair("Unchanged %s\n", L"Onveranderd %s\n"); // should align with formatted addPair("Directory %s\n", L"Directory %s\n"); + addPair("Default option file %s\n", L"Standaard optie bestand %s\n"); + addPair("Project option file %s\n", L"Project optie bestand %s\n"); addPair("Exclude %s\n", L"Uitsluiten %s\n"); addPair("Exclude (unmatched) %s\n", L"Uitgesloten (ongeëvenaarde) %s\n"); addPair(" %s formatted %s unchanged ", L" %s geformatteerd %s onveranderd "); addPair(" seconds ", L" seconden "); addPair("%d min %d sec ", L"%d min %d sec "); addPair("%s lines\n", L"%s lijnen\n"); - addPair("Using default options file %s\n", L"Met behulp van standaard opties bestand %s\n"); addPair("Opening HTML documentation %s\n", L"Het openen van HTML-documentatie %s\n"); - addPair("Invalid option file options:", L"Ongeldige optie file opties:"); + addPair("Invalid default options:", L"Ongeldige standaardopties:"); + addPair("Invalid project options:", L"Ongeldige projectopties:"); addPair("Invalid command line options:", L"Ongeldige command line opties:"); addPair("For help on options type 'astyle -h'", L"Voor hulp bij 'astyle-h' opties het type"); - addPair("Cannot open options file", L"Kan niet worden geopend options bestand"); + addPair("Cannot open default option file", L"Kan het standaardoptiesbestand niet openen"); + addPair("Cannot open project option file", L"Kan het project optie bestand niet openen"); addPair("Cannot open directory", L"Kan niet open directory"); addPair("Cannot open HTML file %s\n", L"Kan HTML-bestand niet openen %s\n"); addPair("Command execute failure", L"Voeren commando falen"); @@ -524,7 +538,7 @@ addPair("No file to process %s\n", L"Geen bestand te verwerken %s\n"); addPair("Did you intend to use --recursive", L"Hebt u van plan bent te gebruiken --recursive"); addPair("Cannot process UTF-32 encoding", L"Kan niet verwerken UTF-32 codering"); - addPair("\nArtistic Style has terminated", L"\nArtistic Style heeft beëindigd"); + addPair("Artistic Style has terminated\n", L"Artistic Style heeft beëindigd\n"); } English::English() @@ -537,18 +551,21 @@ addPair("Formatted %s\n", L"Formaadis %s\n"); // should align with unchanged addPair("Unchanged %s\n", L"Muutumatu %s\n"); // should align with formatted addPair("Directory %s\n", L"Kataloog %s\n"); + addPair("Default option file %s\n", L"Vaikefunktsioonifail %s\n"); + addPair("Project option file %s\n", L"Projekti valiku fail %s\n"); addPair("Exclude %s\n", L"Välista %s\n"); addPair("Exclude (unmatched) %s\n", L"Välista (tasakaalustamata) %s\n"); addPair(" %s formatted %s unchanged ", L" %s formaadis %s muutumatu "); addPair(" seconds ", L" sekundit "); addPair("%d min %d sec ", L"%d min %d sek "); addPair("%s lines\n", L"%s read\n"); - addPair("Using default options file %s\n", L"Kasutades selliseid vaikimisi valikuid faili %s\n"); addPair("Opening HTML documentation %s\n", L"Avamine HTML dokumentatsioon %s\n"); - addPair("Invalid option file options:", L"Vale valik faili võimalusi:"); + addPair("Invalid default options:", L"Vaikevalikud on sobimatud:"); + addPair("Invalid project options:", L"Projekti valikud on sobimatud:"); addPair("Invalid command line options:", L"Vale käsureavõtmetega:"); addPair("For help on options type 'astyle -h'", L"Abiks võimaluste tüüp 'astyle -h'"); - addPair("Cannot open options file", L"Ei saa avada võimalusi faili"); + addPair("Cannot open default option file", L"Vaikimisi valitud faili ei saa avada"); + addPair("Cannot open project option file", L"Projektivaliku faili ei saa avada"); addPair("Cannot open directory", L"Ei saa avada kataloogi"); addPair("Cannot open HTML file %s\n", L"Ei saa avada HTML-faili %s\n"); addPair("Command execute failure", L"Käsk täita rike"); @@ -559,27 +576,30 @@ addPair("No file to process %s\n", L"No faili töötlema %s\n"); addPair("Did you intend to use --recursive", L"Kas te kavatsete kasutada --recursive"); addPair("Cannot process UTF-32 encoding", L"Ei saa töödelda UTF-32 kodeeringus"); - addPair("\nArtistic Style has terminated", L"\nArtistic Style on lõpetatud"); + addPair("Artistic Style has terminated\n", L"Artistic Style on lõpetatud\n"); } Finnish::Finnish() // Suomeksi // build the translation vector in the Translation base class { addPair("Formatted %s\n", L"Muotoiltu %s\n"); // should align with unchanged addPair("Unchanged %s\n", L"Ennallaan %s\n"); // should align with formatted addPair("Directory %s\n", L"Directory %s\n"); + addPair("Default option file %s\n", L"Oletusasetustiedosto %s\n"); + addPair("Project option file %s\n", L"Projektin valintatiedosto %s\n"); addPair("Exclude %s\n", L"Sulkea %s\n"); addPair("Exclude (unmatched) %s\n", L"Sulkea (verraton) %s\n"); addPair(" %s formatted %s unchanged ", L" %s muotoiltu %s ennallaan "); addPair(" seconds ", L" sekuntia "); addPair("%d min %d sec ", L"%d min %d sek "); addPair("%s lines\n", L"%s linjat\n"); - addPair("Using default options file %s\n", L"Käyttämällä oletusasetuksia tiedosto %s\n"); addPair("Opening HTML documentation %s\n", L"Avaaminen HTML asiakirjat %s\n"); - addPair("Invalid option file options:", L"Virheellinen vaihtoehto tiedosto vaihtoehtoja:"); + addPair("Invalid default options:", L"Virheelliset oletusasetukset:"); + addPair("Invalid project options:", L"Virheelliset hankevalinnat:"); addPair("Invalid command line options:", L"Virheellinen komentorivin:"); addPair("For help on options type 'astyle -h'", L"Apua vaihtoehdoista tyyppi 'astyle -h'"); - addPair("Cannot open options file", L"Ei voi avata vaihtoehtoja tiedostoa"); + addPair("Cannot open default option file", L"Et voi avata oletusasetustiedostoa"); + addPair("Cannot open project option file", L"Projektin asetustiedostoa ei voi avata"); addPair("Cannot open directory", L"Ei Open Directory"); addPair("Cannot open HTML file %s\n", L"Ei voi avata HTML-tiedoston %s\n"); addPair("Command execute failure", L"Suorita komento vika"); @@ -590,27 +610,30 @@ addPair("No file to process %s\n", L"Ei tiedostoa käsitellä %s\n"); addPair("Did you intend to use --recursive", L"Oliko aiot käyttää --recursive"); addPair("Cannot process UTF-32 encoding", L"Ei voi käsitellä UTF-32 koodausta"); - addPair("\nArtistic Style has terminated", L"\nArtistic Style on päättynyt"); + addPair("Artistic Style has terminated\n", L"Artistic Style on päättynyt\n"); } French::French() // Française // build the translation vector in the Translation base class { addPair("Formatted %s\n", L"Formaté %s\n"); // should align with unchanged addPair("Unchanged %s\n", L"Inchangée %s\n"); // should align with formatted addPair("Directory %s\n", L"Répertoire %s\n"); + addPair("Default option file %s\n", L"Fichier d'option par défaut %s\n"); + addPair("Project option file %s\n", L"Fichier d'option de projet %s\n"); addPair("Exclude %s\n", L"Exclure %s\n"); addPair("Exclude (unmatched) %s\n", L"Exclure (non appariés) %s\n"); addPair(" %s formatted %s unchanged ", L" %s formaté %s inchangée "); addPair(" seconds ", L" seconde "); addPair("%d min %d sec ", L"%d min %d sec "); addPair("%s lines\n", L"%s lignes\n"); - addPair("Using default options file %s\n", L"Options par défaut utilisation du fichier %s\n"); addPair("Opening HTML documentation %s\n", L"Ouverture documentation HTML %s\n"); - addPair("Invalid option file options:", L"Options Blancs option du fichier:"); + addPair("Invalid default options:", L"Options par défaut invalides:"); + addPair("Invalid project options:", L"Options de projet non valides:"); addPair("Invalid command line options:", L"Blancs options ligne de commande:"); addPair("For help on options type 'astyle -h'", L"Pour de l'aide sur les options tapez 'astyle -h'"); - addPair("Cannot open options file", L"Impossible d'ouvrir le fichier d'options"); + addPair("Cannot open default option file", L"Impossible d'ouvrir le fichier d'option par défaut"); + addPair("Cannot open project option file", L"Impossible d'ouvrir le fichier d'option de projet"); addPair("Cannot open directory", L"Impossible d'ouvrir le répertoire"); addPair("Cannot open HTML file %s\n", L"Impossible d'ouvrir le fichier HTML %s\n"); addPair("Command execute failure", L"Exécuter échec de la commande"); @@ -621,27 +644,30 @@ addPair("No file to process %s\n", L"Aucun fichier à traiter %s\n"); addPair("Did you intend to use --recursive", L"Avez-vous l'intention d'utiliser --recursive"); addPair("Cannot process UTF-32 encoding", L"Impossible de traiter codage UTF-32"); - addPair("\nArtistic Style has terminated", L"\nArtistic Style a mis fin"); + addPair("Artistic Style has terminated\n", L"Artistic Style a mis fin\n"); } German::German() // Deutsch // build the translation vector in the Translation base class { addPair("Formatted %s\n", L"Formatiert %s\n"); // should align with unchanged addPair("Unchanged %s\n", L"Unverändert %s\n"); // should align with formatted addPair("Directory %s\n", L"Verzeichnis %s\n"); + addPair("Default option file %s\n", L"Standard-Optionsdatei %s\n"); + addPair("Project option file %s\n", L"Projektoptionsdatei %s\n"); addPair("Exclude %s\n", L"Ausschließen %s\n"); addPair("Exclude (unmatched) %s\n", L"Ausschließen (unerreichte) %s\n"); addPair(" %s formatted %s unchanged ", L" %s formatiert %s unverändert "); addPair(" seconds ", L" sekunden "); addPair("%d min %d sec ", L"%d min %d sek "); addPair("%s lines\n", L"%s linien\n"); - addPair("Using default options file %s\n", L"Mit Standard-Optionen Dat %s\n"); addPair("Opening HTML documentation %s\n", L"Öffnen HTML-Dokumentation %s\n"); - addPair("Invalid option file options:", L"Ungültige Option Datei-Optionen:"); + addPair("Invalid default options:", L"Ungültige Standardoptionen:"); + addPair("Invalid project options:", L"Ungültige Projektoptionen:"); addPair("Invalid command line options:", L"Ungültige Kommandozeilen-Optionen:"); addPair("For help on options type 'astyle -h'", L"Für Hilfe zu den Optionen geben Sie 'astyle -h'"); - addPair("Cannot open options file", L"Kann nicht geöffnet werden Optionsdatei"); + addPair("Cannot open default option file", L"Die Standardoptionsdatei kann nicht geöffnet werden"); + addPair("Cannot open project option file", L"Die Projektoptionsdatei kann nicht geöffnet werden"); addPair("Cannot open directory", L"Kann nicht geöffnet werden Verzeichnis"); addPair("Cannot open HTML file %s\n", L"Kann nicht öffnen HTML-Datei %s\n"); addPair("Command execute failure", L"Execute Befehl Scheitern"); @@ -652,27 +678,30 @@ addPair("No file to process %s\n", L"Keine Datei zu verarbeiten %s\n"); addPair("Did you intend to use --recursive", L"Haben Sie verwenden möchten --recursive"); addPair("Cannot process UTF-32 encoding", L"Nicht verarbeiten kann UTF-32 Codierung"); - addPair("\nArtistic Style has terminated", L"\nArtistic Style ist beendet"); + addPair("Artistic Style has terminated\n", L"Artistic Style ist beendet\n"); } Greek::Greek() // ελληνικά // build the translation vector in the Translation base class { addPair("Formatted %s\n", L"Διαμορφωμένη %s\n"); // should align with unchanged addPair("Unchanged %s\n", L"Αμετάβλητος %s\n"); // should align with formatted addPair("Directory %s\n", L"Κατάλογος %s\n"); + addPair("Default option file %s\n", L"Προεπιλεγμένο αρχείο επιλογών %s\n"); + addPair("Project option file %s\n", L"Αρχείο επιλογής έργου %s\n"); addPair("Exclude %s\n", L"Αποκλείω %s\n"); addPair("Exclude (unmatched) %s\n", L"Ausschließen (unerreichte) %s\n"); addPair(" %s formatted %s unchanged ", L" %s σχηματοποιημένη %s αμετάβλητες "); addPair(" seconds ", L" δευτερόλεπτα "); addPair("%d min %d sec ", L"%d λεπ %d δευ "); addPair("%s lines\n", L"%s γραμμές\n"); - addPair("Using default options file %s\n", L"Χρησιμοποιώντας το αρχείο προεπιλεγμένες επιλογές %s\n"); addPair("Opening HTML documentation %s\n", L"Εγκαίνια έγγραφα HTML %s\n"); - addPair("Invalid option file options:", L"Μη έγκυρες επιλογές αρχείου επιλογή:"); + addPair("Invalid default options:", L"Μη έγκυρες επιλογές προεπιλογής:"); + addPair("Invalid project options:", L"Μη έγκυρες επιλογές έργου:"); addPair("Invalid command line options:", L"Μη έγκυρη επιλογές γραμμής εντολών:"); addPair("For help on options type 'astyle -h'", L"Για βοήθεια σχετικά με το είδος επιλογές 'astyle -h'"); - addPair("Cannot open options file", L"Δεν μπορείτε να ανοίξετε το αρχείο επιλογών"); + addPair("Cannot open default option file", L"Δεν είναι δυνατό να ανοίξει το προεπιλεγμένο αρχείο επιλογών"); + addPair("Cannot open project option file", L"Δεν είναι δυνατό να ανοίξει το αρχείο επιλογής έργου"); addPair("Cannot open directory", L"Δεν μπορείτε να ανοίξετε τον κατάλογο"); addPair("Cannot open HTML file %s\n", L"Δεν μπορείτε να ανοίξετε το αρχείο HTML %s\n"); addPair("Command execute failure", L"Εντολή να εκτελέσει την αποτυχία"); @@ -683,7 +712,7 @@ addPair("No file to process %s\n", L"Δεν υπάρχει αρχείο για την επεξεργασία %s\n"); addPair("Did you intend to use --recursive", L"Μήπως σκοπεύετε να χρησιμοποιήσετε --recursive"); addPair("Cannot process UTF-32 encoding", L"δεν μπορεί να επεξεργαστεί UTF-32 κωδικοποίηση"); - addPair("\nArtistic Style has terminated", L"\nArtistic Style έχει λήξει"); + addPair("Artistic Style has terminated\n", L"Artistic Style έχει λήξει\n"); } Hindi::Hindi() // हिन्दी @@ -694,18 +723,21 @@ addPair("Formatted %s\n", L"स्वरूपित किया %s\n"); // should align with unchanged addPair("Unchanged %s\n", L"अपरिवर्तित %s\n"); // should align with formatted addPair("Directory %s\n", L"निर्देशिका %s\n"); + addPair("Default option file %s\n", L"डिफ़ॉल्ट विकल्प फ़ाइल %s\n"); + addPair("Project option file %s\n", L"प्रोजेक्ट विकल्प फ़ाइल %s\n"); addPair("Exclude %s\n", L"निकालना %s\n"); addPair("Exclude (unmatched) %s\n", L"अपवर्जित (बेजोड़) %s\n"); addPair(" %s formatted %s unchanged ", L" %s स्वरूपित किया %s अपरिवर्तित "); addPair(" seconds ", L" सेकंड "); addPair("%d min %d sec ", L"%d मिनट %d सेकंड "); addPair("%s lines\n", L"%s लाइनों\n"); - addPair("Using default options file %s\n", L"डिफ़ॉल्ट विकल्प का उपयोग कर फ़ाइल %s\n"); addPair("Opening HTML documentation %s\n", L"एचटीएमएल प्रलेखन खोलना %s\n"); - addPair("Invalid option file options:", L"अवैध विकल्प फ़ाइल विकल्प हैं:"); + addPair("Invalid default options:", L"अमान्य डिफ़ॉल्ट विकल्प:"); + addPair("Invalid project options:", L"अमान्य प्रोजेक्ट विकल्प:"); addPair("Invalid command line options:", L"कमांड लाइन विकल्प अवैध:"); addPair("For help on options type 'astyle -h'", L"विकल्पों पर मदद के लिए प्रकार 'astyle -h'"); - addPair("Cannot open options file", L"विकल्प फ़ाइल नहीं खोल सकता है"); + addPair("Cannot open default option file", L"डिफ़ॉल्ट विकल्प फ़ाइल नहीं खोल सकता"); + addPair("Cannot open project option file", L"परियोजना विकल्प फ़ाइल नहीं खोल सकता"); addPair("Cannot open directory", L"निर्देशिका नहीं खोल सकता"); addPair("Cannot open HTML file %s\n", L"HTML फ़ाइल नहीं खोल सकता %s\n"); addPair("Command execute failure", L"आदेश विफलता निष्पादित"); @@ -716,27 +748,30 @@ addPair("No file to process %s\n", L"कोई फ़ाइल %s प्रक्रिया के लिए\n"); addPair("Did you intend to use --recursive", L"क्या आप उपयोग करना चाहते हैं --recursive"); addPair("Cannot process UTF-32 encoding", L"UTF-32 कूटबन्धन प्रक्रिया नहीं कर सकते"); - addPair("\nArtistic Style has terminated", L"\nArtistic Style समाप्त किया है"); + addPair("Artistic Style has terminated\n", L"Artistic Style समाप्त किया है\n"); } Hungarian::Hungarian() // Magyar // build the translation vector in the Translation base class { addPair("Formatted %s\n", L"Formázott %s\n"); // should align with unchanged addPair("Unchanged %s\n", L"Változatlan %s\n"); // should align with formatted addPair("Directory %s\n", L"Címjegyzék %s\n"); + addPair("Default option file %s\n", L"Alapértelmezett beállítási fájl %s\n"); + addPair("Project option file %s\n", L"Projekt opciófájl %s\n"); addPair("Exclude %s\n", L"Kizár %s\n"); addPair("Exclude (unmatched) %s\n", L"Escludere (senza pari) %s\n"); addPair(" %s formatted %s unchanged ", L" %s formázott %s változatlan "); addPair(" seconds ", L" másodperc "); addPair("%d min %d sec ", L"%d jeg %d más "); addPair("%s lines\n", L"%s vonalak\n"); - addPair("Using default options file %s\n", L"Az alapértelmezett beállítások fájl %s\n"); addPair("Opening HTML documentation %s\n", L"Nyitó HTML dokumentáció %s\n"); - addPair("Invalid option file options:", L"Érvénytelen opció fájlbeállítást:"); + addPair("Invalid default options:", L"Érvénytelen alapértelmezett beállítások:"); + addPair("Invalid project options:", L"Érvénytelen projektbeállítások:"); addPair("Invalid command line options:", L"Érvénytelen parancssori opciók:"); addPair("For help on options type 'astyle -h'", L"Ha segítségre van lehetőség típus 'astyle-h'"); - addPair("Cannot open options file", L"Nem lehet megnyitni beállítási fájlban"); + addPair("Cannot open default option file", L"Nem lehet megnyitni az alapértelmezett beállítási fájlt"); + addPair("Cannot open project option file", L"Nem lehet megnyitni a projekt opció fájlt"); addPair("Cannot open directory", L"Nem lehet megnyitni könyvtár"); addPair("Cannot open HTML file %s\n", L"Nem lehet megnyitni a HTML fájlt %s\n"); addPair("Command execute failure", L"Command végre hiba"); @@ -747,27 +782,30 @@ addPair("No file to process %s\n", L"Nincs fájl feldolgozása %s\n"); addPair("Did you intend to use --recursive", L"Esetleg a használni kívánt --recursive"); addPair("Cannot process UTF-32 encoding", L"Nem tudja feldolgozni UTF-32 kódolással"); - addPair("\nArtistic Style has terminated", L"\nArtistic Style megszűnt"); + addPair("Artistic Style has terminated\n", L"Artistic Style megszűnt\n"); } Italian::Italian() // Italiano // build the translation vector in the Translation base class { addPair("Formatted %s\n", L"Formattata %s\n"); // should align with unchanged addPair("Unchanged %s\n", L"Immutato %s\n"); // should align with formatted addPair("Directory %s\n", L"Elenco %s\n"); + addPair("Default option file %s\n", L"File di opzione predefinito %s\n"); + addPair("Project option file %s\n", L"File di opzione del progetto %s\n"); addPair("Exclude %s\n", L"Escludere %s\n"); addPair("Exclude (unmatched) %s\n", L"Escludere (senza pari) %s\n"); addPair(" %s formatted %s unchanged ", L" %s ormattata %s immutato "); addPair(" seconds ", L" secondo "); addPair("%d min %d sec ", L"%d min %d seg "); addPair("%s lines\n", L"%s linee\n"); - addPair("Using default options file %s\n", L"Utilizzando file delle opzioni di default %s\n"); addPair("Opening HTML documentation %s\n", L"Apertura di documenti HTML %s\n"); - addPair("Invalid option file options:", L"Opzione non valida file delle opzioni:"); + addPair("Invalid default options:", L"Opzioni di default non valide:"); + addPair("Invalid project options:", L"Opzioni di progetto non valide:"); addPair("Invalid command line options:", L"Opzioni della riga di comando non valido:"); addPair("For help on options type 'astyle -h'", L"Per informazioni sulle opzioni di tipo 'astyle-h'"); - addPair("Cannot open options file", L"Impossibile aprire il file opzioni"); + addPair("Cannot open default option file", L"Impossibile aprire il file di opzione predefinito"); + addPair("Cannot open project option file", L"Impossibile aprire il file di opzione del progetto"); addPair("Cannot open directory", L"Impossibile aprire la directory"); addPair("Cannot open HTML file %s\n", L"Impossibile aprire il file HTML %s\n"); addPair("Command execute failure", L"Esegui fallimento comando"); @@ -778,27 +816,30 @@ addPair("No file to process %s\n", L"Nessun file al processo %s\n"); addPair("Did you intend to use --recursive", L"Hai intenzione di utilizzare --recursive"); addPair("Cannot process UTF-32 encoding", L"Non è possibile processo di codifica UTF-32"); - addPair("\nArtistic Style has terminated", L"\nArtistic Style ha terminato"); + addPair("Artistic Style has terminated\n", L"Artistic Style ha terminato\n"); } Japanese::Japanese() // 日本語 // build the translation vector in the Translation base class { addPair("Formatted %s\n", L"フォーマット済みの %s\n"); // should align with unchanged addPair("Unchanged %s\n", L"変わりません %s\n"); // should align with formatted addPair("Directory %s\n", L"ディレクトリ %s\n"); + addPair("Default option file %s\n", L"デフォルトオプションファイル %s\n"); + addPair("Project option file %s\n", L"プロジェクトオプションファイル %s\n"); addPair("Exclude %s\n", L"除外する %s\n"); addPair("Exclude (unmatched) %s\n", L"除外する(一致しません) %s\n"); addPair(" %s formatted %s unchanged ", L" %s フフォーマット済みの %s 変わりません "); addPair(" seconds ", L" 秒 "); addPair("%d min %d sec ", L"%d 分 %d 秒 "); addPair("%s lines\n", L"%s ライン\n"); - addPair("Using default options file %s\n", L"デフォルトのオプションファイルを使用して、 %s\n"); addPair("Opening HTML documentation %s\n", L"オープニングHTMLドキュメント %s\n"); - addPair("Invalid option file options:", L"無効なオプションファイルのオプション:"); + addPair("Invalid default options:", L"無効なデフォルトオプション:"); + addPair("Invalid project options:", L"無効なプロジェクトオプション:"); addPair("Invalid command line options:", L"無効なコマンドラインオプション:"); addPair("For help on options type 'astyle -h'", L"コオプションの種類のヘルプについて'astyle- h'を入力してください"); - addPair("Cannot open options file", L"オプションファイルを開くことができません"); + addPair("Cannot open default option file", L"デフォルトのオプションファイルを開くことができません"); + addPair("Cannot open project option file", L"プロジェクトオプションファイルを開くことができません"); addPair("Cannot open directory", L"ディレクトリを開くことができません。"); addPair("Cannot open HTML file %s\n", L"HTMLファイルを開くことができません %s\n"); addPair("Command execute failure", L"コマンドが失敗を実行します"); @@ -809,27 +850,30 @@ addPair("No file to process %s\n", L"いいえファイルは処理しないように %s\n"); addPair("Did you intend to use --recursive", L"あなたは--recursive使用するつもりでした"); addPair("Cannot process UTF-32 encoding", L"UTF - 32エンコーディングを処理できません"); - addPair("\nArtistic Style has terminated", L"\nArtistic Style 終了しました"); + addPair("Artistic Style has terminated\n", L"Artistic Style 終了しました\n"); } Korean::Korean() // 한국의 // build the translation vector in the Translation base class { addPair("Formatted %s\n", L"수정됨 %s\n"); // should align with unchanged addPair("Unchanged %s\n", L"변경없음 %s\n"); // should align with formatted addPair("Directory %s\n", L"디렉토리 %s\n"); + addPair("Default option file %s\n", L"기본 옵션 파일 %s\n"); + addPair("Project option file %s\n", L"프로젝트 옵션 파일 %s\n"); addPair("Exclude %s\n", L"제외됨 %s\n"); addPair("Exclude (unmatched) %s\n", L"제외 (NO 일치) %s\n"); addPair(" %s formatted %s unchanged ", L" %s 수정됨 %s 변경없음 "); addPair(" seconds ", L" 초 "); addPair("%d min %d sec ", L"%d 분 %d 초 "); addPair("%s lines\n", L"%s 라인\n"); - addPair("Using default options file %s\n", L"기본 구성 파일을 사용 %s\n"); addPair("Opening HTML documentation %s\n", L"HTML 문서를 열기 %s\n"); - addPair("Invalid option file options:", L"잘못된 구성 파일 옵션 :"); + addPair("Invalid default options:", L"잘못된 기본 옵션:"); + addPair("Invalid project options:", L"잘못된 프로젝트 옵션:"); addPair("Invalid command line options:", L"잘못된 명령줄 옵션 :"); addPair("For help on options type 'astyle -h'", L"도움말을 보려면 옵션 유형 'astyle - H'를 사용합니다"); - addPair("Cannot open options file", L"구성 파일을 열 수 없습니다"); + addPair("Cannot open default option file", L"기본 옵션 파일을 열 수 없습니다."); + addPair("Cannot open project option file", L"프로젝트 옵션 파일을 열 수 없습니다."); addPair("Cannot open directory", L"디렉토리를 열지 못했습니다"); addPair("Cannot open HTML file %s\n", L"HTML 파일을 열 수 없습니다 %s\n"); addPair("Command execute failure", L"명령 실패를 실행"); @@ -840,27 +884,30 @@ addPair("No file to process %s\n", L"처리할 파일이 없습니다 %s\n"); addPair("Did you intend to use --recursive", L"--recursive 를 사용하고자 하십니까"); addPair("Cannot process UTF-32 encoding", L"UTF-32 인코딩을 처리할 수 없습니다"); - addPair("\nArtistic Style has terminated", L"\nArtistic Style를 종료합니다"); + addPair("Artistic Style has terminated\n", L"Artistic Style를 종료합니다\n"); } Norwegian::Norwegian() // Norsk // build the translation vector in the Translation base class { addPair("Formatted %s\n", L"Formatert %s\n"); // should align with unchanged addPair("Unchanged %s\n", L"Uendret %s\n"); // should align with formatted addPair("Directory %s\n", L"Katalog %s\n"); + addPair("Default option file %s\n", L"Standard alternativfil %s\n"); + addPair("Project option file %s\n", L"Prosjekt opsjonsfil %s\n"); addPair("Exclude %s\n", L"Ekskluder %s\n"); addPair("Exclude (unmatched) %s\n", L"Ekskluder (uovertruffen) %s\n"); addPair(" %s formatted %s unchanged ", L" %s formatert %s uendret "); addPair(" seconds ", L" sekunder "); addPair("%d min %d sec ", L"%d min %d sek? "); addPair("%s lines\n", L"%s linjer\n"); - addPair("Using default options file %s\n", L"Ved hjelp av standardalternativer fil %s\n"); addPair("Opening HTML documentation %s\n", L"Åpning HTML dokumentasjon %s\n"); - addPair("Invalid option file options:", L"Ugyldige alternativ filalternativer:"); + addPair("Invalid default options:", L"Ugyldige standardalternativer:"); + addPair("Invalid project options:", L"Ugyldige prosjektalternativer:"); addPair("Invalid command line options:", L"Kommandolinjevalg Ugyldige:"); addPair("For help on options type 'astyle -h'", L"For hjelp til alternativer type 'astyle -h'"); - addPair("Cannot open options file", L"Kan ikke åpne alternativer fil"); + addPair("Cannot open default option file", L"Kan ikke åpne standardvalgsfilen"); + addPair("Cannot open project option file", L"Kan ikke åpne prosjektvalgsfilen"); addPair("Cannot open directory", L"Kan ikke åpne katalog"); addPair("Cannot open HTML file %s\n", L"Kan ikke åpne HTML-fil %s\n"); addPair("Command execute failure", L"Command utføre svikt"); @@ -871,27 +918,30 @@ addPair("No file to process %s\n", L"Ingen fil å behandle %s\n"); addPair("Did you intend to use --recursive", L"Har du tenkt å bruke --recursive"); addPair("Cannot process UTF-32 encoding", L"Kan ikke behandle UTF-32 koding"); - addPair("\nArtistic Style has terminated", L"\nArtistic Style har avsluttet"); + addPair("Artistic Style has terminated\n", L"Artistic Style har avsluttet\n"); } Polish::Polish() // Polski // build the translation vector in the Translation base class { addPair("Formatted %s\n", L"Sformatowany %s\n"); // should align with unchanged addPair("Unchanged %s\n", L"Niezmienione %s\n"); // should align with formatted addPair("Directory %s\n", L"Katalog %s\n"); + addPair("Default option file %s\n", L"Domyślny plik opcji %s\n"); + addPair("Project option file %s\n", L"Plik opcji projektu %s\n"); addPair("Exclude %s\n", L"Wykluczać %s\n"); addPair("Exclude (unmatched) %s\n", L"Wyklucz (niezrównany) %s\n"); addPair(" %s formatted %s unchanged ", L" %s sformatowany %s niezmienione "); addPair(" seconds ", L" sekund "); addPair("%d min %d sec ", L"%d min %d sek "); addPair("%s lines\n", L"%s linii\n"); - addPair("Using default options file %s\n", L"Korzystanie z domyślnej opcji %s plik\n"); addPair("Opening HTML documentation %s\n", L"Otwarcie dokumentacji HTML %s\n"); - addPair("Invalid option file options:", L"Nieprawidłowy opcji pliku opcji:"); + addPair("Invalid default options:", L"Nieprawidłowe opcje domyślne:"); + addPair("Invalid project options:", L"Nieprawidłowe opcje projektu:"); addPair("Invalid command line options:", L"Nieprawidłowe opcje wiersza polecenia:"); addPair("For help on options type 'astyle -h'", L"Aby uzyskać pomoc od rodzaju opcji 'astyle -h'"); - addPair("Cannot open options file", L"Nie można otworzyć pliku opcji"); + addPair("Cannot open default option file", L"Nie można otworzyć pliku opcji domyślnych"); + addPair("Cannot open project option file", L"Nie można otworzyć pliku opcji projektu"); addPair("Cannot open directory", L"Nie można otworzyć katalogu"); addPair("Cannot open HTML file %s\n", L"Nie można otworzyć pliku HTML %s\n"); addPair("Command execute failure", L"Wykonaj polecenia niepowodzenia"); @@ -902,27 +952,30 @@ addPair("No file to process %s\n", L"Brak pliku do procesu %s\n"); addPair("Did you intend to use --recursive", L"Czy masz zamiar używać --recursive"); addPair("Cannot process UTF-32 encoding", L"Nie można procesu kodowania UTF-32"); - addPair("\nArtistic Style has terminated", L"\nArtistic Style został zakończony"); + addPair("Artistic Style has terminated\n", L"Artistic Style został zakończony\n"); } Portuguese::Portuguese() // Português // build the translation vector in the Translation base class { addPair("Formatted %s\n", L"Formatado %s\n"); // should align with unchanged addPair("Unchanged %s\n", L"Inalterado %s\n"); // should align with formatted addPair("Directory %s\n", L"Diretório %s\n"); + addPair("Default option file %s\n", L"Arquivo de opção padrão %s\n"); + addPair("Project option file %s\n", L"Arquivo de opção de projeto %s\n"); addPair("Exclude %s\n", L"Excluir %s\n"); addPair("Exclude (unmatched) %s\n", L"Excluir (incomparável) %s\n"); addPair(" %s formatted %s unchanged ", L" %s formatado %s inalterado "); addPair(" seconds ", L" segundo "); addPair("%d min %d sec ", L"%d min %d seg "); addPair("%s lines\n", L"%s linhas\n"); - addPair("Using default options file %s\n", L"Usando o arquivo de opções padrão %s\n"); addPair("Opening HTML documentation %s\n", L"Abrindo a documentação HTML %s\n"); - addPair("Invalid option file options:", L"Opções de arquivo inválido opção:"); + addPair("Invalid default options:", L"Opções padrão inválidas:"); + addPair("Invalid project options:", L"Opções de projeto inválidas:"); addPair("Invalid command line options:", L"Opções de linha de comando inválida:"); addPair("For help on options type 'astyle -h'", L"Para obter ajuda sobre as opções de tipo 'astyle -h'"); - addPair("Cannot open options file", L"Não é possível abrir arquivo de opções"); + addPair("Cannot open default option file", L"Não é possível abrir o arquivo de opção padrão"); + addPair("Cannot open project option file", L"Não é possível abrir o arquivo de opção do projeto"); addPair("Cannot open directory", L"Não é possível abrir diretório"); addPair("Cannot open HTML file %s\n", L"Não é possível abrir arquivo HTML %s\n"); addPair("Command execute failure", L"Executar falha de comando"); @@ -933,27 +986,30 @@ addPair("No file to process %s\n", L"Nenhum arquivo para processar %s\n"); addPair("Did you intend to use --recursive", L"Será que você pretende usar --recursive"); addPair("Cannot process UTF-32 encoding", L"Não pode processar a codificação UTF-32"); - addPair("\nArtistic Style has terminated", L"\nArtistic Style terminou"); + addPair("Artistic Style has terminated\n", L"Artistic Style terminou\n"); } Romanian::Romanian() // Română // build the translation vector in the Translation base class { addPair("Formatted %s\n", L"Formatat %s\n"); // should align with unchanged addPair("Unchanged %s\n", L"Neschimbat %s\n"); // should align with formatted addPair("Directory %s\n", L"Director %s\n"); + addPair("Default option file %s\n", L"Fișier opțional implicit %s\n"); + addPair("Project option file %s\n", L"Fișier opțiune proiect %s\n"); addPair("Exclude %s\n", L"Excludeți %s\n"); addPair("Exclude (unmatched) %s\n", L"Excludeți (necompensată) %s\n"); addPair(" %s formatted %s unchanged ", L" %s formatat %s neschimbat "); addPair(" seconds ", L" secunde "); addPair("%d min %d sec ", L"%d min %d sec "); addPair("%s lines\n", L"%s linii\n"); - addPair("Using default options file %s\n", L"Fișier folosind opțiunile implicite %s\n"); addPair("Opening HTML documentation %s\n", L"Documentație HTML deschidere %s\n"); - addPair("Invalid option file options:", L"Opțiuni de opțiune de fișier nevalide:"); + addPair("Invalid default options:", L"Opțiuni implicite nevalide:"); + addPair("Invalid project options:", L"Opțiunile de proiect nevalide:"); addPair("Invalid command line options:", L"Opțiuni de linie de comandă nevalide:"); addPair("For help on options type 'astyle -h'", L"Pentru ajutor cu privire la tipul de opțiuni 'astyle -h'"); - addPair("Cannot open options file", L"Nu se poate deschide fișierul de opțiuni"); + addPair("Cannot open default option file", L"Nu se poate deschide fișierul cu opțiuni implicite"); + addPair("Cannot open project option file", L"Nu se poate deschide fișierul cu opțiuni de proiect"); addPair("Cannot open directory", L"Nu se poate deschide directorul"); addPair("Cannot open HTML file %s\n", L"Nu se poate deschide fișierul HTML %s\n"); addPair("Command execute failure", L"Comandă executa eșec"); @@ -964,27 +1020,30 @@ addPair("No file to process %s\n", L"Nu există un fișier pentru a procesa %s\n"); addPair("Did you intend to use --recursive", L"V-ați intenționați să utilizați --recursive"); addPair("Cannot process UTF-32 encoding", L"Nu se poate procesa codificarea UTF-32"); - addPair("\nArtistic Style has terminated", L"\nArtistic Style a terminat"); + addPair("Artistic Style has terminated\n", L"Artistic Style a terminat\n"); } Russian::Russian() // русский // build the translation vector in the Translation base class { addPair("Formatted %s\n", L"Форматированный %s\n"); // should align with unchanged addPair("Unchanged %s\n", L"без изменений %s\n"); // should align with formatted addPair("Directory %s\n", L"каталог %s\n"); + addPair("Default option file %s\n", L"Файл с опцией по умолчанию %s\n"); + addPair("Project option file %s\n", L"Файл опций проекта %s\n"); addPair("Exclude %s\n", L"исключать %s\n"); addPair("Exclude (unmatched) %s\n", L"Исключить (непревзойденный) %s\n"); addPair(" %s formatted %s unchanged ", L" %s Форматированный %s без изменений "); addPair(" seconds ", L" секунды "); addPair("%d min %d sec ", L"%d мин %d сек "); addPair("%s lines\n", L"%s линий\n"); - addPair("Using default options file %s\n", L"Использование опции по умолчанию файл %s\n"); addPair("Opening HTML documentation %s\n", L"Открытие HTML документации %s\n"); - addPair("Invalid option file options:", L"Недопустимый файл опций опцию:"); + addPair("Invalid default options:", L"Недействительные параметры по умолчанию:"); + addPair("Invalid project options:", L"Недопустимые параметры проекта:"); addPair("Invalid command line options:", L"Недопустимые параметры командной строки:"); addPair("For help on options type 'astyle -h'", L"Для получения справки по 'astyle -h' опций типа"); - addPair("Cannot open options file", L"Не удается открыть файл параметров"); + addPair("Cannot open default option file", L"Не удается открыть файл параметров по умолчанию"); + addPair("Cannot open project option file", L"Не удается открыть файл опций проекта"); addPair("Cannot open directory", L"Не могу открыть каталог"); addPair("Cannot open HTML file %s\n", L"Не удается открыть файл HTML %s\n"); addPair("Command execute failure", L"Выполнить команду недостаточности"); @@ -995,27 +1054,30 @@ addPair("No file to process %s\n", L"Нет файлов для обработки %s\n"); addPair("Did you intend to use --recursive", L"Неужели вы собираетесь использовать --recursive"); addPair("Cannot process UTF-32 encoding", L"Не удается обработать UTF-32 кодировке"); - addPair("\nArtistic Style has terminated", L"\nArtistic Style прекратил"); + addPair("Artistic Style has terminated\n", L"Artistic Style прекратил\n"); } Spanish::Spanish() // Español // build the translation vector in the Translation base class { addPair("Formatted %s\n", L"Formato %s\n"); // should align with unchanged addPair("Unchanged %s\n", L"Inalterado %s\n"); // should align with formatted addPair("Directory %s\n", L"Directorio %s\n"); + addPair("Default option file %s\n", L"Archivo de opciones predeterminado %s\n"); + addPair("Project option file %s\n", L"Archivo de opciones del proyecto %s\n"); addPair("Exclude %s\n", L"Excluir %s\n"); addPair("Exclude (unmatched) %s\n", L"Excluir (incomparable) %s\n"); addPair(" %s formatted %s unchanged ", L" %s formato %s inalterado "); addPair(" seconds ", L" segundo "); addPair("%d min %d sec ", L"%d min %d seg "); addPair("%s lines\n", L"%s líneas\n"); - addPair("Using default options file %s\n", L"Uso de las opciones por defecto del archivo %s\n"); addPair("Opening HTML documentation %s\n", L"Apertura de documentación HTML %s\n"); - addPair("Invalid option file options:", L"Opción no válida opciones de archivo:"); + addPair("Invalid default options:", L"Opciones predeterminadas no válidas:"); + addPair("Invalid project options:", L"Opciones de proyecto no válidas:"); addPair("Invalid command line options:", L"No válido opciones de línea de comando:"); addPair("For help on options type 'astyle -h'", L"Para obtener ayuda sobre las opciones tipo 'astyle -h'"); - addPair("Cannot open options file", L"No se puede abrir el archivo de opciones"); + addPair("Cannot open default option file", L"No se puede abrir el archivo de opciones predeterminado"); + addPair("Cannot open project option file", L"No se puede abrir el archivo de opciones del proyecto"); addPair("Cannot open directory", L"No se puede abrir el directorio"); addPair("Cannot open HTML file %s\n", L"No se puede abrir el archivo HTML %s\n"); addPair("Command execute failure", L"Ejecutar el fracaso de comandos"); @@ -1026,27 +1088,30 @@ addPair("No file to process %s\n", L"No existe el fichero a procesar %s\n"); addPair("Did you intend to use --recursive", L"Se va a utilizar --recursive"); addPair("Cannot process UTF-32 encoding", L"No se puede procesar la codificación UTF-32"); - addPair("\nArtistic Style has terminated", L"\nArtistic Style ha terminado"); + addPair("Artistic Style has terminated\n", L"Artistic Style ha terminado\n"); } Swedish::Swedish() // Svenska // build the translation vector in the Translation base class { addPair("Formatted %s\n", L"Formaterade %s\n"); // should align with unchanged addPair("Unchanged %s\n", L"Oförändrade %s\n"); // should align with formatted addPair("Directory %s\n", L"Katalog %s\n"); + addPair("Default option file %s\n", L"Standardalternativsfil %s\n"); + addPair("Project option file %s\n", L"Projektalternativ fil %s\n"); addPair("Exclude %s\n", L"Uteslut %s\n"); addPair("Exclude (unmatched) %s\n", L"Uteslut (oöverträffad) %s\n"); addPair(" %s formatted %s unchanged ", L" %s formaterade %s oförändrade "); addPair(" seconds ", L" sekunder "); addPair("%d min %d sec ", L"%d min %d sek "); addPair("%s lines\n", L"%s linjer\n"); - addPair("Using default options file %s\n", L"Använda standardalternativ fil %s\n"); addPair("Opening HTML documentation %s\n", L"Öppna HTML-dokumentation %s\n"); - addPair("Invalid option file options:", L"Ogiltigt alternativ fil alternativ:"); + addPair("Invalid default options:", L"Ogiltiga standardalternativ:"); + addPair("Invalid project options:", L"Ogiltiga projektalternativ:"); addPair("Invalid command line options:", L"Ogiltig kommandoraden alternativ:"); addPair("For help on options type 'astyle -h'", L"För hjälp om alternativ typ 'astyle -h'"); - addPair("Cannot open options file", L"Kan inte öppna inställningsfilen"); + addPair("Cannot open default option file", L"Kan inte öppna standardalternativsfilen"); + addPair("Cannot open project option file", L"Kan inte öppna projektalternativsfilen"); addPair("Cannot open directory", L"Kan inte öppna katalog"); addPair("Cannot open HTML file %s\n", L"Kan inte öppna HTML-filen %s\n"); addPair("Command execute failure", L"Utför kommando misslyckande"); @@ -1057,27 +1122,30 @@ addPair("No file to process %s\n", L"Ingen fil att bearbeta %s\n"); addPair("Did you intend to use --recursive", L"Har du för avsikt att använda --recursive"); addPair("Cannot process UTF-32 encoding", L"Kan inte hantera UTF-32 kodning"); - addPair("\nArtistic Style has terminated", L"\nArtistic Style har upphört"); + addPair("Artistic Style has terminated\n", L"Artistic Style har upphört\n"); } Ukrainian::Ukrainian() // Український // build the translation vector in the Translation base class { addPair("Formatted %s\n", L"форматований %s\n"); // should align with unchanged addPair("Unchanged %s\n", L"без змін %s\n"); // should align with formatted addPair("Directory %s\n", L"Каталог %s\n"); + addPair("Default option file %s\n", L"Файл параметра за замовчуванням %s\n"); + addPair("Project option file %s\n", L"Файл варіанту проекту %s\n"); addPair("Exclude %s\n", L"Виключити %s\n"); addPair("Exclude (unmatched) %s\n", L"Виключити (неперевершений) %s\n"); addPair(" %s formatted %s unchanged ", L" %s відформатований %s без змін "); addPair(" seconds ", L" секунди "); addPair("%d min %d sec ", L"%d хви %d cek "); addPair("%s lines\n", L"%s ліній\n"); - addPair("Using default options file %s\n", L"Використання файлів опцій за замовчуванням %s\n"); addPair("Opening HTML documentation %s\n", L"Відкриття HTML документації %s\n"); - addPair("Invalid option file options:", L"Неприпустимий файл опцій опцію:"); + addPair("Invalid default options:", L"Недійсні параметри за умовчанням:"); + addPair("Invalid project options:", L"Недійсні параметри проекту:"); addPair("Invalid command line options:", L"Неприпустима параметри командного рядка:"); addPair("For help on options type 'astyle -h'", L"Для отримання довідки по 'astyle -h' опцій типу"); - addPair("Cannot open options file", L"Не вдається відкрити файл параметрів"); + addPair("Cannot open default option file", L"Неможливо відкрити файл параметрів за замовчуванням"); + addPair("Cannot open project option file", L"Неможливо відкрити файл параметрів проекту"); addPair("Cannot open directory", L"Не можу відкрити каталог"); addPair("Cannot open HTML file %s\n", L"Не вдається відкрити файл HTML %s\n"); addPair("Command execute failure", L"Виконати команду недостатності"); @@ -1088,7 +1156,7 @@ addPair("No file to process %s\n", L"Немає файлів для обробки %s\n"); addPair("Did you intend to use --recursive", L"Невже ви збираєтеся використовувати --recursive"); addPair("Cannot process UTF-32 encoding", L"Не вдається обробити UTF-32 кодуванні"); - addPair("\nArtistic Style has terminated", L"\nArtistic Style припинив"); + addPair("Artistic Style has terminated\n", L"Artistic Style припинив\n"); } diff --git a/plugins/astyle/3rdparty/libastyle/ASResource.cpp b/plugins/astyle/3rdparty/libastyle/ASResource.cpp --- a/plugins/astyle/3rdparty/libastyle/ASResource.cpp +++ b/plugins/astyle/3rdparty/libastyle/ASResource.cpp @@ -1,7 +1,7 @@ // ASResource.cpp -// Copyright (c) 2016 by Jim Pattee . +// Copyright (c) 2018 by Jim Pattee . // This code is licensed under the MIT License. -// License.txt describes the conditions under which this software may be distributed. +// License.md describes the conditions under which this software may be distributed. //----------------------------------------------------------------------------- // headers @@ -16,51 +16,72 @@ namespace astyle { // -const string ASResource::AS_IF = string("if"); -const string ASResource::AS_ELSE = string("else"); -const string ASResource::AS_FOR = string("for"); -const string ASResource::AS_DO = string("do"); -const string ASResource::AS_WHILE = string("while"); -const string ASResource::AS_SWITCH = string("switch"); +const string ASResource::_AS_EXCEPT = string("__except"); +const string ASResource::_AS_FINALLY = string("__finally"); +const string ASResource::_AS_TRY = string("__try"); +const string ASResource::AS_ADD = string("add"); +const string ASResource::AS_AUTO = string("auto"); +const string ASResource::AS_AUTORELEASEPOOL = string("autoreleasepool"); const string ASResource::AS_CASE = string("case"); -const string ASResource::AS_DEFAULT = string("default"); +const string ASResource::AS_CATCH = string("catch"); const string ASResource::AS_CLASS = string("class"); -const string ASResource::AS_VOLATILE = string("volatile"); -const string ASResource::AS_INTERRUPT = string("interrupt"); -const string ASResource::AS_NOEXCEPT = string("noexcept"); -const string ASResource::AS_AUTORELEASEPOOL = string("autoreleasepool"); -const string ASResource::AS_STRUCT = string("struct"); -const string ASResource::AS_UNION = string("union"); -const string ASResource::AS_INTERFACE = string("interface"); -const string ASResource::AS_NAMESPACE = string("namespace"); -const string ASResource::AS_MODULE = string("module"); // CORBA IDL module definition +const string ASResource::AS_CONST = string("const"); +const string ASResource::AS_CONST_CAST = string("const_cast"); +const string ASResource::AS_DEFAULT = string("default"); +const string ASResource::AS_DELEGATE = string("delegate"); +const string ASResource::AS_DELETE = string("delete"); +const string ASResource::AS_DO = string("do"); +const string ASResource::AS_DYNAMIC_CAST = string("dynamic_cast"); +const string ASResource::AS_ELSE = string("else"); const string ASResource::AS_END = string("end"); -const string ASResource::AS_SELECTOR = string("selector"); -const string ASResource::AS_EXTERN = string("extern"); const string ASResource::AS_ENUM = string("enum"); -const string ASResource::AS_PUBLIC = string("public"); -const string ASResource::AS_PROTECTED = string("protected"); +const string ASResource::AS_EXTERN = string("extern"); +const string ASResource::AS_FINAL = string("final"); +const string ASResource::AS_FINALLY = string("finally"); +const string ASResource::AS_FIXED = string("fixed"); +const string ASResource::AS_FOR = string("for"); +const string ASResource::AS_FOREACH = string("foreach"); +const string ASResource::AS_FOREVER = string("forever"); +const string ASResource::AS_GET = string("get"); +const string ASResource::AS_IF = string("if"); +const string ASResource::AS_INTERFACE = string("interface"); +const string ASResource::AS_INTERRUPT = string("interrupt"); +const string ASResource::AS_LET = string("let"); +const string ASResource::AS_LOCK = string("lock"); +const string ASResource::AS_MODULE = string("module"); // CORBA IDL module definition +const string ASResource::AS_NAMESPACE = string("namespace"); +const string ASResource::AS_NEW = string("new"); +const string ASResource::AS_NOEXCEPT = string("noexcept"); +const string ASResource::AS_NS_DURING = string("NS_DURING"); +const string ASResource::AS_NS_HANDLER = string("NS_HANDLER"); +const string ASResource::AS_OPERATOR = string("operator"); +const string ASResource::AS_OVERRIDE = string("override"); const string ASResource::AS_PRIVATE = string("private"); +const string ASResource::AS_PROTECTED = string("protected"); +const string ASResource::AS_PUBLIC = string("public"); +const string ASResource::AS_QFOREACH = string("Q_FOREACH"); +const string ASResource::AS_QFOREVER = string("Q_FOREVER"); +const string ASResource::AS_REINTERPRET_CAST = string("reinterpret_cast"); +const string ASResource::AS_REMOVE = string("remove"); +const string ASResource::AS_SEALED = string("sealed"); +const string ASResource::AS_SELECTOR = string("selector"); +const string ASResource::AS_SET = string("set"); const string ASResource::AS_STATIC = string("static"); +const string ASResource::AS_STATIC_CAST = string("static_cast"); +const string ASResource::AS_STRUCT = string("struct"); +const string ASResource::AS_SWITCH = string("switch"); const string ASResource::AS_SYNCHRONIZED = string("synchronized"); -const string ASResource::AS_OPERATOR = string("operator"); const string ASResource::AS_TEMPLATE = string("template"); -const string ASResource::AS_TRY = string("try"); -const string ASResource::AS_CATCH = string("catch"); const string ASResource::AS_THROW = string("throw"); -const string ASResource::AS_FINALLY = string("finally"); -const string ASResource::AS_USING = string("using"); -const string ASResource::_AS_TRY = string("__try"); -const string ASResource::_AS_FINALLY = string("__finally"); -const string ASResource::_AS_EXCEPT = string("__except"); const string ASResource::AS_THROWS = string("throws"); -const string ASResource::AS_CONST = string("const"); -const string ASResource::AS_SEALED = string("sealed"); -const string ASResource::AS_OVERRIDE = string("override"); +const string ASResource::AS_TRY = string("try"); +const string ASResource::AS_UNCHECKED = string("unchecked"); +const string ASResource::AS_UNION = string("union"); +const string ASResource::AS_UNSAFE = string("unsafe"); +const string ASResource::AS_USING = string("using"); +const string ASResource::AS_VOLATILE = string("volatile"); const string ASResource::AS_WHERE = string("where"); -const string ASResource::AS_LET = string("let"); -const string ASResource::AS_NEW = string("new"); -const string ASResource::AS_DELETE = string("delete"); +const string ASResource::AS_WHILE = string("while"); const string ASResource::AS_ASM = string("asm"); const string ASResource::AS__ASM__ = string("__asm__"); @@ -73,8 +94,8 @@ const string ASResource::AS_BAR_EL = string("#el"); const string ASResource::AS_BAR_ENDIF = string("#endif"); -const string ASResource::AS_OPEN_BRACKET = string("{"); -const string ASResource::AS_CLOSE_BRACKET = string("}"); +const string ASResource::AS_OPEN_BRACE = string("{"); +const string ASResource::AS_CLOSE_BRACE = string("}"); const string ASResource::AS_OPEN_LINE_COMMENT = string("//"); const string ASResource::AS_OPEN_COMMENT = string("/*"); const string ASResource::AS_CLOSE_COMMENT = string("*/"); @@ -134,28 +155,6 @@ const string ASResource::AS_COMMA = string(","); const string ASResource::AS_SEMICOLON = string(";"); -const string ASResource::AS_QFOREACH = string("Q_FOREACH"); -const string ASResource::AS_QFOREVER = string("Q_FOREVER"); -const string ASResource::AS_FOREVER = string("forever"); -const string ASResource::AS_FOREACH = string("foreach"); -const string ASResource::AS_LOCK = string("lock"); -const string ASResource::AS_UNSAFE = string("unsafe"); -const string ASResource::AS_FIXED = string("fixed"); -const string ASResource::AS_GET = string("get"); -const string ASResource::AS_SET = string("set"); -const string ASResource::AS_ADD = string("add"); -const string ASResource::AS_REMOVE = string("remove"); -const string ASResource::AS_DELEGATE = string("delegate"); -const string ASResource::AS_UNCHECKED = string("unchecked"); - -const string ASResource::AS_CONST_CAST = string("const_cast"); -const string ASResource::AS_DYNAMIC_CAST = string("dynamic_cast"); -const string ASResource::AS_REINTERPRET_CAST = string("reinterpret_cast"); -const string ASResource::AS_STATIC_CAST = string("static_cast"); - -const string ASResource::AS_NS_DURING = string("NS_DURING"); -const string ASResource::AS_NS_HANDLER = string("NS_HANDLER"); - /** * Sort comparison function. * Compares the length of the value of pointers in the vectors. @@ -187,24 +186,33 @@ */ void ASResource::buildAssignmentOperators(vector* assignmentOperators) { - assignmentOperators->push_back(&AS_ASSIGN); - assignmentOperators->push_back(&AS_PLUS_ASSIGN); - assignmentOperators->push_back(&AS_MINUS_ASSIGN); - assignmentOperators->push_back(&AS_MULT_ASSIGN); - assignmentOperators->push_back(&AS_DIV_ASSIGN); - assignmentOperators->push_back(&AS_MOD_ASSIGN); - assignmentOperators->push_back(&AS_OR_ASSIGN); - assignmentOperators->push_back(&AS_AND_ASSIGN); - assignmentOperators->push_back(&AS_XOR_ASSIGN); + const size_t elements = 15; + static bool reserved = false; + if (!reserved) + { + assignmentOperators->reserve(elements); + reserved = true; + } + + assignmentOperators->emplace_back(&AS_ASSIGN); + assignmentOperators->emplace_back(&AS_PLUS_ASSIGN); + assignmentOperators->emplace_back(&AS_MINUS_ASSIGN); + assignmentOperators->emplace_back(&AS_MULT_ASSIGN); + assignmentOperators->emplace_back(&AS_DIV_ASSIGN); + assignmentOperators->emplace_back(&AS_MOD_ASSIGN); + assignmentOperators->emplace_back(&AS_OR_ASSIGN); + assignmentOperators->emplace_back(&AS_AND_ASSIGN); + assignmentOperators->emplace_back(&AS_XOR_ASSIGN); // Java - assignmentOperators->push_back(&AS_GR_GR_GR_ASSIGN); - assignmentOperators->push_back(&AS_GR_GR_ASSIGN); - assignmentOperators->push_back(&AS_LS_LS_ASSIGN); + assignmentOperators->emplace_back(&AS_GR_GR_GR_ASSIGN); + assignmentOperators->emplace_back(&AS_GR_GR_ASSIGN); + assignmentOperators->emplace_back(&AS_LS_LS_ASSIGN); // Unknown - assignmentOperators->push_back(&AS_LS_LS_LS_ASSIGN); + assignmentOperators->emplace_back(&AS_LS_LS_LS_ASSIGN); + assert(assignmentOperators->size() < elements); sort(assignmentOperators->begin(), assignmentOperators->end(), sortOnLength); } @@ -216,10 +224,21 @@ */ void ASResource::buildCastOperators(vector* castOperators) { - castOperators->push_back(&AS_CONST_CAST); - castOperators->push_back(&AS_DYNAMIC_CAST); - castOperators->push_back(&AS_REINTERPRET_CAST); - castOperators->push_back(&AS_STATIC_CAST); + const size_t elements = 5; + static bool reserved = false; + if (!reserved) + { + castOperators->reserve(elements); + reserved = true; + } + + castOperators->emplace_back(&AS_CONST_CAST); + castOperators->emplace_back(&AS_DYNAMIC_CAST); + castOperators->emplace_back(&AS_REINTERPRET_CAST); + castOperators->emplace_back(&AS_STATIC_CAST); + + assert(castOperators->size() < elements); + sort(castOperators->begin(), castOperators->end(), sortOnName); } /** @@ -230,57 +249,67 @@ */ void ASResource::buildHeaders(vector* headers, int fileType, bool beautifier) { - headers->push_back(&AS_IF); - headers->push_back(&AS_ELSE); - headers->push_back(&AS_FOR); - headers->push_back(&AS_WHILE); - headers->push_back(&AS_DO); - headers->push_back(&AS_SWITCH); - headers->push_back(&AS_CASE); - headers->push_back(&AS_DEFAULT); - headers->push_back(&AS_TRY); - headers->push_back(&AS_CATCH); - headers->push_back(&AS_QFOREACH); // QT - headers->push_back(&AS_QFOREVER); // QT - headers->push_back(&AS_FOREACH); // QT & C# - headers->push_back(&AS_FOREVER); // Qt & Boost + const size_t elements = 25; + static bool reserved = false; + if (!reserved) + { + headers->reserve(elements); + reserved = true; + } + + headers->emplace_back(&AS_IF); + headers->emplace_back(&AS_ELSE); + headers->emplace_back(&AS_FOR); + headers->emplace_back(&AS_WHILE); + headers->emplace_back(&AS_DO); + headers->emplace_back(&AS_SWITCH); + headers->emplace_back(&AS_CASE); + headers->emplace_back(&AS_DEFAULT); + headers->emplace_back(&AS_TRY); + headers->emplace_back(&AS_CATCH); + headers->emplace_back(&AS_QFOREACH); // QT + headers->emplace_back(&AS_QFOREVER); // QT + headers->emplace_back(&AS_FOREACH); // QT & C# + headers->emplace_back(&AS_FOREVER); // Qt & Boost if (fileType == C_TYPE) { - headers->push_back(&_AS_TRY); // __try - headers->push_back(&_AS_FINALLY); // __finally - headers->push_back(&_AS_EXCEPT); // __except + headers->emplace_back(&_AS_TRY); // __try + headers->emplace_back(&_AS_FINALLY); // __finally + headers->emplace_back(&_AS_EXCEPT); // __except } if (fileType == JAVA_TYPE) { - headers->push_back(&AS_FINALLY); - headers->push_back(&AS_SYNCHRONIZED); + headers->emplace_back(&AS_FINALLY); + headers->emplace_back(&AS_SYNCHRONIZED); } if (fileType == SHARP_TYPE) { - headers->push_back(&AS_FINALLY); - headers->push_back(&AS_LOCK); - headers->push_back(&AS_FIXED); - headers->push_back(&AS_GET); - headers->push_back(&AS_SET); - headers->push_back(&AS_ADD); - headers->push_back(&AS_REMOVE); - headers->push_back(&AS_USING); + headers->emplace_back(&AS_FINALLY); + headers->emplace_back(&AS_LOCK); + headers->emplace_back(&AS_FIXED); + headers->emplace_back(&AS_GET); + headers->emplace_back(&AS_SET); + headers->emplace_back(&AS_ADD); + headers->emplace_back(&AS_REMOVE); + headers->emplace_back(&AS_USING); } if (beautifier) { if (fileType == C_TYPE) { - headers->push_back(&AS_TEMPLATE); + headers->emplace_back(&AS_TEMPLATE); } if (fileType == JAVA_TYPE) { - headers->push_back(&AS_STATIC); // for static constructor + headers->emplace_back(&AS_STATIC); // for static constructor } } + + assert(headers->size() < elements); sort(headers->begin(), headers->end(), sortOnName); } @@ -292,9 +321,9 @@ */ void ASResource::buildIndentableHeaders(vector* indentableHeaders) { - indentableHeaders->push_back(&AS_RETURN); + indentableHeaders->emplace_back(&AS_RETURN); - sort(indentableHeaders->begin(), indentableHeaders->end(), sortOnName); +// sort(indentableHeaders->begin(), indentableHeaders->end(), sortOnName); } /** @@ -305,24 +334,33 @@ */ void ASResource::buildIndentableMacros(vector* >* indentableMacros) { - typedef pair macro_pair; + const size_t elements = 10; + static bool reserved = false; + if (!reserved) + { + indentableMacros->reserve(elements); + reserved = true; + } // the pairs must be retained in memory because of pair pointers + typedef pair macro_pair; static const macro_pair macros[] = { // wxWidgets - macro_pair("BEGIN_EVENT_TABLE", "END_EVENT_TABLE"), + macro_pair("BEGIN_EVENT_TABLE", "END_EVENT_TABLE"), macro_pair("wxBEGIN_EVENT_TABLE", "wxEND_EVENT_TABLE"), // MFC - macro_pair("BEGIN_DISPATCH_MAP", "END_DISPATCH_MAP"), - macro_pair("BEGIN_EVENT_MAP", "END_EVENT_MAP"), - macro_pair("BEGIN_MESSAGE_MAP", "END_MESSAGE_MAP"), - macro_pair("BEGIN_PROPPAGEIDS", "END_PROPPAGEIDS"), + macro_pair("BEGIN_DISPATCH_MAP", "END_DISPATCH_MAP"), + macro_pair("BEGIN_EVENT_MAP", "END_EVENT_MAP"), + macro_pair("BEGIN_MESSAGE_MAP", "END_MESSAGE_MAP"), + macro_pair("BEGIN_PROPPAGEIDS", "END_PROPPAGEIDS"), }; - size_t elements = sizeof(macros) / sizeof(macros[0]); - for (size_t i = 0; i < elements; i++) - indentableMacros->push_back(¯os[i]); + size_t entries = sizeof(macros) / sizeof(macros[0]); + for (size_t i = 0; i < entries; i++) + indentableMacros->emplace_back(¯os[i]); + + assert(indentableMacros->size() < elements); } /** @@ -333,21 +371,30 @@ */ void ASResource::buildNonAssignmentOperators(vector* nonAssignmentOperators) { - nonAssignmentOperators->push_back(&AS_EQUAL); - nonAssignmentOperators->push_back(&AS_PLUS_PLUS); - nonAssignmentOperators->push_back(&AS_MINUS_MINUS); - nonAssignmentOperators->push_back(&AS_NOT_EQUAL); - nonAssignmentOperators->push_back(&AS_GR_EQUAL); - nonAssignmentOperators->push_back(&AS_GR_GR_GR); - nonAssignmentOperators->push_back(&AS_GR_GR); - nonAssignmentOperators->push_back(&AS_LS_EQUAL); - nonAssignmentOperators->push_back(&AS_LS_LS_LS); - nonAssignmentOperators->push_back(&AS_LS_LS); - nonAssignmentOperators->push_back(&AS_ARROW); - nonAssignmentOperators->push_back(&AS_AND); - nonAssignmentOperators->push_back(&AS_OR); - nonAssignmentOperators->push_back(&AS_LAMBDA); + const size_t elements = 15; + static bool reserved = false; + if (!reserved) + { + nonAssignmentOperators->reserve(elements); + reserved = true; + } + nonAssignmentOperators->emplace_back(&AS_EQUAL); + nonAssignmentOperators->emplace_back(&AS_PLUS_PLUS); + nonAssignmentOperators->emplace_back(&AS_MINUS_MINUS); + nonAssignmentOperators->emplace_back(&AS_NOT_EQUAL); + nonAssignmentOperators->emplace_back(&AS_GR_EQUAL); + nonAssignmentOperators->emplace_back(&AS_GR_GR_GR); + nonAssignmentOperators->emplace_back(&AS_GR_GR); + nonAssignmentOperators->emplace_back(&AS_LS_EQUAL); + nonAssignmentOperators->emplace_back(&AS_LS_LS_LS); + nonAssignmentOperators->emplace_back(&AS_LS_LS); + nonAssignmentOperators->emplace_back(&AS_ARROW); + nonAssignmentOperators->emplace_back(&AS_AND); + nonAssignmentOperators->emplace_back(&AS_OR); + nonAssignmentOperators->emplace_back(&AS_LAMBDA); + + assert(nonAssignmentOperators->size() < elements); sort(nonAssignmentOperators->begin(), nonAssignmentOperators->end(), sortOnLength); } @@ -360,45 +407,55 @@ */ void ASResource::buildNonParenHeaders(vector* nonParenHeaders, int fileType, bool beautifier) { - nonParenHeaders->push_back(&AS_ELSE); - nonParenHeaders->push_back(&AS_DO); - nonParenHeaders->push_back(&AS_TRY); - nonParenHeaders->push_back(&AS_CATCH); // can be paren or non-paren - nonParenHeaders->push_back(&AS_CASE); // can be paren or non-paren - nonParenHeaders->push_back(&AS_DEFAULT); - nonParenHeaders->push_back(&AS_QFOREVER); // QT - nonParenHeaders->push_back(&AS_FOREVER); // Boost + const size_t elements = 20; + static bool reserved = false; + if (!reserved) + { + nonParenHeaders->reserve(elements); + reserved = true; + } + + nonParenHeaders->emplace_back(&AS_ELSE); + nonParenHeaders->emplace_back(&AS_DO); + nonParenHeaders->emplace_back(&AS_TRY); + nonParenHeaders->emplace_back(&AS_CATCH); // can be paren or non-paren + nonParenHeaders->emplace_back(&AS_CASE); // can be paren or non-paren + nonParenHeaders->emplace_back(&AS_DEFAULT); + nonParenHeaders->emplace_back(&AS_QFOREVER); // QT + nonParenHeaders->emplace_back(&AS_FOREVER); // Boost if (fileType == C_TYPE) { - nonParenHeaders->push_back(&_AS_TRY); // __try - nonParenHeaders->push_back(&_AS_FINALLY); // __finally + nonParenHeaders->emplace_back(&_AS_TRY); // __try + nonParenHeaders->emplace_back(&_AS_FINALLY); // __finally } if (fileType == JAVA_TYPE) { - nonParenHeaders->push_back(&AS_FINALLY); + nonParenHeaders->emplace_back(&AS_FINALLY); } if (fileType == SHARP_TYPE) { - nonParenHeaders->push_back(&AS_FINALLY); - nonParenHeaders->push_back(&AS_GET); - nonParenHeaders->push_back(&AS_SET); - nonParenHeaders->push_back(&AS_ADD); - nonParenHeaders->push_back(&AS_REMOVE); + nonParenHeaders->emplace_back(&AS_FINALLY); + nonParenHeaders->emplace_back(&AS_GET); + nonParenHeaders->emplace_back(&AS_SET); + nonParenHeaders->emplace_back(&AS_ADD); + nonParenHeaders->emplace_back(&AS_REMOVE); } if (beautifier) { if (fileType == C_TYPE) { - nonParenHeaders->push_back(&AS_TEMPLATE); + nonParenHeaders->emplace_back(&AS_TEMPLATE); } if (fileType == JAVA_TYPE) { - nonParenHeaders->push_back(&AS_STATIC); + nonParenHeaders->emplace_back(&AS_STATIC); } } + + assert(nonParenHeaders->size() < elements); sort(nonParenHeaders->begin(), nonParenHeaders->end(), sortOnName); } @@ -410,54 +467,65 @@ */ void ASResource::buildOperators(vector* operators, int fileType) { - operators->push_back(&AS_PLUS_ASSIGN); - operators->push_back(&AS_MINUS_ASSIGN); - operators->push_back(&AS_MULT_ASSIGN); - operators->push_back(&AS_DIV_ASSIGN); - operators->push_back(&AS_MOD_ASSIGN); - operators->push_back(&AS_OR_ASSIGN); - operators->push_back(&AS_AND_ASSIGN); - operators->push_back(&AS_XOR_ASSIGN); - operators->push_back(&AS_EQUAL); - operators->push_back(&AS_PLUS_PLUS); - operators->push_back(&AS_MINUS_MINUS); - operators->push_back(&AS_NOT_EQUAL); - operators->push_back(&AS_GR_EQUAL); - operators->push_back(&AS_GR_GR_GR_ASSIGN); - operators->push_back(&AS_GR_GR_ASSIGN); - operators->push_back(&AS_GR_GR_GR); - operators->push_back(&AS_GR_GR); - operators->push_back(&AS_LS_EQUAL); - operators->push_back(&AS_LS_LS_LS_ASSIGN); - operators->push_back(&AS_LS_LS_ASSIGN); - operators->push_back(&AS_LS_LS_LS); - operators->push_back(&AS_LS_LS); - operators->push_back(&AS_QUESTION_QUESTION); - operators->push_back(&AS_LAMBDA); - operators->push_back(&AS_ARROW); - operators->push_back(&AS_AND); - operators->push_back(&AS_OR); - operators->push_back(&AS_SCOPE_RESOLUTION); - operators->push_back(&AS_PLUS); - operators->push_back(&AS_MINUS); - operators->push_back(&AS_MULT); - operators->push_back(&AS_DIV); - operators->push_back(&AS_MOD); - operators->push_back(&AS_QUESTION); - operators->push_back(&AS_COLON); - operators->push_back(&AS_ASSIGN); - operators->push_back(&AS_LS); - operators->push_back(&AS_GR); - operators->push_back(&AS_NOT); - operators->push_back(&AS_BIT_OR); - operators->push_back(&AS_BIT_AND); - operators->push_back(&AS_BIT_NOT); - operators->push_back(&AS_BIT_XOR); + const size_t elements = 50; + static bool reserved = false; + if (!reserved) + { + operators->reserve(elements); + reserved = true; + } + + + operators->emplace_back(&AS_PLUS_ASSIGN); + operators->emplace_back(&AS_MINUS_ASSIGN); + operators->emplace_back(&AS_MULT_ASSIGN); + operators->emplace_back(&AS_DIV_ASSIGN); + operators->emplace_back(&AS_MOD_ASSIGN); + operators->emplace_back(&AS_OR_ASSIGN); + operators->emplace_back(&AS_AND_ASSIGN); + operators->emplace_back(&AS_XOR_ASSIGN); + operators->emplace_back(&AS_EQUAL); + operators->emplace_back(&AS_PLUS_PLUS); + operators->emplace_back(&AS_MINUS_MINUS); + operators->emplace_back(&AS_NOT_EQUAL); + operators->emplace_back(&AS_GR_EQUAL); + operators->emplace_back(&AS_GR_GR_GR_ASSIGN); + operators->emplace_back(&AS_GR_GR_ASSIGN); + operators->emplace_back(&AS_GR_GR_GR); + operators->emplace_back(&AS_GR_GR); + operators->emplace_back(&AS_LS_EQUAL); + operators->emplace_back(&AS_LS_LS_LS_ASSIGN); + operators->emplace_back(&AS_LS_LS_ASSIGN); + operators->emplace_back(&AS_LS_LS_LS); + operators->emplace_back(&AS_LS_LS); + operators->emplace_back(&AS_QUESTION_QUESTION); + operators->emplace_back(&AS_LAMBDA); + operators->emplace_back(&AS_ARROW); + operators->emplace_back(&AS_AND); + operators->emplace_back(&AS_OR); + operators->emplace_back(&AS_SCOPE_RESOLUTION); + operators->emplace_back(&AS_PLUS); + operators->emplace_back(&AS_MINUS); + operators->emplace_back(&AS_MULT); + operators->emplace_back(&AS_DIV); + operators->emplace_back(&AS_MOD); + operators->emplace_back(&AS_QUESTION); + operators->emplace_back(&AS_COLON); + operators->emplace_back(&AS_ASSIGN); + operators->emplace_back(&AS_LS); + operators->emplace_back(&AS_GR); + operators->emplace_back(&AS_NOT); + operators->emplace_back(&AS_BIT_OR); + operators->emplace_back(&AS_BIT_AND); + operators->emplace_back(&AS_BIT_NOT); + operators->emplace_back(&AS_BIT_XOR); if (fileType == C_TYPE) { - operators->push_back(&AS_GCC_MIN_ASSIGN); - operators->push_back(&AS_GCC_MAX_ASSIGN); + operators->emplace_back(&AS_GCC_MIN_ASSIGN); + operators->emplace_back(&AS_GCC_MAX_ASSIGN); } + + assert(operators->size() < elements); sort(operators->begin(), operators->end(), sortOnLength); } @@ -470,27 +538,37 @@ */ void ASResource::buildPreBlockStatements(vector* preBlockStatements, int fileType) { - preBlockStatements->push_back(&AS_CLASS); + const size_t elements = 10; + static bool reserved = false; + if (!reserved) + { + preBlockStatements->reserve(elements); + reserved = true; + } + + preBlockStatements->emplace_back(&AS_CLASS); if (fileType == C_TYPE) { - preBlockStatements->push_back(&AS_STRUCT); - preBlockStatements->push_back(&AS_UNION); - preBlockStatements->push_back(&AS_NAMESPACE); - preBlockStatements->push_back(&AS_MODULE); // for CORBA IDL - preBlockStatements->push_back(&AS_INTERFACE); // for CORBA IDL + preBlockStatements->emplace_back(&AS_STRUCT); + preBlockStatements->emplace_back(&AS_UNION); + preBlockStatements->emplace_back(&AS_NAMESPACE); + preBlockStatements->emplace_back(&AS_MODULE); // for CORBA IDL + preBlockStatements->emplace_back(&AS_INTERFACE); // for CORBA IDL } if (fileType == JAVA_TYPE) { - preBlockStatements->push_back(&AS_INTERFACE); - preBlockStatements->push_back(&AS_THROWS); + preBlockStatements->emplace_back(&AS_INTERFACE); + preBlockStatements->emplace_back(&AS_THROWS); } if (fileType == SHARP_TYPE) { - preBlockStatements->push_back(&AS_INTERFACE); - preBlockStatements->push_back(&AS_NAMESPACE); - preBlockStatements->push_back(&AS_WHERE); - preBlockStatements->push_back(&AS_STRUCT); + preBlockStatements->emplace_back(&AS_INTERFACE); + preBlockStatements->emplace_back(&AS_NAMESPACE); + preBlockStatements->emplace_back(&AS_WHERE); + preBlockStatements->emplace_back(&AS_STRUCT); } + + assert(preBlockStatements->size() < elements); sort(preBlockStatements->begin(), preBlockStatements->end(), sortOnName); } @@ -500,71 +578,131 @@ * NOTE: Cannot be both a header and a preCommandHeader. * * A preCommandHeader is in a function definition between - * the closing paren and the opening bracket. + * the closing paren and the opening brace. * e.g. in "void foo() const {}", "const" is a preCommandHeader. */ void ASResource::buildPreCommandHeaders(vector* preCommandHeaders, int fileType) { + const size_t elements = 10; + static bool reserved = false; + if (!reserved) + { + preCommandHeaders->reserve(elements); + reserved = true; + } + if (fileType == C_TYPE) { - preCommandHeaders->push_back(&AS_CONST); - preCommandHeaders->push_back(&AS_VOLATILE); - preCommandHeaders->push_back(&AS_INTERRUPT); - preCommandHeaders->push_back(&AS_NOEXCEPT); - preCommandHeaders->push_back(&AS_OVERRIDE); - preCommandHeaders->push_back(&AS_SEALED); // Visual C only - preCommandHeaders->push_back(&AS_AUTORELEASEPOOL); // Obj-C only + preCommandHeaders->emplace_back(&AS_CONST); + preCommandHeaders->emplace_back(&AS_FINAL); + preCommandHeaders->emplace_back(&AS_INTERRUPT); + preCommandHeaders->emplace_back(&AS_NOEXCEPT); + preCommandHeaders->emplace_back(&AS_OVERRIDE); + preCommandHeaders->emplace_back(&AS_VOLATILE); + preCommandHeaders->emplace_back(&AS_SEALED); // Visual C only + preCommandHeaders->emplace_back(&AS_AUTORELEASEPOOL); // Obj-C only } if (fileType == JAVA_TYPE) { - preCommandHeaders->push_back(&AS_THROWS); + preCommandHeaders->emplace_back(&AS_THROWS); } if (fileType == SHARP_TYPE) { - preCommandHeaders->push_back(&AS_WHERE); + preCommandHeaders->emplace_back(&AS_WHERE); } + assert(preCommandHeaders->size() < elements); sort(preCommandHeaders->begin(), preCommandHeaders->end(), sortOnName); } /** * Build the vector of pre-definition headers. * Used by ONLY ASFormatter.cpp - * NOTE: Do NOT add 'enum' here. It is an array type bracket. + * NOTE: Do NOT add 'enum' here. It is an array type brace. * NOTE: Do NOT add 'extern' here. Do not want an extra indent. * * @param preDefinitionHeaders a reference to the vector to be built. */ void ASResource::buildPreDefinitionHeaders(vector* preDefinitionHeaders, int fileType) { - preDefinitionHeaders->push_back(&AS_CLASS); + const size_t elements = 10; + static bool reserved = false; + if (!reserved) + { + preDefinitionHeaders->reserve(elements); + reserved = true; + } + + preDefinitionHeaders->emplace_back(&AS_CLASS); if (fileType == C_TYPE) { - preDefinitionHeaders->push_back(&AS_STRUCT); - preDefinitionHeaders->push_back(&AS_UNION); - preDefinitionHeaders->push_back(&AS_NAMESPACE); - preDefinitionHeaders->push_back(&AS_MODULE); // for CORBA IDL - preDefinitionHeaders->push_back(&AS_INTERFACE); // for CORBA IDL + preDefinitionHeaders->emplace_back(&AS_STRUCT); + preDefinitionHeaders->emplace_back(&AS_UNION); + preDefinitionHeaders->emplace_back(&AS_NAMESPACE); + preDefinitionHeaders->emplace_back(&AS_MODULE); // for CORBA IDL + preDefinitionHeaders->emplace_back(&AS_INTERFACE); // for CORBA IDL } if (fileType == JAVA_TYPE) { - preDefinitionHeaders->push_back(&AS_INTERFACE); + preDefinitionHeaders->emplace_back(&AS_INTERFACE); } if (fileType == SHARP_TYPE) { - preDefinitionHeaders->push_back(&AS_STRUCT); - preDefinitionHeaders->push_back(&AS_INTERFACE); - preDefinitionHeaders->push_back(&AS_NAMESPACE); + preDefinitionHeaders->emplace_back(&AS_STRUCT); + preDefinitionHeaders->emplace_back(&AS_INTERFACE); + preDefinitionHeaders->emplace_back(&AS_NAMESPACE); } + + assert(preDefinitionHeaders->size() < elements); sort(preDefinitionHeaders->begin(), preDefinitionHeaders->end(), sortOnName); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ASBase Functions * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +// check if a specific line position contains a header. +const string* ASBase::findHeader(const string& line, int i, + const vector* possibleHeaders) const +{ + assert(isCharPotentialHeader(line, i)); + // check the word + size_t maxHeaders = possibleHeaders->size(); + for (size_t p = 0; p < maxHeaders; p++) + { + const string* header = (*possibleHeaders)[p]; + const size_t wordEnd = i + header->length(); + if (wordEnd > line.length()) + continue; + int result = (line.compare(i, header->length(), *header)); + if (result > 0) + continue; + if (result < 0) + break; + // check that this is not part of a longer word + if (wordEnd == line.length()) + return header; + if (isLegalNameChar(line[wordEnd])) + continue; + const char peekChar = peekNextChar(line, wordEnd - 1); + // is not a header if part of a definition + if (peekChar == ',' || peekChar == ')') + break; + // the following accessor definitions are NOT headers + // goto default; is NOT a header + // default(int) keyword in C# is NOT a header + else if ((header == &AS_GET + || header == &AS_SET + || header == &AS_DEFAULT) + && (peekChar == ';' || peekChar == '(' || peekChar == '=')) + break; + return header; + } + return nullptr; +} + // check if a specific line position contains a keyword. bool ASBase::findKeyword(const string& line, int i, const string& keyword) const { @@ -582,12 +720,32 @@ if (isLegalNameChar(line[wordEnd])) return false; // is not a keyword if part of a definition - const char peekChar = peekNextChar(line, (int)wordEnd - 1); + const char peekChar = peekNextChar(line, (int) wordEnd - 1); if (peekChar == ',' || peekChar == ')') return false; return true; } +// check if a specific line position contains an operator. +const string* ASBase::findOperator(const string& line, int i, + const vector* possibleOperators) const +{ + assert(isCharPotentialOperator(line[i])); + // find the operator in the vector + // the vector contains the LONGEST operators first + // must loop thru the entire vector + size_t maxOperators = possibleOperators->size(); + for (size_t p = 0; p < maxOperators; p++) + { + const size_t wordEnd = i + (*(*possibleOperators)[p]).length(); + if (wordEnd > line.length()) + continue; + if (line.compare(i, (*(*possibleOperators)[p]).length(), *(*possibleOperators)[p]) == 0) + return (*possibleOperators)[p]; + } + return nullptr; +} + // get the current word on a line // index must point to the beginning of the word string ASBase::getCurrentWord(const string& line, size_t index) const @@ -608,7 +766,7 @@ { if (isWhiteSpace(ch)) return false; - if ((unsigned) ch > 127) + if ((unsigned char) ch > 127) return false; return (isalnum((unsigned char) ch) || ch == '.' || ch == '_' @@ -623,6 +781,8 @@ char prevCh = ' '; if (i > 0) prevCh = line[i - 1]; + if (i > 1 && line[i - 2] == '\\') + prevCh = ' '; if (!isLegalNameChar(prevCh) && isLegalNameChar(line[i])) return true; return false; diff --git a/plugins/astyle/3rdparty/libastyle/README b/plugins/astyle/3rdparty/libastyle/README --- a/plugins/astyle/3rdparty/libastyle/README +++ b/plugins/astyle/3rdparty/libastyle/README @@ -1,4 +1,4 @@ -This is a copy of the official AStyle library. +This is a copy of the official AStyle library, currently version 3.1 . See: http://astyle.sourceforge.net/ License: http://astyle.sourceforge.net/license.html @@ -20,4 +20,4 @@ This makes it easier to rebase them afterwards onto a new AStyle release. -Also make sure you add a unit test! \ No newline at end of file +Also make sure you add a unit test! diff --git a/plugins/astyle/3rdparty/libastyle/astyle.h b/plugins/astyle/3rdparty/libastyle/astyle.h --- a/plugins/astyle/3rdparty/libastyle/astyle.h +++ b/plugins/astyle/3rdparty/libastyle/astyle.h @@ -1,7 +1,7 @@ // astyle.h -// Copyright (c) 2016 by Jim Pattee . +// Copyright (c) 2018 by Jim Pattee . // This code is licensed under the MIT License. -// License.txt describes the conditions under which this software may be distributed. +// License.md describes the conditions under which this software may be distributed. #ifndef ASTYLE_H #define ASTYLE_H @@ -19,6 +19,7 @@ #include #include // for cout +#include #include #include @@ -38,6 +39,10 @@ #pragma warn -8004 // variable is assigned a value that is never used #endif +#ifdef __GNUC__ + #pragma GCC diagnostic ignored "-Wconversion" +#endif + #ifdef __INTEL_COMPILER #pragma warning(disable: 383) // value copied to temporary, reference to temporary used #pragma warning(disable: 981) // operands are evaluated in unspecified order @@ -73,7 +78,7 @@ STYLE_STROUSTRUP, STYLE_WHITESMITH, STYLE_VTK, - STYLE_BANNER, + STYLE_RATLIFF, STYLE_GNU, STYLE_LINUX, STYLE_HORSTMANN, @@ -84,17 +89,17 @@ STYLE_LISP }; -enum BracketMode +enum BraceMode { NONE_MODE, ATTACH_MODE, BREAK_MODE, LINUX_MODE, - RUN_IN_MODE // broken brackets + RUN_IN_MODE // broken braces }; -// maximun value for int is 16,384 (total value of 32,767) -enum BracketType +// maximum value for int is 16,384 (total value of 32,767) +enum BraceType { NULL_TYPE = 0, NAMESPACE_TYPE = 1, // also a DEFINITION_TYPE @@ -150,9 +155,10 @@ enum FileEncoding { - ENCODING_8BIT, + ENCODING_8BIT, // includes UTF-8 without BOM + UTF_8BOM, // UTF-8 with BOM UTF_16BE, - UTF_16LE, // Windows default + UTF_16LE, // Windows default UTF_32BE, UTF_32LE }; @@ -181,23 +187,50 @@ public: ASSourceIterator() {} virtual ~ASSourceIterator() {} + virtual streamoff getPeekStart() const = 0; virtual int getStreamLength() const = 0; virtual bool hasMoreLines() const = 0; virtual string nextLine(bool emptyLineWasDeleted = false) = 0; virtual string peekNextLine() = 0; virtual void peekReset() = 0; virtual streamoff tellg() = 0; }; +//----------------------------------------------------------------------------- +// Class ASPeekStream +// A small class using RAII to peek ahead in the ASSourceIterator stream +// and to reset the ASSourceIterator pointer in the destructor. +// It enables a return from anywhere in the method. +//----------------------------------------------------------------------------- + +class ASPeekStream +{ +private: + ASSourceIterator* sourceIterator; + bool needReset; // reset sourceIterator to the original position + +public: + explicit ASPeekStream(ASSourceIterator* sourceIterator_) + { sourceIterator = sourceIterator_; needReset = false; } + + ~ASPeekStream() + { if (needReset) sourceIterator->peekReset(); } + + bool hasMoreLines() const + { return sourceIterator->hasMoreLines(); } + + string peekNextLine() + { needReset = true; return sourceIterator->peekNextLine(); } +}; + + //----------------------------------------------------------------------------- // Class ASResource //----------------------------------------------------------------------------- class ASResource { public: - ASResource() {} - virtual ~ASResource() {} void buildAssignmentOperators(vector* assignmentOperators); void buildCastOperators(vector* castOperators); void buildHeaders(vector* headers, int fileType, bool beautifier = false); @@ -223,14 +256,15 @@ static const string AS_END; static const string AS_SELECTOR; static const string AS_EXTERN, AS_ENUM; - static const string AS_STATIC, AS_CONST, AS_SEALED, AS_OVERRIDE, AS_VOLATILE, AS_NEW, AS_DELETE; + static const string AS_FINAL, AS_OVERRIDE; + static const string AS_STATIC, AS_CONST, AS_SEALED, AS_VOLATILE, AS_NEW, AS_DELETE; static const string AS_NOEXCEPT, AS_INTERRUPT, AS_AUTORELEASEPOOL; static const string AS_WHERE, AS_LET, AS_SYNCHRONIZED; static const string AS_OPERATOR, AS_TEMPLATE; - static const string AS_OPEN_BRACKET, AS_CLOSE_BRACKET; + static const string AS_OPEN_BRACE, AS_CLOSE_BRACE; static const string AS_OPEN_LINE_COMMENT, AS_OPEN_COMMENT, AS_CLOSE_COMMENT; static const string AS_BAR_DEFINE, AS_BAR_INCLUDE, AS_BAR_IF, AS_BAR_EL, AS_BAR_ENDIF; - static const string AS_RETURN; + static const string AS_AUTO, AS_RETURN; static const string AS_CIN, AS_COUT, AS_CERR; static const string AS_ASSIGN, AS_PLUS_ASSIGN, AS_MINUS_ASSIGN, AS_MULT_ASSIGN; static const string AS_DIV_ASSIGN, AS_MOD_ASSIGN, AS_XOR_ASSIGN, AS_OR_ASSIGN, AS_AND_ASSIGN; @@ -258,7 +292,7 @@ // Functions definitions are at the end of ASResource.cpp. //----------------------------------------------------------------------------- -class ASBase +class ASBase : protected ASResource { private: // all variables should be set by the "init" function @@ -275,7 +309,11 @@ bool isWhiteSpace(char ch) const { return (ch == ' ' || ch == '\t'); } protected: // functions definitions are at the end of ASResource.cpp + const string* findHeader(const string& line, int i, + const vector* possibleHeaders) const; bool findKeyword(const string& line, int i, const string& keyword) const; + const string* findOperator(const string& line, int i, + const vector* possibleOperators) const; string getCurrentWord(const string& line, size_t index) const; bool isDigit(char ch) const; bool isLegalNameChar(char ch) const; @@ -290,7 +328,7 @@ // Class ASBeautifier //----------------------------------------------------------------------------- -class ASBeautifier : protected ASResource, protected ASBase +class ASBeautifier : protected ASBase { public: ASBeautifier(); @@ -304,8 +342,10 @@ void setDefaultTabLength(); void setEmptyLineFill(bool state); void setForceTabXIndentation(int length); + void setAfterParenIndent(bool state); void setJavaStyle(); void setLabelIndent(bool state); + void setMaxContinuationIndentLength(int max); void setMaxInStatementIndentLength(int max); void setMinConditionalIndentOption(int min); void setMinConditionalIndentLength(); @@ -326,7 +366,7 @@ string getIndentString() const; string getNextWord(const string& line, size_t currPos) const; bool getAlignMethodColon() const; - bool getBracketIndent() const; + bool getBraceIndent() const; bool getBlockIndent() const; bool getCaseIndent() const; bool getClassIndent() const; @@ -340,23 +380,19 @@ protected: void deleteBeautifierVectors(); - const string* findHeader(const string& line, int i, - const vector* possibleHeaders) const; - const string* findOperator(const string& line, int i, - const vector* possibleOperators) const; int getNextProgramCharDistance(const string& line, int i) const; - int indexOf(vector& container, const string* element) const; + int indexOf(const vector& container, const string* element) const; void setBlockIndent(bool state); - void setBracketIndent(bool state); - void setBracketIndentVtk(bool state); + void setBraceIndent(bool state); + void setBraceIndentVtk(bool state); string extractPreprocessorStatement(const string& line) const; string trim(const string& str) const; string rtrim(const string& str) const; // variables set by ASFormatter - must be updated in activeBeautifierStack int inLineNumber; - int horstmannIndentInStatement; - int nonInStatementBracket; + int runInIndentContinuation; + int nonInStatementBrace; int objCColonAlignSubsequent; // for subsequent lines not counting indent bool lineCommentNoBeautify; bool isElseHeaderIndent; @@ -371,18 +407,18 @@ private: // functions ASBeautifier(const ASBeautifier& other); // inline functions - ASBeautifier& operator=(ASBeautifier&); // not to be implemented + ASBeautifier& operator=(ASBeautifier&); // not to be implemented void adjustObjCMethodDefinitionIndentation(const string& line_); void adjustObjCMethodCallIndentation(const string& line_); void adjustParsedLineIndentation(size_t iPrelim, bool isInExtraHeaderIndent); void computePreliminaryIndentation(); void parseCurrentLine(const string& line); - void popLastInStatementIndent(); + void popLastContinuationIndent(); void processPreprocessor(const string& preproc, const string& line); - void registerInStatementIndent(const string& line, int i, int spaceIndentCount_, - int tabIncrementIn, int minIndent, bool updateParenStack); - void registerInStatementIndentColon(const string& line, int i, int tabIncrementIn); + void registerContinuationIndent(const string& line, int i, int spaceIndentCount_, + int tabIncrementIn, int minIndent, bool updateParenStack); + void registerContinuationIndentColon(const string& line, int i, int tabIncrementIn); void initVectors(); void initTempStacksContainer(vector*>*& container, vector*>* value); @@ -392,15 +428,17 @@ int adjustIndentCountForBreakElseIfComments() const; int computeObjCColonAlignment(const string& line, int colonAlignPosition) const; int convertTabToSpaces(int i, int tabIncrementIn) const; - int getInStatementIndentAssign(const string& line, size_t currPos) const; - int getInStatementIndentComma(const string& line, size_t currPos) const; - int getObjCFollowingKeyword(const string& line, int BracketPos) const; + int findObjCColonAlignment(const string& line) const; + int getContinuationIndentAssign(const string& line, size_t currPos) const; + int getContinuationIndentComma(const string& line, size_t currPos) const; + int getObjCFollowingKeyword(const string& line, int bracePos) const; bool isIndentedPreprocessor(const string& line, size_t currPos) const; bool isLineEndComment(const string& line, int startPos) const; bool isPreprocessorConditionalCplusplus(const string& line) const; bool isInPreprocessorUnterminatedComment(const string& line); + bool isTopLevel() const; bool statementEndsWithComma(const string& line, int index) const; - string& getIndentedLineReturn(string& newLine, const string& originalLine) const; + const string& getIndentedLineReturn(const string& newLine, const string& originalLine) const; string getIndentedSpaceEquivalent(const string& line_) const; string preLineWS(int lineIndentCount, int lineSpaceIndentCount) const; template void deleteContainer(T& container); @@ -424,12 +462,12 @@ vector* activeBeautifierStackLengthStack; vector* headerStack; vector* >* tempStacks; - vector* blockParenDepthStack; + vector* parenDepthStack; vector* blockStatementStack; vector* parenStatementStack; - vector* bracketBlockStateStack; - vector* inStatementIndentStack; - vector* inStatementIndentStackSizeStack; + vector* braceBlockStateStack; + vector* continuationIndentStack; + vector* continuationIndentStackSizeStack; vector* parenIndentStack; vector >* preprocIndentStack; @@ -448,20 +486,20 @@ bool isInAsmBlock; bool isInComment; bool isInPreprocessorComment; - bool isInHorstmannComment; + bool isInRunInComment; bool isInCase; bool isInQuestion; - bool isInStatement; + bool isContinuation; bool isInHeader; bool isInTemplate; bool isInDefine; bool isInDefineDefinition; bool classIndent; bool isIndentModeOff; - bool isInClassHeader; // is in a class before the opening bracket + bool isInClassHeader; // is in a class before the opening brace bool isInClassHeaderTab; // is in an indentable class header line bool isInClassInitializer; // is in a class after the ':' initializer - bool isInClass; // is in a class after the opening bracket + bool isInClass; // is in a class after the opening brace bool isInObjCMethodDefinition; bool isInObjCMethodCall; bool isInObjCMethodCallFirst; @@ -472,13 +510,15 @@ bool isInEnum; bool isInEnumTypeID; bool isInLet; + bool isInTrailingReturnType; bool modifierIndent; bool switchIndent; bool caseIndent; bool namespaceIndent; - bool bracketIndent; - bool bracketIndentVtk; bool blockIndent; + bool braceIndent; + bool braceIndentVtk; + bool shouldIndentAfterParen; bool labelIndent; bool shouldIndentPreprocDefine; bool isInConditional; @@ -492,21 +532,21 @@ bool blockCommentNoIndent; bool blockCommentNoBeautify; bool previousLineProbationTab; - bool lineBeginsWithOpenBracket; - bool lineBeginsWithCloseBracket; + bool lineBeginsWithOpenBrace; + bool lineBeginsWithCloseBrace; bool lineBeginsWithComma; bool lineIsCommentOnly; bool lineIsLineCommentOnly; - bool shouldIndentBrackettedLine; + bool shouldIndentBracedLine; bool isInSwitch; bool foundPreCommandHeader; bool foundPreCommandMacro; bool shouldAlignMethodColon; bool shouldIndentPreprocConditional; int indentCount; int spaceIndentCount; int spaceIndentObjCMethodAlignment; - int bracketPosObjCMethodAlignment; + int bracePosObjCMethodAlignment; int colonIndentObjCMethodAlignment; int lineOpeningBlocksNum; int lineClosingBlocksNum; @@ -518,10 +558,10 @@ int tabLength; int continuationIndent; int blockTabCount; - int maxInStatementIndent; + int maxContinuationIndent; int classInitializerIndents; int templateDepth; - int blockParenCount; + int squareBracketCount; int prevFinalLineSpaceIndentCount; int prevFinalLineIndentCount; int defineIndentCount; @@ -547,16 +587,16 @@ void enhance(string& line, bool isInNamespace, bool isInPreprocessor, bool isInSQL); private: // functions - void convertForceTabIndentToSpaces(string& line) const; - void convertSpaceIndentToForceTab(string& line) const; - size_t findCaseColon(string& line, size_t caseIndex) const; - int indentLine(string& line, int indent) const; - bool isBeginDeclareSectionSQL(string& line, size_t index) const; - bool isEndDeclareSectionSQL(string& line, size_t index) const; - bool isOneLineBlockReached(const string& line, int startChar) const; - void parseCurrentLine(string& line, bool isInPreprocessor, bool isInSQL); - size_t processSwitchBlock(string& line, size_t index); - int unindentLine(string& line, int unindent) const; + void convertForceTabIndentToSpaces(string& line) const; + void convertSpaceIndentToForceTab(string& line) const; + size_t findCaseColon(const string& line, size_t caseIndex) const; + int indentLine(string& line, int indent) const; + bool isBeginDeclareSectionSQL(const string& line, size_t index) const; + bool isEndDeclareSectionSQL(const string& line, size_t index) const; + bool isOneLineBlockReached(const string& line, int startChar) const; + void parseCurrentLine(string& line, bool isInPreprocessor, bool isInSQL); + size_t processSwitchBlock(string& line, size_t index); + int unindentLine(string& line, int unindent) const; private: // options from command line or options file @@ -577,19 +617,19 @@ char quoteChar; // unindent variables - int bracketCount; + int braceCount; int switchDepth; int eventPreprocDepth; - bool lookingForCaseBracket; + bool lookingForCaseBrace; bool unindentNextLine; bool shouldUnindentLine; bool shouldUnindentComment; // struct used by ParseFormattedLine function // contains variables used to unindent the case blocks struct SwitchVariables { - int switchBracketCount; + int switchBraceCount; int unindentDepth; bool unindentCase; }; @@ -623,16 +663,17 @@ LineEndFormat getLineEndFormat() const; bool getIsLineReady() const; void setFormattingStyle(FormatStyle style); - void setAddBracketsMode(bool state); - void setAddOneLineBracketsMode(bool state); - void setRemoveBracketsMode(bool state); + void setAddBracesMode(bool state); + void setAddOneLineBracesMode(bool state); + void setRemoveBracesMode(bool state); void setAttachClass(bool state); + void setAttachClosingWhile(bool state); void setAttachExternC(bool state); void setAttachNamespace(bool state); void setAttachInline(bool state); - void setBracketFormatMode(BracketMode mode); + void setBraceFormatMode(BraceMode mode); void setBreakAfterMode(bool state); - void setBreakClosingHeaderBracketsMode(bool state); + void setBreakClosingHeaderBracesMode(bool state); void setBreakBlocksMode(bool state); void setBreakClosingHeaderBlocksMode(bool state); void setBreakElseIfsMode(bool state); @@ -648,6 +689,10 @@ void setCloseTemplatesMode(bool state); void setCommaPaddingMode(bool state); void setDeleteEmptyLinesMode(bool state); + void setBreakReturnType(bool state); + void setBreakReturnTypeDecl(bool state); + void setAttachReturnType(bool state); + void setAttachReturnTypeDecl(bool state); void setIndentCol1CommentsMode(bool state); void setLineEndFormat(LineEndFormat fmt); void setMaxCodeLength(int max); @@ -667,53 +712,63 @@ size_t getChecksumOut() const; int getChecksumDiff() const; int getFormatterFileType() const; + // retained for compatibility with release 2.06 + // "Brackets" have been changed to "Braces" in 3.0 + // they are referenced only by the old "bracket" options + void setAddBracketsMode(bool state); + void setAddOneLineBracketsMode(bool state); + void setRemoveBracketsMode(bool state); + void setBreakClosingHeaderBracketsMode(bool state); + private: // functions ASFormatter(const ASFormatter& copy); // not to be implemented ASFormatter& operator=(ASFormatter&); // not to be implemented template void deleteContainer(T& container); template void initContainer(T& container, T value); char peekNextChar() const; - BracketType getBracketType(); + BraceType getBraceType(); bool adjustChecksumIn(int adjustment); bool computeChecksumIn(const string& currentLine_); bool computeChecksumOut(const string& beautifiedLine); - bool addBracketsToStatement(); - bool removeBracketsFromStatement(); + bool addBracesToStatement(); + bool removeBracesFromStatement(); bool commentAndHeaderFollows(); bool getNextChar(); bool getNextLine(bool emptyLineWasDeleted = false); bool isArrayOperator() const; bool isBeforeComment() const; bool isBeforeAnyComment() const; bool isBeforeAnyLineEndComment(int startPos) const; bool isBeforeMultipleLineEndComments(int startPos) const; - bool isBracketType(BracketType a, BracketType b) const; + bool isBraceType(BraceType a, BraceType b) const; bool isClassInitializer() const; bool isClosingHeader(const string* header) const; - bool isCurrentBracketBroken() const; + bool isCurrentBraceBroken() const; bool isDereferenceOrAddressOf() const; - bool isExecSQL(string& line, size_t index) const; + bool isExecSQL(const string& line, size_t index) const; bool isEmptyLine(const string& line) const; bool isExternC() const; bool isMultiStatementLine() const; bool isNextWordSharpNonParenHeader(int startChar) const; - bool isNonInStatementArrayBracket() const; + bool isNonInStatementArrayBrace() const; + bool isNumericVariable(string word) const; bool isOkToSplitFormattedLine(); bool isPointerOrReference() const; bool isPointerOrReferenceCentered() const; - bool isPointerOrReferenceVariable(string& word) const; + bool isPointerOrReferenceVariable(const string& word) const; + bool isPointerToPointer(const string& line, int currPos) const; bool isSharpStyleWithParen(const string* header) const; - bool isStructAccessModified(string& firstLine, size_t index) const; - bool isIndentablePreprocessorBlock(string& firstLine, size_t index); - bool isNDefPreprocStatement(string& nextLine_, string& preproc) const; + bool isStructAccessModified(const string& firstLine, size_t index) const; + bool isIndentablePreprocessorBlock(const string& firstLine, size_t index); + bool isNDefPreprocStatement(const string& nextLine_, const string& preproc) const; bool isUnaryOperator() const; - bool isUniformInitializerBracket() const; + bool isUniformInitializerBrace() const; bool isImmediatelyPostCast() const; bool isInExponent() const; bool isInSwitchStatement() const; - bool isNextCharOpeningBracket(int startChar) const; - bool isOkToBreakBlock(BracketType bracketType) const; + bool isNextCharOpeningBrace(int startChar) const; + bool isOkToBreakBlock(BraceType braceType) const; bool isOperatorPaddingDisabled() const; bool pointerSymbolFollows() const; int findObjCColonAlignment() const; @@ -723,6 +778,7 @@ void adjustComments(); void appendChar(char ch, bool canBreakLine); void appendCharInsideComments(); + void appendClosingHeader(); void appendOperator(const string& sequence, bool canBreakLine = true); void appendSequence(const string& sequence, bool canBreakLine = true); void appendSpacePad(); @@ -734,17 +790,18 @@ void checkIfTemplateOpener(); void clearFormattedLineSplitPoints(); void convertTabToSpaces(); - void deleteContainer(vector*& container); + void deleteContainer(vector*& container); + void findReturnTypeSplitPoint(const string& firstLine); void formatArrayRunIn(); void formatRunIn(); - void formatArrayBrackets(BracketType bracketType, bool isOpeningArrayBracket); - void formatClosingBracket(BracketType bracketType); + void formatArrayBraces(BraceType braceType, bool isOpeningArrayBrace); + void formatClosingBrace(BraceType braceType); void formatCommentBody(); void formatCommentOpener(); void formatCommentCloser(); void formatLineCommentBody(); void formatLineCommentOpener(); - void formatOpeningBracket(BracketType bracketType); + void formatOpeningBrace(BraceType braceType); void formatQuoteBody(); void formatQuoteOpener(); void formatPointerOrReference(); @@ -755,7 +812,7 @@ void fixOptionVariableConflicts(); void goForward(int i); void isLineBreakBeforeClosingHeader(); - void initContainer(vector*& container, vector* value); + void initContainer(vector*& container, vector* value); void initNewLine(); void padObjCMethodColon(); void padObjCMethodPrefix(); @@ -765,17 +822,19 @@ void padParens(); void processPreprocessor(); void resetEndOfStatement(); - void setAttachClosingBracketMode(bool state); + void setAttachClosingBraceMode(bool state); void stripCommentPrefix(); void testForTimeToSplitFormattedLine(); void trimContinuationLine(); void updateFormattedLineSplitPointsPointerOrReference(size_t index); size_t findFormattedLineSplitPoint() const; - size_t findNextChar(string& line, char searchChar, int searchStart = 0) const; + size_t findNextChar(const string& line, char searchChar, int searchStart = 0) const; const string* checkForHeaderFollowingComment(const string& firstLine) const; const string* getFollowingOperator() const; string getPreviousWord(const string& line, int currPos) const; - string peekNextText(const string& firstLine, bool endOnEmptyLine = false, bool shouldReset = false) const; + string peekNextText(const string& firstLine, + bool endOnEmptyLine = false, + shared_ptr streamArg = nullptr) const; private: // variables int formatterFileType; @@ -791,8 +850,8 @@ ASSourceIterator* sourceIterator; ASEnhancer* enhancer; - vector* preBracketHeaderStack; - vector* bracketTypeStack; + vector* preBraceHeaderStack; + vector* braceTypeStack; vector* parenStack; vector* structStack; vector* questionMarkStack; @@ -802,28 +861,31 @@ string readyFormattedLine; string verbatimDelimiter; const string* currentHeader; - const string* previousOperator; // used ONLY by pad-oper char currentChar; char previousChar; char previousNonWSChar; char previousCommandChar; char quoteChar; streamoff preprocBlockEnd; int charNum; - int horstmannIndentChars; + int runInIndentChars; int nextLineSpacePadNum; int objCColonAlign; - int preprocBracketTypeStackSize; + int preprocBraceTypeStackSize; int spacePadNum; int tabIncrementIn; int templateDepth; - int blockParenCount; + int squareBracketCount; size_t checksumIn; size_t checksumOut; - size_t currentLineFirstBracketNum; // first bracket location on currentLine + size_t currentLineFirstBraceNum; // first brace location on currentLine size_t formattedLineCommentNum; // comment location on formattedLine size_t leadingSpaces; size_t maxCodeLength; + size_t methodAttachCharNum; + size_t methodAttachLineNum; + size_t methodBreakCharNum; + size_t methodBreakLineNum; // possible split points size_t maxSemi; // probably a 'for' statement @@ -839,8 +901,8 @@ size_t previousReadyFormattedLineLength; FormatStyle formattingStyle; - BracketMode bracketFormatMode; - BracketType previousBracketType; + BraceMode braceFormatMode; + BraceType previousBraceType; PointerAlign pointerAlignment; ReferenceAlign referenceAlignment; ObjCColonPad objCColonPadMode; @@ -862,6 +924,7 @@ bool shouldAttachExternC; bool shouldAttachNamespace; bool shouldAttachClass; + bool shouldAttachClosingWhile; bool shouldAttachInline; bool isInLineComment; bool isInComment; @@ -893,6 +956,7 @@ bool foundInterfaceHeader; bool foundPreCommandHeader; bool foundPreCommandMacro; + bool foundTrailingReturnType; bool foundCastOperator; bool isInLineBreak; bool endOfAsmReached; @@ -907,7 +971,7 @@ bool isLineReady; bool elseHeaderFollowsComments; bool caseHeaderFollowsComments; - bool isPreviousBracketBlockRelated; + bool isPreviousBraceBlockRelated; bool isInPotentialCalculation; bool isCharImmediatelyPostComment; bool isPreviousCharPostComment; @@ -923,21 +987,23 @@ bool isInObjCMethodDefinition; bool isInObjCInterface; bool isInObjCReturnType; + bool isInObjCParam; bool isInObjCSelector; bool breakCurrentOneLineBlock; - bool shouldRemoveNextClosingBracket; - bool isInBracketRunIn; - bool currentLineBeginsWithBracket; - bool attachClosingBracketMode; + bool shouldRemoveNextClosingBrace; + bool isInBraceRunIn; + bool returnTypeChecked; + bool currentLineBeginsWithBrace; + bool attachClosingBraceMode; bool shouldBreakOneLineBlocks; bool shouldBreakOneLineHeaders; bool shouldBreakOneLineStatements; - bool shouldBreakClosingHeaderBrackets; + bool shouldBreakClosingHeaderBraces; bool shouldBreakElseIfs; bool shouldBreakLineAfterLogical; - bool shouldAddBrackets; - bool shouldAddOneLineBrackets; - bool shouldRemoveBrackets; + bool shouldAddBraces; + bool shouldAddOneLineBraces; + bool shouldRemoveBraces; bool shouldPadMethodColon; bool shouldPadMethodPrefix; bool shouldReparseCurrentChar; @@ -947,7 +1013,11 @@ bool shouldPadParamType; bool shouldUnPadParamType; bool shouldDeleteEmptyLines; - bool needHeaderOpeningBracket; + bool shouldBreakReturnType; + bool shouldBreakReturnTypeDecl; + bool shouldAttachReturnType; + bool shouldAttachReturnTypeDecl; + bool needHeaderOpeningBrace; bool shouldBreakLineAtNextChar; bool shouldKeepLineUnbroken; bool passedSemicolon; @@ -972,7 +1042,7 @@ bool isIndentableProprocessor; bool isIndentableProprocessorBlock; bool prependEmptyLine; - bool appendOpeningBracket; + bool appendOpeningBrace; bool foundClosingHeader; bool isInHeader; bool isImmediatelyPostHeader; @@ -984,27 +1054,19 @@ private: // inline functions // append the CURRENT character (curentChar) to the current formatted line. void appendCurrentChar(bool canBreakLine = true) - { - appendChar(currentChar, canBreakLine); - } + { appendChar(currentChar, canBreakLine); } // check if a specific sequence exists in the current placement of the current line bool isSequenceReached(const char* sequence) const - { - return currentLine.compare(charNum, strlen(sequence), sequence) == 0; - } + { return currentLine.compare(charNum, strlen(sequence), sequence) == 0; } // call ASBase::findHeader for the current character const string* findHeader(const vector* headers_) - { - return ASBeautifier::findHeader(currentLine, charNum, headers_); - } + { return ASBase::findHeader(currentLine, charNum, headers_); } // call ASBase::findOperator for the current character - const string* findOperator(const vector* headers_) - { - return ASBeautifier::findOperator(currentLine, charNum, headers_); - } + const string* findOperator(const vector* operators_) + { return ASBase::findOperator(currentLine, charNum, operators_); } }; // Class ASFormatter //----------------------------------------------------------------------------- @@ -1014,7 +1076,7 @@ bool sortOnLength(const string* a, const string* b); bool sortOnName(const string* a, const string* b); -} // end of astyle namespace +} // namespace astyle // end of astyle namespace -------------------------------------------------- diff --git a/plugins/astyle/astyle_formatter.h b/plugins/astyle/astyle_formatter.h --- a/plugins/astyle/astyle_formatter.h +++ b/plugins/astyle/astyle_formatter.h @@ -60,7 +60,7 @@ void setMaxInStatementIndentLength(int max); void setMinConditionalIndentLength(int min); //brackets - void setBracketFormatMode(astyle::BracketMode mode); + void setBracketFormatMode(astyle::BraceMode mode); void setBreakClosingHeaderBracketsMode(bool state); //blocks void setBreakBlocksMode(bool state); diff --git a/plugins/astyle/astyle_formatter.cpp b/plugins/astyle/astyle_formatter.cpp --- a/plugins/astyle/astyle_formatter.cpp +++ b/plugins/astyle/astyle_formatter.cpp @@ -365,7 +365,7 @@ void AStyleFormatter::setBracketIndent(bool on) { m_options[QStringLiteral("IndentBrackets")] = on; - ASFormatter::setBracketIndent(on); + ASFormatter::setBraceIndent(on); } void AStyleFormatter::setCaseIndent(bool on) @@ -417,7 +417,7 @@ ASFormatter::setMinConditionalIndentLength(); } -void AStyleFormatter::setBracketFormatMode(astyle::BracketMode mode) +void AStyleFormatter::setBracketFormatMode(astyle::BraceMode mode) { switch (mode) { case astyle::NONE_MODE: @@ -436,7 +436,7 @@ m_options[QStringLiteral("Brackets")] = QStringLiteral("RunInMode"); break; } - ASFormatter::setBracketFormatMode(mode); + ASFormatter::setBraceFormatMode(mode); } void AStyleFormatter::setBreakClosingHeaderBracketsMode(bool state) diff --git a/plugins/astyle/astyle_stringiterator.h b/plugins/astyle/astyle_stringiterator.h --- a/plugins/astyle/astyle_stringiterator.h +++ b/plugins/astyle/astyle_stringiterator.h @@ -41,7 +41,7 @@ std::string nextLine(bool emptyLineWasDeleted = false) override; std::string peekNextLine() override; void peekReset() override; - + astyle::streamoff getPeekStart() const override; private: QString m_content; QTextStream m_is; diff --git a/plugins/astyle/astyle_stringiterator.cpp b/plugins/astyle/astyle_stringiterator.cpp --- a/plugins/astyle/astyle_stringiterator.cpp +++ b/plugins/astyle/astyle_stringiterator.cpp @@ -72,3 +72,9 @@ m_peekStart = -1; // invalid } +astyle::streamoff AStyleStringIterator::getPeekStart() const +{ + return m_peekStart; +} + + diff --git a/plugins/astyle/kdevastyle.json b/plugins/astyle/kdevastyle.json --- a/plugins/astyle/kdevastyle.json +++ b/plugins/astyle/kdevastyle.json @@ -7,7 +7,7 @@ } ], "Category": "Utilities", - "Description": "A plugin for formatting of sourcecode according to a specified set of rules", + "Description": "A plugin for formatting of sourcecode according to a specified set of rules.\nBased on the Artistic Style formatter v3.1 (https://sourceforge.net/projects/astyle)", "Description[ca@valencia]": "Un connector per a formatar el codi font d'acord a un conjunt especificat de regles", "Description[ca]": "Un connector per a formatar el codi font d'acord a un conjunt especificat de regles", "Description[de]": "Modul zum Formatieren von Quelltext nach bestimmten Vorschriften",