Debian Codegraph @

kwsParser.h

raw
1 /*=========================================================================
2
3 Program: KWStyle - Kitware Style Checker
4 Module: kwsParser.h
5
6 Copyright (c) Kitware, Inc. All rights reserved.
7 See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
8
9 This software is distributed WITHOUT ANY WARRANTY; without even
10 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
11 PURPOSE. See the above copyright notices for more information.
12
13 =========================================================================*/
14 #ifndef kwsParser_h
15 #define kwsParser_h
16
17 // Put kwssys/Configure.h first for proper compiler warning suppression:
18 #include <kwssys/Configure.h>
19
20 #include <iostream>
21 #include <fstream>
22 #include <stdio.h>
23 #include <vector>
24 #include <kwssys/SystemTools.hxx>
25 #include <kwssys/Directory.hxx>
26 #include <kwssys/RegularExpression.hxx>
27 #include <algorithm>
28
29 namespace kws
30 {
31 #define MAX_CHAR 99999999
32 #define NUMBER_ERRORS 37
33
34 typedef enum
35 {
36 SPACE,
37 TAB
38 } IndentType;
39
40 typedef enum
41 {
42 LINE_LENGTH = 0,
43 IVAR_PUBLIC,
44 IVAR_REGEX,
45 IVAR_ALIGN,
46 SVAR_REGEX,
47 SVAR_ALIGN,
48 VARS,
49 SEMICOLON_SPACE,
50 DECL_ORDER,
51 EOF_NEW_LINE,
52 TABS,
53 SPACES,
54 INDENT,
55 HEADER,
56 NDEFINE,
57 TYPEDEF_REGEX,
58 TYPEDEF_ALIGN,
59 NAMESPACE,
60 NAMEOFCLASS,
61 WRONGCOMMENT,
62 MISSINGCOMMENT,
63 EMPTYLINES,
64 TEMPLATE,
65 OPERATOR,
66 BLACKLIST,
67 STATEMENTPERLINE,
68 VARIABLEPERLINE,
69 BADCHARACTERS,
70 MEMBERFUNCTION_REGEX,
71 MEMBERFUNCTION_LENGTH,
72 FUNCTION_REGEX,
73 FUNCTION_LENGTH,
74 USING_DIRECTIVES,
75 RELATIVE_PATH_IN_INCLUDE,
76 IFWHILEFORUNTIL,
77 COMMA,
78 PARENTHESIS
79 } ErrorType;
80
81 const char ErrorTag[NUMBER_ERRORS][4] = {
82 {'L','E','N','\0'},
83 {'I','V','P','\0'},
84 {'I','V','R','\0'},
85 {'I','V','A','\0'},
86 {'S','V','R','\0'},
87 {'S','V','A','\0'},
88 {'V','A','R','\0'},
89 {'S','E','M','\0'},
90 {'D','C','L','\0'},
91 {'E','O','F','\0'},
92 {'T','A','B','\0'},
93 {'E','S','P','\0'},
94 {'I','N','D','\0'},
95 {'H','R','D','\0'},
96 {'D','E','F','\0'},
97 {'T','D','R','\0'},
98 {'T','D','A','\0'},
99 {'N','M','S','\0'},
100 {'N','M','C','\0'},
101 {'W','C','M','\0'},
102 {'M','C','M','\0'},
103 {'E','M','L','\0'},
104 {'T','P','L','\0'},
105 {'O','P','S','\0'},
106 {'B','L','K','\0'},
107 {'S','P','L','\0'},
108 {'V','P','L','\0'},
109 {'B','C','H','\0'},
110 {'M','B','F','\0'},
111 {'M','F','L','\0'},
112 {'F','R','G','\0'},
113 {'F','L','N','\0'},
114 {'U','N','D','\0'},
115 {'R','P','I','\0'},
116 {'I','F','S','\0'},
117 {'C','M','A','\0'},
118 {'P','R','N','\0'}
119 };
120
121 struct ErrorStruct
122 {
123 unsigned long line; // main line of the error
124 unsigned long line2; // second line of error if the error is covering several lines
125 unsigned long number;
126 std::string description;
127 };
128 using Error = struct ErrorStruct;
129
130 struct WarningStruct
131 {
132 unsigned long line; // main line of the warning
133 unsigned long line2; // second line of warning if the warning is covering several lines
134 unsigned long number;
135 std::string description;
136 };
137 using Warning = struct WarningStruct;
138
139 struct IndentPositionStruct
140 {
141 // Position in the file
142 size_t position;
143 // What should be the position in the line of
144 // the word w.r.t the previous position
145 int current;
146 // What should be the position in the line of
147 // the words after w.r.t the previous position
148 int after;
149 // Name of the current ident
150 std::string name;
151 };
152 using IndentPosition = struct IndentPositionStruct;
153
154 class Parser
155 {
156 public:
157
158 /** Constructor */
159 Parser();
160
161
162 /** To be able to use std::sort we provide the < operator */
163 bool operator<(const Parser& a) const;
164
165 typedef std::vector<Error> ErrorVectorType;
166 typedef std::vector<Warning> WarningVectorType;
167 typedef std::pair<size_t,size_t> IfElseEndifPairType;
168 typedef std::vector<IfElseEndifPairType> IfElseEndifListType;
169
170 /** Set the buffer to analyze */
171 void SetBuffer(std::string buffer)
172 {
173 m_Buffer = buffer;
174 this->ConvertBufferToWindowsFileType(m_Buffer);
175 m_FixedBuffer = m_Buffer;
176 this->RemoveComments();
177
178 //Fill up the m_positions vector
179 m_Positions.clear();
180 m_Positions.push_back(0);
181 const char* currentCharacter = m_Buffer.c_str();
182 size_t currentPosition = 0;
183 while( *currentCharacter )
184 {
185 if( (*currentCharacter) == '\n' )
186 m_Positions.push_back(currentPosition);
187 currentPosition++;
188 currentCharacter++;
189 }
190 m_Positions.push_back(currentPosition);
191 }
192
193 /** Return the error tag as string given the error number */
194 std::string GetErrorTag(unsigned long number) const;
195
196 /** Return the error vector */
197 const ErrorVectorType & GetErrors() const {return m_ErrorList;}
198
199 /** Return the last error message */
200 std::string GetLastErrors();
201
202 /** Return the warning vector */
203 std::string GetLastWarnings();
204
205 /** Return the warning vector */
206 const WarningVectorType & GetWarnings() const {return m_WarningList;}
207
208 /** Check if the file contains "using namespace .* ;" */
209 bool CheckUsingDirectives(bool forbidUsingDirectives);
210
211 /** Check if the file contains includes with paths that refer to parent directory (ie: #include "../folder/file.h" ) */
212 bool CheckRelativePathInInclude(bool forbidRelativePaths);
213
214 /** Check if the file contains tabs */
215 bool CheckTabs();
216
217 /** Check the number of succesive empty lines */
218 bool CheckEmptyLines(unsigned long max,bool checkEndOfFile=false);
219
220 /** Check the comments
221 * The comment definition should be set before CheckIndent() to get the correct indentation
222 * for the comments. */
223 bool CheckComments(const char* begin,const char* middle,const char* end,
224 bool allowEmptyLineBeforeClass=false,
225 bool checkWrongComment=true,
226 bool checkMissingComment=true);
227
228 /** Check the indent size
229 * Not in the header file if there is one
230 * If CheckHeader has been done before CheckIndent and doNotCheckHeader is set to true
231 * then the header is not checked for indent*/
232 bool CheckIndent(IndentType,
233 unsigned long size,
234 bool doNotCheckHeader=false,
235 bool allowBlockLine = false,
236 unsigned int maxLength = 81,
237 bool allowCommaIndent = true
238 );
239
240 /** Check Operator spaces foo=bar or foo = bar, etc... */
241 bool CheckOperator(unsigned int before, unsigned int after,
242 unsigned long maxSize = 81,
243 bool doNotCheckInsideParenthesis = true);
244
245 /** Check comma spaces a,b versus a, b, etc... */
246 bool CheckComma(unsigned int before, unsigned int after );
247
248 /** Check parenthesis spaces ( foo ) versus (foo) */
249 bool CheckParenthesis(unsigned int space );
250
251 /** Check spaces after if, while, for, and until keywords */
252 bool CheckIfWhileForUntil(unsigned int after);
253
254 /** Check the number of character per line */
255 bool CheckLineLength(unsigned long max,bool checkHeader=false, bool doErrorCheck=true);
256
257 /** Check if the internal parameters of the class are correct */
258 bool CheckInternalVariables(const char *regEx, bool alignment = true,
259 bool checkProtected = false);
260
261 /** Check variables implementation */
262 bool CheckVariables(const char* regEx);
263
264 /** Check Member Functions implementation */
265 bool CheckMemberFunctions(const char* regEx,unsigned long maxLength=0);
266
267 /** Check any Functions implementation */
268 bool CheckFunctions(const char* regEx,unsigned long maxLength=0);
269
270 /** Check if the strcut parameters of the class are correct */
271 bool CheckStruct(const char *regEx, bool alignment = true);
272
273 /** Check if the typedefs of the class are correct */
274 bool CheckTypedefs(const char* regEx, bool alignment = true,
275 unsigned int maxLength = 81);
276
277 /** Check the order of the declaration */
278 bool CheckDeclarationOrder(size_t posPublic, size_t posProtected,size_t posPrivate);
279
280 /** Check for extra spaces */
281 bool CheckExtraSpaces(unsigned long max,bool checkEmptyLines=false);
282
283 /** Check the number of space between the end of the declaration
284 * and the semicolon */
285 bool CheckSemicolonSpace(unsigned long max);
286
287 /** Check the number of statements per line */
288 bool CheckStatementPerLine(unsigned long max=1,
289 bool checkInlineFunctions=true);
290
291 /** Check the number of variables per line */
292 bool CheckVariablePerLine(unsigned long max=1);
293
294 /** Check bad characters */
295 bool CheckBadCharacters(bool checkComments = true);
296
297 /** Check if the end of the file has a new line */
298 bool CheckEndOfFileNewLine();
299
300 /** Check header
301 * Because most of the time the header is checked in cvs we should ignore the $ $*/
302 bool CheckHeader(const char* filename,bool considerSpaceEOL = true,bool useCVS=true);
303
304 /** Check if the #ifndef/#define is defined correctly for the class */
305 bool CheckIfNDefDefine(const char* match, bool uppercaseTheDefinition=false);
306
307 /** Check the first namespace in the file */
308 bool CheckNamespace(const char* name,bool doNotCheckMain=true);
309
310 /** Check the templates */
311 bool CheckTemplate(const char *regEx);
312
313 /** Check if the name of the class is correct */
314 bool CheckNameOfClass(const char* name, const char* prefix);
315
316 /** Check that there is no word in the class that matches a word in the black list */
317 bool CheckBlackList(const char* filename);
318
319 /** Remove the comments. */
320 std::string RemoveComments(const char* buffer=nullptr);
321
322 /** Clear the error list */
323 void ClearErrors() {m_ErrorList.clear();}
324
325 /** Clear the info list */
326 void ClearInfo() {m_WarningList.clear();}
327
328 /** Set the filename of the file we are checking */
329 void SetFilename(const char* filename) {m_Filename = filename;}
330 std::string GetFilename() const {return m_Filename;}
331
332 /** Return the number of lines */
333 unsigned long GetNumberOfLines() const;
334
335 /** Return the line */
336 std::string GetLine(unsigned long i) const;
337
338 /** Return if a test has been performed */
339 bool HasBeenPerformed(unsigned int test) const;
340
341 /** Return the test description given the error number) */
342 std::string GetTestDescription(size_t test) const;
343
344 /** Given the name of the check to perform and the default value perform the check */
345 bool Check(const char* name, const char* value);
346
347 /** Should KWStyle produce a fix version of the parsed file */
348 void SetFixFile(bool fix) {m_FixFile = fix;}
349 void GenerateFixedFile();
350
351 /** return true if the position pos is between " " or ' ' */
352 bool IsBetweenQuote(size_t pos,bool withComments=false,std::string buffer="") const;
353
354 /** return true if the position pos is between ' ' */
355 bool IsBetweenSingleQuote(size_t pos,bool withComments=false,std::string buffer="") const;
356
357 /** return true if the position pos is between " " */
358 bool IsBetweenDoubleQuote(size_t pos,bool withComments=false,std::string buffer="") const;
359
360 protected:
361
362 /** Convert the file with CR+LF instead of LF */
363 void ConvertBufferToWindowsFileType(std::string & buffer);
364
365 /** Check the operator.
366 * \warning This function add an error in the Error list */
367 bool FindOperator(const char* op,unsigned int before,
368 unsigned int after,unsigned long maxSize,
369 bool doNotCheckInsideParenthesis=true);
370
371 /** Check the spaces after if, while, for, and until.
372 * \warning This function add an error in the Error list */
373 bool FindIfWhileForUntil(const char* op, unsigned int after );
374
375 /** Get the class position within the file. This function checks that this is the
376 * classname */
377 size_t GetClassPosition(size_t position,std::string buffer="") const;
378
379 /** Return the position in the line given the position in the text */
380 size_t GetPositionInLine(size_t pos);
381
382 /** Find an ivar in the source code */
383 std::string FindInternalVariable(size_t start, size_t end,size_t& pos);
384
385 /** Find an ivar in the source code */
386 std::string FindVariable(std::string & buffer,size_t start, size_t end,size_t& pos);
387
388 /** Find a member function in the source code */
389 std::string FindMemberFunction(std::string & buffer,size_t start, size_t end,size_t& pos);
390
391 /** Find a typedef in the source code */
392 std::string FindTypedef(size_t start, size_t end, size_t &pos, size_t &beg,
393 size_t &typdefpos);
394
395 /** Reduces multiple spaces in buffer to one. */
396 void ReduceMultipleSpaces(std::string & buffer);
397
398 /** Removes all val chars from string. */
399 void RemoveChar(std::string & buffer, char val) const;
400
401 /** Find the line number in the commented text given the character description */
402 long int GetLineNumber(size_t pos,bool withoutComments=false) const;
403
404 /** Find the previous word given a position */
405 std::string FindPreviousWord(size_t pos,bool withComments=false,std::string buffer="") const;
406
407 /** Find the next word given a position. This function works only without comments.*/
408 std::string FindNextWord(size_t pos) const;
409
410 /** Find the closing bracket given the position of the opening bracket. */
411 size_t FindClosingChar(char openChar, char closeChar, size_t pos,bool noComment=false,std::string buffer="") const;
412
413 /** Find the opening bracket given the position of the closing bracket. */
414 size_t FindOpeningChar(char closeChar, char openChar, size_t pos,bool noComment=false) const;
415
416 /** Find the constructor in the file. */
417 size_t FindConstructor(const std::string & buffer, const std::string & className,
418 bool headerfile=true, size_t startPos=0) const;
419
420 /** Return true if the position pos is between <>.
421 * The Fast version just check for <test> and not for <test<>,test<>>*/
422 bool IsBetweenCharsFast(const char begin, const char end, size_t pos,bool withComments=false,std::string buffer="") const;
423 bool IsBetweenChars(const char begin, const char end, size_t pos,bool withComments=false,std::string buffer="") const;
424
425 /** Return true if the position pos is between the selected quote character (' or ") */
426 bool IsBetweenQuoteChar(size_t pos,bool withComments,std::string buffer, char quoteChar) const;
427
428 bool IsValidQuote(std::string & stream,size_t pos) const;
429
430 /** Removes ass CtrlN characters from the buffer. */
431 void RemoveCtrlN(std::string & buffer) const;
432
433 /** Find the correct area given its name */
434 size_t FindArea(const char* name,size_t startPos) const;
435
436 /** Find public area in source code. */
437 void FindPublicArea(size_t &before, size_t &after, size_t startPos=0) const;
438
439 /** Find protected area in source code. */
440 void FindProtectedArea(size_t &before, size_t &after, size_t startPos=0) const;
441
442 /** Find private area in source code. */
443 void FindPrivateArea(size_t &before, size_t &after, size_t startPos=0) const;
444
445 /** Return the position of the template if the class has a template otherwise npos. */
446 size_t IsTemplated(const std::string &buffer, size_t classnamepos) const;
447
448 /** Return true if the position pos is inside a comment */
449 bool IsInComments(size_t pos) const;
450
451 /** Return true if the position pos is inside a function */
452 bool IsInFunction(size_t pos,const char* buffer=nullptr) const;
453
454 /** Return true if the position pos is inside a struct */
455 bool IsInStruct(size_t pos,const char* buffer=nullptr) const;
456
457 /** Return true if the position pos is inside a union */
458 bool IsInUnion(size_t pos,const char* buffer=nullptr) const;
459
460 /** Return true if the position pos is inside a comment defined by the compiler */
461 bool IsInAnyComments(size_t pos) const;
462
463 /** Given the position without comments return the position with the comments */
464 size_t GetPositionWithComments(size_t pos) const;
465 size_t GetPositionWithoutComments(size_t pos) const;
466
467 /** Init the indentation step for CheckIndent() */
468 bool InitIndentation();
469
470 /** Extract the current line from pos to LF */
471 std::string ExtractLine(size_t pos);
472
473 /** Return the current ident */
474 int GetCurrentIdent(std::string line,char type);
475
476 /** Helper function to add words to the special indent vector */
477 void AddIndent(const char* name,int current,int after);
478
479 /** Find the end of the class */
480 size_t FindEndOfClass(size_t position) const;
481
482 /** Return if the dept of the current class */
483 int IsInClass(size_t position) const;
484
485 /** Return the position of the last character
486 * of the function name/definition/ */
487 size_t FindFunction(size_t pos, const char *buffer = nullptr) const;
488
489 /** Compute the list of #if/#else/#endif */
490 void ComputeIfElseEndifList();
491 bool IsInElseForbiddenSection(size_t pos);
492
493 /** Functions to deal with the fixed buffer */
494 void ReplaceCharInFixedBuffer(size_t pos,size_t size,const char* replacingString);
495
496 /** Check if the current position is a valid switch statement */
497 bool CheckValidSwitchStatement(unsigned int posSwitch);
498
499 private:
500
501 ErrorVectorType m_ErrorList;
502 WarningVectorType m_WarningList;
503 bool m_TestsDone[NUMBER_ERRORS];
504 std::string m_TestsDescription[NUMBER_ERRORS];
505
506 std::string m_Buffer;
507 std::string m_BufferNoComment;
508 std::string m_FixedBuffer;
509 std::vector<size_t> m_Positions;
510 typedef std::pair<size_t, size_t> PairType;
511 std::vector<PairType> m_CommentPositions;
512 std::string m_Filename;
513 std::string m_HeaderFilename;
514 std::string m_CommentBegin;
515 std::string m_CommentMiddle;
516 std::string m_CommentEnd;
517 bool m_FixFile;
518 std::vector<PairType> m_FixedPositions;
519
520 std::vector<IndentPosition> m_IdentPositionVector;
521
522 std::string m_BlackList;
523 std::string m_BlackListBuffer;
524
525 IfElseEndifListType m_IfElseEndifList;
526 };
527
528 } // end namespace kws
529
530 #endif