Skip to content

Commit 105f8dd

Browse files
committed
CPP: Better fileHeaderLimit.
1 parent 91c7362 commit 105f8dd

File tree

1 file changed

+45
-11
lines changed

1 file changed

+45
-11
lines changed

cpp/ql/src/semmle/code/cpp/AutogeneratedFile.qll

Lines changed: 45 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -48,14 +48,45 @@ predicate hasPragmaDifferentFile(File f) {
4848
}
4949

5050
/**
51-
* The maximum line number we consider to be "near the beginning" of file `f`.
51+
* The line where the first comment in file `f` begins (maximum of 5). This allows
52+
* us to skip past any preprocessor logic or similar code before the first comment.
53+
*/
54+
private int fileFirstComment(File f) {
55+
result = min(int line |
56+
exists(Comment c |
57+
c.getFile() = f and
58+
c.getLocation().getStartLine() = line and
59+
line < 5
60+
)
61+
).minimum(5)
62+
}
63+
64+
/**
65+
* The line where the initial comments of file `f` end. This is just before the
66+
* first bit of code, excluding anything skipped over by `fileFirstComment`.
5267
*/
5368
private int fileHeaderLimit(File f) {
54-
result = max(int head, int line |
55-
head <= 5 and
56-
locations_default(_, underlyingElement(f), head, _, line, _) |
57-
line
58-
) + 5
69+
exists(int fc |
70+
fc = fileFirstComment(f) and
71+
result = min(int line |
72+
exists(DeclarationEntry de, Location l |
73+
l = de.getLocation() and
74+
l.getFile() = f and
75+
line = l.getStartLine() - 1 and
76+
line > fc
77+
) or exists(PreprocessorDirective pd, Location l |
78+
l = pd.getLocation() and
79+
l.getFile() = f and
80+
line = l.getStartLine() - 1 and
81+
line > fc
82+
) or exists(NamespaceDeclarationEntry nde, Location l |
83+
l = nde.getLocation() and
84+
l.getFile() = f and
85+
line = l.getStartLine() - 1 and
86+
line > fc
87+
) or line = f.getMetrics().getNumberOfLines()
88+
)
89+
)
5990
}
6091

6192
/**
@@ -69,10 +100,13 @@ private int fileHeaderLimit(File f) {
69100
*/
70101
class AutogeneratedFile extends File {
71102
cached AutogeneratedFile() {
72-
exists(Comment c |
73-
c.getFile() = this and
74-
c.getLocation().getStartLine() <= fileHeaderLimit(this) and
75-
autogeneratedComment(c)
76-
) or hasPragmaDifferentFile(this)
103+
autogeneratedComment(
104+
concat(Comment c |
105+
c.getFile() = this and
106+
c.getLocation().getStartLine() <= fileHeaderLimit(this) |
107+
c.getContents() order by c.getLocation().getStartLine()
108+
)
109+
) or
110+
hasPragmaDifferentFile(this)
77111
}
78112
}

0 commit comments

Comments
 (0)