xref: /llvm-project/flang/lib/Parser/message.cpp (revision cc575dd2cefce3170655a026dbf058a42e1a4330)
1 //===-- lib/Parser/message.cpp --------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "flang/Parser/message.h"
10 #include "flang/Common/idioms.h"
11 #include "flang/Parser/char-set.h"
12 #include "llvm/Support/raw_ostream.h"
13 #include <algorithm>
14 #include <cstdarg>
15 #include <cstddef>
16 #include <cstdio>
17 #include <cstring>
18 #include <string>
19 #include <vector>
20 
21 namespace Fortran::parser {
22 
23 llvm::raw_ostream &operator<<(llvm::raw_ostream &o, const MessageFixedText &t) {
24   std::size_t n{t.text().size()};
25   for (std::size_t j{0}; j < n; ++j) {
26     o << t.text()[j];
27   }
28   return o;
29 }
30 
31 void MessageFormattedText::Format(const MessageFixedText *text, ...) {
32   const char *p{text->text().begin()};
33   std::string asString;
34   if (*text->text().end() != '\0') {
35     // not NUL-terminated
36     asString = text->text().NULTerminatedToString();
37     p = asString.c_str();
38   }
39   va_list ap;
40   va_start(ap, text);
41   int need{vsnprintf(nullptr, 0, p, ap)};
42   CHECK(need >= 0);
43   char *buffer{
44       static_cast<char *>(std::malloc(static_cast<std::size_t>(need) + 1))};
45   CHECK(buffer);
46   va_end(ap);
47   va_start(ap, text);
48   int need2{vsnprintf(buffer, need + 1, p, ap)};
49   CHECK(need2 == need);
50   va_end(ap);
51   string_ = buffer;
52   std::free(buffer);
53   conversions_.clear();
54 }
55 
56 const char *MessageFormattedText::Convert(const std::string &s) {
57   conversions_.emplace_front(s);
58   return conversions_.front().c_str();
59 }
60 
61 const char *MessageFormattedText::Convert(std::string &s) {
62   conversions_.emplace_front(s);
63   return conversions_.front().c_str();
64 }
65 
66 const char *MessageFormattedText::Convert(std::string &&s) {
67   conversions_.emplace_front(std::move(s));
68   return conversions_.front().c_str();
69 }
70 
71 const char *MessageFormattedText::Convert(CharBlock x) {
72   return Convert(x.ToString());
73 }
74 
75 std::string MessageExpectedText::ToString() const {
76   return std::visit(
77       common::visitors{
78           [](CharBlock cb) {
79             return MessageFormattedText("expected '%s'"_err_en_US, cb)
80                 .MoveString();
81           },
82           [](const SetOfChars &set) {
83             SetOfChars expect{set};
84             if (expect.Has('\n')) {
85               expect = expect.Difference('\n');
86               if (expect.empty()) {
87                 return "expected end of line"_err_en_US.text().ToString();
88               } else {
89                 std::string s{expect.ToString()};
90                 if (s.size() == 1) {
91                   return MessageFormattedText(
92                       "expected end of line or '%s'"_err_en_US, s)
93                       .MoveString();
94                 } else {
95                   return MessageFormattedText(
96                       "expected end of line or one of '%s'"_err_en_US, s)
97                       .MoveString();
98                 }
99               }
100             }
101             std::string s{expect.ToString()};
102             if (s.size() != 1) {
103               return MessageFormattedText("expected one of '%s'"_err_en_US, s)
104                   .MoveString();
105             } else {
106               return MessageFormattedText("expected '%s'"_err_en_US, s)
107                   .MoveString();
108             }
109           },
110       },
111       u_);
112 }
113 
114 bool MessageExpectedText::Merge(const MessageExpectedText &that) {
115   return std::visit(common::visitors{
116                         [](SetOfChars &s1, const SetOfChars &s2) {
117                           s1 = s1.Union(s2);
118                           return true;
119                         },
120                         [](const auto &, const auto &) { return false; },
121                     },
122       u_, that.u_);
123 }
124 
125 bool Message::SortBefore(const Message &that) const {
126   // Messages from prescanning have ProvenanceRange values for their locations,
127   // while messages from later phases have CharBlock values, since the
128   // conversion of cooked source stream locations to provenances is not
129   // free and needs to be deferred, and many messages created during parsing
130   // are speculative.  Messages with ProvenanceRange locations are ordered
131   // before others for sorting.
132   return std::visit(
133       common::visitors{
134           [](CharBlock cb1, CharBlock cb2) {
135             return cb1.begin() < cb2.begin();
136           },
137           [](CharBlock, const ProvenanceRange &) { return false; },
138           [](const ProvenanceRange &pr1, const ProvenanceRange &pr2) {
139             return pr1.start() < pr2.start();
140           },
141           [](const ProvenanceRange &, CharBlock) { return true; },
142       },
143       location_, that.location_);
144 }
145 
146 bool Message::IsFatal() const {
147   return std::visit(
148       common::visitors{
149           [](const MessageExpectedText &) { return true; },
150           [](const MessageFixedText &x) { return x.isFatal(); },
151           [](const MessageFormattedText &x) { return x.isFatal(); },
152       },
153       text_);
154 }
155 
156 std::string Message::ToString() const {
157   return std::visit(
158       common::visitors{
159           [](const MessageFixedText &t) {
160             return t.text().NULTerminatedToString();
161           },
162           [](const MessageFormattedText &t) { return t.string(); },
163           [](const MessageExpectedText &e) { return e.ToString(); },
164       },
165       text_);
166 }
167 
168 void Message::ResolveProvenances(const AllCookedSources &allCooked) {
169   if (CharBlock * cb{std::get_if<CharBlock>(&location_)}) {
170     if (std::optional<ProvenanceRange> resolved{
171             allCooked.GetProvenanceRange(*cb)}) {
172       location_ = *resolved;
173     }
174   }
175   if (Message * attachment{attachment_.get()}) {
176     attachment->ResolveProvenances(allCooked);
177   }
178 }
179 
180 std::optional<ProvenanceRange> Message::GetProvenanceRange(
181     const AllCookedSources &allCooked) const {
182   return std::visit(
183       common::visitors{
184           [&](CharBlock cb) { return allCooked.GetProvenanceRange(cb); },
185           [](const ProvenanceRange &pr) { return std::make_optional(pr); },
186       },
187       location_);
188 }
189 
190 void Message::Emit(llvm::raw_ostream &o, const AllCookedSources &allCooked,
191     bool echoSourceLine) const {
192   std::optional<ProvenanceRange> provenanceRange{GetProvenanceRange(allCooked)};
193   std::string text;
194   if (IsFatal()) {
195     text += "error: ";
196   }
197   text += ToString();
198   const AllSources &sources{allCooked.allSources()};
199   sources.EmitMessage(o, provenanceRange, text, echoSourceLine);
200   if (attachmentIsContext_) {
201     for (const Message *context{attachment_.get()}; context;
202          context = context->attachment_.get()) {
203       std::optional<ProvenanceRange> contextProvenance{
204           context->GetProvenanceRange(allCooked)};
205       text = "in the context: ";
206       text += context->ToString();
207       // TODO: don't echo the source lines of a context when it's the
208       // same line (or maybe just never echo source for context)
209       sources.EmitMessage(o, contextProvenance, text,
210           echoSourceLine && contextProvenance != provenanceRange);
211       provenanceRange = contextProvenance;
212     }
213   } else {
214     for (const Message *attachment{attachment_.get()}; attachment;
215          attachment = attachment->attachment_.get()) {
216       sources.EmitMessage(o, attachment->GetProvenanceRange(allCooked),
217           attachment->ToString(), echoSourceLine);
218     }
219   }
220 }
221 
222 bool Message::Merge(const Message &that) {
223   return AtSameLocation(that) &&
224       (!that.attachment_.get() ||
225           attachment_.get() == that.attachment_.get()) &&
226       std::visit(
227           common::visitors{
228               [](MessageExpectedText &e1, const MessageExpectedText &e2) {
229                 return e1.Merge(e2);
230               },
231               [](const auto &, const auto &) { return false; },
232           },
233           text_, that.text_);
234 }
235 
236 Message &Message::Attach(Message *m) {
237   if (!attachment_) {
238     attachment_ = m;
239   } else {
240     attachment_->Attach(m);
241   }
242   return *this;
243 }
244 
245 Message &Message::Attach(std::unique_ptr<Message> &&m) {
246   return Attach(m.release());
247 }
248 
249 bool Message::AtSameLocation(const Message &that) const {
250   return std::visit(
251       common::visitors{
252           [](CharBlock cb1, CharBlock cb2) {
253             return cb1.begin() == cb2.begin();
254           },
255           [](const ProvenanceRange &pr1, const ProvenanceRange &pr2) {
256             return pr1.start() == pr2.start();
257           },
258           [](const auto &, const auto &) { return false; },
259       },
260       location_, that.location_);
261 }
262 
263 bool Messages::Merge(const Message &msg) {
264   if (msg.IsMergeable()) {
265     for (auto &m : messages_) {
266       if (m.Merge(msg)) {
267         return true;
268       }
269     }
270   }
271   return false;
272 }
273 
274 void Messages::Merge(Messages &&that) {
275   if (messages_.empty()) {
276     *this = std::move(that);
277   } else {
278     while (!that.messages_.empty()) {
279       if (Merge(that.messages_.front())) {
280         that.messages_.pop_front();
281       } else {
282         auto next{that.messages_.begin()};
283         ++next;
284         messages_.splice(
285             messages_.end(), that.messages_, that.messages_.begin(), next);
286       }
287     }
288   }
289 }
290 
291 void Messages::Copy(const Messages &that) {
292   for (const Message &m : that.messages_) {
293     Message copy{m};
294     Say(std::move(copy));
295   }
296 }
297 
298 void Messages::ResolveProvenances(const AllCookedSources &allCooked) {
299   for (Message &m : messages_) {
300     m.ResolveProvenances(allCooked);
301   }
302 }
303 
304 void Messages::Emit(llvm::raw_ostream &o, const AllCookedSources &allCooked,
305     bool echoSourceLines) const {
306   std::vector<const Message *> sorted;
307   for (const auto &msg : messages_) {
308     sorted.push_back(&msg);
309   }
310   std::stable_sort(sorted.begin(), sorted.end(),
311       [](const Message *x, const Message *y) { return x->SortBefore(*y); });
312   for (const Message *msg : sorted) {
313     msg->Emit(o, allCooked, echoSourceLines);
314   }
315 }
316 
317 void Messages::AttachTo(Message &msg) {
318   for (Message &m : messages_) {
319     msg.Attach(std::move(m));
320   }
321   messages_.clear();
322 }
323 
324 bool Messages::AnyFatalError() const {
325   for (const auto &msg : messages_) {
326     if (msg.IsFatal()) {
327       return true;
328     }
329   }
330   return false;
331 }
332 } // namespace Fortran::parser
333