Skip to content

Commit f5d4b2e

Browse files
committed
C#: Make Element.getLocation (mostly) functional
1 parent 3c22067 commit f5d4b2e

File tree

1 file changed

+34
-7
lines changed

1 file changed

+34
-7
lines changed

csharp/ql/lib/semmle/code/csharp/ExprOrStmtParent.qll

Lines changed: 34 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -51,8 +51,6 @@ class TopLevelExprParent extends Element, @top_level_expr_parent {
5151
final Expr getAChildExpr() { result = this.getChildExpr(_) }
5252
}
5353

54-
private predicate hasNoSourceLocation(Element e) { not e.getALocation() instanceof SourceLocation }
55-
5654
/** INTERNAL: Do not use. */
5755
Expr getExpressionBody(Callable c) {
5856
result = c.getAChildExpr() and
@@ -67,17 +65,46 @@ private ControlFlowElement getBody(Callable c) {
6765
result = getStatementBody(c)
6866
}
6967

68+
pragma[nomagic]
69+
private Location getASourceLocation(Element e) {
70+
result = e.getALocation().(SourceLocation) and
71+
not exists(e.getALocation().(SourceLocation).getMappedLocation())
72+
or
73+
result = e.getALocation().(SourceLocation).getMappedLocation()
74+
}
75+
76+
pragma[nomagic]
77+
private predicate hasNoSourceLocation(Element e) { not exists(getASourceLocation(e)) }
78+
79+
pragma[nomagic]
80+
private Location getFirstSourceLocation(Element e) {
81+
result =
82+
min(Location l, string filepath, int startline, int startcolumn, int endline, int endcolumn |
83+
l = getASourceLocation(e) and
84+
l.hasLocationInfo(filepath, startline, startcolumn, endline, endcolumn)
85+
|
86+
l order by filepath, startline, startcolumn, endline, endcolumn
87+
)
88+
}
89+
7090
cached
7191
private module Cached {
7292
cached
7393
Location bestLocation(Element e) {
74-
result = e.getALocation().(SourceLocation) and
75-
not exists(e.getALocation().(SourceLocation).getMappedLocation())
76-
or
77-
result = e.getALocation().(SourceLocation).getMappedLocation()
94+
(
95+
if e.(Modifiable).isPartial() or e instanceof Namespace
96+
then result = getASourceLocation(e)
97+
else result = getFirstSourceLocation(e)
98+
)
7899
or
79100
hasNoSourceLocation(e) and
80-
result = min(Location l | l = e.getALocation() | l order by l.getFile().toString())
101+
result =
102+
min(Location l, string filepath |
103+
l = e.getALocation() and
104+
l.hasLocationInfo(filepath, _, _, _, _)
105+
|
106+
l order by filepath
107+
)
81108
or
82109
not exists(e.getALocation()) and
83110
result instanceof EmptyLocation

0 commit comments

Comments
 (0)