10b57cec5SDimitry Andric //===- SourceMgr.cpp - Manager for Simple Source Buffers & Diagnostics ----===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file implements the SourceMgr class.  This class is used as a simple
100b57cec5SDimitry Andric // substrate for diagnostics, #include handling, and other low level things for
110b57cec5SDimitry Andric // simple parsers.
120b57cec5SDimitry Andric //
130b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
140b57cec5SDimitry Andric 
150b57cec5SDimitry Andric #include "llvm/Support/SourceMgr.h"
160b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
170b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
18bdd1243dSDimitry Andric #include "llvm/ADT/SmallString.h"
190b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
200b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
210b57cec5SDimitry Andric #include "llvm/ADT/Twine.h"
220b57cec5SDimitry Andric #include "llvm/Support/ErrorOr.h"
230b57cec5SDimitry Andric #include "llvm/Support/Locale.h"
240b57cec5SDimitry Andric #include "llvm/Support/MemoryBuffer.h"
250b57cec5SDimitry Andric #include "llvm/Support/Path.h"
260b57cec5SDimitry Andric #include "llvm/Support/SMLoc.h"
270b57cec5SDimitry Andric #include "llvm/Support/WithColor.h"
280b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
290b57cec5SDimitry Andric #include <algorithm>
300b57cec5SDimitry Andric #include <cassert>
310b57cec5SDimitry Andric #include <cstddef>
320b57cec5SDimitry Andric #include <limits>
330b57cec5SDimitry Andric #include <memory>
340b57cec5SDimitry Andric #include <string>
350b57cec5SDimitry Andric #include <utility>
360b57cec5SDimitry Andric 
370b57cec5SDimitry Andric using namespace llvm;
380b57cec5SDimitry Andric 
390b57cec5SDimitry Andric static const size_t TabStop = 8;
400b57cec5SDimitry Andric 
AddIncludeFile(const std::string & Filename,SMLoc IncludeLoc,std::string & IncludedFile)410b57cec5SDimitry Andric unsigned SourceMgr::AddIncludeFile(const std::string &Filename,
420b57cec5SDimitry Andric                                    SMLoc IncludeLoc,
430b57cec5SDimitry Andric                                    std::string &IncludedFile) {
4481ad6265SDimitry Andric   ErrorOr<std::unique_ptr<MemoryBuffer>> NewBufOrErr =
4581ad6265SDimitry Andric       OpenIncludeFile(Filename, IncludedFile);
4681ad6265SDimitry Andric   if (!NewBufOrErr)
4781ad6265SDimitry Andric     return 0;
4881ad6265SDimitry Andric 
4981ad6265SDimitry Andric   return AddNewSourceBuffer(std::move(*NewBufOrErr), IncludeLoc);
5081ad6265SDimitry Andric }
5181ad6265SDimitry Andric 
5281ad6265SDimitry Andric ErrorOr<std::unique_ptr<MemoryBuffer>>
OpenIncludeFile(const std::string & Filename,std::string & IncludedFile)5381ad6265SDimitry Andric SourceMgr::OpenIncludeFile(const std::string &Filename,
5481ad6265SDimitry Andric                            std::string &IncludedFile) {
550b57cec5SDimitry Andric   ErrorOr<std::unique_ptr<MemoryBuffer>> NewBufOrErr =
56bdd1243dSDimitry Andric       MemoryBuffer::getFile(Filename);
570b57cec5SDimitry Andric 
58bdd1243dSDimitry Andric   SmallString<64> Buffer(Filename);
590b57cec5SDimitry Andric   // If the file didn't exist directly, see if it's in an include path.
600b57cec5SDimitry Andric   for (unsigned i = 0, e = IncludeDirectories.size(); i != e && !NewBufOrErr;
610b57cec5SDimitry Andric        ++i) {
62bdd1243dSDimitry Andric     Buffer = IncludeDirectories[i];
63bdd1243dSDimitry Andric     sys::path::append(Buffer, Filename);
64bdd1243dSDimitry Andric     NewBufOrErr = MemoryBuffer::getFile(Buffer);
650b57cec5SDimitry Andric   }
660b57cec5SDimitry Andric 
67bdd1243dSDimitry Andric   if (NewBufOrErr)
68bdd1243dSDimitry Andric     IncludedFile = static_cast<std::string>(Buffer);
69bdd1243dSDimitry Andric 
7081ad6265SDimitry Andric   return NewBufOrErr;
710b57cec5SDimitry Andric }
720b57cec5SDimitry Andric 
FindBufferContainingLoc(SMLoc Loc) const730b57cec5SDimitry Andric unsigned SourceMgr::FindBufferContainingLoc(SMLoc Loc) const {
740b57cec5SDimitry Andric   for (unsigned i = 0, e = Buffers.size(); i != e; ++i)
750b57cec5SDimitry Andric     if (Loc.getPointer() >= Buffers[i].Buffer->getBufferStart() &&
760b57cec5SDimitry Andric         // Use <= here so that a pointer to the null at the end of the buffer
770b57cec5SDimitry Andric         // is included as part of the buffer.
780b57cec5SDimitry Andric         Loc.getPointer() <= Buffers[i].Buffer->getBufferEnd())
790b57cec5SDimitry Andric       return i + 1;
800b57cec5SDimitry Andric   return 0;
810b57cec5SDimitry Andric }
820b57cec5SDimitry Andric 
830b57cec5SDimitry Andric template <typename T>
GetOrCreateOffsetCache(void * & OffsetCache,MemoryBuffer * Buffer)845ffd83dbSDimitry Andric static std::vector<T> &GetOrCreateOffsetCache(void *&OffsetCache,
855ffd83dbSDimitry Andric                                               MemoryBuffer *Buffer) {
865ffd83dbSDimitry Andric   if (OffsetCache)
875ffd83dbSDimitry Andric     return *static_cast<std::vector<T> *>(OffsetCache);
880b57cec5SDimitry Andric 
895ffd83dbSDimitry Andric   // Lazily fill in the offset cache.
905ffd83dbSDimitry Andric   auto *Offsets = new std::vector<T>();
910b57cec5SDimitry Andric   size_t Sz = Buffer->getBufferSize();
920b57cec5SDimitry Andric   assert(Sz <= std::numeric_limits<T>::max());
930b57cec5SDimitry Andric   StringRef S = Buffer->getBuffer();
940b57cec5SDimitry Andric   for (size_t N = 0; N < Sz; ++N) {
955ffd83dbSDimitry Andric     if (S[N] == '\n')
960b57cec5SDimitry Andric       Offsets->push_back(static_cast<T>(N));
970b57cec5SDimitry Andric   }
985ffd83dbSDimitry Andric 
995ffd83dbSDimitry Andric   OffsetCache = Offsets;
1005ffd83dbSDimitry Andric   return *Offsets;
1010b57cec5SDimitry Andric }
1025ffd83dbSDimitry Andric 
1035ffd83dbSDimitry Andric template <typename T>
getLineNumberSpecialized(const char * Ptr) const1045ffd83dbSDimitry Andric unsigned SourceMgr::SrcBuffer::getLineNumberSpecialized(const char *Ptr) const {
1055ffd83dbSDimitry Andric   std::vector<T> &Offsets =
1065ffd83dbSDimitry Andric       GetOrCreateOffsetCache<T>(OffsetCache, Buffer.get());
1070b57cec5SDimitry Andric 
1080b57cec5SDimitry Andric   const char *BufStart = Buffer->getBufferStart();
1090b57cec5SDimitry Andric   assert(Ptr >= BufStart && Ptr <= Buffer->getBufferEnd());
1100b57cec5SDimitry Andric   ptrdiff_t PtrDiff = Ptr - BufStart;
1115ffd83dbSDimitry Andric   assert(PtrDiff >= 0 &&
1125ffd83dbSDimitry Andric          static_cast<size_t>(PtrDiff) <= std::numeric_limits<T>::max());
1130b57cec5SDimitry Andric   T PtrOffset = static_cast<T>(PtrDiff);
1140b57cec5SDimitry Andric 
1150b57cec5SDimitry Andric   // llvm::lower_bound gives the number of EOL before PtrOffset. Add 1 to get
1160b57cec5SDimitry Andric   // the line number.
1175ffd83dbSDimitry Andric   return llvm::lower_bound(Offsets, PtrOffset) - Offsets.begin() + 1;
1185ffd83dbSDimitry Andric }
1195ffd83dbSDimitry Andric 
1205f757f3fSDimitry Andric /// Look up a given \p Ptr in the buffer, determining which line it came
1215ffd83dbSDimitry Andric /// from.
getLineNumber(const char * Ptr) const1225ffd83dbSDimitry Andric unsigned SourceMgr::SrcBuffer::getLineNumber(const char *Ptr) const {
1235ffd83dbSDimitry Andric   size_t Sz = Buffer->getBufferSize();
1245ffd83dbSDimitry Andric   if (Sz <= std::numeric_limits<uint8_t>::max())
1255ffd83dbSDimitry Andric     return getLineNumberSpecialized<uint8_t>(Ptr);
1265ffd83dbSDimitry Andric   else if (Sz <= std::numeric_limits<uint16_t>::max())
1275ffd83dbSDimitry Andric     return getLineNumberSpecialized<uint16_t>(Ptr);
1285ffd83dbSDimitry Andric   else if (Sz <= std::numeric_limits<uint32_t>::max())
1295ffd83dbSDimitry Andric     return getLineNumberSpecialized<uint32_t>(Ptr);
1305ffd83dbSDimitry Andric   else
1315ffd83dbSDimitry Andric     return getLineNumberSpecialized<uint64_t>(Ptr);
1325ffd83dbSDimitry Andric }
1335ffd83dbSDimitry Andric 
1345ffd83dbSDimitry Andric template <typename T>
getPointerForLineNumberSpecialized(unsigned LineNo) const1355ffd83dbSDimitry Andric const char *SourceMgr::SrcBuffer::getPointerForLineNumberSpecialized(
1365ffd83dbSDimitry Andric     unsigned LineNo) const {
1375ffd83dbSDimitry Andric   std::vector<T> &Offsets =
1385ffd83dbSDimitry Andric       GetOrCreateOffsetCache<T>(OffsetCache, Buffer.get());
1395ffd83dbSDimitry Andric 
1405ffd83dbSDimitry Andric   // We start counting line and column numbers from 1.
1415ffd83dbSDimitry Andric   if (LineNo != 0)
1425ffd83dbSDimitry Andric     --LineNo;
1435ffd83dbSDimitry Andric 
1445ffd83dbSDimitry Andric   const char *BufStart = Buffer->getBufferStart();
1455ffd83dbSDimitry Andric 
1465ffd83dbSDimitry Andric   // The offset cache contains the location of the \n for the specified line,
1475ffd83dbSDimitry Andric   // we want the start of the line.  As such, we look for the previous entry.
1485ffd83dbSDimitry Andric   if (LineNo == 0)
1495ffd83dbSDimitry Andric     return BufStart;
1505ffd83dbSDimitry Andric   if (LineNo > Offsets.size())
1515ffd83dbSDimitry Andric     return nullptr;
1525ffd83dbSDimitry Andric   return BufStart + Offsets[LineNo - 1] + 1;
1535ffd83dbSDimitry Andric }
1545ffd83dbSDimitry Andric 
1555ffd83dbSDimitry Andric /// Return a pointer to the first character of the specified line number or
1565ffd83dbSDimitry Andric /// null if the line number is invalid.
1575ffd83dbSDimitry Andric const char *
getPointerForLineNumber(unsigned LineNo) const1585ffd83dbSDimitry Andric SourceMgr::SrcBuffer::getPointerForLineNumber(unsigned LineNo) const {
1595ffd83dbSDimitry Andric   size_t Sz = Buffer->getBufferSize();
1605ffd83dbSDimitry Andric   if (Sz <= std::numeric_limits<uint8_t>::max())
1615ffd83dbSDimitry Andric     return getPointerForLineNumberSpecialized<uint8_t>(LineNo);
1625ffd83dbSDimitry Andric   else if (Sz <= std::numeric_limits<uint16_t>::max())
1635ffd83dbSDimitry Andric     return getPointerForLineNumberSpecialized<uint16_t>(LineNo);
1645ffd83dbSDimitry Andric   else if (Sz <= std::numeric_limits<uint32_t>::max())
1655ffd83dbSDimitry Andric     return getPointerForLineNumberSpecialized<uint32_t>(LineNo);
1665ffd83dbSDimitry Andric   else
1675ffd83dbSDimitry Andric     return getPointerForLineNumberSpecialized<uint64_t>(LineNo);
1680b57cec5SDimitry Andric }
1690b57cec5SDimitry Andric 
SrcBuffer(SourceMgr::SrcBuffer && Other)1700b57cec5SDimitry Andric SourceMgr::SrcBuffer::SrcBuffer(SourceMgr::SrcBuffer &&Other)
1715ffd83dbSDimitry Andric     : Buffer(std::move(Other.Buffer)), OffsetCache(Other.OffsetCache),
1720b57cec5SDimitry Andric       IncludeLoc(Other.IncludeLoc) {
1730b57cec5SDimitry Andric   Other.OffsetCache = nullptr;
1740b57cec5SDimitry Andric }
1750b57cec5SDimitry Andric 
~SrcBuffer()1760b57cec5SDimitry Andric SourceMgr::SrcBuffer::~SrcBuffer() {
1775ffd83dbSDimitry Andric   if (OffsetCache) {
1785ffd83dbSDimitry Andric     size_t Sz = Buffer->getBufferSize();
1795ffd83dbSDimitry Andric     if (Sz <= std::numeric_limits<uint8_t>::max())
1805ffd83dbSDimitry Andric       delete static_cast<std::vector<uint8_t> *>(OffsetCache);
1815ffd83dbSDimitry Andric     else if (Sz <= std::numeric_limits<uint16_t>::max())
1825ffd83dbSDimitry Andric       delete static_cast<std::vector<uint16_t> *>(OffsetCache);
1835ffd83dbSDimitry Andric     else if (Sz <= std::numeric_limits<uint32_t>::max())
1845ffd83dbSDimitry Andric       delete static_cast<std::vector<uint32_t> *>(OffsetCache);
1850b57cec5SDimitry Andric     else
1865ffd83dbSDimitry Andric       delete static_cast<std::vector<uint64_t> *>(OffsetCache);
1870b57cec5SDimitry Andric     OffsetCache = nullptr;
1880b57cec5SDimitry Andric   }
1890b57cec5SDimitry Andric }
1900b57cec5SDimitry Andric 
1910b57cec5SDimitry Andric std::pair<unsigned, unsigned>
getLineAndColumn(SMLoc Loc,unsigned BufferID) const1920b57cec5SDimitry Andric SourceMgr::getLineAndColumn(SMLoc Loc, unsigned BufferID) const {
1930b57cec5SDimitry Andric   if (!BufferID)
1940b57cec5SDimitry Andric     BufferID = FindBufferContainingLoc(Loc);
195e8d8bef9SDimitry Andric   assert(BufferID && "Invalid location!");
1960b57cec5SDimitry Andric 
1970b57cec5SDimitry Andric   auto &SB = getBufferInfo(BufferID);
1980b57cec5SDimitry Andric   const char *Ptr = Loc.getPointer();
1990b57cec5SDimitry Andric 
2005ffd83dbSDimitry Andric   unsigned LineNo = SB.getLineNumber(Ptr);
2010b57cec5SDimitry Andric   const char *BufStart = SB.Buffer->getBufferStart();
2020b57cec5SDimitry Andric   size_t NewlineOffs = StringRef(BufStart, Ptr - BufStart).find_last_of("\n\r");
2035ffd83dbSDimitry Andric   if (NewlineOffs == StringRef::npos)
2045ffd83dbSDimitry Andric     NewlineOffs = ~(size_t)0;
2050b57cec5SDimitry Andric   return std::make_pair(LineNo, Ptr - BufStart - NewlineOffs);
2060b57cec5SDimitry Andric }
2070b57cec5SDimitry Andric 
208e8d8bef9SDimitry Andric // FIXME: Note that the formatting of source locations is spread between
209e8d8bef9SDimitry Andric // multiple functions, some in SourceMgr and some in SMDiagnostic. A better
210e8d8bef9SDimitry Andric // solution would be a general-purpose source location formatter
211e8d8bef9SDimitry Andric // in one of those two classes, or possibly in SMLoc.
212e8d8bef9SDimitry Andric 
213e8d8bef9SDimitry Andric /// Get a string with the source location formatted in the standard
214e8d8bef9SDimitry Andric /// style, but without the line offset. If \p IncludePath is true, the path
215e8d8bef9SDimitry Andric /// is included. If false, only the file name and extension are included.
getFormattedLocationNoOffset(SMLoc Loc,bool IncludePath) const216e8d8bef9SDimitry Andric std::string SourceMgr::getFormattedLocationNoOffset(SMLoc Loc,
217e8d8bef9SDimitry Andric                                                     bool IncludePath) const {
218e8d8bef9SDimitry Andric   auto BufferID = FindBufferContainingLoc(Loc);
219e8d8bef9SDimitry Andric   assert(BufferID && "Invalid location!");
220e8d8bef9SDimitry Andric   auto FileSpec = getBufferInfo(BufferID).Buffer->getBufferIdentifier();
221e8d8bef9SDimitry Andric 
222e8d8bef9SDimitry Andric   if (IncludePath) {
223e8d8bef9SDimitry Andric     return FileSpec.str() + ":" + std::to_string(FindLineNumber(Loc, BufferID));
224e8d8bef9SDimitry Andric   } else {
225e8d8bef9SDimitry Andric     auto I = FileSpec.find_last_of("/\\");
226e8d8bef9SDimitry Andric     I = (I == FileSpec.size()) ? 0 : (I + 1);
227e8d8bef9SDimitry Andric     return FileSpec.substr(I).str() + ":" +
228e8d8bef9SDimitry Andric            std::to_string(FindLineNumber(Loc, BufferID));
229e8d8bef9SDimitry Andric   }
230e8d8bef9SDimitry Andric }
231e8d8bef9SDimitry Andric 
2325ffd83dbSDimitry Andric /// Given a line and column number in a mapped buffer, turn it into an SMLoc.
2335ffd83dbSDimitry Andric /// This will return a null SMLoc if the line/column location is invalid.
FindLocForLineAndColumn(unsigned BufferID,unsigned LineNo,unsigned ColNo)2345ffd83dbSDimitry Andric SMLoc SourceMgr::FindLocForLineAndColumn(unsigned BufferID, unsigned LineNo,
2355ffd83dbSDimitry Andric                                          unsigned ColNo) {
2365ffd83dbSDimitry Andric   auto &SB = getBufferInfo(BufferID);
2375ffd83dbSDimitry Andric   const char *Ptr = SB.getPointerForLineNumber(LineNo);
2385ffd83dbSDimitry Andric   if (!Ptr)
2395ffd83dbSDimitry Andric     return SMLoc();
2405ffd83dbSDimitry Andric 
2415ffd83dbSDimitry Andric   // We start counting line and column numbers from 1.
2425ffd83dbSDimitry Andric   if (ColNo != 0)
2435ffd83dbSDimitry Andric     --ColNo;
2445ffd83dbSDimitry Andric 
2455ffd83dbSDimitry Andric   // If we have a column number, validate it.
2465ffd83dbSDimitry Andric   if (ColNo) {
2475ffd83dbSDimitry Andric     // Make sure the location is within the current line.
2485ffd83dbSDimitry Andric     if (Ptr + ColNo > SB.Buffer->getBufferEnd())
2495ffd83dbSDimitry Andric       return SMLoc();
2505ffd83dbSDimitry Andric 
2515ffd83dbSDimitry Andric     // Make sure there is no newline in the way.
2525ffd83dbSDimitry Andric     if (StringRef(Ptr, ColNo).find_first_of("\n\r") != StringRef::npos)
2535ffd83dbSDimitry Andric       return SMLoc();
2545ffd83dbSDimitry Andric 
2555ffd83dbSDimitry Andric     Ptr += ColNo;
2565ffd83dbSDimitry Andric   }
2575ffd83dbSDimitry Andric 
2585ffd83dbSDimitry Andric   return SMLoc::getFromPointer(Ptr);
2595ffd83dbSDimitry Andric }
2605ffd83dbSDimitry Andric 
PrintIncludeStack(SMLoc IncludeLoc,raw_ostream & OS) const2610b57cec5SDimitry Andric void SourceMgr::PrintIncludeStack(SMLoc IncludeLoc, raw_ostream &OS) const {
2625ffd83dbSDimitry Andric   if (IncludeLoc == SMLoc())
2635ffd83dbSDimitry Andric     return; // Top of stack.
2640b57cec5SDimitry Andric 
2650b57cec5SDimitry Andric   unsigned CurBuf = FindBufferContainingLoc(IncludeLoc);
2660b57cec5SDimitry Andric   assert(CurBuf && "Invalid or unspecified location!");
2670b57cec5SDimitry Andric 
2680b57cec5SDimitry Andric   PrintIncludeStack(getBufferInfo(CurBuf).IncludeLoc, OS);
2690b57cec5SDimitry Andric 
2705ffd83dbSDimitry Andric   OS << "Included from " << getBufferInfo(CurBuf).Buffer->getBufferIdentifier()
2710b57cec5SDimitry Andric      << ":" << FindLineNumber(IncludeLoc, CurBuf) << ":\n";
2720b57cec5SDimitry Andric }
2730b57cec5SDimitry Andric 
GetMessage(SMLoc Loc,SourceMgr::DiagKind Kind,const Twine & Msg,ArrayRef<SMRange> Ranges,ArrayRef<SMFixIt> FixIts) const2740b57cec5SDimitry Andric SMDiagnostic SourceMgr::GetMessage(SMLoc Loc, SourceMgr::DiagKind Kind,
2755ffd83dbSDimitry Andric                                    const Twine &Msg, ArrayRef<SMRange> Ranges,
2760b57cec5SDimitry Andric                                    ArrayRef<SMFixIt> FixIts) const {
2770b57cec5SDimitry Andric   // First thing to do: find the current buffer containing the specified
2780b57cec5SDimitry Andric   // location to pull out the source line.
2790b57cec5SDimitry Andric   SmallVector<std::pair<unsigned, unsigned>, 4> ColRanges;
2800b57cec5SDimitry Andric   std::pair<unsigned, unsigned> LineAndCol;
2810b57cec5SDimitry Andric   StringRef BufferID = "<unknown>";
282e8d8bef9SDimitry Andric   StringRef LineStr;
2830b57cec5SDimitry Andric 
2840b57cec5SDimitry Andric   if (Loc.isValid()) {
2850b57cec5SDimitry Andric     unsigned CurBuf = FindBufferContainingLoc(Loc);
2860b57cec5SDimitry Andric     assert(CurBuf && "Invalid or unspecified location!");
2870b57cec5SDimitry Andric 
2880b57cec5SDimitry Andric     const MemoryBuffer *CurMB = getMemoryBuffer(CurBuf);
2890b57cec5SDimitry Andric     BufferID = CurMB->getBufferIdentifier();
2900b57cec5SDimitry Andric 
2910b57cec5SDimitry Andric     // Scan backward to find the start of the line.
2920b57cec5SDimitry Andric     const char *LineStart = Loc.getPointer();
2930b57cec5SDimitry Andric     const char *BufStart = CurMB->getBufferStart();
2940b57cec5SDimitry Andric     while (LineStart != BufStart && LineStart[-1] != '\n' &&
2950b57cec5SDimitry Andric            LineStart[-1] != '\r')
2960b57cec5SDimitry Andric       --LineStart;
2970b57cec5SDimitry Andric 
2980b57cec5SDimitry Andric     // Get the end of the line.
2990b57cec5SDimitry Andric     const char *LineEnd = Loc.getPointer();
3000b57cec5SDimitry Andric     const char *BufEnd = CurMB->getBufferEnd();
3010b57cec5SDimitry Andric     while (LineEnd != BufEnd && LineEnd[0] != '\n' && LineEnd[0] != '\r')
3020b57cec5SDimitry Andric       ++LineEnd;
303e8d8bef9SDimitry Andric     LineStr = StringRef(LineStart, LineEnd - LineStart);
3040b57cec5SDimitry Andric 
3050b57cec5SDimitry Andric     // Convert any ranges to column ranges that only intersect the line of the
3060b57cec5SDimitry Andric     // location.
3070eae32dcSDimitry Andric     for (SMRange R : Ranges) {
3085ffd83dbSDimitry Andric       if (!R.isValid())
3095ffd83dbSDimitry Andric         continue;
3100b57cec5SDimitry Andric 
3110b57cec5SDimitry Andric       // If the line doesn't contain any part of the range, then ignore it.
3120b57cec5SDimitry Andric       if (R.Start.getPointer() > LineEnd || R.End.getPointer() < LineStart)
3130b57cec5SDimitry Andric         continue;
3140b57cec5SDimitry Andric 
3150b57cec5SDimitry Andric       // Ignore pieces of the range that go onto other lines.
3160b57cec5SDimitry Andric       if (R.Start.getPointer() < LineStart)
3170b57cec5SDimitry Andric         R.Start = SMLoc::getFromPointer(LineStart);
3180b57cec5SDimitry Andric       if (R.End.getPointer() > LineEnd)
3190b57cec5SDimitry Andric         R.End = SMLoc::getFromPointer(LineEnd);
3200b57cec5SDimitry Andric 
3210b57cec5SDimitry Andric       // Translate from SMLoc ranges to column ranges.
3220b57cec5SDimitry Andric       // FIXME: Handle multibyte characters.
3230b57cec5SDimitry Andric       ColRanges.push_back(std::make_pair(R.Start.getPointer() - LineStart,
3240b57cec5SDimitry Andric                                          R.End.getPointer() - LineStart));
3250b57cec5SDimitry Andric     }
3260b57cec5SDimitry Andric 
3270b57cec5SDimitry Andric     LineAndCol = getLineAndColumn(Loc, CurBuf);
3280b57cec5SDimitry Andric   }
3290b57cec5SDimitry Andric 
3300b57cec5SDimitry Andric   return SMDiagnostic(*this, Loc, BufferID, LineAndCol.first,
3315ffd83dbSDimitry Andric                       LineAndCol.second - 1, Kind, Msg.str(), LineStr,
3325ffd83dbSDimitry Andric                       ColRanges, FixIts);
3330b57cec5SDimitry Andric }
3340b57cec5SDimitry Andric 
PrintMessage(raw_ostream & OS,const SMDiagnostic & Diagnostic,bool ShowColors) const3350b57cec5SDimitry Andric void SourceMgr::PrintMessage(raw_ostream &OS, const SMDiagnostic &Diagnostic,
3360b57cec5SDimitry Andric                              bool ShowColors) const {
3370b57cec5SDimitry Andric   // Report the message with the diagnostic handler if present.
3380b57cec5SDimitry Andric   if (DiagHandler) {
3390b57cec5SDimitry Andric     DiagHandler(Diagnostic, DiagContext);
3400b57cec5SDimitry Andric     return;
3410b57cec5SDimitry Andric   }
3420b57cec5SDimitry Andric 
3430b57cec5SDimitry Andric   if (Diagnostic.getLoc().isValid()) {
3440b57cec5SDimitry Andric     unsigned CurBuf = FindBufferContainingLoc(Diagnostic.getLoc());
3450b57cec5SDimitry Andric     assert(CurBuf && "Invalid or unspecified location!");
3460b57cec5SDimitry Andric     PrintIncludeStack(getBufferInfo(CurBuf).IncludeLoc, OS);
3470b57cec5SDimitry Andric   }
3480b57cec5SDimitry Andric 
3490b57cec5SDimitry Andric   Diagnostic.print(nullptr, OS, ShowColors);
3500b57cec5SDimitry Andric }
3510b57cec5SDimitry Andric 
PrintMessage(raw_ostream & OS,SMLoc Loc,SourceMgr::DiagKind Kind,const Twine & Msg,ArrayRef<SMRange> Ranges,ArrayRef<SMFixIt> FixIts,bool ShowColors) const3520b57cec5SDimitry Andric void SourceMgr::PrintMessage(raw_ostream &OS, SMLoc Loc,
3535ffd83dbSDimitry Andric                              SourceMgr::DiagKind Kind, const Twine &Msg,
3545ffd83dbSDimitry Andric                              ArrayRef<SMRange> Ranges, ArrayRef<SMFixIt> FixIts,
3555ffd83dbSDimitry Andric                              bool ShowColors) const {
3560b57cec5SDimitry Andric   PrintMessage(OS, GetMessage(Loc, Kind, Msg, Ranges, FixIts), ShowColors);
3570b57cec5SDimitry Andric }
3580b57cec5SDimitry Andric 
PrintMessage(SMLoc Loc,SourceMgr::DiagKind Kind,const Twine & Msg,ArrayRef<SMRange> Ranges,ArrayRef<SMFixIt> FixIts,bool ShowColors) const3590b57cec5SDimitry Andric void SourceMgr::PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind,
3600b57cec5SDimitry Andric                              const Twine &Msg, ArrayRef<SMRange> Ranges,
3610b57cec5SDimitry Andric                              ArrayRef<SMFixIt> FixIts, bool ShowColors) const {
3620b57cec5SDimitry Andric   PrintMessage(errs(), Loc, Kind, Msg, Ranges, FixIts, ShowColors);
3630b57cec5SDimitry Andric }
3640b57cec5SDimitry Andric 
3650b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
3665ffd83dbSDimitry Andric // SMFixIt Implementation
3675ffd83dbSDimitry Andric //===----------------------------------------------------------------------===//
3685ffd83dbSDimitry Andric 
SMFixIt(SMRange R,const Twine & Replacement)3695ffd83dbSDimitry Andric SMFixIt::SMFixIt(SMRange R, const Twine &Replacement)
3705ffd83dbSDimitry Andric     : Range(R), Text(Replacement.str()) {
3715ffd83dbSDimitry Andric   assert(R.isValid());
3725ffd83dbSDimitry Andric }
3735ffd83dbSDimitry Andric 
3745ffd83dbSDimitry Andric //===----------------------------------------------------------------------===//
3750b57cec5SDimitry Andric // SMDiagnostic Implementation
3760b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
3770b57cec5SDimitry Andric 
SMDiagnostic(const SourceMgr & sm,SMLoc L,StringRef FN,int Line,int Col,SourceMgr::DiagKind Kind,StringRef Msg,StringRef LineStr,ArrayRef<std::pair<unsigned,unsigned>> Ranges,ArrayRef<SMFixIt> Hints)3785ffd83dbSDimitry Andric SMDiagnostic::SMDiagnostic(const SourceMgr &sm, SMLoc L, StringRef FN, int Line,
3795ffd83dbSDimitry Andric                            int Col, SourceMgr::DiagKind Kind, StringRef Msg,
3805ffd83dbSDimitry Andric                            StringRef LineStr,
3810b57cec5SDimitry Andric                            ArrayRef<std::pair<unsigned, unsigned>> Ranges,
3820b57cec5SDimitry Andric                            ArrayRef<SMFixIt> Hints)
3835ffd83dbSDimitry Andric     : SM(&sm), Loc(L), Filename(std::string(FN)), LineNo(Line), ColumnNo(Col),
384e8d8bef9SDimitry Andric       Kind(Kind), Message(Msg), LineContents(LineStr), Ranges(Ranges.vec()),
385e8d8bef9SDimitry Andric       FixIts(Hints.begin(), Hints.end()) {
3860b57cec5SDimitry Andric   llvm::sort(FixIts);
3870b57cec5SDimitry Andric }
3880b57cec5SDimitry Andric 
buildFixItLine(std::string & CaretLine,std::string & FixItLine,ArrayRef<SMFixIt> FixIts,ArrayRef<char> SourceLine)3890b57cec5SDimitry Andric static void buildFixItLine(std::string &CaretLine, std::string &FixItLine,
3905ffd83dbSDimitry Andric                            ArrayRef<SMFixIt> FixIts,
3915ffd83dbSDimitry Andric                            ArrayRef<char> SourceLine) {
3920b57cec5SDimitry Andric   if (FixIts.empty())
3930b57cec5SDimitry Andric     return;
3940b57cec5SDimitry Andric 
3950b57cec5SDimitry Andric   const char *LineStart = SourceLine.begin();
3960b57cec5SDimitry Andric   const char *LineEnd = SourceLine.end();
3970b57cec5SDimitry Andric 
3980b57cec5SDimitry Andric   size_t PrevHintEndCol = 0;
3990b57cec5SDimitry Andric 
400e8d8bef9SDimitry Andric   for (const llvm::SMFixIt &Fixit : FixIts) {
4010b57cec5SDimitry Andric     // If the fixit contains a newline or tab, ignore it.
402e8d8bef9SDimitry Andric     if (Fixit.getText().find_first_of("\n\r\t") != StringRef::npos)
4030b57cec5SDimitry Andric       continue;
4040b57cec5SDimitry Andric 
405e8d8bef9SDimitry Andric     SMRange R = Fixit.getRange();
4060b57cec5SDimitry Andric 
4070b57cec5SDimitry Andric     // If the line doesn't contain any part of the range, then ignore it.
4080b57cec5SDimitry Andric     if (R.Start.getPointer() > LineEnd || R.End.getPointer() < LineStart)
4090b57cec5SDimitry Andric       continue;
4100b57cec5SDimitry Andric 
4110b57cec5SDimitry Andric     // Translate from SMLoc to column.
4120b57cec5SDimitry Andric     // Ignore pieces of the range that go onto other lines.
4130b57cec5SDimitry Andric     // FIXME: Handle multibyte characters in the source line.
4140b57cec5SDimitry Andric     unsigned FirstCol;
4150b57cec5SDimitry Andric     if (R.Start.getPointer() < LineStart)
4160b57cec5SDimitry Andric       FirstCol = 0;
4170b57cec5SDimitry Andric     else
4180b57cec5SDimitry Andric       FirstCol = R.Start.getPointer() - LineStart;
4190b57cec5SDimitry Andric 
4200b57cec5SDimitry Andric     // If we inserted a long previous hint, push this one forwards, and add
4210b57cec5SDimitry Andric     // an extra space to show that this is not part of the previous
4220b57cec5SDimitry Andric     // completion. This is sort of the best we can do when two hints appear
4230b57cec5SDimitry Andric     // to overlap.
4240b57cec5SDimitry Andric     //
4250b57cec5SDimitry Andric     // Note that if this hint is located immediately after the previous
4260b57cec5SDimitry Andric     // hint, no space will be added, since the location is more important.
4270b57cec5SDimitry Andric     unsigned HintCol = FirstCol;
4280b57cec5SDimitry Andric     if (HintCol < PrevHintEndCol)
4290b57cec5SDimitry Andric       HintCol = PrevHintEndCol + 1;
4300b57cec5SDimitry Andric 
4310b57cec5SDimitry Andric     // FIXME: This assertion is intended to catch unintended use of multibyte
4320b57cec5SDimitry Andric     // characters in fixits. If we decide to do this, we'll have to track
4330b57cec5SDimitry Andric     // separate byte widths for the source and fixit lines.
434e8d8bef9SDimitry Andric     assert((size_t)sys::locale::columnWidth(Fixit.getText()) ==
435e8d8bef9SDimitry Andric            Fixit.getText().size());
4360b57cec5SDimitry Andric 
4370b57cec5SDimitry Andric     // This relies on one byte per column in our fixit hints.
438e8d8bef9SDimitry Andric     unsigned LastColumnModified = HintCol + Fixit.getText().size();
4390b57cec5SDimitry Andric     if (LastColumnModified > FixItLine.size())
4400b57cec5SDimitry Andric       FixItLine.resize(LastColumnModified, ' ');
4410b57cec5SDimitry Andric 
442e8d8bef9SDimitry Andric     llvm::copy(Fixit.getText(), FixItLine.begin() + HintCol);
4430b57cec5SDimitry Andric 
4440b57cec5SDimitry Andric     PrevHintEndCol = LastColumnModified;
4450b57cec5SDimitry Andric 
4460b57cec5SDimitry Andric     // For replacements, mark the removal range with '~'.
4470b57cec5SDimitry Andric     // FIXME: Handle multibyte characters in the source line.
4480b57cec5SDimitry Andric     unsigned LastCol;
4490b57cec5SDimitry Andric     if (R.End.getPointer() >= LineEnd)
4500b57cec5SDimitry Andric       LastCol = LineEnd - LineStart;
4510b57cec5SDimitry Andric     else
4520b57cec5SDimitry Andric       LastCol = R.End.getPointer() - LineStart;
4530b57cec5SDimitry Andric 
4540b57cec5SDimitry Andric     std::fill(&CaretLine[FirstCol], &CaretLine[LastCol], '~');
4550b57cec5SDimitry Andric   }
4560b57cec5SDimitry Andric }
4570b57cec5SDimitry Andric 
printSourceLine(raw_ostream & S,StringRef LineContents)4580b57cec5SDimitry Andric static void printSourceLine(raw_ostream &S, StringRef LineContents) {
4590b57cec5SDimitry Andric   // Print out the source line one character at a time, so we can expand tabs.
4600b57cec5SDimitry Andric   for (unsigned i = 0, e = LineContents.size(), OutCol = 0; i != e; ++i) {
4610b57cec5SDimitry Andric     size_t NextTab = LineContents.find('\t', i);
4620b57cec5SDimitry Andric     // If there were no tabs left, print the rest, we are done.
4630b57cec5SDimitry Andric     if (NextTab == StringRef::npos) {
4640b57cec5SDimitry Andric       S << LineContents.drop_front(i);
4650b57cec5SDimitry Andric       break;
4660b57cec5SDimitry Andric     }
4670b57cec5SDimitry Andric 
4680b57cec5SDimitry Andric     // Otherwise, print from i to NextTab.
4690b57cec5SDimitry Andric     S << LineContents.slice(i, NextTab);
4700b57cec5SDimitry Andric     OutCol += NextTab - i;
4710b57cec5SDimitry Andric     i = NextTab;
4720b57cec5SDimitry Andric 
4730b57cec5SDimitry Andric     // If we have a tab, emit at least one space, then round up to 8 columns.
4740b57cec5SDimitry Andric     do {
4750b57cec5SDimitry Andric       S << ' ';
4760b57cec5SDimitry Andric       ++OutCol;
4770b57cec5SDimitry Andric     } while ((OutCol % TabStop) != 0);
4780b57cec5SDimitry Andric   }
4790b57cec5SDimitry Andric   S << '\n';
4800b57cec5SDimitry Andric }
4810b57cec5SDimitry Andric 
isNonASCII(char c)4825ffd83dbSDimitry Andric static bool isNonASCII(char c) { return c & 0x80; }
4830b57cec5SDimitry Andric 
print(const char * ProgName,raw_ostream & OS,bool ShowColors,bool ShowKindLabel) const4845ffd83dbSDimitry Andric void SMDiagnostic::print(const char *ProgName, raw_ostream &OS, bool ShowColors,
4855ffd83dbSDimitry Andric                          bool ShowKindLabel) const {
4865ffd83dbSDimitry Andric   ColorMode Mode = ShowColors ? ColorMode::Auto : ColorMode::Disable;
4875ffd83dbSDimitry Andric 
4880b57cec5SDimitry Andric   {
4895ffd83dbSDimitry Andric     WithColor S(OS, raw_ostream::SAVEDCOLOR, true, false, Mode);
4900b57cec5SDimitry Andric 
4910b57cec5SDimitry Andric     if (ProgName && ProgName[0])
4920b57cec5SDimitry Andric       S << ProgName << ": ";
4930b57cec5SDimitry Andric 
4940b57cec5SDimitry Andric     if (!Filename.empty()) {
4950b57cec5SDimitry Andric       if (Filename == "-")
4960b57cec5SDimitry Andric         S << "<stdin>";
4970b57cec5SDimitry Andric       else
4980b57cec5SDimitry Andric         S << Filename;
4990b57cec5SDimitry Andric 
5000b57cec5SDimitry Andric       if (LineNo != -1) {
5010b57cec5SDimitry Andric         S << ':' << LineNo;
5020b57cec5SDimitry Andric         if (ColumnNo != -1)
5030b57cec5SDimitry Andric           S << ':' << (ColumnNo + 1);
5040b57cec5SDimitry Andric       }
5050b57cec5SDimitry Andric       S << ": ";
5060b57cec5SDimitry Andric     }
5070b57cec5SDimitry Andric   }
5080b57cec5SDimitry Andric 
5090b57cec5SDimitry Andric   if (ShowKindLabel) {
5100b57cec5SDimitry Andric     switch (Kind) {
5110b57cec5SDimitry Andric     case SourceMgr::DK_Error:
5120b57cec5SDimitry Andric       WithColor::error(OS, "", !ShowColors);
5130b57cec5SDimitry Andric       break;
5140b57cec5SDimitry Andric     case SourceMgr::DK_Warning:
5150b57cec5SDimitry Andric       WithColor::warning(OS, "", !ShowColors);
5160b57cec5SDimitry Andric       break;
5170b57cec5SDimitry Andric     case SourceMgr::DK_Note:
5180b57cec5SDimitry Andric       WithColor::note(OS, "", !ShowColors);
5190b57cec5SDimitry Andric       break;
5200b57cec5SDimitry Andric     case SourceMgr::DK_Remark:
5210b57cec5SDimitry Andric       WithColor::remark(OS, "", !ShowColors);
5220b57cec5SDimitry Andric       break;
5230b57cec5SDimitry Andric     }
5240b57cec5SDimitry Andric   }
5250b57cec5SDimitry Andric 
5265ffd83dbSDimitry Andric   WithColor(OS, raw_ostream::SAVEDCOLOR, true, false, Mode) << Message << '\n';
5270b57cec5SDimitry Andric 
5280b57cec5SDimitry Andric   if (LineNo == -1 || ColumnNo == -1)
5290b57cec5SDimitry Andric     return;
5300b57cec5SDimitry Andric 
5310b57cec5SDimitry Andric   // FIXME: If there are multibyte or multi-column characters in the source, all
5320b57cec5SDimitry Andric   // our ranges will be wrong. To do this properly, we'll need a byte-to-column
5330b57cec5SDimitry Andric   // map like Clang's TextDiagnostic. For now, we'll just handle tabs by
5340b57cec5SDimitry Andric   // expanding them later, and bail out rather than show incorrect ranges and
5350b57cec5SDimitry Andric   // misaligned fixits for any other odd characters.
536e8d8bef9SDimitry Andric   if (any_of(LineContents, isNonASCII)) {
5370b57cec5SDimitry Andric     printSourceLine(OS, LineContents);
5380b57cec5SDimitry Andric     return;
5390b57cec5SDimitry Andric   }
5400b57cec5SDimitry Andric   size_t NumColumns = LineContents.size();
5410b57cec5SDimitry Andric 
5420b57cec5SDimitry Andric   // Build the line with the caret and ranges.
5430b57cec5SDimitry Andric   std::string CaretLine(NumColumns + 1, ' ');
5440b57cec5SDimitry Andric 
5450b57cec5SDimitry Andric   // Expand any ranges.
546e8d8bef9SDimitry Andric   for (const std::pair<unsigned, unsigned> &R : Ranges)
5470b57cec5SDimitry Andric     std::fill(&CaretLine[R.first],
5485ffd83dbSDimitry Andric               &CaretLine[std::min((size_t)R.second, CaretLine.size())], '~');
5490b57cec5SDimitry Andric 
5500b57cec5SDimitry Andric   // Add any fix-its.
5510b57cec5SDimitry Andric   // FIXME: Find the beginning of the line properly for multibyte characters.
5520b57cec5SDimitry Andric   std::string FixItInsertionLine;
553bdd1243dSDimitry Andric   buildFixItLine(CaretLine, FixItInsertionLine, FixIts,
554bdd1243dSDimitry Andric                  ArrayRef(Loc.getPointer() - ColumnNo, LineContents.size()));
5550b57cec5SDimitry Andric 
5560b57cec5SDimitry Andric   // Finally, plop on the caret.
5570b57cec5SDimitry Andric   if (unsigned(ColumnNo) <= NumColumns)
5580b57cec5SDimitry Andric     CaretLine[ColumnNo] = '^';
5590b57cec5SDimitry Andric   else
5600b57cec5SDimitry Andric     CaretLine[NumColumns] = '^';
5610b57cec5SDimitry Andric 
5620b57cec5SDimitry Andric   // ... and remove trailing whitespace so the output doesn't wrap for it.  We
5630b57cec5SDimitry Andric   // know that the line isn't completely empty because it has the caret in it at
5640b57cec5SDimitry Andric   // least.
5650b57cec5SDimitry Andric   CaretLine.erase(CaretLine.find_last_not_of(' ') + 1);
5660b57cec5SDimitry Andric 
5670b57cec5SDimitry Andric   printSourceLine(OS, LineContents);
5680b57cec5SDimitry Andric 
5690b57cec5SDimitry Andric   {
5705ffd83dbSDimitry Andric     ColorMode Mode = ShowColors ? ColorMode::Auto : ColorMode::Disable;
5715ffd83dbSDimitry Andric     WithColor S(OS, raw_ostream::GREEN, true, false, Mode);
5720b57cec5SDimitry Andric 
5730b57cec5SDimitry Andric     // Print out the caret line, matching tabs in the source line.
5740b57cec5SDimitry Andric     for (unsigned i = 0, e = CaretLine.size(), OutCol = 0; i != e; ++i) {
5750b57cec5SDimitry Andric       if (i >= LineContents.size() || LineContents[i] != '\t') {
5760b57cec5SDimitry Andric         S << CaretLine[i];
5770b57cec5SDimitry Andric         ++OutCol;
5780b57cec5SDimitry Andric         continue;
5790b57cec5SDimitry Andric       }
5800b57cec5SDimitry Andric 
5810b57cec5SDimitry Andric       // Okay, we have a tab.  Insert the appropriate number of characters.
5820b57cec5SDimitry Andric       do {
5830b57cec5SDimitry Andric         S << CaretLine[i];
5840b57cec5SDimitry Andric         ++OutCol;
5850b57cec5SDimitry Andric       } while ((OutCol % TabStop) != 0);
5860b57cec5SDimitry Andric     }
5870b57cec5SDimitry Andric     S << '\n';
5880b57cec5SDimitry Andric   }
5890b57cec5SDimitry Andric 
5900b57cec5SDimitry Andric   // Print out the replacement line, matching tabs in the source line.
5910b57cec5SDimitry Andric   if (FixItInsertionLine.empty())
5920b57cec5SDimitry Andric     return;
5930b57cec5SDimitry Andric 
5940b57cec5SDimitry Andric   for (size_t i = 0, e = FixItInsertionLine.size(), OutCol = 0; i < e; ++i) {
5950b57cec5SDimitry Andric     if (i >= LineContents.size() || LineContents[i] != '\t') {
5960b57cec5SDimitry Andric       OS << FixItInsertionLine[i];
5970b57cec5SDimitry Andric       ++OutCol;
5980b57cec5SDimitry Andric       continue;
5990b57cec5SDimitry Andric     }
6000b57cec5SDimitry Andric 
6010b57cec5SDimitry Andric     // Okay, we have a tab.  Insert the appropriate number of characters.
6020b57cec5SDimitry Andric     do {
6030b57cec5SDimitry Andric       OS << FixItInsertionLine[i];
6040b57cec5SDimitry Andric       // FIXME: This is trying not to break up replacements, but then to re-sync
6050b57cec5SDimitry Andric       // with the tabs between replacements. This will fail, though, if two
6060b57cec5SDimitry Andric       // fix-it replacements are exactly adjacent, or if a fix-it contains a
6070b57cec5SDimitry Andric       // space. Really we should be precomputing column widths, which we'll
6080b57cec5SDimitry Andric       // need anyway for multibyte chars.
6090b57cec5SDimitry Andric       if (FixItInsertionLine[i] != ' ')
6100b57cec5SDimitry Andric         ++i;
6110b57cec5SDimitry Andric       ++OutCol;
6120b57cec5SDimitry Andric     } while (((OutCol % TabStop) != 0) && i != e);
6130b57cec5SDimitry Andric   }
6140b57cec5SDimitry Andric   OS << '\n';
6150b57cec5SDimitry Andric }
616