blob: d0138530dbe23c2a0c1c1311a4350f0a330496eb [file] [log] [blame]
Chris Lattner3690f152006-06-28 06:48:36 +00001//===--- 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"
17using namespace llvm;
18using namespace clang;
19
20// ScratchBufSize - The size of each chunk of scratch memory. Slightly less
21//than a page, almost certainly enough for anything. :)
22static const unsigned ScratchBufSize = 4060;
23
24ScratchBuffer::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.
34SourceLocation 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
Chris Lattner4fb517b2006-06-29 06:34:53 +000042 unsigned InstantiationFileID =
43 SourceMgr.createFileIDForMacroExp(SourceLoc, FileID);
44
Chris Lattner3690f152006-06-28 06:48:36 +000045 // Create the initial SourceLocation.
Chris Lattner4fb517b2006-06-29 06:34:53 +000046 SourceLocation Loc(InstantiationFileID, BytesUsed);
Chris Lattner3690f152006-06-28 06:48:36 +000047 assert(BytesUsed < (1 << SourceLocation::FilePosBits) &&
48 "Out of range file position!");
49
Chris Lattner3690f152006-06-28 06:48:36 +000050 // Remember that we used these bytes.
51 BytesUsed += Len;
52
53 return Loc;
54}
55
56void ScratchBuffer::AllocScratchBuffer(unsigned RequestLen) {
57 // Only pay attention to the requested length if it is larger than our default
58 // page size. If it is, we allocate an entire chunk for it. This is to
59 // support gigantic tokens, which almost certainly won't happen. :)
60 if (RequestLen < ScratchBufSize)
61 RequestLen = ScratchBufSize;
62
63 SourceBuffer *Buf =
64 SourceBuffer::getNewMemBuffer(RequestLen, "<scratch space>");
65 FileID = SourceMgr.createFileIDForMemBuffer(Buf);
66 CurBuffer = const_cast<char*>(Buf->getBufferStart());
67 BytesUsed = 0;
68}