DBC Framework
DBC parsing and CAN signal decoding framework
Loading...
Searching...
No Matches
dbc_parser_test.cpp
2#include "dbc_decoder.h"
3#include "dbc_parser.h"
4#include "dbc_statement_handler.h"
5#include "dbc_tree_builder.h"
6#include <algorithm>
7#include <clocale>
8#include <limits>
9#include <locale>
10
11#include <QtTest>
12#include <chrono>
13#include <filesystem>
14#include <fstream>
15
16#define CHECK(condition, name) QVERIFY2((condition), std::string(name).c_str())
17#include <stdexcept>
18
19struct Fixture {
20 std::filesystem::path path = std::filesystem::temp_directory_path() /
21 ("dbc_parser_test_" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()) + ".dbc");
22 ~Fixture() {
23 std::error_code error;
24 std::filesystem::remove(path, error);
25 }
26 void Write(const std::string &text) const {
27 std::ofstream output(path);
28 output << text;
29 if (!output)
30 throw std::runtime_error("Cannot write test fixture.");
31 }
32};
33
34class CommaDecimalPunctuation : public std::numpunct<char> {
35protected:
36 char do_decimal_point() const override { return ','; }
37 char do_thousands_sep() const override { return '.'; }
38 std::string do_grouping() const override { return "\3"; }
39};
40
41class ApplicationLocaleGuard {
42public:
43 ApplicationLocaleGuard()
44 : previousCppLocale(std::locale()), previousCLocale(std::setlocale(LC_ALL, nullptr)) {}
45 ~ApplicationLocaleGuard() {
46 std::locale::global(previousCppLocale);
47 std::setlocale(LC_ALL, previousCLocale.c_str());
48 }
49
50private:
51 std::locale previousCppLocale;
52 std::string previousCLocale;
53};
54
55class CountingHandler : public DbcStatementHandler {
56public:
57 inline static int instances = 0;
58 inline static int calls = 0;
59 CountingHandler() { ++instances; }
60 void Handle(const std::string &, DbcParseContext &context) const override {
61 ++calls;
62 context.database.frames.emplace_back();
63 }
64};
65
66std::string SignalLine(const std::string &start, const std::string &length,
67 const std::string &order, const std::string &factor,
68 const std::string &offset, const std::string &minimum,
69 const std::string &maximum, const std::string &name = "Value") {
70 return "SG_ " + name + " : " + start + "|" + length + "@" + order +
71 " (" + factor + "," + offset + ") [" + minimum + "|" + maximum + "] \"\" ECU";
72}
73
74class DbcParserTest : public QObject {
75 Q_OBJECT
76private:
77 void CheckPhysicalNumbers();
78 void RejectSignal(const Fixture &fixture, const std::string &line, unsigned payload = 8U) {
79 fixture.Write("BO_ 1 Frame: " + std::to_string(payload) + " ECU\n\n" + line + "\n");
80 try {
81 DbcParser().ParseFile(fixture.path.string());
82 CHECK(false, "Reject " + line);
83 } catch (const std::runtime_error &error) {
84 const std::string prefix = fixture.path.string() + ":3: ";
85 CHECK(std::string(error.what()).find(prefix) == 0U &&
86 std::string(error.what()).size() > prefix.size(),
87 "Reject " + line);
88 }
89 }
90private Q_SLOTS:
91 void attributes();
92 void multilineAttributes();
93 void invalidMultilineAttributes();
94 void invalidAttributes();
95 void attributeNumbers();
96 void invalidAttributeNumbers_data();
97 void invalidAttributeNumbers();
98 void attributeWarnings();
99 void diagnostics();
100 void diagnosticErrors();
101 void diagnosticUnsupportedStatements();
102 void diagnosticNamespaceBoundaries();
103 void diagnosticFormatting();
104 void multiplexing();
105 void multiplexingBoundaries();
106 void extendedMultiplexing();
107 void extendedMultiplexingErrors();
108 void validFrames();
109 void invalidFrames();
110 void duplicateFrames();
111 void duplicateSignals();
112 void distinctDefinitions();
113 void comments();
114 void invalidComments_data();
115 void invalidComments();
116 void integration();
117 void invalidSignals();
118 void validSignals();
119 void physicalNumbersCppLocale();
120 void physicalNumbersCLocale();
121 void dispatch();
122 void independentSessions();
123 void valueDescriptions();
124 void invalidValueDescriptions();
125};
126
127void DbcParserTest::attributes() {
128 Fixture fixture;
129 fixture.Write(
130 "BA_ \"GenMsgCycleTime\" BO_ 1 25;\n"
131 "BA_ \"VFrameFormat\" BO_ 2147483649 1;\n"
132 "BA_ \"Label\" SG_ 1 Value \"a\\\"b\\\\c\";\n"
133 "BA_ \"NodeLabel\" BU_ ECU \"node\";\n"
134 "BA_ \"Environment\" EV_ Env 2;\n"
135 "BA_DEF_DEF_ \"GenMsgCycleTime\" 100;\n"
136 "BA_DEF_DEF_ \"VFrameFormat\" \"StandardCAN\";\n"
137 "BA_DEF_DEF_ \"Label\" \"default\";\n"
138 "BA_DEF_DEF_ \"BusLabel\" \"CAN\";\n"
139 "BA_DEF_DEF_ \"Ratio\" 1.5e-1;\n"
140 "BA_DEF_ BO_ \"GenMsgCycleTime\" INT 0 10000;\n"
141 "BA_DEF_ BO_ \"VFrameFormat\" ENUM \"StandardCAN\",\"ExtendedCAN\",\"StandardCAN_FD\";\n"
142 "BA_DEF_ SG_ \"Label\" STRING;\n"
143 "BA_DEF_ \"BusLabel\" STRING;\n"
144 "BA_DEF_ BO_ \"Ratio\" FLOAT -1 1;\n"
145 "BA_DEF_ BU_ \"NodeLabel\" STRING;\n"
146 "BA_DEF_ EV_ \"Environment\" HEX 0 255;\n"
147 "BO_ 1 Standard: 1 ECU\n"
148 "SG_ Value : 0|8@1+ (1,0) [0|255] \"\" ECU\n"
149 "BO_ 2147483649 Extended: 1 ECU\n"
150 "SG_ Value : 0|8@1+ (1,0) [0|255] \"\" ECU\n");
151 const DbcParseResult result = DbcParser().ParseFileWithDiagnostics(fixture.path.string());
152 QVERIFY(!result.HasErrors());
153 QVERIFY(result.diagnostics.empty());
154 const DbcDatabase &database = result.database;
155 QCOMPARE(database.attributeDefinitions.size(), std::size_t(7));
156 QCOMPARE(database.attributeAssignments.size(), std::size_t(5));
157 QCOMPARE(std::get<std::string>(database.attributes.at("BusLabel")), std::string("CAN"));
158 QCOMPARE(database.frames[0].cycleTimeMs.value(), 25U);
159 QCOMPARE(database.frames[1].cycleTimeMs.value(), 100U);
160 QCOMPARE(database.frames[1].frameFormat.value(), std::string("ExtendedCAN"));
161 QVERIFY(!database.frames[1].hasPgn);
162 QCOMPARE(std::get<double>(database.frames[0].attributes.at("Ratio")), 0.15);
163 QCOMPARE(std::get<std::string>(database.frames[0].signals[0].attributes.at("Label")), std::string("a\"b\\c"));
164 QCOMPARE(std::get<std::string>(database.frames[1].signals[0].attributes.at("Label")), std::string("default"));
165 const DecodeDatabase runtime = DbcDecodeBuilder().Build(database);
166 QCOMPARE(runtime.GetFrames()[0].cycleTimeMs.value(), 25U);
167 QCOMPARE(runtime.GetFrames()[1].frameFormat.value(), std::string("ExtendedCAN"));
168 QCOMPARE(runtime.GetFrames()[0].signals[0].attributes, database.frames[0].signals[0].attributes);
169 const std::unique_ptr<TreeNode> tree = DbcTreeBuilder().Build(database);
170 QCOMPARE(tree->GetChild(0)->GetFrame()->cycleTimeMs.value(), 25U);
171 QCOMPARE(tree->GetChild(0)->GetChild(0)->GetSignal()->attributes, database.frames[0].signals[0].attributes);
172 fixture.Write("BA_DEF_ BO_ \"Period\" INT 0 10;\nBA_DEF_DEF_ \"Period\" 1;\n"
173 "BA_ \"Period\" BO_ 1 2;\nBA_ \"Period\" BO_ 1 3;\nBO_ 1 F: 0 ECU\n");
174 const DbcDatabase repeated = DbcParser().ParseFile(fixture.path.string());
175 QCOMPARE(std::get<std::int64_t>(repeated.frames[0].attributes.at("Period")), std::int64_t(3));
176
177 fixture.Write("BA_DEF_ BO_ \"GenMsgCycleTime\" INT 0 4294967295;\n"
178 "BA_DEF_DEF_ \"GenMsgCycleTime\" 0;\n"
179 "BA_ \"GenMsgCycleTime\" BO_ 1 4294967295;\n"
180 "BA_DEF_ \"Wide\" INT -9223372036854775808 9223372036854775807;\n"
181 "BA_DEF_DEF_ \"Wide\" -9223372036854775808;\n"
182 "BA_DEF_ SG_ \"State\" ENUM \"off\",\"on\";\n"
183 "BA_DEF_DEF_ \"State\" 1;\n"
184 "BO_ 1 F: 0 ECU\nBO_ 2 Empty: 0 ECU\n");
185 const DbcDatabase boundaries = DbcParser().ParseFile(fixture.path.string());
186 QCOMPARE(boundaries.frames[0].cycleTimeMs.value(), std::numeric_limits<std::uint32_t>::max());
187 QCOMPARE(boundaries.frames[1].cycleTimeMs.value(), 0U);
188 QVERIFY(!boundaries.frames[0].frameFormat);
189 QCOMPARE(std::get<std::int64_t>(boundaries.attributes.at("Wide")), std::numeric_limits<std::int64_t>::min());
190 QCOMPARE(std::get<std::int64_t>(*boundaries.attributeDefinitions.at("State").defaultValue), std::int64_t(1));
191}
192
193void DbcParserTest::multilineAttributes() {
194 Fixture fixture;
195 fixture.Write(R"DBC(BA_
196 "GenMsgCycleTime" BO_ 1
197 25;
198BA_DEF_ BO_ "VFrameFormat" ENUM
199 "StandardCAN",
200 "StandardCAN_FD";
201BA_DEF_DEF_
202 "VFrameFormat"
203 "StandardCAN_FD";
204BA_DEF_ BO_ "GenMsgCycleTime"
205 INT 0 100;
206BA_DEF_DEF_ "GenMsgCycleTime"
207 50;
208BA_DEF_ SG_ "Label" STRING;
209BA_ "Label" SG_ 1 Value
210 "first; \"quoted\"
211second\\path";
212BA_ "VFrameFormat" BO_ 1
213 0;
214BO_ 1 F: 1 ECU
215SG_ Value : 0|8@1+ (1,0) [0|255] "" ECU
216BO_ 2 Default: 0 ECU
217)DBC");
218 const DbcParseResult result = DbcParser().ParseFileWithDiagnostics(fixture.path.string());
219 QVERIFY(!result.HasErrors());
220 QCOMPARE(result.database.frames.size(), std::size_t(2));
221 QCOMPARE(result.database.frames[0].cycleTimeMs.value(), 25U);
222 QCOMPARE(result.database.frames[1].cycleTimeMs.value(), 50U);
223 QCOMPARE(result.database.frames[0].frameFormat.value(), std::string("StandardCAN"));
224 QCOMPARE(result.database.frames[1].frameFormat.value(), std::string("StandardCAN_FD"));
225 QCOMPARE(std::get<std::string>(result.database.frames[0].signals[0].attributes.at("Label")),
226 std::string("first; \"quoted\"\nsecond\\path"));
227 QCOMPARE(result.diagnostics.size(), std::size_t(1));
228 QCOMPARE(result.diagnostics[0].code, DbcDiagnosticCode::UnsupportedAttribute);
229 QCOMPARE(result.diagnostics[0].lineNumber, std::size_t(7));
230
231 fixture.Write("BA_DEF_ BO_ \"VFrameFormat\" ENUM\r\n \"StandardCAN\",\r\n \"ExtendedCAN_FD\";\r\n"
232 "BA_\r\n \"VFrameFormat\" BO_ 1\r\n 1;\r\nBO_ 1 F: 0 ECU\r\n");
233 const DbcParseResult explicitFormat = DbcParser().ParseFileWithDiagnostics(fixture.path.string());
234 QVERIFY(!explicitFormat.HasErrors());
235 QCOMPARE(explicitFormat.diagnostics.size(), std::size_t(1));
236 QCOMPARE(explicitFormat.diagnostics[0].code, DbcDiagnosticCode::UnsupportedAttribute);
237 QCOMPARE(explicitFormat.diagnostics[0].lineNumber, std::size_t(4));
238 QCOMPARE(explicitFormat.database.frames[0].frameFormat.value(), std::string("ExtendedCAN_FD"));
239
240 fixture.Write("BA_DEF_ \"Text\" STRING;\n BA_ \"Text\" \"first \nsecond\";\n"
241 "UnsupportedStatement\n");
242 const DbcParseResult whitespace = DbcParser().ParseFileWithDiagnostics(fixture.path.string());
243 QVERIFY(!whitespace.HasErrors());
244 QCOMPARE(std::get<std::string>(whitespace.database.attributes.at("Text")), std::string("first \nsecond"));
245 QCOMPARE(whitespace.diagnostics.size(), std::size_t(1));
246 QCOMPARE(whitespace.diagnostics[0].code, DbcDiagnosticCode::UnsupportedStatement);
247 QCOMPARE(whitespace.diagnostics[0].lineNumber, std::size_t(4));
248}
249
250void DbcParserTest::invalidMultilineAttributes() {
251 Fixture fixture;
252 const std::vector<std::string> invalid = {
253 "BA_DEF_\n BO_ \"A\" INT\n 10 0;\n",
254 "BA_DEF_ BO_ \"A\" ENUM\n \"one\",\n;\n",
255 "BA_DEF_ BO_ \"A\" STRING\n",
256 "BA_DEF_ BO_ \"A\" ENUM\n \"unterminated;\n",
257 "BA_DEF_DEF_\n \"Unknown\"\n 0;\n",
258 "BA_\n \"Unknown\" BO_ 1\n 0;\n",
259 "BA_DEF_ BO_ \"A\" STRING\n ; trailing\n"};
260 for (const std::string &statement: invalid) {
261 fixture.Write("BO_ 1 F: 0 ECU\n" + statement);
262 const DbcParseResult result = DbcParser().ParseFileWithDiagnostics(fixture.path.string());
263 QVERIFY2(result.HasErrors(), statement.c_str());
264 QVERIFY(result.database.frames.empty());
265 QCOMPARE(result.diagnostics.back().code, DbcDiagnosticCode::InvalidAttribute);
266 QCOMPARE(result.diagnostics.back().lineNumber, std::size_t(2));
267 QVERIFY_THROWS_EXCEPTION(std::runtime_error, DbcParser().ParseFile(fixture.path.string()));
268 }
269}
270
271void DbcParserTest::invalidAttributes() {
272 Fixture fixture;
273 const std::vector<std::string> invalid = {
274 "BA_DEF_ BO_ \"A\"STRING;",
275 "BA_DEF_ BO_\"A\" STRING;",
276 "BA_DEF_ BO_ \"A\" \"STRING\";",
277 "BA_DEF_ BO_ A STRING;",
278 "BA_DEF_ ZZ_ \"A\" STRING;",
279 "BA_DEF_ BO_ \"A\" BLOB;",
280 "BA_DEF_ BO_ \"A\" FLOAT 2 1;",
281 "BA_DEF_ BO_ \"A\" STRING;\nBA_ \"A\" BO_ 1 0;",
282 "BA_DEF_ BO_ \"A\" FLOAT 0 1;\nBA_ \"A\" BO_ 1 2;",
283 "BA_DEF_ BO_ \"A\" INT 0 1;\nBA_ \"A\" BO_ -1 0;",
284 "BA_DEF_ BO_ \"A\" INT 0 1;\nBA_ \"A\" BO_ 4294967296 0;",
285 "BA_DEF_ BO_ \"A\" INT 0 1;\nBA_ \"A\" BO_ 536870912 0;",
286 "BA_DEF_ BO_ \"A\" INT 2 1;",
287 "BA_DEF_ BO_ \"A\" FLOAT nan 1;",
288 "BA_DEF_ BO_ \"A\" FLOAT 0 inf;",
289 "BA_DEF_ BO_ \"A\" INT 0 9223372036854775808;",
290 "BA_DEF_ BO_ \"A\" STRING; trailing",
291 "BA_DEF_ BO_ \"A\" ENUM;",
292 "BA_DEF_ BO_ \"A\" ENUM \"one\",;",
293 "BA_DEF_ BO_ \"A\" ENUM \"one\",\"one\";",
294 "BA_DEF_ BO_ \"VFrameFormat\" STRING;",
295 "BA_DEF_ SG_ \"GenMsgCycleTime\" INT 0 10;",
296 "BA_ \"Unknown\" BO_ 1 0;",
297 "BA_DEF_DEF_ \"Unknown\" 0;",
298 "BA_DEF_ BO_ \"A\" INT 0 1;\nBA_ \"A\" BO_ 1 2;",
299 "BA_DEF_ BO_ \"A\" INT 0 1;\nBA_ \"A\" BO_ 1 \"0\";",
300 "BA_DEF_ BO_ \"A\" INT 0 1;\nBA_ \"A\" SG_ 1 S 0;",
301 "BA_DEF_ BO_ \"A\" INT 0 1;\nBA_ \"A\" BO_ 2 0;",
302 "BA_DEF_ SG_ \"A\" INT 0 1;\nBA_ \"A\" SG_ 1 Missing 0;",
303 "BA_DEF_ BO_ \"A\" INT 0 1;\nBA_DEF_ BO_ \"A\" INT 0 1;",
304 "BA_DEF_ BO_ \"A\" INT 0 1;\nBA_DEF_DEF_ \"A\" 0;\nBA_DEF_DEF_ \"A\" 1;",
305 "BA_DEF_ BO_ \"A\" STRING;\nBA_ \"A\" BO_ 1 \"bad\\q\";",
306 "BA_DEF_ BO_ \"A\" STRING;\nBA_ \"A\" BO_ 1 \"unterminated;",
307 "BA_DEF_ BO_ \"A\" ENUM \"one\";\nBA_DEF_DEF_ \"A\" \"missing\";",
308 "BA_DEF_ BO_ \"A\" ENUM \"one\";\nBA_ \"A\" BO_ 1 1;",
309 "BA_DEF_ BO_ \"GenMsgCycleTime\" INT -1 4294967296;\nBA_DEF_DEF_ \"GenMsgCycleTime\" -1;",
310 "BA_DEF_ BO_ \"GenMsgCycleTime\" INT 0 4294967296;\nBA_ \"GenMsgCycleTime\" BO_ 1 4294967296;"};
311 for (const std::string &statement: invalid) {
312 fixture.Write("BO_ 1 F: 0 ECU\n" + statement + '\n');
313 const DbcParseResult result = DbcParser().ParseFileWithDiagnostics(fixture.path.string());
314 QVERIFY2(result.HasErrors(), statement.c_str());
315 QVERIFY(result.database.frames.empty());
316 QCOMPARE(result.diagnostics.back().code, DbcDiagnosticCode::InvalidAttribute);
317 QCOMPARE(result.diagnostics.back().lineNumber, std::size_t(2 + std::count(statement.begin(), statement.end(), '\n')));
318 QVERIFY_THROWS_EXCEPTION(std::runtime_error, DbcParser().ParseFile(fixture.path.string()));
319 }
320}
321
322void DbcParserTest::attributeNumbers() {
323 ApplicationLocaleGuard guard;
324 std::locale::global(std::locale(std::locale::classic(), new CommaDecimalPunctuation));
325 Fixture fixture;
326 fixture.Write("BA_DEF_ \"I\" INT -9223372036854775808 +9223372036854775807;\n"
327 "BA_DEF_DEF_ \"I\" -9223372036854775808;\n"
328 "BA_ \"I\" +9223372036854775807;\n"
329 "BA_DEF_ \"H\" HEX -10 +10;\n"
330 "BA_DEF_DEF_ \"H\" +0;\n"
331 "BA_ \"H\" -10;\n"
332 "BA_DEF_ \"F\" FLOAT -1.25e+2 +2.5E2;\n"
333 "BA_DEF_DEF_ \"F\" +.5;\n"
334 "BA_ \"F\" -1.25e+2;\n"
335 "BA_DEF_ BU_ \"NodeDefault\" INT 0 10;\n"
336 "BA_DEF_DEF_ \"NodeDefault\" 5;\n"
337 "BA_DEF_ EV_ \"EnvironmentDefault\" STRING;\n"
338 "BA_DEF_DEF_ \"EnvironmentDefault\" \"default\";\n");
339 const DbcParseResult result = DbcParser().ParseFileWithDiagnostics(fixture.path.string());
340 QVERIFY(!result.HasErrors());
341 QVERIFY(result.diagnostics.empty());
342 QCOMPARE(std::get<std::int64_t>(*result.database.attributeDefinitions.at("I").defaultValue), std::numeric_limits<std::int64_t>::min());
343 QCOMPARE(std::get<std::int64_t>(result.database.attributes.at("I")), std::numeric_limits<std::int64_t>::max());
344 QCOMPARE(std::get<std::int64_t>(*result.database.attributeDefinitions.at("H").defaultValue), std::int64_t(0));
345 QCOMPARE(std::get<std::int64_t>(result.database.attributes.at("H")), std::int64_t(-10));
346 QCOMPARE(std::get<double>(*result.database.attributeDefinitions.at("F").defaultValue), 0.5);
347 QCOMPARE(std::get<double>(result.database.attributes.at("F")), -125.0);
348 QCOMPARE(result.database.attributes.size(), std::size_t(3));
349 QCOMPARE(std::get<std::int64_t>(*result.database.attributeDefinitions.at("NodeDefault").defaultValue), std::int64_t(5));
350 QCOMPARE(std::get<std::string>(*result.database.attributeDefinitions.at("EnvironmentDefault").defaultValue), std::string("default"));
351}
352
353void DbcParserTest::invalidAttributeNumbers_data() {
354 QTest::addColumn<QString>("type");
355 QTest::addColumn<QString>("number");
356 const char *types[] = {"INT", "HEX", "FLOAT"};
357 const char *invalid[] = {"+", "-", "++1", "+-1", "--1", "1x", "0x10",
358 "nan", "inf", "-inf", "1e9999", "1e-9999"};
359 for (const char *type: types) {
360 for (const char *number: invalid) {
361 const std::string name = std::string(type) + '-' + number;
362 QTest::newRow(name.c_str()) << QString(type) << QString(number);
363 }
364 }
365 QTest::newRow("integer-overflow") << QString("INT") << QString("9223372036854775808");
366 QTest::newRow("integer-underflow") << QString("INT") << QString("-9223372036854775809");
367 QTest::newRow("integer-fraction") << QString("INT") << QString("1.5");
368}
369
370void DbcParserTest::invalidAttributeNumbers() {
371 QFETCH(QString, type);
372 QFETCH(QString, number);
373 const std::string kind = type.toStdString();
374 const std::string text = number.toStdString();
375 const std::string definition = "BA_DEF_ \"A\" " + kind + " -10 10;\n";
376 const std::string statements[] = {
377 "BA_DEF_ \"A\" " + kind + ' ' + text + " 10;\n",
378 "BA_DEF_ \"A\" " + kind + " -10 " + text + ";\n",
379 definition + "BA_DEF_DEF_ \"A\" " + text + ";\n",
380 definition + "BA_ \"A\" " + text + ";\n"};
381 Fixture fixture;
382 for (const std::string &statement: statements) {
383 fixture.Write(statement);
384 const DbcParseResult result = DbcParser().ParseFileWithDiagnostics(fixture.path.string());
385 QVERIFY2(result.HasErrors(), statement.c_str());
386 QVERIFY(result.database.attributeDefinitions.empty());
387 QCOMPARE(result.diagnostics.back().code, DbcDiagnosticCode::InvalidAttribute);
388 QCOMPARE(result.diagnostics.back().lineNumber,
389 static_cast<std::size_t>(std::count(statement.begin(), statement.end(), '\n')));
390 QVERIFY_THROWS_EXCEPTION(std::runtime_error, DbcParser().ParseFile(fixture.path.string()));
391 }
392}
393
394void DbcParserTest::attributeWarnings() {
395 Fixture fixture;
396 fixture.Write("BA_DEF_ BO_ \"VFrameFormat\" ENUM \"StandardCAN\",\"ExtendedCAN\",\"J1939PG\",\"StandardCAN_FD\";\n"
397 "BA_DEF_DEF_ \"VFrameFormat\" \"StandardCAN_FD\";\n"
398 "BA_ \"VFrameFormat\" BO_ 1 2;\n"
399 "BA_ \"VFrameFormat\" BO_ 2147483649 0;\n"
400 "BO_ 1 F: 0 ECU\nBO_ 2147483649 E: 0 ECU\nBO_ 2 Default: 0 ECU\n");
401 const DbcParseResult result = DbcParser().ParseFileWithDiagnostics(fixture.path.string());
402 QVERIFY(!result.HasErrors());
403 QCOMPARE(result.diagnostics.size(), std::size_t(3));
404 const std::size_t lines[] = {3U, 4U, 2U};
405 for (std::size_t index = 0; index < 3U; ++index) {
406 QCOMPARE(result.diagnostics[index].code, DbcDiagnosticCode::UnsupportedAttribute);
407 QCOMPARE(result.diagnostics[index].severity, DbcDiagnosticSeverity::Warning);
408 QCOMPARE(result.diagnostics[index].lineNumber, lines[index]);
409 QCOMPARE(result.diagnostics[index].filePath, fixture.path.string());
410 }
411 QCOMPARE(result.database.frames[0].frameFormat.value(), std::string("J1939PG"));
412 QVERIFY(!result.database.frames[0].hasPgn);
413 QVERIFY(result.database.frames[1].isExtended);
414}
415
416void DbcParserTest::diagnostics() {
417 Fixture fixture;
418 fixture.Write("VERSION \"test\"\n"
419 "NS_ :\n"
420 " CM_\n"
421 " BA_\n"
422 " SIG_VALTYPE_\n"
423 " SG_MUL_VAL_\n\n"
424 "BS_:\n"
425 "BU_: ECU\n"
426 "BO_ 1 Frame: 1 ECU\n"
427 "SG_ Value : 0|8@1+ (1,0) [0|255] \"\" ECU\n"
428 "SIG_VALTYPE_ 1 Value : 1;\n"
429 "BA_REL_ \"SignalType\" SG_ 1 Value 1;\n"
430 "VENDOR_EXTENSION_ data;\n");
431 const DbcParseResult result = DbcParser().ParseFileWithDiagnostics(fixture.path.string());
432 CHECK(!result.HasErrors() && result.database.frames.size() == 1U,
433 "Warnings preserve the supported database");
434 QCOMPARE(result.diagnostics.size(), std::size_t(3U));
435 for (std::size_t index = 0U; index < result.diagnostics.size(); ++index) {
436 const DbcDiagnostic &diagnostic = result.diagnostics[index];
437 CHECK(diagnostic.severity == DbcDiagnosticSeverity::Warning &&
438 diagnostic.code == DbcDiagnosticCode::UnsupportedStatement,
439 "Unsupported statements have structured warning severity and code");
440 QCOMPARE(diagnostic.filePath, fixture.path.string());
441 QCOMPARE(diagnostic.lineNumber, 12U + index);
442 CHECK(diagnostic.message.find("ignored") != std::string::npos,
443 "Warning explains unsupported syntax");
444 }
445 CHECK(DbcParser().ParseFile(fixture.path.string()).frames.size() == 1U,
446 "Legacy API accepts files with warnings");
447 fixture.Write("VERSION \"\"\nNS_:\nSIG_VALTYPE_\n\tBA_\n BS_ :\n BU_ : ECU\n");
448 const DbcParseResult headers = DbcParser().ParseFileWithDiagnostics(fixture.path.string());
449 CHECK(headers.diagnostics.empty(), "Common header variants stay quiet");
450 fixture.Write("NS_ :\n BA_\n BO_\n");
451 CHECK(DbcParser().ParseFileWithDiagnostics(fixture.path.string()).HasErrors(),
452 "Namespace handling does not swallow a malformed frame");
453}
454
455void DbcParserTest::diagnosticErrors() {
456 Fixture fixture;
457 struct ErrorCase {
458 const char *text;
459 DbcDiagnosticCode code;
460 std::size_t line;
461 };
462 const ErrorCase cases[] = {
463 {"UNKNOWN_ data;\n\nBO_ invalid Frame: 1 ECU\n",
464 DbcDiagnosticCode::InvalidStatement, 3U},
465 {"BO_ 1 Frame: 1 ECU\nSG_MUL_VAL_ 1 Value Mode 1-2;\n",
466 DbcDiagnosticCode::InvalidMultiplexing, 2U},
467 {"BO_ 1 Frame: 1 ECU\nVAL_ 1 Missing 0 \"Off\";\n",
468 DbcDiagnosticCode::InvalidValueDescription, 2U},
469 {"BO_ 1 Frame: 1 ECU\nSG_ Value m1 : 0|8@1+ (1,0) [0|255] \"\" ECU\n",
470 DbcDiagnosticCode::InvalidMultiplexing, 2U},
471 {"BO_ 1 Frame: 1 ECU\nSG_ Mode M : 0|8@1- (1,0) [-128|127] \"\" ECU\n",
472 DbcDiagnosticCode::InvalidMultiplexing, 2U},
473 {"VAL_ broken\n", DbcDiagnosticCode::InvalidValueDescription, 1U},
474 {"SG_ Value : 0|8@1+ (1,0) [0|255] \"\" ECU\n",
475 DbcDiagnosticCode::InvalidStatement, 1U},
476 {"BO_ 1 Frame: 1 ECU\nBO_ 1 Duplicate: 1 ECU\n",
477 DbcDiagnosticCode::InvalidStatement, 2U},
478 {"BO_ 1 Frame: 1 ECU\nSG_ Value : 0|8@1+ (1,0) [0|255] \"\" ECU\n"
479 "SG_ Value : 0|8@1+ (1,0) [0|255] \"\" ECU\n",
480 DbcDiagnosticCode::InvalidStatement, 3U},
481 {"BO_ 1 Frame: 1 ECU\nSG_ Value : 8|8@1+ (1,0) [0|255] \"\" ECU\n",
482 DbcDiagnosticCode::InvalidStatement, 2U},
483 {"BO_ 1 Frame: 1 ECU\nVAL_ 2 Missing 0 \"Off\";\n",
484 DbcDiagnosticCode::InvalidValueDescription, 2U},
485 {"BO_ 1 Frame: 1 ECU\nSG_ Value : 0|8@1+ (1,0) [0|255] \"\" ECU\n"
486 "VAL_ 1 Value 0 \"Off\";\nVAL_ 1 Value 0 \"Duplicate\";\n",
487 DbcDiagnosticCode::InvalidValueDescription, 4U},
488 {"BO_ 1 Frame: 2 ECU\nSG_ Mode M : 0|1@1+ (1,0) [0|1] \"\" ECU\n"
489 "SG_ Value m2 : 8|8@1+ (1,0) [0|255] \"\" ECU\n",
490 DbcDiagnosticCode::InvalidMultiplexing, 3U},
491 {"BO_ 1 Frame: 2 ECU\nSG_ Mode M : 0|8@1+ (1,0) [0|255] \"\" ECU\n"
492 "SG_ Other M : 8|8@1- (1,0) [-128|127] \"\" ECU\n",
493 DbcDiagnosticCode::InvalidMultiplexing, 3U},
494 {"BO_ 1 Frame: 1 ECU\nSG_ First : 0|8@1+ (1,0) [0|255] \"\" ECU\n"
495 "SG_ Second : 7|8@0+ (1,0) [0|255] \"\" ECU\n",
496 DbcDiagnosticCode::InvalidMultiplexing, 3U}};
497 for (const ErrorCase &test : cases) {
498 fixture.Write(test.text);
499 const DbcParseResult result = DbcParser().ParseFileWithDiagnostics(fixture.path.string());
500 CHECK(result.HasErrors() && result.database.frames.empty(),
501 "Failed parse never returns a partial database");
502 const DbcDiagnostic &diagnostic = result.diagnostics.back();
503 CHECK(diagnostic.severity == DbcDiagnosticSeverity::Error && diagnostic.code == test.code,
504 "Error has expected severity and code");
505 QCOMPARE(diagnostic.filePath, fixture.path.string());
506 QCOMPARE(diagnostic.lineNumber, test.line);
507 CHECK(!diagnostic.message.empty(), "Error includes a message");
508 const bool hasWarning = std::string(test.text).find("UNKNOWN_") == 0U;
509 QCOMPARE(result.diagnostics.size(), hasWarning ? std::size_t(2U) : std::size_t(1U));
510 try {
511 DbcParser().ParseFile(fixture.path.string());
512 CHECK(false, "Legacy parser must throw");
513 } catch (const std::runtime_error &error) {
514 QCOMPARE(std::string(error.what()), fixture.path.string() + ":" +
515 std::to_string(test.line) + ": " + diagnostic.message);
516 }
517 }
518 const std::string missingPath = fixture.path.string() + ".missing";
519 const DbcParseResult missing = DbcParser().ParseFileWithDiagnostics(missingPath);
520 CHECK(missing.HasErrors() && missing.database.frames.empty(), "Missing file returns error");
521 QCOMPARE(missing.diagnostics.size(), std::size_t(1U));
522 CHECK(missing.diagnostics[0].code == DbcDiagnosticCode::FileOpenError,
523 "Missing file has a distinct code");
524 QCOMPARE(missing.diagnostics[0].lineNumber, std::size_t(0U));
525 QCOMPARE(missing.diagnostics[0].filePath, missingPath);
526 QCOMPARE(missing.diagnostics[0].message, "Failed to open DBC file: " + missingPath);
527 try {
528 DbcParser().ParseFile(missingPath);
529 CHECK(false, "Legacy API throws on missing file");
530 } catch (const std::runtime_error &error) {
531 QCOMPARE(std::string(error.what()), missing.diagnostics[0].message);
532 }
533 const std::string directoryPath = fixture.path.parent_path().string();
534 const DbcParseResult directory = DbcParser().ParseFileWithDiagnostics(directoryPath);
535 CHECK(directory.HasErrors() && directory.database.frames.empty(),
536 "Directory cannot be parsed as a file");
537 QCOMPARE(directory.diagnostics.size(), std::size_t(1U));
538 CHECK(directory.diagnostics[0].code == DbcDiagnosticCode::FileReadError ||
539 directory.diagnostics[0].code == DbcDiagnosticCode::FileOpenError,
540 "Directory produces a file-level error on supported platforms");
541 QCOMPARE(directory.diagnostics[0].lineNumber, std::size_t(0U));
542 QCOMPARE(directory.diagnostics[0].filePath, directoryPath);
543#ifdef __linux__
544 CHECK(directory.diagnostics[0].code == DbcDiagnosticCode::FileReadError,
545 "Linux directory input exercises the read-error path");
546 QCOMPARE(directory.diagnostics[0].message, "Failed to read DBC file: " + directoryPath);
547#endif
548 try {
549 DbcParser().ParseFile(directoryPath);
550 CHECK(false, "Legacy API throws on unreadable input");
551 } catch (const std::runtime_error &error) {
552 QCOMPARE(std::string(error.what()), directory.diagnostics[0].message);
553 }
554 fixture.Write("BO_ 1 Frame: 1 ECU\n");
555 CHECK(DbcParser().ParseFileWithDiagnostics(fixture.path.string()).diagnostics.empty(),
556 "Diagnostics belong to an independent parse session");
557}
558
559void DbcParserTest::diagnosticUnsupportedStatements() {
560 Fixture fixture;
561 const std::string definitions =
562 "BO_ 1 Frame: 1 ECU\nSG_ Value : 0|8@1+ (2,10) [10|520] \"V\" ECU\n"
563 "CM_ SG_ 1 Value \"Signal comment\";\nVAL_ 1 Value 1 \"On\";\n";
564 const std::vector<std::string> statements = {
565 "SIG_VALTYPE_ 1 Value : 1;", "SIG_VALTYPE_ 1 Value : 2;",
566 "BA_REL_ \"SignalType\" SG_ 1 Value 1;",
567 "BA_DEF_REL_ BU_SG_REL_ \"Relation\" INT 0 1;",
568 "BA_REL_ \"Relation\" BU_SG_REL_ ECU SG_ 1 Value 1;",
569 "SGTYPE_ Type : 8@1+ (1,0) [0|255] \"\" 0, Table;",
570 "SIG_TYPE_REF_ 1 Value : Type;",
571 "EV_ Environment : 0 [0|1] \"\" 0 1 DUMMY_NODE_VECTOR0 ECU;",
572 "ENVVAR_DATA_ Environment : 4;",
573 "VAL_TABLE_ Table 0 \"Off\" 1 \"On\";",
574 "BO_TX_BU_ 1 : ECU;", "VENDOR_EXTENSION_ data;", "UNKNOWN_"
575 };
576 for (const std::string &statement : statements) {
577 fixture.Write(definitions + statement + '\n');
578 const DbcParseResult result = DbcParser().ParseFileWithDiagnostics(fixture.path.string());
579 CHECK(!result.HasErrors(), statement);
580 QCOMPARE(result.diagnostics.size(), std::size_t(1U));
581 const DbcDiagnostic &warning = result.diagnostics[0];
582 CHECK(warning.severity == DbcDiagnosticSeverity::Warning &&
583 warning.code == DbcDiagnosticCode::UnsupportedStatement, statement);
584 QCOMPARE(warning.filePath, fixture.path.string());
585 QCOMPARE(warning.lineNumber, std::size_t(5U));
586 const std::string keyword = statement.substr(0U, statement.find(' '));
587 CHECK(warning.message.find("'" + keyword + "'") != std::string::npos, statement);
588 const DecodeDatabase runtime = DbcDecodeBuilder().Build(result.database);
589 RawCanFrame raw;
590 raw.canId = 1U;
591 raw.data = {1U};
592 const DecodedFrameValue decoded = DbcDecoder().Decode(runtime, raw);
593 CHECK(decoded.valid && decoded.signals.size() == 1U && decoded.signals[0].valid,
594 "Warnings preserve supported signal decoding");
595 QCOMPARE(decoded.signals[0].physicalValue, 12.0);
596 CHECK(decoded.signals[0].GetValueDescription() &&
597 *decoded.signals[0].GetValueDescription() == "On",
598 "Warnings preserve VAL_ descriptions");
599 QCOMPARE(runtime.GetFrames()[0].signals[0].comment, std::string("Signal comment"));
600 }
601}
602
603void DbcParserTest::diagnosticNamespaceBoundaries() {
604 Fixture fixture;
605 const std::vector<std::string> endings = {
606 "BS_\n", "BS_:\n", "BS_ :\n", "BU_\n", "BU_:\n", "BU_ : ECU\n",
607 "BO_ 1 Frame: 1 ECU\n", "VENDOR_EXTENSION_ data;\n"
608 };
609 for (const std::string &ending : endings) {
610 fixture.Write("NS_ :\n\tSG_MUL_VAL_\n\nBA_\n" + ending + "SIG_VALTYPE_\n");
611 const DbcParseResult result = DbcParser().ParseFileWithDiagnostics(fixture.path.string());
612 CHECK(!result.HasErrors(), ending);
613 const std::size_t expectedWarnings = ending.find("VENDOR_") == 0U ? 2U : 1U;
614 QCOMPARE(result.diagnostics.size(), expectedWarnings);
615 QCOMPARE(result.diagnostics.back().lineNumber, std::size_t(6U));
616 CHECK(result.diagnostics.back().message.find("SIG_VALTYPE_") != std::string::npos,
617 "Unsupported keyword outside NS_ must produce a warning");
618 }
619 for (const std::string &definition : {std::string("BO_"), std::string("SG_")}) {
620 fixture.Write("NS_:\n\tBA_\n\t" + definition + '\n');
621 const DbcParseResult result = DbcParser().ParseFileWithDiagnostics(fixture.path.string());
622 CHECK(result.HasErrors(), "Malformed definition ends NS_ instead of being hidden");
623 QCOMPARE(result.diagnostics.size(), std::size_t(1U));
624 QCOMPARE(result.diagnostics[0].lineNumber, std::size_t(3U));
625 }
626}
627
628void DbcParserTest::diagnosticFormatting() {
629 Fixture fixture;
630 fixture.path += " with spaces";
631 const DbcParser parser;
632 for (const std::string &text : {std::string(), std::string(" \t\r\n\n")}) {
633 fixture.Write(text);
634 const DbcParseResult empty = parser.ParseFileWithDiagnostics(fixture.path.string());
635 CHECK(!empty.HasErrors() && empty.diagnostics.empty() && empty.database.frames.empty(),
636 "Empty and whitespace-only inputs are valid");
637 }
638 fixture.Write("\r\n\tVENDOR_EXTENSION_ data;\r\n\r\nUNKNOWN_");
639 const std::string relativePath = std::filesystem::relative(fixture.path).string();
640 const DbcParseResult warnings = parser.ParseFileWithDiagnostics(relativePath);
641 CHECK(!warnings.HasErrors() && warnings.database.frames.empty(), "Warnings-only input");
642 QCOMPARE(warnings.diagnostics.size(), std::size_t(2U));
643 QCOMPARE(warnings.diagnostics[0].lineNumber, std::size_t(2U));
644 QCOMPARE(warnings.diagnostics[1].lineNumber, std::size_t(4U));
645 for (const DbcDiagnostic &warning : warnings.diagnostics)
646 QCOMPARE(warning.filePath, relativePath);
647
648 fixture.Write("UNKNOWN_ first;\nBO_ invalid Frame: 1 ECU\n"
649 "UNKNOWN_ after_error;\nSG_ broken\n");
650 const DbcParseResult stopped = parser.ParseFileWithDiagnostics(relativePath);
651 CHECK(stopped.HasErrors() && stopped.database.frames.empty(), "First error stops parsing");
652 QCOMPARE(stopped.diagnostics.size(), std::size_t(2U));
653 QCOMPARE(stopped.diagnostics[0].lineNumber, std::size_t(1U));
654 QCOMPARE(stopped.diagnostics[1].lineNumber, std::size_t(2U));
655 QCOMPARE(stopped.diagnostics[1].filePath, relativePath);
656
657 fixture.Write("VAL_ 1 Missing 0 \"Off\";\nBO_ 1 Frame: 1 ECU\nUNKNOWN_ data;\n");
658 const DbcParseResult deferred = parser.ParseFileWithDiagnostics(relativePath);
659 CHECK(deferred.HasErrors() && deferred.database.frames.empty(), "Deferred error rejects database");
660 QCOMPARE(deferred.diagnostics.size(), std::size_t(2U));
661 CHECK(deferred.diagnostics[0].severity == DbcDiagnosticSeverity::Warning &&
662 deferred.diagnostics[1].severity == DbcDiagnosticSeverity::Error,
663 "Deferred errors follow warnings in detection order");
664 QCOMPARE(deferred.diagnostics[0].lineNumber, std::size_t(3U));
665 QCOMPARE(deferred.diagnostics[1].lineNumber, std::size_t(1U));
666 QCOMPARE(deferred.diagnostics[1].filePath, relativePath);
667 fixture.Write("BO_ 1 Frame: 1 ECU");
668 const DbcParseResult recovered = parser.ParseFileWithDiagnostics(relativePath);
669 CHECK(!recovered.HasErrors() && recovered.diagnostics.empty() && recovered.database.frames.size() == 1U,
670 "Same parser has clean state after errors and accepts missing final newline");
671}
672
673void DbcParserTest::validFrames() {
674 Fixture fixture;
675 struct ValidCase {
676 const char *line;
677 std::uint32_t id;
678 bool extended;
679 unsigned length;
680 };
681 const ValidCase valid[] = {
682 {"BO_ 0 Frame: 0 ECU", 0U, false, 0U},
683 {"BO_ 2047 Frame: 8 ECU", 2047U, false, 8U},
684 {"BO_ 2048 Frame: 64 ECU", 2048U, true, 64U},
685 {"BO_ 536870911 Frame: 255 ECU", 0x1FFFFFFFU, true, 255U},
686 {"BO_ 2147483649 Frame: 8 ECU", 1U, true, 8U},
687 {"BO_ 2684354559 Frame: 8 ECU", 0x1FFFFFFFU, true, 8U},
688 {" BO_\t256\tFrame :\t8\tECU \r", 256U, false, 8U}};
689 for (const ValidCase &test: valid) {
690 fixture.Write(std::string(test.line) + '\n');
691 try {
692 const DbcDatabase database = DbcParser().ParseFile(fixture.path.string());
693 QCOMPARE(database.frames.size(), std::size_t(1U));
694 const FrameInfo &frame = database.frames[0];
695 QCOMPARE(frame.name, std::string("Frame"));
696 QCOMPARE(frame.canId, test.id);
697 QCOMPARE(frame.isExtended, test.extended);
698 QCOMPARE(static_cast<unsigned>(frame.dlc), test.length);
699 QCOMPARE(frame.transmitter, std::string("ECU"));
700 } catch (const std::exception &error) { CHECK(false, error.what()); }
701 }
702}
703
704void DbcParserTest::invalidFrames() {
705 Fixture fixture;
706 const char *invalid[] = {
707 "BO_ invalid", "BO_", "BO_ 1", "BO_ 1 : 8 ECU", "BO_ 1 Frame 8 ECU",
708 "BO_ 1 Frame:", "BO_ 1 Frame: 8", "BO_ 1 Frame: 8 ECU extra",
709 "BO_ 1 Two Names: 8 ECU", "BO_ -1 Frame: 8 ECU", "BO_ +1 Frame: 8 ECU",
710 "BO_ 1x Frame: 8 ECU", "BO_ 0x123 Frame: 8 ECU", "BO_ 1.5 Frame: 8 ECU",
711 "BO_ 4294967296 Frame: 8 ECU", "BO_ 999999999999999999999 Frame: 8 ECU",
712 "BO_ 536870912 Frame: 8 ECU", "BO_ 1073741824 Frame: 8 ECU",
713 "BO_ 2684354560 Frame: 8 ECU", "BO_ 4294967295 Frame: 8 ECU",
714 "BO_ 1 Frame: -1 ECU", "BO_ 1 Frame: +8 ECU", "BO_ 1 Frame: 8x ECU",
715 "BO_ 1 Frame: 8.5 ECU", "BO_ 1 Frame: 256 ECU",
716 "BO_ 1 Frame: 4294967296 ECU", "BO_\tinvalid"};
717 for (const char *line: invalid) {
718 fixture.Write(std::string("VERSION \"test\"\n\n") + line + '\n');
719 try {
720 DbcParser().ParseFile(fixture.path.string());
721 CHECK(false, line);
722 } catch (const std::runtime_error &error) {
723 const std::string prefix = fixture.path.string() + ":3: ";
724 CHECK(std::string(error.what()).find(prefix) == 0U &&
725 std::string(error.what()).size() > prefix.size(),
726 line);
727 }
728 }
729}
730
731void DbcParserTest::duplicateFrames() {
732 Fixture fixture;
733 struct DuplicateCase {
734 const char *firstId;
735 const char *duplicateId;
736 const char *message;
737 };
738 const DuplicateCase cases[] = {
739 {"1", "1", "Duplicate standard frame CAN ID: 1"},
740 {"2147483649", "2147483649", "Duplicate extended frame CAN ID: 1"},
741 {"2048", "2147485696", "Duplicate extended frame CAN ID: 2048"},
742 {"2147485696", "2048", "Duplicate extended frame CAN ID: 2048"},
743 {"536870911", "2684354559", "Duplicate extended frame CAN ID: 536870911"}
744 };
745 const DbcParser parser;
746 for (const DuplicateCase &test : cases) {
747 fixture.Write("BO_ " + std::string(test.firstId) + " First: 8 ECU\n"
748 "BO_ 2 Other: 8 ECU\n\n"
749 " BO_\t" + test.duplicateId + "\tSecond: 8 ECU\n");
750 try {
751 parser.ParseFile(fixture.path.string());
752 CHECK(false, "Duplicate frame must be rejected");
753 } catch (const std::runtime_error &error) {
754 QCOMPARE(std::string(error.what()), fixture.path.string() + ":4: " + test.message);
755 }
756 }
757 fixture.Write("BO_ 1 First: 8 ECU\n");
758 QCOMPARE(parser.ParseFile(fixture.path.string()).frames.size(), std::size_t(1U));
759}
760
761void DbcParserTest::duplicateSignals() {
762 Fixture fixture;
763 const std::string first = "SG_ State : 0|8@1+ (1,0) [0|255] \"\" ECU\n";
764 const std::string duplicates[] = {
765 first,
766 " SG_\tState : 16|8@1+ (2,1) [0|511] \"V\" ECU\n",
767 "SG_ State m1 : 16|8@1+ (1,0) [0|255] \"\" ECU\n"
768 };
769 for (const std::string &duplicate : duplicates) {
770 fixture.Write("BO_ 1 Frame: 8 ECU\n" + first +
771 "SG_ Other : 8|8@1+ (1,0) [0|255] \"\" ECU\n\n" + duplicate);
772 try {
773 DbcParser().ParseFile(fixture.path.string());
774 CHECK(false, "Duplicate signal must be rejected");
775 } catch (const std::runtime_error &error) {
776 QCOMPARE(std::string(error.what()), fixture.path.string() +
777 ":5: Duplicate signal name 'State' in frame 'Frame'.");
778 }
779 }
780}
781
782void DbcParserTest::distinctDefinitions() {
783 Fixture fixture;
784 fixture.Write("BO_ 1 Shared: 1 ECU\n"
785 "SG_ State : 0|8@1+ (1,0) [0|255] \"\" ECU\n"
786 "BO_ 2147483649 Shared: 1 ECU\n"
787 "SG_ State : 0|8@1+ (1,0) [0|255] \"\" ECU\n"
788 "BO_ 2 Shared: 2 ECU\n"
789 "SG_ State : 0|8@1+ (1,0) [0|255] \"\" ECU\n"
790 "SG_ state : 8|8@1+ (1,0) [0|255] \"\" ECU\n"
791 "CM_ BO_ 1 \"Standard\";\n"
792 "CM_ BO_ 2147483649 \"Extended\";\n"
793 "CM_ SG_ 1 State \"Standard state\";\n"
794 "CM_ SG_ 2147483649 State \"Extended state\";\n");
795 const DbcDatabase parsed = DbcParser().ParseFile(fixture.path.string());
796 QCOMPARE(parsed.frames.size(), std::size_t(3U));
797 QCOMPARE(parsed.frames[0].canId, parsed.frames[1].canId);
798 CHECK(!parsed.frames[0].isExtended && parsed.frames[1].isExtended,
799 "Standard and extended frames with the same numeric ID remain distinct");
800 QCOMPARE(parsed.frames[0].comment, std::string("Standard"));
801 QCOMPARE(parsed.frames[1].comment, std::string("Extended"));
802 QCOMPARE(parsed.frames[0].signals[0].comment, std::string("Standard state"));
803 QCOMPARE(parsed.frames[1].signals[0].comment, std::string("Extended state"));
804 QCOMPARE(parsed.frames[2].signals.size(), std::size_t(2U));
805 const DecodeDatabase runtime = DbcDecodeBuilder().Build(parsed);
806 RawCanFrame raw;
807 raw.canId = 1U;
808 raw.data = {7U};
809 const DecodedFrameValue standard = DbcDecoder().Decode(runtime, raw);
810 QVERIFY(standard.valid);
811 QCOMPARE(standard.definition->comment, std::string("Standard"));
812 raw.isExtended = true;
813 const DecodedFrameValue extended = DbcDecoder().Decode(runtime, raw);
814 QVERIFY(extended.valid);
815 QCOMPARE(extended.definition->comment, std::string("Extended"));
816}
817
818void DbcParserTest::comments() {
819 Fixture fixture;
820 fixture.Write(
821 "CM_\tBO_\t1\t\"First\";\r\n"
822 "CM_\tSG_\t1\tState\t\" Line one \r\n"
823 "\r\n"
824 "\tBO_ is text; \\\"quoted\\\" and \\\\slash\"\t;\r\n"
825 "CM_ BO_ 2147483649 \"Extended\";\r\n"
826 "CM_ SG_ 2147483649 State \"Extended signal\";\r\n"
827 "BO_ 1 Standard: 1 ECU\r\n"
828 "CM_ BO_ 1 \"Last\";\r\n"
829 "SG_ State : 0|8@1+ (1,0) [0|255] \"\" ECU\r\n"
830 "BO_ 2147483649 Extended: 1 ECU\r\n"
831 "SG_ State : 0|8@1+ (1,0) [0|255] \"\" ECU");
832 const DbcParseResult result = DbcParser().ParseFileWithDiagnostics(fixture.path.string());
833 QVERIFY(!result.HasErrors());
834 QVERIFY(result.diagnostics.empty());
835 QCOMPARE(result.database.frames.size(), std::size_t(2));
836 QCOMPARE(result.database.frames[0].comment, std::string("Last"));
837 QCOMPARE(result.database.frames[0].signals[0].comment,
838 std::string(" Line one \n\n\tBO_ is text; \"quoted\" and \\slash"));
839 QCOMPARE(result.database.frames[1].comment, std::string("Extended"));
840 QCOMPARE(result.database.frames[1].signals[0].comment, std::string("Extended signal"));
841
842 const std::string ids[][2] = {
843 {"0", "0"},
844 {"2047", "2047"},
845 {"2048", "2147485696"},
846 {"536870911", "2684354559"},
847 {"2684354559", "536870911"}};
848 for (const std::string(&id)[2]: ids) {
849 fixture.Write("CM_ BO_ " + id[0] + " \"Frame\";\nCM_ SG_ " + id[0] +
850 " State \"Signal\";\nBO_ " + id[1] + " Frame: 1 ECU\n"
851 "SG_ State : 0|8@1+ (1,0) [0|255] \"\" ECU\n");
852 const DbcDatabase database = DbcParser().ParseFile(fixture.path.string());
853 QCOMPARE(database.frames[0].comment, std::string("Frame"));
854 QCOMPARE(database.frames[0].signals[0].comment, std::string("Signal"));
855 }
856 fixture.Write("CM_ BO_ 1 \"Line one\nLine two\";\n"
857 "BO_ 1 Frame: 0 ECU\nUNKNOWN_ value\nBO_ bad Frame: 0 ECU\n");
858 const DbcParseResult following = DbcParser().ParseFileWithDiagnostics(fixture.path.string());
859 QVERIFY(following.HasErrors());
860 QCOMPARE(following.diagnostics.size(), std::size_t(2));
861 QCOMPARE(following.diagnostics[0].lineNumber, std::size_t(4));
862 QCOMPARE(following.diagnostics[1].lineNumber, std::size_t(5));
863}
864
865void DbcParserTest::invalidComments_data() {
866 QTest::addColumn<QString>("statement");
867 const char *ids[] = {"-1", "+1", "1x", "0x1", "4294967296", "536870912",
868 "1073741824", "2684354560", "4294967295"};
869 for (const char *id: ids) {
870 const std::string frameRow = std::string("frame-id-") + id;
871 const std::string signalRow = std::string("signal-id-") + id;
872 QTest::newRow(frameRow.c_str()) << QString::fromStdString("CM_ BO_ " + std::string(id) + " \"Text\";");
873 QTest::newRow(signalRow.c_str()) << QString::fromStdString("CM_ SG_ " + std::string(id) + " State \"Text\";");
874 }
875 QTest::newRow("missing-id") << QStringLiteral("CM_ BO_");
876 QTest::newRow("missing-signal") << QStringLiteral("CM_ SG_ 1 \"Text\";");
877 QTest::newRow("missing-quote") << QStringLiteral("CM_ BO_ 1 Text;");
878 QTest::newRow("unclosed") << QStringLiteral("CM_ SG_ 1 State \"Text\n More");
879 QTest::newRow("invalid-escape") << QStringLiteral("CM_ BO_ 1 \"bad\\q\";");
880 QTest::newRow("dangling-escape") << QStringLiteral("CM_ BO_ 1 \"bad\\");
881 QTest::newRow("missing-semicolon") << QStringLiteral("CM_ SG_ 1 State \"Text\"");
882 QTest::newRow("trailing-text") << QStringLiteral("CM_ BO_ 1 \"Text\"; garbage");
883 QTest::newRow("extra-header") << QStringLiteral("CM_ BO_ 1 extra \"Text\";");
884 QTest::newRow("extra-string") << QStringLiteral("CM_ BO_ 1 \"Text\" \"More\";");
885 QTest::newRow("missing-frame") << QStringLiteral("CM_ BO_ 2 \"Text\";");
886 QTest::newRow("missing-signal-frame") << QStringLiteral("CM_ SG_ 2 State \"Text\";");
887 QTest::newRow("missing-signal-reference") << QStringLiteral("CM_ SG_ 1 Missing \"Text\";");
888 QTest::newRow("different-frame-type") << QStringLiteral("CM_ BO_ 2147483649 \"Text\";");
889 QTest::newRow("missing-multiline-reference") << QStringLiteral("CM_ SG_ 1 Missing \"Text\nMore\";");
890}
891
892void DbcParserTest::invalidComments() {
893 QFETCH(QString, statement);
894 Fixture fixture;
895 fixture.Write("BO_ 1 Frame: 1 ECU\nSG_ State : 0|8@1+ (1,0) [0|255] \"\" ECU\n\n" +
896 statement.toStdString());
897 const DbcParseResult result = DbcParser().ParseFileWithDiagnostics(fixture.path.string());
898 QVERIFY(result.HasErrors());
899 QVERIFY(result.database.frames.empty());
900 QCOMPARE(result.diagnostics.size(), std::size_t(1));
901 const DbcDiagnostic &error = result.diagnostics[0];
902 QCOMPARE(error.severity, DbcDiagnosticSeverity::Error);
903 QCOMPARE(error.code, DbcDiagnosticCode::InvalidStatement);
904 QCOMPARE(error.filePath, fixture.path.string());
905 QCOMPARE(error.lineNumber, std::size_t(4));
906 QVERIFY(!error.message.empty());
907 try {
908 DbcParser().ParseFile(fixture.path.string());
909 QFAIL("Malformed or unresolved comment must throw.");
910 } catch (const std::runtime_error &exception) {
911 QVERIFY(std::string(exception.what()).find(fixture.path.string() + ":4: ") == 0U);
912 }
913}
914
915void DbcParserTest::integration() {
916 Fixture fixture;
917 fixture.Write(
918 "BO_TX_BU_ 256 : ECU;\nBO_ 256 Frame: 8 ECU\n"
919 " SG_ Speed : 0|16@1+ (0.5,1) [0|100] \"rpm\" ECU\n"
920 "CM_ BO_ 256 \"Frame comment\";\nCM_ SG_ 256 Speed \"Signal comment\";\n"
921 "BO_ 257 Second: 8 ECU\n");
922 const DbcDatabase database = DbcParser().ParseFile(fixture.path.string());
923 CHECK(database.frames.size() == 2U && database.frames[0].signals.size() == 1U &&
924 database.frames[0].comment == "Frame comment" &&
925 database.frames[0].signals[0].comment == "Signal comment",
926 "Integration");
927 fixture.Write("\nSG_ Speed : invalid\n");
928 try {
929 DbcParser().ParseFile(fixture.path.string());
930 CHECK(false, "Signal error location");
931 } catch (const std::runtime_error &error) {
932 CHECK(std::string(error.what()).find(fixture.path.string() + ":2: ") == 0U,
933 "Signal error location");
934 }
935}
936
937void DbcParserTest::multiplexing() {
938 Fixture fixture;
939 const std::string selector = "SG_ Mode M : 0|8@1+ (10,3) [0|255] \"\" ECU\n";
940 const std::string first = "SG_ First m1 : 8|8@1- (2,0) [-128|127] \"V\" ECU\n";
941 const std::string second = "SG_ Second m2 : 15|8@0+ (1,0) [0|255] \"\" ECU\n";
942 const std::string common = "SG_ Common : 16|8@1+ (1,0) [0|255] \"\" ECU\n";
943 fixture.Write("BO_ 1 Frame: 3 ECU\n" + first + second + common + selector +
944 "VAL_ 1 First -1 \"Negative\";\n");
945 const DbcDatabase parsed = DbcParser().ParseFile(fixture.path.string());
946 const DecodeDatabase runtime = DbcDecodeBuilder().Build(parsed);
947 CHECK(parsed.frames[0].signals[3].multiplexing.role == MultiplexRole::Selector,
948 "Selector declared after branches");
949 const std::unique_ptr<TreeNode> tree = DbcTreeBuilder().Build(parsed);
950 CHECK(tree->GetChild(0U)->GetChild(0U)->GetSignal()->multiplexing.value == 1U,
951 "Tree preserves multiplexing");
952 RawCanFrame raw;
953 raw.canId = 1U;
954 raw.data = {1U, 255U, 7U};
955 DecodedFrameValue result = DbcDecoder().Decode(runtime, raw);
956 CHECK(result.signals[0].valid && std::get<std::int64_t>(result.signals[0].rawValue) == -1 &&
957 result.signals[0].physicalValue == -2 && *result.signals[0].GetValueDescription() == "Negative",
958 "Active signed branch and VAL_ use exact raw selector");
959 CHECK(!result.signals[1].valid && result.signals[1].status == SignalDecodeStatus::Inactive &&
960 result.signals[1].GetValueDescription() == nullptr && result.signals[2].valid,
961 "Inactive branch and unconditional signal");
962 raw.data[0] = 2U;
963 result = DbcDecoder().Decode(runtime, raw);
964 CHECK(result.signals[0].status == SignalDecodeStatus::Inactive && result.signals[1].valid &&
965 std::get<std::uint64_t>(result.signals[1].rawValue) == 255U,
966 "Motorola branch becomes active");
967 raw.data = {3U};
968 result = DbcDecoder().Decode(runtime, raw);
969 CHECK(result.signals[0].status == SignalDecodeStatus::Inactive &&
970 result.signals[1].status == SignalDecodeStatus::Inactive &&
971 result.signals[2].status == SignalDecodeStatus::InsufficientPayload,
972 "Unmapped selector leaves branches inactive even with missing bytes");
973 raw.data = {1U};
974 result = DbcDecoder().Decode(runtime, raw);
975 CHECK(result.signals[0].status == SignalDecodeStatus::InsufficientPayload,
976 "Active branch requires payload");
977 raw.data.clear();
978 result = DbcDecoder().Decode(runtime, raw);
979 CHECK(result.signals[0].status == SignalDecodeStatus::SelectorUnavailable &&
980 result.signals[3].status == SignalDecodeStatus::InsufficientPayload,
981 "Unavailable selector does not imply inactive branch");
982
983 const std::vector<std::string> invalid = {
984 first,
985 selector + "SG_ Other M : 16|8@1- (1,0) [-128|127] \"\" ECU\n",
986 "SG_ Mode M : 0|8@1- (1,0) [-128|127] \"\" ECU\n",
987 selector + "SG_ TooLarge m256 : 8|8@1+ (1,0) [0|255] \"\" ECU\n",
988 selector + first + "SG_ Same m1 : 15|8@0+ (1,0) [0|255] \"\" ECU\n",
989 selector + "SG_ Collision m1 : 0|8@1+ (1,0) [0|255] \"\" ECU\n",
990 selector + first + "SG_ Always : 8|8@1+ (1,0) [0|255] \"\" ECU\n",
991 "SG_MUL_VAL_ 1 First Mode 1-2;\n"};
992 for (const std::string &signals : invalid) {
993 fixture.Write("BO_ 1 Frame: 3 ECU\n" + signals);
994 bool rejected = false;
995 try {
996 DbcParser().ParseFile(fixture.path.string());
997 } catch (const std::runtime_error &error) {
998 rejected = std::string(error.what()).find(fixture.path.string() + ":") == 0U;
999 }
1000 CHECK(rejected, "Invalid multiplexing rejected with location");
1001 }
1002 for (const std::string marker : {"m", "m-1", "m+1", "m1M", "m18446744073709551616", "M m1"})
1003 RejectSignal(fixture, "SG_ Bad " + marker + " : 8|8@1+ (1,0) [0|255] \"\" ECU");
1004}
1005
1006void DbcParserTest::multiplexingBoundaries() {
1007 Fixture fixture;
1008 fixture.Write("BO_ 1 Frame: 9 ECU\n"
1009 "SG_ Branch m18446744073709551615 : 64|8@1+ (1,0) [0|255] \"\" ECU\n"
1010 "SG_ Mode M : 7|64@0+ (0,5) [0|1] \"\" ECU\n");
1011 const DbcDatabase parsed = DbcParser().ParseFile(fixture.path.string());
1012 DecodeDatabase runtime = DbcDecodeBuilder().Build(parsed);
1013 CHECK(runtime.GetFrames()[0].signals[0].multiplexing.value == std::numeric_limits<std::uint64_t>::max(),
1014 "Exact uint64 branch metadata");
1015 RawCanFrame raw;
1016 raw.canId = 1U;
1017 raw.data = std::vector<std::uint8_t>(9U, 255U);
1018 DecodedFrameValue result = DbcDecoder().Decode(runtime, raw);
1019 CHECK(result.signals[0].valid && result.signals[1].valid &&
1020 std::get<std::uint64_t>(result.signals[1].rawValue) == std::numeric_limits<std::uint64_t>::max(),
1021 "Motorola uint64 selector compares raw value before zero scaling");
1022 raw.data[7] = 254U;
1023 result = DbcDecoder().Decode(runtime, raw);
1024 CHECK(result.signals[0].status == SignalDecodeStatus::Inactive,
1025 "Adjacent large integers remain distinct");
1026 std::vector<DecodeFrame> definitions = runtime.GetFrames();
1027 definitions[0].signals[1].length = 0U;
1028 QVERIFY_THROWS_EXCEPTION(std::invalid_argument, runtime = DecodeDatabase(definitions));
1029 definitions[0].signals.pop_back();
1030 QVERIFY_THROWS_EXCEPTION(std::invalid_argument, runtime = DecodeDatabase(definitions));
1031 fixture.Write("BO_ 1 Frame: 2 ECU\n\n"
1032 "SG_ Branch m2 : 8|8@1+ (1,0) [0|255] \"\" ECU\n"
1033 "SG_ Mode M : 0|1@1+ (1,0) [0|1] \"\" ECU\n");
1034 bool rejected = false;
1035 try {
1036 DbcParser().ParseFile(fixture.path.string());
1037 } catch (const std::runtime_error &error) {
1038 rejected = std::string(error.what()).find(fixture.path.string() + ":3: ") == 0U;
1039 }
1040 CHECK(rejected, "Deferred validation reports branch source line");
1041 fixture.Write("BO_ 1 Frame: 2 ECU\n"
1042 "SG_ A : 8|8@1+ (1,0) [0|255] \"\" ECU\n"
1043 "SG_ B : 15|8@0+ (1,0) [0|255] \"\" ECU\n");
1044 rejected = false;
1045 try {
1046 DbcParser().ParseFile(fixture.path.string());
1047 } catch (const std::runtime_error &) {
1048 rejected = true;
1049 }
1050 CHECK(rejected, "Ordinary overlapping signals rejected");
1051}
1052
1053void DbcParserTest::invalidSignals() {
1054 Fixture fixture;
1055 const std::string ordinary = SignalLine("0", "8", "1+", "1", "0", "0", "255");
1056 for (const std::string value: {"-1", "+1", "0junk", "0x10", "1.5",
1057 "4294967296", "999999999999999999999"}) {
1058 RejectSignal(fixture, SignalLine(value, "8", "1+", "1", "0", "0", "255"));
1059 RejectSignal(fixture, SignalLine("0", value, "1+", "1", "0", "0", "255"));
1060 }
1061 for (const std::string length: {"0", "65"})
1062 RejectSignal(fixture, SignalLine("0", length, "1+", "1", "0", "0", "255"));
1063 for (const std::string order: {"2+", "9-", "1", "1x", "1++", "01+"})
1064 RejectSignal(fixture, SignalLine("0", "8", order, "1", "0", "0", "255"));
1065 for (const std::string value: {"1junk", "nan", "NaN", "inf", "-inf", "1e999", "1e-999", "0x1p2", "", "1e", "1.2.3"}) {
1066 RejectSignal(fixture, SignalLine("0", "8", "1+", value, "0", "0", "255"));
1067 RejectSignal(fixture, SignalLine("0", "8", "1+", "1", value, "0", "255"));
1068 RejectSignal(fixture, SignalLine("0", "8", "1+", "1", "0", value, "255"));
1069 RejectSignal(fixture, SignalLine("0", "8", "1+", "1", "0", "0", value));
1070 }
1071 RejectSignal(fixture, SignalLine("0", "8", "1+", "1", "0", "2", "1"));
1072 for (const std::string name: {"", "Two Names", "Value m1M"}) {
1073 std::string line = ordinary;
1074 line.replace(4U, 5U, name);
1075 RejectSignal(fixture, line);
1076 }
1077 for (const std::string broken: {
1078 "SG_", "SG_ Value", "SG_ Value : 0|8@1+ (1,0) [0|255] ECU",
1079 "SG_ Value : 0|8@1+ (1,0) [0|255] \"\"",
1080 "SG_ Value : 0|8@1+ (1,0) [0|255] \"\" ECU,",
1081 "SG_ Value : 0|8@1+ (1,0) [0|255] \"\" ECU extra"})
1082 RejectSignal(fixture, broken);
1083 RejectSignal(fixture, SignalLine("64", "1", "1+", "1", "0", "0", "1"));
1084 RejectSignal(fixture, SignalLine("63", "2", "1+", "1", "0", "0", "3"));
1085 RejectSignal(fixture, SignalLine("56", "2", "0+", "1", "0", "0", "3"));
1086 RejectSignal(fixture, SignalLine("4294967295", "64", "1+", "1", "0", "0", "1"));
1087 RejectSignal(fixture, ordinary, 0U);
1088 for (const char delimiter: {'|', '@', '(', ')', '[', ']', '"'}) {
1089 std::string line = ordinary;
1090 line.erase(line.find(delimiter), 1U);
1091 RejectSignal(fixture, line);
1092 }
1093}
1094
1095void DbcParserTest::validSignals() {
1096 Fixture fixture;
1097 const DbcParser signalParser;
1098 fixture.Write("BO_ 1 Frame: 8 ECU\n" +
1099 SignalLine("0", "8", "1+", "0", "0", "0", "0") + "\n" +
1100 SignalLine("8", "8", "1-", "-1", "0", "-255", "0", "Negative") + "\n");
1101 const DbcDatabase factors = signalParser.ParseFile(fixture.path.string());
1102 CHECK(factors.frames[0].signals.size() == 2U &&
1103 factors.frames[0].signals[0].factor == 0.0 &&
1104 factors.frames[0].signals[1].factor == -1.0,
1105 "Zero and negative factors and equal range boundaries");
1106
1107 struct SignalCase {
1108 const char *start;
1109 const char *length;
1110 const char *order;
1111 unsigned payload;
1112 };
1113 const SignalCase validSignals[] = {
1114 {"0", "1", "1+", 1U},
1115 {"7", "1", "0-", 1U},
1116 {"0", "64", "1+", 8U},
1117 {"7", "64", "0-", 8U},
1118 {"63", "1", "1+", 8U},
1119 {"56", "1", "0+", 8U},
1120 {"3", "12", "0+", 2U},
1121 {"2039", "1", "1+", 255U}};
1122 for (const SignalCase &test: validSignals) {
1123 fixture.Write("BO_ 1 Frame: " + std::to_string(test.payload) + " ECU\n" +
1124 SignalLine(test.start, test.length, test.order, ".5e+1", "-2.5E-1", "-1.", "+2e2") + "\n");
1125 try {
1126 const DbcDatabase parsed = signalParser.ParseFile(fixture.path.string());
1127 const SignalInfo &signal = parsed.frames.at(0).signals.at(0);
1128 QCOMPARE(signal.startBit, static_cast<std::uint32_t>(std::stoul(test.start)));
1129 QCOMPARE(signal.length, static_cast<std::uint32_t>(std::stoul(test.length)));
1130 QCOMPARE(signal.isLittleEndian, test.order[0] == '1');
1131 QCOMPARE(signal.isSigned, test.order[1] == '-');
1132 QCOMPARE(signal.factor, 5.0);
1133 QCOMPARE(signal.offset, -0.25);
1134 QCOMPARE(signal.minimum, -1.0);
1135 QCOMPARE(signal.maximum, 200.0);
1136 } catch (const std::exception &error) { CHECK(false, error.what()); }
1137 }
1138 fixture.Write("BO_ 1 Frame: 8 ECU\n"
1139 "SG_\tValue\t:\t0 | 8 @1+ ( 1 , 0 ) [ 0 | 255 ] \"rpm\" ECU1,\tECU2\n");
1140 try {
1141 const DbcDatabase parsed = signalParser.ParseFile(fixture.path.string());
1142 const SignalInfo &signal = parsed.frames.at(0).signals.at(0);
1143 CHECK(signal.name == "Value" && signal.unit == "rpm" &&
1144 signal.receivers == std::vector<std::string>({"ECU1", "ECU2"}),
1145 "Signal tabs, spaces, and receiver list");
1146 } catch (const std::exception &error) { CHECK(false, error.what()); }
1147}
1148
1149void DbcParserTest::CheckPhysicalNumbers() {
1150 Fixture fixture;
1151 struct PhysicalCase {
1152 const char *factor;
1153 const char *offset;
1154 const char *minimum;
1155 const char *maximum;
1156 double expectedFactor;
1157 double expectedOffset;
1158 double expectedMinimum;
1159 double expectedMaximum;
1160 };
1161 const PhysicalCase valid[] = {
1162 {"+1.25", "-0.5", "-2.75", "255.5", 1.25, -0.5, -2.75, 255.5},
1163 {"+.5e+1", "-2.5E-1", "-1.", "+2e2", 5.0, -0.25, -1.0, 200.0},
1164 {"0e-999", "+0.", "-.0", ".0e+999", 0.0, 0.0, 0.0, 0.0},
1165 {"1.7976931348623157e308", "2.2250738585072014e-308", "-1e308", "+1e308",
1166 std::numeric_limits<double>::max(), std::numeric_limits<double>::min(), -1e308, 1e308}};
1167 for (const PhysicalCase &test: valid) {
1168 fixture.Write("BO_ 1 Frame: 1 ECU\n" +
1169 SignalLine("0", "8", "1+", test.factor, test.offset, test.minimum, test.maximum) + "\n");
1170 const DbcParseResult result = DbcParser().ParseFileWithDiagnostics(fixture.path.string());
1171 QVERIFY(!result.HasErrors());
1172 QVERIFY(result.diagnostics.empty());
1173 QCOMPARE(result.database.frames.size(), std::size_t(1));
1174 const SignalInfo &signal = result.database.frames[0].signals[0];
1175 QCOMPARE(signal.factor, test.expectedFactor);
1176 QCOMPARE(signal.offset, test.expectedOffset);
1177 QCOMPARE(signal.minimum, test.expectedMinimum);
1178 QCOMPARE(signal.maximum, test.expectedMaximum);
1179 }
1180
1181 const char *invalid[] = {"1,5", "1.234,5", "1,234.5", "1junk", "nan", "inf", "-inf",
1182 "1e999", "1e-999", "1e-320", "-1e-320", "0x1p2", "1e", "1.2.3"};
1183 for (const char *value: invalid) {
1184 RejectSignal(fixture, SignalLine("0", "8", "1+", value, "0", "0", "255"));
1185 RejectSignal(fixture, SignalLine("0", "8", "1+", "1", value, "0", "255"));
1186 RejectSignal(fixture, SignalLine("0", "8", "1+", "1", "0", value, "255"));
1187 RejectSignal(fixture, SignalLine("0", "8", "1+", "1", "0", "0", value));
1188 }
1189 RejectSignal(fixture, SignalLine("0", "8", "1+", "1.25", "0", "2.5", "1.5"));
1190}
1191
1192void DbcParserTest::physicalNumbersCppLocale() {
1193 const ApplicationLocaleGuard guard;
1194 std::locale::global(std::locale(std::locale::classic(), new CommaDecimalPunctuation));
1195 QCOMPARE(std::use_facet<std::numpunct<char>>(std::locale()).decimal_point(), ',');
1196 CheckPhysicalNumbers();
1197 QCOMPARE(std::use_facet<std::numpunct<char>>(std::locale()).decimal_point(), ',');
1198}
1199
1200void DbcParserTest::physicalNumbersCLocale() {
1201 const ApplicationLocaleGuard guard;
1202 bool found = false;
1203 const char *names[] = {"de_DE.UTF-8", "de_DE.utf8", "fr_FR.UTF-8", "fr_FR.utf8",
1204 "German_Germany.1252", "French_France.1252"};
1205 for (const char *name: names) {
1206 if (std::setlocale(LC_NUMERIC, name) && std::string(std::localeconv()->decimal_point) == ",") {
1207 found = true;
1208 break;
1209 }
1210 }
1211 if (!found)
1212 QSKIP("No named comma-decimal C locale is installed; generate de_DE.UTF-8 and set LOCPATH.");
1213 QCOMPARE(std::string(std::localeconv()->decimal_point), std::string(","));
1214 CheckPhysicalNumbers();
1215 QCOMPARE(std::string(std::localeconv()->decimal_point), std::string(","));
1216}
1217
1218void DbcParserTest::dispatch() {
1219 CountingHandler::instances = 0;
1220 CountingHandler::calls = 0;
1221 DbcDatabase dispatchDatabase;
1222 DbcParseContext context{dispatchDatabase, nullptr};
1223 DbcStatementDispatcher dispatcher;
1224 dispatcher.RegisterType<CountingHandler>("TEST_");
1225 CHECK(dispatcher.Dispatch("TEST_ first", context) &&
1226 dispatcher.Dispatch("TEST_ second", context) &&
1227 CountingHandler::instances == 1 && CountingHandler::calls == 2 &&
1228 dispatchDatabase.frames.size() == 2U,
1229 "Factory dispatch and handler reuse");
1230 CHECK(!dispatcher.Dispatch("TEST_OTHER data", context) &&
1231 !dispatcher.Dispatch("BO_TX_BU_ 1 : ECU;", context) &&
1232 !dispatcher.Dispatch("VAL_TABLE_ States 0 \"Stopped\";", context) &&
1233 CountingHandler::calls == 2,
1234 "Exact and unknown keyword dispatch");
1235}
1236
1237void DbcParserTest::independentSessions() {
1238 Fixture fixture;
1239 const DbcParser parser;
1240 fixture.Write("BO_ 1 First: 8 ECU\n");
1241 CHECK(parser.ParseFile(fixture.path.string()).frames.size() == 1U, "First parse");
1242 fixture.Write("SG_ Speed : invalid\n");
1243 try {
1244 parser.ParseFile(fixture.path.string());
1245 CHECK(false, "Independent parse context");
1246 } catch (const std::runtime_error &error) {
1247 CHECK(std::string(error.what()).find("Signal found before any frame") !=
1248 std::string::npos,
1249 "Independent parse context");
1250 }
1251 fixture.Write("BO_ 2 Second: 8 ECU\n");
1252 const DbcDatabase recovered = parser.ParseFile(fixture.path.string());
1253 CHECK(recovered.frames.size() == 1U && recovered.frames[0].canId == 2U,
1254 "Fresh parse after error");
1255}
1256
1257
1258void DbcParserTest::valueDescriptions() {
1259 Fixture fixture;
1260 fixture.Write(
1261 "VAL_\t256\tState\t0\t\"Off\"\t1 \"On\" 2 \"Error with spaces; and \\\"quotes\\\"\";\n"
1262 "BO_ 256 Status: 8 ECU\n"
1263 "SG_ State : 0|8@1+ (2,10) [0|520] \"\" ECU\n"
1264 "VAL_ 256 State 3 \"\";\n"
1265 "VAL_ 2147483904 State -9223372036854775808 \"Minimum\" -1 \"Negative\" 9223372036854775807 \"Maximum\";\n"
1266 "BO_ 2147483904 Extended: 8 ECU\n"
1267 "SG_ State : 0|64@1- (1,0) [-1e20|1e20] \"\" ECU\n"
1268 "BO_ 2048 Unsigned: 8 ECU\n"
1269 "SG_ State : 0|64@1+ (1,0) [0|2e20] \"\" ECU\n"
1270 "VAL_ 2147485696 State 9223372036854775808 \"High\" 18446744073709551615 \"Full\";\n");
1271 const DbcDatabase parsed = DbcParser().ParseFile(fixture.path.string());
1272 const DecodeDatabase runtime = DbcDecodeBuilder().Build(parsed);
1273 const std::unique_ptr<TreeNode> tree = DbcTreeBuilder().Build(parsed);
1274 CHECK(tree->GetChild(0)->GetSignal() == nullptr, "Frame node");
1275 for (std::size_t index = 0; index < parsed.frames.size(); ++index) {
1276 CHECK(tree->GetChild(index)->GetChild(0)->GetSignal()->valueDescriptions ==
1277 parsed.frames[index].signals[0].valueDescriptions &&
1278 runtime.GetFrames()[index].signals[0].valueDescriptions ==
1279 parsed.frames[index].signals[0].valueDescriptions,
1280 "All mappings survive both builders");
1281 }
1282 CHECK(tree->GetChild(0)->GetChild(0)->GetSignal()->valueDescriptions ==
1283 runtime.GetFrames()[0].signals[0].valueDescriptions,
1284 "Both builders preserve descriptions");
1285 RawCanFrame frame;
1286 frame.canId = 256;
1287 frame.data.resize(8);
1288 const std::string expected[] = {"Off", "On", "Error with spaces; and \"quotes\"", ""};
1289 for (unsigned value = 0; value < 5; ++value) {
1290 frame.data[0] = value;
1291 const DecodedSignalValue decoded = DbcDecoder().Decode(runtime, frame).signals[0];
1292 CHECK(decoded.valid && decoded.physicalValue == value * 2 + 10, "Numeric scaling unchanged");
1293 const std::string *description = decoded.GetValueDescription();
1294 CHECK(value < 4 ? description && *description == expected[value] : !description,
1295 "Raw lookup and unknown value");
1296 }
1297 frame.isExtended = true;
1298 struct Boundary {
1299 std::uint64_t bits;
1300 const char *description;
1301 };
1302 for (const Boundary &test: {Boundary{0x8000000000000000ULL, "Minimum"},
1303 Boundary{0xFFFFFFFFFFFFFFFFULL, "Negative"},
1304 Boundary{0x7FFFFFFFFFFFFFFFULL, "Maximum"}}) {
1305 for (unsigned byte = 0; byte < 8; ++byte)
1306 frame.data[byte] = static_cast<std::uint8_t>(test.bits >> (byte * 8));
1307 const DecodedSignalValue decoded = DbcDecoder().Decode(runtime, frame).signals[0];
1308 CHECK(decoded.GetValueDescription() && *decoded.GetValueDescription() == test.description,
1309 "Signed boundaries and distinct extended frame");
1310 }
1311 frame.canId = 2048;
1312 for (const Boundary &test: {Boundary{0x8000000000000000ULL, "High"},
1313 Boundary{0xFFFFFFFFFFFFFFFFULL, "Full"}}) {
1314 for (unsigned byte = 0; byte < 8; ++byte)
1315 frame.data[byte] = static_cast<std::uint8_t>(test.bits >> (byte * 8));
1316 const DecodedSignalValue decoded = DbcDecoder().Decode(runtime, frame).signals[0];
1317 CHECK(decoded.GetValueDescription() && *decoded.GetValueDescription() == test.description,
1318 "Unsigned boundaries");
1319 }
1320 CHECK(FindValueDescription(runtime.GetFrames()[0].signals[0].valueDescriptions, std::int64_t(1)) != nullptr,
1321 "Nonnegative signed lookup matches unsigned key");
1322 frame.data.clear();
1323 CHECK(!DbcDecoder().Decode(runtime, frame).signals[0].GetValueDescription(), "Invalid decode has no description");
1324}
1325
1326void DbcParserTest::invalidValueDescriptions() {
1327 Fixture fixture;
1328 const std::string definitions = "BO_ 1 Frame: 8 ECU\nSG_ State : 0|64@1+ (1,0) [0|2e20] \"\" ECU\n";
1329 for (const std::string statement: {
1330 "VAL_", "VAL_ 1 State;", "VAL_ 1 State ;", "VAL_ 1 State 0 \"Off\"",
1331 "VAL_ 1 State 0 \"Off\"; junk", "VAL_ 1 State 0 Off;",
1332 "VAL_ 1 State 0 \"Unclosed;", "VAL_ 1 State 0 \"Off\"1 \"On\";",
1333 "VAL_ 1 State 0 \"Off\" 00 \"Duplicate\";",
1334 "VAL_ 1 State 0 \"Off\" -0 \"Duplicate\";",
1335 "VAL_ 1 State 0 \"Off\";\nVAL_ 1 State 0 \"Duplicate\";",
1336 "VAL_ 2 State 0 \"Missing frame\";", "VAL_ 1 Missing 0 \"Missing signal\";",
1337 "VAL_ -1 State 0 \"Bad ID\";", "VAL_ 536870912 State 0 \"Bad ID\";",
1338 "VAL_ 4294967296 State 0 \"Bad ID\";", "VAL_ Environment 0 \"Unsupported\";",
1339 "VAL_ 1 State 0 \"Bad\\q escape\";"}) {
1340 fixture.Write(definitions + statement + '\n');
1341 const int line = statement.find('\n') == std::string::npos ? 3 : 4;
1342 try {
1343 DbcParser().ParseFile(fixture.path.string());
1344 CHECK(false, statement);
1345 } catch (const std::runtime_error &error) {
1346 CHECK(std::string(error.what()).find(fixture.path.string() + ":" + std::to_string(line) + ": ") == 0,
1347 statement + " " + error.what());
1348 }
1349 }
1350 for (const std::string suffix: {
1351 "BO_ 1 Other: 8 ECU\n", // Duplicate frame definition.
1352 "SG_ State : 0|8@1+ (1,0) [0|255] \"\" ECU\n",// Duplicate signal definition.
1353 ""}) {
1354 fixture.Write("VAL_ 1 " + std::string(suffix.empty() ? "Missing" : "State") +
1355 " 0 \"Description\";\n" + definitions + suffix);
1356 try {
1357 DbcParser().ParseFile(fixture.path.string());
1358 CHECK(false, "Missing reference or duplicate definition");
1359 } catch (const std::runtime_error &error) {
1360 const std::string line = suffix.empty() ? "1" : "4";
1361 CHECK(std::string(error.what()).find(fixture.path.string() + ":" + line + ": ") == 0,
1362 "Error retains the reference or duplicate definition source location");
1363 }
1364 }
1365 for (const std::string number: {"+1", "1x", "0x10", "1.5", "1e2", "--1",
1366 "-9223372036854775809", "18446744073709551616"}) {
1367 fixture.Write("VAL_ 1 State " + number + " \"Bad\";\n" + definitions);
1368 try {
1369 DbcParser().ParseFile(fixture.path.string());
1370 CHECK(false, number);
1371 } catch (const std::runtime_error &error) {
1372 CHECK(std::string(error.what()).find(fixture.path.string() + ":1: ") == 0, number);
1373 }
1374 }
1375}
1376
1377
1378void DbcParserTest::extendedMultiplexing() {
1379 Fixture fixture;
1380 // Forward references, multiple ranges, repeated range statements, and nested siblings.
1381 fixture.Write(
1382 "SG_MUL_VAL_ 1 Child Root 1-2, 4-4;\n"
1383 "SG_MUL_VAL_ 1 Leaf Child 3-5;\n"
1384 "SG_MUL_VAL_ 1 Leaf Child 7-7;\n"
1385 "SG_MUL_VAL_ 1 Sibling Root 6-6;\n"
1386 "SG_MUL_VAL_ 1 Other Sibling 3-5;\n"
1387 "BO_ 1 Frame: 4 ECU\n"
1388 "SG_ Leaf m99 : 16|8@1- (2,1) [-128|127] \"\" ECU\n"
1389 "SG_ Other m0 : 23|8@0+ (1,0) [0|255] \"\" ECU\n"
1390 "SG_ Child m1M : 8|8@1+ (10,3) [0|255] \"\" ECU\n"
1391 "SG_ Sibling m6M : 15|8@0+ (1,0) [0|255] \"\" ECU\n"
1392 "SG_ Root M : 0|8@1+ (10,3) [0|255] \"\" ECU\n"
1393 "SG_ Common : 24|8@1+ (1,0) [0|255] \"\" ECU\n");
1394 const DbcDatabase parsed = DbcParser().ParseFile(fixture.path.string());
1395 const DecodeDatabase database = DbcDecodeBuilder().Build(parsed);
1396 const std::unique_ptr<TreeNode> tree = DbcTreeBuilder().Build(parsed);
1397 const Multiplexing &metadata = tree->GetChild(0U)->GetChild(0U)->GetSignal()->multiplexing;
1398 CHECK(metadata.selector == "Child" && metadata.ranges.size() == 2U &&
1399 metadata.ranges[1].minimum == 7U,
1400 "Tree preserves ranges and selector name");
1401 CHECK(database.GetFrames()[0].signals[2].multiplexing.role == MultiplexRole::BranchSelector,
1402 "Runtime preserves nested selector role");
1403 RawCanFrame raw;
1404 raw.canId = 1U;
1405 raw.data = {2U, 4U, 255U, 8U};
1406 DecodedFrameValue result = DbcDecoder().Decode(database, raw);
1407 CHECK(result.signals[0].valid && result.signals[0].physicalValue == -1.0 &&
1408 result.signals[1].status == SignalDecodeStatus::Inactive && result.signals[2].valid &&
1409 result.signals[3].status == SignalDecodeStatus::Inactive && result.signals[5].valid,
1410 "Nested raw conditions select one path and preserve definition order");
1411 const std::vector<SignalKey> selection = {SignalKey(FrameKey(1U, false), "Leaf")};
1412 result = DbcDecoder().Decode(database, raw, selection);
1413 CHECK(result.signals.size() == 1U && result.signals[0].valid,
1414 "Selection reads all ancestors internally");
1415 for (std::uint8_t root: {1U, 2U, 4U}) {
1416 for (std::uint8_t child: {3U, 5U, 7U}) {
1417 raw.data = {root, child, 9U, 8U};
1418 CHECK(DbcDecoder().Decode(database, raw, selection).signals[0].valid,
1419 "Inclusive endpoints and separated ranges");
1420 }
1421 }
1422 raw.data = {6U, 4U, 9U, 8U};
1423 result = DbcDecoder().Decode(database, raw);
1424 CHECK(result.signals[0].status == SignalDecodeStatus::Inactive && result.signals[1].valid &&
1425 result.signals[3].valid,
1426 "Overlapping sibling selector path becomes active");
1427 raw.data = {0U};
1428 CHECK(DbcDecoder().Decode(database, raw, selection).signals[0].status == SignalDecodeStatus::Inactive,
1429 "Inactive root does not require child selector bytes");
1430 raw.data = {1U};
1431 CHECK(DbcDecoder().Decode(database, raw, selection).signals[0].status == SignalDecodeStatus::SelectorUnavailable,
1432 "Active root with missing child selector");
1433 raw.data = {1U, 3U};
1434 CHECK(DbcDecoder().Decode(database, raw, selection).signals[0].status == SignalDecodeStatus::InsufficientPayload,
1435 "Active nested leaf needs its bytes");
1436 raw.data = {1U, 6U};
1437 CHECK(DbcDecoder().Decode(database, raw, selection).signals[0].status == SignalDecodeStatus::Inactive,
1438 "Gap between explicit ranges does not fall back to mN");
1439 raw.data.clear();
1440 CHECK(DbcDecoder().Decode(database, raw, selection).signals[0].status == SignalDecodeStatus::SelectorUnavailable,
1441 "Missing root selector");
1442
1443 fixture.Write("BO_ 1 Frame: 9 ECU\n"
1444 "SG_ Root M : 0|64@1+ (1,0) [0|1] \"\" ECU\n"
1445 "SG_ Leaf m0 : 64|8@1+ (1,0) [0|255] \"\" ECU\n"
1446 "SG_MUL_VAL_ 1 Leaf Root 18446744073709551614-18446744073709551615;\n");
1447 raw.data.assign(9U, 255U);
1448 CHECK(DbcDecoder().Decode(DbcDecodeBuilder().Build(DbcParser().ParseFile(fixture.path.string())), raw).signals[1].valid,
1449 "64-bit ranges retain exact UINT64_MAX without expansion");
1450
1451 fixture.Write("BO_ 1 Frame: 4 ECU\n"
1452 "SG_ Root M : 0|8@1+ (1,0) [0|255] \"\" ECU\n"
1453 "SG_ Second M : 8|8@1+ (1,0) [0|255] \"\" ECU\n"
1454 "SG_ A m0 : 16|8@1+ (1,0) [0|255] \"\" ECU\n"
1455 "SG_ B m0 : 24|8@1+ (1,0) [0|255] \"\" ECU\n"
1456 "SG_MUL_VAL_ 1 A Root 1-1;\nSG_MUL_VAL_ 1 B Second 2-2;\n");
1457 raw.data = {1U, 2U, 9U, 10U};
1458 result = DbcDecoder().Decode(DbcDecodeBuilder().Build(DbcParser().ParseFile(fixture.path.string())), raw);
1459 CHECK(result.signals[2].valid && result.signals[3].valid, "Independent explicit selectors");
1460
1461 fixture.Write("BO_ 1 Deep: 5 ECU\n"
1462 "SG_ Root M : 0|8@1+ (1,0) [0|255] \"\" ECU\n"
1463 "SG_ Child m1M : 8|8@1+ (1,0) [0|255] \"\" ECU\n"
1464 "SG_ Grandchild m2M : 16|8@1+ (1,0) [0|255] \"\" ECU\n"
1465 "SG_ Leaf : 24|8@1+ (1,0) [0|255] \"\" ECU\n"
1466 "SG_MUL_VAL_ 1 Grandchild Child 2-2;\n"
1467 "SG_MUL_VAL_ 1 Leaf Grandchild 3-3;\n");
1468 const DecodeDatabase deep = DbcDecodeBuilder().Build(DbcParser().ParseFile(fixture.path.string()));
1469 raw.data = {1U, 2U, 3U, 9U, 0U};
1470 CHECK(DbcDecoder().Decode(deep, raw).signals[3].valid, "Three selector levels and an unmarked extended branch");
1471 raw.data = {1U, 0U};
1472 CHECK(DbcDecoder().Decode(deep, raw).signals[3].status == SignalDecodeStatus::Inactive,
1473 "Inactive middle ancestor skips missing descendant bytes");
1474
1475 // Marker fallback also works on a nested selector without its own SG_MUL_VAL_.
1476 fixture.Write("BO_ 1 Frame: 3 ECU\n"
1477 "SG_ Root M : 0|8@1+ (1,0) [0|255] \"\" ECU\n"
1478 "SG_ Child m1M : 8|8@1+ (1,0) [0|255] \"\" ECU\n"
1479 "SG_ Leaf m2 : 16|8@1+ (1,0) [0|255] \"\" ECU\n"
1480 "SG_MUL_VAL_ 1 Leaf Child 2-2;\n");
1481 raw.data = {1U, 2U, 9U};
1482 CHECK(DbcDecoder().Decode(DbcDecodeBuilder().Build(DbcParser().ParseFile(fixture.path.string())), raw).signals[2].valid,
1483 "mNM retains implicit root fallback");
1484}
1485
1486void DbcParserTest::extendedMultiplexingErrors() {
1487 Fixture fixture;
1488 const std::string definitions =
1489 "BO_ 1 Frame: 3 ECU\n"
1490 "SG_ Root M : 0|8@1+ (1,0) [0|255] \"\" ECU\n"
1491 "SG_ Child m1M : 8|8@1+ (1,0) [0|255] \"\" ECU\n"
1492 "SG_ Leaf m2 : 16|8@1+ (1,0) [0|255] \"\" ECU\n";
1493 for (const std::string statement: {
1494 "SG_MUL_VAL_ 1 Leaf Root 3-2;", "SG_MUL_VAL_ 1 Leaf Root -1-2;",
1495 "SG_MUL_VAL_ 1 Leaf Root 1-256;", "SG_MUL_VAL_ 1 Leaf Root 1-2,;",
1496 "SG_MUL_VAL_ 1 Leaf Root 1-2 trailing;", "SG_MUL_VAL_ 1 Leaf Root 1-2",
1497 "SG_MUL_VAL_ 1 Leaf Root 0-18446744073709551616;",
1498 "SG_MUL_VAL_ 1 Leaf Missing 1-2;", "SG_MUL_VAL_ 1 Missing Root 1-2;",
1499 "SG_MUL_VAL_ 2 Leaf Root 1-2;", "SG_MUL_VAL_ 1 Leaf Leaf 1-2;"}) {
1500 fixture.Write(statement + "\n" + definitions);
1501 const DbcParseResult result = DbcParser().ParseFileWithDiagnostics(fixture.path.string());
1502 CHECK(result.HasErrors() && result.database.frames.empty(), statement);
1503 CHECK(result.diagnostics.back().code == DbcDiagnosticCode::InvalidMultiplexing &&
1504 result.diagnostics.back().lineNumber == 1U,
1505 "Extended error retains source statement location");
1506 }
1507 for (const std::string statements: {
1508 "SG_MUL_VAL_ 1 Root Child 1-1;\nSG_MUL_VAL_ 1 Child Root 1-1;\n",
1509 "SG_MUL_VAL_ 1 Child Child 1-1;\n",
1510 "SG_MUL_VAL_ 1 Leaf Root 1-1;\nSG_MUL_VAL_ 1 Leaf Child 1-1;\n"}) {
1511 fixture.Write(definitions + statements);
1512 CHECK(DbcParser().ParseFileWithDiagnostics(fixture.path.string()).HasErrors(), "Cyclic or conflicting parents rejected");
1513 }
1514 // Range intersection and inherited root conditions must both protect overlaps.
1515 const std::string overlapping =
1516 "BO_ 1 Frame: 4 ECU\n"
1517 "SG_ Root M : 0|8@1+ (1,0) [0|255] \"\" ECU\n"
1518 "SG_ Child m1M : 8|8@1+ (1,0) [0|255] \"\" ECU\n"
1519 "SG_ A m0 : 16|8@1+ (1,0) [0|255] \"\" ECU\n"
1520 "SG_ B m0 : 23|8@0+ (1,0) [0|255] \"\" ECU\n"
1521 "SG_MUL_VAL_ 1 A Child 2-4;\n"
1522 "SG_MUL_VAL_ 1 Child Root 1-1;\n";
1523 for (const std::string condition: {"SG_MUL_VAL_ 1 B Child 4-6;\n",
1524 "SG_MUL_VAL_ 1 B Root 1-1;\n"}) {
1525 fixture.Write(overlapping + condition);
1526 CHECK(DbcParser().ParseFileWithDiagnostics(fixture.path.string()).HasErrors(),
1527 "Overlapping ranges or compatible ancestors cannot share bits");
1528 }
1529 fixture.Write(overlapping + "SG_MUL_VAL_ 1 B Child 5-6;\n");
1530 CHECK(!DbcParser().ParseFileWithDiagnostics(fixture.path.string()).HasErrors(),
1531 "Disjoint adjacent ranges may share bits");
1532 fixture.Write(overlapping + "SG_ Second M : 24|8@1+ (1,0) [0|255] \"\" ECU\n"
1533 "SG_MUL_VAL_ 1 B Second 2-4;\n");
1534 const DbcParseResult independent = DbcParser().ParseFileWithDiagnostics(fixture.path.string());
1535 CHECK(independent.HasErrors() && independent.diagnostics.back().message ==
1536 "Signals overlap without mutually exclusive multiplexing conditions.",
1537 "Independent selector conditions do not imply exclusion");
1538
1539 // Validate manually constructed runtime graphs with the same rules.
1540 fixture.Write(definitions + "SG_MUL_VAL_ 1 Leaf Child 2-3;\n");
1541 const DecodeDatabase valid = DbcDecodeBuilder().Build(DbcParser().ParseFile(fixture.path.string()));
1542 for (unsigned kind = 0U; kind < 6U; ++kind) {
1543 std::vector<DecodeFrame> frames = valid.GetFrames();
1544 Multiplexing &leaf = frames[0].signals[2].multiplexing;
1545 switch (kind) {
1546 case 0:
1547 leaf.selector = "Missing";
1548 break;
1549 case 1:
1550 leaf.ranges[0] = {4U, 3U};
1551 break;
1552 case 2:
1553 leaf.ranges[0] = {0U, 256U};
1554 break;
1555 case 3:
1556 leaf.ranges.clear();
1557 break;
1558 case 4:
1559 frames[0].signals[0].multiplexing.selector = "Child";
1560 frames[0].signals[0].multiplexing.ranges = {{1U, 1U}};
1561 break;
1562 case 5:
1563 frames[0].signals[1].valueType = ValueType::Signed;
1564 break;
1565 }
1566 QVERIFY_THROWS_EXCEPTION(std::invalid_argument, (void) DecodeDatabase(frames));
1567 }
1568}
1569
1570int RunParserTests(int argc, char **argv) {
1571 DbcParserTest tests;
1572 return QTest::qExec(&tests, argc, argv);
1573}
1574
1575#include "dbc_parser_test.moc"
Converts parsed DBC data into runtime decode database.
DecodeDatabase Build(const DbcDatabase &source) const
Build runtime decode database.
Runtime CAN decoder using prebuilt decode database.
Definition dbc_decoder.h:87
DecodedFrameValue Decode(const DecodeDatabase &database, const RawCanFrame &frame) const
Decode one raw CAN frame.
Minimal DBC parser.
Definition dbc_parser.h:43
DbcParseResult ParseFileWithDiagnostics(const std::string &filePath) const
Parse with warnings and a structured first error instead of throwing.
DbcDatabase ParseFile(const std::string &filePath) const
Parse DBC file.
void RegisterType(const std::string &keyword)
Register or replace a handler and create its reusable instance.
bool Dispatch(const std::string &line, DbcParseContext &context) const
Interface for processing a registered DBC statement.
virtual void Handle(const std::string &line, DbcParseContext &context) const =0
Process a trimmed statement using state belonging to this parse.
Builds a simple tree from parsed DBC database.
std::unique_ptr< TreeNode > Build(const DbcDatabase &database) const
Build tree representation of parsed DBC data.
Immutable runtime snapshot. Copies share storage; reload replaces a snapshot. Owning lookup handles a...
const std::vector< DecodeFrame > & GetFrames() const
Runtime decode database builder.
CAN frame decoding API and result types.
DBC file parser and interpretation options.
Metadata tree builder.
Parsed DBC content stored in a simple internal form.
std::map< std::string, AttributeDefinition > attributeDefinitions
std::vector< FrameInfo > frames
AttributeMap attributes
std::vector< AttributeAssignment > attributeAssignments
Diagnostic message and physical source location.
std::string message
DbcDiagnosticSeverity severity
DbcDiagnosticCode code
std::string filePath
std::size_t lineNumber
Parsed database and diagnostics; the database is empty on error.
std::vector< DbcDiagnostic > diagnostics
bool HasErrors() const
Return whether any diagnostic has error severity.
DbcDatabase database
Fully decoded frame.
Definition dbc_decoder.h:74
std::shared_ptr< const DecodeFrame > definition
Definition dbc_decoder.h:75
FrameDecodeStatus status
Definition dbc_decoder.h:79
One decoded signal value.
Definition dbc_decoder.h:55
const std::string * GetValueDescription() const
Definition dbc_decoder.h:64
Describes one CAN frame from a DBC file.
Definition frame_info.h:25
bool isExtended
Definition frame_info.h:28
std::string transmitter
Definition frame_info.h:32
std::uint8_t dlc
Definition frame_info.h:31
std::string name
Definition frame_info.h:26
std::uint32_t canId
Definition frame_info.h:27
Stable frame identifier: normalized CAN ID and frame type.
Basic markers and optional explicit extended multiplexing condition.
std::vector< MultiplexRange > ranges
std::string selector
Raw CAN frame used for runtime or trace decoding.
Definition dbc_decoder.h:25
std::vector< std::uint8_t > data
Definition dbc_decoder.h:28
std::uint32_t canId
Definition dbc_decoder.h:26
bool isExtended
Definition dbc_decoder.h:27
Describes one signal inside a DBC frame.
Definition signal_info.h:25
std::uint32_t length
Definition signal_info.h:29
std::string unit
Definition signal_info.h:36
std::vector< std::string > receivers
Definition signal_info.h:37
std::string name
Definition signal_info.h:27
bool isSigned
Definition signal_info.h:31
double offset
Definition signal_info.h:33
std::uint32_t startBit
Definition signal_info.h:28
double minimum
Definition signal_info.h:34
double maximum
Definition signal_info.h:35
double factor
Definition signal_info.h:32
bool isLittleEndian
Definition signal_info.h:30