xref: /llvm-project/flang/lib/Parser/message.cpp (revision 35249cb7b1e82147ef08de12bdf34a29d8c58d53)
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 {
159   return std::visit(
160       common::visitors{
161           [](const MessageExpectedText &) { return true; },
162           [](const MessageFixedText &x) { return x.isFatal(); },
163           [](const MessageFormattedText &x) { return x.isFatal(); },
164       },
165       text_);
166 }
167 
168 std::string Message::ToString() const {
169   return std::visit(
170       common::visitors{
171           [](const MessageFixedText &t) {
172             return t.text().NULTerminatedToString();
173           },
174           [](const MessageFormattedText &t) { return t.string(); },
175           [](const MessageExpectedText &e) { return e.ToString(); },
176       },
177       text_);
178 }
179 
180 void Message::ResolveProvenances(const AllCookedSources &allCooked) {
181   if (CharBlock * cb{std::get_if<CharBlock>(&location_)}) {
182     if (std::optional<ProvenanceRange> resolved{
183             allCooked.GetProvenanceRange(*cb)}) {
184       location_ = *resolved;
185     }
186   }
187   if (Message * attachment{attachment_.get()}) {
188     attachment->ResolveProvenances(allCooked);
189   }
190 }
191 
192 std::optional<ProvenanceRange> Message::GetProvenanceRange(
193     const AllCookedSources &allCooked) const {
194   return std::visit(
195       common::visitors{
196           [&](CharBlock cb) { return allCooked.GetProvenanceRange(cb); },
197           [](const ProvenanceRange &pr) { return std::make_optional(pr); },
198       },
199       location_);
200 }
201 
202 void Message::Emit(llvm::raw_ostream &o, const AllCookedSources &allCooked,
203     bool echoSourceLine) const {
204   std::optional<ProvenanceRange> provenanceRange{GetProvenanceRange(allCooked)};
205   std::string text;
206   if (IsFatal()) {
207     text += "error: ";
208   }
209   text += ToString();
210   const AllSources &sources{allCooked.allSources()};
211   sources.EmitMessage(o, provenanceRange, text, echoSourceLine);
212   bool isContext{attachmentIsContext_};
213   for (const Message *attachment{attachment_.get()}; attachment;
214        attachment = attachment->attachment_.get()) {
215     text.clear();
216     if (isContext) {
217       text = "in the context: ";
218     }
219     text += attachment->ToString();
220     sources.EmitMessage(
221         o, attachment->GetProvenanceRange(allCooked), text, echoSourceLine);
222     isContext = attachment->attachmentIsContext_;
223   }
224 }
225 
226 // Messages are equal if they're for the same location and text, and the user
227 // visible aspects of their attachments are the same
228 bool Message::operator==(const Message &that) const {
229   if (!AtSameLocation(that) || ToString() != that.ToString()) {
230     return false;
231   }
232   const Message *thatAttachment{that.attachment_.get()};
233   for (const Message *attachment{attachment_.get()}; attachment;
234        attachment = attachment->attachment_.get()) {
235     if (!thatAttachment ||
236         attachment->attachmentIsContext_ !=
237             thatAttachment->attachmentIsContext_ ||
238         *attachment != *thatAttachment) {
239       return false;
240     }
241     thatAttachment = thatAttachment->attachment_.get();
242   }
243   return true;
244 }
245 
246 bool Message::Merge(const Message &that) {
247   return AtSameLocation(that) &&
248       (!that.attachment_.get() ||
249           attachment_.get() == that.attachment_.get()) &&
250       std::visit(
251           common::visitors{
252               [](MessageExpectedText &e1, const MessageExpectedText &e2) {
253                 return e1.Merge(e2);
254               },
255               [](const auto &, const auto &) { return false; },
256           },
257           text_, that.text_);
258 }
259 
260 Message &Message::Attach(Message *m) {
261   if (!attachment_) {
262     attachment_ = m;
263   } else {
264     if (attachment_->references() > 1) {
265       // Don't attach to a shared context attachment; copy it first.
266       attachment_ = new Message{*attachment_};
267     }
268     attachment_->Attach(m);
269   }
270   return *this;
271 }
272 
273 Message &Message::Attach(std::unique_ptr<Message> &&m) {
274   return Attach(m.release());
275 }
276 
277 bool Message::AtSameLocation(const Message &that) const {
278   return std::visit(
279       common::visitors{
280           [](CharBlock cb1, CharBlock cb2) {
281             return cb1.begin() == cb2.begin();
282           },
283           [](const ProvenanceRange &pr1, const ProvenanceRange &pr2) {
284             return pr1.start() == pr2.start();
285           },
286           [](const auto &, const auto &) { return false; },
287       },
288       location_, that.location_);
289 }
290 
291 bool Messages::Merge(const Message &msg) {
292   if (msg.IsMergeable()) {
293     for (auto &m : messages_) {
294       if (m.Merge(msg)) {
295         return true;
296       }
297     }
298   }
299   return false;
300 }
301 
302 void Messages::Merge(Messages &&that) {
303   if (messages_.empty()) {
304     *this = std::move(that);
305   } else {
306     while (!that.messages_.empty()) {
307       if (Merge(that.messages_.front())) {
308         that.messages_.pop_front();
309       } else {
310         auto next{that.messages_.begin()};
311         ++next;
312         messages_.splice(
313             messages_.end(), that.messages_, that.messages_.begin(), next);
314       }
315     }
316   }
317 }
318 
319 void Messages::Copy(const Messages &that) {
320   for (const Message &m : that.messages_) {
321     Message copy{m};
322     Say(std::move(copy));
323   }
324 }
325 
326 void Messages::ResolveProvenances(const AllCookedSources &allCooked) {
327   for (Message &m : messages_) {
328     m.ResolveProvenances(allCooked);
329   }
330 }
331 
332 void Messages::Emit(llvm::raw_ostream &o, const AllCookedSources &allCooked,
333     bool echoSourceLines) const {
334   std::vector<const Message *> sorted;
335   for (const auto &msg : messages_) {
336     sorted.push_back(&msg);
337   }
338   std::stable_sort(sorted.begin(), sorted.end(),
339       [](const Message *x, const Message *y) { return x->SortBefore(*y); });
340   const Message *lastMsg{nullptr};
341   for (const Message *msg : sorted) {
342     if (lastMsg && *msg == *lastMsg) {
343       // Don't emit two identical messages for the same location
344       continue;
345     }
346     msg->Emit(o, allCooked, echoSourceLines);
347     lastMsg = msg;
348   }
349 }
350 
351 void Messages::AttachTo(Message &msg) {
352   for (Message &m : messages_) {
353     msg.Attach(std::move(m));
354   }
355   messages_.clear();
356 }
357 
358 bool Messages::AnyFatalError() const {
359   for (const auto &msg : messages_) {
360     if (msg.IsFatal()) {
361       return true;
362     }
363   }
364   return false;
365 }
366 } // namespace Fortran::parser
367