Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit ab7542c

Browse files
committed
improve printing of JSON values
1 parent 1ebd49b commit ab7542c

1 file changed

Lines changed: 50 additions & 5 deletions

File tree

javascript/ql/src/semmle/javascript/PrintAst.qll

Lines changed: 50 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -210,16 +210,20 @@ private module PrintJavaScript {
210210
* Either the result is `ASTNode::toString`, or a custom made string representation of `element`.
211211
*/
212212
string print(ASTNode element) {
213-
result = element.toString().regexpReplaceAll("(\\\\n|\\\\r|\\\\t| )+", " ") and
214-
not exists(repr(element))
215-
or
216-
result = repr(element)
213+
shouldPrint(element, _) and
214+
(
215+
result = element.toString().regexpReplaceAll("(\\\\n|\\\\r|\\\\t| )+", " ") and
216+
not exists(repr(element))
217+
or
218+
result = repr(element)
219+
)
217220
}
218221

219222
/**
220223
* Gets a string representing `a`.
221224
*/
222225
private string repr(ASTNode a) {
226+
shouldPrint(a, _) and
223227
exists(DeclStmt decl | decl = a |
224228
result =
225229
getDeclarationKeyword(decl) + " " +
@@ -506,7 +510,7 @@ private module PrintJSON {
506510

507511
JSONNode() { this = TJSONNode(value) }
508512

509-
override string toString() { result = getQlClass(value) + value.toString() }
513+
override string toString() { result = getQlClass(value) + PrettyPrinting::print(value) }
510514

511515
override Location getLocation() { result = value.getLocation() }
512516

@@ -521,6 +525,47 @@ private module PrintJSON {
521525
)
522526
}
523527
}
528+
529+
/** Provied predicates for pretty printing JSON. */
530+
private module PrettyPrinting {
531+
/**
532+
* Gets a string representation of `n`.
533+
* Either using the default `JSONValue::toString`, or a custom printing of the JSON value.
534+
*/
535+
string print(JSONValue n) {
536+
shouldPrint(n, _) and
537+
(
538+
result = n.toString().regexpReplaceAll("(\\\\n|\\\\r|\\\\t| )+", " ") and
539+
not exists(repr(n))
540+
or
541+
result = repr(n)
542+
)
543+
}
544+
545+
/** Gets a string representing `n`. */
546+
private string repr(JSONValue n) {
547+
shouldPrint(n, _) and
548+
(
549+
exists(JSONObject obj, string name, JSONValue prop | obj = n |
550+
prop = obj.getPropValue(name) and
551+
prop = obj.getChild(0) and
552+
result = "{" + name + ": ...}"
553+
)
554+
or
555+
n instanceof JSONObject and not exists(n.getChild(_)) and result = "{}"
556+
or
557+
result = n.(JSONPrimitiveValue).getRawValue()
558+
or
559+
exists(JSONArray arr | arr = n |
560+
result = "[]" and not exists(arr.getChild(_))
561+
or
562+
result = "[" + repr(arr.getChild(0)) + "]" and not exists(arr.getChild(1))
563+
or
564+
result = "[" + repr(arr.getChild(0)) + ", ...]" and exists(arr.getChild(1))
565+
)
566+
)
567+
}
568+
}
524569
}
525570

526571
/**

0 commit comments

Comments
 (0)