Skip to content

Commit 2c27ce7

Browse files
committed
Python: Make ast viewer see regexes
This work is due to @erik-krogh who also - made corresponding fixes to `RegexTreeView.qll` - implemented `toUnicode` so it is available on `String`s
1 parent d953ba8 commit 2c27ce7

File tree

1 file changed

+41
-1
lines changed

1 file changed

+41
-1
lines changed

python/ql/src/semmle/python/PrintAst.qll

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
*/
88

99
import python
10+
import semmle.python.RegexTreeView
1011

1112
private newtype TPrintAstConfiguration = MkPrintAstConfiguration()
1213

@@ -53,6 +54,9 @@ private newtype TPrintAstNode =
5354
not list = any(Module mod).getBody() and
5455
not forall(AstNode child | child = list.getAnItem() | isNotNeeded(child)) and
5556
exists(list.getAnItem())
57+
} or
58+
TRegExpTermNode(RegExpTerm term) {
59+
exists(StrConst str | term.getRootTerm() = getParsedRegExp(str) and shouldPrint(str, _))
5660
}
5761

5862
/**
@@ -419,6 +423,42 @@ class ParameterNode extends AstElementNode {
419423
}
420424
}
421425

426+
/**
427+
* A print node for a `StrConst`.
428+
*
429+
* The string has a child, if the child is used as a regular expression,
430+
* which is the root of the regular expression.
431+
*/
432+
class StrConstNode extends AstElementNode {
433+
override StrConst element;
434+
435+
override PrintAstNode getChild(int childIndex) {
436+
childIndex = 0 and result.(RegExpTermNode).getTerm() = getParsedRegExp(element)
437+
}
438+
}
439+
440+
/**
441+
* A print node for a regular expression term.
442+
*/
443+
class RegExpTermNode extends TRegExpTermNode, PrintAstNode {
444+
RegExpTerm term;
445+
446+
RegExpTermNode() { this = TRegExpTermNode(term) }
447+
448+
/** Gets the `RegExpTerm` for this node. */
449+
RegExpTerm getTerm() { result = term }
450+
451+
override PrintAstNode getChild(int childIndex) {
452+
result.(RegExpTermNode).getTerm() = term.getChild(childIndex)
453+
}
454+
455+
override string toString() {
456+
result = "[" + strictconcat(term.getPrimaryQLClass(), " | ") + "] " + term.toString()
457+
}
458+
459+
override Location getLocation() { result = term.getLocation() }
460+
}
461+
422462
/**
423463
* Gets the `i`th child from `node` ordered by location.
424464
*/
@@ -447,7 +487,7 @@ private module PrettyPrinting {
447487
string getQlClass(AstNode a) {
448488
shouldPrint(a, _) and
449489
(
450-
not exists(getQlCustomClass(a)) and result = a.toString()
490+
not exists(getQlCustomClass(a)) and result = strictconcat(a.toString(), " | ")
451491
or
452492
result = strictconcat(getQlCustomClass(a), " | ")
453493
)

0 commit comments

Comments
 (0)