1 | // Copyright (C) 2016 The Qt Company Ltd. |
2 | // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0 |
3 | |
4 | #include "parser.h" |
5 | #include "utils.h" |
6 | #include <stdio.h> |
7 | #include <stdlib.h> |
8 | |
9 | QT_BEGIN_NAMESPACE |
10 | |
11 | static const char *error_msg = nullptr; |
12 | |
13 | /*! \internal |
14 | Base implementation for printing diagnostic messages. |
15 | |
16 | For example: |
17 | "/path/to/file:line:column: error: %s\n" |
18 | '%s' is replaced by \a msg. (Currently "column" is always 1). |
19 | |
20 | If sym.lineNum is -1, the line and column parts aren't printed: |
21 | "/path/to/file: error: %s\n" |
22 | |
23 | \a formatStringSuffix specifies the type of the message e.g.: |
24 | "error: %s\n" |
25 | "warning: %s\n" |
26 | "note: %s\n" |
27 | "Parse error at %s\n" (from defaultErrorMsg()) |
28 | */ |
29 | void Parser::printMsg(QByteArrayView formatStringSuffix, QByteArrayView msg, const Symbol &sym) |
30 | { |
31 | if (sym.lineNum != -1) { |
32 | #ifdef Q_CC_MSVC |
33 | QByteArray formatString = "%s(%d:%d): " + formatStringSuffix; |
34 | #else |
35 | QByteArray formatString = "%s:%d:%d: " + formatStringSuffix; |
36 | #endif |
37 | fprintf(stderr, format: formatString.constData(), |
38 | currentFilenames.top().constData(), sym.lineNum, 1, msg.data()); |
39 | } else { |
40 | QByteArray formatString = "%s: " + formatStringSuffix; |
41 | fprintf(stderr, format: formatString.constData(), |
42 | currentFilenames.top().constData(), msg.data()); |
43 | } |
44 | } |
45 | |
46 | void Parser::defaultErrorMsg(const Symbol &sym) |
47 | { |
48 | if (sym.lineNum != -1) |
49 | printMsg(formatStringSuffix: "error: Parse error at \"%s\"\n" , msg: sym.lexem().data(), sym); |
50 | else |
51 | printMsg(formatStringSuffix: "error: could not parse file\n" , msg: "" , sym); |
52 | } |
53 | |
54 | void Parser::error(const Symbol &sym) |
55 | { |
56 | defaultErrorMsg(sym); |
57 | exit(EXIT_FAILURE); |
58 | } |
59 | |
60 | void Parser::error(const char *msg) |
61 | { |
62 | if (msg || error_msg) |
63 | printMsg(formatStringSuffix: "error: %s\n" , |
64 | msg: msg ? msg : error_msg, |
65 | sym: index > 0 ? symbol() : Symbol{}); |
66 | else |
67 | defaultErrorMsg(sym: symbol()); |
68 | |
69 | exit(EXIT_FAILURE); |
70 | } |
71 | |
72 | void Parser::warning(const Symbol &sym, QByteArrayView msg) |
73 | { |
74 | if (displayWarnings) |
75 | printMsg(formatStringSuffix: "warning: %s\n" , msg, sym); |
76 | } |
77 | |
78 | void Parser::warning(const char *msg) { |
79 | warning(sym: index > 0 ? symbol() : Symbol{}, msg); |
80 | } |
81 | |
82 | void Parser::note(const char *msg) { |
83 | if (displayNotes && msg) |
84 | printMsg(formatStringSuffix: "note: %s\n" , msg, sym: index > 0 ? symbol() : Symbol{}); |
85 | } |
86 | |
87 | QT_END_NAMESPACE |
88 | |