Debian Codegraph @

plugins/symbolbrowser/symbols/parsers/parser_python.cpp

raw symbols SCIP
1 /***************************************************************************
2 A SymbolBrowser plugin for JuffEd editor.
3
4 Copyright: 2010 Aleksander Sokoloff <[email protected]>
5
6 Some of the code based on a ctags project http://ctags.sourceforge.net/
7
8 This program is free software; you can redistribute it and/or
9 modify it under the terms of the GNU General Public License.
10 version 2 as published by the Free Software Foundation.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software Foundation,
19 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 ***************************************************************************/
21
22 #ifndef PARSER_PYTHON
23 #define PARSER_PYTHON
24
25 #include <QDebug>
26 #include "../common.h"
27 #include "vstring.h"
28 #include "parser.h"
29 #include "../symbol.h"
30
31 //#define SHOW_IMPORTS
32 //#define SHOW_VARIABLES
33
34
35 /*****************************************************************************
36 *****************************************************************************/
37 class PythonSymbol: public Symbol {
38 public:
39 PythonSymbol(const Symbol::SymbolType type=SymbolUnknown, const QString &name="", Symbol *parent = NULL): Symbol(type, name, parent) {};
40 int indent() const { return mIndent; }
41 void setIndent(int value) { mIndent = value; };
42
43 private:
44 int mIndent;
45 };
46
47
48
49
50 static char const * const singletriple = "'''";
51 static char const * const doubletriple = "\"\"\"";
52
53
54
55 class Parser_Python: public Parser {
56
57 public:
58 Parser_Python();
59
60 protected:
61 void parse();
62
63 private:
64 QList<PythonSymbol*> nestingSymbols;
65 PythonSymbol* getParent(int indent);
66 void checkParent(int indent, const vString *parent);
67 void addNestingSymbol(PythonSymbol *symbol);
68
69 bool isIdentifierFirstCharacter (int c) const;
70 bool isIdentifierCharacter (int c) const;
71
72 const char *skipString (const char *cp);
73 const char *skipEverything (const char *cp);
74 const char *skipIdentifier (const char *cp);
75 const char *findDefinitionOrClass (const char *cp);
76 const char *skipSpace (const char *cp);
77 const char *parseIdentifier (const char *cp, vString *const identifier) const;
78
79 PythonSymbol* makeClass (const char *cp, vString *const className, Symbol *parent);
80 PythonSymbol* makeFunction (const char *cp, vString *const def, Symbol *parent);
81
82 void parseImports (const char *cp);
83 vString *parseArgs(const char *buf);
84
85 char const *find_triple_start(char const *string, char const **which);
86 void find_triple_end(char const *string, char const **which);
87 const char *findVariable(const char *line);
88 const char *skipTypeDecl(const char *cp, bool *is_class);
89 int calcIndent(const char *line);
90 };
91
92
93 /*****************************************************************************
94 *****************************************************************************/
95 Parser_Python::Parser_Python() {
96
97 }
98
99
100
101 /*****************************************************************************
102 *****************************************************************************/
103 bool Parser_Python::isIdentifierFirstCharacter (int c) const
104 {
105 return (bool) (isalpha (c) || c == '_');
106 }
107
108
109 /*****************************************************************************
110 *****************************************************************************/
111 bool Parser_Python::isIdentifierCharacter (int c) const
112 {
113 return (bool) (isalnum (c) || c == '_');
114 }
115
116
117 /*****************************************************************************
118 Skip a single or double quoted string.
119 *****************************************************************************/
120 const char *Parser_Python::skipString (const char *cp)
121 {
122 const char *start = cp;
123 int escaped = 0;
124 for (cp++; *cp; cp++)
125 {
126 if (escaped)
127 escaped--;
128 else if (*cp == '\\')
129 escaped++;
130 else if (*cp == *start)
131 return cp + 1;
132 }
133 return cp;
134 }
135
136
137 /*****************************************************************************
138 Skip everything up to an identifier start.
139 *****************************************************************************/
140 const char *Parser_Python::skipEverything (const char *cp)
141 {
142 for (; *cp; cp++)
143 {
144 if (*cp == '"' || *cp == '\'')
145 {
146 cp = skipString(cp);
147 if (!*cp) break;
148 }
149 if (isIdentifierFirstCharacter ((int) *cp))
150 return cp;
151 }
152 return cp;
153 }
154
155
156 /*****************************************************************************
157 Skip an identifier.
158 *****************************************************************************/
159 const char *Parser_Python::skipIdentifier (const char *cp)
160 {
161 while (isIdentifierCharacter ((int) *cp))
162 cp++;
163 return cp;
164 }
165
166
167 /*****************************************************************************
168 *****************************************************************************/
169 const char *Parser_Python::findDefinitionOrClass (const char *cp)
170 {
171 while (*cp)
172 {
173 cp = skipEverything (cp);
174 if (!strncmp(cp, "def", 3) || !strncmp(cp, "class", 5) ||
175 !strncmp(cp, "cdef", 4) || !strncmp(cp, "cpdef", 5))
176 {
177 return cp;
178 }
179 cp = skipIdentifier (cp);
180 }
181 return NULL;
182 }
183
184
185 /*****************************************************************************
186 *****************************************************************************/
187 const char *Parser_Python::skipSpace (const char *cp)
188 {
189 while (isspace ((int) *cp))
190 ++cp;
191 return cp;
192 }
193
194
195 /*****************************************************************************
196 Starting at ''cp'', parse an identifier into ''identifier''.
197 *****************************************************************************/
198 const char *Parser_Python::parseIdentifier (const char *cp, vString *const identifier) const
199 {
200 vStringClear (identifier);
201 while (isIdentifierCharacter ((int) *cp))
202 {
203 vStringPut (identifier, (int) *cp);
204 ++cp;
205 }
206 vStringTerminate (identifier);
207 return cp;
208 }
209
210
211 /*****************************************************************************
212 Given a string with the contents of the line directly after the "class"
213 keyword, extract all necessary information and create a tag.
214 *****************************************************************************/
215 PythonSymbol* Parser_Python::makeClass (const char *cp, vString *const className, Symbol *parent)
216 {
217 int lineNum = getSourceLineNumber() - 1;
218 cp = parseIdentifier (cp, className);
219 vString *const inheritance = parseArgs(cp);
220
221 Symbol * parentSymbol = (parent) ? parent : mSymbols;
222
223 QString name = vStringToQString(className);
224 PythonSymbol *symbol = new PythonSymbol(Symbol::SymbolClass, name, parentSymbol);
225 symbol->setDetailedText(QString("%1 (%2)").arg(name).arg(vStringToQString(inheritance).simplified()));
226 symbol->setLine(lineNum);
227
228
229 vStringDelete (inheritance);
230 return symbol;
231 }
232
233
234 /*****************************************************************************
235 Given a string with the contents of a line directly after the "def" keyword,
236 extract all relevant information and create a symbol.
237 *****************************************************************************/
238 PythonSymbol* Parser_Python::makeFunction (const char *cp, vString *const def, Symbol *parent)
239 {
240 int lineNum = getSourceLineNumber() - 1;
241 cp = parseIdentifier(cp, def);
242 vString *const args = parseArgs(cp);
243 Symbol * parentSymbol = (parent) ? parent : mSymbols;
244
245 QString name = vStringToQString(def);
246 PythonSymbol *symbol = new PythonSymbol(Symbol::SymbolFunc, name, parentSymbol);
247 symbol->setDetailedText(QString("%1 (%2)").arg(name).arg(vStringToQString(args)).simplified());
248 symbol->setLine(lineNum);
249
250 vStringDelete (args);
251 return symbol;
252
253 }
254
255
256 /*****************************************************************************
257 Badly
258 *****************************************************************************/
259 void Parser_Python::parseImports (const char *cp)
260 {
261 const char *pos;
262 vString *name, *name_next;
263
264 cp = skipEverything (cp);
265
266 if ((pos = strstr (cp, "import")) == NULL)
267 return;
268
269 cp = pos + 6;
270
271 /* continue only if there is some space between the keyword and the identifier */
272 if (! isspace (*cp))
273 return;
274
275 cp++;
276 cp = skipSpace (cp);
277
278 name = vStringNew ();
279 name_next = vStringNew ();
280
281 cp = skipEverything (cp);
282 while (*cp)
283 {
284 cp = parseIdentifier (cp, name);
285
286 cp = skipEverything (cp);
287 /* we parse the next possible import statement as well to be able to ignore 'foo' in
288 * 'import foo as bar' */
289 parseIdentifier (cp, name_next);
290
291 /* take the current tag only if the next one is not "as" */
292 if (strcmp (vStringValue (name_next), "as") != 0 &&
293 strcmp (vStringValue (name), "as") != 0)
294 {
295 Symbol *symbol = new Symbol(Symbol::SymbolNamespace, vStringToQString(name), mSymbols);
296 symbol->setLine(getInputLineNumber());
297 }
298 }
299 vStringDelete (name);
300 vStringDelete (name_next);
301 }
302
303
304 /*****************************************************************************
305 *****************************************************************************/
306 vString *Parser_Python::parseArgs(const char *buf)
307 {
308 vString *const res = vStringNew ();
309 const char *cp = skipSpace (buf);
310 if (*cp == '(') {
311 ++cp;
312
313 while (*cp != ')') {
314 if (*cp == '\0') {
315 /* Closing parenthesis can be in follow up line. */
316 cp = (const char *) fileReadLine ();
317 if (!cp) break;
318 vStringPut (res, ' ');
319 continue;
320 }
321
322 vStringPut(res, *cp);
323 ++cp;
324 }
325
326 vStringTerminate (res);
327 }
328
329 return res;
330 }
331
332
333 /*****************************************************************************
334
335 *****************************************************************************/
336 PythonSymbol* Parser_Python::getParent(int indent) {
337 PythonSymbol *s = NULL;
338
339 for (int i=0; i<nestingSymbols.count(); ++i) {
340 if (nestingSymbols.at(i)->indent() >= indent)
341 break;
342 s = nestingSymbols.at(i);
343 }
344
345 return s;
346 }
347
348
349 /*****************************************************************************
350 Check whether parent's indentation level is higher than the current level and
351 if so, remove it.
352 *****************************************************************************/
353 void Parser_Python::checkParent(int indent, const vString *parent) {
354 QString parentStr = vStringToQString(parent);
355
356 for (int i=0; i<nestingSymbols.count(); ++i) {
357 PythonSymbol *ns = nestingSymbols.at(i);
358
359 if (parentStr == ns->name()) {
360
361 if (indent <= ns->indent()) {
362 nestingSymbols.removeAt(i);
363 }
364
365 break;
366 }
367 }
368 }
369
370
371 /*****************************************************************************
372 *****************************************************************************/
373 void Parser_Python::addNestingSymbol(PythonSymbol *symbol) {
374
375 QList<PythonSymbol*>::iterator i;
376 for (i=nestingSymbols.begin(); i != nestingSymbols.end(); ++i) {
377 if (symbol->indent() <= (*i)->indent())
378 break;
379 }
380
381 nestingSymbols.erase(i, nestingSymbols.end());
382 nestingSymbols.append(symbol);
383
384 }
385
386
387 /*****************************************************************************
388 Return a pointer to the start of the next triple string, or NULL. Store
389 the kind of triple string in "which" if the return is not NULL.
390 *****************************************************************************/
391 char const *Parser_Python::find_triple_start(char const *string, char const **which)
392 {
393 char const *cp = string;
394
395 for (; *cp; cp++)
396 {
397 if (*cp == '"' || *cp == '\'')
398 {
399 if (strncmp(cp, doubletriple, 3) == 0)
400 {
401 *which = doubletriple;
402 return cp;
403 }
404 if (strncmp(cp, singletriple, 3) == 0)
405 {
406 *which = singletriple;
407 return cp;
408 }
409 cp = skipString(cp);
410 if (!*cp) break;
411 }
412 }
413 return NULL;
414 }
415
416
417 /*****************************************************************************
418 Find the end of a triple string as pointed to by "which", and update "which"
419 with any other triple strings following in the given string.
420 *****************************************************************************/
421 void Parser_Python::find_triple_end(char const *string, char const **which)
422 {
423 char const *s = string;
424 while (1)
425 {
426 /* Check if the string ends in the same line. */
427 s = strstr (s, *which);
428 if (!s) break;
429 s += 3;
430 *which = NULL;
431 /* If yes, check if another one starts in the same line. */
432 s = find_triple_start(s, which);
433 if (!s) break;
434 s += 3;
435 }
436 }
437
438
439 /*****************************************************************************
440
441 *****************************************************************************/
442 const char *Parser_Python::findVariable(const char *line)
443 {
444 /* Parse global and class variable names (C.x) from assignment statements.
445 * Object attributes (obj.x) are ignored.
446 * Assignment to a tuple 'x, y = 2, 3' not supported.
447 * TODO: ignore duplicate tags from reassignment statements. */
448 const char *cp, *sp, *eq, *start;
449
450 cp = strstr(line, "=");
451 if (!cp)
452 return NULL;
453
454 eq = cp + 1;
455 while (*eq)
456 {
457 if (*eq == '=')
458 return NULL; /* ignore '==' operator and 'x=5,y=6)' function lines */
459
460 if (*eq == '(' || *eq == '#')
461 break; /* allow 'x = func(b=2,y=2,' lines and comments at the end of line */
462
463 eq++;
464 }
465
466 /* go backwards to the start of the line, checking we have valid chars */
467 start = cp - 1;
468 while (start >= line && isspace ((int) *start))
469 --start;
470
471 while (start >= line && isIdentifierCharacter ((int) *start))
472 --start;
473
474 if (!isIdentifierFirstCharacter(*(start + 1)))
475 return NULL;
476
477 sp = start;
478 while (sp >= line && isspace ((int) *sp))
479 --sp;
480
481 if ((sp + 1) != line) /* the line isn't a simple variable assignment */
482 return NULL;
483
484 /* the line is valid, parse the variable name */
485 ++start;
486 return start;
487 }
488
489
490 /*****************************************************************************
491 Skip type declaration that optionally follows a cdef/cpdef
492 *****************************************************************************/
493 const char *Parser_Python::Parser_Python::skipTypeDecl(const char *cp, bool *is_class)
494 {
495 const char *lastStart = cp, *ptr = cp;
496 int loopCount = 0;
497 ptr = skipSpace(cp);
498 if (!strncmp("extern", ptr, 6)) {
499 ptr += 6;
500 ptr = skipSpace(ptr);
501 if (!strncmp("from", ptr, 4)) { return NULL; }
502 }
503 if (!strncmp("class", ptr, 5)) {
504 ptr += 5 ;
505 *is_class = true;
506 ptr = skipSpace(ptr);
507 return ptr;
508 }
509 /* limit so that we don't pick off "int item=obj()" */
510 while (*ptr && loopCount++ < 2) {
511 while (*ptr && *ptr != '=' && *ptr != '(' && !isspace(*ptr)) ptr++;
512 if (!*ptr || *ptr == '=') return NULL;
513 if (*ptr == '(') {
514 return lastStart; /* if we stopped on a '(' we are done */
515 }
516 ptr = skipSpace(ptr);
517 lastStart = ptr;
518 while (*lastStart == '*') lastStart++; /* cdef int *identifier */
519 }
520 return NULL;
521 }
522
523
524 /*****************************************************************************
525 *****************************************************************************/
526 int Parser_Python::calcIndent(const char *line) {
527 int indent = 0;
528
529 while(true) {
530 switch (*line) {
531 case ' ':
532 indent+= 1;
533 break;
534
535 case '\t':
536 indent+= 8;
537 break;
538
539 default:
540 return indent;
541 }
542 line++;
543 }
544
545 }
546
547
548 /*****************************************************************************
549 *****************************************************************************/
550 void Parser_Python::parse()
551 {
552 vString *const continuation = vStringNew ();
553 vString *const name = vStringNew ();
554 vString *const parent = vStringNew();
555
556 const char *line;
557 int line_skip = 0;
558 char const *longStringLiteral = NULL;
559
560 while ((line = (const char *) fileReadLine ()) != NULL)
561 {
562 const char *cp = line, *candidate;
563 char const *longstring, *keyword;
564 int indent;
565
566 cp = skipSpace (cp);
567
568 if (*cp == '\0') /* skip blank line */
569 continue;
570
571 /* Skip comment if we are not inside a multi-line string. */
572 if (*cp == '#' && !longStringLiteral)
573 continue;
574
575 /* Deal with line continuation. */
576 if (!line_skip) vStringClear(continuation);
577
578
579 vStringCatS(continuation, line);
580 vStringStripTrailing(continuation);
581
582
583 if (vStringLast(continuation) == '\\')
584 {
585 vStringChop(continuation);
586 vStringCatS(continuation, " ");
587 line_skip = 1;
588 continue;
589 }
590
591
592
593 cp = line = vStringValue(continuation);
594 cp = skipSpace (cp);
595 indent = calcIndent(line);
596 line_skip = 0;
597
598 checkParent(indent, parent);
599
600 /* Deal with multiline string ending. */
601 if (longStringLiteral)
602 {
603 find_triple_end(cp, &longStringLiteral);
604 continue;
605 }
606
607 /* Deal with multiline string start. */
608 longstring = find_triple_start(cp, &longStringLiteral);
609 if (longstring)
610 {
611 longstring += 3;
612 find_triple_end(longstring, &longStringLiteral);
613 /* We don't parse for any tags in the rest of the line. */
614 continue;
615 }
616
617 /* Deal with def and class keywords. */
618 keyword = findDefinitionOrClass (cp);
619 if (keyword)
620 {
621 bool found = false;
622 bool is_class = false;
623
624 if (!strncmp (keyword, "def", 3) && isspace(keyword[3]))
625 {
626 cp = skipSpace (keyword + 3);
627 found = true;
628 }
629 else if (!strncmp (keyword, "class", 5) && isspace(keyword[5]))
630 {
631 cp = skipSpace (keyword + 5);
632 found = true;
633 is_class = true;
634 }
635 else if (!strncmp (keyword, "cdef", 4) && isspace(keyword[4]))
636 {
637 cp = skipSpace(keyword + 4);
638 candidate = skipTypeDecl (cp, &is_class);
639 if (candidate)
640 {
641 found = true;
642 cp = candidate;
643 }
644
645 }
646 else if (!strncmp (keyword, "cpdef", 5) && isspace(keyword[5]))
647 {
648 cp = skipSpace(keyword + 5);
649 candidate = skipTypeDecl (cp, &is_class);
650 if (candidate)
651 {
652 found = true;
653 cp = candidate;
654 }
655 }
656
657 if (found)
658 {
659 PythonSymbol *symbol = NULL;
660 PythonSymbol *parentSymbol;
661
662 parentSymbol = getParent(indent);
663
664 if (is_class)
665 symbol = makeClass (cp, name, parentSymbol);
666 else
667 symbol = makeFunction(cp, name, parentSymbol);
668
669 symbol->setIndent(indent);
670 nestingSymbols.append(symbol);
671
672 addNestingSymbol(symbol);
673 // continue;
674 }
675 }
676
677
678 /* Find global and class variables */
679 #ifdef SHOW_VARIABLES
680 char const *variable = findVariable(line);
681 if (variable)
682 {
683 const char *start = variable;
684
685 vStringClear (name);
686 while (isIdentifierCharacter ((int) *start))
687 {
688 vStringPut (name, (int) *start);
689 ++start;
690 }
691 vStringTerminate (name);
692
693 PythonSymbol *symbol = NULL;
694 PythonSymbol *parentSymbol = getParent(indent);
695
696
697 symbol = new PythonSymbol(parentSymbol, vStringToQString(name));
698 symbol->setIndent(indent);
699 symbol->setLine(this->getSourceLineNumber());
700 symbol->setIconType(Symbol::IconVar);
701 }
702 #endif
703
704 /* Find and parse imports */
705 #ifdef SHOW_IMPORTS
706 parseImports(line);
707 #endif
708 }
709
710 /* Clean up all memory we allocated. */
711 vStringDelete (parent);
712 vStringDelete (name);
713 vStringDelete (continuation);
714 }
715
716 #endif // PARSER_PYTHON