kwstyle-1.0.0+cvs20120330.orig/0000755000175000017500000000000011735330661015432 5ustar mathieumathieukwstyle-1.0.0+cvs20120330.orig/Copyright.txt0000644000175000017500000000330210415052566020140 0ustar mathieumathieu The KWStyle copyright is as follows: Copyright (c) Kitware, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * The name of Kitware Inc., or the name of any contributors, may not be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. See also the KWStyle web site: http://public.kitware.com/KWStyle for more information. kwstyle-1.0.0+cvs20120330.orig/kwsCheckDeclarationOrder.cxx0000755000175000017500000001367511177325234023101 0ustar mathieumathieu/*========================================================================= Program: KWStyle - Kitware Style Checker Module: $RCSfile: kwsCheckDeclarationOrder.cxx,v $ Copyright (c) Kitware, Inc. All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "kwsParser.h" namespace kws { /** Check the order of the declaration */ bool Parser::CheckDeclarationOrder(size_t posPublic, size_t posProtected, size_t posPrivate) { m_TestsDone[DECL_ORDER] = true; char* val = new char[255]; sprintf(val,"Declaration order should match "); m_TestsDescription[DECL_ORDER] = val; if(posPublic>posProtected && posProtected>posPrivate) { m_TestsDescription[DECL_ORDER] += "Private/Protected/Public"; } else if(posPublicposPrivate && posProtectedFindPublicArea(publicFirst,publicLast); size_t class_end = this->FindEndOfClass(publicFirst); size_t class_beg = this->FindOpeningChar('}','{',class_end,true); // Find the first public declaration while(publicFirst!=std::string::npos && publicFirst!=MAX_CHAR && (publicFirstclass_end)) { this->FindPublicArea(publicFirst,publicLast,publicFirst+1); class_end = this->FindEndOfClass(publicFirst); class_beg = this->FindOpeningChar('}','{',class_end,true); } // Currently checking only one class per file (do a loop in the future) size_t currentclass = class_beg; size_t protectedFirst; size_t protectedLast; this->FindProtectedArea(protectedFirst,protectedLast); class_end = this->FindEndOfClass(protectedFirst); class_beg = this->FindOpeningChar('}','{',class_end,true); while(protectedFirst!=std::string::npos && protectedFirst!=MAX_CHAR &&class_beg != currentclass) { this->FindProtectedArea(protectedFirst,protectedLast,protectedFirst+1); class_end = this->FindEndOfClass(protectedFirst); class_beg = this->FindOpeningChar('}','{',class_end,true); } size_t privateFirst; size_t privateLast; this->FindPrivateArea(privateFirst,privateLast); class_end = this->FindEndOfClass(privateFirst); class_beg = this->FindOpeningChar('}','{',class_end,true); while(privateFirst!=std::string::npos && privateFirst!=MAX_CHAR && class_beg != currentclass) { this->FindPrivateArea(privateFirst,privateLast,privateFirst+1); class_end = this->FindEndOfClass(privateFirst); class_beg = this->FindOpeningChar('}','{',class_end,true); } bool hasError = false; // public v.s protected if( (posPublic > posProtected) && (protectedFirst != MAX_CHAR) && (publicFirst != MAX_CHAR) && (protectedFirst > publicFirst) ) { Error error; error.line = this->GetLineNumber(publicFirst,true); error.line2 = this->GetLineNumber(publicFirst,true); error.number = DECL_ORDER; error.description = "Public defined before Protected"; m_ErrorList.push_back(error); hasError = true; } else if( (posPublic < posProtected) && (protectedFirst != MAX_CHAR) && (publicFirst != MAX_CHAR) && (protectedFirst < publicFirst) ) { Error error; error.line = this->GetLineNumber(protectedFirst,true); error.line2 = this->GetLineNumber(protectedFirst,true); error.number = DECL_ORDER; error.description = "Protected defined before Public"; m_ErrorList.push_back(error); hasError = true; } // protected v.s. private if( (posPrivate > posProtected) && (protectedFirst != MAX_CHAR) && (privateFirst != MAX_CHAR) && (protectedFirst > privateFirst) ) { Error error; error.line = this->GetLineNumber(privateFirst,true); error.line2 = this->GetLineNumber(privateFirst,true); error.number = DECL_ORDER; error.description = "Private defined before Protected"; m_ErrorList.push_back(error); hasError = true; } else if( (posPrivate > posProtected) && (protectedFirst != MAX_CHAR) && (privateFirst != MAX_CHAR) && (protectedFirst > privateFirst) ) { Error error; error.line = this->GetLineNumber(protectedFirst,true); error.line2 = this->GetLineNumber(protectedFirst,true); error.number = DECL_ORDER; error.description = "Protected defined before Private"; m_ErrorList.push_back(error); hasError = true; } // Public v.s. Private if( (posPublic > posPrivate) && (privateFirst != MAX_CHAR) && (publicFirst != MAX_CHAR) && (privateFirst > publicFirst) ) { Error error; error.line = this->GetLineNumber(publicFirst,true); error.line2 = this->GetLineNumber(publicFirst,true); error.number = DECL_ORDER; error.description = "Public defined before Private"; m_ErrorList.push_back(error); hasError = true; } else if( (posPublic > posPrivate) && (privateFirst != MAX_CHAR) && (publicFirst != MAX_CHAR) && (privateFirst > publicFirst) ) { Error error; error.line = this->GetLineNumber(privateFirst,true); error.line2 = this->GetLineNumber(privateFirst,true); error.number = DECL_ORDER; error.description = "Private defined before Public"; m_ErrorList.push_back(error); hasError = true; } return !hasError; } } // end namespace kws kwstyle-1.0.0+cvs20120330.orig/kwsCheckEmptyLines.cxx0000644000175000017500000000431011143340104021712 0ustar mathieumathieu/*========================================================================= Program: KWStyle - Kitware Style Checker Module: $RCSfile: kwsCheckEmptyLines.cxx,v $ Copyright (c) Kitware, Inc. All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "kwsParser.h" namespace kws { /** Check the number of succesive empty lines */ bool Parser::CheckEmptyLines(unsigned long max, bool checkEndOfFile) { m_TestsDone[EMPTYLINES] = true; char* val = new char[255]; sprintf(val,"Empty lines = %ld max lines",max); m_TestsDescription[EMPTYLINES] = val; delete [] val; bool hasError = false; unsigned long total = m_Buffer.size(); unsigned long i = 0; unsigned long j = 1; unsigned long empty = 0; while(imax) { bool valid = true; // Check if we are at the end of the file if(!checkEndOfFile) { if(m_Buffer.find_first_not_of("\r\n ",i) == std::string::npos) { valid = false; } } if(valid) { Error error; error.line = j; error.line2 = error.line; error.number = EMPTYLINES; error.description = "Empty lines exceed "; char* val = new char[10]; sprintf(val,"%ld",empty); error.description += val; error.description += " (max="; delete [] val; val = new char[10]; sprintf(val,"%ld",max); error.description += val; error.description += ")"; delete [] val; m_ErrorList.push_back(error); hasError = true; } } j++; i += line.length()+1; } return !hasError; } } // end namespace kws kwstyle-1.0.0+cvs20120330.orig/kwsCheckFunctions.cxx0000644000175000017500000001276011153402351021605 0ustar mathieumathieu/*========================================================================= Program: KWStyle - Kitware Style Checker Module: $RCSfile: kwsCheckFunctions.cxx,v $ Copyright (c) Kitware, Inc. All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "kwsParser.h" namespace kws { /** Check if ANY function implement in the given file is correct */ bool Parser::CheckFunctions(const char* regEx,unsigned long maxLength) { if(regEx) { m_TestsDone[FUNCTION_REGEX] = true; m_TestsDescription[FUNCTION_REGEX] = "Functions should match regular expression: "; m_TestsDescription[FUNCTION_REGEX] += regEx; } if(maxLength>0) { m_TestsDone[FUNCTION_LENGTH] = true; m_TestsDescription[FUNCTION_LENGTH] = "Functions must not exceed: "; char* temp = new char[10]; sprintf(temp,"%ld",maxLength); m_TestsDescription[FUNCTION_LENGTH] += temp; m_TestsDescription[FUNCTION_LENGTH] += " lines"; delete [] temp; } // First we need to find the parameters bool hasError = false; kwssys::RegularExpression regex(regEx); // List all the function in the file long int pos = this->FindFunction(0); while(pos != -1) { // We extract the name of the function std::string functionName = ""; // Find the ) and the openning ( long int i=pos; for(;i>0;i--) { if(m_BufferNoComment[i] == ')') { i = this->FindOpeningChar(')','(',i,true); i--; break; } } bool inWord = false; for(;i>0;i--) { if(m_BufferNoComment[i] != ' ' && m_BufferNoComment[i] != '\t' && m_BufferNoComment[i] != '\r' && m_BufferNoComment[i] != '\n' && m_BufferNoComment[i] != '*' && m_BufferNoComment[i] != '&') { inWord = true; functionName = m_BufferNoComment[i]+functionName; } else if(inWord) { break; } } // Check that this is not a #define (tricky) std::string functionLine = this->GetLine(this->GetLineNumber(i,true)-1); if(functionLine.find("#define") == std::string::npos && functionLine.find("_attribute_") == std::string::npos && functionLine.find(" operator") == std::string::npos && functionLine.find("friend ") == std::string::npos && functionName.find("if") == std::string::npos && functionName.find("while") == std::string::npos && functionName.find("for") == std::string::npos && functionName.find("switch") == std::string::npos && functionName.find("main") == std::string::npos && functionName.find("~") == std::string::npos // skip destructor for now... ) { long int posf = functionName.find("::",0); long int posp = functionName.find("(",posf); if(posp != -1 && posf != -1 && posp>posf) { functionName = functionName.substr(posf+2,posp-posf-2); } else if(posf != -1) { functionName = functionName.substr(posf+2,functionName.size()-posf-2); } } else { functionName = ""; } //std::cout << "Function Name = " << functionName.c_str() << std::endl; if(functionName.size() == 0) { long int bf = m_BufferNoComment.find('{',pos); long int pos2 = this->FindClosingChar('{','}',bf,true); pos = this->FindFunction(pos2+1); // we cannot go backward /*if(pos2 > pos) { long int bf = m_BufferNoComment.find('{',pos2); pos = this->FindFunction(bf); }*/ continue; } else if(functionName.size()>0) { long int bf = m_BufferNoComment.find('{',pos); long int bfcomments = GetPositionWithComments(bf); long int bfl = this->GetLineNumber(bfcomments); long int pos2 = this->FindClosingChar('{','}',bf,true); long int poscomments = GetPositionWithComments(pos2); long int efl = this->GetLineNumber(poscomments); pos = this->FindFunction(pos2+1); // we cannot go backward if(pos2 > pos) { long int bf = m_BufferNoComment.find('{',pos2); pos = this->FindFunction(bf); } if(!regex.find(functionName)) { Error error; error.line = bfl; error.line2 = error.line; error.number = FUNCTION_REGEX; error.description = "function (" + functionName + ") doesn't match regular expression: " + regEx; m_ErrorList.push_back(error); hasError = true; } if(maxLength>0) { if((bfl>-1) && (efl>-1) && (efl-bfl>(long int)maxLength)) { Error error; error.line = bfl; error.line2 = efl; error.number = FUNCTION_LENGTH; error.description = "function (" + functionName + ") has too many lines: "; char* temp = new char[10]; sprintf(temp,"%ld",efl-bfl); error.description += temp; error.description += " ("; sprintf(temp,"%ld",maxLength); error.description += temp; error.description += ")"; m_ErrorList.push_back(error); hasError = true; delete [] temp; } } } } return !hasError; } } // end namespace kws kwstyle-1.0.0+cvs20120330.orig/kwsCheckLineLength.cxx0000755000175000017500000000565211155521350021676 0ustar mathieumathieu/*========================================================================= Program: KWStyle - Kitware Style Checker Module: $RCSfile: kwsCheckLineLength.cxx,v $ Copyright (c) Kitware, Inc. All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "kwsParser.h" namespace kws { /** Check the number of character per line */ bool Parser::CheckLineLength(unsigned long max,bool checkHeader) { m_TestsDone[LINE_LENGTH] = true; char* val = new char[255]; sprintf(val,"Line Length = %ld max chars",max); m_TestsDescription[LINE_LENGTH] = val; delete [] val; m_Positions.clear(); bool hasError = false; size_t fileSize = 0; // If we do not want to check the header if(!checkHeader) { if(m_HeaderFilename.size()>0) { std::ifstream file; file.open(m_HeaderFilename.c_str(), std::ios::binary | std::ios::in); if(!file.is_open()) { std::cout << "CheckLineLength() - Cannot open file: " << m_HeaderFilename << std::endl; } else { file.seekg(0,std::ios::end); fileSize = file.tellg(); file.close(); } } else { // we look at the first '*/' in the file which indicated the end of the current header // This assume that there is an header at some point size_t endHeader = m_Buffer.find("*/",0); if(endHeader != std::string::npos) { fileSize = endHeader; } } } size_t cc; const char* inch = m_Buffer.c_str(); size_t inStrSize = m_Buffer.size(); long int line_start = 0; long int line_end = 0; long int line_count = 1; m_Positions.push_back(0); for ( cc = 0; cc < inStrSize; ++ cc ) { if ( *inch == '\n' ) { m_Positions.push_back(cc); line_end = cc; long int line_length = line_end - line_start-1; if(line_length > (long int)max && cc>fileSize) { Error error; error.line = line_count; error.line2 = error.line; error.number = LINE_LENGTH; error.description = "Line length exceed "; char* val = new char[10]; sprintf(val,"%ld",line_length); error.description += val; error.description += " (max="; delete [] val; val = new char[10]; sprintf(val,"%ld",max); error.description += val; error.description += ")"; delete [] val; m_ErrorList.push_back(error); hasError = true; } line_start = cc + 1; line_count ++; } inch ++; } m_Positions.push_back(cc); return !hasError; } } // end namespace kws kwstyle-1.0.0+cvs20120330.orig/kwsCheckVariables.cxx0000644000175000017500000001646311155521351021555 0ustar mathieumathieu/*========================================================================= Program: KWStyle - Kitware Style Checker Module: $RCSfile: kwsCheckVariables.cxx,v $ Copyright (c) Kitware, Inc. All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "kwsParser.h" namespace kws { /** Check if the variables implementation of the class are correct */ bool Parser::CheckVariables(const char* regEx) { m_TestsDone[VARS] = true; m_TestsDescription[VARS] = "ivars implentation should match regular expression: "; m_TestsDescription[VARS] += regEx; // First we need to find the parameters bool hasError = false; kwssys::RegularExpression regex(regEx); // We first read the .h if any std::string headerfile = kwssys::SystemTools::GetFilenamePath(m_Filename.c_str()); headerfile += "/"; headerfile += kwssys::SystemTools::GetFilenameWithoutExtension(m_Filename.c_str()); headerfile += ".h"; if(!kwssys::SystemTools::FileExists(headerfile.c_str())) { return false; } // We open the file std::ifstream file; file.open(headerfile.c_str(), std::ios::binary | std::ios::in); if(!file.is_open()) { std::cout << "Cannot open file: " << headerfile.c_str() << std::endl; return 1; } file.seekg(0,std::ios::end); size_t fileSize = file.tellg(); file.seekg(0,std::ios::beg); char* buf = new char[fileSize+1]; file.read(buf,fileSize); buf[fileSize] = 0; std::string buffer(buf); buffer.resize(fileSize); delete [] buf; file.close(); this->ConvertBufferToWindowsFileType(buffer); buffer = this->RemoveComments(buffer.c_str()); // Construct the list of variables to check typedef std::pair PairType; std::vector ivars; size_t pos = 0; while(pos != std::string::npos) { std::string var = this->FindVariable(buffer,pos+1,buffer.size(),pos); if(var.size()>0) { std::string correct = ""; for(size_t i=0;iGetLineNumber(pos,true)-1; ivars.push_back(p); } } // Do the checking std::vector::const_iterator it = ivars.begin(); while(it != ivars.end()) { std::string v = (*it).first; long int p =(*it).second; size_t posVar = m_BufferNoComment.find(v); while(posVar != std::string::npos) { // Extract the complete insert of the variable if(!this->IsBetweenQuote(posVar) &&( m_BufferNoComment[posVar-1]=='.' || m_BufferNoComment[posVar-1]=='>' || m_BufferNoComment[posVar-1]=='\n' || m_BufferNoComment[posVar-1]==' ' || m_BufferNoComment[posVar-1]=='(' || m_BufferNoComment[posVar-1]=='[' ) &&( m_BufferNoComment[posVar+v.size()]=='.' || m_BufferNoComment[posVar+v.size()]=='>' || m_BufferNoComment[posVar+v.size()]=='\n' || m_BufferNoComment[posVar+v.size()]==' ' || m_BufferNoComment[posVar+v.size()]=='(' || m_BufferNoComment[posVar+v.size()]=='[' || m_BufferNoComment[posVar+v.size()]==')' || m_BufferNoComment[posVar+v.size()]==']' ) ) { size_t i = posVar-1; while(i>0) { if(m_BufferNoComment[i]==' ' || m_BufferNoComment[i]=='(' || m_BufferNoComment[i]=='[' || m_BufferNoComment[i]=='\n' || m_BufferNoComment[i]=='!' || m_BufferNoComment[i]=='{' || m_BufferNoComment[i]==';' || m_BufferNoComment[i]=='<' || m_BufferNoComment[i]=='*' ) { break; } i--; } std::string var = m_BufferNoComment.substr(i+1,posVar-i+v.size()-1); bool showError = true; // Check if this a macro if(this->GetLineNumber(posVar,true) == p+1) { showError = false; } else { std::string line = this->GetLine(this->GetLineNumber(posVar,true)-1); if(line.find("Macro") != std::string::npos) { showError = false; } } // Check the regex if(showError && !regex.find(var)) { Error error; error.line = this->GetLineNumber(posVar,true); error.line2 = error.line; error.number = VARS; error.description = "variable (" + var + ") doesn't match regular expression"; m_ErrorList.push_back(error); hasError = true; } } posVar = m_BufferNoComment.find(v,posVar+1); } it++; } return !hasError; } /** Find the first ivar in the source code */ std::string Parser::FindVariable(std::string & buffer, size_t start, size_t end,size_t & pos) { size_t posSemicolon = buffer.find(";",start); while(posSemicolon != std::string::npos && posSemicolonIsInFunction(posSemicolon,buffer.c_str()) && !this->IsInStruct(posSemicolon,buffer.c_str()) ) { return ivar; } } posSemicolon = buffer.find(";",posSemicolon+1); } pos = std::string::npos; return ""; } } // end namespace kws kwstyle-1.0.0+cvs20120330.orig/kwsGenerator.h0000755000175000017500000000645110765101226020262 0ustar mathieumathieu/*========================================================================= Program: KWStyle - Kitware Style Checker Module: $RCSfile: kwsGenerator.h,v $ Copyright (c) Kitware, Inc. All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef __kwsGenerator_h #define __kwsGenerator_h #include "kwsParser.h" #include #include #include #include #include namespace kws { const char ErrorColor[NUMBER_ERRORS][8] = { {'#','F','F','C','C','3','3','\0'}, {'#','F','F','C','C','6','6','\0'}, {'#','F','F','F','F','6','6','\0'}, {'#','6','6','6','6','C','C','\0'}, {'#','F','F','F','F','6','6','\0'}, {'#','6','6','6','6','C','C','\0'}, {'#','9','9','F','F','C','C','\0'}, {'#','9','9','C','C','F','F','\0'}, {'#','6','6','6','6','C','C','\0'}, {'#','F','F','C','C','3','3','\0'}, {'#','F','F','C','C','3','3','\0'}, {'#','F','F','C','C','3','3','\0'}, {'#','F','F','9','9','C','C','\0'}, {'#','F','F','9','9','C','C','\0'}, {'#','F','F','3','3','0','0','\0'}, {'#','0','0','a','a','0','0','\0'}, {'#','6','6','0','0','3','3','\0'}, {'#','9','9','C','C','F','F','\0'}, {'#','9','9','C','C','F','F','\0'}, {'#','9','9','C','C','F','F','\0'}, {'#','6','6','C','C','C','C','\0'}, {'#','6','6','6','6','C','C','\0'}, {'#','0','0','0','0','F','F','\0'}, {'#','0','0','0','0','F','F','\0'}, {'#','D','4','D','0','C','8','\0'}, {'#','F','F','F','F','C','C','\0'}, {'#','9','9','C','C','C','C','\0'}, {'#','C','C','C','C','F','F','\0'}, {'#','9','9','C','C','C','C','\0'}, {'#','F','F','3','3','0','0','\0'}, {'#','9','9','C','C','C','C','\0'}, {'#','F','F','3','3','0','0','\0'} }; class Generator { public: typedef std::vector ParserVectorType; /** Constructor */ Generator(); /** Destructor */ ~Generator(); /** Set the buffer to analyze */ void SetParser(ParserVectorType* parsers) { m_Parsers = parsers; } /** Generate the HTML files */ bool GenerateHTML(const char* dir,bool showAllErrors = true); /** Export the HTML report */ void ExportHTML(std::ostream & output); /** Generate dart files */ bool GenerateDart(const char* dir,int maxerror = -1, bool group = false,std::string url="", double time=0, std::string baseDirectory=""); /** Generate a simple XML report of the errors */ bool ExportXML(const char* filename); /** Set the configuration file */ void ReadConfigurationFile(const char* configFile); private: bool CreateHeader(std::ostream * file,const char* title); bool CreateFooter(std::ostream * file); bool GenerateMatrix(const char* dir,bool showAllErrors); bool GenerateDescription(const char* dir); ParserVectorType* m_Parsers; std::string m_ProjectTitle; std::string m_ProjectLogo; std::string m_KWStyleLogo; unsigned int m_MaxDirectoryDepth; unsigned int m_ErrorThreshold; }; } // end namespace kws #endif kwstyle-1.0.0+cvs20120330.orig/kwsCheckBadCharacters.cxx0000644000175000017500000000311111153402351022311 0ustar mathieumathieu/*========================================================================= Program: KWStyle - Kitware Style Checker Module: $RCSfile: kwsCheckBadCharacters.cxx,v $ Copyright (c) Kitware, Inc. All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "kwsParser.h" namespace kws { /** Check if the current file as bad characters like */ bool Parser::CheckBadCharacters(bool checkComments) { m_TestsDone[BADCHARACTERS] = true; m_TestsDescription[BADCHARACTERS] = "Checking for bad characters"; std::string buffer = m_BufferNoComment; if(checkComments) { buffer = m_Buffer; } bool hasErrors = false; unsigned long pos = 0; std::string::const_iterator it = buffer.begin(); long int currentline = -1; while(it!= buffer.end()) { if((*it)<0) { long int linenum = this->GetLineNumber(pos,!checkComments); if(linenum != currentline) { currentline = linenum; Error error; error.line = linenum; error.line2 = error.line; error.number = BADCHARACTERS; error.description = "Bad character"; m_ErrorList.push_back(error); hasErrors = true; } } pos++; it++; } return !hasErrors; } } // end namespace kws kwstyle-1.0.0+cvs20120330.orig/metaCommand.cxx0000644000175000017500000012532611156172254020413 0ustar mathieumathieu/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: metaCommand.cxx,v $ Language: C++ Date: $Date: 2009-03-12 11:40:28 $ Version: $Revision: 1.7 $ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "metaCommand.h" #include #include // atoi #include #include #if (METAIO_USE_NAMESPACE) namespace METAIO_NAMESPACE { #endif MetaCommand::MetaCommand() { m_HelpCallBack = NULL; m_OptionVector.clear(); m_Version = "Not defined"; m_Date = "Not defined"; m_Name = ""; m_Author = "Not defined"; m_Description = ""; m_ParsedOptionVector.clear(); m_Verbose = true; } /** Extract the date from the $Date: 2009-03-12 11:40:28 $ cvs command */ METAIO_STL::string MetaCommand::ExtractDateFromCVS(METAIO_STL::string date) { METAIO_STL::string newdate; for(int i=7;i<(int)date.size()-1;i++) { newdate += date[i]; } return newdate.c_str(); } /** */ bool MetaCommand::SetOption(Option option) { // need to add some tests here to check if the option is not defined yet m_OptionVector.push_back(option); return true; } bool MetaCommand::SetOption(METAIO_STL::string name, METAIO_STL::string tag, bool required, METAIO_STL::string description, METAIO_STL::vector fields) { // need to add some tests here to check if the option is not defined yet if(tag == "") { METAIO_STREAM::cout << "Tag cannot be empty : use AddField() instead." << METAIO_STREAM::endl; return false; } Option option; option.name = name; option.tag = tag; option.fields = fields; option.required = required; option.description = description; option.userDefined = false; option.complete = false; m_OptionVector.push_back(option); return true; } bool MetaCommand::SetOption(METAIO_STL::string name, METAIO_STL::string tag, bool required, METAIO_STL::string description, TypeEnumType type, METAIO_STL::string defVal) { // need to add some tests here to check if the option is not defined yet if(tag == "") { METAIO_STREAM::cout << "Tag cannot be empty : use AddField() instead." << METAIO_STREAM::endl; return false; } Option option; option.tag = tag; option.name = name; option.required = required; option.description = description; option.userDefined = false; option.complete = false; // Create a field without description as a flag Field field; if(type == LIST) { field.name = "NumberOfValues"; } else { field.name = name; } field.externaldata = DATA_NONE; field.type = type; field.value = defVal; field.userDefined = false; field.required = true; field.rangeMin = ""; field.rangeMax = ""; option.fields.push_back(field); m_OptionVector.push_back(option); return true; } /** Add a field */ bool MetaCommand::AddField(METAIO_STL::string name, METAIO_STL::string description, TypeEnumType type, DataEnumType externalData, METAIO_STL::string rangeMin, METAIO_STL::string rangeMax) { // need to add some tests here to check if the option is not defined yet Option option; option.tag = ""; // Create a field without description with the specified type Field field; field.name = name; field.type = type; field.required = true; field.userDefined = false; field.externaldata = externalData; field.rangeMin = rangeMin; field.rangeMax = rangeMax; option.fields.push_back(field); option.required = true; option.name = name; option.description = description; option.userDefined = false; option.complete = false; m_OptionVector.push_back(option); return true; } /** Collect all the information until the next tag * \warning this function works only if the field is of type String */ void MetaCommand::SetOptionComplete(METAIO_STL::string optionName, bool complete) { OptionVector::iterator it = m_OptionVector.begin(); while(it != m_OptionVector.end()) { if((*it).name == optionName) { (*it).complete = complete; return; } it++; } } /** Add a field to a given an option */ bool MetaCommand::AddOptionField(METAIO_STL::string optionName, METAIO_STL::string name, TypeEnumType type, bool required, METAIO_STL::string defVal, METAIO_STL::string description, DataEnumType externalData ) { OptionVector::iterator it = m_OptionVector.begin(); while(it != m_OptionVector.end()) { if((*it).name == optionName) { // Create a field without description with the specified type Field field; field.name = name; field.type = type; field.required = required; field.value = defVal; field.description = description; field.userDefined = false; field.externaldata = externalData; field.rangeMin = ""; field.rangeMax = ""; // If this is the first field in the list we replace the current field if((*it).fields[0].type == FLAG) { (*it).fields[0] = field; } else { (*it).fields.push_back(field); } return true; } it++; } return false; } /** Set the range of an option */ bool MetaCommand::SetOptionRange(METAIO_STL::string optionName, METAIO_STL::string name, METAIO_STL::string rangeMin, METAIO_STL::string rangeMax) { OptionVector::iterator it = m_OptionVector.begin(); while(it != m_OptionVector.end()) { if((*it).name == optionName) { METAIO_STL::vector & fields = (*it).fields; METAIO_STL::vector::iterator itField = fields.begin(); while(itField != fields.end()) { if((*itField).name == name) { (*itField).rangeMin = rangeMin; (*itField).rangeMax = rangeMax; return true; } itField++; } } it++; } return false; } /** Return the value of the option as a boolean */ bool MetaCommand::GetValueAsBool(METAIO_STL::string optionName,METAIO_STL::string fieldName) { METAIO_STL::string fieldname = fieldName; if(fieldName == "") { fieldname = optionName; } OptionVector::const_iterator it = m_OptionVector.begin(); while(it != m_OptionVector.end()) { if((*it).name == optionName) { METAIO_STL::vector::const_iterator itField = (*it).fields.begin(); while(itField != (*it).fields.end()) { if((*itField).name == fieldname) { if((*itField).value == "true" || (*itField).value == "1" || (*itField).value == "True" || (*itField).value == "TRUE" ) { return true; } return false; } itField++; } } it++; } return false; } /** Return the value of the option as a bool */ bool MetaCommand::GetValueAsBool(Option option,METAIO_STL::string fieldName) { METAIO_STL::string fieldname = fieldName; if(fieldName == "") { fieldname = option.name; } METAIO_STL::vector::const_iterator itField = option.fields.begin(); while(itField != option.fields.end()) { if((*itField).name == fieldname) { if((*itField).value == "true" || (*itField).value == "1" || (*itField).value == "True" || (*itField).value == "TRUE" ) { return true; } return false; } itField++; } return 0; } /** Return the value of the option as a float */ float MetaCommand::GetValueAsFloat(METAIO_STL::string optionName,METAIO_STL::string fieldName) { METAIO_STL::string fieldname = fieldName; if(fieldName == "") { fieldname = optionName; } OptionVector::const_iterator it = m_OptionVector.begin(); while(it != m_OptionVector.end()) { if((*it).name == optionName) { METAIO_STL::vector::const_iterator itField = (*it).fields.begin(); while(itField != (*it).fields.end()) { if((*itField).name == fieldname) { return (float)atof((*itField).value.c_str()); } itField++; } } it++; } return 0; } /** Return the value of the option as a float */ float MetaCommand::GetValueAsFloat(Option option,METAIO_STL::string fieldName) { METAIO_STL::string fieldname = fieldName; if(fieldName == "") { fieldname = option.name; } METAIO_STL::vector::const_iterator itField = option.fields.begin(); while(itField != option.fields.end()) { if((*itField).name == fieldname) { return (float)atof((*itField).value.c_str()); } itField++; } return 0; } /** Return the value of the option as a int */ int MetaCommand::GetValueAsInt(METAIO_STL::string optionName,METAIO_STL::string fieldName) { METAIO_STL::string fieldname = fieldName; if(fieldName == "") { fieldname = optionName; } OptionVector::const_iterator it = m_OptionVector.begin(); while(it != m_OptionVector.end()) { if((*it).name == optionName) { METAIO_STL::vector::const_iterator itField = (*it).fields.begin(); while(itField != (*it).fields.end()) { if((*itField).name == fieldname) { return atoi((*itField).value.c_str()); } itField++; } } it++; } return 0; } /** Return the value of the option as a int */ int MetaCommand::GetValueAsInt(Option option,METAIO_STL::string fieldName) { METAIO_STL::string fieldname = fieldName; if(fieldName == "") { fieldname = option.name; } METAIO_STL::vector::const_iterator itField = option.fields.begin(); while(itField != option.fields.end()) { if((*itField).name == fieldname) { return atoi((*itField).value.c_str()); } itField++; } return 0; } /** Return the value of the option as a string */ METAIO_STL::string MetaCommand::GetValueAsString(METAIO_STL::string optionName, METAIO_STL::string fieldName) { METAIO_STL::string fieldname = fieldName; if(fieldName == "") { fieldname = optionName; } OptionVector::const_iterator it = m_OptionVector.begin(); while(it != m_OptionVector.end()) { if((*it).name == optionName) { METAIO_STL::vector::const_iterator itField = (*it).fields.begin(); while(itField != (*it).fields.end()) { if((*itField).name == fieldname) { return (*itField).value; } itField++; } } it++; } return ""; } /** Return the value of the option as a string */ METAIO_STL::string MetaCommand::GetValueAsString(Option option,METAIO_STL::string fieldName) { METAIO_STL::string fieldname = fieldName; if(fieldName == "") { fieldname = option.name; } METAIO_STL::vector::const_iterator itField = option.fields.begin(); while(itField != option.fields.end()) { if((*itField).name == fieldname) { return (*itField).value; } itField++; } return ""; } /** Return the value of the option as a list of strings */ METAIO_STL::list MetaCommand:: GetValueAsList( Option option ) { METAIO_STL::list results; results.clear(); METAIO_STL::vector::const_iterator itField = option.fields.begin(); itField++; while(itField != option.fields.end()) { results.push_back((*itField).value); itField++; } return results; } METAIO_STL::list< METAIO_STL::string > MetaCommand:: GetValueAsList( METAIO_STL::string optionName ) { OptionVector::const_iterator it = m_OptionVector.begin(); while(it != m_OptionVector.end()) { if((*it).name == optionName) { return this->GetValueAsList( *it ); } it++; } METAIO_STL::list< METAIO_STL::string > empty; empty.clear(); return empty; } bool MetaCommand:: GetOptionWasSet(Option option) { if(option.userDefined) { return true; } return false; } bool MetaCommand:: GetOptionWasSet( METAIO_STL::string optionName) { OptionVector::const_iterator it = m_ParsedOptionVector.begin(); while(it != m_ParsedOptionVector.end()) { if((*it).name == optionName) { return true; } it++; } return false; } /** List the current options */ void MetaCommand::ListOptions() { OptionVector::const_iterator it = m_OptionVector.begin(); int i=0; while(it != m_OptionVector.end()) { METAIO_STREAM::cout << "Option #" << i << METAIO_STREAM::endl; METAIO_STREAM::cout << " Name: " << (*it).name.c_str() << METAIO_STREAM::endl; if((*it).tag.size() > 0) { METAIO_STREAM::cout << " Tag: " << (*it).tag.c_str() << METAIO_STREAM::endl; } METAIO_STREAM::cout << " Description: " << (*it).description.c_str() << METAIO_STREAM::endl; if((*it).required) { METAIO_STREAM::cout << " Required: true" << METAIO_STREAM::endl; } else { METAIO_STREAM::cout << " Required: false" << METAIO_STREAM::endl; } METAIO_STREAM::cout << " Number of expeted values: " << (*it).fields.size() << METAIO_STREAM::endl; METAIO_STL::vector::const_iterator itField = (*it).fields.begin(); while(itField != (*it).fields.end()) { METAIO_STREAM::cout << " Field Name: " << (*itField).name.c_str() << METAIO_STREAM::endl; METAIO_STREAM::cout << " Description: " << (*itField).description.c_str() << METAIO_STREAM::endl; METAIO_STREAM::cout << " Type: " << this->TypeToString((*itField).type).c_str() << METAIO_STREAM::endl; METAIO_STREAM::cout << " Value: " << (*itField).value.c_str() << METAIO_STREAM::endl; if((*itField).externaldata) { METAIO_STREAM::cout << " External Data: true" << METAIO_STREAM::endl; } else { METAIO_STREAM::cout << " External Data: false" << METAIO_STREAM::endl; } if((*itField).required) { METAIO_STREAM::cout << " Required: true" << METAIO_STREAM::endl; } else { METAIO_STREAM::cout << " Required: false" << METAIO_STREAM::endl; } itField++; } METAIO_STREAM::cout << METAIO_STREAM::endl; i++; it++; } if(m_HelpCallBack != NULL) { m_HelpCallBack(); } } /** List the current options in xml format */ void MetaCommand::ListOptionsXML() { OptionVector::const_iterator it = m_OptionVector.begin(); int i=0; while(it != m_OptionVector.end()) { METAIO_STREAM::cout << "" << METAIO_STREAM::endl; i++; it++; } } /** Internal small XML parser */ METAIO_STL::string MetaCommand::GetXML(const char* buffer, const char* desc, unsigned long pos) { METAIO_STL::string begin = "<"; begin += desc; begin += ">"; METAIO_STL::string end = ""; METAIO_STL::string buf = buffer; size_t posb = buf.find(begin,pos); if(posb == std::string::npos) { return ""; } size_t pose = buf.find(end,posb); if(pose == std::string::npos) { return ""; } return buf.substr(posb+begin.size(),pose-posb-begin.size()); } /** Given an XML buffer fill in the command line arguments */ bool MetaCommand::ParseXML(const char* buffer) { m_OptionVector.clear(); METAIO_STL::string buf = this->GetXML(buffer,"option",0); long pos = 0; while(buf.size() > 0) { Option option; option.name = this->GetXML(buf.c_str(),"name",0); option.tag = this->GetXML(buf.c_str(),"tag",0); option.description = this->GetXML(buf.c_str(),"description",0); if(atoi(this->GetXML(buf.c_str(),"required",0).c_str()) == 0) { option.required = false; } else { option.required = true; } unsigned int n = atoi(this->GetXML(buf.c_str(),"nvalues",0).c_str()); // Now check the fields long posF = buf.find(""); for(unsigned int i=0;iGetXML(buf.c_str(),"field",posF); Field field; field.userDefined = false; field.name = this->GetXML(f.c_str(),"name",0); field.description = this->GetXML(f.c_str(),"description",0); field.value = this->GetXML(f.c_str(),"value",0); field.type = this->StringToType(this->GetXML(f.c_str(),"type",0).c_str()); if(atoi(this->GetXML(f.c_str(),"external",0).c_str()) == 0) { field.externaldata = DATA_NONE; } else { if(atoi(this->GetXML(f.c_str(),"external",0).c_str()) == 1) { field.externaldata = DATA_IN; } else { field.externaldata = DATA_OUT; } } if(atoi(this->GetXML(f.c_str(),"required",0).c_str()) == 0) { field.required = false; } else { field.required = true; } option.fields.push_back(field); posF += f.size()+8; } m_OptionVector.push_back(option); pos += buf.size()+17; buf = this->GetXML(buffer,"option",pos); } return true; } /** List the current options */ void MetaCommand::ListOptionsSimplified() { OptionVector::const_iterator it = m_OptionVector.begin(); while(it != m_OptionVector.end()) { if(!(*it).required) { METAIO_STREAM::cout << " [ "; } else { METAIO_STREAM::cout << " "; } if((*it).tag.size() > 0) { METAIO_STREAM::cout << "-" << (*it).tag.c_str() << " "; } METAIO_STL::vector::const_iterator itField = (*it).fields.begin(); while(itField != (*it).fields.end()) { if((*itField).type != FLAG) // only display the type if it's not a FLAG { if((*itField).required) { METAIO_STREAM::cout << "<"; } else { METAIO_STREAM::cout << "["; } METAIO_STREAM::cout << (*itField).name.c_str(); if((*itField).required) { METAIO_STREAM::cout << "> "; } else { METAIO_STREAM::cout << "] "; } } itField++; } if(!(*it).required) { METAIO_STREAM::cout << "]"; } METAIO_STREAM::cout << METAIO_STREAM::endl; if((*it).description.size()>0) { METAIO_STREAM::cout << " = " << (*it).description.c_str(); METAIO_STREAM::cout << METAIO_STREAM::endl; itField = (*it).fields.begin(); while(itField != (*it).fields.end()) { if((*itField).description.size() > 0 || (*itField).value.size() > 0) { METAIO_STREAM::cout << " With: " << (*itField).name.c_str(); if((*itField).description.size() > 0) { METAIO_STREAM::cout << " = " << (*itField).description.c_str(); } if((*itField).value.size() > 0) { METAIO_STREAM::cout << " (Default = " << (*itField).value << ")"; } METAIO_STREAM::cout << METAIO_STREAM::endl; } itField++; } } METAIO_STREAM::cout << METAIO_STREAM::endl; it++; } if(m_HelpCallBack != NULL) { m_HelpCallBack(); } } /** Get the option by "-"+tag */ bool MetaCommand::OptionExistsByMinusTag(METAIO_STL::string minusTag) { OptionVector::const_iterator it = m_OptionVector.begin(); while(it != m_OptionVector.end()) { METAIO_STL::string tagToSearch = "-"; tagToSearch += (*it).tag; if(tagToSearch == minusTag) { return true; } it++; } return false; } /** Get the option by "-"+tag */ MetaCommand::Option * MetaCommand::GetOptionByMinusTag(METAIO_STL::string minusTag) { OptionVector::iterator it = m_OptionVector.begin(); while(it != m_OptionVector.end()) { METAIO_STL::string tagToSearch = "-"; tagToSearch += (*it).tag; if(tagToSearch == minusTag) { return &(*it); } it++; } return NULL; } /** Get the option by tag */ MetaCommand::Option * MetaCommand::GetOptionByTag(METAIO_STL::string minusTag) { OptionVector::iterator it = m_OptionVector.begin(); while(it != m_OptionVector.end()) { if((*it).tag == minusTag) { return &(*it); } it++; } return NULL; } /** Return the option id. i.e the position in the vector */ long MetaCommand::GetOptionId(Option* option) { OptionVector::iterator it = m_OptionVector.begin(); unsigned long i = 0; while(it != m_OptionVector.end()) { if(&(*it) == option) { return i; } i++; it++; } return -1; } /** Export the current command line arguments to a Grid Application * Description file */ bool MetaCommand::ExportGAD(bool dynamic) { METAIO_STREAM::cout << "Exporting GAD file..."; OptionVector options = m_OptionVector; if(dynamic) { options = m_ParsedOptionVector; } if(m_Name=="") { METAIO_STREAM::cout << "Set the name of the application using SetName()" << METAIO_STREAM::endl; return false; } METAIO_STL::string filename = m_Name; filename += ".gad.xml"; METAIO_STREAM::ofstream file; file.open(filename.c_str(), METAIO_STREAM::ios::binary | METAIO_STREAM::ios::out); if(!file.is_open()) { METAIO_STREAM::cout << "Cannot open file for writing: " << filename.c_str() << METAIO_STREAM::endl; return false; } file << "" << METAIO_STREAM::endl; file << "" << METAIO_STREAM::endl; file << "" << METAIO_STREAM::endl; file << "" << METAIO_STREAM::endl; file << METAIO_STREAM::endl; unsigned int order = 1; // Write out the input data to be transfered OptionVector::const_iterator it = options.begin(); while(it != options.end()) { METAIO_STL::vector::const_iterator itFields = (*it).fields.begin(); while(itFields != (*it).fields.end()) { if((*itFields).externaldata == DATA_IN) { file << " " << METAIO_STREAM::endl; file << " " << METAIO_STREAM::endl; file << " " << METAIO_STREAM::endl; file << " " << METAIO_STREAM::endl; file << " " << METAIO_STREAM::endl; file << " " << METAIO_STREAM::endl; file << " " << METAIO_STREAM::endl; METAIO_STL::string datapath = (*itFields).value; size_t slash = datapath.find_last_of("/"); if(slash>0) { datapath = datapath.substr(slash+1,datapath.size()-slash-1); } slash = datapath.find_last_of("\\"); if(slash>0) { datapath = datapath.substr(slash+1,datapath.size()-slash-1); } file << " " << METAIO_STREAM::endl; file << " " << METAIO_STREAM::endl; file << METAIO_STREAM::endl; order++; } itFields++; } it++; } file << " " << METAIO_STREAM::endl; file << " " << METAIO_STREAM::endl; file << " " << METAIO_STREAM::endl; // Write out the arguments that are not data it = options.begin(); while(it != options.end()) { // Find if this is a non data field bool isData = false; METAIO_STL::vector::const_iterator itFields = (*it).fields.begin(); while(itFields != (*it).fields.end()) { if((*itFields).externaldata != DATA_NONE) { isData = true; break; } itFields++; } if(isData) { it++; continue; } file << " 0) { file << "-" << (*it).tag.c_str() << " "; } itFields = (*it).fields.begin(); while(itFields != (*it).fields.end()) { if(itFields != (*it).fields.begin()) { file << " "; } file << "{" << (*it).name << (*itFields).name << "}"; itFields++; } file << "\""; if(!(*it).required) { file << " optional=\"true\""; // Add if the option was selected if((*it).userDefined) { file << " selected=\"true\""; } else { file << " selected=\"false\""; } } file << ">" << METAIO_STREAM::endl; // Now writes the value of the arguments itFields = (*it).fields.begin(); while(itFields != (*it).fields.end()) { file << " TypeToString((*itFields).type).c_str(); file << "\""; if((*itFields).rangeMin != "") { file << " rangeMin=\"" << (*itFields).rangeMin << "\""; } if((*itFields).rangeMax != "") { file << " rangeMax=\"" << (*itFields).rangeMax << "\""; } file << "/>" << METAIO_STREAM::endl; itFields++; } file << " " << METAIO_STREAM::endl; it++; } file << " " << METAIO_STREAM::endl; order++; file << METAIO_STREAM::endl; // Write out the input data to be transfered it = options.begin(); while(it != options.end()) { METAIO_STL::vector::const_iterator itFields = (*it).fields.begin(); while(itFields != (*it).fields.end()) { if((*itFields).externaldata == DATA_OUT) { file << " " << METAIO_STREAM::endl; file << " " << METAIO_STREAM::endl; file << " " << METAIO_STREAM::endl; file << " " << METAIO_STREAM::endl; file << " " << METAIO_STREAM::endl; file << " " << METAIO_STREAM::endl; METAIO_STL::string datapath = (*itFields).value; size_t slash = datapath.find_last_of("/"); if(slash>0) { datapath = datapath.substr(slash+1,datapath.size()-slash-1); } slash = datapath.find_last_of("\\"); if(slash>0) { datapath = datapath.substr(slash+1,datapath.size()-slash-1); } file << " " << METAIO_STREAM::endl; file << " " << METAIO_STREAM::endl; file << " " << METAIO_STREAM::endl; file << METAIO_STREAM::endl; order++; } itFields++; } it++; } file << " " << METAIO_STREAM::endl; file << " " << METAIO_STREAM::endl; file << "" << METAIO_STREAM::endl; file.close(); METAIO_STREAM::cout << "done" << METAIO_STREAM::endl; return true; } /** Parse the command line */ bool MetaCommand::Parse(int argc, char* argv[]) { m_ExecutableName = argv[0]; size_t slash = m_ExecutableName.find_last_of("/"); if(slash>0) { m_ExecutableName = m_ExecutableName.substr(slash+1,m_ExecutableName.size()-slash-1); } slash = m_ExecutableName.find_last_of("\\"); if(slash>0) { m_ExecutableName = m_ExecutableName.substr(slash+1,m_ExecutableName.size()-slash-1); } // List the options if using -V if((argc == 2 && !strcmp(argv[1],"-V")) || (argc == 2 && !strcmp(argv[1],"-H"))) { METAIO_STREAM::cout << "Usage : " << argv[0] << METAIO_STREAM::endl; this->ListOptions(); return false; } // List the options if using -v else if((argc == 2 && !strcmp(argv[1],"-v")) || (argc == 2 && !strcmp(argv[1],"-h"))) { METAIO_STREAM::cout << "Usage : " << argv[0] << METAIO_STREAM::endl; this->ListOptionsSimplified(); return false; } else if(argc == 2 && !strcmp(argv[1],"-vxml")) { this->ListOptionsXML(); return false; } else if(argc == 2 && !strcmp(argv[1],"-version")) { METAIO_STREAM::cout << "Version: " << m_Version.c_str() << METAIO_STREAM::endl; return false; } else if(argc == 2 && !strcmp(argv[1],"-date")) { METAIO_STREAM::cout << "Date: " << m_Date.c_str() << METAIO_STREAM::endl; return false; } else if(argc == 2 && !strcmp(argv[1],"-exportGAD")) { this->ExportGAD(); return false; } // Fill in the results m_ParsedOptionVector.clear(); bool inArgument = false; METAIO_STL::string tag = ""; METAIO_STL::string args; unsigned int currentField = 0; // current field position int currentOption = 0; // id of the option to fill unsigned int valuesRemaining=0; bool isComplete = false; // check if the option should be parse until the next tag is found METAIO_STL::string completeString = ""; bool exportGAD = false; for(unsigned int i=1;i<(unsigned int)argc;i++) { // If we have the tag -export-gad if(!strcmp(argv[i],"-exportGAD")) { exportGAD = true; continue; } // If this is a tag if(argv[i][0] == '-' && (atof(argv[i])==0) && (strlen(argv[i])>1)) { // if we have a tag before the expected values we throw an exception if(valuesRemaining!=0) { if(!isComplete) { METAIO_STREAM::cout << "Found tag before end of value list!" << METAIO_STREAM::endl; return false; } else { m_OptionVector[currentOption].fields[0].value = completeString; m_OptionVector[currentOption].fields[0].userDefined = true; m_OptionVector[currentOption].userDefined = true; m_ParsedOptionVector.push_back(m_OptionVector[currentOption]); } } inArgument = false; // New tag so we add the previous values to the tag tag = argv[i]; // Check if the tag is in the list if(this->OptionExistsByMinusTag(tag)) { inArgument = true; valuesRemaining = this->GetOptionByMinusTag(tag)->fields.size(); currentOption = this->GetOptionId(this->GetOptionByMinusTag(tag)); if(currentOption < 0) { METAIO_STREAM::cout << "Error processing tag " << tag.c_str() << ". Tag exists but cannot find its Id." << METAIO_STREAM::endl; } else { isComplete = m_OptionVector[currentOption].complete; if(m_OptionVector[currentOption].fields[0].type == FLAG) { // the tag exists by default m_OptionVector[currentOption].fields[0].value = "true"; valuesRemaining = 0; inArgument = false; } else if(m_OptionVector[currentOption].fields[0].type == LIST) { inArgument = true; unsigned int valuesInList = (int)atoi(argv[++i]); m_OptionVector[currentOption].fields[0].value = argv[i]; valuesRemaining += valuesInList-1; char optName[255]; for(unsigned int j=0; jAddOptionField( m_OptionVector[currentOption].name, optName, STRING ); } } args = ""; } } else if(m_Verbose) { METAIO_STREAM::cout << "The tag " << tag.c_str() << " is not a valid argument : skipping this tag" << METAIO_STREAM::endl; } if(inArgument) { i++; } } else if(!inArgument) // If this is a field { // Look for the field to add OptionVector::iterator it = m_OptionVector.begin(); unsigned long pos = 0; bool found = false; while(it != m_OptionVector.end()) { if((pos >= currentField) && ((*it).tag=="")) { currentOption = pos; valuesRemaining = (*it).fields.size(); found = true; break; } pos++; it++; } if(!found && m_Verbose) { METAIO_STREAM::cout << "Too many arguments specified in your command line! " << "Skipping extra argument: " << argv[i] << METAIO_STREAM::endl; } inArgument=true; currentField=currentOption+1; } // We collect the values if(isComplete) { if(completeString.size()==0) { completeString = argv[i]; } else { completeString += " "; completeString += argv[i]; } } else if(inArgument && i<(unsigned int)argc && valuesRemaining>0) { if(currentOption >=0 && currentOption < (int)(m_OptionVector.size())) { unsigned long s = m_OptionVector[currentOption].fields.size(); m_OptionVector[currentOption].fields[s-valuesRemaining].value = argv[i]; m_OptionVector[currentOption].fields[s-valuesRemaining].userDefined = true; } valuesRemaining--; } if(valuesRemaining == 0) { inArgument = false; m_OptionVector[currentOption].userDefined = true; m_ParsedOptionVector.push_back(m_OptionVector[currentOption]); } } if(valuesRemaining>0) { METAIO_STREAM::cout << "Not enough parameters for " << m_OptionVector[currentOption].name << METAIO_STREAM::endl; METAIO_STREAM::cout << "Command: " << argv[0] << METAIO_STREAM::endl; METAIO_STREAM::cout << "Options: " << METAIO_STREAM::endl << " -v or -h for help listed in short format" << METAIO_STREAM::endl << " -V or -H for help listed in long format" << METAIO_STREAM::endl << " -vxml for help listed in xml format" << METAIO_STREAM::endl << " -export-gad to export Grid Application" << "Description file format" << METAIO_STREAM::endl; return false; } // Check if the options with required arguments are defined OptionVector::iterator it = m_OptionVector.begin(); bool requiredAndNotDefined = false; while(it != m_OptionVector.end()) { if((*it).required) { // First check if the option is actually defined if(!(*it).userDefined) { METAIO_STREAM::cout << "Option " << (*it).name << " is required but not defined" << METAIO_STREAM::endl; requiredAndNotDefined = true; it++; continue; } // Check if the values are defined METAIO_STL::vector::const_iterator itFields = (*it).fields.begin(); bool defined = true; while(itFields != (*it).fields.end()) { if((*itFields).value == "") { defined = false; } itFields++; } if(!defined) { if((*it).tag.size()>0) { METAIO_STREAM::cout << "Field " << (*it).tag.c_str() << " is required but not defined" << METAIO_STREAM::endl; } else { METAIO_STREAM::cout << "Field " << (*it).name.c_str() << " is required but not defined" << METAIO_STREAM::endl; } requiredAndNotDefined = true; } } it++; } if(requiredAndNotDefined) { METAIO_STREAM::cout << "Command: " << argv[0] << METAIO_STREAM::endl << "Options: " << METAIO_STREAM::endl << " -v or -h for help listed in short format" << METAIO_STREAM::endl << " -V or -H for help listed in long format" << METAIO_STREAM::endl << " -vxml for help listed in xml format" << METAIO_STREAM::endl << " -export-gad to export Grid Application" << "Description file format" << METAIO_STREAM::endl; return false; } // Check if the values are in range (if the range is defined) OptionVector::iterator itParsed = m_ParsedOptionVector.begin(); bool valueInRange = true; while(itParsed != m_ParsedOptionVector.end()) { METAIO_STL::vector::const_iterator itFields = (*itParsed).fields.begin(); while(itFields != (*itParsed).fields.end()) { // Check only if this is a number if(((*itFields).type == INT || (*itFields).type == FLOAT || (*itFields).type == CHAR) && ((*itFields).value != "") ) { // Check the range min if( (((*itFields).rangeMin != "") && (atof((*itFields).rangeMin.c_str())>atof((*itFields).value.c_str()))) || (((*itFields).rangeMax != "") && (atof((*itFields).rangeMax.c_str())ExportGAD(true); return false; // prevent from running the application } return true; } /** Return the string representation of a type */ METAIO_STL::string MetaCommand::TypeToString(TypeEnumType type) { switch(type) { case INT: return "int"; case FLOAT: return "float"; case STRING: return "string"; case LIST: return "list"; case FLAG: return "flag"; case BOOL: return "boolean"; default: return "not defined"; } } /** Return a type given a string */ MetaCommand::TypeEnumType MetaCommand::StringToType(const char* type) { if(!strcmp(type,"int")) { return INT; } else if(!strcmp(type,"float")) { return FLOAT; } else if(!strcmp(type,"string")) { return STRING; } else if(!strcmp(type,"list")) { return LIST; } else if(!strcmp(type,"flag")) { return FLAG; } return INT; // by default } #if (METAIO_USE_NAMESPACE) }; #endif kwstyle-1.0.0+cvs20120330.orig/kwsCheckTypedefs.cxx0000755000175000017500000001422711155521351021427 0ustar mathieumathieu/*========================================================================= Program: KWStyle - Kitware Style Checker Module: $RCSfile: kwsCheckTypedefs.cxx,v $ Copyright (c) Kitware, Inc. All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "kwsParser.h" namespace kws { /** Check if the typedefs of the class are correct */ bool Parser::CheckTypedefs(const char* regEx, bool alignment,unsigned int maxLength) { if(alignment) { m_TestsDone[TYPEDEF_ALIGN] = true; char* val = new char[255]; sprintf(val,"Typedefs should be aligned"); m_TestsDescription[TYPEDEF_ALIGN] = val; delete [] val; } m_TestsDone[TYPEDEF_REGEX] = true; m_TestsDescription[TYPEDEF_REGEX] = "Typedefs should match regular expression: "; m_TestsDescription[TYPEDEF_REGEX] += regEx; // First we need to find the typedefs // typedef type MyTypeDef; bool hasError = false; kwssys::RegularExpression regex(regEx); size_t previousline = 0; size_t previouspos = 0; size_t pos = 0; while(pos!= std::string::npos) { size_t beg = 0; size_t typedefpos = 0; std::string var = this->FindTypedef(pos+1,m_BufferNoComment.size(),pos,beg,typedefpos); if(var == "") { continue; } // Check the alignment if specified if(alignment) { // Find the position in the line size_t l = this->GetPositionInLine(beg); size_t line = this->GetLineNumber(beg,true); size_t typdefline = this->GetLineNumber(typedefpos,true); // if the typedef is on a line close to the previous one we check if(typdefline-previousline<2) { if(l!=previouspos) { bool reportError = true; // We check that the previous line is not ending with a semicolon // and that the sum of the two lines is more than maxLength std::string previousLine = this->GetLine(this->GetLineNumber(beg,true)-2); std::string currentLine = this->GetLine(this->GetLineNumber(beg,true)-1); if( (previousLine[previousLine.size()-1] != ';') && (previousLine.size()+currentLine.size()>maxLength) ) { reportError = false; } // Check if the alignement is possible due to the length of the line size_t size = currentLine.size()-l; if(previouspos+size>maxLength) { previouspos = l; reportError = false; } // This one is a bit tricky. Check the minimum // typedef igstk::VascularNetworkObject VascularNetworkObjectType; // typedef VascularNetworkObjectType::VesselObjectType VesselObjectType; // First find the optimal position (one space) for the current line size_t optimalCurrentLinePos = l; while(optimalCurrentLinePos>1 && currentLine[optimalCurrentLinePos-1] == ' ') { optimalCurrentLinePos--; } optimalCurrentLinePos++; // Second find the size of the previous typedefs; size_t sizeTypedef = previousLine.size()-previouspos; // if the size is too big we don't report if(optimalCurrentLinePos+sizeTypedef>maxLength) { previouspos = l; reportError = false; } if(reportError) { Error error; error.line = this->GetLineNumber(beg,true); error.line2 = error.line; error.number = TYPEDEF_ALIGN; error.description = "Type definition (" + var + ") is not aligned with the previous one: "; char* var = new char[10]; sprintf(var,"%ld",l); error.description += var; error.description += " v.s. "; sprintf(var,"%ld",previouspos); error.description += var; delete [] var; m_ErrorList.push_back(error); hasError = true; } } } else { previouspos = l; } previousline = line; } if(!regex.find(var)) { Error error; error.line = this->GetLineNumber(pos,true); error.line2 = error.line; error.number = TYPEDEF_REGEX; error.description = "Type definition (" + var + ") doesn't match regular expression"; m_ErrorList.push_back(error); hasError = true; } } return !hasError; } /** Find a typedef in the source code */ std::string Parser::FindTypedef(size_t start, size_t end,size_t & pos,size_t & beg,size_t & typdefpos) { size_t posTypedef = m_BufferNoComment.find("typedef",start); if(posTypedef == std::string::npos) { pos = std::string::npos; return ""; } typdefpos = posTypedef; size_t posSemicolon = m_BufferNoComment.find(";",posTypedef); // Check if we have any () in the subword then we don't check the typdef std::string sub = m_BufferNoComment.substr(posTypedef,posSemicolon-posTypedef); if((sub.find("(",0) != std::string::npos) || (sub.find(")",0) != std::string::npos) || (sub.find("{",0) != std::string::npos) || (sub.find("}",0) != std::string::npos) ) { pos = posSemicolon; return ""; } std::string typedefname = ""; if(posSemicolon != std::string::npos && posSemicolon=0 && inWord) { if(m_BufferNoComment[i] != ' ') { std::string store = typedefname; typedefname = m_BufferNoComment[i]; typedefname += store; beg = i; inWord = true; first = true; } else // we have a space { if(first) { inWord = false; } } i--; } } pos = posSemicolon; return typedefname; } } // end namespace kws kwstyle-1.0.0+cvs20120330.orig/kwsParser.h0000755000175000017500000003630711155620174017575 0ustar mathieumathieu/*========================================================================= Program: KWStyle - Kitware Style Checker Module: $RCSfile: kwsParser.h,v $ Copyright (c) Kitware, Inc. All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef __kwsParser_h #define __kwsParser_h // Put kwssys/Configure.h first for proper compiler warning suppression: #include #include #include #include #include #include #include #include #include namespace kws { #define MAX_CHAR 99999999 #define NUMBER_ERRORS 32 typedef enum { SPACE, TAB } IndentType; typedef enum { LINE_LENGTH = 0, IVAR_PUBLIC, IVAR_REGEX, IVAR_ALIGN, SVAR_REGEX, SVAR_ALIGN, VARS, SEMICOLON_SPACE, DECL_ORDER, EOF_NEW_LINE, TABS, SPACES, INDENT, HEADER, NDEFINE, TYPEDEF_REGEX, TYPEDEF_ALIGN, NAMESPACE, NAMEOFCLASS, WRONGCOMMENT, MISSINGCOMMENT, EMPTYLINES, TEMPLATE, OPERATOR, BLACKLIST, STATEMENTPERLINE, VARIABLEPERLINE, BADCHARACTERS, MEMBERFUNCTION_REGEX, MEMBERFUNCTION_LENGTH, FUNCTION_REGEX, FUNCTION_LENGTH } ErrorType; const char ErrorTag[NUMBER_ERRORS][4] = { {'L','E','N','\0'}, {'I','V','P','\0'}, {'I','V','R','\0'}, {'I','V','A','\0'}, {'S','V','R','\0'}, {'S','V','A','\0'}, {'V','A','R','\0'}, {'S','E','M','\0'}, {'D','C','L','\0'}, {'E','O','F','\0'}, {'T','A','B','\0'}, {'E','S','P','\0'}, {'I','N','D','\0'}, {'H','R','D','\0'}, {'D','E','F','\0'}, {'T','D','R','\0'}, {'T','D','A','\0'}, {'N','M','S','\0'}, {'N','M','C','\0'}, {'W','C','M','\0'}, {'M','C','M','\0'}, {'E','M','L','\0'}, {'T','P','L','\0'}, {'O','P','S','\0'}, {'B','L','K','\0'}, {'S','P','L','\0'}, {'V','P','L','\0'}, {'B','C','H','\0'}, {'M','B','F','\0'}, {'M','F','L','\0'}, {'F','R','G','\0'}, {'F','L','N','\0'} }; typedef struct { unsigned long line; // main line of the error unsigned long line2; // second line of error if the error is covering several lines unsigned long number; std::string description; } Error; typedef struct { unsigned long line; // main line of the warning unsigned long line2; // second line of warning if the warning is covering several lines unsigned long number; std::string description; } Warning; typedef struct { // Position in the file size_t position; // What should be the position in the line of // the word w.r.t the previous position int current; // What should be the position in the line of // the words after w.r.t the previous position int after; // Name of the current ident std::string name; } IndentPosition; class Parser { public: /** Constructor */ Parser(); /** Destructor */ ~Parser(); /** To be able to use std::sort we provide the < operator */ bool operator<(const Parser& a) const; typedef std::vector ErrorVectorType; typedef std::vector WarningVectorType; typedef std::pair IfElseEndifPairType; typedef std::vector IfElseEndifListType; /** Set the buffer to analyze */ void SetBuffer(std::string buffer) { m_Buffer = buffer; this->ConvertBufferToWindowsFileType(m_Buffer); m_FixedBuffer = m_Buffer; this->RemoveComments(); } /** Return the error tag as string given the error number */ std::string GetErrorTag(unsigned long number) const; /** Return the error vector */ const ErrorVectorType & GetErrors() const {return m_ErrorList;} /** Return the last error message */ std::string GetLastErrors(); /** Return the warning vector */ std::string GetLastWarnings(); /** Return the warning vector */ const WarningVectorType & GetWarnings() const {return m_WarningList;} /** Check if the file contains tabs */ bool CheckTabs(); /** Check the number of succesive empty lines */ bool CheckEmptyLines(unsigned long max,bool checkEndOfFile=false); /** Check the comments * The comment definition should be set before CheckIndent() to get the correct indentation * for the comments. */ bool CheckComments(const char* begin,const char* middle,const char* end, bool allowEmptyLineBeforeClass=false, bool checkWrongComment=true, bool checkMissingComment=true); /** Check the indent size * Not in the header file if there is one * If CheckHeader has been done before CheckIndent and doNotCheckHeader is set to true * then the header is not checked for indent*/ bool CheckIndent(IndentType, unsigned long size, bool doNotCheckHeader=false, bool allowBlockLine = false, unsigned int maxLength = 81, bool allowCommaIndent = true ); /** Check Operator spaces foo=bar or foo = bar, etc... */ bool CheckOperator(unsigned int foo, unsigned int bar, unsigned long maxSize=81, bool doNotCheckInsideParenthesis=true); /** Check the number of character per line */ bool CheckLineLength(unsigned long max,bool checkHeader=false); /** Check if the internal parameters of the class are correct */ bool CheckInternalVariables(const char* regEx,bool alignement = true,bool checkProtected=false); /** Check variables implementation */ bool CheckVariables(const char* regEx); /** Check Member Functions implementation */ bool CheckMemberFunctions(const char* regEx,unsigned long maxLength=0); /** Check any Functions implementation */ bool CheckFunctions(const char* regEx,unsigned long maxLength=0); /** Check if the strcut parameters of the class are correct */ bool CheckStruct(const char* regEx,bool alignement = true); /** Check if the typedefs of the class are correct */ bool CheckTypedefs(const char* regEx, bool alignment = true, unsigned int maxLength = 81); /** Check the order of the declaration */ bool CheckDeclarationOrder(size_t posPublic, size_t posProtected,size_t posPrivate); /** Check for extra spaces */ bool CheckExtraSpaces(unsigned long max,bool checkEmptyLines=false); /** Check the number of space between the end of the declaration * and the semicolon */ bool CheckSemicolonSpace(unsigned long max); /** Check the number of statements per line */ bool CheckStatementPerLine(unsigned long max=1, bool checkInlineFunctions=true); /** Check the number of variables per line */ bool CheckVariablePerLine(unsigned long max=1); /** Check bad characters */ bool CheckBadCharacters(bool withComments=true); /** Check if the end of the file has a new line */ bool CheckEndOfFileNewLine(); /** Check header * Because most of the time the header is checked in cvs we should ignore the $ $*/ bool CheckHeader(const char* filename,bool considerSpaceEOL = true,bool useCVS=true); /** Check if the #ifndef/#define is defined correctly for the class */ bool CheckIfNDefDefine(const char* match); /** Check the first namespace in the file */ bool CheckNamespace(const char* name,bool doNotCheckMain=true); /** Check the templates */ bool CheckTemplate(const char* regex); /** Check if the name of the class is correct */ bool CheckNameOfClass(const char* name, const char* prefix); /** Check that there is no word in the class that matches a word in the black list */ bool CheckBlackList(const char* filename); /** Remove the comments. */ std::string RemoveComments(const char* buffer=NULL); /** Clear the error list */ void ClearErrors() {m_ErrorList.clear();} /** Clear the info list */ void ClearInfo() {m_WarningList.clear();} /** Set the filename of the file we are checking */ void SetFilename(const char* filename) {m_Filename = filename;} std::string GetFilename() const {return m_Filename;} /** Return the number of lines */ unsigned long GetNumberOfLines() const; /** Return the line */ std::string GetLine(unsigned long i) const; /** Return if a test has been performed */ bool HasBeenPerformed(unsigned int test) const; /** Return the test description given the error number) */ std::string GetTestDescription(unsigned int test) const; /** Given the name of the check to perform and the default value perform the check */ bool Check(const char* name, const char* value); /** Should KWStyle produce a fix version of the parsed file */ void SetFixFile(bool fix) {m_FixFile = fix;} void GenerateFixedFile(); /** return true if the position pos is between " " */ bool IsBetweenQuote(size_t pos,bool withComments=false,std::string buffer="") const; protected: /** Convert the file with \r\n instead of \n */ void ConvertBufferToWindowsFileType(std::string & buffer); /** Check the operator. * \warning This function add an error in the Error list */ bool FindOperator(const char* op,unsigned int before, unsigned int after,unsigned long maxSize, bool doNotCheckInsideParenthesis=true); /** Get the class position within the file. This function checks that this is the * classname */ size_t GetClassPosition(size_t position,std::string buffer="") const; /** Return the position in the line given the position in the text */ size_t GetPositionInLine(size_t pos); /** Find an ivar in the source code */ std::string FindInternalVariable(size_t start, size_t end,size_t& pos); /** Find an ivar in the source code */ std::string FindVariable(std::string & buffer,size_t start, size_t end,size_t& pos); /** Find a member function in the source code */ std::string FindMemberFunction(std::string & buffer,size_t start, size_t end,size_t& pos); /** Find a typedef in the source code */ std::string FindTypedef(size_t start, size_t end,size_t& pos,size_t & beg,size_t & typedefpos); /** Reduces multiple spaces in buffer to one. */ void ReduceMultipleSpaces(std::string & buffer); /** Removes all val chars from string. */ void RemoveChar(std::string & buffer, char val) const; /** Find the line number in the commented text given the character description */ long int GetLineNumber(size_t pos,bool withoutComments=false) const; /** Find the previous word given a position */ std::string FindPreviousWord(size_t pos,bool withComments=false,std::string buffer="") const; /** Find the next word given a position. This function works only without comments.*/ std::string FindNextWord(size_t pos) const; /** Find the closing bracket given the position of the opening bracket. */ size_t FindClosingChar(char openChar, char closeChar, size_t pos,bool noComment=false,std::string buffer="") const; /** Find the opening bracket given the position of the closing bracket. */ size_t FindOpeningChar(char closeChar, char openChar, size_t pos,bool noComment=false) const; /** Find the constructor in the file. */ size_t FindConstructor(const std::string & buffer, const std::string & className, bool headerfile=true, size_t startPos=0) const; /** Return true if the position pos is between <>. * The Fast version just check for and not for ,test<>>*/ bool IsBetweenCharsFast(const char begin, const char end, size_t pos,bool withComments=false,std::string buffer="") const; bool IsBetweenChars(const char begin, const char end, size_t pos,bool withComments=false,std::string buffer="") const; bool IsValidQuote(std::string & stream,size_t pos) const; /** Removes ass CtrlN characters from the buffer. */ void RemoveCtrlN(std::string & buffer) const; /** Find the correct area given its name */ size_t FindArea(const char* name,size_t startPos) const; /** Find public area in source code. */ void FindPublicArea(size_t &before, size_t &after, size_t startPos=0) const; /** Find protected area in source code. */ void FindProtectedArea(size_t &before, size_t &after, size_t startPos=0) const; /** Find private area in source code. */ void FindPrivateArea(size_t &before, size_t &after, size_t startPos=0) const; /** Return the position of the template if the class has a template otherwise npos. */ size_t IsTemplated(const std::string & buffer, size_t pos) const; /** Return true if the position pos is inside a comment */ bool IsInComments(size_t pos) const; /** Return true if the position pos is inside a function */ bool IsInFunction(size_t pos,const char* buffer=NULL) const; /** Return true if the position pos is inside a struct */ bool IsInStruct(size_t pos,const char* buffer=NULL) const; /** Return true if the position pos is inside a union */ bool IsInUnion(size_t pos,const char* buffer=NULL) const; /** Return true if the position pos is inside a comment defined by the compiler */ bool IsInAnyComments(size_t pos) const; /** Given the position without comments return the position with the comments */ size_t GetPositionWithComments(size_t pos) const; size_t GetPositionWithoutComments(size_t pos) const; /** Init the indentation step for CheckIndent() */ bool InitIndentation(); /** Extract the current line from pos to \n */ std::string ExtractLine(size_t pos); /** Return the current ident */ int GetCurrentIdent(std::string line,char type); /** Helper function to add words to the special indent vector */ void AddIndent(const char* name,int current,int after); /** Find the end of the class */ size_t FindEndOfClass(size_t position) const; /** Return if the dept of the current class */ int IsInClass(size_t position) const; /** Return the position of the last character * of the function name/definition/ */ size_t FindFunction(size_t position,const char* buffer=NULL) const; /** Compute the list of #if/#else/#endif */ void ComputeIfElseEndifList(); bool IsInElseForbiddenSection(size_t pos); /** Functions to deal with the fixed buffer */ void ReplaceCharInFixedBuffer(size_t pos,size_t size,const char* replacingString); /** Check if the current position is a valid switch statement */ bool CheckValidSwitchStatement(unsigned int posSwitch); private: ErrorVectorType m_ErrorList; WarningVectorType m_WarningList; bool m_TestsDone[NUMBER_ERRORS]; std::string m_TestsDescription[NUMBER_ERRORS]; std::string m_Buffer; std::string m_BufferNoComment; std::string m_FixedBuffer; std::vector m_Positions; typedef std::pair PairType; std::vector m_CommentPositions; std::string m_Filename; std::string m_HeaderFilename; std::string m_CommentBegin; std::string m_CommentMiddle; std::string m_CommentEnd; bool m_FixFile; std::vector m_FixedPositions; std::vector m_IdentPositionVector; std::string m_BlackList; std::string m_BlackListBuffer; IfElseEndifListType m_IfElseEndifList; }; } // end namespace kws #endif kwstyle-1.0.0+cvs20120330.orig/CTestConfig.cmake0000644000175000017500000000102211072452460020573 0ustar mathieumathieu## This file should be placed in the root directory of your project. ## Then modify the CMakeLists.txt file in the root directory of your ## project to incorporate the testing dashboard. ## # The following are required to uses Dart and the Cdash dashboard ## ENABLE_TESTING() ## INCLUDE(Dart) set(CTEST_PROJECT_NAME "KWStyle") set(CTEST_NIGHTLY_START_TIME "21:00:00 EST") set(CTEST_DROP_METHOD "http") set(CTEST_DROP_SITE "my.cdash.org") set(CTEST_DROP_LOCATION "/submit.php?project=KWStyle") set(CTEST_DROP_SITE_CDASH TRUE) kwstyle-1.0.0+cvs20120330.orig/kwsCheckIndent.cxx0000755000175000017500000010074011302100741021047 0ustar mathieumathieu/*========================================================================= Program: KWStyle - Kitware Style Checker Module: $RCSfile: kwsCheckIndent.cxx,v $ Copyright (c) Kitware, Inc. All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "kwsParser.h" namespace kws { #define ALIGN_LEFT -99999 /** Extract the current line from pos to \n */ std::string Parser::ExtractLine(size_t pos) { size_t p = m_Buffer.find("\n",pos); if(p>pos) { return m_Buffer.substr(pos,p-pos-1); } return ""; } /** Return the current ident */ int Parser::GetCurrentIdent(std::string line,char type) { int indent = 0; std::string::const_iterator it = line.begin(); while(it != line.end() && (*it)== type) { indent++; it++; } return indent; } /** Check the indent size */ bool Parser::CheckIndent(IndentType itype, unsigned long size, bool doNotCheckHeader, bool allowBlockLine, unsigned int maxLength, bool allowCommaIndent) { m_TestsDone[INDENT] = true; m_TestsDescription[INDENT] = "The Indent should respect: "; char* val = new char[10]; sprintf(val,"%ld ",size); m_TestsDescription[INDENT] += val; if(itype == (IndentType)TABS) { m_TestsDescription[INDENT] += "tabs"; } else { m_TestsDescription[INDENT] += "spaces"; } delete [] val; if(doNotCheckHeader) { m_TestsDescription[INDENT] += " (not checking header, "; } else { m_TestsDescription[INDENT] += " (checking header, "; } if(allowBlockLine) { m_TestsDescription[INDENT] += "blockline allowed)"; } else { m_TestsDescription[INDENT] += "blockline not allowed)"; } bool hasError = false; unsigned long pos = 0; std::string::const_iterator it = m_Buffer.begin(); // Variable to check if we are in a comment or not bool isCheckingComment = false; // In the case we have #if/#else/#endif we want to ignore the #else section // if we have some '{' not closed // #if // { // #else // { // #endif this->ComputeIfElseEndifList(); // Create the indentation this->InitIndentation(); // Print the initial indentation /*std::vector::const_iterator itIndent = m_IdentPositionVector.begin(); while(itIndent != m_IdentPositionVector.end()) { std::cout << this->GetLineNumber((*itIndent).position) << std::endl; std::cout << (*itIndent).current << std::endl; std::cout << (*itIndent).after << std::endl; std::cout << (*itIndent).name.c_str() << std::endl; itIndent++; }*/ // If we do not want to check the header if(doNotCheckHeader) { unsigned long fileSize = 0; // if the file is specified if(m_HeaderFilename.size() > 0) { std::ifstream file; file.open(m_HeaderFilename.c_str(), std::ios::binary | std::ios::in); if(!file.is_open()) { std::cout << "Cannot open file: " << m_HeaderFilename << std::endl; return false; } file.seekg(0,std::ios::end); fileSize = file.tellg(); file.close(); } else { // we look at the first '*/' in the file which indicated the end of the current header // This assume that there is an header at some point long int endHeader = m_Buffer.find("*/",0); if(endHeader>0) { fileSize = endHeader; } } // We skip the header for(unsigned int i=0;iExtractLine(pos); int currentIndent = this->GetCurrentIdent(line,type); bool firstChar = true; // We start to check while(it != m_Buffer.end()) { // If we should skip the line bool skip = this->IsInElseForbiddenSection(pos); if((*it) == type || (*it)=='\r' || skip) { it++; pos++; continue; } if((*it) == '\n') { it++; pos++; // We extract the next line std::string line = this->ExtractLine(pos); currentIndent = this->GetCurrentIdent(line,type); firstChar = true; continue; } // Check if pos is in the list of positions std::vector::iterator itIdentPos = m_IdentPositionVector.begin(); IndentPosition* sindent = NULL; while(itIdentPos != m_IdentPositionVector.end()) { if((*itIdentPos).position == pos) { sindent = &(*itIdentPos); break; } itIdentPos++; } // We check if we have the right indent if(sindent) { long int wanted = wantedIndent+size*sindent->current; if(sindent->current == ALIGN_LEFT) { wanted = 0; } else if(currentIndent != wanted) { bool returnError = true; // We check that the previous line is not ending with a semicolon // and that the sum of the two lines is more than maxLength std::string previousLine = this->GetLine(this->GetLineNumber(pos)-2); std::string currentLine = this->GetLine(this->GetLineNumber(pos)-1); if( (previousLine[previousLine.size()-1] != ';') && (previousLine.size()+currentLine.size()-currentIndent>maxLength) ) { returnError = false; } // Check for special characters if(previousLine[previousLine.size()-1] != ';') { // Check if we have a << at the beginning of the current line long int posSpecialChar = currentLine.find("<<"); if(posSpecialChar != -1) { returnError = false; for(long int i=0;iname == "public:" || sindent->name == "protected:" || sindent->name == "private:" || sindent->name == "signals:" || sindent->name == "public slots:" ) { int inClass = this->IsInClass(this->GetPositionWithoutComments(pos)); if(inClass>1) { returnError = false; } } // Check if we are inside a macro. If yes we disable the checking of the ident // (This is too complex for macros) if(returnError) { // We are in a macro if we have // '#define foo' and the line finishs with '\' long int begMacro = m_Buffer.find("#define",0); while(begMacro!=-1) { // Find the end of the macro long int endMacro = m_Buffer.find("\r",begMacro); while(endMacro>0 && m_Buffer[endMacro-1]=='\\') { endMacro = m_Buffer.find("\r",endMacro+1); } if(endMacro!=-1 && (long int)posbegMacro) { returnError = false; break; } begMacro = m_Buffer.find("#define",endMacro); } } if(returnError) { Error error; error.line = this->GetLineNumber(pos); error.line2 = error.line; error.number = INDENT; error.description = "Special Indent is wrong "; char* val = new char[10]; sprintf(val,"%d",currentIndent); error.description += val; error.description += " (should be "; delete [] val; val = new char[10]; sprintf(val,"%ld",wanted); error.description += val; error.description += ")"; delete [] val; m_ErrorList.push_back(error); hasError = true; } } wantedIndent += size*sindent->after; firstChar = false; } else if((it != m_Buffer.end()) && ((*it) == '{') //&& !this->IsInComments(pos) && !isCheckingComment //&& !this->IsBetweenQuote(pos,true) && !( (!this->IsInAnyComments(pos) && this->IsBetweenQuote(this->GetPositionWithoutComments(pos),false)) || (this->IsInAnyComments(pos) && this->IsBetweenQuote(pos,true))) ) // openning bracket { bool check = true; // Check if { is after // [THIS CHECK IS NOT USEFULL ANYMORE] long int doubleslash = m_Buffer.rfind("//",pos); if(doubleslash != -1) { if(this->GetLineNumber(doubleslash) == this->GetLineNumber(pos)) { check = false; } } if(check) { wantedIndent += size; } } if(firstChar) // general case { // If we are in a comment if(this->IsInComments(pos)) { if(this->IsInAnyComments(pos)) { isCheckingComment = true; } // We check how much space we have in the middle section unsigned int nSpaceMiddle = 0; while(m_CommentMiddle[nSpaceMiddle] == type) { nSpaceMiddle++; } if((*it) == m_CommentMiddle[nSpaceMiddle]) { if(currentIndent>0) { currentIndent -= nSpaceMiddle; } } else { // We check how much space we have in the end section unsigned int nSpaceEnd = 0; while(m_CommentEnd[nSpaceEnd] == type) { nSpaceEnd++; } if((*it) == m_CommentEnd[nSpaceEnd]) { currentIndent -= nSpaceEnd; isCheckingComment = false; } } } else { isCheckingComment = false; } bool inComment = this->IsInAnyComments(pos); if(isCheckingComment && !inComment) { Warning warning; warning.line = this->GetLineNumber(pos); warning.line2 = this->GetLineNumber(pos); warning.description = "There is a problem with the comments"; warning.number = INDENT; m_WarningList.push_back(warning); // We check how much space we have in the end section unsigned int nSpaceEnd = 0; while(m_CommentEnd[nSpaceEnd] == type) { nSpaceEnd++; } currentIndent -= nSpaceEnd; isCheckingComment = false; } unsigned int poswithoutcomment = this->GetPositionWithoutComments(pos); if((currentIndent != wantedIndent) && ((inComment && !this->IsBetweenCharsFast('<','>',pos,true) && !this->IsBetweenCharsFast('(',')',pos,true) && !this->IsBetweenChars('(',')',pos,true) && !this->IsBetweenChars('<','>',pos,true)) || ( !inComment && !this->IsBetweenCharsFast('<','>',poswithoutcomment,false) && !this->IsBetweenCharsFast('(',')',poswithoutcomment,false) && !this->IsBetweenChars('(',')',poswithoutcomment,false) && !this->IsBetweenChars('<','>',poswithoutcomment,false))) ) { // If we are inside an enum we do not check indent bool isInsideEnum = false; long int bracket = m_Buffer.find_last_of('{',pos); if(bracket != -1) { unsigned int l = this->FindPreviousWord(bracket-1,true).size(); if(this->FindPreviousWord(bracket-l-2,true) == "enum") { isInsideEnum = true; } } bool reportError = true; // We check that the previous line is not ending with a semicolon // and that the sum of the two lines is more than maxLength std::string previousLine = this->GetLine(this->GetLineNumber(pos)-2); std::string currentLine = this->GetLine(this->GetLineNumber(pos)-1); if(( (previousLine[previousLine.size()-1] != ';') && (previousLine.size()+currentLine.size()-currentIndent>maxLength)) || (isInsideEnum) ) { reportError = false; } // Check if the line start with '<<' if this is the case we ignore it else if((*it) == '<' && (*(it+1) == '<')) { long int posInf = previousLine.find("<<"); if((posInf != -1) && (posInf == currentIndent+1)) { reportError = false; } } // We don't care about everything between the class and '{' else { long int classPos = m_Buffer.find("class",0); while(classPos!=-1) { long int endClass = m_Buffer.find("{",classPos); if(endClass!=-1 && (long int)posclassPos) { reportError = false; break; } classPos = m_Buffer.find("class",classPos+1); } } // If the ident is between a '=' and a ';' we ignore // This is for lists. THIS IS NOT A STRICT CHECK. Might be missing some. if(reportError) { long int classPos = m_BufferNoComment.find("=",0); while(classPos!=-1) { long int posNoCommments = this->GetPositionWithoutComments(pos); long int endClass = m_BufferNoComment.find(";",classPos); if(endClass!=-1 && (long int)posNoCommmentsclassPos) { reportError = false; break; } classPos = m_BufferNoComment.find("=",classPos+1); } } // If the ident is between a ':' and a '{' we ignore // This is for the constructor. if(reportError) { long int classPos = m_BufferNoComment.find(":",0); while(classPos!=-1) { long int posNoCommments = this->GetPositionWithoutComments(pos); long int endConstructor = m_BufferNoComment.find("{",classPos); if(endConstructor!=-1 && (long int)posNoCommmentsclassPos) { reportError = false; break; } classPos = m_BufferNoComment.find(":",classPos+1); } } // If the ident is between 'return' and ';' we ignore // Ideally we should have a strict check if(reportError) { long int classPos = m_BufferNoComment.find("return",0); while(classPos!=-1) { long int posNoCommments = this->GetPositionWithoutComments(pos); long int endConstructor = m_BufferNoComment.find(";",classPos); if(endConstructor!=-1 && (long int)posNoCommmentsclassPos) { reportError = false; break; } classPos = m_BufferNoComment.find("return",classPos+1); } } // Check if we are inside a macro. If yes we disable the checking of the ident // (This is too complex for macros) if(reportError) { // We are in a macro if we have // '#define foo' and the line finishs with '\' long int begMacro = m_Buffer.find("#define",0); while(begMacro!=-1) { // Find the end of the macro long int endMacro = m_Buffer.find("\r",begMacro); while(endMacro>0 && m_Buffer[endMacro-1]=='\\') { endMacro = m_Buffer.find("\r",endMacro+1); } if(endMacro!=-1 && (long int)posbegMacro) { reportError = false; break; } begMacro = m_Buffer.find("#define",endMacro); } } // If we allowCommaIndentation: // if(myvalue, // myvalue2) if(allowCommaIndent && reportError) { // Check the end of the previous line if we have a comma long int j = previousLine.size()-1; while(j>0) { if(previousLine[j] != ' ' && previousLine[j] != '\n' && previousLine[j] != '\r') { break; } j--; } if(previousLine[j] == ',') { reportError = false; } } if(reportError) { Error error; error.line = this->GetLineNumber(pos); error.line2 = error.line; error.number = INDENT; error.description = "Indent is wrong "; char* val = new char[10]; sprintf(val,"%d",currentIndent); error.description += val; error.description += " (should be "; delete [] val; val = new char[10]; sprintf(val,"%d",wantedIndent); error.description += val; error.description += ")"; delete [] val; m_ErrorList.push_back(error); hasError = true; } } } if((it != m_Buffer.end()) && ((*it) == '}') && !sindent //&& !this->IsInComments(pos) && !isCheckingComment //&& !this->IsBetweenQuote(pos,true) && !( (!this->IsInAnyComments(pos) && this->IsBetweenQuote(this->GetPositionWithoutComments(pos),false)) || (this->IsInAnyComments(pos) && this->IsBetweenQuote(pos,true))) ) // closing bracket { bool check = true; // Check if { is after // long int doubleslash = m_Buffer.rfind("//",pos); if(doubleslash != -1) { if(this->GetLineNumber(doubleslash) == this->GetLineNumber(pos)) { check = false; } } if(check) { wantedIndent -= size; } } firstChar = false; if(it != m_Buffer.end()) { it++; pos++; } } return !hasError; } /** Check if the current position is a valid switch statement */ bool Parser::CheckValidSwitchStatement(unsigned int posSwitch) { if((m_BufferNoComment[posSwitch-1]!='\n' && m_BufferNoComment[posSwitch-1]!=' ' && posSwitch-1 != 0) || (m_BufferNoComment.size() > posSwitch+6 && m_BufferNoComment[posSwitch+6] != ' ' && m_BufferNoComment[posSwitch+6] != '(')) { return false; } return true; } /** Init the indentation */ bool Parser::InitIndentation() { m_IdentPositionVector.clear(); // namespace std::vector namespacevec; size_t posNamespace = m_BufferNoComment.find("namespace",0); while(posNamespace!=std::string::npos) { size_t posNamespace1 = m_BufferNoComment.find("{",posNamespace); if(posNamespace1 != std::string::npos) { size_t posNamespace2 = m_BufferNoComment.find(";",posNamespace); if((posNamespace2 == std::string::npos) || (posNamespace2 > posNamespace1)) { size_t posNamespaceComments = this->GetPositionWithComments(posNamespace1); IndentPosition ind; ind.position = posNamespaceComments; ind.current = 0; ind.after = 0; namespacevec.push_back(posNamespaceComments); //std::cout << "Found Namespace at: " << this->GetLineNumber(posNamespaceComments) << std::endl; m_IdentPositionVector.push_back(ind); ind.position = this->FindClosingChar('{','}',posNamespaceComments); namespacevec.push_back(ind.position); m_IdentPositionVector.push_back(ind); } } posNamespace = m_BufferNoComment.find("namespace",posNamespace+1); } // Create a list of position specific for namespaces std::vector namespacePos; std::vector::iterator itIdentPos = m_IdentPositionVector.begin(); while(itIdentPos != m_IdentPositionVector.end()) { namespacePos.push_back((*itIdentPos).position); itIdentPos++; } // Check if the { is the first in the file/function or in a namespace size_t posClass = m_BufferNoComment.find('{',0); while(posClass!= std::string::npos && this->IsInElseForbiddenSection(this->GetPositionWithComments(posClass))) { posClass = m_BufferNoComment.find('{',posClass+1); } while(posClass != std::string::npos) { // We count the number of { and } before posClass int nOpen = 0; int nClose = 0; size_t open = m_BufferNoComment.find('{',0); while(open!=std::string::npos && openIsInElseForbiddenSection(this->GetPositionWithComments(open)) && !this->IsBetweenQuote(open) ) { bool isNamespace = false; // Remove the potential namespaces std::vector::const_iterator itN = namespacePos.begin(); while(itN != namespacePos.end()) { if((*itN)==this->GetPositionWithComments(open)) { isNamespace = true; } itN++; } if(!isNamespace) { nOpen++; } } open = m_BufferNoComment.find('{',open+1); } size_t close = m_BufferNoComment.find('}',0); while(close!=std::string::npos && closeIsInElseForbiddenSection(this->GetPositionWithComments(close)) && !this->IsBetweenQuote(close) ) { bool isNamespace = false; // Remove the potential namespaces std::vector::const_iterator itN = namespacePos.begin(); while(itN != namespacePos.end()) { if((*itN)==this->GetPositionWithComments(close)) { isNamespace = true; } itN++; } if(!isNamespace) { nClose++; } } close = m_BufferNoComment.find('}',close+1); } bool defined = false; if(nClose == nOpen) { // Check if this is not the namespace previously defined std::vector::iterator itname = namespacevec.begin(); while(itname != namespacevec.end()) { if((*itname) == this->GetPositionWithComments(posClass)) { defined = true; break; } itname++; } } if((nClose == nOpen) && !defined) { // translate the position in the buffer position; size_t posClassComments = this->GetPositionWithComments(posClass); IndentPosition ind; ind.position = posClassComments; ind.current = 0; ind.after = 1; m_IdentPositionVector.push_back(ind); ind.position = this->FindClosingChar('{','}',posClassComments); while(this->IsBetweenQuote(ind.position,true)) { ind.position = this->FindClosingChar('{','}',ind.position+1); } ind.current = -1; ind.after = -1; m_IdentPositionVector.push_back(ind); } posClass = m_BufferNoComment.find('{',posClass+1); } // int main() size_t posMain = m_BufferNoComment.find("main",0); while(posMain != std::string::npos) { // Check if the next char is '(' bool valid = true; unsigned long pos = posMain+5; while(posGetPositionWithComments(bracket); IndentPosition ind; ind.position = posMainComments; ind.current = 0; ind.after = 1; m_IdentPositionVector.push_back(ind); ind.position = this->FindClosingChar('{','}',posMainComments); ind.current = -1; ind.after = -1; m_IdentPositionVector.push_back(ind); } } posMain = m_BufferNoComment.find("main",posMain+4); } // switch/case statement // for the moment break; restore the indentation size_t posSwitch = m_BufferNoComment.find("switch",0); while(posSwitch != std::string::npos) { // Check that it is a valid switch statement if(!this->CheckValidSwitchStatement(posSwitch)) { posSwitch = m_BufferNoComment.find("switch",posSwitch+1); continue; } // If this is the first case we find the openning { in order to // find the closing } of the switch statement size_t openningBracket = m_BufferNoComment.find("{",posSwitch); size_t closingBracket = this->FindClosingChar('{','}',openningBracket,true); size_t posColumnComments = this->GetPositionWithComments(closingBracket); IndentPosition ind; ind.position = posColumnComments; ind.current = -1; ind.after = -2; m_IdentPositionVector.push_back(ind); // Do the default case size_t defaultPos = m_BufferNoComment.find("default",openningBracket); if(defaultPos > closingBracket) { defaultPos = std::string::npos; } // We need to make sure that there is no "switch" statement nested size_t nestedSwitch = m_BufferNoComment.find("switch",posSwitch+1); while(nestedSwitch != std::string::npos) { if(!this->CheckValidSwitchStatement(nestedSwitch)) { nestedSwitch = m_BufferNoComment.find("switch",nestedSwitch+1); continue; } if(nestedSwitch < defaultPos) { defaultPos = m_BufferNoComment.find("default",defaultPos+1); } else { break; } nestedSwitch = m_BufferNoComment.find("switch",nestedSwitch+1); } if(defaultPos != std::string::npos) { size_t posColumnComments = this->GetPositionWithComments(defaultPos); IndentPosition ind; ind.position = posColumnComments; // The current indent should be -1 unless we are right after the openning // bracket. In that case the current indent should be 0; size_t j=defaultPos-1; while(j!=std::string::npos) { if(m_BufferNoComment[j] != ' ' && m_BufferNoComment[j] != '\n' && m_BufferNoComment[j] != '\r' ) { break; } j--; } if(j == openningBracket) { ind.current = 0; } else { ind.current = -1; } ind.after = 0; m_IdentPositionVector.push_back(ind); // Find the ':' after the default size_t column = m_BufferNoComment.find(":",defaultPos+1); column = this->GetPositionWithComments(column); // Sometimes there is a { right after the : we skip it if this is // the case size_t ic = column+1; while(icFindClosingChar('{','}',ic); ind.current = 0; ind.after = 0; m_IdentPositionVector.push_back(ind); } } size_t posCase = m_BufferNoComment.find("case",openningBracket); bool firstCase = true; size_t previousCase = openningBracket; while(posCase!= std::string::npos && posCaseopenningBracket && insideSwitchFindClosingChar('{','}',insideBracket,true); } else { size_t posColumnComments = this->GetPositionWithComments(posCase); IndentPosition ind; ind.position = posColumnComments; if(firstCase) { ind.current = 0; } else { ind.current = -1; } ind.after = 0; m_IdentPositionVector.push_back(ind); size_t column = m_BufferNoComment.find(':',posCase+3); // Make sure that we are not checing '::' while(column+1GetPositionWithComments(column); IndentPosition ind; ind.position = posColumnComments; if(firstCase) { ind.current = 0; ind.after = 1; } else { ind.current = -1; ind.after = 0; } m_IdentPositionVector.push_back(ind); // Sometimes there is a { right after the : we skip it if this is // the case size_t ic = posColumnComments+1; while(icFindClosingChar('{','}',ic); ind.current = 0; ind.after = 0; m_IdentPositionVector.push_back(ind); } } } firstCase = false; previousCase = posCase; posCase = m_BufferNoComment.find("case",posCase+1); } posSwitch = m_BufferNoComment.find("switch",posSwitch+3); } // Some words should be indented as the previous indent this->AddIndent("public:",-1,0); this->AddIndent("private:",-1,0); this->AddIndent("protected:",-1,0); this->AddIndent("signals:",-1,0); this->AddIndent("public slots:",-1,0); this->AddIndent("private slots:",-1,0); this->AddIndent("protected slots:",-1,0); // some words should be always align left this->AddIndent("#include",ALIGN_LEFT,0); this->AddIndent("#if",ALIGN_LEFT,0); //this->AddIndent("#ifdef",ALIGN_LEFT,0); // #if is taking care of it this->AddIndent("#elif",ALIGN_LEFT,0); this->AddIndent("#else",ALIGN_LEFT,0); this->AddIndent("#endif",ALIGN_LEFT,0); //this->AddIndent("#ifndef",ALIGN_LEFT,0); // #if is taking care of it this->AddIndent("#define",ALIGN_LEFT,0); this->AddIndent("#undef",ALIGN_LEFT,0); return true; } void Parser::AddIndent(const char* name,int current,int after) { size_t posPrev = m_Buffer.find(name,0); while(posPrev!=std::string::npos) { IndentPosition ind; ind.position = posPrev; ind.current = current; ind.after = after; ind.name = name; m_IdentPositionVector.push_back(ind); posPrev = m_Buffer.find(name,posPrev+1); } } /** Return true if the current position with comments is in the * #else section of the forbiden part. * In case we have something like: * #if * { * #else * { * #endif */ bool Parser::IsInElseForbiddenSection(size_t pos) { IfElseEndifListType::const_iterator itLS = m_IfElseEndifList.begin(); while(itLS != m_IfElseEndifList.end()) { if(pos>(*itLS).first && pos<(*itLS).second) { return true; } itLS++; } return false; } } // end namespace kws kwstyle-1.0.0+cvs20120330.orig/kwsCheckEndOfFileNewLine.cxx0000755000175000017500000000434711143340104022713 0ustar mathieumathieu/*========================================================================= Program: KWStyle - Kitware Style Checker Module: $RCSfile: kwsCheckEndOfFileNewLine.cxx,v $ Copyright (c) Kitware, Inc. All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "kwsParser.h" namespace kws { /** Check if the end of the file has a new line */ bool Parser::CheckEndOfFileNewLine() { m_TestsDone[EOF_NEW_LINE] = true; char* val = new char[255]; sprintf(val,"The file should have only one new line"); m_TestsDescription[EOF_NEW_LINE] = val; delete [] val; bool hasError = false; // Check if the last character is an end of line if(m_Buffer[m_Buffer.size()-1] != '\n') { Error error; error.line = this->GetLineNumber(m_Buffer.size()-1,false); error.line2 = error.line; error.number = EOF_NEW_LINE; error.description = "No new line at the end of file"; m_ErrorList.push_back(error); hasError = true; } // Check the number empty lines at the end of the file if((m_Buffer[m_Buffer.size()-1] == ' ') || (m_Buffer[m_Buffer.size()-1] == '\n')) { long i = m_Buffer.size()-1; unsigned long numberOfEmptyLines = 0; while( ((m_Buffer[i] == '\n') || (m_Buffer[i] == ' ') || (m_Buffer[i] == '\r')) && (i>0)) { if(m_Buffer[i] == '\n') { numberOfEmptyLines++; } i-=1; } if(numberOfEmptyLines>1) { // Maybe should be info and not error Error info; info.line2 = this->GetLineNumber(m_Buffer.size()-1,false)+1; info.line = info.line2-numberOfEmptyLines+2; info.number = EOF_NEW_LINE; info.description = "Number of empty lines at the end of files: "; char* val = new char[10]; sprintf(val,"%ld",numberOfEmptyLines); info.description += val; delete [] val; m_ErrorList.push_back(info); } } return !hasError; } } // end namespace kws kwstyle-1.0.0+cvs20120330.orig/kwsCheckVariablePerLine.cxx0000644000175000017500000001146511155521351022646 0ustar mathieumathieu/*========================================================================= Program: KWStyle - Kitware Style Checker Module: $RCSfile: kwsCheckVariablePerLine.cxx,v $ Copyright (c) Kitware, Inc. All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "kwsParser.h" namespace kws { /** Check the number of statements per line */ bool Parser::CheckVariablePerLine(unsigned long max) { m_TestsDone[VARIABLEPERLINE] = true; char* val = new char[255]; sprintf(val,"Variables per line = %ld max",max); m_TestsDescription[VARIABLEPERLINE] = val; delete [] val; // For the moment only standard types are defined. // We might be able to do more with finding typedefs #define ntypes 12 const char* types[ntypes] = {"int","unsigned int", "char","unsigned char", "short","unsigned short", "long","unsigned long", "float","double","void","long int"}; bool hasError = false; for(unsigned int i = 0;i0) && (m_BufferNoComment[pos]==' ')) { pos--; } if((pos<=0) || (m_BufferNoComment[pos]=='\n')) { firstWord = true; } if(firstWord) { std::string line = this->GetLine(this->GetLineNumber(posType,true)-1); // Check if we have any comments int poscom = line.find("//",0); if(poscom != -1) { line = line.substr(0,poscom); } poscom = line.find("/*",0); while(poscom != -1) { int poscomend = line.find("*/",0); if(poscomend == -1) { line = line.substr(0,poscom); break; } std::string line_temp = line.substr(0,poscom); line = line_temp+line.substr(poscomend+2,line.size()-poscomend-2); poscom = line.find("/*",poscom+1); } // If we have any '(' in the line we stop if(line.find('(') == std::string::npos) { // This is a very simple check we count the number of comas unsigned int vars = 1; pos = line.find(',',0); while(pos!=-1) { // Check that we are not initializing an array bool betweenBraces = false; long int openCurly = pos-1; while(openCurly>0) { // Ok we have the opening if(line[openCurly] == '{') { long int posClosing = this->FindClosingChar('{','}',openCurly,false,line); if(posClosing == -1 || pos max) { Error error; error.line = this->GetLineNumber(posType,true); error.line2 = error.line; error.number = VARIABLEPERLINE; error.description = "Number of variable per line exceed: "; char* val = new char[10]; sprintf(val,"%d",vars); error.description += val; error.description += " (max="; delete [] val; val = new char[10]; sprintf(val,"%ld",max); error.description += val; error.description += ")"; delete [] val; m_ErrorList.push_back(error); hasError = true; } } }// end firstWord posType = m_BufferNoComment.find(typeToFind,posType+1); } } return !hasError; } } // end namespace kws kwstyle-1.0.0+cvs20120330.orig/kwsCheckBlackList.cxx0000644000175000017500000000641511155521350021510 0ustar mathieumathieu/*========================================================================= Program: KWStyle - Kitware Style Checker Module: $RCSfile: kwsCheckBlackList.cxx,v $ Copyright (c) Kitware, Inc. All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "kwsParser.h" #include namespace kws { /** Check that there is no word in the class that matches a word in the black list */ bool Parser::CheckBlackList(const char* filename) { m_TestsDone[BLACKLIST] = true; m_TestsDescription[BLACKLIST] = "No word should matche any words from the file: "; m_TestsDescription[BLACKLIST] += filename; bool hasError = false; // If the black list is not read we read it if(strcmp(m_BlackList.c_str(),filename)) { // Read the file std::ifstream file; file.open(filename, std::ios::binary | std::ios::in); if(!file.is_open()) { std::cout << "Cannot open file: " << filename << std::endl; return 0; } file.seekg(0,std::ios::end); unsigned long fileSize = file.tellg(); file.seekg(0,std::ios::beg); char* buf = new char[fileSize+1]; file.read(buf,fileSize); buf[fileSize] = 0; m_BlackListBuffer = buf; m_BlackListBuffer.resize(fileSize); delete [] buf; m_BlackList = filename; file.close(); } // Go through the list of words size_t start = 0; size_t space = m_BlackListBuffer.find(" ",start); size_t eol = m_BlackListBuffer.find("\n",start); size_t end = space; if(eol != std::string::npos && eol < space) { if(eol == 0) { end = std::string::npos; } else { end = eol-1; } } if(end == std::string::npos && eol != std::string::npos) { if(eol == 0) { end = std::string::npos; } else { end = eol-1; } } while(end != std::string::npos && end>start) { std::string blackword = m_BlackListBuffer.substr(start,end-start); start = end+1; space = m_BlackListBuffer.find(" ",start); eol = m_BlackListBuffer.find("\n",start); end = space; if(eol != std::string::npos && eol < space) { if(eol == 0) { end = std::string::npos; } else { end = eol-1; } } if(end == std::string::npos && eol != std::string::npos) { if(eol == 0) { end = std::string::npos; } else { end = eol-1; } } if(blackword.length() <= 1) { continue; } size_t pos = m_BufferNoComment.find(blackword,0); while(pos != std::string::npos) { Error error; error.line = this->GetLineNumber(pos,true); error.line2 = error.line; error.number = BLACKLIST; error.description = "The word is in the black list"; m_ErrorList.push_back(error); hasError = true; pos = m_BufferNoComment.find(blackword,pos+1); } } return !hasError; } } // end namespace kws kwstyle-1.0.0+cvs20120330.orig/metaCommand.h0000644000175000017500000001665010461710245020033 0ustar mathieumathieu/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: metaCommand.h,v $ Language: C++ Date: $Date: 2006-07-26 15:56:21 $ Version: $Revision: 1.2 $ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef ITKMetaIO_METACOMMAND_H #define ITKMetaIO_METACOMMAND_H #ifdef _MSC_VER #pragma warning ( disable : 4786 ) #endif #include #include #include #include #include #if (METAIO_USE_NAMESPACE) namespace METAIO_NAMESPACE { #endif #include #include #define METAIO_STL std #define METAIO_STREAM std class MetaCommand { public: typedef enum {DATA_NONE,DATA_IN,DATA_OUT} DataEnumType; typedef enum {INT,FLOAT,CHAR,STRING,LIST,FLAG,BOOL} TypeEnumType; struct Field{ METAIO_STL::string name; METAIO_STL::string description; METAIO_STL::string value; TypeEnumType type; DataEnumType externaldata; METAIO_STL::string rangeMin; METAIO_STL::string rangeMax; bool required; bool userDefined; }; struct Option{ METAIO_STL::string name; METAIO_STL::string description; METAIO_STL::string tag; METAIO_STL::vector fields; bool required; bool userDefined; bool complete; }; typedef METAIO_STL::vector