Chris Lattner | 3690f15 | 2006-06-28 06:48:36 +0000 | [diff] [blame^] | 1 | //===--- ScratchBuffer.cpp - Scratch space for forming tokens -------------===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file was developed by Chris Lattner and is distributed under |
| 6 | // the University of Illinois Open Source License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // This file implements the ScratchBuffer interface. |
| 11 | // |
| 12 | //===----------------------------------------------------------------------===// |
| 13 | |
| 14 | #include "clang/Lex/ScratchBuffer.h" |
| 15 | #include "clang/Basic/SourceBuffer.h" |
| 16 | #include "clang/Basic/SourceManager.h" |
| 17 | using namespace llvm; |
| 18 | using namespace clang; |
| 19 | |
| 20 | // ScratchBufSize - The size of each chunk of scratch memory. Slightly less |
| 21 | //than a page, almost certainly enough for anything. :) |
| 22 | static const unsigned ScratchBufSize = 4060; |
| 23 | |
| 24 | ScratchBuffer::ScratchBuffer(SourceManager &SM) : SourceMgr(SM), CurBuffer(0) { |
| 25 | // Set BytesUsed so that the first call to getToken will require an alloc. |
| 26 | BytesUsed = ScratchBufSize; |
| 27 | FileID = 0; |
| 28 | } |
| 29 | |
| 30 | |
| 31 | /// getToken - Splat the specified text into a temporary SourceBuffer and |
| 32 | /// return a SourceLocation that refers to the token. The SourceLoc value |
| 33 | /// gives a virtual location that the token will appear to be from. |
| 34 | SourceLocation ScratchBuffer::getToken(const char *Buf, unsigned Len, |
| 35 | SourceLocation SourceLoc) { |
| 36 | if (BytesUsed+Len > ScratchBufSize) |
| 37 | AllocScratchBuffer(Len); |
| 38 | |
| 39 | // Copy the token data into the buffer. |
| 40 | memcpy(CurBuffer+BytesUsed, Buf, Len); |
| 41 | |
| 42 | // Create the initial SourceLocation. |
| 43 | SourceLocation Loc(FileID, BytesUsed); |
| 44 | assert(BytesUsed < (1 << SourceLocation::FilePosBits) && |
| 45 | "Out of range file position!"); |
| 46 | |
| 47 | // FIXME: Merge SourceLoc into it. |
| 48 | |
| 49 | // Remember that we used these bytes. |
| 50 | BytesUsed += Len; |
| 51 | |
| 52 | return Loc; |
| 53 | } |
| 54 | |
| 55 | void ScratchBuffer::AllocScratchBuffer(unsigned RequestLen) { |
| 56 | // Only pay attention to the requested length if it is larger than our default |
| 57 | // page size. If it is, we allocate an entire chunk for it. This is to |
| 58 | // support gigantic tokens, which almost certainly won't happen. :) |
| 59 | if (RequestLen < ScratchBufSize) |
| 60 | RequestLen = ScratchBufSize; |
| 61 | |
| 62 | SourceBuffer *Buf = |
| 63 | SourceBuffer::getNewMemBuffer(RequestLen, "<scratch space>"); |
| 64 | FileID = SourceMgr.createFileIDForMemBuffer(Buf); |
| 65 | CurBuffer = const_cast<char*>(Buf->getBufferStart()); |
| 66 | BytesUsed = 0; |
| 67 | } |