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 #ifdef _MSC_VER
42   // Microsoft has a separate function for "positional arguments", which is
43   // used in some messages.
44   int need{_vsprintf_p(nullptr, 0, p, ap)};
45 #else
46   int need{vsnprintf(nullptr, 0, p, ap)};
47 #endif
48 
49   CHECK(need >= 0);
50   char *buffer{
51       static_cast<char *>(std::malloc(static_cast<std::size_t>(need) + 1))};
52   CHECK(buffer);
53   va_end(ap);
54   va_start(ap, text);
55 #ifdef _MSC_VER
56   // Use positional argument variant of printf.
57   int need2{_vsprintf_p(buffer, need + 1, p, ap)};
58 #else
59   int need2{vsnprintf(buffer, need + 1, p, ap)};
60 #endif
61   CHECK(need2 == need);
62   va_end(ap);
63   string_ = buffer;
64   std::free(buffer);
65   conversions_.clear();
66 }
67 
68 const char *MessageFormattedText::Convert(const std::string &s) {
69   conversions_.emplace_front(s);
70   return conversions_.front().c_str();
71 }
72 
73 const char *MessageFormattedText::Convert(std::string &s) {
74   conversions_.emplace_front(s);
75   return conversions_.front().c_str();
76 }
77 
78 const char *MessageFormattedText::Convert(std::string &&s) {
79   conversions_.emplace_front(std::move(s));
80   return conversions_.front().c_str();
81 }
82 
83 const char *MessageFormattedText::Convert(CharBlock x) {
84   return Convert(x.ToString());
85 }
86 
87 std::string MessageExpectedText::ToString() const {
88   return std::visit(
89       common::visitors{
90           [](CharBlock cb) {
91             return MessageFormattedText("expected '%s'"_err_en_US, cb)
92                 .MoveString();
93           },
94           [](const SetOfChars &set) {
95             SetOfChars expect{set};
96             if (expect.Has('\n')) {
97               expect = expect.Difference('\n');
98               if (expect.empty()) {
99                 return "expected end of line"_err_en_US.text().ToString();
100               } else {
101                 std::string s{expect.ToString()};
102                 if (s.size() == 1) {
103                   return MessageFormattedText(
104                       "expected end of line or '%s'"_err_en_US, s)
105                       .MoveString();
106                 } else {
107                   return MessageFormattedText(
108                       "expected end of line or one of '%s'"_err_en_US, s)
109                       .MoveString();
110                 }
111               }
112             }
113             std::string s{expect.ToString()};
114             if (s.size() != 1) {
115               return MessageFormattedText("expected one of '%s'"_err_en_US, s)
116                   .MoveString();
117             } else {
118               return MessageFormattedText("expected '%s'"_err_en_US, s)
119                   .MoveString();
120             }
121           },
122       },
123       u_);
124 }
125 
126 bool MessageExpectedText::Merge(const MessageExpectedText &that) {
127   return std::visit(common::visitors{
128                         [](SetOfChars &s1, const SetOfChars &s2) {
129                           s1 = s1.Union(s2);
130                           return true;
131                         },
132                         [](const auto &, const auto &) { return false; },
133                     },
134       u_, that.u_);
135 }
136 
137 bool Message::SortBefore(const Message &that) const {
138   // Messages from prescanning have ProvenanceRange values for their locations,
139   // while messages from later phases have CharBlock values, since the
140   // conversion of cooked source stream locations to provenances is not
141   // free and needs to be deferred, and many messages created during parsing
142   // are speculative.  Messages with ProvenanceRange locations are ordered
143   // before others for sorting.
144   return std::visit(
145       common::visitors{
146           [](CharBlock cb1, CharBlock cb2) {
147             return cb1.begin() < cb2.begin();
148           },
149           [](CharBlock, const ProvenanceRange &) { return false; },
150           [](const ProvenanceRange &pr1, const ProvenanceRange &pr2) {
151             return pr1.start() < pr2.start();
152           },
153           [](const ProvenanceRange &, CharBlock) { return true; },
154       },
155       location_, that.location_);
156 }
157 
158 bool Message::IsFatal() const { return severity() == Severity::Error; }
159 
160 Severity Message::severity() const {
161   return std::visit(
162       common::visitors{
163           [](const MessageExpectedText &) { return Severity::Error; },
164           [](const MessageFixedText &x) { return x.severity(); },
165           [](const MessageFormattedText &x) { return x.severity(); },
166       },
167       text_);
168 }
169 
170 std::string Message::ToString() const {
171   return std::visit(
172       common::visitors{
173           [](const MessageFixedText &t) {
174             return t.text().NULTerminatedToString();
175           },
176           [](const MessageFormattedText &t) { return t.string(); },
177           [](const MessageExpectedText &e) { return e.ToString(); },
178       },
179       text_);
180 }
181 
182 void Message::ResolveProvenances(const AllCookedSources &allCooked) {
183   if (CharBlock * cb{std::get_if<CharBlock>(&location_)}) {
184     if (std::optional<ProvenanceRange> resolved{
185             allCooked.GetProvenanceRange(*cb)}) {
186       location_ = *resolved;
187     }
188   }
189   if (Message * attachment{attachment_.get()}) {
190     attachment->ResolveProvenances(allCooked);
191   }
192 }
193 
194 std::optional<ProvenanceRange> Message::GetProvenanceRange(
195     const AllCookedSources &allCooked) const {
196   return std::visit(
197       common::visitors{
198           [&](CharBlock cb) { return allCooked.GetProvenanceRange(cb); },
199           [](const ProvenanceRange &pr) { return std::make_optional(pr); },
200       },
201       location_);
202 }
203 
204 void Message::Emit(llvm::raw_ostream &o, const AllCookedSources &allCooked,
205     bool echoSourceLine) const {
206   std::optional<ProvenanceRange> provenanceRange{GetProvenanceRange(allCooked)};
207   std::string text;
208   switch (severity()) {
209   case Severity::Error:
210     text = "error: ";
211     break;
212   case Severity::Warning:
213     text = "warning: ";
214     break;
215   case Severity::Portability:
216     text = "portability: ";
217     break;
218   case Severity::None:
219     break;
220   }
221   text += ToString();
222   const AllSources &sources{allCooked.allSources()};
223   sources.EmitMessage(o, provenanceRange, text, echoSourceLine);
224   bool isContext{attachmentIsContext_};
225   for (const Message *attachment{attachment_.get()}; attachment;
226        attachment = attachment->attachment_.get()) {
227     text.clear();
228     if (isContext) {
229       text = "in the context: ";
230     }
231     text += attachment->ToString();
232     sources.EmitMessage(
233         o, attachment->GetProvenanceRange(allCooked), text, echoSourceLine);
234     isContext = attachment->attachmentIsContext_;
235   }
236 }
237 
238 // Messages are equal if they're for the same location and text, and the user
239 // visible aspects of their attachments are the same
240 bool Message::operator==(const Message &that) const {
241   if (!AtSameLocation(that) || ToString() != that.ToString()) {
242     return false;
243   }
244   const Message *thatAttachment{that.attachment_.get()};
245   for (const Message *attachment{attachment_.get()}; attachment;
246        attachment = attachment->attachment_.get()) {
247     if (!thatAttachment ||
248         attachment->attachmentIsContext_ !=
249             thatAttachment->attachmentIsContext_ ||
250         *attachment != *thatAttachment) {
251       return false;
252     }
253     thatAttachment = thatAttachment->attachment_.get();
254   }
255   return true;
256 }
257 
258 bool Message::Merge(const Message &that) {
259   return AtSameLocation(that) &&
260       (!that.attachment_.get() ||
261           attachment_.get() == that.attachment_.get()) &&
262       std::visit(
263           common::visitors{
264               [](MessageExpectedText &e1, const MessageExpectedText &e2) {
265                 return e1.Merge(e2);
266               },
267               [](const auto &, const auto &) { return false; },
268           },
269           text_, that.text_);
270 }
271 
272 Message &Message::Attach(Message *m) {
273   if (!attachment_) {
274     attachment_ = m;
275   } else {
276     if (attachment_->references() > 1) {
277       // Don't attach to a shared context attachment; copy it first.
278       attachment_ = new Message{*attachment_};
279     }
280     attachment_->Attach(m);
281   }
282   return *this;
283 }
284 
285 Message &Message::Attach(std::unique_ptr<Message> &&m) {
286   return Attach(m.release());
287 }
288 
289 bool Message::AtSameLocation(const Message &that) const {
290   return std::visit(
291       common::visitors{
292           [](CharBlock cb1, CharBlock cb2) {
293             return cb1.begin() == cb2.begin();
294           },
295           [](const ProvenanceRange &pr1, const ProvenanceRange &pr2) {
296             return pr1.start() == pr2.start();
297           },
298           [](const auto &, const auto &) { return false; },
299       },
300       location_, that.location_);
301 }
302 
303 bool Messages::Merge(const Message &msg) {
304   if (msg.IsMergeable()) {
305     for (auto &m : messages_) {
306       if (m.Merge(msg)) {
307         return true;
308       }
309     }
310   }
311   return false;
312 }
313 
314 void Messages::Merge(Messages &&that) {
315   if (messages_.empty()) {
316     *this = std::move(that);
317   } else {
318     while (!that.messages_.empty()) {
319       if (Merge(that.messages_.front())) {
320         that.messages_.pop_front();
321       } else {
322         auto next{that.messages_.begin()};
323         ++next;
324         messages_.splice(
325             messages_.end(), that.messages_, that.messages_.begin(), next);
326       }
327     }
328   }
329 }
330 
331 void Messages::Copy(const Messages &that) {
332   for (const Message &m : that.messages_) {
333     Message copy{m};
334     Say(std::move(copy));
335   }
336 }
337 
338 void Messages::ResolveProvenances(const AllCookedSources &allCooked) {
339   for (Message &m : messages_) {
340     m.ResolveProvenances(allCooked);
341   }
342 }
343 
344 void Messages::Emit(llvm::raw_ostream &o, const AllCookedSources &allCooked,
345     bool echoSourceLines) const {
346   std::vector<const Message *> sorted;
347   for (const auto &msg : messages_) {
348     sorted.push_back(&msg);
349   }
350   std::stable_sort(sorted.begin(), sorted.end(),
351       [](const Message *x, const Message *y) { return x->SortBefore(*y); });
352   const Message *lastMsg{nullptr};
353   for (const Message *msg : sorted) {
354     if (lastMsg && *msg == *lastMsg) {
355       // Don't emit two identical messages for the same location
356       continue;
357     }
358     msg->Emit(o, allCooked, echoSourceLines);
359     lastMsg = msg;
360   }
361 }
362 
363 void Messages::AttachTo(Message &msg) {
364   for (Message &m : messages_) {
365     msg.Attach(std::move(m));
366   }
367   messages_.clear();
368 }
369 
370 bool Messages::AnyFatalError() const {
371   for (const auto &msg : messages_) {
372     if (msg.IsFatal()) {
373       return true;
374     }
375   }
376   return false;
377 }
378 } // namespace Fortran::parser
379