Skip to content

Commit a3c1e8d

Browse files
dmcppcheckclaude
andcommitted
explorer: fix review comments
- hl() and scanBlock() now share one tokenizer so they agree on where block comments start and end. scanBlock() treated the ' in digit separators (1'000) and header names (#include <a'b>) as character literals, so a block comment that was open at a chunk boundary could be missed and the next chunk was highlighted as code. - Long lines that are not highlighted still update the comment state. - Ignore the message of checkersReport when matching old and new warnings, it differs between xml versions and cppcheck versions. - Lint and compile reports/**/*.py in CI, and run all explorer tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 38f6275 commit a3c1e8d

4 files changed

Lines changed: 185 additions & 57 deletions

File tree

‎.github/workflows/scriptcheck.yml‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ jobs:
109109
if: matrix.python-latest
110110
run: |
111111
shopt -s globstar
112-
pylint --jobs $(nproc) --py-version 3.7 addons/**/*.py reports/htmlreport/cppcheck-htmlreport reports/htmlreport/**/*.py test/**/*.py tools/**/*.py
112+
pylint --jobs $(nproc) --py-version 3.7 addons/**/*.py reports/htmlreport/cppcheck-htmlreport reports/**/*.py test/**/*.py tools/**/*.py
113113
114114
- name: check .json files
115115
if: matrix.python-latest
@@ -126,7 +126,7 @@ jobs:
126126
shopt -s globstar
127127
python -m py_compile addons/**/*.py
128128
python -m py_compile reports/htmlreport/cppcheck-htmlreport
129-
python -m py_compile reports/htmlreport/**/*.py
129+
python -m py_compile reports/**/*.py
130130
python -m py_compile test/**/*.py
131131
python -m py_compile tools/**/*.py
132132
@@ -199,11 +199,11 @@ jobs:
199199
env:
200200
PYTHONPATH: ./tools
201201

202-
# uses the node that is installed on the runner
203-
- name: test explorer report javascript
202+
# the javascript tests use the node that is installed on the runner
203+
- name: test explorer report
204204
run: |
205205
node --version
206-
python -m pytest -Werror --strict-markers -vv test/tools/explorer/explorer_js_test.py
206+
python -m pytest -Werror --strict-markers -vv test/tools/explorer/
207207
208208
- name: Show all ignored files
209209
if: false # TODO: currently lists all the contents of ignored folders - we only need what actually matched

‎reports/explorer/report.py‎

Lines changed: 57 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -177,13 +177,20 @@ def parse_reports(paths):
177177
return combined
178178

179179

180+
# warnings without hash whose message is ignored when matching old and new warnings
181+
# checkersReport: "Active checkers: 176/189 (use --checkers-report=<filename> to see details)"
182+
VARYING_MESSAGE_IDS = {'checkersReport'}
183+
184+
180185
def result_key(r):
181186
"""Key used to match warnings between the old and the new report."""
182187
if r['hash']:
183188
return 'h:' + r['hash']
184189
# No hash (e.g. missingInclude). Use a key that does not depend on line numbers.
185190
files = '|'.join(loc['file'] for loc in r['locations'])
186-
return 'k:%s|%s|%s' % (r['id'], r['msg'], files)
191+
# the message of these changes with the cppcheck version and xml version
192+
msg = '' if r['id'] in VARYING_MESSAGE_IDS else r['msg']
193+
return 'k:%s|%s|%s' % (r['id'], msg, files)
187194

188195

189196
def primary_file(r):
@@ -1454,77 +1461,76 @@ def main():
14541461
'int8_t int16_t int32_t int64_t uint8_t uint16_t uint32_t uint64_t intptr_t uintptr_t std string vector map set list FILE').split(' '));
14551462
const TOK = /(\/\/.*$)|(\/\*)|("(?:\\.|[^"\\])*"?)|('(?:\\.|[^'\\])*'?)|(\b\d[\w.']*|\.\d[\w']*)|([A-Za-z_]\w*)(\s*\()?|([^\w\s"'\/]+|\/|\s+)/y;
14561463
1457-
// returns true if the line ends inside a block comment
1458-
function scanBlock(line, block) {
1459-
let i = 0;
1460-
const n = line.length;
1461-
while (i < n) {
1462-
if (block) {
1463-
const e = line.indexOf('*/', i);
1464-
if (e < 0) return true;
1465-
block = false; i = e + 2;
1466-
continue;
1467-
}
1468-
const c = line.charCodeAt(i);
1469-
if (c === 47 /* / */) {
1470-
const d = line.charCodeAt(i + 1);
1471-
if (d === 47) return false;
1472-
if (d === 42) { block = true; i += 2; continue; }
1473-
} else if (c === 34 || c === 39) {
1474-
i++;
1475-
while (i < n && line.charCodeAt(i) !== c) i += line.charCodeAt(i) === 92 ? 2 : 1;
1476-
}
1477-
i++;
1478-
}
1479-
return block;
1480-
}
1481-
1482-
function hl(line, st) {
1483-
if (line.length > 3000) return esc(line);
1484-
let out = '', pos = 0;
1464+
// Split a line of C/C++ code into tokens and call emit(cls, text) for each token, cls is the
1465+
// t-<cls> css class or '' for plain text. emit can be null to only update the state.
1466+
// st.block is true if the line starts inside a block comment, and is updated for the next line.
1467+
// hl() and scanBlock() both use this so they always agree on where block comments start and end.
1468+
function lexLine(line, st, emit) {
1469+
const put = emit || (() => {});
1470+
let pos = 0;
14851471
if (st.block) {
14861472
const e = line.indexOf('*/');
1487-
if (e < 0) return `<span class="t-co">${esc(line)}</span>`;
1488-
out += `<span class="t-co">${esc(line.slice(0, e + 2))}</span>`;
1473+
if (e < 0) { put('co', line); return; }
1474+
put('co', line.slice(0, e + 2));
14891475
pos = e + 2; st.block = false;
14901476
}
14911477
if (pos === 0 && /^\s*#/.test(line)) {
1492-
const m = /^(\s*#\s*\w*)(.*)$/.exec(line);
1493-
out += `<span class="t-pp">${esc(m[1])}</span>`;
1494-
const inc = /^(\s*)(<[^>]*>|"[^"]*")(.*)$/.exec(m[2]);
1495-
if (inc) return out + esc(inc[1]) + `<span class="t-st">${esc(inc[2])}</span>` + hlRest(inc[3], st);
1496-
return out + hlRest(m[2], st);
1478+
const m = /^(\s*#\s*\w*)([\s\S]*)$/.exec(line);
1479+
put('pp', m[1]);
1480+
const inc = /^(\s*)(<[^>]*>|"[^"]*")([\s\S]*)$/.exec(m[2]);
1481+
if (inc) {
1482+
put('', inc[1]);
1483+
put('st', inc[2]);
1484+
lexRest(inc[3], st, put);
1485+
} else lexRest(m[2], st, put);
1486+
return;
14971487
}
1498-
return out + hlRest(line.slice(pos), st);
1488+
lexRest(line.slice(pos), st, put);
14991489
}
15001490
1501-
function hlRest(s, st) {
1502-
let out = '';
1491+
function lexRest(s, st, put) {
15031492
TOK.lastIndex = 0;
15041493
while (TOK.lastIndex < s.length) {
15051494
const start = TOK.lastIndex;
15061495
const m = TOK.exec(s);
1507-
if (!m) { out += esc(s.slice(start)); break; }
1508-
if (m[1]) out += `<span class="t-co">${esc(m[1])}</span>`;
1496+
if (!m) { put('', s.slice(start)); break; }
1497+
if (m[1]) put('co', m[1]);
15091498
else if (m[2]) {
15101499
const e = s.indexOf('*/', TOK.lastIndex);
1511-
if (e < 0) { out += `<span class="t-co">${esc(s.slice(start))}</span>`; st.block = true; break; }
1512-
out += `<span class="t-co">${esc(s.slice(start, e + 2))}</span>`;
1500+
if (e < 0) { put('co', s.slice(start)); st.block = true; break; }
1501+
put('co', s.slice(start, e + 2));
15131502
TOK.lastIndex = e + 2;
1514-
} else if (m[3] || m[4]) out += `<span class="t-st">${esc(m[3] || m[4])}</span>`;
1515-
else if (m[5]) out += `<span class="t-nu">${esc(m[5])}</span>`;
1503+
} else if (m[3] || m[4]) put('st', m[3] || m[4]);
1504+
else if (m[5]) put('nu', m[5]);
15161505
else if (m[6]) {
15171506
const w = m[6];
1518-
if (KW.has(w)) out += `<span class="t-kw">${w}</span>`;
1519-
else if (TY.has(w)) out += `<span class="t-ty">${w}</span>`;
1520-
else if (m[7]) out += `<span class="t-fn">${w}</span>`;
1521-
else out += w;
1522-
if (m[7]) out += esc(m[7]);
1523-
} else out += esc(m[8]);
1507+
put(KW.has(w) ? 'kw' : TY.has(w) ? 'ty' : m[7] ? 'fn' : '', w);
1508+
if (m[7]) put('', m[7]);
1509+
} else put('', m[8]);
1510+
}
1511+
}
1512+
1513+
// highlight a line, st.block is updated for the next line
1514+
function hl(line, st) {
1515+
if (line.length > 3000) {
1516+
// too long to highlight, but the comment state is still needed for the next lines
1517+
lexLine(line, st, null);
1518+
return esc(line);
15241519
}
1520+
let out = '';
1521+
lexLine(line, st, (cls, text) => { out += cls ? `<span class="t-${cls}">${esc(text)}</span>` : esc(text); });
15251522
return out;
15261523
}
15271524
1525+
// returns true if the line ends inside a block comment
1526+
function scanBlock(line, block) {
1527+
// the state can only change on a line with "/*" (outside a comment) or "*/" (inside one)
1528+
if (line.indexOf(block ? '*/' : '/*') < 0) return block;
1529+
const st = { block };
1530+
lexLine(line, st, null);
1531+
return st.block;
1532+
}
1533+
15281534
return { esc, fmt, pct, cap, basename, countBy, highlightMatch, tipInner, tipHtml, niceStep, yAxis, fmtShort, scanBlock, hl };
15291535
})();
15301536
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
#!/usr/bin/env python3
2+
"""Test the Python side of the Cppcheck Explorer report (reports/explorer/report.py)."""
3+
4+
import importlib.util
5+
import os
6+
import subprocess
7+
import sys
8+
9+
TEST_DIR = os.path.dirname(os.path.abspath(__file__))
10+
ROOT_DIR = os.path.dirname(os.path.dirname(os.path.dirname(TEST_DIR)))
11+
REPORT_PY = os.path.join(ROOT_DIR, 'reports', 'explorer', 'report.py')
12+
13+
14+
def load_report():
15+
spec = importlib.util.spec_from_file_location('explorer_report', REPORT_PY)
16+
module = importlib.util.module_from_spec(spec)
17+
spec.loader.exec_module(module)
18+
return module
19+
20+
21+
report = load_report()
22+
23+
24+
def result(id, msg, files=('a.cpp',), hash=''):
25+
return {'id': id, 'msg': msg, 'hash': hash,
26+
'locations': [{'file': f, 'line': 1, 'column': 1, 'info': ''} for f in files]}
27+
28+
29+
def test_result_key_hash():
30+
assert report.result_key(result('uninitvar', 'x', hash='123')) == report.result_key(result('uninitvar', 'y', ('b.cpp',), hash='123'))
31+
assert report.result_key(result('uninitvar', 'x', hash='123')) != report.result_key(result('uninitvar', 'x', hash='456'))
32+
33+
34+
def test_result_key_without_hash():
35+
# without hash the message and files are used
36+
assert report.result_key(result('missingInclude', 'a.h')) == report.result_key(result('missingInclude', 'a.h'))
37+
assert report.result_key(result('missingInclude', 'a.h')) != report.result_key(result('missingInclude', 'b.h'))
38+
assert report.result_key(result('missingInclude', 'a.h')) != report.result_key(result('missingInclude', 'a.h', ('b.cpp',)))
39+
40+
41+
def test_result_key_checkers_report():
42+
# the checkersReport message differs between xml versions and cppcheck versions
43+
v2 = result('checkersReport', 'Active checkers: 176/189 (use --checkers-report=<filename> to see details)', ())
44+
v3 = result('checkersReport', 'Active checkers: 176/189', ())
45+
upgrade = result('checkersReport', 'Active checkers: 180/195', ())
46+
assert report.result_key(v2) == report.result_key(v3) == report.result_key(upgrade)
47+
48+
49+
def xml(checkers_msg, xml_version=2):
50+
return '''<?xml version="1.0" encoding="UTF-8"?>
51+
<results version="%d">
52+
<cppcheck version="2.19 dev"/>
53+
<errors>
54+
<error id="uninitvar" severity="error" msg="Uninitialized variable: x" verbose="Uninitialized variable: x" cwe="457" hash="111">
55+
<location file="a.cpp" line="3" column="12"/>
56+
</error>
57+
<error id="missingIncludeSystem" severity="information" msg="Include file: &lt;x.h&gt; not found." verbose="Include file: &lt;x.h&gt; not found."/>
58+
<error id="checkersReport" severity="information" msg="%s" verbose="%s"/>
59+
</errors>
60+
</results>
61+
''' % (xml_version, checkers_msg, checkers_msg)
62+
63+
64+
def run_report(tmp_path, new_xml, old_xml):
65+
(tmp_path / 'new.xml').write_text(new_xml, encoding='utf-8')
66+
(tmp_path / 'old.xml').write_text(old_xml, encoding='utf-8')
67+
p = subprocess.run([sys.executable, REPORT_PY, str(tmp_path / 'new.xml'), '--baseline', str(tmp_path / 'old.xml'),
68+
'-o', str(tmp_path / 'out')],
69+
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, check=False)
70+
assert p.returncode == 0, p.stdout
71+
return p.stdout
72+
73+
74+
def test_baseline_checkers_report_v2_v3(tmp_path):
75+
# same warnings, only the checkersReport message differs
76+
out = run_report(tmp_path,
77+
xml('Active checkers: 176/189', 3),
78+
xml('Active checkers: 176/189 (use --checkers-report=&lt;filename&gt; to see details)', 2))
79+
assert '(3 warnings, 0 new, 0 fixed' in out
80+
81+
82+
def test_baseline_checkers_report_upgrade(tmp_path):
83+
# more checkers after a cppcheck upgrade
84+
out = run_report(tmp_path, xml('Active checkers: 180/195'), xml('Active checkers: 176/189'))
85+
assert '(3 warnings, 0 new, 0 fixed' in out
86+
87+
88+
def test_baseline_new_and_fixed(tmp_path):
89+
old = xml('Active checkers: 176/189')
90+
new = old.replace('hash="111"', 'hash="222"').replace('x.h', 'y.h')
91+
out = run_report(tmp_path, new, old)
92+
assert '(3 warnings, 2 new, 2 fixed' in out

‎test/tools/explorer/lib.test.js‎

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,20 @@ test('hl: block comment over several lines', () => {
147147

148148
test('hl and scanBlock agree on where block comments end', () => {
149149
// the code view renders chunks lazily and uses scanBlock() to find the state at the start of a chunk
150-
const lines = ['int a; /* x', 'y */ int b; // /*', 's = "/*"; /* z', '*/', '/**/ c /*', 'd */'];
150+
const lines = [
151+
'int a; /* x', 'y */ int b; // /*', 's = "/*"; /* z', '*/', '/**/ c /*', 'd */',
152+
// a ' that is not a character literal
153+
"int x = 1'000; /* start of comment", '*/',
154+
"#include <a'b> /* x", '*/',
155+
"#include \"a'b\" /* x", '*/',
156+
"char c = 'a'; /* x", '*/',
157+
"c = '\\''; /* x", '*/',
158+
// unterminated literals
159+
"#error don't /* x", 's = "abc /* x',
160+
// a line that is too long to highlight
161+
'x'.repeat(3001) + ' /* x', 'y */ z',
162+
'/* a */ /* b */ /*', '*/ /* */',
163+
];
151164
const st = { block: false };
152165
let block = false;
153166
for (const l of lines) {
@@ -156,3 +169,20 @@ test('hl and scanBlock agree on where block comments end', () => {
156169
assert.equal(st.block, block, `after line ${JSON.stringify(l)}`);
157170
}
158171
});
172+
173+
test('scanBlock: digit separators and header names', () => {
174+
assert.equal(L.scanBlock("int x = 1'000; /* start of comment", false), true);
175+
assert.equal(L.scanBlock("#include <a'b> /* x", false), true);
176+
assert.equal(L.scanBlock("int x = 1'000; // /*", false), false);
177+
});
178+
179+
test('hl: a block comment in a long line continues on the next line', () => {
180+
const st = { block: false };
181+
L.hl('x'.repeat(3001) + ' /* x', st);
182+
assert.equal(st.block, true);
183+
assert.equal(L.hl('y */ z', st), '<span class="t-co">y */</span> z');
184+
});
185+
186+
test('hl: preprocessor line with a line separator character', () => {
187+
assert.equal(L.hl('#define A 
 B', { block: false }), '<span class="t-pp">#define</span> A 
 B');
188+
});

0 commit comments

Comments
 (0)