1
0
Fork 0
mirror of https://github.com/beefytech/Beef.git synced 2025-06-08 03:28:20 +02:00

Trailing whitespace trimming

This commit is contained in:
Brian Fiete 2022-07-26 13:27:03 -04:00
parent 06425735d9
commit 7f328385db
88 changed files with 9577 additions and 9850 deletions

View file

@ -7,7 +7,6 @@ struct CV_LVAR_ADDR_GAP;
NS_BF_BEGIN NS_BF_BEGIN
#define PE_SIZEOF_SHORT_NAME 8 #define PE_SIZEOF_SHORT_NAME 8
#define PE_DIRECTORY_ENTRY_EXPORT 0 // Export Directory #define PE_DIRECTORY_ENTRY_EXPORT 0 // Export Directory
#define PE_NUMBEROF_DIRECTORY_ENTRIES 16 #define PE_NUMBEROF_DIRECTORY_ENTRIES 16
@ -17,7 +16,6 @@ NS_BF_BEGIN
#define PE_MACHINE_X86 0x14c #define PE_MACHINE_X86 0x14c
#define PE_MACHINE_X64 0x8664 #define PE_MACHINE_X64 0x8664
// DOS .EXE header // DOS .EXE header
struct PEHeader struct PEHeader
{ {
@ -174,8 +172,8 @@ struct PE_NTHeaders64
struct PESectionHeader struct PESectionHeader
{ {
char mName[IMAGE_SIZEOF_SHORT_NAME]; char mName[IMAGE_SIZEOF_SHORT_NAME];
DWORD mVirtualSize; DWORD mVirtualSize;
DWORD mVirtualAddress; DWORD mVirtualAddress;
DWORD mSizeOfRawData; DWORD mSizeOfRawData;
DWORD mPointerToRawData; DWORD mPointerToRawData;
@ -234,8 +232,8 @@ struct PE_SymInfoAux
// int GetPrologSize() const { return mAttributes & 0xF; } // int GetPrologSize() const { return mAttributes & 0xF; }
// //
// // # regs saved // // # regs saved
// int GetNumSavedRegs() const { return (mAttributes >> 8) & 0x7; } // int GetNumSavedRegs() const { return (mAttributes >> 8) & 0x7; }
// bool HasSEH() const { return (mAttributes >> 9) & 1; } // bool HasSEH() const { return (mAttributes >> 9) & 1; }
// bool UseBP() const { return (mAttributes >> 10) & 1; } // bool UseBP() const { return (mAttributes >> 10) & 1; }
// //
// // cbFrame: frame pointer // // cbFrame: frame pointer
@ -279,7 +277,7 @@ struct COFFFrameProgram
Command_Align, Command_Align,
Command_Set, Command_Set,
Command_Deref, Command_Deref,
Command_Value, Command_Value,
Command_Value8 Command_Value8
}; };

View file

@ -17,11 +17,11 @@ BfStructuralVisitor::BfStructuralVisitor()
} }
void BfStructuralVisitor::VisitMembers(BfBlock* node) void BfStructuralVisitor::VisitMembers(BfBlock* node)
{ {
for (auto& child : *node) for (auto& child : *node)
{ {
child->Accept(this); child->Accept(this);
} }
} }
void BfStructuralVisitor::VisitChildNoRef(BfAstNode* node) void BfStructuralVisitor::VisitChildNoRef(BfAstNode* node)
@ -673,7 +673,7 @@ void BfStructuralVisitor::Visit(BfNamespaceDeclaration* namespaceDeclaration)
void BfStructuralVisitor::Visit(BfBlock* block) void BfStructuralVisitor::Visit(BfBlock* block)
{ {
Visit(block->ToBase()); Visit(block->ToBase());
} }
void BfStructuralVisitor::Visit(BfUnscopedBlock* block) void BfStructuralVisitor::Visit(BfUnscopedBlock* block)
@ -688,7 +688,7 @@ void BfStructuralVisitor::Visit(BfBlockExtension* block)
void BfStructuralVisitor::Visit(BfRootNode* rootNode) void BfStructuralVisitor::Visit(BfRootNode* rootNode)
{ {
Visit(rootNode->ToBase()); Visit(rootNode->ToBase());
} }
void BfStructuralVisitor::Visit(BfInlineAsmStatement* asmStmt) void BfStructuralVisitor::Visit(BfInlineAsmStatement* asmStmt)
@ -715,7 +715,7 @@ BfAstTypeInfo::BfAstTypeInfo(const char* name, BfAstTypeInfo* baseType, BfAstAcc
if (mBaseType != NULL) if (mBaseType != NULL)
{ {
mBaseType->mDerivedTypes.Add(this); mBaseType->mDerivedTypes.Add(this);
} }
sTypeCount++; sTypeCount++;
#ifdef _DEBUG #ifdef _DEBUG
@ -800,7 +800,7 @@ bool BfAstNode::IsMissingSemicolon()
return (attribExpr->mStatement == NULL) || (attribExpr->mStatement->IsMissingSemicolon()); return (attribExpr->mStatement == NULL) || (attribExpr->mStatement->IsMissingSemicolon());
if (auto stmt = BfNodeDynCast<BfStatement>(this)) if (auto stmt = BfNodeDynCast<BfStatement>(this))
return stmt->mTrailingSemicolon == NULL; return stmt->mTrailingSemicolon == NULL;
return false; return false;
} }
@ -832,7 +832,7 @@ bool BfAstNode::WantsWarning(int warningNumber)
} }
bool BfAstNode::LocationEquals(BfAstNode* otherNode) bool BfAstNode::LocationEquals(BfAstNode* otherNode)
{ {
return (GetSourceData() == otherNode->GetSourceData()) && return (GetSourceData() == otherNode->GetSourceData()) &&
(GetSrcStart() == otherNode->GetSrcStart()) && (GetSrcStart() == otherNode->GetSrcStart()) &&
(GetSrcEnd() == otherNode->GetSrcEnd()); (GetSrcEnd() == otherNode->GetSrcEnd());
@ -851,7 +851,7 @@ String BfAstNode::LocationToString()
return String(); return String();
String loc; String loc;
int line = -1; int line = -1;
int lineChar = -1; int lineChar = -1;
parserData->GetLineCharAtIdx(mSrcStart, line, lineChar); parserData->GetLineCharAtIdx(mSrcStart, line, lineChar);
@ -864,10 +864,10 @@ String BfAstNode::LocationToString()
} }
void BfAstNode::Add(BfAstNode* bfAstNode) void BfAstNode::Add(BfAstNode* bfAstNode)
{ {
#ifdef BF_AST_HAS_PARENT_MEMBER #ifdef BF_AST_HAS_PARENT_MEMBER
BF_ASSERT(bfAstNode->mParent == NULL); BF_ASSERT(bfAstNode->mParent == NULL);
bfAstNode->mParent = this; bfAstNode->mParent = this;
#endif #endif
if (!IsInitialized()) if (!IsInitialized())
@ -897,7 +897,7 @@ void BfAstNode::Add(BfAstNode* bfAstNode)
SetSrcStart(childSrcStart); SetSrcStart(childSrcStart);
if (childSrcEnd > prevSrcEnd) if (childSrcEnd > prevSrcEnd)
SetSrcEnd(childSrcEnd); SetSrcEnd(childSrcEnd);
#else #else
BF_ASSERT(mSrcStart >= 0); BF_ASSERT(mSrcStart >= 0);
BF_ASSERT(bfAstNode->mSrcStart >= 0); BF_ASSERT(bfAstNode->mSrcStart >= 0);
@ -934,14 +934,14 @@ void BfAstNode::RemoveNextSibling()
} }
void BfAstNode::DeleteNextSibling() void BfAstNode::DeleteNextSibling()
{ {
//mNext->DeleteSelf(); //mNext->DeleteSelf();
} }
void BfAstNode::Init(BfParser* bfParser) void BfAstNode::Init(BfParser* bfParser)
{ {
BF_ASSERT(GetSourceData() == bfParser->mSourceData); BF_ASSERT(GetSourceData() == bfParser->mSourceData);
Init(bfParser->mTriviaStart, bfParser->mTokenStart, bfParser->mTokenEnd); Init(bfParser->mTriviaStart, bfParser->mTokenStart, bfParser->mTokenEnd);
} }
void BfAstNode::Accept(BfStructuralVisitor* bfVisitor) void BfAstNode::Accept(BfStructuralVisitor* bfVisitor)
@ -960,7 +960,7 @@ bool BfAstNode::IsTemporary()
int BfAstNode::GetStartCharId() int BfAstNode::GetStartCharId()
{ {
if (!IsTemporary()) if (!IsTemporary())
{ {
auto bfParser = GetSourceData()->ToParserData(); auto bfParser = GetSourceData()->ToParserData();
if (bfParser != NULL) if (bfParser != NULL)
@ -970,8 +970,8 @@ int BfAstNode::GetStartCharId()
} }
BfSourceData* BfAstNode::GetSourceData() BfSourceData* BfAstNode::GetSourceData()
{ {
#ifdef BF_AST_ALLOCATOR_USE_PAGES #ifdef BF_AST_ALLOCATOR_USE_PAGES
//BF_ASSERT((intptr)this > 0x4200000000); //BF_ASSERT((intptr)this > 0x4200000000);
BfAstPageHeader* pageHeader = (BfAstPageHeader*)((intptr)this & ~(BfAstAllocManager::PAGE_SIZE - 1)); BfAstPageHeader* pageHeader = (BfAstPageHeader*)((intptr)this & ~(BfAstAllocManager::PAGE_SIZE - 1));
return pageHeader->mSourceData; return pageHeader->mSourceData;
@ -1021,14 +1021,14 @@ String BfAstNode::ToString()
int srcLen = GetSrcLength(); int srcLen = GetSrcLength();
if (srcLen <= 0) if (srcLen <= 0)
{ {
if (auto namedTypeRef = BfNodeDynCast<BfNamedTypeReference>(this)) if (auto namedTypeRef = BfNodeDynCast<BfNamedTypeReference>(this))
return namedTypeRef->mNameNode->ToString(); return namedTypeRef->mNameNode->ToString();
return ""; return "";
} }
auto source = GetSourceData(); auto source = GetSourceData();
String str(source->mSrc + GetSrcStart(), srcLen); String str(source->mSrc + GetSrcStart(), srcLen);
return str; return str;
} }
@ -1057,7 +1057,7 @@ void BfAstNode::ToString(StringImpl& str)
} }
auto source = GetSourceData(); auto source = GetSourceData();
str.Append(source->mSrc + GetSrcStart(), srcLen); str.Append(source->mSrc + GetSrcStart(), srcLen);
} }
bool BfAstNode::Equals(const StringImpl& str) bool BfAstNode::Equals(const StringImpl& str)
@ -1079,7 +1079,7 @@ bool BfAstNode::Equals(const StringView& str)
} }
bool BfAstNode::Equals(const char* str) bool BfAstNode::Equals(const char* str)
{ {
auto source = GetSourceData(); auto source = GetSourceData();
const char* ptrLhs = source->mSrc + mSrcStart; const char* ptrLhs = source->mSrc + mSrcStart;
const char* ptrLhsEnd = source->mSrc + mSrcEnd; const char* ptrLhsEnd = source->mSrc + mSrcEnd;
@ -1087,7 +1087,7 @@ bool BfAstNode::Equals(const char* str)
while (true) while (true)
{ {
char cRhs = *(ptrRhs++); char cRhs = *(ptrRhs++);
if (cRhs == 0) if (cRhs == 0)
return ptrLhs == ptrLhsEnd; return ptrLhs == ptrLhsEnd;
if (ptrLhs == ptrLhsEnd) if (ptrLhs == ptrLhsEnd)
@ -1098,7 +1098,6 @@ bool BfAstNode::Equals(const char* str)
} }
} }
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
void BfBlock::Init(const SizedArrayImpl<BfAstNode*>& vec, BfAstAllocator* alloc) void BfBlock::Init(const SizedArrayImpl<BfAstNode*>& vec, BfAstAllocator* alloc)
@ -1112,18 +1111,18 @@ void BfBlock::Init(const SizedArrayImpl<BfAstNode*>& vec, BfAstAllocator* alloc)
{ {
int bytesLeft = alloc->GetCurPageBytesLeft(); int bytesLeft = alloc->GetCurPageBytesLeft();
int useElems = std::min(bytesLeft / (int)sizeof(ASTREF(BfAstNode*)), elemsLeft); int useElems = std::min(bytesLeft / (int)sizeof(ASTREF(BfAstNode*)), elemsLeft);
BfBlockExtension* nextExt = NULL; BfBlockExtension* nextExt = NULL;
BfSizedArray<ASTREF(BfAstNode*)>& childArrRef = (curExt != NULL) ? curExt->mChildArr : mChildArr; BfSizedArray<ASTREF(BfAstNode*)>& childArrRef = (curExt != NULL) ? curExt->mChildArr : mChildArr;
childArrRef.mVals = (ASTREF(BfAstNode*)*)alloc->AllocBytes(useElems * sizeof(ASTREF(BfAstNode*)), sizeof(ASTREF(BfAstNode*))); childArrRef.mVals = (ASTREF(BfAstNode*)*)alloc->AllocBytes(useElems * sizeof(ASTREF(BfAstNode*)), sizeof(ASTREF(BfAstNode*)));
childArrRef.mSize = useElems; childArrRef.mSize = useElems;
if (useElems < elemsLeft) if (useElems < elemsLeft)
{ {
nextExt = alloc->Alloc<BfBlockExtension>(); nextExt = alloc->Alloc<BfBlockExtension>();
useElems--; useElems--;
} }
for (int i = 0; i < useElems; i++) for (int i = 0; i < useElems; i++)
childArrRef[i] = vec[curIdx++]; childArrRef[i] = vec[curIdx++];
if (nextExt != NULL) if (nextExt != NULL)
{ {
childArrRef[useElems] = nextExt; childArrRef[useElems] = nextExt;
@ -1131,7 +1130,7 @@ void BfBlock::Init(const SizedArrayImpl<BfAstNode*>& vec, BfAstAllocator* alloc)
} }
elemsLeft -= useElems; elemsLeft -= useElems;
} }
#else #else
BfSizedArrayInitIndirect(mChildArr, vec, alloc); BfSizedArrayInitIndirect(mChildArr, vec, alloc);
#endif #endif
} }
@ -1157,10 +1156,10 @@ int BfBlock::GetSize()
{ {
int size = mChildArr.mSize; int size = mChildArr.mSize;
if (mChildArr.mSize == 0) if (mChildArr.mSize == 0)
return size; return size;
BfAstNode* backNode = mChildArr.mVals[mChildArr.mSize - 1]; BfAstNode* backNode = mChildArr.mVals[mChildArr.mSize - 1];
while (true) while (true)
{ {
if (auto blockExt = BfNodeDynCastExact<BfBlockExtension>(backNode)) if (auto blockExt = BfNodeDynCastExact<BfBlockExtension>(backNode))
{ {
size--; size--;
@ -1172,12 +1171,12 @@ int BfBlock::GetSize()
break; break;
} }
} }
return size; return size;
} }
void BfBlock::SetSize(int wantSize) void BfBlock::SetSize(int wantSize)
{ {
int size = mChildArr.mSize; int size = mChildArr.mSize;
if (wantSize == size) if (wantSize == size)
return; return;
@ -1390,7 +1389,7 @@ const char* Beefy::BfTokenToString(BfToken token)
case BfToken_Extension: case BfToken_Extension:
return "extension"; return "extension";
case BfToken_Fallthrough: case BfToken_Fallthrough:
return "fallthrough"; return "fallthrough";
case BfToken_Finally: case BfToken_Finally:
return "finally"; return "finally";
case BfToken_Fixed: case BfToken_Fixed:
@ -1426,7 +1425,7 @@ const char* Beefy::BfTokenToString(BfToken token)
case BfToken_Namespace: case BfToken_Namespace:
return "namespace"; return "namespace";
case BfToken_New: case BfToken_New:
return "new"; return "new";
case BfToken_Null: case BfToken_Null:
return "null"; return "null";
case BfToken_Nullable: case BfToken_Nullable:
@ -1578,7 +1577,7 @@ const char* Beefy::BfTokenToString(BfToken token)
case BfToken_Colon: case BfToken_Colon:
return ":"; return ":";
case BfToken_Comma: case BfToken_Comma:
return ","; return ",";
case BfToken_Dot: case BfToken_Dot:
case BfToken_AutocompleteDot: case BfToken_AutocompleteDot:
return "."; return ".";
@ -1645,7 +1644,7 @@ bool Beefy::BfTokenIsKeyword(BfToken token)
BfBinaryOp Beefy::BfAssignOpToBinaryOp(BfAssignmentOp assignmentOp) BfBinaryOp Beefy::BfAssignOpToBinaryOp(BfAssignmentOp assignmentOp)
{ {
switch (assignmentOp) switch (assignmentOp)
{ {
case BfAssignmentOp_Add: case BfAssignmentOp_Add:
return BfBinaryOp_Add; return BfBinaryOp_Add;
case BfAssignmentOp_Subtract: case BfAssignmentOp_Subtract:
@ -1681,9 +1680,9 @@ BfBinaryOp Beefy::BfAssignOpToBinaryOp(BfAssignmentOp assignmentOp)
} }
int Beefy::BfGetBinaryOpPrecendence(BfBinaryOp binOp) int Beefy::BfGetBinaryOpPrecendence(BfBinaryOp binOp)
{ {
switch (binOp) switch (binOp)
{ {
case BfBinaryOp_Multiply: case BfBinaryOp_Multiply:
case BfBinaryOp_OverflowMultiply: case BfBinaryOp_OverflowMultiply:
case BfBinaryOp_Divide: case BfBinaryOp_Divide:
@ -1693,7 +1692,7 @@ int Beefy::BfGetBinaryOpPrecendence(BfBinaryOp binOp)
case BfBinaryOp_Subtract: case BfBinaryOp_Subtract:
case BfBinaryOp_OverflowAdd: case BfBinaryOp_OverflowAdd:
case BfBinaryOp_OverflowSubtract: case BfBinaryOp_OverflowSubtract:
return 13; return 13;
case BfBinaryOp_LeftShift: case BfBinaryOp_LeftShift:
case BfBinaryOp_RightShift: case BfBinaryOp_RightShift:
return 12; return 12;
@ -1722,7 +1721,7 @@ int Beefy::BfGetBinaryOpPrecendence(BfBinaryOp binOp)
case BfBinaryOp_StrictInEquality: case BfBinaryOp_StrictInEquality:
return 4; return 4;
case BfBinaryOp_ConditionalAnd: case BfBinaryOp_ConditionalAnd:
return 3; return 3;
case BfBinaryOp_ConditionalOr: case BfBinaryOp_ConditionalOr:
return 2; return 2;
case BfBinaryOp_NullCoalesce: case BfBinaryOp_NullCoalesce:
@ -1797,7 +1796,7 @@ const char* Beefy::BfGetOpName(BfUnaryOp unaryOp)
case BfUnaryOp_FromEnd: return "^"; case BfUnaryOp_FromEnd: return "^";
case BfUnaryOp_PartialRangeUpTo: return "..<"; case BfUnaryOp_PartialRangeUpTo: return "..<";
case BfUnaryOp_PartialRangeThrough: return "..."; case BfUnaryOp_PartialRangeThrough: return "...";
case BfUnaryOp_PartialRangeFrom: return "..."; case BfUnaryOp_PartialRangeFrom: return "...";
default: return "???"; default: return "???";
} }
} }
@ -1929,7 +1928,6 @@ bool Beefy::BfCanOverloadOperator(BfUnaryOp unaryOp)
} }
} }
BfAssignmentOp Beefy::BfTokenToAssignmentOp(BfToken token) BfAssignmentOp Beefy::BfTokenToAssignmentOp(BfToken token)
{ {
switch (token) switch (token)
@ -1941,7 +1939,7 @@ BfAssignmentOp Beefy::BfTokenToAssignmentOp(BfToken token)
case BfToken_MinusEquals: case BfToken_MinusEquals:
return BfAssignmentOp_Subtract; return BfAssignmentOp_Subtract;
case BfToken_MultiplyEquals: case BfToken_MultiplyEquals:
return BfAssignmentOp_Multiply; return BfAssignmentOp_Multiply;
case BfToken_AndPlusEquals: case BfToken_AndPlusEquals:
return BfAssignmentOp_OverflowAdd; return BfAssignmentOp_OverflowAdd;
case BfToken_AndMinusEquals: case BfToken_AndMinusEquals:
@ -2143,4 +2141,4 @@ String BfInlineAsmInstruction::AsmInst::ToString()
} }
return s; return s;
} }

File diff suppressed because it is too large Load diff

View file

@ -24,36 +24,35 @@ void BfBitSet::Init(int numBits)
memset(mBits, 0, numInts * 4); memset(mBits, 0, numInts * 4);
} }
bool BfBitSet::IsSet(int idx) bool BfBitSet::IsSet(int idx)
{ {
return (mBits[idx / 32] & (1 << (idx % 32))) != 0; return (mBits[idx / 32] & (1 << (idx % 32))) != 0;
} }
void BfBitSet::Set(int idx) void BfBitSet::Set(int idx)
{ {
mBits[idx / 32] |= (1 << (idx % 32)); mBits[idx / 32] |= (1 << (idx % 32));
} }
void BfBitSet::Clear(int idx) void BfBitSet::Clear(int idx)
{ {
mBits[idx / 32] &= ~(1 << (idx % 32)); mBits[idx / 32] &= ~(1 << (idx % 32));
} }
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
BfAstAllocator::BfAstAllocator() BfAstAllocator::BfAstAllocator()
{ {
mSourceData = NULL; mSourceData = NULL;
mCurPtr = NULL; mCurPtr = NULL;
mCurPageEnd = mCurPtr; mCurPageEnd = mCurPtr;
mLargeAllocSizes = 0; mLargeAllocSizes = 0;
mNumPagesUsed = 0; mNumPagesUsed = 0;
mUsedSize = 0; mUsedSize = 0;
} }
BfAstAllocator::~BfAstAllocator() BfAstAllocator::~BfAstAllocator()
{ {
for (auto addr : mLargeAllocs) for (auto addr : mLargeAllocs)
delete [] (uint8*)addr; delete [] (uint8*)addr;
if (mPages.size() != 0) if (mPages.size() != 0)
@ -61,16 +60,16 @@ BfAstAllocator::~BfAstAllocator()
} }
void BfAstAllocator::InitChunkHead(int wantSize) void BfAstAllocator::InitChunkHead(int wantSize)
{ {
mCurPtr = mSourceData->mAstAllocManager->AllocPage(); mCurPtr = mSourceData->mAstAllocManager->AllocPage();
mPages.push_back(mCurPtr); mPages.push_back(mCurPtr);
mCurPageEnd = mCurPtr + BfAstAllocManager::PAGE_SIZE; mCurPageEnd = mCurPtr + BfAstAllocManager::PAGE_SIZE;
mNumPagesUsed++; mNumPagesUsed++;
#ifdef BF_AST_ALLOCATOR_USE_PAGES #ifdef BF_AST_ALLOCATOR_USE_PAGES
BfAstPageHeader* pageHeader = (BfAstPageHeader*)mCurPtr; BfAstPageHeader* pageHeader = (BfAstPageHeader*)mCurPtr;
pageHeader->mSourceData = mSourceData; pageHeader->mSourceData = mSourceData;
BF_ASSERT(sizeof(BfAstPageHeader) <= 16); BF_ASSERT(sizeof(BfAstPageHeader) <= 16);
mCurPtr += 16; mCurPtr += 16;
#endif #endif
} }
@ -95,28 +94,28 @@ BfAstAllocManager::~BfAstAllocManager()
#endif #endif
} }
//TODO: Remove this //TODO: Remove this
//static int gAstChunkAllocCount = 0; //static int gAstChunkAllocCount = 0;
uint8* BfAstAllocManager::AllocPage() uint8* BfAstAllocManager::AllocPage()
{ {
#ifdef BF_AST_ALLOCATOR_USE_PAGES #ifdef BF_AST_ALLOCATOR_USE_PAGES
AutoCrit autoCrit(mCritSect); AutoCrit autoCrit(mCritSect);
if (mFreePageCount != 0) if (mFreePageCount != 0)
{ {
mFreePageCount--; mFreePageCount--;
return (uint8*)mFreePages.PopFront(); return (uint8*)mFreePages.PopFront();
} }
BF_ASSERT(mFreePages.mHead == NULL); BF_ASSERT(mFreePages.mHead == NULL);
//auto newChunk = (uint8*)::VirtualAlloc((void*)(0x4200000000 + gAstChunkAllocCount*CHUNK_SIZE), CHUNK_SIZE, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); //auto newChunk = (uint8*)::VirtualAlloc((void*)(0x4200000000 + gAstChunkAllocCount*CHUNK_SIZE), CHUNK_SIZE, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
//gAstChunkAllocCount++; //gAstChunkAllocCount++;
auto newChunk = (uint8*)::VirtualAlloc(NULL, CHUNK_SIZE, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); auto newChunk = (uint8*)::VirtualAlloc(NULL, CHUNK_SIZE, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
BF_ASSERT(newChunk != NULL); BF_ASSERT(newChunk != NULL);
BF_ASSERT(((intptr)newChunk & (PAGE_SIZE - 1)) == 0); BF_ASSERT(((intptr)newChunk & (PAGE_SIZE - 1)) == 0);
mAllocChunks.push_back(newChunk); mAllocChunks.push_back(newChunk);
//BfLog("BfAstAllocManager alloc %p\n", newChunk); //BfLog("BfAstAllocManager alloc %p\n", newChunk);
@ -128,7 +127,7 @@ uint8* BfAstAllocManager::AllocPage()
} }
mFreePageCount--; mFreePageCount--;
return (uint8*)mFreePages.PopFront(); return (uint8*)mFreePages.PopFront();
#else #else
return new uint8[PAGE_SIZE]; return new uint8[PAGE_SIZE];
#endif #endif

View file

@ -49,14 +49,13 @@ public:
class BfAstPageHeader class BfAstPageHeader
{ {
public: public:
BfSourceData* mSourceData; BfSourceData* mSourceData;
}; };
#endif #endif
class BfAstAllocChunk; class BfAstAllocChunk;
class BfAstAllocManager; class BfAstAllocManager;
struct BfAstFreePage struct BfAstFreePage
{ {
BfAstFreePage* mNext; BfAstFreePage* mNext;
@ -75,7 +74,7 @@ public:
Array<uint8*> mAllocChunks; Array<uint8*> mAllocChunks;
#endif #endif
public: public:
BfAstAllocManager(); BfAstAllocManager();
~BfAstAllocManager(); ~BfAstAllocManager();
@ -90,7 +89,7 @@ public:
// { // {
// int mCount; // int mCount;
// int mSize; // int mSize;
// //
// BumpAllocTrackedEntry() // BumpAllocTrackedEntry()
// { // {
// mCount = 0; // mCount = 0;
@ -103,9 +102,9 @@ class BfAstAllocator
{ {
public: public:
static const int LARGE_ALLOC_SIZE = 2048; static const int LARGE_ALLOC_SIZE = 2048;
BfSourceData* mSourceData; BfSourceData* mSourceData;
uint8* mCurPtr; uint8* mCurPtr;
uint8* mCurPageEnd; uint8* mCurPageEnd;
Array<void*> mLargeAllocs; Array<void*> mLargeAllocs;
Array<uint8*> mPages; Array<uint8*> mPages;
int mLargeAllocSizes; int mLargeAllocSizes;
@ -117,8 +116,8 @@ public:
public: public:
BfAstAllocator(); BfAstAllocator();
~BfAstAllocator(); ~BfAstAllocator();
void InitChunkHead(int wantSize); void InitChunkHead(int wantSize);
int GetAllocSize() const int GetAllocSize() const
@ -141,7 +140,7 @@ public:
{ {
int alignSize = alignof(T); int alignSize = alignof(T);
mCurPtr = (uint8*)(((intptr)mCurPtr + alignSize - 1) & ~(alignSize - 1)); mCurPtr = (uint8*)(((intptr)mCurPtr + alignSize - 1) & ~(alignSize - 1));
int wantSize = sizeof(T) + extraBytes; int wantSize = sizeof(T) + extraBytes;
#ifdef BUMPALLOC_TRACKALLOCS #ifdef BUMPALLOC_TRACKALLOCS
const char* name = typeid(T).name(); const char* name = typeid(T).name();
@ -152,10 +151,10 @@ public:
#endif #endif
if (mCurPtr + wantSize >= mCurPageEnd) if (mCurPtr + wantSize >= mCurPageEnd)
InitChunkHead(wantSize); InitChunkHead(wantSize);
memset(mCurPtr, 0, wantSize); memset(mCurPtr, 0, wantSize);
T* retVal = new (mCurPtr) T(); T* retVal = new (mCurPtr) T();
mCurPtr += wantSize; mCurPtr += wantSize;
#ifndef BF_AST_ALLOCATOR_USE_PAGES #ifndef BF_AST_ALLOCATOR_USE_PAGES
retVal->mSourceData = this->mSourceData; retVal->mSourceData = this->mSourceData;
@ -165,8 +164,8 @@ public:
} }
uint8* AllocBytes(int wantSize, int alignSize, const char* dbgName = "AllocBytes") uint8* AllocBytes(int wantSize, int alignSize, const char* dbgName = "AllocBytes")
{ {
#ifdef BUMPALLOC_TRACKALLOCS #ifdef BUMPALLOC_TRACKALLOCS
BumpAllocTrackedEntry* allocSizePtr; BumpAllocTrackedEntry* allocSizePtr;
mTrackedAllocs.TryAdd(dbgName, NULL, &allocSizePtr); mTrackedAllocs.TryAdd(dbgName, NULL, &allocSizePtr);
allocSizePtr->mCount++; allocSizePtr->mCount++;
@ -188,13 +187,13 @@ public:
InitChunkHead(wantSize); InitChunkHead(wantSize);
memset(mCurPtr, 0, wantSize); memset(mCurPtr, 0, wantSize);
uint8* retVal = mCurPtr; uint8* retVal = mCurPtr;
mCurPtr += wantSize; mCurPtr += wantSize;
return retVal; return retVal;
} }
uint8* AllocBytes(int wantSize, const char* dbgName = "AllocBytes") uint8* AllocBytes(int wantSize, const char* dbgName = "AllocBytes")
{ {
#ifdef BUMPALLOC_TRACKALLOCS #ifdef BUMPALLOC_TRACKALLOCS
BumpAllocTrackedEntry* allocSizePtr; BumpAllocTrackedEntry* allocSizePtr;
mTrackedAllocs.TryAdd(dbgName, NULL, &allocSizePtr); mTrackedAllocs.TryAdd(dbgName, NULL, &allocSizePtr);
allocSizePtr->mCount++; allocSizePtr->mCount++;
@ -211,12 +210,10 @@ public:
if (mCurPtr + wantSize >= mCurPageEnd) if (mCurPtr + wantSize >= mCurPageEnd)
InitChunkHead(wantSize); InitChunkHead(wantSize);
memset(mCurPtr, 0, wantSize); memset(mCurPtr, 0, wantSize);
uint8* retVal = mCurPtr; uint8* retVal = mCurPtr;
mCurPtr += wantSize; mCurPtr += wantSize;
return retVal; return retVal;
} }
}; };
NS_BF_END NS_BF_END

File diff suppressed because it is too large Load diff

View file

@ -62,7 +62,7 @@ public:
} }
bool operator==(const AutoCompleteEntry& other) const bool operator==(const AutoCompleteEntry& other) const
{ {
return strcmp(mDisplay, other.mDisplay) == 0; return strcmp(mDisplay, other.mDisplay) == 0;
} }
}; };
@ -73,7 +73,7 @@ template <>
struct BeefHash<Beefy::AutoCompleteEntry> struct BeefHash<Beefy::AutoCompleteEntry>
{ {
size_t operator()(const Beefy::AutoCompleteEntry& val) size_t operator()(const Beefy::AutoCompleteEntry& val)
{ {
intptr hash = 0; intptr hash = 0;
const char* curPtr = val.mDisplay; const char* curPtr = val.mDisplay;
while (true) while (true)
@ -92,7 +92,7 @@ NS_BF_BEGIN
class AutoCompleteBase class AutoCompleteBase
{ {
public: public:
class EntryLess class EntryLess
{ {
public: public:
@ -103,7 +103,7 @@ public:
result = strcmp(left.mDisplay, right.mDisplay); result = strcmp(left.mDisplay, right.mDisplay);
return result < 0; return result < 0;
} }
}; };
public: public:
BumpAllocator mAlloc; BumpAllocator mAlloc;
@ -128,13 +128,13 @@ public:
class BfAutoComplete : public AutoCompleteBase class BfAutoComplete : public AutoCompleteBase
{ {
public: public:
class MethodMatchEntry class MethodMatchEntry
{ {
public: public:
BfMethodDef* mMethodDef; BfMethodDef* mMethodDef;
BfFieldInstance* mPayloadEnumField; BfFieldInstance* mPayloadEnumField;
BfTypeInstance* mTypeInstance; BfTypeInstance* mTypeInstance;
BfTypeVector mGenericArguments; BfTypeVector mGenericArguments;
BfMethodInstance* mCurMethodInstance; BfMethodInstance* mCurMethodInstance;
@ -142,34 +142,34 @@ public:
{ {
mMethodDef = NULL; mMethodDef = NULL;
mPayloadEnumField = NULL; mPayloadEnumField = NULL;
mTypeInstance = NULL; mTypeInstance = NULL;
mCurMethodInstance = NULL; mCurMethodInstance = NULL;
} }
}; };
class MethodMatchInfo class MethodMatchInfo
{ {
public: public:
BfTypeInstance* mCurTypeInstance; BfTypeInstance* mCurTypeInstance;
BfMethodInstance* mCurMethodInstance; BfMethodInstance* mCurMethodInstance;
Array<MethodMatchEntry> mInstanceList; Array<MethodMatchEntry> mInstanceList;
int mInvocationSrcIdx; int mInvocationSrcIdx;
int mBestIdx; int mBestIdx;
int mPrevBestIdx; int mPrevBestIdx;
bool mHadExactMatch; bool mHadExactMatch;
int mMostParamsMatched; int mMostParamsMatched;
Array<int> mSrcPositions; // start, commas, end Array<int> mSrcPositions; // start, commas, end
public: public:
MethodMatchInfo() MethodMatchInfo()
{ {
mInvocationSrcIdx = -1; mInvocationSrcIdx = -1;
mCurTypeInstance = NULL; mCurTypeInstance = NULL;
mCurMethodInstance = NULL; mCurMethodInstance = NULL;
mBestIdx = 0; mBestIdx = 0;
mPrevBestIdx = -1; mPrevBestIdx = -1;
mHadExactMatch = false; mHadExactMatch = false;
mMostParamsMatched = 0; mMostParamsMatched = 0;
} }
~MethodMatchInfo() ~MethodMatchInfo()
@ -177,10 +177,10 @@ public:
} }
}; };
public: public:
BfModule* mModule; BfModule* mModule;
BfCompiler* mCompiler; BfCompiler* mCompiler;
BfSystem* mSystem; BfSystem* mSystem;
MethodMatchInfo* mMethodMatchInfo; MethodMatchInfo* mMethodMatchInfo;
bool mIsCapturingMethodMatchInfo; bool mIsCapturingMethodMatchInfo;
String mDefaultSelection; String mDefaultSelection;
@ -196,8 +196,8 @@ public:
bool mForceAllowNonStatic; bool mForceAllowNonStatic;
int mCursorLineStart; int mCursorLineStart;
int mCursorLineEnd; int mCursorLineEnd;
int mReplaceLocalId; int mReplaceLocalId;
BfMethodDef* mDefMethod; BfMethodDef* mDefMethod;
BfTypeDef* mDefType; BfTypeDef* mDefType;
BfFieldDef* mDefField; BfFieldDef* mDefField;
@ -206,7 +206,7 @@ public:
int mDefMethodGenericParamIdx; int mDefMethodGenericParamIdx;
int mDefTypeGenericParamIdx; int mDefTypeGenericParamIdx;
public: public:
BfProject* GetActiveProject(); BfProject* GetActiveProject();
bool WantsEntries(); bool WantsEntries();
bool CheckProtection(BfProtection protection, BfTypeDef* typeDef, bool allowProtected, bool allowPrivate); bool CheckProtection(BfProtection protection, BfTypeDef* typeDef, bool allowProtected, bool allowPrivate);
@ -216,9 +216,9 @@ public:
bool IsAutocompleteNode(BfAstNode* node, int lengthAdd = 0, int startAdd = 0); bool IsAutocompleteNode(BfAstNode* node, int lengthAdd = 0, int startAdd = 0);
bool IsAutocompleteNode(BfAstNode* startNode, BfAstNode* endNode, int lengthAdd = 0, int startAdd = 0); bool IsAutocompleteNode(BfAstNode* startNode, BfAstNode* endNode, int lengthAdd = 0, int startAdd = 0);
bool IsAutocompleteLineNode(BfAstNode* node); bool IsAutocompleteLineNode(BfAstNode* node);
BfTypedValue LookupTypeRefOrIdentifier(BfAstNode* node, bool* isStatic, BfEvalExprFlags evalExprFlags = BfEvalExprFlags_None, BfType* expectingType = NULL); BfTypedValue LookupTypeRefOrIdentifier(BfAstNode* node, bool* isStatic, BfEvalExprFlags evalExprFlags = BfEvalExprFlags_None, BfType* expectingType = NULL);
void SetDefinitionLocation(BfAstNode* astNode, bool force = false); void SetDefinitionLocation(BfAstNode* astNode, bool force = false);
bool IsAttribute(BfTypeInstance* typeInst); bool IsAttribute(BfTypeInstance* typeInst);
void AddMethod(BfTypeInstance* typeInstance, BfMethodDef* methodDef, BfMethodInstance* methodInstance, BfMethodDeclaration* methodDecl, const StringImpl& methodName, const StringImpl& filter); void AddMethod(BfTypeInstance* typeInstance, BfMethodDef* methodDef, BfMethodInstance* methodInstance, BfMethodDeclaration* methodDecl, const StringImpl& methodName, const StringImpl& filter);
void AddField(BfTypeInstance* typeInst, BfFieldDef* fieldDef, BfFieldInstance* fieldInstance, const StringImpl& filter); void AddField(BfTypeInstance* typeInst, BfFieldDef* fieldDef, BfFieldInstance* fieldInstance, const StringImpl& filter);
void AddProp(BfTypeInstance* typeInst, BfPropertyDef* propDef, const StringImpl& filter); void AddProp(BfTypeInstance* typeInst, BfPropertyDef* propDef, const StringImpl& filter);
@ -228,26 +228,26 @@ public:
void AddTypeMembers(BfTypeInstance* typeInst, bool addStatic, bool addNonStatic, const StringImpl& filter, BfTypeInstance* startType, bool allowInterfaces, bool allowImplicitThis, bool checkOuterType); void AddTypeMembers(BfTypeInstance* typeInst, bool addStatic, bool addNonStatic, const StringImpl& filter, BfTypeInstance* startType, bool allowInterfaces, bool allowImplicitThis, bool checkOuterType);
void AddSelfResultTypeMembers(BfTypeInstance* typeInst, BfTypeInstance* selfType, const StringImpl& filter, bool allowPrivate); void AddSelfResultTypeMembers(BfTypeInstance* typeInst, BfTypeInstance* selfType, const StringImpl& filter, bool allowPrivate);
bool InitAutocomplete(BfAstNode* dotNode, BfAstNode* nameNode, String& filter); bool InitAutocomplete(BfAstNode* dotNode, BfAstNode* nameNode, String& filter);
void AddEnumTypeMembers(BfTypeInstance* typeInst, const StringImpl& filter, bool allowProtected, bool allowPrivate); void AddEnumTypeMembers(BfTypeInstance* typeInst, const StringImpl& filter, bool allowProtected, bool allowPrivate);
void AddExtensionMethods(BfTypeInstance* targetType, BfTypeInstance* extensionContainer, const StringImpl& filter, bool allowProtected, bool allowPrivate); void AddExtensionMethods(BfTypeInstance* targetType, BfTypeInstance* extensionContainer, const StringImpl& filter, bool allowProtected, bool allowPrivate);
void AddTopLevelNamespaces(BfAstNode* identifierNode); void AddTopLevelNamespaces(BfAstNode* identifierNode);
void AddTopLevelTypes(BfAstNode* identifierNode, bool onlyAttribute = false); void AddTopLevelTypes(BfAstNode* identifierNode, bool onlyAttribute = false);
void AddOverrides(const StringImpl& filter); void AddOverrides(const StringImpl& filter);
void UpdateReplaceData(); void UpdateReplaceData();
void AddTypeInstanceEntry(BfTypeInstance* typeInst); void AddTypeInstanceEntry(BfTypeInstance* typeInst);
bool CheckDocumentation(AutoCompleteEntry* entry, BfCommentNode* documentation); bool CheckDocumentation(AutoCompleteEntry* entry, BfCommentNode* documentation);
bool GetMethodInfo(BfMethodInstance* methodInst, StringImpl* methodName, StringImpl* insertString, bool isImplementing, bool isExplicitInterface); bool GetMethodInfo(BfMethodInstance* methodInst, StringImpl* methodName, StringImpl* insertString, bool isImplementing, bool isExplicitInterface);
void FixitGetParamString(const BfTypeVector& paramTypes, StringImpl& outStr); void FixitGetParamString(const BfTypeVector& paramTypes, StringImpl& outStr);
int FixitGetMemberInsertPos(BfTypeDef* typeDef); int FixitGetMemberInsertPos(BfTypeDef* typeDef);
String FixitGetLocation(BfParserData* parserData, int insertPos); String FixitGetLocation(BfParserData* parserData, int insertPos);
String ConstantToString(BfIRConstHolder* constHolder, BfIRValue id); String ConstantToString(BfIRConstHolder* constHolder, BfIRValue id);
public: public:
BfAutoComplete(BfResolveType resolveType = BfResolveType_Autocomplete, bool doFuzzyAutoComplete = false); BfAutoComplete(BfResolveType resolveType = BfResolveType_Autocomplete, bool doFuzzyAutoComplete = false);
~BfAutoComplete(); ~BfAutoComplete();
void SetModule(BfModule* module); void SetModule(BfModule* module);
void Clear(); void Clear();
void RemoveMethodMatchInfo(); void RemoveMethodMatchInfo();
void ClearMethodMatchEntries(); void ClearMethodMatchEntries();
@ -256,21 +256,21 @@ public:
bool CheckExplicitInterface(BfTypeInstance* interfaceType, BfAstNode* dotToken, BfAstNode* memberName); bool CheckExplicitInterface(BfTypeInstance* interfaceType, BfAstNode* dotToken, BfAstNode* memberName);
void CheckTypeRef(BfTypeReference* typeRef, bool mayBeIdentifier, bool isInExpression = false, bool onlyAttribute = false); void CheckTypeRef(BfTypeReference* typeRef, bool mayBeIdentifier, bool isInExpression = false, bool onlyAttribute = false);
void CheckAttributeTypeRef(BfTypeReference* typeRef); void CheckAttributeTypeRef(BfTypeReference* typeRef);
void CheckInvocation(BfAstNode* invocationNode, BfTokenNode* openParen, BfTokenNode* closeParen, const BfSizedArray<BfTokenNode*>& commas); void CheckInvocation(BfAstNode* invocationNode, BfTokenNode* openParen, BfTokenNode* closeParen, const BfSizedArray<BfTokenNode*>& commas);
void CheckNode(BfAstNode* node, bool mayBeIdentifier, bool isInExpression = false); void CheckNode(BfAstNode* node, bool mayBeIdentifier, bool isInExpression = false);
void CheckMethod(BfMethodDeclaration* methodDeclaration, bool isLocalMethod); void CheckMethod(BfMethodDeclaration* methodDeclaration, bool isLocalMethod);
void CheckProperty(BfPropertyDeclaration* propertyDeclaration); void CheckProperty(BfPropertyDeclaration* propertyDeclaration);
void CheckVarResolution(BfAstNode* varTypeRef, BfType* resolvedTypeRef); void CheckVarResolution(BfAstNode* varTypeRef, BfType* resolvedTypeRef);
void CheckResult(BfAstNode* node, const BfTypedValue& typedValue); void CheckResult(BfAstNode* node, const BfTypedValue& typedValue);
void CheckLocalDef(BfAstNode* identifierNode, BfLocalVariable* varDecl); void CheckLocalDef(BfAstNode* identifierNode, BfLocalVariable* varDecl);
void CheckLocalRef(BfAstNode* identifierNode, BfLocalVariable* varDecl); void CheckLocalRef(BfAstNode* identifierNode, BfLocalVariable* varDecl);
void CheckFieldRef(BfAstNode* identifierNode, BfFieldInstance* fieldInst); void CheckFieldRef(BfAstNode* identifierNode, BfFieldInstance* fieldInst);
void CheckLabel(BfIdentifierNode* identifierNode, BfAstNode* precedingNode, BfScopeData* scopeData); void CheckLabel(BfIdentifierNode* identifierNode, BfAstNode* precedingNode, BfScopeData* scopeData);
void CheckNamespace(BfAstNode* node, const BfAtomComposite& namespaceName); void CheckNamespace(BfAstNode* node, const BfAtomComposite& namespaceName);
void CheckEmptyStart(BfAstNode* prevNode, BfType* type); void CheckEmptyStart(BfAstNode* prevNode, BfType* type);
bool CheckFixit(BfAstNode* node); bool CheckFixit(BfAstNode* node);
void CheckInterfaceFixit(BfTypeInstance* typeInstance, BfAstNode* node); void CheckInterfaceFixit(BfTypeInstance* typeInstance, BfAstNode* node);
void FixitAddMember(BfTypeInstance* typeInst, BfType* fieldType, const StringImpl& fieldName, bool isStatic, BfTypeInstance* referencedFrom); void FixitAddMember(BfTypeInstance* typeInst, BfType* fieldType, const StringImpl& fieldName, bool isStatic, BfTypeInstance* referencedFrom);
void FixitAddCase(BfTypeInstance * typeInst, const StringImpl & caseName, const BfTypeVector & fieldTypes); void FixitAddCase(BfTypeInstance * typeInst, const StringImpl & caseName, const BfTypeVector & fieldTypes);
void FixitAddMethod(BfTypeInstance* typeInst, const StringImpl& methodName, BfType* returnType, const BfTypeVector& paramTypes, bool wantStatic); void FixitAddMethod(BfTypeInstance* typeInst, const StringImpl& methodName, BfType* returnType, const BfTypeVector& paramTypes, bool wantStatic);

View file

@ -57,7 +57,6 @@
USING_NS_BF; USING_NS_BF;
using namespace llvm; using namespace llvm;
String BfCodeGenDirectoryData::GetDataFileName() String BfCodeGenDirectoryData::GetDataFileName()
{ {
return mDirectoryName + "/build.dat"; return mDirectoryName + "/build.dat";
@ -89,7 +88,7 @@ void BfCodeGenDirectoryData::Read()
for (int fileIdx = 0; fileIdx < numFiles; fileIdx++) for (int fileIdx = 0; fileIdx < numFiles; fileIdx++)
{ {
String fileName = fileStream.ReadAscii32SizedString(); String fileName = fileStream.ReadAscii32SizedString();
BfCodeGenFileData fileData; BfCodeGenFileData fileData;
fileStream.Read(&fileData.mIRHash, sizeof(Val128)); fileStream.Read(&fileData.mIRHash, sizeof(Val128));
fileStream.Read(&fileData.mIROrderedHash, sizeof(Val128)); fileStream.Read(&fileData.mIROrderedHash, sizeof(Val128));
fileStream.Read(&fileData.mLastWasObjectWrite, sizeof(bool)); fileStream.Read(&fileData.mLastWasObjectWrite, sizeof(bool));
@ -159,7 +158,7 @@ void BfCodeGenDirectoryData::Write()
} }
void BfCodeGenDirectoryData::Verify() void BfCodeGenDirectoryData::Verify()
{ {
if (!mError.empty()) if (!mError.empty())
return; return;
@ -171,12 +170,12 @@ void BfCodeGenDirectoryData::Verify()
} }
else else
{ {
mError = "Build directory corrupted, perform clean"; mError = "Build directory corrupted, perform clean";
} }
} }
void BfCodeGenDirectoryData::Clear() void BfCodeGenDirectoryData::Clear()
{ {
mFileMap.Clear(); mFileMap.Clear();
mBuildSettings.Clear(); mBuildSettings.Clear();
} }
@ -187,16 +186,16 @@ bool BfCodeGenDirectoryData::CheckCache(const StringImpl& fileName, Val128 hash,
Verify(); Verify();
BfCodeGenFileData* fileData = NULL; BfCodeGenFileData* fileData = NULL;
if (!mFileMap.TryAdd(fileName, NULL, &fileData)) if (!mFileMap.TryAdd(fileName, NULL, &fileData))
{ {
if ((fileData->mLastWasObjectWrite) && (disallowObjectWrite)) if ((fileData->mLastWasObjectWrite) && (disallowObjectWrite))
return false; return false;
if (outOrderedHash != NULL) if (outOrderedHash != NULL)
*outOrderedHash = fileData->mIROrderedHash; *outOrderedHash = fileData->mIROrderedHash;
if (fileData->mIRHash == hash) if (fileData->mIRHash == hash)
return true; return true;
fileData->mIRHash = hash; fileData->mIRHash = hash;
return false; return false;
} }
@ -212,9 +211,9 @@ void BfCodeGenDirectoryData::SetHash(const StringImpl& fileName, Val128 hash, Va
BfCodeGenFileData* fileData = NULL; BfCodeGenFileData* fileData = NULL;
mFileMap.TryAdd(fileName, NULL, &fileData); mFileMap.TryAdd(fileName, NULL, &fileData);
fileData->mIRHash = hash; fileData->mIRHash = hash;
fileData->mIROrderedHash = orderedHash; fileData->mIROrderedHash = orderedHash;
fileData->mLastWasObjectWrite = isObjectWrite; fileData->mLastWasObjectWrite = isObjectWrite;
} }
@ -223,7 +222,6 @@ void BfCodeGenDirectoryData::ClearHash(const StringImpl& fileName)
mFileMap.Remove(fileName); mFileMap.Remove(fileName);
} }
void BfCodeGenDirectoryData::FileFailed() void BfCodeGenDirectoryData::FileFailed()
{ {
mFileFailed = true; mFileFailed = true;
@ -240,7 +238,7 @@ String BfCodeGenDirectoryData::GetValue(const StringImpl& key)
} }
void BfCodeGenDirectoryData::SetValue(const StringImpl& key, const StringImpl& value) void BfCodeGenDirectoryData::SetValue(const StringImpl& key, const StringImpl& value)
{ {
mBuildSettings[key] = value; mBuildSettings[key] = value;
} }
@ -265,16 +263,16 @@ void DbgSaveData(BfCodeGenRequest* genRequest)
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
BfCodeGenThread::BfCodeGenThread() BfCodeGenThread::BfCodeGenThread()
{ {
mShuttingDown = false; mShuttingDown = false;
mRunning = false; mRunning = false;
mThreadIdx = 0; mThreadIdx = 0;
mCodeGen = NULL; mCodeGen = NULL;
} }
BfCodeGenThread::~BfCodeGenThread() BfCodeGenThread::~BfCodeGenThread()
{ {
Shutdown(); Shutdown();
} }
void BfCodeGenThread::RunLoop() void BfCodeGenThread::RunLoop()
@ -282,21 +280,21 @@ void BfCodeGenThread::RunLoop()
String threadName = StrFormat("CodeGen/Worker %d", mThreadIdx); String threadName = StrFormat("CodeGen/Worker %d", mThreadIdx);
BpSetThreadName(threadName.c_str()); BpSetThreadName(threadName.c_str());
BfpThread_SetName(NULL, threadName.c_str(), NULL); BfpThread_SetName(NULL, threadName.c_str(), NULL);
while (!mShuttingDown) while (!mShuttingDown)
{ {
BfCodeGenRequest* request = NULL; BfCodeGenRequest* request = NULL;
{ {
AutoCrit autoCrit(mCodeGen->mPendingRequestCritSect); AutoCrit autoCrit(mCodeGen->mPendingRequestCritSect);
if (!mCodeGen->mPendingRequests.IsEmpty()) if (!mCodeGen->mPendingRequests.IsEmpty())
{ {
request = mCodeGen->mPendingRequests[0]; request = mCodeGen->mPendingRequests[0];
mCodeGen->mPendingRequests.RemoveAt(0); mCodeGen->mPendingRequests.RemoveAt(0);
} }
} }
if (request == NULL) if (request == NULL)
{ {
mCodeGen->mRequestEvent.WaitFor(20); mCodeGen->mRequestEvent.WaitFor(20);
continue; continue;
} }
@ -318,7 +316,7 @@ void BfCodeGenThread::RunLoop()
#ifndef CODEGEN_DISABLE_CACHE #ifndef CODEGEN_DISABLE_CACHE
{ {
AutoCrit autoCrit(mCodeGen->mCacheCritSect); AutoCrit autoCrit(mCodeGen->mCacheCritSect);
dirCache = mCodeGen->GetDirCache(cacheDir); dirCache = mCodeGen->GetDirCache(cacheDir);
//For testing only! //For testing only!
@ -328,11 +326,11 @@ void BfCodeGenThread::RunLoop()
fileStr.Write(request->mData.mVals, request->mData.mSize); fileStr.Write(request->mData.mVals, request->mData.mSize);
}*/ }*/
HashContext hashCtx; HashContext hashCtx;
hashCtx.Mixin(request->mOptions.mHash); hashCtx.Mixin(request->mOptions.mHash);
hashCtx.Mixin(request->mData.mVals, request->mData.mSize); hashCtx.Mixin(request->mData.mVals, request->mData.mSize);
hash = hashCtx.Finish128(); hash = hashCtx.Finish128();
hasCacheMatch = dirCache->CheckCache(cacheFileName, hash, &orderedHash, isLibWrite); hasCacheMatch = dirCache->CheckCache(cacheFileName, hash, &orderedHash, isLibWrite);
#ifdef BF_PLATFORM_WINDOWS #ifdef BF_PLATFORM_WINDOWS
@ -346,10 +344,9 @@ void BfCodeGenThread::RunLoop()
hash = Val128(); hash = Val128();
hasCacheMatch = false; hasCacheMatch = false;
} }
} }
#endif #endif
} }
#endif #endif
@ -360,7 +357,7 @@ void BfCodeGenThread::RunLoop()
hasCacheMatch = false; hasCacheMatch = false;
#endif #endif
String errorMsg; String errorMsg;
bool doBEProcessing = true; // TODO: Normally 'true' so we do ordered cache check for LLVM too bool doBEProcessing = true; // TODO: Normally 'true' so we do ordered cache check for LLVM too
if (request->mOptions.mOptLevel == BfOptLevel_OgPlus) if (request->mOptions.mOptLevel == BfOptLevel_OgPlus)
@ -375,7 +372,7 @@ void BfCodeGenThread::RunLoop()
} }
else else
{ {
#ifdef BF_PLATFORM_WINDOWS #ifdef BF_PLATFORM_WINDOWS
BeIRCodeGen* beIRCodeGen = new BeIRCodeGen(); BeIRCodeGen* beIRCodeGen = new BeIRCodeGen();
defer ( delete beIRCodeGen; ); defer ( delete beIRCodeGen; );
@ -383,17 +380,17 @@ void BfCodeGenThread::RunLoop()
beIRCodeGen->SetConfigConst(BfIRConfigConst_DynSlotOfs, request->mOptions.mDynSlotOfs); beIRCodeGen->SetConfigConst(BfIRConfigConst_DynSlotOfs, request->mOptions.mDynSlotOfs);
if (doBEProcessing) if (doBEProcessing)
{ {
BP_ZONE("ProcessBfIRData"); BP_ZONE("ProcessBfIRData");
beIRCodeGen->Init(request->mData); beIRCodeGen->Init(request->mData);
BeHashContext hashCtx; BeHashContext hashCtx;
hashCtx.Mixin(request->mOptions.mHash); hashCtx.Mixin(request->mOptions.mHash);
beIRCodeGen->Hash(hashCtx); beIRCodeGen->Hash(hashCtx);
auto newOrderedHash = hashCtx.Finish128(); auto newOrderedHash = hashCtx.Finish128();
BfLogX(2, "Ordered hash for %s New:%s Old:%s\n", cacheFileName.c_str(), newOrderedHash.ToString().c_str(), orderedHash.ToString().c_str()); BfLogX(2, "Ordered hash for %s New:%s Old:%s\n", cacheFileName.c_str(), newOrderedHash.ToString().c_str(), orderedHash.ToString().c_str());
hasCacheMatch = newOrderedHash == orderedHash; hasCacheMatch = newOrderedHash == orderedHash;
errorMsg = beIRCodeGen->mErrorMsg; errorMsg = beIRCodeGen->mErrorMsg;
orderedHash = newOrderedHash; orderedHash = newOrderedHash;
} }
@ -402,10 +399,10 @@ void BfCodeGenThread::RunLoop()
{ {
result.mType = BfCodeGenResult_DoneCached; result.mType = BfCodeGenResult_DoneCached;
} }
#ifndef CODEGEN_DISABLE_CACHE #ifndef CODEGEN_DISABLE_CACHE
{ {
AutoCrit autoCrit(mCodeGen->mCacheCritSect); AutoCrit autoCrit(mCodeGen->mCacheCritSect);
dirCache->SetHash(cacheFileName, hash, orderedHash, !isLibWrite); dirCache->SetHash(cacheFileName, hash, orderedHash, !isLibWrite);
} }
#endif #endif
@ -416,7 +413,7 @@ void BfCodeGenThread::RunLoop()
// //
} }
else if (request->mOptions.mOptLevel == BfOptLevel_OgPlus) else if (request->mOptions.mOptLevel == BfOptLevel_OgPlus)
{ {
#ifdef BF_PLATFORM_WINDOWS #ifdef BF_PLATFORM_WINDOWS
BP_ZONE("BfCodeGen::RunLoop.Beef"); BP_ZONE("BfCodeGen::RunLoop.Beef");
@ -432,7 +429,7 @@ void BfCodeGenThread::RunLoop()
{ {
if (!errorMsg.empty()) if (!errorMsg.empty())
errorMsg += "\n"; errorMsg += "\n";
errorMsg += "Failed writing IR '" + fileName + "': " + ec.message(); errorMsg += "Failed writing IR '" + fileName + "': " + ec.message();
} }
else else
fs.WriteSNZ(str); fs.WriteSNZ(str);
@ -445,9 +442,9 @@ void BfCodeGenThread::RunLoop()
BfLogX(2, "Generating obj %s\n", request->mOutFileName.c_str()); BfLogX(2, "Generating obj %s\n", request->mOutFileName.c_str());
BeCOFFObject coffObject; BeCOFFObject coffObject;
coffObject.mWriteToLib = request->mOptions.mWriteToLib; coffObject.mWriteToLib = request->mOptions.mWriteToLib;
if (!coffObject.Generate(beIRCodeGen->mBeModule, objFileName)) if (!coffObject.Generate(beIRCodeGen->mBeModule, objFileName))
errorMsg = StrFormat("Failed to write object file: %s", objFileName.c_str()); errorMsg = StrFormat("Failed to write object file: %s", objFileName.c_str());
if (!beIRCodeGen->mErrorMsg.IsEmpty()) if (!beIRCodeGen->mErrorMsg.IsEmpty())
{ {
@ -467,14 +464,14 @@ void BfCodeGenThread::RunLoop()
BfIRCodeGen* llvmIRCodeGen = new BfIRCodeGen(); BfIRCodeGen* llvmIRCodeGen = new BfIRCodeGen();
llvmIRCodeGen->SetCodeGenOptions(request->mOptions); llvmIRCodeGen->SetCodeGenOptions(request->mOptions);
llvmIRCodeGen->SetConfigConst(BfIRConfigConst_VirtualMethodOfs, request->mOptions.mVirtualMethodOfs); llvmIRCodeGen->SetConfigConst(BfIRConfigConst_VirtualMethodOfs, request->mOptions.mVirtualMethodOfs);
llvmIRCodeGen->SetConfigConst(BfIRConfigConst_DynSlotOfs, request->mOptions.mDynSlotOfs); llvmIRCodeGen->SetConfigConst(BfIRConfigConst_DynSlotOfs, request->mOptions.mDynSlotOfs);
llvmIRCodeGen->ProcessBfIRData(request->mData); llvmIRCodeGen->ProcessBfIRData(request->mData);
errorMsg = llvmIRCodeGen->mErrorMsg; errorMsg = llvmIRCodeGen->mErrorMsg;
llvmIRCodeGen->mErrorMsg.Clear(); llvmIRCodeGen->mErrorMsg.Clear();
if (errorMsg.IsEmpty()) if (errorMsg.IsEmpty())
{ {
if (request->mOptions.mWriteLLVMIR) if (request->mOptions.mWriteLLVMIR)
{ {
BP_ZONE("BfCodeGen::RunLoop.LLVM.IR"); BP_ZONE("BfCodeGen::RunLoop.LLVM.IR");
@ -503,16 +500,16 @@ void BfCodeGenThread::RunLoop()
result.mType = BfCodeGenResult_Failed; result.mType = BfCodeGenResult_Failed;
dirCache->FileFailed(); dirCache->FileFailed();
} }
} }
} }
if (!llvmIRCodeGen->mErrorMsg.IsEmpty()) if (!llvmIRCodeGen->mErrorMsg.IsEmpty())
{ {
if (!errorMsg.IsEmpty()) if (!errorMsg.IsEmpty())
errorMsg += "\n"; errorMsg += "\n";
errorMsg += llvmIRCodeGen->mErrorMsg; errorMsg += llvmIRCodeGen->mErrorMsg;
} }
delete llvmIRCodeGen; delete llvmIRCodeGen;
} }
} }
@ -538,9 +535,9 @@ void BfCodeGenThread::RunLoop()
// It's an extern request, so we own this // It's an extern request, so we own this
bool deleteRequest = false; bool deleteRequest = false;
if (request->mExternResultPtr != NULL) if (request->mExternResultPtr != NULL)
{ {
*request->mExternResultPtr = result; *request->mExternResultPtr = result;
deleteRequest = true; deleteRequest = true;
} }
// We need this fence for BF_USE_CODEGEN_RELEASE_THUNK usage- because we can't access the request anymore after setting // We need this fence for BF_USE_CODEGEN_RELEASE_THUNK usage- because we can't access the request anymore after setting
@ -549,21 +546,21 @@ void BfCodeGenThread::RunLoop()
AutoCrit autoCrit(mCodeGen->mPendingRequestCritSect); AutoCrit autoCrit(mCodeGen->mPendingRequestCritSect);
request->mResult = result; request->mResult = result;
mCodeGen->mDoneEvent.Set(); mCodeGen->mDoneEvent.Set();
if (deleteRequest) if (deleteRequest)
delete request; delete request;
} }
} }
mRunning = false; mRunning = false;
mCodeGen->mDoneEvent.Set(); mCodeGen->mDoneEvent.Set();
} }
void BfCodeGenThread::Shutdown() void BfCodeGenThread::Shutdown()
{ {
mShuttingDown = true; mShuttingDown = true;
if (mRunning) if (mRunning)
mCodeGen->mRequestEvent.Set(true); mCodeGen->mRequestEvent.Set(true);
while (mRunning) while (mRunning)
{ {
@ -580,11 +577,11 @@ static void BFP_CALLTYPE RunLoopThunk(void* codeGenThreadP)
void BfCodeGenThread::Start() void BfCodeGenThread::Start()
{ {
mRunning = true; mRunning = true;
//TODO: How much mem do we need? WTF- we have 32MB set before! //TODO: How much mem do we need? WTF- we have 32MB set before!
auto mThread = BfpThread_Create(RunLoopThunk, (void*)this, 1024 * 1024, BfpThreadCreateFlag_StackSizeReserve); auto mThread = BfpThread_Create(RunLoopThunk, (void*)this, 1024 * 1024, BfpThreadCreateFlag_StackSizeReserve);
BfpThread_SetPriority(mThread, BfpThreadPriority_Low, NULL); BfpThread_SetPriority(mThread, BfpThreadPriority_Low, NULL);
BfpThread_Release(mThread); BfpThread_Release(mThread);
} }
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
@ -592,7 +589,7 @@ void BfCodeGenThread::Start()
BfCodeGen::BfCodeGen() BfCodeGen::BfCodeGen()
{ {
mAttemptedReleaseThunkLoad = false; mAttemptedReleaseThunkLoad = false;
mIsUsingReleaseThunk = false; mIsUsingReleaseThunk = false;
mReleaseModule = NULL; mReleaseModule = NULL;
mClearCacheFunc = NULL; mClearCacheFunc = NULL;
mGetVersionFunc = NULL; mGetVersionFunc = NULL;
@ -600,10 +597,10 @@ BfCodeGen::BfCodeGen()
mCancelFunc = NULL; mCancelFunc = NULL;
mFinishFunc = NULL; mFinishFunc = NULL;
mGenerateObjFunc = NULL; mGenerateObjFunc = NULL;
mRequestIdx = 0; mRequestIdx = 0;
#ifdef MAX_THREADS #ifdef MAX_THREADS
mMaxThreadCount = MAX_THREADS; mMaxThreadCount = MAX_THREADS;
#else #else
mMaxThreadCount = 6; mMaxThreadCount = 6;
#endif #endif
@ -703,7 +700,7 @@ void BfCodeGen::UpdateStats()
auto request = mRequests[0]; auto request = mRequests[0];
if (request->mResult.mType == BfCodeGenResult_NotDone) if (request->mResult.mType == BfCodeGenResult_NotDone)
return; return;
RequestComplete(request); RequestComplete(request);
delete request; delete request;
mRequests.RemoveAt(0); mRequests.RemoveAt(0);
@ -732,7 +729,7 @@ void BfCodeGen::ClearBuildCache()
for (auto& dirCachePair : mDirectoryCache) for (auto& dirCachePair : mDirectoryCache)
{ {
auto dirData = dirCachePair.mValue; auto dirData = dirCachePair.mValue;
dirData->Clear(); dirData->Clear();
} }
// This just disables reading the cache file, but it does not disable creating // This just disables reading the cache file, but it does not disable creating
// the cache structes in memory and writing them out, thus it's valid to leave // the cache structes in memory and writing them out, thus it's valid to leave
@ -747,9 +744,9 @@ void BfCodeGen::ClearBuildCache()
} }
void BfCodeGen::DoWriteObjectFile(BfCodeGenRequest* codeGenRequest, const void* ptr, int size, const StringImpl& outFileName, BfCodeGenResult* externResultPtr) void BfCodeGen::DoWriteObjectFile(BfCodeGenRequest* codeGenRequest, const void* ptr, int size, const StringImpl& outFileName, BfCodeGenResult* externResultPtr)
{ {
codeGenRequest->mData.mVals = (uint8*)ptr; codeGenRequest->mData.mVals = (uint8*)ptr;
codeGenRequest->mData.mSize = size; codeGenRequest->mData.mSize = size;
codeGenRequest->mOutFileName = outFileName; codeGenRequest->mOutFileName = outFileName;
codeGenRequest->mResult.mType = BfCodeGenResult_NotDone; codeGenRequest->mResult.mType = BfCodeGenResult_NotDone;
codeGenRequest->mResult.mErrorMsgBufLen = 0; codeGenRequest->mResult.mErrorMsgBufLen = 0;
@ -769,11 +766,11 @@ void BfCodeGen::DoWriteObjectFile(BfCodeGenRequest* codeGenRequest, const void*
auto thread = mThreads[threadIdx]; auto thread = mThreads[threadIdx];
BP_ZONE("WriteObjectFile_CritSect"); BP_ZONE("WriteObjectFile_CritSect");
AutoCrit autoCrit(mPendingRequestCritSect); AutoCrit autoCrit(mPendingRequestCritSect);
mPendingRequests.push_back(codeGenRequest); mPendingRequests.push_back(codeGenRequest);
#ifdef BF_PLATFORM_WINDOWS #ifdef BF_PLATFORM_WINDOWS
BF_ASSERT(!mRequestEvent.mEvent->mManualReset); // Make sure it's out of the SignalAll state BF_ASSERT(!mRequestEvent.mEvent->mManualReset); // Make sure it's out of the SignalAll state
#endif #endif
mRequestEvent.Set(); mRequestEvent.Set();
@ -843,11 +840,11 @@ bool BfCodeGen::ExternWriteObjectFile(BfCodeGenRequest* codeGenRequest)
#ifndef BF_USE_CODEGEN_RELEASE_THUNK #ifndef BF_USE_CODEGEN_RELEASE_THUNK
return false; return false;
#endif #endif
BindReleaseThunks(); BindReleaseThunks();
if (!mIsUsingReleaseThunk) if (!mIsUsingReleaseThunk)
return false; return false;
mGenerateObjFunc(codeGenRequest->mData.mVals, codeGenRequest->mData.mSize, codeGenRequest->mOutFileName.c_str(), &codeGenRequest->mResult, codeGenRequest->mOptions); mGenerateObjFunc(codeGenRequest->mData.mVals, codeGenRequest->mData.mSize, codeGenRequest->mOutFileName.c_str(), &codeGenRequest->mResult, codeGenRequest->mOptions);
@ -855,15 +852,15 @@ bool BfCodeGen::ExternWriteObjectFile(BfCodeGenRequest* codeGenRequest)
} }
void BfCodeGen::WriteObjectFile(BfModule* bfModule, const StringImpl& outFileName, const BfCodeGenOptions& options) void BfCodeGen::WriteObjectFile(BfModule* bfModule, const StringImpl& outFileName, const BfCodeGenOptions& options)
{ {
mQueuedCount++; mQueuedCount++;
BfLogSys(bfModule->mSystem, "WriteObjectFile %s\n", outFileName.c_str()); BfLogSys(bfModule->mSystem, "WriteObjectFile %s\n", outFileName.c_str());
BfCodeGenRequest* codeGenRequest = new BfCodeGenRequest(); BfCodeGenRequest* codeGenRequest = new BfCodeGenRequest();
mRequests.push_back(codeGenRequest); mRequests.push_back(codeGenRequest);
{ {
BP_ZONE("WriteObjectFile_GetBufferData"); BP_ZONE("WriteObjectFile_GetBufferData");
bfModule->mBfIRBuilder->GetBufferData(codeGenRequest->mOutBuffer); bfModule->mBfIRBuilder->GetBufferData(codeGenRequest->mOutBuffer);
} }
@ -873,13 +870,13 @@ void BfCodeGen::WriteObjectFile(BfModule* bfModule, const StringImpl& outFileNam
rootModule = rootModule->mParentModule; rootModule = rootModule->mParentModule;
codeGenRequest->mSrcModule = rootModule; codeGenRequest->mSrcModule = rootModule;
codeGenRequest->mOutFileName = outFileName; codeGenRequest->mOutFileName = outFileName;
codeGenRequest->mData = codeGenRequest->mOutBuffer; codeGenRequest->mData = codeGenRequest->mOutBuffer;
codeGenRequest->mOptions = options; codeGenRequest->mOptions = options;
if (ExternWriteObjectFile(codeGenRequest)) if (ExternWriteObjectFile(codeGenRequest))
return; return;
DoWriteObjectFile(codeGenRequest, (void*)&codeGenRequest->mOutBuffer[0], (int)codeGenRequest->mOutBuffer.size(), codeGenRequest->mOutFileName, NULL); DoWriteObjectFile(codeGenRequest, (void*)&codeGenRequest->mOutBuffer[0], (int)codeGenRequest->mOutBuffer.size(), codeGenRequest->mOutFileName, NULL);
#ifdef DBG_FORCE_SYNCHRONIZED #ifdef DBG_FORCE_SYNCHRONIZED
while (mRequests.size() != 0) while (mRequests.size() != 0)
@ -918,7 +915,7 @@ void BfCodeGen::RequestComplete(BfCodeGenRequest* request)
if ((request->mResult.mType == BfCodeGenResult_Failed) || (request->mResult.mType == BfCodeGenResult_Aborted)) if ((request->mResult.mType == BfCodeGenResult_Failed) || (request->mResult.mType == BfCodeGenResult_Aborted))
{ {
BfCodeGenErrorEntry errorEntry; BfCodeGenErrorEntry errorEntry;
errorEntry.mSrcModule = request->mSrcModule; errorEntry.mSrcModule = request->mSrcModule;
errorEntry.mOutFileName = request->mOutFileName; errorEntry.mOutFileName = request->mOutFileName;
int errorPos = 0; int errorPos = 0;
@ -928,7 +925,7 @@ void BfCodeGen::RequestComplete(BfCodeGenRequest* request)
errorEntry.mErrorMessages.push_back(errorStr); errorEntry.mErrorMessages.push_back(errorStr);
errorPos += (int)strlen(errorStr) + 1; errorPos += (int)strlen(errorStr) + 1;
} }
mFailedRequests.push_back(errorEntry); mFailedRequests.push_back(errorEntry);
} }
else else
@ -970,7 +967,7 @@ void BfCodeGen::ProcessErrors(BfPassInstance* passInstance, bool canceled)
{ {
passInstance->Fail(dirEntry->mError); passInstance->Fail(dirEntry->mError);
showedCacheError = true; showedCacheError = true;
} }
dirEntry->mError.clear(); dirEntry->mError.clear();
} }
} }
@ -1000,7 +997,7 @@ void BfCodeGen::Cancel()
{ {
for (auto thread : mThreads) for (auto thread : mThreads)
{ {
thread->mShuttingDown = true; thread->mShuttingDown = true;
} }
mRequestEvent.Set(true); mRequestEvent.Set(true);
@ -1016,9 +1013,9 @@ void BfCodeGen::ClearResults()
} }
bool BfCodeGen::Finish() bool BfCodeGen::Finish()
{ {
BP_ZONE("BfCodeGen::Finish"); BP_ZONE("BfCodeGen::Finish");
while (mRequests.size() != 0) while (mRequests.size() != 0)
{ {
auto request = mRequests[0]; auto request = mRequests[0];
@ -1047,7 +1044,7 @@ bool BfCodeGen::Finish()
return false; return false;
} }
if (mIsUsingReleaseThunk) if (mIsUsingReleaseThunk)
{ {
// Make the thunk release its threads (and more important, its LLVM contexts) // Make the thunk release its threads (and more important, its LLVM contexts)
mFinishFunc(); mFinishFunc();
@ -1056,14 +1053,14 @@ bool BfCodeGen::Finish()
// We need to shut down these threads to remove their memory // We need to shut down these threads to remove their memory
for (auto thread : mThreads) for (auto thread : mThreads)
{ {
thread->mShuttingDown = true; thread->mShuttingDown = true;
mOldThreads.push_back(thread); mOldThreads.push_back(thread);
} }
mThreads.Clear(); mThreads.Clear();
mRequestEvent.Set(true); mRequestEvent.Set(true);
ClearOldThreads(false); ClearOldThreads(false);
// for (auto request : mPendingRequests) // for (auto request : mPendingRequests)
// { // {
// if (request->mExternResultPtr != NULL) // if (request->mExternResultPtr != NULL)
@ -1073,7 +1070,7 @@ bool BfCodeGen::Finish()
// } // }
// //request->mResult.mType = BfCodeGenResult_Aborted; // //request->mResult.mType = BfCodeGenResult_Aborted;
// //delete request; // //delete request;
// } // }
// mPendingRequests.Clear(); // mPendingRequests.Clear();
/// ///
@ -1113,8 +1110,8 @@ BF_EXPORT int BF_CALLTYPE BfCodeGen_GetVersion()
BF_EXPORT void BF_CALLTYPE BfCodeGen_ClearCache() BF_EXPORT void BF_CALLTYPE BfCodeGen_ClearCache()
{ {
GetExternCodeGen(); GetExternCodeGen();
gExternCodeGen->ClearBuildCache(); gExternCodeGen->ClearBuildCache();
} }
BF_EXPORT void BF_CALLTYPE BfCodeGen_Finish() BF_EXPORT void BF_CALLTYPE BfCodeGen_Finish()
@ -1129,7 +1126,7 @@ BF_EXPORT void BF_CALLTYPE BfCodeGen_Finish()
BF_EXPORT void BF_CALLTYPE BfCodeGen_Kill() BF_EXPORT void BF_CALLTYPE BfCodeGen_Kill()
{ {
delete gExternCodeGen; delete gExternCodeGen;
gExternCodeGen = NULL; gExternCodeGen = NULL;
Targets_Delete(); Targets_Delete();
} }
@ -1140,11 +1137,10 @@ BF_EXPORT void BF_CALLTYPE BfCodeGen_Cancel()
} }
BF_EXPORT void BF_CALLTYPE BfCodeGen_GenerateObj(const void* ptr, int size, const char* outFileName, BfCodeGenResult* resultPtr, const BfCodeGenOptions& options) BF_EXPORT void BF_CALLTYPE BfCodeGen_GenerateObj(const void* ptr, int size, const char* outFileName, BfCodeGenResult* resultPtr, const BfCodeGenOptions& options)
{ {
GetExternCodeGen(); GetExternCodeGen();
BfCodeGenRequest* codeGenRequest = new BfCodeGenRequest(); BfCodeGenRequest* codeGenRequest = new BfCodeGenRequest();
codeGenRequest->mOptions = options; codeGenRequest->mOptions = options;
gExternCodeGen->DoWriteObjectFile(codeGenRequest, ptr, size, outFileName, resultPtr); gExternCodeGen->DoWriteObjectFile(codeGenRequest, ptr, size, outFileName, resultPtr);
} }

View file

@ -45,16 +45,15 @@ public:
Array<String> mErrorMessages; Array<String> mErrorMessages;
}; };
class BfCodeGenRequest class BfCodeGenRequest
{ {
public: public:
BfModule* mSrcModule; BfModule* mSrcModule;
BfCodeGenOptions mOptions; BfCodeGenOptions mOptions;
BfCodeGenResult mResult; BfCodeGenResult mResult;
Array<uint8> mOutBuffer; Array<uint8> mOutBuffer;
BfSizedArray<uint8> mData; BfSizedArray<uint8> mData;
String mOutFileName; String mOutFileName;
BfCodeGenResult* mExternResultPtr; BfCodeGenResult* mExternResultPtr;
@ -64,13 +63,13 @@ public:
mSrcModule = NULL; mSrcModule = NULL;
mResult.mType = BfCodeGenResult_NotDone; mResult.mType = BfCodeGenResult_NotDone;
mResult.mErrorMsgBufLen = 0; mResult.mErrorMsgBufLen = 0;
mExternResultPtr = NULL; mExternResultPtr = NULL;
} }
~BfCodeGenRequest() ~BfCodeGenRequest()
{ {
} }
void DbgSaveData(); void DbgSaveData();
}; };
@ -78,18 +77,18 @@ class BfCodeGen;
class BfCodeGenThread class BfCodeGenThread
{ {
public: public:
BfCodeGen* mCodeGen; BfCodeGen* mCodeGen;
int mThreadIdx; int mThreadIdx;
//std::vector<BfCodeGenRequest*> mRequests; //std::vector<BfCodeGenRequest*> mRequests;
volatile bool mShuttingDown; volatile bool mShuttingDown;
volatile bool mRunning; volatile bool mRunning;
public: public:
bool RawWriteObjectFile(llvm::Module* module, const StringImpl& outFileName, const BfCodeGenOptions& codeGenOptions); bool RawWriteObjectFile(llvm::Module* module, const StringImpl& outFileName, const BfCodeGenOptions& codeGenOptions);
public: public:
BfCodeGenThread(); BfCodeGenThread();
~BfCodeGenThread(); ~BfCodeGenThread();
@ -103,7 +102,7 @@ class BfCodeGenFileData
{ {
public: public:
Val128 mIRHash; // Equal when exact IR bits are equal Val128 mIRHash; // Equal when exact IR bits are equal
Val128 mIROrderedHash; // Equal when isomorphic (when alphabetically reordered functions hash equally) Val128 mIROrderedHash; // Equal when isomorphic (when alphabetically reordered functions hash equally)
bool mLastWasObjectWrite; bool mLastWasObjectWrite;
}; };
@ -115,7 +114,7 @@ public:
Dictionary<String, String> mBuildSettings; Dictionary<String, String> mBuildSettings;
String mDirectoryName; String mDirectoryName;
bool mDirty; bool mDirty;
bool mVerified; bool mVerified;
int64 mFileTime; int64 mFileTime;
String mError; String mError;
bool mFileFailed; bool mFileFailed;
@ -163,18 +162,18 @@ public:
typedef void (BF_CALLTYPE* FinishFunc)(); typedef void (BF_CALLTYPE* FinishFunc)();
typedef void (BF_CALLTYPE* GenerateObjFunc)(const void* ptr, int size, const char* outFileName, BfCodeGenResult* resultPtr, const BfCodeGenOptions& options); typedef void (BF_CALLTYPE* GenerateObjFunc)(const void* ptr, int size, const char* outFileName, BfCodeGenResult* resultPtr, const BfCodeGenOptions& options);
public: public:
BfpDynLib* mReleaseModule; BfpDynLib* mReleaseModule;
bool mAttemptedReleaseThunkLoad; bool mAttemptedReleaseThunkLoad;
bool mIsUsingReleaseThunk; bool mIsUsingReleaseThunk;
ClearCacheFunc mClearCacheFunc; ClearCacheFunc mClearCacheFunc;
GetVersionFunc mGetVersionFunc; GetVersionFunc mGetVersionFunc;
KillFunc mKillFunc; KillFunc mKillFunc;
CancelFunc mCancelFunc; CancelFunc mCancelFunc;
FinishFunc mFinishFunc; FinishFunc mFinishFunc;
GenerateObjFunc mGenerateObjFunc; GenerateObjFunc mGenerateObjFunc;
Val128 mBackendHash; Val128 mBackendHash;
int mMaxThreadCount; int mMaxThreadCount;
CritSect mThreadsCritSect; CritSect mThreadsCritSect;
Array<BfCodeGenThread*> mThreads; Array<BfCodeGenThread*> mThreads;
@ -184,19 +183,19 @@ public:
Deque<BfCodeGenRequest*> mPendingRequests; Deque<BfCodeGenRequest*> mPendingRequests;
SyncEvent mRequestEvent; SyncEvent mRequestEvent;
int mRequestIdx; int mRequestIdx;
SyncEvent mDoneEvent; SyncEvent mDoneEvent;
int mQueuedCount; int mQueuedCount;
int mCompletionCount; int mCompletionCount;
Array<BfCodeGenErrorEntry> mFailedRequests; Array<BfCodeGenErrorEntry> mFailedRequests;
Array<BfCodeGenFileEntry> mCodeGenFiles; Array<BfCodeGenFileEntry> mCodeGenFiles;
CritSect mCacheCritSect; CritSect mCacheCritSect;
bool mDisableCacheReads; bool mDisableCacheReads;
Dictionary<String, BfCodeGenDirectoryData*> mDirectoryCache; Dictionary<String, BfCodeGenDirectoryData*> mDirectoryCache;
public: public:
void SetMaxThreads(int maxThreads); void SetMaxThreads(int maxThreads);
void BindReleaseThunks(); void BindReleaseThunks();
void ClearResults(); void ClearResults();
@ -208,13 +207,13 @@ public:
void ProcessErrors(BfPassInstance* passInstance, bool canceled); void ProcessErrors(BfPassInstance* passInstance, bool canceled);
BfCodeGenDirectoryData* GetDirCache(const StringImpl& cacheDir); BfCodeGenDirectoryData* GetDirCache(const StringImpl& cacheDir);
public: public:
BfCodeGen(); BfCodeGen();
~BfCodeGen(); ~BfCodeGen();
void ResetStats(); void ResetStats();
void UpdateStats(); void UpdateStats();
void WriteObjectFile(BfModule* module, const StringImpl& outFileName, const BfCodeGenOptions& options); void WriteObjectFile(BfModule* module, const StringImpl& outFileName, const BfCodeGenOptions& options);
String GetBuildValue(const StringImpl& buildDir, const StringImpl& key); String GetBuildValue(const StringImpl& buildDir, const StringImpl& key);
void SetBuildValue(const StringImpl& buildDir, const StringImpl& key, const StringImpl& value); void SetBuildValue(const StringImpl& buildDir, const StringImpl& key, const StringImpl& value);
void WriteBuildCache(const StringImpl& buildDir); void WriteBuildCache(const StringImpl& buildDir);

File diff suppressed because it is too large Load diff

View file

@ -50,7 +50,7 @@ enum BfCompileOnDemandKind
BfCompileOnDemandKind_SkipUnused BfCompileOnDemandKind_SkipUnused
}; };
class BfCompiler class BfCompiler
{ {
public: public:
enum CompileState enum CompileState
@ -63,22 +63,22 @@ public:
}; };
struct Stats struct Stats
{ {
int mTotalTypes; int mTotalTypes;
int mMethodDeclarations; int mMethodDeclarations;
int mTypesPopulated; int mTypesPopulated;
int mMethodsProcessed; int mMethodsProcessed;
int mUnreifiedMethodsProcessed; int mUnreifiedMethodsProcessed;
int mQueuedTypesProcessed; int mQueuedTypesProcessed;
int mTypesQueued; int mTypesQueued;
int mTypesDeleted; int mTypesDeleted;
int mMethodsQueued; int mMethodsQueued;
int mModulesStarted; int mModulesStarted;
int mModulesFinished; int mModulesFinished;
int mModulesReified; int mModulesReified;
int mModulesUnreified; int mModulesUnreified;
@ -94,19 +94,19 @@ public:
{ {
BfProject* mHotProject; BfProject* mHotProject;
int mHotCompileIdx; int mHotCompileIdx;
int32 mForceRebuildIdx; int32 mForceRebuildIdx;
BfCompileOnDemandKind mCompileOnDemandKind; BfCompileOnDemandKind mCompileOnDemandKind;
String mTargetTriple; String mTargetTriple;
String mTargetCPU; String mTargetCPU;
BfPlatformType mPlatformType; BfPlatformType mPlatformType;
BfMachineType mMachineType; BfMachineType mMachineType;
int mCLongSize; int mCLongSize;
BfToolsetType mToolsetType; BfToolsetType mToolsetType;
BfSIMDSetting mSIMDSetting; BfSIMDSetting mSIMDSetting;
String mMallocLinkName; String mMallocLinkName;
String mFreeLinkName; String mFreeLinkName;
bool mIncrementalBuild; bool mIncrementalBuild;
bool mEmitDebugInfo; bool mEmitDebugInfo;
bool mEmitLineInfo; bool mEmitLineInfo;
@ -116,15 +116,15 @@ public:
bool mRuntimeChecks; bool mRuntimeChecks;
bool mAllowStructByVal; bool mAllowStructByVal;
bool mEmitDynamicCastCheck; bool mEmitDynamicCastCheck;
bool mAllowHotSwapping; bool mAllowHotSwapping;
bool mObjectHasDebugFlags; bool mObjectHasDebugFlags;
bool mEnableRealtimeLeakCheck; bool mEnableRealtimeLeakCheck;
bool mEmitObjectAccessCheck; // Only valid with mObjectHasDebugFlags bool mEmitObjectAccessCheck; // Only valid with mObjectHasDebugFlags
bool mArithmeticChecks; bool mArithmeticChecks;
bool mEnableCustodian; bool mEnableCustodian;
bool mEnableSideStack; bool mEnableSideStack;
bool mHasVDataExtender; bool mHasVDataExtender;
bool mDebugAlloc; bool mDebugAlloc;
bool mOmitDebugHelpers; bool mOmitDebugHelpers;
@ -167,7 +167,7 @@ public:
mAllowHotSwapping = false; mAllowHotSwapping = false;
mEmitObjectAccessCheck = false; mEmitObjectAccessCheck = false;
mArithmeticChecks = false; mArithmeticChecks = false;
mObjectHasDebugFlags = false; mObjectHasDebugFlags = false;
mEnableRealtimeLeakCheck = false; mEnableRealtimeLeakCheck = false;
mWriteIR = false; mWriteIR = false;
mGenerateObj = true; mGenerateObj = true;
@ -195,19 +195,19 @@ public:
} }
}; };
Options mOptions; Options mOptions;
enum HotTypeFlags enum HotTypeFlags
{ {
HotTypeFlag_None = 0, HotTypeFlag_None = 0,
HotTypeFlag_UserNotUsed = 1, HotTypeFlag_UserNotUsed = 1,
HotTypeFlag_UserUsed = 2, HotTypeFlag_UserUsed = 2,
HotTypeFlag_Heap = 4, HotTypeFlag_Heap = 4,
HotTypeFlag_ActiveFunction = 8, // Only set for a type version mismatch HotTypeFlag_ActiveFunction = 8, // Only set for a type version mismatch
HotTypeFlag_Delegate = 0x10, // Only set for a type version mismatch HotTypeFlag_Delegate = 0x10, // Only set for a type version mismatch
HotTypeFlag_FuncPtr = 0x20, // Only set for a type version mismatch HotTypeFlag_FuncPtr = 0x20, // Only set for a type version mismatch
HotTypeFlag_CanAllocate = 0x40 HotTypeFlag_CanAllocate = 0x40
}; };
enum HotResolveFlags enum HotResolveFlags
{ {
@ -237,7 +237,7 @@ public:
Array<HotTypeFlags> mHotTypeIdFlags; Array<HotTypeFlags> mHotTypeIdFlags;
Array<BfHotDepData*> mReasons; Array<BfHotDepData*> mReasons;
HashSet<BfHotMethod*> mDeferredThisCheckMethods; HashSet<BfHotMethod*> mDeferredThisCheckMethods;
~HotResolveData(); ~HotResolveData();
}; };
@ -261,7 +261,7 @@ public:
BfHotThisType* GetThisType(BfHotTypeVersion* hotVersion); BfHotThisType* GetThisType(BfHotTypeVersion* hotVersion);
BfHotAllocation* GetAllocation(BfHotTypeVersion* hotVersion); BfHotAllocation* GetAllocation(BfHotTypeVersion* hotVersion);
BfHotDevirtualizedMethod* GetDevirtualizedMethod(BfHotMethod* hotMethod); BfHotDevirtualizedMethod* GetDevirtualizedMethod(BfHotMethod* hotMethod);
BfHotFunctionReference* GetFunctionReference(BfHotMethod* hotMethod); BfHotFunctionReference* GetFunctionReference(BfHotMethod* hotMethod);
BfHotVirtualDeclaration* GetVirtualDeclaration(BfHotMethod* hotMethod); BfHotVirtualDeclaration* GetVirtualDeclaration(BfHotMethod* hotMethod);
BfHotInnerMethod* GetInnerMethod(BfHotMethod* hotMethod); BfHotInnerMethod* GetInnerMethod(BfHotMethod* hotMethod);
}; };
@ -270,10 +270,10 @@ public:
{ {
public: public:
BfProject* mHotProject; BfProject* mHotProject;
int mLastStringId; int mLastStringId;
int mCommittedHotCompileIdx; int mCommittedHotCompileIdx;
bool mHasNewTypes; bool mHasNewTypes;
bool mHasNewInterfaceTypes; bool mHasNewInterfaceTypes;
Array<BfCodeGenFileEntry> mQueuedOutFiles; // Queues up when we have failed hot compiles Array<BfCodeGenFileEntry> mQueuedOutFiles; // Queues up when we have failed hot compiles
HashSet<int> mSlotDefineTypeIds; HashSet<int> mSlotDefineTypeIds;
HashSet<int> mNewlySlottedTypeIds; HashSet<int> mNewlySlottedTypeIds;
@ -284,7 +284,7 @@ public:
public: public:
HotState() HotState()
{ {
mHotProject = NULL; mHotProject = NULL;
mLastStringId = -1; mLastStringId = -1;
mCommittedHotCompileIdx = 0; mCommittedHotCompileIdx = 0;
@ -298,28 +298,28 @@ public:
void RemovePendingChanges(BfTypeInstance* type); void RemovePendingChanges(BfTypeInstance* type);
}; };
HotData* mHotData; HotData* mHotData;
HotState* mHotState; HotState* mHotState;
HotResolveData* mHotResolveData; HotResolveData* mHotResolveData;
struct StringValueEntry struct StringValueEntry
{ {
int mId; int mId;
BfIRValue mStringVal; BfIRValue mStringVal;
}; };
struct TestMethod struct TestMethod
{ {
String mName; String mName;
BfMethodInstance* mMethodInstance; BfMethodInstance* mMethodInstance;
}; };
public: public:
BfPassInstance* mPassInstance; BfPassInstance* mPassInstance;
FILE* mCompileLogFP; FILE* mCompileLogFP;
CeMachine* mCeMachine; CeMachine* mCeMachine;
int mCurCEExecuteId; int mCurCEExecuteId;
BfSystem* mSystem; BfSystem* mSystem;
bool mIsResolveOnly; bool mIsResolveOnly;
BfResolvePassData* mResolvePassData; BfResolvePassData* mResolvePassData;
Dictionary<String, Array<int>> mAttributeTypeOptionMap; Dictionary<String, Array<int>> mAttributeTypeOptionMap;
@ -343,13 +343,13 @@ public:
bool mDepsMayHaveDeletedTypes; bool mDepsMayHaveDeletedTypes;
float mCompletionPct; float mCompletionPct;
int mHSPreserveIdx; int mHSPreserveIdx;
BfModule* mLastAutocompleteModule; BfModule* mLastAutocompleteModule;
CompileState mCompileState; CompileState mCompileState;
HashSet<String> mRebuildFileSet; HashSet<String> mRebuildFileSet;
HashSet<String> mRebuildChangedFileSet; // Files we had actual changes from HashSet<String> mRebuildChangedFileSet; // Files we had actual changes from
Array<BfVDataModule*> mVDataModules; Array<BfVDataModule*> mVDataModules;
BfTypeDef* mBfObjectTypeDef; BfTypeDef* mBfObjectTypeDef;
BfTypeDef* mChar32TypeDef; BfTypeDef* mChar32TypeDef;
BfTypeDef* mFloatTypeDef; BfTypeDef* mFloatTypeDef;
@ -360,16 +360,16 @@ public:
BfTypeDef* mArray2TypeDef; BfTypeDef* mArray2TypeDef;
BfTypeDef* mArray3TypeDef; BfTypeDef* mArray3TypeDef;
BfTypeDef* mArray4TypeDef; BfTypeDef* mArray4TypeDef;
BfTypeDef* mSpanTypeDef; BfTypeDef* mSpanTypeDef;
BfTypeDef* mRangeTypeDef; BfTypeDef* mRangeTypeDef;
BfTypeDef* mClosedRangeTypeDef; BfTypeDef* mClosedRangeTypeDef;
BfTypeDef* mIndexTypeDef; BfTypeDef* mIndexTypeDef;
BfTypeDef* mIndexRangeTypeDef; BfTypeDef* mIndexRangeTypeDef;
BfTypeDef* mClassVDataTypeDef; BfTypeDef* mClassVDataTypeDef;
BfTypeDef* mDbgRawAllocDataTypeDef; BfTypeDef* mDbgRawAllocDataTypeDef;
BfTypeDef* mDeferredCallTypeDef; BfTypeDef* mDeferredCallTypeDef;
BfTypeDef* mDelegateTypeDef; BfTypeDef* mDelegateTypeDef;
BfTypeDef* mFunctionTypeDef; BfTypeDef* mFunctionTypeDef;
BfTypeDef* mActionTypeDef; BfTypeDef* mActionTypeDef;
@ -377,13 +377,13 @@ public:
BfTypeDef* mStringTypeDef; BfTypeDef* mStringTypeDef;
BfTypeDef* mStringViewTypeDef; BfTypeDef* mStringViewTypeDef;
BfTypeDef* mTypeTypeDef; BfTypeDef* mTypeTypeDef;
BfTypeDef* mValueTypeTypeDef; BfTypeDef* mValueTypeTypeDef;
BfTypeDef* mResultTypeDef; BfTypeDef* mResultTypeDef;
BfTypeDef* mGCTypeDef; BfTypeDef* mGCTypeDef;
BfTypeDef* mGenericIEnumerableTypeDef; BfTypeDef* mGenericIEnumerableTypeDef;
BfTypeDef* mGenericIEnumeratorTypeDef; BfTypeDef* mGenericIEnumeratorTypeDef;
BfTypeDef* mGenericIRefEnumeratorTypeDef; BfTypeDef* mGenericIRefEnumeratorTypeDef;
BfTypeDef* mThreadTypeDef; BfTypeDef* mThreadTypeDef;
BfTypeDef* mInternalTypeDef; BfTypeDef* mInternalTypeDef;
BfTypeDef* mPlatformTypeDef; BfTypeDef* mPlatformTypeDef;
@ -395,15 +395,15 @@ public:
BfTypeDef* mIPrintableTypeDef; BfTypeDef* mIPrintableTypeDef;
BfTypeDef* mIHashableTypeDef; BfTypeDef* mIHashableTypeDef;
BfTypeDef* mIComptimeTypeApply; BfTypeDef* mIComptimeTypeApply;
BfTypeDef* mIComptimeMethodApply; BfTypeDef* mIComptimeMethodApply;
BfTypeDef* mIOnTypeInitTypeDef; BfTypeDef* mIOnTypeInitTypeDef;
BfTypeDef* mIOnTypeDoneTypeDef; BfTypeDef* mIOnTypeDoneTypeDef;
BfTypeDef* mIOnFieldInitTypeDef; BfTypeDef* mIOnFieldInitTypeDef;
BfTypeDef* mIOnMethodInitTypeDef; BfTypeDef* mIOnMethodInitTypeDef;
BfTypeDef* mMethodRefTypeDef; BfTypeDef* mMethodRefTypeDef;
BfTypeDef* mNullableTypeDef; BfTypeDef* mNullableTypeDef;
BfTypeDef* mPointerTTypeDef; BfTypeDef* mPointerTTypeDef;
BfTypeDef* mPointerTypeDef; BfTypeDef* mPointerTypeDef;
BfTypeDef* mReflectTypeIdTypeDef; BfTypeDef* mReflectTypeIdTypeDef;
@ -420,17 +420,17 @@ public:
BfTypeDef* mReflectConstExprType; BfTypeDef* mReflectConstExprType;
BfTypeDef* mReflectSpecializedGenericType; BfTypeDef* mReflectSpecializedGenericType;
BfTypeDef* mReflectTypeInstanceTypeDef; BfTypeDef* mReflectTypeInstanceTypeDef;
BfTypeDef* mReflectUnspecializedGenericType; BfTypeDef* mReflectUnspecializedGenericType;
BfTypeDef* mReflectFieldInfoTypeDef; BfTypeDef* mReflectFieldInfoTypeDef;
BfTypeDef* mReflectMethodInfoTypeDef; BfTypeDef* mReflectMethodInfoTypeDef;
BfTypeDef* mSizedArrayTypeDef; BfTypeDef* mSizedArrayTypeDef;
BfTypeDef* mAttributeTypeDef; BfTypeDef* mAttributeTypeDef;
BfTypeDef* mAttributeUsageAttributeTypeDef; BfTypeDef* mAttributeUsageAttributeTypeDef;
BfTypeDef* mLinkNameAttributeTypeDef; BfTypeDef* mLinkNameAttributeTypeDef;
BfTypeDef* mCallingConventionAttributeTypeDef; BfTypeDef* mCallingConventionAttributeTypeDef;
BfTypeDef* mOrderedAttributeTypeDef; BfTypeDef* mOrderedAttributeTypeDef;
BfTypeDef* mInlineAttributeTypeDef; BfTypeDef* mInlineAttributeTypeDef;
BfTypeDef* mCLinkAttributeTypeDef; BfTypeDef* mCLinkAttributeTypeDef;
BfTypeDef* mImportAttributeTypeDef; BfTypeDef* mImportAttributeTypeDef;
BfTypeDef* mExportAttributeTypeDef; BfTypeDef* mExportAttributeTypeDef;
@ -446,30 +446,30 @@ public:
BfTypeDef* mConstEvalAttributeTypeDef; BfTypeDef* mConstEvalAttributeTypeDef;
BfTypeDef* mNoExtensionAttributeTypeDef; BfTypeDef* mNoExtensionAttributeTypeDef;
BfTypeDef* mCheckedAttributeTypeDef; BfTypeDef* mCheckedAttributeTypeDef;
BfTypeDef* mUncheckedAttributeTypeDef; BfTypeDef* mUncheckedAttributeTypeDef;
BfTypeDef* mStaticInitAfterAttributeTypeDef; BfTypeDef* mStaticInitAfterAttributeTypeDef;
BfTypeDef* mStaticInitPriorityAttributeTypeDef; BfTypeDef* mStaticInitPriorityAttributeTypeDef;
BfTypeDef* mTestAttributeTypeDef; BfTypeDef* mTestAttributeTypeDef;
BfTypeDef* mThreadStaticAttributeTypeDef; BfTypeDef* mThreadStaticAttributeTypeDef;
BfTypeDef* mUnboundAttributeTypeDef; BfTypeDef* mUnboundAttributeTypeDef;
BfTypeDef* mObsoleteAttributeTypeDef; BfTypeDef* mObsoleteAttributeTypeDef;
BfTypeDef* mErrorAttributeTypeDef; BfTypeDef* mErrorAttributeTypeDef;
BfTypeDef* mWarnAttributeTypeDef; BfTypeDef* mWarnAttributeTypeDef;
BfTypeDef* mConstSkipAttributeTypeDef; BfTypeDef* mConstSkipAttributeTypeDef;
BfTypeDef* mIgnoreErrorsAttributeTypeDef; BfTypeDef* mIgnoreErrorsAttributeTypeDef;
BfTypeDef* mReflectAttributeTypeDef; BfTypeDef* mReflectAttributeTypeDef;
BfTypeDef* mOnCompileAttributeTypeDef; BfTypeDef* mOnCompileAttributeTypeDef;
int mCurTypeId; int mCurTypeId;
int mTypeInitCount; int mTypeInitCount;
String mOutputPath; String mOutputPath;
Array<BfType*> mGenericInstancePurgatory; Array<BfType*> mGenericInstancePurgatory;
Array<int> mTypeIdFreeList; Array<int> mTypeIdFreeList;
int mMaxInterfaceSlots; int mMaxInterfaceSlots;
bool mInterfaceSlotCountChanged; bool mInterfaceSlotCountChanged;
public: public:
bool IsTypeAccessible(BfType* checkType, BfProject* curProject); bool IsTypeAccessible(BfType* checkType, BfProject* curProject);
bool IsTypeUsed(BfType* checkType, BfProject* curProject); bool IsTypeUsed(BfType* checkType, BfProject* curProject);
bool IsModuleAccessible(BfModule* module, BfProject* curProject); bool IsModuleAccessible(BfModule* module, BfProject* curProject);
@ -479,22 +479,22 @@ public:
BfIRFunction CreateLoadSharedLibraries(BfVDataModule* bfModule, Array<BfMethodInstance*>& dllMethods); BfIRFunction CreateLoadSharedLibraries(BfVDataModule* bfModule, Array<BfMethodInstance*>& dllMethods);
void GetTestMethods(BfVDataModule* bfModule, Array<TestMethod>& testMethods, HashContext& vdataHashCtx); void GetTestMethods(BfVDataModule* bfModule, Array<TestMethod>& testMethods, HashContext& vdataHashCtx);
void EmitTestMethod(BfVDataModule* bfModule, Array<TestMethod>& testMethods, BfIRValue& retValue); void EmitTestMethod(BfVDataModule* bfModule, Array<TestMethod>& testMethods, BfIRValue& retValue);
void CreateVData(BfVDataModule* bfModule); void CreateVData(BfVDataModule* bfModule);
void UpdateDependencyMap(bool deleteUnusued, bool& didWork); void UpdateDependencyMap(bool deleteUnusued, bool& didWork);
void SanitizeDependencyMap(); void SanitizeDependencyMap();
bool ProcessPurgatory(bool reifiedOnly); bool ProcessPurgatory(bool reifiedOnly);
bool VerifySlotNums(); bool VerifySlotNums();
bool QuickGenerateSlotNums(); bool QuickGenerateSlotNums();
bool SlowGenerateSlotNums(); bool SlowGenerateSlotNums();
void GenerateSlotNums(); void GenerateSlotNums();
void GenerateDynCastData(); void GenerateDynCastData();
void UpdateRevisedTypes(); void UpdateRevisedTypes();
void VisitAutocompleteExteriorIdentifiers(); void VisitAutocompleteExteriorIdentifiers();
void VisitSourceExteriorNodes(); void VisitSourceExteriorNodes();
void UpdateCompletion(); void UpdateCompletion();
bool DoWorkLoop(bool onlyReifiedTypes = false, bool onlyReifiedMethods = false); bool DoWorkLoop(bool onlyReifiedTypes = false, bool onlyReifiedMethods = false);
BfMangler::MangleKind GetMangleKind(); BfMangler::MangleKind GetMangleKind();
BfTypeDef* GetArrayTypeDef(int dimensions); BfTypeDef* GetArrayTypeDef(int dimensions);
void GenerateAutocompleteInfo(); void GenerateAutocompleteInfo();
void MarkStringPool(BfModule* module); void MarkStringPool(BfModule* module);
@ -517,7 +517,7 @@ public:
bool IsCePaused(); bool IsCePaused();
bool EnsureCeUnpaused(BfType* refType); bool EnsureCeUnpaused(BfType* refType);
void HotCommit(); void HotCommit();
void HotResolve_Start(HotResolveFlags flags); void HotResolve_Start(HotResolveFlags flags);
void HotResolve_PopulateMethodNameMap(); void HotResolve_PopulateMethodNameMap();
bool HotResolve_AddReachableMethod(BfHotMethod* hotMethod, HotTypeFlags flags, bool devirtualized, bool forceProcess = false); bool HotResolve_AddReachableMethod(BfHotMethod* hotMethod, HotTypeFlags flags, bool devirtualized, bool forceProcess = false);
@ -532,24 +532,24 @@ public:
public: public:
BfCompiler(BfSystem* bfSystem, bool isResolveOnly); BfCompiler(BfSystem* bfSystem, bool isResolveOnly);
~BfCompiler(); ~BfCompiler();
bool Compile(const StringImpl& outputPath); bool Compile(const StringImpl& outputPath);
bool DoCompile(const StringImpl& outputPath); bool DoCompile(const StringImpl& outputPath);
void ClearResults(); void ClearResults();
void ProcessAutocompleteTempType(); void ProcessAutocompleteTempType();
void GetSymbolReferences(); void GetSymbolReferences();
void Cancel(); void Cancel();
void RequestFastFinish(); void RequestFastFinish();
String GetTypeDefList(); String GetTypeDefList();
String GetGeneratorString(BfTypeDef* typeDef, BfTypeInstance* typeInst, const StringImpl& generatorMethodName, const StringImpl* args); String GetGeneratorString(BfTypeDef* typeDef, BfTypeInstance* typeInst, const StringImpl& generatorMethodName, const StringImpl* args);
void HandleGeneratorErrors(StringImpl& result); void HandleGeneratorErrors(StringImpl& result);
String GetGeneratorTypeDefList(); String GetGeneratorTypeDefList();
String GetGeneratorInitData(const StringImpl& typeName, const StringImpl& args); String GetGeneratorInitData(const StringImpl& typeName, const StringImpl& args);
String GetGeneratorGenData(const StringImpl& typeName, const StringImpl& args); String GetGeneratorGenData(const StringImpl& typeName, const StringImpl& args);
String GetTypeDefMatches(const StringImpl& searchSrc); String GetTypeDefMatches(const StringImpl& searchSrc);
void GetTypeDefs(const StringImpl& typeName, Array<BfTypeDef*>& typeDefs); void GetTypeDefs(const StringImpl& typeName, Array<BfTypeDef*>& typeDefs);
String GetTypeDefInfo(const StringImpl& typeName); String GetTypeDefInfo(const StringImpl& typeName);
int GetTypeId(const StringImpl& typeName); int GetTypeId(const StringImpl& typeName);
BfType* GetType(const StringImpl& typeName); BfType* GetType(const StringImpl& typeName);
int GetEmitSource(const StringImpl& fileName, StringImpl* outBuffer); int GetEmitSource(const StringImpl& fileName, StringImpl* outBuffer);
@ -561,4 +561,3 @@ public:
}; };
NS_BF_END NS_BF_END

View file

@ -64,25 +64,25 @@ BfTypedValue BfConstResolver::Resolve(BfExpression* expr, BfType* wantType, BfCo
// Dot-initialized // Dot-initialized
if (memberRefExpr->mTarget == NULL) if (memberRefExpr->mTarget == NULL)
arraySize = (int)invocationExpr->mArguments.size(); arraySize = (int)invocationExpr->mArguments.size();
} }
else if (auto indexerExpr = BfNodeDynCast<BfIndexerExpression>(invocationExpr->mTarget)) else if (auto indexerExpr = BfNodeDynCast<BfIndexerExpression>(invocationExpr->mTarget))
{ {
if (indexerExpr->mArguments.size() == 0) if (indexerExpr->mArguments.size() == 0)
{ {
// Inferred-type sized array initializer // Inferred-type sized array initializer
arraySize = (int)invocationExpr->mArguments.size(); arraySize = (int)invocationExpr->mArguments.size();
} }
} }
} }
} }
if (arraySize != -1) if (arraySize != -1)
{ {
mResult = BfTypedValue(mModule->GetConstValue(arraySize), mModule->GetPrimitiveType(BfTypeCode_IntPtr)); mResult = BfTypedValue(mModule->GetConstValue(arraySize), mModule->GetPrimitiveType(BfTypeCode_IntPtr));
return mResult; return mResult;
} }
else else
{ {
mResult = BfTypedValue(mModule->mBfIRBuilder->GetUndefConstValue(mModule->mBfIRBuilder->GetPrimitiveType(BfTypeCode_IntPtr)), mModule->GetPrimitiveType(BfTypeCode_IntPtr)); mResult = BfTypedValue(mModule->mBfIRBuilder->GetUndefConstValue(mModule->mBfIRBuilder->GetPrimitiveType(BfTypeCode_IntPtr)), mModule->GetPrimitiveType(BfTypeCode_IntPtr));
return mResult; return mResult;
} }
@ -103,16 +103,16 @@ BfTypedValue BfConstResolver::Resolve(BfExpression* expr, BfType* wantType, BfCo
} }
SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, wantIgnoreWrites); SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, wantIgnoreWrites);
auto prevInsertBlock = mModule->mBfIRBuilder->GetInsertBlock(); auto prevInsertBlock = mModule->mBfIRBuilder->GetInsertBlock();
mNoBind = true; mNoBind = true;
if (wantType != NULL) if (wantType != NULL)
mExpectingType = wantType; mExpectingType = wantType;
VisitChildNoRef(expr); VisitChildNoRef(expr);
mResult = GetResult(); mResult = GetResult();
auto compilerVal = mModule->GetCompilerFieldValue(mResult); auto compilerVal = mModule->GetCompilerFieldValue(mResult);
if (compilerVal) if (compilerVal)
mResult = compilerVal; mResult = compilerVal;
@ -131,14 +131,14 @@ BfTypedValue BfConstResolver::Resolve(BfExpression* expr, BfType* wantType, BfCo
(toType == mResult.mType))) (toType == mResult.mType)))
{ {
auto constant = mModule->mBfIRBuilder->GetConstant(mResult.mValue); auto constant = mModule->mBfIRBuilder->GetConstant(mResult.mValue);
if (constant->mTypeCode == BfTypeCode_NullPtr) if (constant->mTypeCode == BfTypeCode_NullPtr)
{ {
return mModule->GetDefaultTypedValue(toType); return mModule->GetDefaultTypedValue(toType);
} }
else else
{ {
int stringId = mModule->GetStringPoolIdx(mResult.mValue); int stringId = mModule->GetStringPoolIdx(mResult.mValue);
if (stringId != -1) if (stringId != -1)
{ {
if ((flags & BfConstResolveFlag_ActualizeValues) != 0) if ((flags & BfConstResolveFlag_ActualizeValues) != 0)
@ -166,9 +166,9 @@ BfTypedValue BfConstResolver::Resolve(BfExpression* expr, BfType* wantType, BfCo
mResult = convValue; mResult = convValue;
} }
else else
{ {
mResult = mModule->Cast(expr, mResult, wantType, (BfCastFlags)(BfCastFlags_NoConversionOperator | (explicitCast ? BfCastFlags_Explicit : BfCastFlags_None))); mResult = mModule->Cast(expr, mResult, wantType, (BfCastFlags)(BfCastFlags_NoConversionOperator | (explicitCast ? BfCastFlags_Explicit : BfCastFlags_None)));
} }
} }
if (mResult.mKind == BfTypedValueKind_GenericConstValue) if (mResult.mKind == BfTypedValueKind_GenericConstValue)
@ -195,9 +195,9 @@ BfTypedValue BfConstResolver::Resolve(BfExpression* expr, BfType* wantType, BfCo
isConst = false; isConst = false;
} }
} }
if ((!isConst) && ((mBfEvalExprFlags & BfEvalExprFlags_AllowNonConst) == 0)) if ((!isConst) && ((mBfEvalExprFlags & BfEvalExprFlags_AllowNonConst) == 0))
{ {
mModule->Fail("Expression does not evaluate to a constant value", expr); mModule->Fail("Expression does not evaluate to a constant value", expr);
if (wantType != NULL) if (wantType != NULL)
@ -210,7 +210,7 @@ BfTypedValue BfConstResolver::Resolve(BfExpression* expr, BfType* wantType, BfCo
{ {
if (wantType != NULL) if (wantType != NULL)
mResult = mModule->GetDefaultTypedValue(wantType); mResult = mModule->GetDefaultTypedValue(wantType);
} }
if (prevInsertBlock) if (prevInsertBlock)
mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock); mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
@ -221,7 +221,7 @@ BfTypedValue BfConstResolver::Resolve(BfExpression* expr, BfType* wantType, BfCo
mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock); mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
}*/ }*/
mModule->FixIntUnknown(mResult); mModule->FixIntUnknown(mResult);
if ((flags & BfConstResolveFlag_NoActualizeValues) == 0) if ((flags & BfConstResolveFlag_NoActualizeValues) == 0)
{ {
@ -240,10 +240,10 @@ bool BfConstResolver::PrepareMethodArguments(BfAstNode* targetSrc, BfMethodMatch
int extendedParamIdx = 0; int extendedParamIdx = 0;
SetAndRestoreValue<bool> ignoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true); SetAndRestoreValue<bool> ignoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
llvm::SmallVector<BfIRValue, 4> expandedParamsConstValues; llvm::SmallVector<BfIRValue, 4> expandedParamsConstValues;
BfType* expandedParamsElementType = NULL; BfType* expandedParamsElementType = NULL;
// We don't do GetMethodInstance in mModule, because our module may not have init finished yet // We don't do GetMethodInstance in mModule, because our module may not have init finished yet
//auto targetModule = methodMatcher->mBestMethodTypeInstance->mModule; //auto targetModule = methodMatcher->mBestMethodTypeInstance->mModule;
auto targetModule = mModule->mContext->mUnreifiedModule; auto targetModule = mModule->mContext->mUnreifiedModule;
@ -260,7 +260,7 @@ bool BfConstResolver::PrepareMethodArguments(BfAstNode* targetSrc, BfMethodMatch
auto& arguments = methodMatcher->mArguments; auto& arguments = methodMatcher->mArguments;
mModule->AddDependency(methodInstance->mReturnType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage); mModule->AddDependency(methodInstance->mReturnType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
for (int paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++) for (int paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
{ {
auto paramType = methodInstance->GetParamType(paramIdx); auto paramType = methodInstance->GetParamType(paramIdx);
mModule->AddDependency(paramType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage); mModule->AddDependency(paramType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
@ -271,7 +271,7 @@ bool BfConstResolver::PrepareMethodArguments(BfAstNode* targetSrc, BfMethodMatch
if (paramIdx >= (int)methodInstance->GetParamCount()) if (paramIdx >= (int)methodInstance->GetParamCount())
{ {
if (argIdx < (int)arguments.size()) if (argIdx < (int)arguments.size())
{ {
BfAstNode* errorRef = arguments[methodInstance->GetParamCount()].mExpression; BfAstNode* errorRef = arguments[methodInstance->GetParamCount()].mExpression;
if (errorRef->GetSourceData() == NULL) if (errorRef->GetSourceData() == NULL)
errorRef = targetSrc; errorRef = targetSrc;
@ -281,7 +281,7 @@ bool BfConstResolver::PrepareMethodArguments(BfAstNode* targetSrc, BfMethodMatch
return false; return false;
} }
break; break;
} }
BfType* wantType = NULL; BfType* wantType = NULL;
if (expandedParamsElementType != NULL) if (expandedParamsElementType != NULL)
@ -351,7 +351,7 @@ bool BfConstResolver::PrepareMethodArguments(BfAstNode* targetSrc, BfMethodMatch
if (attributeDirective->mCtorCloseParen != NULL) if (attributeDirective->mCtorCloseParen != NULL)
refNode = attributeDirective->mCtorCloseParen; refNode = attributeDirective->mCtorCloseParen;
} }
} }
auto autoComplete = GetAutoComplete(); auto autoComplete = GetAutoComplete();
if (autoComplete != NULL) if (autoComplete != NULL)
@ -361,14 +361,14 @@ bool BfConstResolver::PrepareMethodArguments(BfAstNode* targetSrc, BfMethodMatch
autoComplete->CheckEmptyStart(prevNode, wantType); autoComplete->CheckEmptyStart(prevNode, wantType);
} }
} }
if (mModule->PreFail()) if (mModule->PreFail())
mModule->Fail(StrFormat("Not enough parameters specified. Expected %d more.", methodInstance->GetParamCount() - (int)arguments.size()), refNode); mModule->Fail(StrFormat("Not enough parameters specified. Expected %d more.", methodInstance->GetParamCount() - (int)arguments.size()), refNode);
return false; return false;
} }
auto foreignDefaultVal = methodInstance->mDefaultValues[argIdx]; auto foreignDefaultVal = methodInstance->mDefaultValues[argIdx];
auto foreignConst = methodInstance->GetOwner()->mConstHolder->GetConstant(foreignDefaultVal.mValue); auto foreignConst = methodInstance->GetOwner()->mConstHolder->GetConstant(foreignDefaultVal.mValue);
argValue = mModule->GetTypedValueFromConstant(foreignConst, methodInstance->GetOwner()->mConstHolder, foreignDefaultVal.mType); argValue = mModule->GetTypedValueFromConstant(foreignConst, methodInstance->GetOwner()->mConstHolder, foreignDefaultVal.mType);
} }
@ -387,7 +387,7 @@ bool BfConstResolver::PrepareMethodArguments(BfAstNode* targetSrc, BfMethodMatch
arg.mArgFlags = BfArgFlag_None; arg.mArgFlags = BfArgFlag_None;
} }
} }
if (!argValue) if (!argValue)
return BfTypedValue(); return BfTypedValue();
@ -410,14 +410,14 @@ bool BfConstResolver::PrepareMethodArguments(BfAstNode* targetSrc, BfMethodMatch
extendedParamIdx++; extendedParamIdx++;
} }
else else
{ {
bool requiresConst = false; bool requiresConst = false;
if ((mModule->mCurMethodInstance == NULL) || (mModule->mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Mixin)) if ((mModule->mCurMethodInstance == NULL) || (mModule->mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Mixin))
requiresConst = true; requiresConst = true;
if ((requiresConst) && (argValue.mValue.IsFake()) && (!argValue.mType->IsValuelessType())) if ((requiresConst) && (argValue.mValue.IsFake()) && (!argValue.mType->IsValuelessType()))
{ {
mModule->Fail("Expression does not evaluate to a constant value", argExpr); mModule->Fail("Expression does not evaluate to a constant value", argExpr);
} }
if (!argValue.mType->IsVar()) if (!argValue.mType->IsVar())
@ -433,11 +433,11 @@ bool BfConstResolver::PrepareMethodArguments(BfAstNode* targetSrc, BfMethodMatch
} }
if (expandedParamsElementType != NULL) if (expandedParamsElementType != NULL)
{ {
auto arrayType = mModule->mBfIRBuilder->GetSizedArrayType(mModule->mBfIRBuilder->MapType(expandedParamsElementType), (int)expandedParamsConstValues.size()); auto arrayType = mModule->mBfIRBuilder->GetSizedArrayType(mModule->mBfIRBuilder->MapType(expandedParamsElementType), (int)expandedParamsConstValues.size());
auto constArray = mModule->mBfIRBuilder->CreateConstAgg(arrayType, expandedParamsConstValues); auto constArray = mModule->mBfIRBuilder->CreateConstAgg(arrayType, expandedParamsConstValues);
llvmArgs.push_back(constArray); llvmArgs.push_back(constArray);
} }
return true; return true;
} }

View file

@ -24,13 +24,13 @@ enum BfConstResolveFlags
class BfConstResolver : public BfExprEvaluator class BfConstResolver : public BfExprEvaluator
{ {
public: public:
bool mIsInvalidConstExpr; bool mIsInvalidConstExpr;
public: public:
virtual bool CheckAllowValue(const BfTypedValue& typedValue, BfAstNode* refNode) override; virtual bool CheckAllowValue(const BfTypedValue& typedValue, BfAstNode* refNode) override;
public: public:
BfConstResolver(BfModule* bfModule); BfConstResolver(BfModule* bfModule);
BfTypedValue Resolve(BfExpression* expr, BfType* wantType = NULL, BfConstResolveFlags flags = BfConstResolveFlag_None); BfTypedValue Resolve(BfExpression* expr, BfType* wantType = NULL, BfConstResolveFlags flags = BfConstResolveFlag_None);
bool PrepareMethodArguments(BfAstNode* targetSrc, BfMethodMatcher* methodMatcher, Array<BfIRValue>& llvmArgs); bool PrepareMethodArguments(BfAstNode* targetSrc, BfMethodMatcher* methodMatcher, Array<BfIRValue>& llvmArgs);

File diff suppressed because it is too large Load diff

View file

@ -12,22 +12,22 @@ public:
BfModule* mFromModule; BfModule* mFromModule;
int mRevision; int mRevision;
int mSignatureRevision; int mSignatureRevision;
int mFromModuleRevision; int mFromModuleRevision;
int mFromModuleRebuildIdx; int mFromModuleRebuildIdx;
int mReqId; int mReqId;
static int sCurReqId; static int sCurReqId;
public: public:
BfWorkListEntry() BfWorkListEntry()
{ {
mType = NULL; mType = NULL;
mFromModule = NULL; mFromModule = NULL;
mRevision = -1; mRevision = -1;
mSignatureRevision = -1; mSignatureRevision = -1;
mFromModuleRevision = -1; mFromModuleRevision = -1;
mFromModuleRebuildIdx = -1; mFromModuleRebuildIdx = -1;
mReqId = ++sCurReqId; mReqId = ++sCurReqId;
} }
}; };
class BfTypeProcessRequest : public BfWorkListEntry class BfTypeProcessRequest : public BfWorkListEntry
@ -43,7 +43,7 @@ public:
class BfMethodSpecializationRequest : public BfWorkListEntry class BfMethodSpecializationRequest : public BfWorkListEntry
{ {
public: public:
int32 mMethodIdx; int32 mMethodIdx;
BfTypeVector mMethodGenericArguments; BfTypeVector mMethodGenericArguments;
BfGetMethodInstanceFlags mFlags; BfGetMethodInstanceFlags mFlags;
@ -51,7 +51,7 @@ public:
public: public:
BfMethodSpecializationRequest() BfMethodSpecializationRequest()
{ {
mMethodIdx = -1; mMethodIdx = -1;
mFlags = BfGetMethodInstanceFlag_None; mFlags = BfGetMethodInstanceFlag_None;
mForeignType = NULL; mForeignType = NULL;
@ -97,9 +97,9 @@ public:
class BfInlineMethodRequest : public BfMethodProcessRequest class BfInlineMethodRequest : public BfMethodProcessRequest
{ {
public: public:
BfIRFunction mFunc; BfIRFunction mFunc;
~BfInlineMethodRequest() ~BfInlineMethodRequest()
{ {
mMethodInstance = NULL; mMethodInstance = NULL;
@ -110,12 +110,12 @@ class BfTypeRefVerifyRequest : public BfWorkListEntry
{ {
public: public:
BfTypeInstance* mCurTypeInstance; BfTypeInstance* mCurTypeInstance;
BfAstNode* mRefNode; BfAstNode* mRefNode;
}; };
class BfMidCompileRequest : public BfWorkListEntry class BfMidCompileRequest : public BfWorkListEntry
{ {
public: public:
String mReason; String mReason;
}; };
@ -153,15 +153,15 @@ public:
BfType* mType; BfType* mType;
BfTypeDef* mGlobalContainerCurUserTypeDef; BfTypeDef* mGlobalContainerCurUserTypeDef;
Array<BfGlobalContainerEntry> mGlobalContainers; // All global containers that are visible Array<BfGlobalContainerEntry> mGlobalContainers; // All global containers that are visible
BfPopulateType mPopulateType; BfPopulateType mPopulateType;
BfTypeReference* mCurBaseTypeRef; BfTypeReference* mCurBaseTypeRef;
BfTypeInstance* mCurBaseType; BfTypeInstance* mCurBaseType;
BfTypeReference* mCurAttributeTypeRef; BfTypeReference* mCurAttributeTypeRef;
BfFieldDef* mCurFieldDef; BfFieldDef* mCurFieldDef;
BfTypeDef* mCurTypeDef; BfTypeDef* mCurTypeDef;
BfTypeDef* mForceActiveTypeDef; BfTypeDef* mForceActiveTypeDef;
BfProject* mActiveProject; BfProject* mActiveProject;
ResolveKind mResolveKind; ResolveKind mResolveKind;
BfAstNode* mCurVarInitializer; BfAstNode* mCurVarInitializer;
@ -209,7 +209,7 @@ public:
class BfSavedTypeData class BfSavedTypeData
{ {
public: public:
BfHotTypeData* mHotTypeData; BfHotTypeData* mHotTypeData;
int mTypeId; int mTypeId;
public: public:
@ -221,7 +221,7 @@ public:
struct SpecializedErrorData struct SpecializedErrorData
{ {
// We need to store errors during type specialization and method specialization, // We need to store errors during type specialization and method specialization,
// because if the type is deleted we need to clear the errors // because if the type is deleted we need to clear the errors
BfTypeInstance* mRefType; BfTypeInstance* mRefType;
BfModule* mModule; BfModule* mModule;
@ -241,8 +241,8 @@ struct BfCaseInsensitiveStringHash
{ {
size_t operator()(const StringImpl& str) const size_t operator()(const StringImpl& str) const
{ {
int curHash = 0; int curHash = 0;
for (int i = 0; i < (int)str.length(); i++) for (int i = 0; i < (int)str.length(); i++)
curHash = ((curHash ^ (int)(intptr)toupper(str[i])) << 5) - curHash; curHash = ((curHash ^ (int)(intptr)toupper(str[i])) << 5) - curHash;
return curHash; return curHash;
} }
@ -251,7 +251,7 @@ struct BfCaseInsensitiveStringHash
struct BfCaseInsensitiveStringEquals struct BfCaseInsensitiveStringEquals
{ {
bool operator()(const StringImpl& lhs, const StringImpl& rhs) const bool operator()(const StringImpl& lhs, const StringImpl& rhs) const
{ {
if (lhs.length() != rhs.length()) if (lhs.length() != rhs.length())
return false; return false;
return _stricmp(lhs.c_str(), rhs.c_str()) == 0; return _stricmp(lhs.c_str(), rhs.c_str()) == 0;
@ -270,7 +270,7 @@ public:
{ {
T*& ref = (*this)[idx]; T*& ref = (*this)[idx];
if (ref != NULL) if (ref != NULL)
(*ref).~T(); (*ref).~T();
Deque<T*>::RemoveAt(0); Deque<T*>::RemoveAt(0);
if (this->mSize == 0) if (this->mSize == 0)
{ {
@ -303,7 +303,7 @@ public:
T* item = mWorkAlloc.Alloc<T>(); T* item = mWorkAlloc.Alloc<T>();
this->Add(item); this->Add(item);
return item; return item;
} }
}; };
template <typename T> template <typename T>
@ -348,7 +348,7 @@ public:
bool operator==(const BfConstraintState& other) const bool operator==(const BfConstraintState& other) const
{ {
return return
(mGenericParamInstance == other.mGenericParamInstance) && (mGenericParamInstance == other.mGenericParamInstance) &&
(mLeftType == other.mLeftType) && (mLeftType == other.mLeftType) &&
(mRightType == other.mRightType); (mRightType == other.mRightType);
@ -358,9 +358,9 @@ public:
class BfContext class BfContext
{ {
public: public:
CritSect mCritSect; CritSect mCritSect;
bool mDeleting; bool mDeleting;
BfTypeState* mCurTypeState; BfTypeState* mCurTypeState;
BfSizedArray<BfNamespaceDeclaration*>* mCurNamespaceNodes; BfSizedArray<BfNamespaceDeclaration*>* mCurNamespaceNodes;
BfConstraintState* mCurConstraintState; BfConstraintState* mCurConstraintState;
@ -369,25 +369,25 @@ public:
bool mAssertOnPopulateType; bool mAssertOnPopulateType;
BfSystem* mSystem; BfSystem* mSystem;
BfCompiler* mCompiler; BfCompiler* mCompiler;
bool mAllowLockYield; bool mAllowLockYield;
bool mLockModules; bool mLockModules;
BfModule* mScratchModule; BfModule* mScratchModule;
BfModule* mUnreifiedModule; BfModule* mUnreifiedModule;
HashSet<String> mUsedModuleNames; HashSet<String> mUsedModuleNames;
Dictionary<BfProject*, BfModule*> mProjectModule; Dictionary<BfProject*, BfModule*> mProjectModule;
Array<BfModule*> mModules; Array<BfModule*> mModules;
Array<BfModule*> mDeletingModules; Array<BfModule*> mDeletingModules;
HashSet<BfTypeInstance*> mFailTypes; // All types handled after a failure need to be rebuild on subsequent compile HashSet<BfTypeInstance*> mFailTypes; // All types handled after a failure need to be rebuild on subsequent compile
HashSet<BfTypeInstance*> mReferencedIFaceSlots; HashSet<BfTypeInstance*> mReferencedIFaceSlots;
BfMethodInstance* mValueTypeDeinitSentinel; BfMethodInstance* mValueTypeDeinitSentinel;
Array<BfAstNode*> mTempNodes; Array<BfAstNode*> mTempNodes;
BfResolvedTypeSet mResolvedTypes; BfResolvedTypeSet mResolvedTypes;
Array<BfType*> mTypes; // Can contain NULLs for deleted types Array<BfType*> mTypes; // Can contain NULLs for deleted types
Array<BfFieldInstance*> mFieldResolveReentrys; // For detecting 'var' field circular refs Array<BfFieldInstance*> mFieldResolveReentrys; // For detecting 'var' field circular refs
Dictionary<String, BfSavedTypeData*> mSavedTypeDataMap; Dictionary<String, BfSavedTypeData*> mSavedTypeDataMap;
Array<BfSavedTypeData*> mSavedTypeData; Array<BfSavedTypeData*> mSavedTypeData;
@ -399,7 +399,7 @@ public:
PtrWorkQueue<BfModule*> mReifyModuleWorkList; PtrWorkQueue<BfModule*> mReifyModuleWorkList;
WorkQueue<BfMethodProcessRequest> mMethodWorkList; WorkQueue<BfMethodProcessRequest> mMethodWorkList;
WorkQueue<BfInlineMethodRequest> mInlineMethodWorkList; WorkQueue<BfInlineMethodRequest> mInlineMethodWorkList;
WorkQueue<BfTypeProcessRequest> mPopulateTypeWorkList; WorkQueue<BfTypeProcessRequest> mPopulateTypeWorkList;
WorkQueue<BfMethodSpecializationRequest> mMethodSpecializationWorkList; WorkQueue<BfMethodSpecializationRequest> mMethodSpecializationWorkList;
WorkQueue<BfTypeRefVerifyRequest> mTypeRefVerifyWorkList; WorkQueue<BfTypeRefVerifyRequest> mTypeRefVerifyWorkList;
@ -409,7 +409,7 @@ public:
bool mHasReifiedQueuedRebuildTypes; bool mHasReifiedQueuedRebuildTypes;
Array<BfGenericParamType*> mGenericParamTypes[3]; Array<BfGenericParamType*> mGenericParamTypes[3];
Array<BfType*> mTypeGraveyard; Array<BfType*> mTypeGraveyard;
Array<BfTypeDef*> mTypeDefGraveyard; Array<BfTypeDef*> mTypeDefGraveyard;
Array<BfLocalMethod*> mLocalMethodGraveyard; Array<BfLocalMethod*> mLocalMethodGraveyard;
@ -418,9 +418,9 @@ public:
Dictionary<int, BfStringPoolEntry> mStringObjectIdMap; Dictionary<int, BfStringPoolEntry> mStringObjectIdMap;
int mCurStringObjectPoolId; int mCurStringObjectPoolId;
HashSet<BfTypeInstance*> mQueuedSpecializedMethodRebuildTypes; HashSet<BfTypeInstance*> mQueuedSpecializedMethodRebuildTypes;
BfAllocPool<BfPointerType> mPointerTypePool; BfAllocPool<BfPointerType> mPointerTypePool;
BfAllocPool<BfArrayType> mArrayTypePool; BfAllocPool<BfArrayType> mArrayTypePool;
BfAllocPool<BfSizedArrayType> mSizedArrayTypePool; BfAllocPool<BfSizedArrayType> mSizedArrayTypePool;
BfAllocPool<BfUnknownSizedArrayType> mUnknownSizedArrayTypePool; BfAllocPool<BfUnknownSizedArrayType> mUnknownSizedArrayTypePool;
@ -429,13 +429,13 @@ public:
BfAllocPool<BfTypeAliasType> mAliasTypePool; BfAllocPool<BfTypeAliasType> mAliasTypePool;
BfAllocPool<BfRefType> mRefTypePool; BfAllocPool<BfRefType> mRefTypePool;
BfAllocPool<BfModifiedTypeType> mModifiedTypeTypePool; BfAllocPool<BfModifiedTypeType> mModifiedTypeTypePool;
BfAllocPool<BfTypeInstance> mGenericTypeInstancePool; BfAllocPool<BfTypeInstance> mGenericTypeInstancePool;
BfAllocPool<BfArrayType> mArrayTypeInstancePool; BfAllocPool<BfArrayType> mArrayTypeInstancePool;
BfAllocPool<BfGenericParamType> mGenericParamTypePool; BfAllocPool<BfGenericParamType> mGenericParamTypePool;
BfAllocPool<BfDirectTypeDefReference> mTypeDefTypeRefPool; BfAllocPool<BfDirectTypeDefReference> mTypeDefTypeRefPool;
BfAllocPool<BfConcreteInterfaceType> mConcreteInterfaceTypePool; BfAllocPool<BfConcreteInterfaceType> mConcreteInterfaceTypePool;
BfAllocPool<BfConstExprValueType> mConstExprValueTypePool; BfAllocPool<BfConstExprValueType> mConstExprValueTypePool;
BfAllocPool<BfDelegateType> mDelegateTypePool; BfAllocPool<BfDelegateType> mDelegateTypePool;
BfPrimitiveType* mPrimitiveTypes[BfTypeCode_Length]; BfPrimitiveType* mPrimitiveTypes[BfTypeCode_Length];
BfPrimitiveType* mPrimitiveStructTypes[BfTypeCode_Length]; BfPrimitiveType* mPrimitiveStructTypes[BfTypeCode_Length];
@ -447,15 +447,15 @@ public:
void PopulateHotTypeDataVTable(BfTypeInstance* typeInstance); void PopulateHotTypeDataVTable(BfTypeInstance* typeInstance);
void DeleteType(BfType* type, bool deferDepRebuilds = false); void DeleteType(BfType* type, bool deferDepRebuilds = false);
void UpdateAfterDeletingTypes(); void UpdateAfterDeletingTypes();
void VerifyTypeLookups(BfTypeInstance* typeInst); void VerifyTypeLookups(BfTypeInstance* typeInst);
void GenerateModuleName_TypeInst(BfTypeInstance* typeInst, StringImpl& name); void GenerateModuleName_TypeInst(BfTypeInstance* typeInst, StringImpl& name);
void GenerateModuleName_Type(BfType* type, StringImpl& name); void GenerateModuleName_Type(BfType* type, StringImpl& name);
void GenerateModuleName(BfTypeInstance* typeInst, StringImpl& name); void GenerateModuleName(BfTypeInstance* typeInst, StringImpl& name);
bool IsSentinelMethod(BfMethodInstance* methodInstance); bool IsSentinelMethod(BfMethodInstance* methodInstance);
void SaveDeletingType(BfType* type); void SaveDeletingType(BfType* type);
BfType* FindType(const StringImpl& typeName); BfType* FindType(const StringImpl& typeName);
String TypeIdToString(int typeId); String TypeIdToString(int typeId);
BfHotTypeData* GetHotTypeData(int typeId); BfHotTypeData* GetHotTypeData(int typeId);
void ReflectInit(); void ReflectInit();
public: public:
@ -464,28 +464,28 @@ public:
void ReportMemory(MemReporter* memReporter); void ReportMemory(MemReporter* memReporter);
void ProcessMethod(BfMethodInstance* methodInstance); void ProcessMethod(BfMethodInstance* methodInstance);
int GetStringLiteralId(const StringImpl& str); int GetStringLiteralId(const StringImpl& str);
void CheckLockYield(); void CheckLockYield();
bool IsCancellingAndYield(); bool IsCancellingAndYield();
void QueueFinishModule(BfModule * module); void QueueFinishModule(BfModule * module);
void CancelWorkItems(); void CancelWorkItems();
bool ProcessWorkList(bool onlyReifiedTypes, bool onlyReifiedMethods); bool ProcessWorkList(bool onlyReifiedTypes, bool onlyReifiedMethods);
void HandleChangedTypeDef(BfTypeDef* typeDef, bool isAutoCompleteTempType = false); void HandleChangedTypeDef(BfTypeDef* typeDef, bool isAutoCompleteTempType = false);
void PreUpdateRevisedTypes(); void PreUpdateRevisedTypes();
void UpdateRevisedTypes(); void UpdateRevisedTypes();
void VerifyTypeLookups(); void VerifyTypeLookups();
void QueueMethodSpecializations(BfTypeInstance* typeInst, bool checkSpecializedMethodRebuildFlag); void QueueMethodSpecializations(BfTypeInstance* typeInst, bool checkSpecializedMethodRebuildFlag);
void MarkAsReferenced(BfDependedType* depType); void MarkAsReferenced(BfDependedType* depType);
void RemoveInvalidFailTypes(); void RemoveInvalidFailTypes();
bool IsWorkItemValid(BfWorkListEntry* item); bool IsWorkItemValid(BfWorkListEntry* item);
bool IsWorkItemValid(BfMethodProcessRequest* item); bool IsWorkItemValid(BfMethodProcessRequest* item);
bool IsWorkItemValid(BfMethodSpecializationRequest* item); bool IsWorkItemValid(BfMethodSpecializationRequest* item);
void RemoveInvalidWorkItems(); void RemoveInvalidWorkItems();
BfType* FindTypeById(int typeId); BfType* FindTypeById(int typeId);
void AddTypeToWorkList(BfType* type); void AddTypeToWorkList(BfType* type);
void ValidateDependencies(); void ValidateDependencies();
void RebuildType(BfType* type, bool deleteOnDemandTypes = true, bool rebuildModule = true, bool placeSpecializiedInPurgatory = true); void RebuildType(BfType* type, bool deleteOnDemandTypes = true, bool rebuildModule = true, bool placeSpecializiedInPurgatory = true);
void RebuildDependentTypes(BfDependedType* dType); void RebuildDependentTypes(BfDependedType* dType);
void QueueMidCompileRebuildDependentTypes(BfDependedType* dType, const String& reason); void QueueMidCompileRebuildDependentTypes(BfDependedType* dType, const String& reason);
void RebuildDependentTypes_MidCompile(BfDependedType* dType, const String& reason); void RebuildDependentTypes_MidCompile(BfDependedType* dType, const String& reason);
bool CanRebuild(BfType* type); bool CanRebuild(BfType* type);

File diff suppressed because it is too large Load diff

View file

@ -39,14 +39,14 @@ public:
Array<BfTypeReference*> mInternalAccessSet; Array<BfTypeReference*> mInternalAccessSet;
HashContext* mFullHashCtx; HashContext* mFullHashCtx;
HashContext* mSignatureHashCtx; HashContext* mSignatureHashCtx;
Array<NamespaceState> mFileLevelNamespaceState; Array<NamespaceState> mFileLevelNamespaceState;
int mNamespaceBlockDepth; int mNamespaceBlockDepth;
public: public:
void ParseGenericParams(BfGenericParamsDeclaration* genericParamsDecl, BfGenericConstraintsDeclaration* genericConstraints, Array<BfGenericParamDef*>& genericParams, Array<BfExternalConstraintDef>* externConstraintDefs, int outerGenericSize, bool isInGeneric); void ParseGenericParams(BfGenericParamsDeclaration* genericParamsDecl, BfGenericConstraintsDeclaration* genericConstraints, Array<BfGenericParamDef*>& genericParams, Array<BfExternalConstraintDef>* externConstraintDefs, int outerGenericSize, bool isInGeneric);
BfProtection GetProtection(BfAstNode* protectionNode); BfProtection GetProtection(BfAstNode* protectionNode);
bool WantsNode(BfAstNode* wholeNode, BfAstNode* startNode = NULL, int addLen = 0); bool WantsNode(BfAstNode* wholeNode, BfAstNode* startNode = NULL, int addLen = 0);
//static BfNamedTypeReference* AllocTypeReference(BfSource* bfSource, const StringImpl& typeName); //static BfNamedTypeReference* AllocTypeReference(BfSource* bfSource, const StringImpl& typeName);
//static BfResolvedTypeReference* AllocTypeReference(BfSource* bfSource, BfType* type); //static BfResolvedTypeReference* AllocTypeReference(BfSource* bfSource, BfType* type);
static BfFieldDef* AddField(BfTypeDef* typeDef, BfTypeReference* typeRef, const StringImpl& name); static BfFieldDef* AddField(BfTypeDef* typeDef, BfTypeReference* typeRef, const StringImpl& name);
@ -67,18 +67,18 @@ public:
~BfDefBuilder(); ~BfDefBuilder();
void Process(BfPassInstance* passInstance, BfSource* bfSource, bool fullRefresh); void Process(BfPassInstance* passInstance, BfSource* bfSource, bool fullRefresh);
void RemoveDefsFrom(BfSource* bfSource); void RemoveDefsFrom(BfSource* bfSource);
virtual void Visit(BfIdentifierNode* identifier) override; virtual void Visit(BfIdentifierNode* identifier) override;
virtual void Visit(BfMethodDeclaration* methodDeclaration) override; virtual void Visit(BfMethodDeclaration* methodDeclaration) override;
virtual void Visit(BfConstructorDeclaration* ctorDeclaration) override; virtual void Visit(BfConstructorDeclaration* ctorDeclaration) override;
virtual void Visit(BfPropertyDeclaration* propertyDeclaration) override; virtual void Visit(BfPropertyDeclaration* propertyDeclaration) override;
virtual void Visit(BfFieldDeclaration* fieldDeclaration) override; virtual void Visit(BfFieldDeclaration* fieldDeclaration) override;
virtual void Visit(BfEnumCaseDeclaration* enumCaseDeclaration) override; virtual void Visit(BfEnumCaseDeclaration* enumCaseDeclaration) override;
virtual void Visit(BfTypeDeclaration* typeDeclaration) override; virtual void Visit(BfTypeDeclaration* typeDeclaration) override;
virtual void Visit(BfUsingDirective* usingDirective) override; virtual void Visit(BfUsingDirective* usingDirective) override;
virtual void Visit(BfUsingModDirective* usingDirective) override; virtual void Visit(BfUsingModDirective* usingDirective) override;
virtual void Visit(BfNamespaceDeclaration* namespaceDeclaration) override; virtual void Visit(BfNamespaceDeclaration* namespaceDeclaration) override;
virtual void Visit(BfBlock* block) override; virtual void Visit(BfBlock* block) override;
virtual void Visit(BfRootNode* rootNode) override; virtual void Visit(BfRootNode* rootNode) override;
}; };

View file

@ -8,14 +8,14 @@ BfDeferEvalChecker::BfDeferEvalChecker()
mRootNode = NULL; mRootNode = NULL;
mNeedsDeferEval = false; mNeedsDeferEval = false;
mDeferLiterals = true; mDeferLiterals = true;
mDeferDelegateBind = true; mDeferDelegateBind = true;
} }
void BfDeferEvalChecker::Check(BfAstNode* node) void BfDeferEvalChecker::Check(BfAstNode* node)
{ {
if (auto namedNode = BfNodeDynCastExact<BfNamedExpression>(node)) if (auto namedNode = BfNodeDynCastExact<BfNamedExpression>(node))
node = namedNode->mExpression; node = namedNode->mExpression;
if (node == NULL) if (node == NULL)
return; return;
@ -46,16 +46,16 @@ void BfDeferEvalChecker::Visit(BfLiteralExpression* literalExpr)
case BfTypeCode_Boolean: case BfTypeCode_Boolean:
case BfTypeCode_Char8: case BfTypeCode_Char8:
case BfTypeCode_Int8: case BfTypeCode_Int8:
case BfTypeCode_UInt8: case BfTypeCode_UInt8:
case BfTypeCode_Int16: case BfTypeCode_Int16:
case BfTypeCode_UInt16: case BfTypeCode_UInt16:
case BfTypeCode_Int32: case BfTypeCode_Int32:
case BfTypeCode_UInt32: case BfTypeCode_UInt32:
case BfTypeCode_Int64: case BfTypeCode_Int64:
case BfTypeCode_UInt64: case BfTypeCode_UInt64:
case BfTypeCode_IntPtr: case BfTypeCode_IntPtr:
case BfTypeCode_UIntPtr: case BfTypeCode_UIntPtr:
case BfTypeCode_IntUnknown: case BfTypeCode_IntUnknown:
case BfTypeCode_UIntUnknown: case BfTypeCode_UIntUnknown:
if (mDeferLiterals) if (mDeferLiterals)
mNeedsDeferEval = true; mNeedsDeferEval = true;
@ -63,11 +63,10 @@ void BfDeferEvalChecker::Visit(BfLiteralExpression* literalExpr)
default: default:
mNeedsDeferEval = false; mNeedsDeferEval = false;
} }
} }
void BfDeferEvalChecker::Visit(BfCastExpression* castExpr) void BfDeferEvalChecker::Visit(BfCastExpression* castExpr)
{ {
if (auto namedTypeRef = BfNodeDynCastExact<BfNamedTypeReference>(castExpr->mTypeRef)) if (auto namedTypeRef = BfNodeDynCastExact<BfNamedTypeReference>(castExpr->mTypeRef))
{ {
if (namedTypeRef->ToString() == "ExpectedType") if (namedTypeRef->ToString() == "ExpectedType")
@ -122,11 +121,11 @@ void BfDeferEvalChecker::Visit(BfDelegateBindExpression* delegateBindExpr)
} }
void BfDeferEvalChecker::Visit(BfConditionalExpression* condExpr) void BfDeferEvalChecker::Visit(BfConditionalExpression* condExpr)
{ {
VisitChild(condExpr->mConditionExpression); VisitChild(condExpr->mConditionExpression);
bool prev = mNeedsDeferEval; bool prev = mNeedsDeferEval;
VisitChild(condExpr->mTrueExpression); VisitChild(condExpr->mTrueExpression);
prev |= mNeedsDeferEval; prev |= mNeedsDeferEval;
VisitChild(condExpr->mFalseExpression); VisitChild(condExpr->mFalseExpression);
mNeedsDeferEval |= prev; mNeedsDeferEval |= prev;
} }
@ -154,7 +153,7 @@ void BfDeferEvalChecker::Visit(BfObjectCreateExpression * objCreateExpr)
{ {
if (objCreateExpr->mTypeRef->IsExact<BfDotTypeReference>()) if (objCreateExpr->mTypeRef->IsExact<BfDotTypeReference>())
mNeedsDeferEval = true; mNeedsDeferEval = true;
} }
} }
void BfDeferEvalChecker::Visit(BfBinaryOperatorExpression* binOpExpr) void BfDeferEvalChecker::Visit(BfBinaryOperatorExpression* binOpExpr)
@ -170,14 +169,14 @@ void BfDeferEvalChecker::Visit(BfBinaryOperatorExpression* binOpExpr)
case BfBinaryOp_BitwiseOr: case BfBinaryOp_BitwiseOr:
case BfBinaryOp_ExclusiveOr: case BfBinaryOp_ExclusiveOr:
case BfBinaryOp_LeftShift: case BfBinaryOp_LeftShift:
case BfBinaryOp_RightShift: case BfBinaryOp_RightShift:
case BfBinaryOp_GreaterThan: case BfBinaryOp_GreaterThan:
case BfBinaryOp_LessThan: case BfBinaryOp_LessThan:
case BfBinaryOp_GreaterThanOrEqual: case BfBinaryOp_GreaterThanOrEqual:
case BfBinaryOp_LessThanOrEqual: case BfBinaryOp_LessThanOrEqual:
{ {
VisitChild(binOpExpr->mLeft); VisitChild(binOpExpr->mLeft);
bool prev = mNeedsDeferEval; bool prev = mNeedsDeferEval;
VisitChild(binOpExpr->mRight); VisitChild(binOpExpr->mRight);
mNeedsDeferEval |= prev; mNeedsDeferEval |= prev;
} }
@ -188,7 +187,7 @@ void BfDeferEvalChecker::Visit(BfBinaryOperatorExpression* binOpExpr)
} }
void BfDeferEvalChecker::Visit(BfDefaultExpression* defaultExpr) void BfDeferEvalChecker::Visit(BfDefaultExpression* defaultExpr)
{ {
if (defaultExpr->mTypeRef == NULL) if (defaultExpr->mTypeRef == NULL)
mNeedsDeferEval = true; mNeedsDeferEval = true;
} }
@ -197,5 +196,4 @@ void BfDeferEvalChecker::Visit(BfVariableDeclaration* varDecl)
{ {
if (varDecl != mRootNode) if (varDecl != mRootNode)
mNeedsDeferEval = true; mNeedsDeferEval = true;
} }

View file

@ -11,7 +11,7 @@ public:
BfAstNode* mRootNode; BfAstNode* mRootNode;
bool mNeedsDeferEval; bool mNeedsDeferEval;
bool mDeferDelegateBind; bool mDeferDelegateBind;
bool mDeferLiterals; bool mDeferLiterals;
public: public:
BfDeferEvalChecker(); BfDeferEvalChecker();
@ -19,7 +19,7 @@ public:
void Check(BfAstNode* node); void Check(BfAstNode* node);
virtual void Visit(BfAstNode* node) override; virtual void Visit(BfAstNode* node) override;
virtual void Visit(BfAttributedExpression* attributedExpr) override; virtual void Visit(BfAttributedExpression* attributedExpr) override;
virtual void Visit(BfInitializerExpression* collectionInitExpr) override; virtual void Visit(BfInitializerExpression* collectionInitExpr) override;
virtual void Visit(BfLiteralExpression* literalExpr) override; virtual void Visit(BfLiteralExpression* literalExpr) override;
@ -38,5 +38,4 @@ public:
virtual void Visit(BfVariableDeclaration* varDecl) override; virtual void Visit(BfVariableDeclaration* varDecl) override;
}; };
NS_BF_END NS_BF_END

File diff suppressed because it is too large Load diff

View file

@ -14,7 +14,7 @@ public:
int mCurIdx; int mCurIdx;
String mResult; String mResult;
bool mFailed; bool mFailed;
String mMangledName; String mMangledName;
SubstituteList mSubstituteList; SubstituteList mSubstituteList;
bool mInArgs; bool mInArgs;
bool mBeefFixed; bool mBeefFixed;
@ -28,25 +28,25 @@ public:
class DwDemangler : public DemangleBase class DwDemangler : public DemangleBase
{ {
public: public:
SubstituteList mTemplateList; SubstituteList mTemplateList;
bool mIsFirstName; bool mIsFirstName;
int mTemplateDepth; int mTemplateDepth;
bool mOmitSubstituteAdd; bool mOmitSubstituteAdd;
bool mCaptureTargetType; bool mCaptureTargetType;
bool mFunctionPopSubstitute; bool mFunctionPopSubstitute;
bool mRawDemangle; bool mRawDemangle;
public: public:
bool DemangleEnd(); bool DemangleEnd();
bool DemangleArrayType(StringImpl& outName); bool DemangleArrayType(StringImpl& outName);
bool DemangleBuiltinType(StringImpl& outName); bool DemangleBuiltinType(StringImpl& outName);
bool DemangleFunctionType(StringImpl& outName); bool DemangleFunctionType(StringImpl& outName);
bool DemangleSourceName(StringImpl& outName); bool DemangleSourceName(StringImpl& outName);
bool DemangleRefQualifier(StringImpl& outName); bool DemangleRefQualifier(StringImpl& outName);
bool DemangleType(StringImpl& outName); bool DemangleType(StringImpl& outName);
bool DemangleNestedName(StringImpl& outName); bool DemangleNestedName(StringImpl& outName);
bool DemangleCVQualifiers(StringImpl& outName); bool DemangleCVQualifiers(StringImpl& outName);
bool DemangleOperatorName(StringImpl& outName); bool DemangleOperatorName(StringImpl& outName);
bool DemangleExprPriamry(StringImpl& outName); bool DemangleExprPriamry(StringImpl& outName);
bool DemangleTemplateArgPack(StringImpl& outName); bool DemangleTemplateArgPack(StringImpl& outName);
@ -62,7 +62,7 @@ public:
bool DemangleName(StringImpl& outName, bool* outHasTemplateArgs = NULL); bool DemangleName(StringImpl& outName, bool* outHasTemplateArgs = NULL);
bool DemangleFunction(StringImpl& outName); bool DemangleFunction(StringImpl& outName);
public: public:
DwDemangler(); DwDemangler();
String Demangle(const StringImpl& mangledName); String Demangle(const StringImpl& mangledName);
@ -104,7 +104,7 @@ public:
bool DemangleType(); bool DemangleType();
bool DemangleScopedName(); bool DemangleScopedName();
bool DemangleName(); bool DemangleName();
public: public:
MsDemangleScanner(); MsDemangleScanner();

View file

@ -6,7 +6,6 @@ USING_NS_BF;
BfElementVisitor::BfElementVisitor() BfElementVisitor::BfElementVisitor()
{ {
} }
void BfElementVisitor::Visit(BfTypedValueExpression* typedValueExpr) void BfElementVisitor::Visit(BfTypedValueExpression* typedValueExpr)
@ -36,7 +35,7 @@ void BfElementVisitor::Visit(BfPreprocessorDefinedExpression* definedExpr)
{ {
Visit(definedExpr->ToBase()); Visit(definedExpr->ToBase());
VisitChild(definedExpr->mIdentifier); VisitChild(definedExpr->mIdentifier);
} }
void BfElementVisitor::Visit(BfAttributeDirective* attributeDirective) void BfElementVisitor::Visit(BfAttributeDirective* attributeDirective)
@ -65,7 +64,7 @@ void BfElementVisitor::Visit(BfGenericParamsDeclaration* genericParams)
for (auto& val : genericParams->mGenericParams) for (auto& val : genericParams->mGenericParams)
VisitChild(val); VisitChild(val);
for (auto& val : genericParams->mCommas) for (auto& val : genericParams->mCommas)
VisitChild(val); VisitChild(val);
VisitChild(genericParams->mCloseChevron); VisitChild(genericParams->mCloseChevron);
} }
@ -84,7 +83,7 @@ void BfElementVisitor::Visit(BfGenericConstraintsDeclaration* genericConstraints
Visit(genericConstraints->ToBase()); Visit(genericConstraints->ToBase());
for (auto genericConstraintNode : genericConstraints->mGenericConstraints) for (auto genericConstraintNode : genericConstraints->mGenericConstraints)
{ {
if (auto genericConstraint = BfNodeDynCast<BfGenericConstraint>(genericConstraintNode)) if (auto genericConstraint = BfNodeDynCast<BfGenericConstraint>(genericConstraintNode))
{ {
VisitChild(genericConstraint->mWhereToken); VisitChild(genericConstraint->mWhereToken);
@ -100,7 +99,7 @@ void BfElementVisitor::Visit(BfGenericConstraintsDeclaration* genericConstraints
VisitChild(genericConstraintExpr->mWhereToken); VisitChild(genericConstraintExpr->mWhereToken);
VisitChild(genericConstraintExpr->mExpression); VisitChild(genericConstraintExpr->mExpression);
} }
} }
} }
void BfElementVisitor::Visit(BfGenericArgumentsNode* genericArgumentsNode) void BfElementVisitor::Visit(BfGenericArgumentsNode* genericArgumentsNode)
@ -111,7 +110,7 @@ void BfElementVisitor::Visit(BfGenericArgumentsNode* genericArgumentsNode)
for (auto& val : genericArgumentsNode->mGenericArgs) for (auto& val : genericArgumentsNode->mGenericArgs)
VisitChild(val); VisitChild(val);
for (auto& val : genericArgumentsNode->mCommas) for (auto& val : genericArgumentsNode->mCommas)
VisitChild(val); VisitChild(val);
VisitChild(genericArgumentsNode->mCloseChevron); VisitChild(genericArgumentsNode->mCloseChevron);
} }
@ -169,7 +168,7 @@ void BfElementVisitor::Visit(BfNewNode* newNode)
void BfElementVisitor::Visit(BfLabeledBlock* labeledBlock) void BfElementVisitor::Visit(BfLabeledBlock* labeledBlock)
{ {
Visit(labeledBlock->ToBase()); Visit(labeledBlock->ToBase());
VisitChild(labeledBlock->mBlock); VisitChild(labeledBlock->mBlock);
} }
@ -266,7 +265,7 @@ void BfElementVisitor::Visit(BfQualifiedNameNode* nameNode)
void BfElementVisitor::Visit(BfThisExpression* thisExpr) void BfElementVisitor::Visit(BfThisExpression* thisExpr)
{ {
Visit(thisExpr->ToBase()); Visit(thisExpr->ToBase());
} }
void BfElementVisitor::Visit(BfBaseExpression* baseExpr) void BfElementVisitor::Visit(BfBaseExpression* baseExpr)
@ -306,9 +305,9 @@ void BfElementVisitor::Visit(BfCollectionInitializerExpression* collectionInitEx
VisitChild(collectionInitExpr->mOpenBrace); VisitChild(collectionInitExpr->mOpenBrace);
for (auto& val : collectionInitExpr->mValues) for (auto& val : collectionInitExpr->mValues)
VisitChild(val); VisitChild(val);
for (auto& val : collectionInitExpr->mCommas) for (auto& val : collectionInitExpr->mCommas)
VisitChild(val); VisitChild(val);
VisitChild(collectionInitExpr->mCloseBrace); VisitChild(collectionInitExpr->mCloseBrace);
} }
@ -327,7 +326,7 @@ void BfElementVisitor::Visit(BfNamedTypeReference* typeRef)
void BfElementVisitor::Visit(BfQualifiedTypeReference* qualifiedTypeRef) void BfElementVisitor::Visit(BfQualifiedTypeReference* qualifiedTypeRef)
{ {
Visit(qualifiedTypeRef->ToBase()); Visit(qualifiedTypeRef->ToBase());
VisitChild(qualifiedTypeRef->mLeft); VisitChild(qualifiedTypeRef->mLeft);
VisitChild(qualifiedTypeRef->mDot); VisitChild(qualifiedTypeRef->mDot);
VisitChild(qualifiedTypeRef->mRight); VisitChild(qualifiedTypeRef->mRight);
@ -381,17 +380,17 @@ void BfElementVisitor::Visit(BfConstExprTypeRef* typeRef)
void BfElementVisitor::Visit(BfRefTypeRef* typeRef) void BfElementVisitor::Visit(BfRefTypeRef* typeRef)
{ {
Visit((BfTypeReference*)typeRef); // Skip the Elemented part so we can put the element in the right spot Visit((BfTypeReference*)typeRef); // Skip the Elemented part so we can put the element in the right spot
VisitChild(typeRef->mRefToken); VisitChild(typeRef->mRefToken);
VisitChild(typeRef->mElementType); VisitChild(typeRef->mElementType);
} }
void BfElementVisitor::Visit(BfModifiedTypeRef * typeRef) void BfElementVisitor::Visit(BfModifiedTypeRef * typeRef)
{ {
Visit((BfTypeReference*)typeRef); // Skip the Elemented part so we can put the element in the right spot Visit((BfTypeReference*)typeRef); // Skip the Elemented part so we can put the element in the right spot
VisitChild(typeRef->mRetTypeToken); VisitChild(typeRef->mRetTypeToken);
VisitChild(typeRef->mOpenParen); VisitChild(typeRef->mOpenParen);
VisitChild(typeRef->mElementType); VisitChild(typeRef->mElementType);
VisitChild(typeRef->mCloseParen); VisitChild(typeRef->mCloseParen);
} }
@ -399,11 +398,11 @@ void BfElementVisitor::Visit(BfModifiedTypeRef * typeRef)
void BfElementVisitor::Visit(BfArrayTypeRef* typeRef) void BfElementVisitor::Visit(BfArrayTypeRef* typeRef)
{ {
Visit((BfTypeReference*)typeRef); // Skip the Elemented part so we can put the element in the right spot Visit((BfTypeReference*)typeRef); // Skip the Elemented part so we can put the element in the right spot
VisitChild(typeRef->mElementType); VisitChild(typeRef->mElementType);
VisitChild(typeRef->mOpenBracket); VisitChild(typeRef->mOpenBracket);
for (auto& val : typeRef->mParams) for (auto& val : typeRef->mParams)
VisitChild(val); VisitChild(val);
VisitChild(typeRef->mCloseBracket); VisitChild(typeRef->mCloseBracket);
} }
@ -413,7 +412,7 @@ void BfElementVisitor::Visit(BfGenericInstanceTypeRef* typeRef)
VisitChild(typeRef->mOpenChevron); VisitChild(typeRef->mOpenChevron);
for (auto& val : typeRef->mGenericArguments) for (auto& val : typeRef->mGenericArguments)
VisitChild(val); VisitChild(val);
if (typeRef->mCommas.mVals != NULL) if (typeRef->mCommas.mVals != NULL)
{ {
for (auto& val : typeRef->mCommas) for (auto& val : typeRef->mCommas)
@ -428,7 +427,7 @@ void BfElementVisitor::Visit(BfTupleTypeRef* typeRef)
VisitChild(typeRef->mOpenParen); VisitChild(typeRef->mOpenParen);
for (auto& val : typeRef->mFieldNames) for (auto& val : typeRef->mFieldNames)
VisitChild(val); VisitChild(val);
for (auto& val : typeRef->mFieldTypes) for (auto& val : typeRef->mFieldTypes)
VisitChild(val); VisitChild(val);
if (typeRef->mCommas.mVals != NULL) if (typeRef->mCommas.mVals != NULL)
@ -535,7 +534,7 @@ void BfElementVisitor::Visit(BfNameOfExpression* nameOfExpr)
VisitChild(nameOfExpr->mToken); VisitChild(nameOfExpr->mToken);
VisitChild(nameOfExpr->mOpenParen); VisitChild(nameOfExpr->mOpenParen);
VisitChild(nameOfExpr->mTarget); VisitChild(nameOfExpr->mTarget);
VisitChild(nameOfExpr->mCloseParen); VisitChild(nameOfExpr->mCloseParen);
} }
@ -608,16 +607,16 @@ void BfElementVisitor::Visit(BfLambdaBindExpression* lambdaBindExpr)
Visit(lambdaBindExpr->ToBase()); Visit(lambdaBindExpr->ToBase());
VisitChild(lambdaBindExpr->mNewToken); VisitChild(lambdaBindExpr->mNewToken);
VisitChild(lambdaBindExpr->mOpenParen); VisitChild(lambdaBindExpr->mOpenParen);
VisitChild(lambdaBindExpr->mCloseParen); VisitChild(lambdaBindExpr->mCloseParen);
for (auto& val : lambdaBindExpr->mParams) for (auto& val : lambdaBindExpr->mParams)
VisitChild(val); VisitChild(val);
for (auto& val : lambdaBindExpr->mCommas) for (auto& val : lambdaBindExpr->mCommas)
VisitChild(val); VisitChild(val);
VisitChild(lambdaBindExpr->mFatArrowToken); VisitChild(lambdaBindExpr->mFatArrowToken);
VisitChild(lambdaBindExpr->mBody); // Either expression or block VisitChild(lambdaBindExpr->mBody); // Either expression or block
VisitChild(lambdaBindExpr->mDtor); VisitChild(lambdaBindExpr->mDtor);
} }
@ -627,13 +626,13 @@ void BfElementVisitor::Visit(BfObjectCreateExpression* newExpr)
VisitChild(newExpr->mNewNode); VisitChild(newExpr->mNewNode);
VisitChild(newExpr->mStarToken); VisitChild(newExpr->mStarToken);
VisitChild(newExpr->mTypeRef); VisitChild(newExpr->mTypeRef);
VisitChild(newExpr->mOpenToken); VisitChild(newExpr->mOpenToken);
VisitChild(newExpr->mCloseToken); VisitChild(newExpr->mCloseToken);
for (auto& val : newExpr->mArguments) for (auto& val : newExpr->mArguments)
VisitChild(val); VisitChild(val);
for (auto& val : newExpr->mCommas) for (auto& val : newExpr->mCommas)
VisitChild(val); VisitChild(val);
} }
void BfElementVisitor::Visit(BfBoxExpression* boxExpr) void BfElementVisitor::Visit(BfBoxExpression* boxExpr)
@ -665,7 +664,7 @@ void BfElementVisitor::Visit(BfThrowStatement* throwStmt)
void BfElementVisitor::Visit(BfDeleteStatement* deleteStmt) void BfElementVisitor::Visit(BfDeleteStatement* deleteStmt)
{ {
Visit(deleteStmt->ToBase()); Visit(deleteStmt->ToBase());
VisitChild(deleteStmt->mDeleteToken); VisitChild(deleteStmt->mDeleteToken);
VisitChild(deleteStmt->mTargetTypeToken); VisitChild(deleteStmt->mTargetTypeToken);
VisitChild(deleteStmt->mAllocExpr); VisitChild(deleteStmt->mAllocExpr);
@ -683,7 +682,7 @@ void BfElementVisitor::Visit(BfInvocationExpression* invocationExpr)
for (auto& val : invocationExpr->mArguments) for (auto& val : invocationExpr->mArguments)
VisitChild(val); VisitChild(val);
for (auto& val : invocationExpr->mCommas) for (auto& val : invocationExpr->mCommas)
VisitChild(val); VisitChild(val);
} }
void BfElementVisitor::Visit(BfEnumCaseBindExpression* caseBindExpr) void BfElementVisitor::Visit(BfEnumCaseBindExpression* caseBindExpr)
@ -713,7 +712,7 @@ void BfElementVisitor::Visit(BfSwitchCase* switchCase)
for (auto& val : switchCase->mCaseExpressions) for (auto& val : switchCase->mCaseExpressions)
VisitChild(val); VisitChild(val);
for (auto& val : switchCase->mCaseCommas) for (auto& val : switchCase->mCaseCommas)
VisitChild(val); VisitChild(val);
VisitChild(switchCase->mColonToken); VisitChild(switchCase->mColonToken);
VisitChild(switchCase->mCodeBlock); VisitChild(switchCase->mCodeBlock);
VisitChild(switchCase->mEndingToken); VisitChild(switchCase->mEndingToken);
@ -808,13 +807,13 @@ void BfElementVisitor::Visit(BfDeferStatement* deferStmt)
if (deferStmt->mBind != NULL) if (deferStmt->mBind != NULL)
{ {
auto bind = deferStmt->mBind; auto bind = deferStmt->mBind;
VisitChild(bind->mOpenBracket); VisitChild(bind->mOpenBracket);
VisitChild(bind->mCloseBracket); VisitChild(bind->mCloseBracket);
for (auto& val : bind->mParams) for (auto& val : bind->mParams)
VisitChild(val); VisitChild(val);
for (auto& val : bind->mCommas) for (auto& val : bind->mCommas)
VisitChild(val); VisitChild(val);
} }
VisitChild(deferStmt->mOpenParen); VisitChild(deferStmt->mOpenParen);
@ -849,7 +848,6 @@ void BfElementVisitor::Visit(BfUsingStatement* usingStmt)
VisitChild(usingStmt->mVariableDeclaration); VisitChild(usingStmt->mVariableDeclaration);
VisitChild(usingStmt->mCloseParen); VisitChild(usingStmt->mCloseParen);
VisitChild(usingStmt->mEmbeddedStatement); VisitChild(usingStmt->mEmbeddedStatement);
} }
void BfElementVisitor::Visit(BfDoStatement* doStmt) void BfElementVisitor::Visit(BfDoStatement* doStmt)
@ -857,7 +855,7 @@ void BfElementVisitor::Visit(BfDoStatement* doStmt)
Visit(doStmt->ToBase()); Visit(doStmt->ToBase());
VisitChild(doStmt->mDoToken); VisitChild(doStmt->mDoToken);
VisitChild(doStmt->mEmbeddedStatement); VisitChild(doStmt->mEmbeddedStatement);
} }
void BfElementVisitor::Visit(BfRepeatStatement* repeatStmt) void BfElementVisitor::Visit(BfRepeatStatement* repeatStmt)
@ -915,14 +913,14 @@ void BfElementVisitor::Visit(BfForStatement* forStmt)
for (auto& val : forStmt->mInitializers) for (auto& val : forStmt->mInitializers)
VisitChild(val); VisitChild(val);
for (auto& val : forStmt->mInitializerCommas) for (auto& val : forStmt->mInitializerCommas)
VisitChild(val); VisitChild(val);
VisitChild(forStmt->mInitializerSemicolon); VisitChild(forStmt->mInitializerSemicolon);
VisitChild(forStmt->mCondition); VisitChild(forStmt->mCondition);
VisitChild(forStmt->mConditionSemicolon); VisitChild(forStmt->mConditionSemicolon);
for (auto& val : forStmt->mIterators) for (auto& val : forStmt->mIterators)
VisitChild(val); VisitChild(val);
for (auto& val : forStmt->mIteratorCommas) for (auto& val : forStmt->mIteratorCommas)
VisitChild(val); VisitChild(val);
VisitChild(forStmt->mCloseParen); VisitChild(forStmt->mCloseParen);
VisitChild(forStmt->mEmbeddedStatement); VisitChild(forStmt->mEmbeddedStatement);
} }
@ -982,12 +980,12 @@ void BfElementVisitor::Visit(BfTupleExpression* tupleExpr)
{ {
VisitChild(val->mNameNode); VisitChild(val->mNameNode);
VisitChild(val->mColonToken); VisitChild(val->mColonToken);
} }
} }
for (auto& val : tupleExpr->mValues) for (auto& val : tupleExpr->mValues)
VisitChild(val); VisitChild(val);
for (auto& val : tupleExpr->mCommas) for (auto& val : tupleExpr->mCommas)
VisitChild(val); VisitChild(val);
VisitChild(tupleExpr->mCloseParen); VisitChild(tupleExpr->mCloseParen);
} }
@ -1006,11 +1004,11 @@ void BfElementVisitor::Visit(BfIndexerExpression* indexerExpr)
VisitChild(indexerExpr->mTarget); VisitChild(indexerExpr->mTarget);
VisitChild(indexerExpr->mOpenBracket); VisitChild(indexerExpr->mOpenBracket);
VisitChild(indexerExpr->mCloseBracket); VisitChild(indexerExpr->mCloseBracket);
for (auto& arg : indexerExpr->mArguments) for (auto& arg : indexerExpr->mArguments)
VisitChild(arg); VisitChild(arg);
for (auto& comma : indexerExpr->mCommas) for (auto& comma : indexerExpr->mCommas)
VisitChild(comma); VisitChild(comma);
} }
void BfElementVisitor::Visit(BfUnaryOperatorExpression* binOpExpr) void BfElementVisitor::Visit(BfUnaryOperatorExpression* binOpExpr)
@ -1052,11 +1050,11 @@ void BfElementVisitor::Visit(BfMethodDeclaration* methodDeclaration)
{ {
Visit(methodDeclaration->ToBase()); Visit(methodDeclaration->ToBase());
VisitChild(methodDeclaration->mAttributes); VisitChild(methodDeclaration->mAttributes);
VisitChild(methodDeclaration->mProtectionSpecifier); VisitChild(methodDeclaration->mProtectionSpecifier);
VisitChild(methodDeclaration->mReadOnlySpecifier); VisitChild(methodDeclaration->mReadOnlySpecifier);
VisitChild(methodDeclaration->mStaticSpecifier); VisitChild(methodDeclaration->mStaticSpecifier);
VisitChild(methodDeclaration->mExternSpecifier); VisitChild(methodDeclaration->mExternSpecifier);
VisitChild(methodDeclaration->mVirtualSpecifier); // either 'virtual', 'override', or 'abstract' VisitChild(methodDeclaration->mVirtualSpecifier); // either 'virtual', 'override', or 'abstract'
VisitChild(methodDeclaration->mNewSpecifier); VisitChild(methodDeclaration->mNewSpecifier);
@ -1072,7 +1070,7 @@ void BfElementVisitor::Visit(BfMethodDeclaration* methodDeclaration)
for (auto& param : methodDeclaration->mParams) for (auto& param : methodDeclaration->mParams)
VisitChild(param); VisitChild(param);
for (auto& comma : methodDeclaration->mCommas) for (auto& comma : methodDeclaration->mCommas)
VisitChild(comma); VisitChild(comma);
VisitChild(methodDeclaration->mCloseParen); VisitChild(methodDeclaration->mCloseParen);
VisitChild(methodDeclaration->mGenericParams); VisitChild(methodDeclaration->mGenericParams);
VisitChild(methodDeclaration->mGenericConstraintsDeclaration); VisitChild(methodDeclaration->mGenericConstraintsDeclaration);
@ -1109,26 +1107,26 @@ void BfElementVisitor::Visit(BfPropertyBodyExpression* propertyBodyExpression)
Visit(propertyBodyExpression->ToBase()); Visit(propertyBodyExpression->ToBase());
VisitChild(propertyBodyExpression->mMutSpecifier); VisitChild(propertyBodyExpression->mMutSpecifier);
VisitChild(propertyBodyExpression->mFatTokenArrow); VisitChild(propertyBodyExpression->mFatTokenArrow);
} }
void BfElementVisitor::Visit(BfPropertyDeclaration* propertyDeclaration) void BfElementVisitor::Visit(BfPropertyDeclaration* propertyDeclaration)
{ {
Visit(propertyDeclaration->ToBase()); Visit(propertyDeclaration->ToBase());
VisitChild(propertyDeclaration->mAttributes); VisitChild(propertyDeclaration->mAttributes);
VisitChild(propertyDeclaration->mProtectionSpecifier); VisitChild(propertyDeclaration->mProtectionSpecifier);
VisitChild(propertyDeclaration->mStaticSpecifier); VisitChild(propertyDeclaration->mStaticSpecifier);
VisitChild(propertyDeclaration->mVirtualSpecifier); // either 'virtual', 'override', or 'abstract' VisitChild(propertyDeclaration->mVirtualSpecifier); // either 'virtual', 'override', or 'abstract'
VisitChild(propertyDeclaration->mExplicitInterface); VisitChild(propertyDeclaration->mExplicitInterface);
VisitChild(propertyDeclaration->mExplicitInterfaceDotToken); VisitChild(propertyDeclaration->mExplicitInterfaceDotToken);
if (auto block = BfNodeDynCast<BfBlock>(propertyDeclaration->mDefinitionBlock)) if (auto block = BfNodeDynCast<BfBlock>(propertyDeclaration->mDefinitionBlock))
{ {
VisitChild(block->mOpenBrace); VisitChild(block->mOpenBrace);
for (auto& method : propertyDeclaration->mMethods) for (auto& method : propertyDeclaration->mMethods)
VisitChild(method); VisitChild(method);
VisitChild(block->mCloseBrace); VisitChild(block->mCloseBrace);
} }
else else
@ -1156,7 +1154,7 @@ void BfElementVisitor::Visit(BfFieldDeclaration* fieldDeclaration)
{ {
Visit(fieldDeclaration->ToBase()); Visit(fieldDeclaration->ToBase());
VisitChild(fieldDeclaration->mAttributes); VisitChild(fieldDeclaration->mAttributes);
VisitChild(fieldDeclaration->mProtectionSpecifier); VisitChild(fieldDeclaration->mProtectionSpecifier);
VisitChild(fieldDeclaration->mStaticSpecifier); VisitChild(fieldDeclaration->mStaticSpecifier);
@ -1181,7 +1179,7 @@ void BfElementVisitor::Visit(BfEnumCaseDeclaration* enumCaseDeclaration)
for (auto& entry : enumCaseDeclaration->mEntries) for (auto& entry : enumCaseDeclaration->mEntries)
VisitChild(entry); VisitChild(entry);
for (auto& comma : enumCaseDeclaration->mCommas) for (auto& comma : enumCaseDeclaration->mCommas)
VisitChild(comma); VisitChild(comma);
} }
void BfElementVisitor::Visit(BfFieldDtorDeclaration* fieldDtorDeclaration) void BfElementVisitor::Visit(BfFieldDtorDeclaration* fieldDtorDeclaration)
@ -1199,7 +1197,7 @@ void BfElementVisitor::Visit(BfTypeDeclaration* typeDeclaration)
VisitChild(typeDeclaration->mAttributes); VisitChild(typeDeclaration->mAttributes);
VisitChild(typeDeclaration->mAbstractSpecifier); VisitChild(typeDeclaration->mAbstractSpecifier);
VisitChild(typeDeclaration->mSealedSpecifier); VisitChild(typeDeclaration->mSealedSpecifier);
VisitChild(typeDeclaration->mProtectionSpecifier); VisitChild(typeDeclaration->mProtectionSpecifier);
VisitChild(typeDeclaration->mStaticSpecifier); VisitChild(typeDeclaration->mStaticSpecifier);
VisitChild(typeDeclaration->mPartialSpecifier); VisitChild(typeDeclaration->mPartialSpecifier);
@ -1210,7 +1208,7 @@ void BfElementVisitor::Visit(BfTypeDeclaration* typeDeclaration)
for (auto& baseClass : typeDeclaration->mBaseClasses) for (auto& baseClass : typeDeclaration->mBaseClasses)
VisitChild(baseClass); VisitChild(baseClass);
for (auto& comma : typeDeclaration->mBaseClassCommas) for (auto& comma : typeDeclaration->mBaseClassCommas)
VisitChild(comma); VisitChild(comma);
VisitChild(typeDeclaration->mGenericParams); VisitChild(typeDeclaration->mGenericParams);
VisitChild(typeDeclaration->mGenericConstraintsDeclaration); VisitChild(typeDeclaration->mGenericConstraintsDeclaration);
@ -1221,7 +1219,6 @@ void BfElementVisitor::Visit(BfTypeDeclaration* typeDeclaration)
for (auto& member : *typeDeclaration->mDefineBlock) for (auto& member : *typeDeclaration->mDefineBlock)
VisitChild(member); VisitChild(member);
}*/ }*/
} }
void BfElementVisitor::Visit(BfTypeAliasDeclaration* typeDeclaration) void BfElementVisitor::Visit(BfTypeAliasDeclaration* typeDeclaration)
@ -1237,7 +1234,7 @@ void BfElementVisitor::Visit(BfUsingDirective* usingDirective)
{ {
Visit(usingDirective->ToBase()); Visit(usingDirective->ToBase());
VisitChild(usingDirective->mUsingToken); VisitChild(usingDirective->mUsingToken);
VisitChild(usingDirective->mNamespace); VisitChild(usingDirective->mNamespace);
} }

View file

@ -48,7 +48,7 @@ public:
virtual void Visit(BfMixinExpression* thisExpr); virtual void Visit(BfMixinExpression* thisExpr);
virtual void Visit(BfSizedArrayCreateExpression* createExpr); virtual void Visit(BfSizedArrayCreateExpression* createExpr);
virtual void Visit(BfInitializerExpression* initExpr); virtual void Visit(BfInitializerExpression* initExpr);
virtual void Visit(BfCollectionInitializerExpression* collectionInitExpr); virtual void Visit(BfCollectionInitializerExpression* collectionInitExpr);
virtual void Visit(BfTypeReference* typeRef); virtual void Visit(BfTypeReference* typeRef);
virtual void Visit(BfNamedTypeReference* typeRef); virtual void Visit(BfNamedTypeReference* typeRef);
virtual void Visit(BfQualifiedTypeReference* qualifiedType); virtual void Visit(BfQualifiedTypeReference* qualifiedType);
@ -69,8 +69,8 @@ public:
virtual void Visit(BfNullableTypeRef* typeRef); virtual void Visit(BfNullableTypeRef* typeRef);
virtual void Visit(BfVariableDeclaration* varDecl); virtual void Visit(BfVariableDeclaration* varDecl);
virtual void Visit(BfLocalMethodDeclaration* methodDecl); virtual void Visit(BfLocalMethodDeclaration* methodDecl);
virtual void Visit(BfParameterDeclaration* paramDecl); virtual void Visit(BfParameterDeclaration* paramDecl);
virtual void Visit(BfTypeAttrExpression* typeAttrExpr); virtual void Visit(BfTypeAttrExpression* typeAttrExpr);
virtual void Visit(BfOffsetOfExpression* offsetOfExpr); virtual void Visit(BfOffsetOfExpression* offsetOfExpr);
virtual void Visit(BfNameOfExpression* nameOfExpr); virtual void Visit(BfNameOfExpression* nameOfExpr);
virtual void Visit(BfDefaultExpression* defaultExpr); virtual void Visit(BfDefaultExpression* defaultExpr);
@ -85,7 +85,7 @@ public:
virtual void Visit(BfBoxExpression* boxExpr); virtual void Visit(BfBoxExpression* boxExpr);
virtual void Visit(BfScopedInvocationTarget* scopedTarget); virtual void Visit(BfScopedInvocationTarget* scopedTarget);
virtual void Visit(BfInvocationExpression* invocationExpr); virtual void Visit(BfInvocationExpression* invocationExpr);
virtual void Visit(BfDeferStatement* deferStmt); virtual void Visit(BfDeferStatement* deferStmt);
virtual void Visit(BfEnumCaseBindExpression* caseBindExpr); virtual void Visit(BfEnumCaseBindExpression* caseBindExpr);
virtual void Visit(BfCaseExpression* caseExpr); virtual void Visit(BfCaseExpression* caseExpr);
virtual void Visit(BfSwitchCase* switchCase); virtual void Visit(BfSwitchCase* switchCase);

View file

@ -762,7 +762,6 @@ void BfMethodMatcher::CompareMethods(BfMethodInstance* prevMethodInstance, BfTyp
return; return;
} }
if (newMethodDef->mExplicitInterface != prevMethodDef->mExplicitInterface) if (newMethodDef->mExplicitInterface != prevMethodDef->mExplicitInterface)
{ {
if (mModule->CompareMethodSignatures(newMethodInstance, prevMethodInstance)) if (mModule->CompareMethodSignatures(newMethodInstance, prevMethodInstance))
@ -1594,7 +1593,6 @@ bool BfMethodMatcher::InferFromGenericConstraints(BfMethodInstance* methodInstan
if (checkOpConstraint.mCastToken == BfToken_Implicit) if (checkOpConstraint.mCastToken == BfToken_Implicit)
{ {
} }
else else
{ {
@ -1603,7 +1601,6 @@ bool BfMethodMatcher::InferFromGenericConstraints(BfMethodInstance* methodInstan
if (checkOpConstraint.mCastToken == BfToken_Explicit) if (checkOpConstraint.mCastToken == BfToken_Explicit)
{ {
} }
else else
{ {
@ -1755,7 +1752,6 @@ bool BfMethodMatcher::CheckMethod(BfTypeInstance* targetTypeInstance, BfTypeInst
} }
} }
if (mHasArgNames) if (mHasArgNames)
{ {
checkMethod->BuildParamNameMap(); checkMethod->BuildParamNameMap();
@ -1788,7 +1784,6 @@ bool BfMethodMatcher::CheckMethod(BfTypeInstance* targetTypeInstance, BfTypeInst
} }
} }
for (auto& checkGenericArgRef : mCheckMethodGenericArguments) for (auto& checkGenericArgRef : mCheckMethodGenericArguments)
checkGenericArgRef = NULL; checkGenericArgRef = NULL;
@ -3068,7 +3063,6 @@ void BfMethodMatcher::TryDevirtualizeCall(BfTypedValue target, BfTypedValue* ori
// Failed // Failed
mFakeConcreteTarget = true; mFakeConcreteTarget = true;
} }
} }
} }
} }
@ -3796,7 +3790,6 @@ void BfExprEvaluator::Visit(BfCaseExpression* caseExpr)
if (mResult) if (mResult)
return; return;
} }
if ((caseValAddr) && (IsVar(caseValAddr.mType))) if ((caseValAddr) && (IsVar(caseValAddr.mType)))
@ -5523,7 +5516,6 @@ BfTypedValue BfExprEvaluator::LookupField(BfAstNode* targetSrc, BfTypedValue tar
else else
findName.Reference(fieldName); findName.Reference(fieldName);
auto activeTypeDef = mModule->GetActiveTypeDef(); auto activeTypeDef = mModule->GetActiveTypeDef();
for (int pass = 0; pass < 2; pass++) for (int pass = 0; pass < 2; pass++)
{ {
@ -6990,8 +6982,6 @@ BfTypedValue BfExprEvaluator::CreateCall(BfAstNode* targetSrc, BfMethodInstance*
return result; return result;
} }
BfTypedValue BfExprEvaluator::CreateCall(BfMethodMatcher* methodMatcher, BfTypedValue target) BfTypedValue BfExprEvaluator::CreateCall(BfMethodMatcher* methodMatcher, BfTypedValue target)
{ {
auto moduleMethodInstance = GetSelectedMethod(*methodMatcher); auto moduleMethodInstance = GetSelectedMethod(*methodMatcher);
@ -7273,7 +7263,6 @@ void BfExprEvaluator::PushThis(BfAstNode* targetSrc, BfTypedValue argVal, BfMeth
} }
} }
} }
} }
if (argVal.mType->IsValuelessType()) if (argVal.mType->IsValuelessType())
@ -7921,7 +7910,6 @@ BfTypedValue BfExprEvaluator::CreateCall(BfAstNode* targetSrc, const BfTypedValu
mModule->Warn(BfWarning_BF4205_StringInterpolationParam, "Expanded string interpolation argument not used as 'params'. If string allocation was intended then consider adding a specifier such as 'scope'.", errorRef); mModule->Warn(BfWarning_BF4205_StringInterpolationParam, "Expanded string interpolation argument not used as 'params'. If string allocation was intended then consider adding a specifier such as 'scope'.", errorRef);
} }
// if ((arg == NULL) && (argValues[argExprIdx].mExpression != NULL)) // if ((arg == NULL) && (argValues[argExprIdx].mExpression != NULL))
// hadMissingArg = true; // hadMissingArg = true;
@ -8009,7 +7997,6 @@ BfTypedValue BfExprEvaluator::CreateCall(BfAstNode* targetSrc, const BfTypedValu
if (auto typerDecl = BfNodeDynCast<BfTypeDeclaration>(mModule->mParentNodeEntry->mNode)) if (auto typerDecl = BfNodeDynCast<BfTypeDeclaration>(mModule->mParentNodeEntry->mNode))
showCtorError = true; showCtorError = true;
if (showCtorError) if (showCtorError)
{ {
if (mModule->PreFail()) if (mModule->PreFail())
@ -8848,7 +8835,6 @@ BfTypedValue BfExprEvaluator::ResolveArgValue(BfResolvedArg& resolvedArg, BfType
} }
} }
if (wantType->IsRef()) if (wantType->IsRef())
{ {
auto refType = (BfRefType*)wantType; auto refType = (BfRefType*)wantType;
@ -9587,7 +9573,6 @@ BfTypedValue BfExprEvaluator::MatchMethod(BfAstNode* targetSrc, BfMethodBoundExp
else if (isUnboundCall) else if (isUnboundCall)
{ {
//auto resolvedType = mModule->ResolveGenericType(lookupType); //auto resolvedType = mModule->ResolveGenericType(lookupType);
} }
else if (lookupType->IsGenericParam()) else if (lookupType->IsGenericParam())
{ {
@ -9869,7 +9854,6 @@ BfTypedValue BfExprEvaluator::MatchMethod(BfAstNode* targetSrc, BfMethodBoundExp
if (resolvedType != NULL) if (resolvedType != NULL)
resolvedTypeInstance = resolvedType->ToTypeInstance(); resolvedTypeInstance = resolvedType->ToTypeInstance();
} }
} }
else else
{ {
@ -10198,7 +10182,6 @@ BfTypedValue BfExprEvaluator::MatchMethod(BfAstNode* targetSrc, BfMethodBoundExp
if (methodDef == NULL) if (methodDef == NULL)
{ {
} }
// This will flush out any new ambiguity errors from extension methods // This will flush out any new ambiguity errors from extension methods
@ -10587,7 +10570,6 @@ BfTypedValue BfExprEvaluator::MatchMethod(BfAstNode* targetSrc, BfMethodBoundExp
mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str(), mModule->MethodToString(mModule->mCurMethodInstance).c_str()), targetSrc); mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str(), mModule->MethodToString(mModule->mCurMethodInstance).c_str()), targetSrc);
} }
BfTypedValue result; BfTypedValue result;
BfTypedValue argCascade; BfTypedValue argCascade;
@ -10950,7 +10932,6 @@ void BfExprEvaluator::LookupQualifiedName(BfAstNode* nameNode, BfIdentifierNode*
{ {
if (mResult.mType->IsSizedArray()) if (mResult.mType->IsSizedArray())
{ {
if (mResult.mType->IsValuelessType()) if (mResult.mType->IsValuelessType())
{ {
mResult.mType = mModule->GetWrappedStructType(mResult.mType); mResult.mType = mModule->GetWrappedStructType(mResult.mType);
@ -12935,7 +12916,6 @@ BfTypedValue BfExprEvaluator::DoImplicitArgCapture(BfAstNode* refNode, BfIdentif
BfLocalVarEntry* entry; BfLocalVarEntry* entry;
if (checkMethodState->mLocalVarSet.TryGetWith<StringImpl&>(findName, &entry)) if (checkMethodState->mLocalVarSet.TryGetWith<StringImpl&>(findName, &entry))
{ {
auto varDecl = entry->mLocalVar; auto varDecl = entry->mLocalVar;
while (varDecl != NULL) while (varDecl != NULL)
@ -12961,7 +12941,6 @@ BfTypedValue BfExprEvaluator::DoImplicitArgCapture(BfAstNode* refNode, BfIdentif
varDecl = varDecl->mShadowedLocal; varDecl = varDecl->mShadowedLocal;
} }
} }
// Check for the captured locals. It's important we do it here so we get local-first precedence still // Check for the captured locals. It's important we do it here so we get local-first precedence still
@ -13233,7 +13212,6 @@ void BfExprEvaluator::Visit(BfDelegateBindExpression* delegateBindExpr)
else else
delegateTypeInstance = mExpectingType->ToTypeInstance(); delegateTypeInstance = mExpectingType->ToTypeInstance();
if ((delegateTypeInstance == NULL) || if ((delegateTypeInstance == NULL) ||
((!delegateTypeInstance->IsDelegate()) && (!delegateTypeInstance->IsFunction()))) ((!delegateTypeInstance->IsDelegate()) && (!delegateTypeInstance->IsFunction())))
{ {
@ -14713,7 +14691,6 @@ BfLambdaInstance* BfExprEvaluator::GetLambdaInstance(BfLambdaBindExpression* lam
mModule->mBfIRBuilder->PopulateType(useTypeInstance); mModule->mBfIRBuilder->PopulateType(useTypeInstance);
mModule->PopulateType(useTypeInstance); mModule->PopulateType(useTypeInstance);
methodDef->mIsStatic = closureTypeInst == NULL; methodDef->mIsStatic = closureTypeInst == NULL;
SizedArray<BfIRType, 8> origParamTypes; SizedArray<BfIRType, 8> origParamTypes;
@ -14860,7 +14837,6 @@ BfLambdaInstance* BfExprEvaluator::GetLambdaInstance(BfLambdaBindExpression* lam
mModule->mBfIRBuilder->SaveDebugLocation(); mModule->mBfIRBuilder->SaveDebugLocation();
// //
{ {
BfGetSymbolReferenceKind prevSymbolRefKind = BfGetSymbolReferenceKind_None; BfGetSymbolReferenceKind prevSymbolRefKind = BfGetSymbolReferenceKind_None;
if (mModule->mCompiler->mResolvePassData != NULL) if (mModule->mCompiler->mResolvePassData != NULL)
{ {
@ -15642,7 +15618,6 @@ void BfExprEvaluator::CreateObject(BfObjectCreateExpression* objCreateExpr, BfAs
BfInitContext(BfModule* module, BfType* resultType, int dimensions, SizedArray<BfIRValue, 2>& dimLengthVals, BfIRValue arraySize, int& writeIdx) : BfInitContext(BfModule* module, BfType* resultType, int dimensions, SizedArray<BfIRValue, 2>& dimLengthVals, BfIRValue arraySize, int& writeIdx) :
mModule(module), resultType(resultType), dimensions(dimensions), dimLengthVals(dimLengthVals), arraySize(arraySize), writeIdx(writeIdx) mModule(module), resultType(resultType), dimensions(dimensions), dimLengthVals(dimLengthVals), arraySize(arraySize), writeIdx(writeIdx)
{ {
} }
void Handle(BfIRValue addr, int curDim, const BfSizedArray<BfExpression*>& valueExprs) void Handle(BfIRValue addr, int curDim, const BfSizedArray<BfExpression*>& valueExprs)
@ -16160,7 +16135,6 @@ void BfExprEvaluator::CreateObject(BfObjectCreateExpression* objCreateExpr, BfAs
/*if (typeInstance != NULL) /*if (typeInstance != NULL)
{ {
mModule->InitTypeInst(mResult, scopeData, true); mModule->InitTypeInst(mResult, scopeData, true);
} }
if (isStackAlloc) if (isStackAlloc)
@ -18089,11 +18063,9 @@ void BfExprEvaluator::DoInvocation(BfAstNode* target, BfMethodBoundExpression* m
{ {
if (mExpectingType->IsVar()) if (mExpectingType->IsVar())
{ {
} }
mResult = BfTypedValue(mExpectingType); mResult = BfTypedValue(mExpectingType);
} }
else if (!gaveUnqualifiedDotError) else if (!gaveUnqualifiedDotError)
mModule->Fail("Unqualified dot syntax can only be used when the result type can be inferred", memberRefExpression->mDotToken); mModule->Fail("Unqualified dot syntax can only be used when the result type can be inferred", memberRefExpression->mDotToken);
@ -18135,7 +18107,6 @@ void BfExprEvaluator::DoInvocation(BfAstNode* target, BfMethodBoundExpression* m
thisValue = mResult; thisValue = mResult;
mResult = BfTypedValue(); mResult = BfTypedValue();
} }
} }
if (mPropDef != NULL) if (mPropDef != NULL)
thisValue = GetResult(true); thisValue = GetResult(true);
@ -18220,7 +18191,6 @@ void BfExprEvaluator::DoInvocation(BfAstNode* target, BfMethodBoundExpression* m
flags = (BfEvalExprFlags)(flags | BfEvalExprFlags_AllowRefExpr); flags = (BfEvalExprFlags)(flags | BfEvalExprFlags_AllowRefExpr);
expr = paranExpr->mExpression; expr = paranExpr->mExpression;
} }
} }
if (expr != NULL) if (expr != NULL)
mResult = mModule->CreateValueFromExpression(expr, expectingTargetType, flags); mResult = mModule->CreateValueFromExpression(expr, expectingTargetType, flags);
@ -18349,7 +18319,6 @@ void BfExprEvaluator::DoInvocation(BfAstNode* target, BfMethodBoundExpression* m
mResult = BfTypedValue(); mResult = BfTypedValue();
} }
} }
} }
if (mPropDef != NULL) if (mPropDef != NULL)
thisValue = GetResult(true); thisValue = GetResult(true);
@ -18940,7 +18909,6 @@ BfMethodDef* BfExprEvaluator::GetPropertyMethodDef(BfPropertyDef* propDef, BfMet
if (methodDef->mMethodType != methodType) if (methodDef->mMethodType != methodType)
continue; continue;
if (methodDef->mCheckedKind == checkedKind) if (methodDef->mCheckedKind == checkedKind)
{ {
matchedMethod = methodDef; matchedMethod = methodDef;
@ -19623,8 +19591,6 @@ bool BfExprEvaluator::CheckModifyResult(BfTypedValue& typedVal, BfAstNode* refNo
break; break;
} }
} }
} }
} }
@ -20098,7 +20064,6 @@ BfTypedValue BfExprEvaluator::PerformAssignment_CheckOp(BfAssignmentExpression*
return leftValue; return leftValue;
} }
checkTypeInst = mModule->GetBaseType(checkTypeInst); checkTypeInst = mModule->GetBaseType(checkTypeInst);
} }
@ -21945,7 +21910,6 @@ void BfExprEvaluator::Visit(BfIndexerExpression* indexerExpr)
} }
else else
{ {
auto indexResult = mModule->CreateIndexedValue(underlyingType, target.mValue, indexArgument.mValue); auto indexResult = mModule->CreateIndexedValue(underlyingType, target.mValue, indexArgument.mValue);
mResult = BfTypedValue(indexResult, underlyingType, target.IsReadOnly() ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr); mResult = BfTypedValue(indexResult, underlyingType, target.IsReadOnly() ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
} }
@ -22037,7 +22001,6 @@ void BfExprEvaluator::PerformUnaryOperation(BfExpression* unaryOpExpr, BfUnaryOp
mExpectingType = prevExpedcting; mExpectingType = prevExpedcting;
} }
BfExprEvaluator::PerformUnaryOperation_OnResult(unaryOpExpr, unaryOp, opToken, opFlags); BfExprEvaluator::PerformUnaryOperation_OnResult(unaryOpExpr, unaryOp, opToken, opFlags);
} }
@ -22998,7 +22961,6 @@ bool BfExprEvaluator::PerformBinaryOperation_NullCoalesce(BfTokenNode* opToken,
mModule->AddBasicBlock(rhsBB); mModule->AddBasicBlock(rhsBB);
BfTypedValue rightValue; BfTypedValue rightValue;
if (assignTo != NULL) if (assignTo != NULL)
rightValue = mModule->CreateValueFromExpression(rightExpression, wantType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_CreateConditionalScope)); rightValue = mModule->CreateValueFromExpression(rightExpression, wantType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_CreateConditionalScope));
else else
@ -25079,4 +25041,4 @@ void BfExprEvaluator::Visit(BfBinaryOperatorExpression* binOpExpr)
} }
PerformBinaryOperation(binOpExpr->mLeft, binOpExpr->mRight, binOpExpr->mOp, binOpExpr->mOpToken, BfBinOpFlag_None); PerformBinaryOperation(binOpExpr->mLeft, binOpExpr->mRight, binOpExpr->mOp, binOpExpr->mOpToken, BfBinOpFlag_None);
} }

View file

@ -7,7 +7,7 @@ NS_BF_BEGIN
enum BfArgFlags enum BfArgFlags
{ {
BfArgFlag_None = 0, BfArgFlag_None = 0,
BfArgFlag_DelegateBindAttempt = 1, BfArgFlag_DelegateBindAttempt = 1,
BfArgFlag_LambdaBindAttempt = 2, BfArgFlag_LambdaBindAttempt = 2,
BfArgFlag_UnqualifiedDotAttempt = 4, BfArgFlag_UnqualifiedDotAttempt = 4,
@ -62,7 +62,7 @@ public:
BfIdentifierNode* mNameNode; BfIdentifierNode* mNameNode;
BfType* mResolvedType; BfType* mResolvedType;
BfAstNode* mExpression; BfAstNode* mExpression;
BfArgFlags mArgFlags; BfArgFlags mArgFlags;
BfType* mExpectedType; BfType* mExpectedType;
BfType* mBestBoundType; BfType* mBestBoundType;
bool mWantsRecalc; bool mWantsRecalc;
@ -87,10 +87,10 @@ public:
struct BfResolvedArgs struct BfResolvedArgs
{ {
SizedArray<BfResolvedArg, 4> mResolvedArgs; SizedArray<BfResolvedArg, 4> mResolvedArgs;
BfTokenNode* mOpenToken; BfTokenNode* mOpenToken;
const BfSizedArray<BfExpression*>* mArguments; const BfSizedArray<BfExpression*>* mArguments;
const BfSizedArray<BfTokenNode*>* mCommas; const BfSizedArray<BfTokenNode*>* mCommas;
BfTokenNode* mCloseToken; BfTokenNode* mCloseToken;
public: public:
@ -134,8 +134,7 @@ public:
mCloseToken = NULL; mCloseToken = NULL;
} }
void HandleFixits(BfModule* module); void HandleFixits(BfModule* module);
}; };
class BfGenericInferContext class BfGenericInferContext
@ -145,13 +144,13 @@ public:
BfModule* mModule; BfModule* mModule;
BfTypeVector* mCheckMethodGenericArguments; BfTypeVector* mCheckMethodGenericArguments;
SizedArray<BfIRValue, 4> mPrevArgValues; SizedArray<BfIRValue, 4> mPrevArgValues;
int mInferredCount; int mInferredCount;
public: public:
BfGenericInferContext() BfGenericInferContext()
{ {
mModule = NULL; mModule = NULL;
mInferredCount = 0; mInferredCount = 0;
} }
bool AddToCheckedSet(BfType* argType, BfType* wantType); bool AddToCheckedSet(BfType* argType, BfType* wantType);
@ -166,13 +165,13 @@ public:
struct BfMethodGenericArguments struct BfMethodGenericArguments
{ {
BfSizedArray<BfAstNode*>* mArguments; BfSizedArray<BfAstNode*>* mArguments;
bool mIsPartial; bool mIsPartial;
bool mIsOpen; // Ends with ... bool mIsOpen; // Ends with ...
BfMethodGenericArguments() BfMethodGenericArguments()
{ {
mArguments = NULL; mArguments = NULL;
mIsPartial = false; mIsPartial = false;
mIsOpen = false; mIsOpen = false;
} }
@ -198,17 +197,17 @@ public:
{ {
BackupMatchKind_None, BackupMatchKind_None,
BackupMatchKind_TooManyArgs, BackupMatchKind_TooManyArgs,
BackupMatchKind_EarlyMismatch, BackupMatchKind_EarlyMismatch,
BackupMatchKind_PartialLastArgMatch BackupMatchKind_PartialLastArgMatch
}; };
public: public:
BfAstNode* mTargetSrc; BfAstNode* mTargetSrc;
BfTypedValue mTarget; BfTypedValue mTarget;
BfTypedValue mOrigTarget; BfTypedValue mOrigTarget;
BfModule* mModule; BfModule* mModule;
BfTypeDef* mActiveTypeDef; BfTypeDef* mActiveTypeDef;
String mMethodName; String mMethodName;
BfMethodInstance* mInterfaceMethodInstance; BfMethodInstance* mInterfaceMethodInstance;
SizedArrayImpl<BfResolvedArg>& mArguments; SizedArrayImpl<BfResolvedArg>& mArguments;
BfType* mCheckReturnType; BfType* mCheckReturnType;
@ -216,32 +215,32 @@ public:
BfCheckedKind mCheckedKind; BfCheckedKind mCheckedKind;
Array<SizedArray<BfUsingFieldData::MemberRef, 1>*>* mUsingLists; Array<SizedArray<BfUsingFieldData::MemberRef, 1>*>* mUsingLists;
bool mHasArgNames; bool mHasArgNames;
bool mHadExplicitGenericArguments; bool mHadExplicitGenericArguments;
bool mHadOpenGenericArguments; bool mHadOpenGenericArguments;
bool mHadPartialGenericArguments; bool mHadPartialGenericArguments;
bool mHasVarArguments; bool mHasVarArguments;
bool mHadVarConflictingReturnType; bool mHadVarConflictingReturnType;
bool mBypassVirtual; bool mBypassVirtual;
bool mAllowImplicitThis; bool mAllowImplicitThis;
bool mAllowImplicitRef; bool mAllowImplicitRef;
bool mAllowImplicitWrap; bool mAllowImplicitWrap;
bool mAllowStatic; bool mAllowStatic;
bool mAllowNonStatic; bool mAllowNonStatic;
bool mSkipImplicitParams; bool mSkipImplicitParams;
bool mAutoFlushAmbiguityErrors; bool mAutoFlushAmbiguityErrors;
BfEvalExprFlags mBfEvalExprFlags; BfEvalExprFlags mBfEvalExprFlags;
int mMethodCheckCount; int mMethodCheckCount;
BfType* mExplicitInterfaceCheck; BfType* mExplicitInterfaceCheck;
MatchFailKind mMatchFailKind; MatchFailKind mMatchFailKind;
BfTypeVector mCheckMethodGenericArguments; BfTypeVector mCheckMethodGenericArguments;
BfType* mSelfType; // Only when matching interfaces when 'Self' needs to refer back to the implementing type BfType* mSelfType; // Only when matching interfaces when 'Self' needs to refer back to the implementing type
BfMethodDef* mBackupMethodDef; BfMethodDef* mBackupMethodDef;
BackupMatchKind mBackupMatchKind; BackupMatchKind mBackupMatchKind;
int mBackupArgMatchCount; int mBackupArgMatchCount;
BfMethodDef* mBestMethodDef; BfMethodDef* mBestMethodDef;
BfTypeInstance* mBestMethodTypeInstance; BfTypeInstance* mBestMethodTypeInstance;
BfMethodInstance* mBestRawMethodInstance; BfMethodInstance* mBestRawMethodInstance;
BfModuleMethodInstance mBestMethodInstance; BfModuleMethodInstance mBestMethodInstance;
SizedArray<int, 4> mBestMethodGenericArgumentSrcs; SizedArray<int, 4> mBestMethodGenericArgumentSrcs;
@ -254,9 +253,9 @@ public:
BfTypedValue ResolveArgTypedValue(BfResolvedArg& resolvedArg, BfType* checkType, BfTypeVector* genericArgumentsSubstitute, BfType *origCheckType = NULL, BfResolveArgFlags flags = BfResolveArgFlag_None); BfTypedValue ResolveArgTypedValue(BfResolvedArg& resolvedArg, BfType* checkType, BfTypeVector* genericArgumentsSubstitute, BfType *origCheckType = NULL, BfResolveArgFlags flags = BfResolveArgFlag_None);
bool InferFromGenericConstraints(BfMethodInstance* methodInstance, BfGenericParamInstance* genericParamInst, BfTypeVector* methodGenericArgs); bool InferFromGenericConstraints(BfMethodInstance* methodInstance, BfGenericParamInstance* genericParamInst, BfTypeVector* methodGenericArgs);
void CompareMethods(BfMethodInstance* prevMethodInstance, BfTypeVector* prevGenericArgumentsSubstitute, void CompareMethods(BfMethodInstance* prevMethodInstance, BfTypeVector* prevGenericArgumentsSubstitute,
BfMethodInstance* newMethodInstance, BfTypeVector* genericArgumentsSubstitute, BfMethodInstance* newMethodInstance, BfTypeVector* genericArgumentsSubstitute,
bool* outNewIsBetter, bool* outNewIsWorse, bool allowSpecializeFail); bool* outNewIsBetter, bool* outNewIsWorse, bool allowSpecializeFail);
void FlushAmbiguityError(); void FlushAmbiguityError();
bool IsType(BfTypedValue& val, BfType* type); bool IsType(BfTypedValue& val, BfType* type);
int GetMostSpecificType(BfType* lhs, BfType* rhs); // 0, 1, or -1 int GetMostSpecificType(BfType* lhs, BfType* rhs); // 0, 1, or -1
@ -317,8 +316,8 @@ class BfFunctionBindResult
{ {
public: public:
BfTypedValue mOrigTarget; BfTypedValue mOrigTarget;
BfTypedValue mTarget; BfTypedValue mTarget;
BfIRValue mFunc; BfIRValue mFunc;
BfMethodInstance* mMethodInstance; BfMethodInstance* mMethodInstance;
BfType* mBindType; BfType* mBindType;
bool mSkipThis; bool mSkipThis;
@ -329,7 +328,7 @@ public:
public: public:
BfFunctionBindResult() BfFunctionBindResult()
{ {
mMethodInstance = NULL; mMethodInstance = NULL;
mBindType = NULL; mBindType = NULL;
mSkipMutCheck = false; mSkipMutCheck = false;
@ -342,7 +341,7 @@ public:
struct DeferredTupleAssignData struct DeferredTupleAssignData
{ {
struct Entry struct Entry
{ {
BfExpression* mExpr; BfExpression* mExpr;
BfType* mVarType; BfType* mVarType;
BfAstNode* mVarNameNode; BfAstNode* mVarNameNode;
@ -359,8 +358,8 @@ struct DeferredTupleAssignData
enum BfImplicitParamKind enum BfImplicitParamKind
{ {
BfImplicitParamKind_General, BfImplicitParamKind_General,
BfImplicitParamKind_GenericMethodMember, BfImplicitParamKind_GenericMethodMember,
BfImplicitParamKind_GenericTypeMember, BfImplicitParamKind_GenericTypeMember,
BfImplicitParamKind_GenericTypeMember_Addr, BfImplicitParamKind_GenericTypeMember_Addr,
}; };
@ -409,11 +408,11 @@ public:
BfGetMethodInstanceFlags mPropGetMethodFlags; BfGetMethodInstanceFlags mPropGetMethodFlags;
BfCheckedKind mPropCheckedKind; BfCheckedKind mPropCheckedKind;
BfPropertyDef* mPropDef; BfPropertyDef* mPropDef;
BfType* mExpectingType; BfType* mExpectingType;
BfAttributeState* mPrefixedAttributeState; BfAttributeState* mPrefixedAttributeState;
BfTypedValue* mReceivingValue; BfTypedValue* mReceivingValue;
BfFunctionBindResult* mFunctionBindResult; BfFunctionBindResult* mFunctionBindResult;
SizedArray<BfResolvedArg, 2> mIndexerValues; SizedArray<BfResolvedArg, 2> mIndexerValues;
BfAstNode* mDeferCallRef; BfAstNode* mDeferCallRef;
BfScopeData* mDeferScopeAlloc; BfScopeData* mDeferScopeAlloc;
bool mUsedAsStatement; bool mUsedAsStatement;
@ -434,18 +433,18 @@ public:
bool CheckForMethodName(BfAstNode* refNode, BfTypeInstance* typeInst, const StringImpl& findName); bool CheckForMethodName(BfAstNode* refNode, BfTypeInstance* typeInst, const StringImpl& findName);
bool IsVar(BfType* type, bool forceIgnoreWrites = false); bool IsVar(BfType* type, bool forceIgnoreWrites = false);
void GetLiteral(BfAstNode* refNode, const BfVariant& variant); void GetLiteral(BfAstNode* refNode, const BfVariant& variant);
void FinishExpressionResult(); void FinishExpressionResult();
virtual bool CheckAllowValue(const BfTypedValue& typedValue, BfAstNode* refNode); virtual bool CheckAllowValue(const BfTypedValue& typedValue, BfAstNode* refNode);
BfAutoComplete* GetAutoComplete(); BfAutoComplete* GetAutoComplete();
bool IsComptime(); bool IsComptime();
bool IsConstEval(); bool IsConstEval();
bool IsComptimeEntry(); bool IsComptimeEntry();
int GetStructRetIdx(BfMethodInstance* methodInstance, bool forceStatic = false); int GetStructRetIdx(BfMethodInstance* methodInstance, bool forceStatic = false);
BfTypedValue SetupNullConditional(BfTypedValue target, BfTokenNode* dotToken); BfTypedValue SetupNullConditional(BfTypedValue target, BfTokenNode* dotToken);
void Evaluate(BfAstNode* astNode, bool propogateNullConditional = false, bool ignoreNullConditional = false, bool allowSplat = true); void Evaluate(BfAstNode* astNode, bool propogateNullConditional = false, bool ignoreNullConditional = false, bool allowSplat = true);
BfType* BindGenericType(BfAstNode* node, BfType* bindType); BfType* BindGenericType(BfAstNode* node, BfType* bindType);
BfType* ResolveTypeRef(BfTypeReference* typeRef, BfPopulateType populateType = BfPopulateType_Data, BfResolveTypeRefFlags resolveFlags = (BfResolveTypeRefFlags)0); BfType* ResolveTypeRef(BfTypeReference* typeRef, BfPopulateType populateType = BfPopulateType_Data, BfResolveTypeRefFlags resolveFlags = (BfResolveTypeRefFlags)0);
void ResolveGenericType(); void ResolveGenericType();
void ResolveArgValues(BfResolvedArgs& resolvedArgs, BfResolveArgsFlags flags = BfResolveArgsFlag_None); void ResolveArgValues(BfResolvedArgs& resolvedArgs, BfResolveArgsFlags flags = BfResolveArgsFlag_None);
void ResolveAllocTarget(BfAllocTarget& allocTarget, BfAstNode* newNode, BfTokenNode*& newToken, BfCustomAttributes** outCustomAttributes = NULL); void ResolveAllocTarget(BfAllocTarget& allocTarget, BfAstNode* newNode, BfTokenNode*& newToken, BfCustomAttributes** outCustomAttributes = NULL);
BfTypedValue ResolveArgValue(BfResolvedArg& resolvedArg, BfType* wantType, BfTypedValue* receivingValue = NULL, BfParamKind paramKind = BfParamKind_Normal, BfIdentifierNode* paramNameNode = NULL); BfTypedValue ResolveArgValue(BfResolvedArg& resolvedArg, BfType* wantType, BfTypedValue* receivingValue = NULL, BfParamKind paramKind = BfParamKind_Normal, BfIdentifierNode* paramNameNode = NULL);
@ -453,21 +452,21 @@ public:
BfModuleMethodInstance GetPropertyMethodInstance(BfMethodDef* methodDef); BfModuleMethodInstance GetPropertyMethodInstance(BfMethodDef* methodDef);
void CheckPropFail(BfMethodDef* propMethodDef, BfMethodInstance* methodInstance, bool checkProt); void CheckPropFail(BfMethodDef* propMethodDef, BfMethodInstance* methodInstance, bool checkProt);
bool HasResult(); bool HasResult();
BfTypedValue GetResult(bool clearResult = false, bool resolveGenericType = false); BfTypedValue GetResult(bool clearResult = false, bool resolveGenericType = false);
void CheckResultForReading(BfTypedValue& typedValue); void CheckResultForReading(BfTypedValue& typedValue);
void MarkResultUsed(); void MarkResultUsed();
void MarkResultAssigned(); void MarkResultAssigned();
void MakeResultAsValue(); void MakeResultAsValue();
bool CheckIsBase(BfAstNode* checkNode); bool CheckIsBase(BfAstNode* checkNode);
bool CheckModifyResult(BfTypedValue& typeValue, BfAstNode* refNode, const char* modifyType, bool onlyNeedsMut = false, bool emitWarning = false, bool skipCopyOnMutate = false); bool CheckModifyResult(BfTypedValue& typeValue, BfAstNode* refNode, const char* modifyType, bool onlyNeedsMut = false, bool emitWarning = false, bool skipCopyOnMutate = false);
bool CheckGenericCtor(BfGenericParamType* genericParamType, BfResolvedArgs& argValues, BfAstNode* targetSrc); bool CheckGenericCtor(BfGenericParamType* genericParamType, BfResolvedArgs& argValues, BfAstNode* targetSrc);
BfTypedValue LoadProperty(BfAstNode* targetSrc, BfTypedValue target, BfTypeInstance* typeInstance, BfPropertyDef* prop, BfLookupFieldFlags flags, BfCheckedKind checkedKind, bool isInline); BfTypedValue LoadProperty(BfAstNode* targetSrc, BfTypedValue target, BfTypeInstance* typeInstance, BfPropertyDef* prop, BfLookupFieldFlags flags, BfCheckedKind checkedKind, bool isInline);
BfTypedValue LoadField(BfAstNode* targetSrc, BfTypedValue target, BfTypeInstance* typeInstance, BfFieldDef* fieldDef, BfLookupFieldFlags flags); BfTypedValue LoadField(BfAstNode* targetSrc, BfTypedValue target, BfTypeInstance* typeInstance, BfFieldDef* fieldDef, BfLookupFieldFlags flags);
BfTypedValue LookupField(BfAstNode* targetSrc, BfTypedValue target, const StringImpl& fieldName, BfLookupFieldFlags flags = BfLookupFieldFlag_None); BfTypedValue LookupField(BfAstNode* targetSrc, BfTypedValue target, const StringImpl& fieldName, BfLookupFieldFlags flags = BfLookupFieldFlag_None);
void CheckObjectCreateTypeRef(BfType* expectingType, BfAstNode* afterNode); void CheckObjectCreateTypeRef(BfType* expectingType, BfAstNode* afterNode);
void LookupQualifiedName(BfQualifiedNameNode* nameNode, bool ignoreInitialError = false, bool* hadError = NULL); void LookupQualifiedName(BfQualifiedNameNode* nameNode, bool ignoreInitialError = false, bool* hadError = NULL);
void LookupQualifiedName(BfAstNode* nameNode, BfIdentifierNode* nameLeft, BfIdentifierNode* nameRight, bool ignoreInitialError, bool* hadError = NULL); void LookupQualifiedName(BfAstNode* nameNode, BfIdentifierNode* nameLeft, BfIdentifierNode* nameRight, bool ignoreInitialError, bool* hadError = NULL);
void LookupQualifiedStaticField(BfQualifiedNameNode* nameNode, bool ignoreIdentifierNotFoundError); void LookupQualifiedStaticField(BfQualifiedNameNode* nameNode, bool ignoreIdentifierNotFoundError);
void LookupQualifiedStaticField(BfAstNode* nameNode, BfIdentifierNode* nameLeft, BfIdentifierNode* nameRight, bool ignoreIdentifierNotFoundError); void LookupQualifiedStaticField(BfAstNode* nameNode, BfIdentifierNode* nameLeft, BfIdentifierNode* nameRight, bool ignoreIdentifierNotFoundError);
bool CheckConstCompare(BfBinaryOp binaryOp, BfAstNode* opToken, const BfTypedValue& leftValue, const BfTypedValue& rightValue); bool CheckConstCompare(BfBinaryOp binaryOp, BfAstNode* opToken, const BfTypedValue& leftValue, const BfTypedValue& rightValue);
void AddStrings(const BfTypedValue& leftValue, const BfTypedValue& rightValue, BfAstNode* refNode); void AddStrings(const BfTypedValue& leftValue, const BfTypedValue& rightValue, BfAstNode* refNode);
@ -489,41 +488,41 @@ public:
void SplatArgs(BfTypedValue value, SizedArrayImpl<BfIRValue>& irArgs); void SplatArgs(BfTypedValue value, SizedArrayImpl<BfIRValue>& irArgs);
void PushArg(BfTypedValue argVal, SizedArrayImpl<BfIRValue>& irArgs, bool disableSplat = false, bool disableLowering = false, bool isIntrinsic = false, bool createCompositeCopy = false); void PushArg(BfTypedValue argVal, SizedArrayImpl<BfIRValue>& irArgs, bool disableSplat = false, bool disableLowering = false, bool isIntrinsic = false, bool createCompositeCopy = false);
void PushThis(BfAstNode* targetSrc, BfTypedValue callTarget, BfMethodInstance* methodInstance, SizedArrayImpl<BfIRValue>& irArgs, bool skipMutCheck = false); void PushThis(BfAstNode* targetSrc, BfTypedValue callTarget, BfMethodInstance* methodInstance, SizedArrayImpl<BfIRValue>& irArgs, bool skipMutCheck = false);
BfTypedValue MatchConstructor(BfAstNode* targetSrc, BfMethodBoundExpression* methodBoundExpr, BfTypedValue target, BfTypeInstance* targetType, BfTypedValue MatchConstructor(BfAstNode* targetSrc, BfMethodBoundExpression* methodBoundExpr, BfTypedValue target, BfTypeInstance* targetType,
BfResolvedArgs& argValues, bool callCtorBodyOnly, bool allowAppendAlloc, BfTypedValue* appendIndexValue = NULL); BfResolvedArgs& argValues, bool callCtorBodyOnly, bool allowAppendAlloc, BfTypedValue* appendIndexValue = NULL);
BfTypedValue CheckEnumCreation(BfAstNode* targetSrc, BfTypeInstance* enumType, const StringImpl& caseName, BfResolvedArgs& argValues); BfTypedValue CheckEnumCreation(BfAstNode* targetSrc, BfTypeInstance* enumType, const StringImpl& caseName, BfResolvedArgs& argValues);
BfTypedValue MatchMethod(BfAstNode* targetSrc, BfMethodBoundExpression* methodBoundExpr, BfTypedValue target, bool allowImplicitThis, bool bypassVirtual, const StringImpl& name, BfTypedValue MatchMethod(BfAstNode* targetSrc, BfMethodBoundExpression* methodBoundExpr, BfTypedValue target, bool allowImplicitThis, bool bypassVirtual, const StringImpl& name,
BfResolvedArgs& argValue, const BfMethodGenericArguments& methodGenericArguments, BfCheckedKind checkedKind = BfCheckedKind_NotSet); BfResolvedArgs& argValue, const BfMethodGenericArguments& methodGenericArguments, BfCheckedKind checkedKind = BfCheckedKind_NotSet);
BfTypedValue MakeCallableTarget(BfAstNode* targetSrc, BfTypedValue target); BfTypedValue MakeCallableTarget(BfAstNode* targetSrc, BfTypedValue target);
BfModuleMethodInstance GetSelectedMethod(BfAstNode* targetSrc, BfTypeInstance* curTypeInst, BfMethodDef* methodDef, BfMethodMatcher& methodMatcher, BfType** overrideReturnType = NULL); BfModuleMethodInstance GetSelectedMethod(BfAstNode* targetSrc, BfTypeInstance* curTypeInst, BfMethodDef* methodDef, BfMethodMatcher& methodMatcher, BfType** overrideReturnType = NULL);
BfModuleMethodInstance GetSelectedMethod(BfMethodMatcher& methodMatcher); BfModuleMethodInstance GetSelectedMethod(BfMethodMatcher& methodMatcher);
bool CheckVariableDeclaration(BfAstNode* checkNode, bool requireSimpleIfExpr, bool exprMustBeTrue, bool silentFail); bool CheckVariableDeclaration(BfAstNode* checkNode, bool requireSimpleIfExpr, bool exprMustBeTrue, bool silentFail);
bool HasVariableDeclaration(BfAstNode* checkNode); bool HasVariableDeclaration(BfAstNode* checkNode);
void DoInvocation(BfAstNode* target, BfMethodBoundExpression* methodBoundExpr, const BfSizedArray<BfExpression*>& args, const BfMethodGenericArguments& methodGenericArgs, BfTypedValue* outCascadeValue = NULL); void DoInvocation(BfAstNode* target, BfMethodBoundExpression* methodBoundExpr, const BfSizedArray<BfExpression*>& args, const BfMethodGenericArguments& methodGenericArgs, BfTypedValue* outCascadeValue = NULL);
int GetMixinVariable(); int GetMixinVariable();
void CheckLocalMethods(BfAstNode* targetSrc, BfTypeInstance* typeInstance, const StringImpl& methodName, BfMethodMatcher& methodMatcher, BfMethodType methodType); void CheckLocalMethods(BfAstNode* targetSrc, BfTypeInstance* typeInstance, const StringImpl& methodName, BfMethodMatcher& methodMatcher, BfMethodType methodType);
void InjectMixin(BfAstNode* targetSrc, BfTypedValue target, bool allowImplicitThis, const StringImpl& name, const BfSizedArray<BfExpression*>& arguments, const BfMethodGenericArguments& methodGenericArgs); void InjectMixin(BfAstNode* targetSrc, BfTypedValue target, bool allowImplicitThis, const StringImpl& name, const BfSizedArray<BfExpression*>& arguments, const BfMethodGenericArguments& methodGenericArgs);
void SetMethodElementType(BfAstNode* target); void SetMethodElementType(BfAstNode* target);
BfTypedValue DoImplicitArgCapture(BfAstNode* refNode, BfIdentifierNode* identifierNode, int shadowIdx); BfTypedValue DoImplicitArgCapture(BfAstNode* refNode, BfIdentifierNode* identifierNode, int shadowIdx);
BfTypedValue DoImplicitArgCapture(BfAstNode* refNode, BfMethodInstance* methodInstance, int paramIdx, bool& failed, BfImplicitParamKind paramKind = BfImplicitParamKind_General, const BfTypedValue& methodRefTarget = BfTypedValue()); BfTypedValue DoImplicitArgCapture(BfAstNode* refNode, BfMethodInstance* methodInstance, int paramIdx, bool& failed, BfImplicitParamKind paramKind = BfImplicitParamKind_General, const BfTypedValue& methodRefTarget = BfTypedValue());
bool CanBindDelegate(BfDelegateBindExpression* delegateBindExpr, BfMethodInstance** boundMethod = NULL, BfType* origMethodExpectingType = NULL, BfTypeVector* methodGenericArgumentsSubstitute = NULL); bool CanBindDelegate(BfDelegateBindExpression* delegateBindExpr, BfMethodInstance** boundMethod = NULL, BfType* origMethodExpectingType = NULL, BfTypeVector* methodGenericArgumentsSubstitute = NULL);
bool IsExactMethodMatch(BfMethodInstance* methodA, BfMethodInstance* methodB, bool ignoreImplicitParams = false); bool IsExactMethodMatch(BfMethodInstance* methodA, BfMethodInstance* methodB, bool ignoreImplicitParams = false);
BfTypeInstance* VerifyBaseDelegateType(BfTypeInstance* delegateType); BfTypeInstance* VerifyBaseDelegateType(BfTypeInstance* delegateType);
void ConstResolve(BfExpression* expr); void ConstResolve(BfExpression* expr);
void ProcessArrayInitializer(BfTokenNode* openToken, const BfSizedArray<BfExpression*>& values, const BfSizedArray<BfTokenNode*>& commas, BfTokenNode* closeToken, int dimensions, SizedArrayImpl<int64>& dimLengths, int dim, bool& hasFailed); void ProcessArrayInitializer(BfTokenNode* openToken, const BfSizedArray<BfExpression*>& values, const BfSizedArray<BfTokenNode*>& commas, BfTokenNode* closeToken, int dimensions, SizedArrayImpl<int64>& dimLengths, int dim, bool& hasFailed);
BfLambdaInstance* GetLambdaInstance(BfLambdaBindExpression* lambdaBindExpr, BfAllocTarget& allocTarget); BfLambdaInstance* GetLambdaInstance(BfLambdaBindExpression* lambdaBindExpr, BfAllocTarget& allocTarget);
void VisitLambdaBodies(BfAstNode* body, BfFieldDtorDeclaration* fieldDtor); void VisitLambdaBodies(BfAstNode* body, BfFieldDtorDeclaration* fieldDtor);
void FixitAddMember(BfTypeInstance* typeInst, BfType* fieldType, const StringImpl& fieldName, bool isStatic); void FixitAddMember(BfTypeInstance* typeInst, BfType* fieldType, const StringImpl& fieldName, bool isStatic);
BfTypedValue TryArrowLookup(BfTypedValue typedValue, BfTokenNode* arrowToken); BfTypedValue TryArrowLookup(BfTypedValue typedValue, BfTokenNode* arrowToken);
void PerformUnaryOperation(BfExpression* unaryOpExpr, BfUnaryOp unaryOp, BfTokenNode* opToken, BfUnaryOpFlags opFlags); void PerformUnaryOperation(BfExpression* unaryOpExpr, BfUnaryOp unaryOp, BfTokenNode* opToken, BfUnaryOpFlags opFlags);
BfTypedValue PerformUnaryOperation_TryOperator(const BfTypedValue& inValue, BfExpression* unaryOpExpr, BfUnaryOp unaryOp, BfTokenNode* opToken, BfUnaryOpFlags opFlags); BfTypedValue PerformUnaryOperation_TryOperator(const BfTypedValue& inValue, BfExpression* unaryOpExpr, BfUnaryOp unaryOp, BfTokenNode* opToken, BfUnaryOpFlags opFlags);
void PerformUnaryOperation_OnResult(BfExpression* unaryOpExpr, BfUnaryOp unaryOp, BfTokenNode* opToken, BfUnaryOpFlags opFlags); void PerformUnaryOperation_OnResult(BfExpression* unaryOpExpr, BfUnaryOp unaryOp, BfTokenNode* opToken, BfUnaryOpFlags opFlags);
BfTypedValue PerformAssignment_CheckOp(BfAssignmentExpression* assignExpr, bool deferBinop, BfTypedValue& leftValue, BfTypedValue& rightValue, bool& evaluatedRight); BfTypedValue PerformAssignment_CheckOp(BfAssignmentExpression* assignExpr, bool deferBinop, BfTypedValue& leftValue, BfTypedValue& rightValue, bool& evaluatedRight);
void PerformAssignment(BfAssignmentExpression* assignExpr, bool evaluatedLeft, BfTypedValue rightValue, BfTypedValue* outCascadeValue = NULL); void PerformAssignment(BfAssignmentExpression* assignExpr, bool evaluatedLeft, BfTypedValue rightValue, BfTypedValue* outCascadeValue = NULL);
void PopulateDeferrredTupleAssignData(BfTupleExpression* tupleExr, DeferredTupleAssignData& deferredTupleAssignData); void PopulateDeferrredTupleAssignData(BfTupleExpression* tupleExr, DeferredTupleAssignData& deferredTupleAssignData);
void AssignDeferrredTupleAssignData(BfAssignmentExpression* assignExpr, DeferredTupleAssignData& deferredTupleAssignData, BfTypedValue rightValue); void AssignDeferrredTupleAssignData(BfAssignmentExpression* assignExpr, DeferredTupleAssignData& deferredTupleAssignData, BfTypedValue rightValue);
void DoTupleAssignment(BfAssignmentExpression* assignExpr); void DoTupleAssignment(BfAssignmentExpression* assignExpr);
void FinishDeferredEvals(SizedArrayImpl<BfResolvedArg>& argValues); void FinishDeferredEvals(SizedArrayImpl<BfResolvedArg>& argValues);
void FinishDeferredEvals(BfResolvedArgs& argValues); void FinishDeferredEvals(BfResolvedArgs& argValues);
bool LookupTypeProp(BfTypeOfExpression* typeOfExpr, BfIdentifierNode* propName); bool LookupTypeProp(BfTypeOfExpression* typeOfExpr, BfIdentifierNode* propName);
void DoTypeIntAttr(BfTypeReference* typeRef, BfTokenNode* commaToken, BfIdentifierNode* memberName, BfToken token); void DoTypeIntAttr(BfTypeReference* typeRef, BfTokenNode* commaToken, BfIdentifierNode* memberName, BfToken token);
@ -534,7 +533,7 @@ public:
void CreateObject(BfObjectCreateExpression* objCreateExpr, BfAstNode* allocNode, BfType* allocType); void CreateObject(BfObjectCreateExpression* objCreateExpr, BfAstNode* allocNode, BfType* allocType);
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
virtual void Visit(BfErrorNode* errorNode) override; virtual void Visit(BfErrorNode* errorNode) override;
virtual void Visit(BfTypeReference* typeRef) override; virtual void Visit(BfTypeReference* typeRef) override;
virtual void Visit(BfAttributedExpression* attribExpr) override; virtual void Visit(BfAttributedExpression* attribExpr) override;
@ -543,7 +542,7 @@ public:
virtual void Visit(BfVariableDeclaration* varDecl) override; virtual void Visit(BfVariableDeclaration* varDecl) override;
virtual void Visit(BfCaseExpression* caseExpr) override; virtual void Visit(BfCaseExpression* caseExpr) override;
virtual void Visit(BfTypedValueExpression* typedValueExpr) override; virtual void Visit(BfTypedValueExpression* typedValueExpr) override;
virtual void Visit(BfLiteralExpression* literalExpr) override; virtual void Visit(BfLiteralExpression* literalExpr) override;
virtual void Visit(BfStringInterpolationExpression* stringInterpolationExpression) override; virtual void Visit(BfStringInterpolationExpression* stringInterpolationExpression) override;
virtual void Visit(BfIdentifierNode* identifierNode) override; virtual void Visit(BfIdentifierNode* identifierNode) override;
virtual void Visit(BfAttributedIdentifierNode* attrIdentifierNode) override; virtual void Visit(BfAttributedIdentifierNode* attrIdentifierNode) override;
@ -553,7 +552,7 @@ public:
virtual void Visit(BfMixinExpression* mixinExpr) override; virtual void Visit(BfMixinExpression* mixinExpr) override;
virtual void Visit(BfSizedArrayCreateExpression* createExpr) override; virtual void Visit(BfSizedArrayCreateExpression* createExpr) override;
virtual void Visit(BfInitializerExpression* initExpr) override; virtual void Visit(BfInitializerExpression* initExpr) override;
virtual void Visit(BfCollectionInitializerExpression* initExpr) override; virtual void Visit(BfCollectionInitializerExpression* initExpr) override;
virtual void Visit(BfTypeOfExpression* typeOfExpr) override; virtual void Visit(BfTypeOfExpression* typeOfExpr) override;
virtual void Visit(BfSizeOfExpression* sizeOfExpr) override; virtual void Visit(BfSizeOfExpression* sizeOfExpr) override;
virtual void Visit(BfAlignOfExpression* alignOfExpr) override; virtual void Visit(BfAlignOfExpression* alignOfExpr) override;
@ -570,7 +569,7 @@ public:
virtual void Visit(BfLambdaBindExpression* lambdaBindExpr) override; virtual void Visit(BfLambdaBindExpression* lambdaBindExpr) override;
virtual void Visit(BfObjectCreateExpression* objCreateExpr) override; virtual void Visit(BfObjectCreateExpression* objCreateExpr) override;
virtual void Visit(BfBoxExpression* boxExpr) override; virtual void Visit(BfBoxExpression* boxExpr) override;
virtual void Visit(BfInvocationExpression* invocationExpr) override; virtual void Visit(BfInvocationExpression* invocationExpr) override;
virtual void Visit(BfConditionalExpression* condExpr) override; virtual void Visit(BfConditionalExpression* condExpr) override;
virtual void Visit(BfAssignmentExpression* assignExpr) override; virtual void Visit(BfAssignmentExpression* assignExpr) override;
virtual void Visit(BfParenthesizedExpression* parenExpr) override; virtual void Visit(BfParenthesizedExpression* parenExpr) override;
@ -578,7 +577,7 @@ public:
virtual void Visit(BfMemberReferenceExpression* memberRefExpr) override; virtual void Visit(BfMemberReferenceExpression* memberRefExpr) override;
virtual void Visit(BfIndexerExpression* indexerExpr) override; virtual void Visit(BfIndexerExpression* indexerExpr) override;
virtual void Visit(BfUnaryOperatorExpression* unaryOpExpr) override; virtual void Visit(BfUnaryOperatorExpression* unaryOpExpr) override;
virtual void Visit(BfBinaryOperatorExpression* binOpExpr) override; virtual void Visit(BfBinaryOperatorExpression* binOpExpr) override;
}; };
NS_BF_END NS_BF_END

View file

@ -19,7 +19,7 @@ public:
{ {
idx++; idx++;
break; break;
} }
idx++; idx++;
} }
return idx; return idx;
@ -37,10 +37,10 @@ public:
{ {
char c = source->mSrc[idx]; char c = source->mSrc[idx];
if (c == '\n') if (c == '\n')
{ {
idx++; idx++;
break; break;
} }
idx--; idx--;
} }
return idx; return idx;
@ -67,13 +67,13 @@ public:
virtual void Visit(BfUsingDirective* usingDirective) override virtual void Visit(BfUsingDirective* usingDirective) override
{ {
mLastIdx = FindLineStartAfter(usingDirective->GetSourceData(), usingDirective->GetSrcEnd()); mLastIdx = FindLineStartAfter(usingDirective->GetSourceData(), usingDirective->GetSrcEnd());
} }
virtual void Visit(BfNamespaceDeclaration* namespaceDecl) override virtual void Visit(BfNamespaceDeclaration* namespaceDecl) override
{ {
if (mFromIdx != -1) if (mFromIdx != -1)
{ {
if ((mFromIdx < namespaceDecl->mSrcStart) || (mFromIdx >= namespaceDecl->mSrcEnd)) if ((mFromIdx < namespaceDecl->mSrcStart) || (mFromIdx >= namespaceDecl->mSrcEnd))
{ {
// Not inside // Not inside

File diff suppressed because it is too large Load diff

View file

@ -60,16 +60,16 @@ public:
mCurSrcPos = 0; mCurSrcPos = 0;
mCurLine = 0; mCurLine = 0;
mCurColumn = 0; mCurColumn = 0;
} }
}; };
enum BfTypeCode : uint8 enum BfTypeCode : uint8
{ {
BfTypeCode_None, BfTypeCode_None,
BfTypeCode_CharPtr, BfTypeCode_CharPtr,
BfTypeCode_StringId, BfTypeCode_StringId,
BfTypeCode_Pointer, BfTypeCode_Pointer,
BfTypeCode_NullPtr, BfTypeCode_NullPtr,
BfTypeCode_Self, BfTypeCode_Self,
BfTypeCode_Dot, BfTypeCode_Dot,
BfTypeCode_Var, BfTypeCode_Var,
@ -123,7 +123,7 @@ enum BfTypeCode : uint8
enum BfConstType enum BfConstType
{ {
BfConstType_GlobalVar = BfTypeCode_Length, BfConstType_GlobalVar = BfTypeCode_Length,
BfConstType_BitCast, BfConstType_BitCast,
BfConstType_BitCastNull, BfConstType_BitCastNull,
BfConstType_GEP32_1, BfConstType_GEP32_1,
@ -145,13 +145,13 @@ enum BfConstType
enum BfIRValueFlags : uint8 enum BfIRValueFlags : uint8
{ {
BfIRValueFlags_None, BfIRValueFlags_None,
BfIRValueFlags_Value = 1, BfIRValueFlags_Value = 1,
BfIRValueFlags_Arg = 2, BfIRValueFlags_Arg = 2,
BfIRValueFlags_Const = 4, BfIRValueFlags_Const = 4,
BfIRValueFlags_FromLLVM = 8, BfIRValueFlags_FromLLVM = 8,
BfIRValueFlags_Block = 16, BfIRValueFlags_Block = 16,
BfIRValueFlags_Func = 32 BfIRValueFlags_Func = 32
}; };
enum BfIRCmd : uint8 enum BfIRCmd : uint8
@ -162,7 +162,7 @@ enum BfIRCmd : uint8
BfIRCmd_WriteIR, BfIRCmd_WriteIR,
BfIRCmd_SetType, BfIRCmd_SetType,
BfIRCmd_SetInstType, BfIRCmd_SetInstType,
BfIRCmd_PrimitiveType, BfIRCmd_PrimitiveType,
BfIRCmd_CreateAnonymousStruct, BfIRCmd_CreateAnonymousStruct,
BfIRCmd_CreateStruct, BfIRCmd_CreateStruct,
@ -175,7 +175,7 @@ enum BfIRCmd : uint8
BfIRCmd_GetPointerToType, BfIRCmd_GetPointerToType,
BfIRCmd_GetSizedArrayType, BfIRCmd_GetSizedArrayType,
BfIRCmd_GetVectorType, BfIRCmd_GetVectorType,
BfIRCmd_CreateConstStructZero, BfIRCmd_CreateConstStructZero,
BfIRCmd_CreateConstAgg, BfIRCmd_CreateConstAgg,
BfIRCmd_CreateConstArrayZero, BfIRCmd_CreateConstArrayZero,
@ -228,10 +228,10 @@ enum BfIRCmd : uint8
BfIRCmd_SetAllocaNoChkStkHint, BfIRCmd_SetAllocaNoChkStkHint,
BfIRCmd_SetAllocaForceMem, BfIRCmd_SetAllocaForceMem,
BfIRCmd_AliasValue, BfIRCmd_AliasValue,
BfIRCmd_LifetimeStart, BfIRCmd_LifetimeStart,
BfIRCmd_LifetimeEnd, BfIRCmd_LifetimeEnd,
BfIRCmd_LifetimeSoftEnd, BfIRCmd_LifetimeSoftEnd,
BfIRCmd_LifetimeExtend, BfIRCmd_LifetimeExtend,
BfIRCmd_ValueScopeStart, BfIRCmd_ValueScopeStart,
BfIRCmd_ValueScopeRetain, BfIRCmd_ValueScopeRetain,
BfIRCmd_ValueScopeSoftEnd, BfIRCmd_ValueScopeSoftEnd,
@ -255,9 +255,9 @@ enum BfIRCmd : uint8
BfIRCmd_CreateBlock, BfIRCmd_CreateBlock,
BfIRCmd_MaybeChainNewBlock, BfIRCmd_MaybeChainNewBlock,
BfIRCmd_AddBlock, BfIRCmd_AddBlock,
BfIRCmd_DropBlocks, BfIRCmd_DropBlocks,
BfIRCmd_MergeBlockDown, BfIRCmd_MergeBlockDown,
BfIRCmd_GetInsertBlock, BfIRCmd_GetInsertBlock,
BfIRCmd_SetInsertPoint, BfIRCmd_SetInsertPoint,
BfIRCmd_SetInsertPointAtStart, BfIRCmd_SetInsertPointAtStart,
@ -276,9 +276,9 @@ enum BfIRCmd : uint8
BfIRCmd_CreatePhi, BfIRCmd_CreatePhi,
BfIRCmd_AddPhiIncoming, BfIRCmd_AddPhiIncoming,
BfIRCmd_GetIntrinsic, BfIRCmd_GetIntrinsic,
BfIRCmd_CreateFunctionType, BfIRCmd_CreateFunctionType,
BfIRCmd_CreateFunction, BfIRCmd_CreateFunction,
BfIRCmd_SetFunctionName, BfIRCmd_SetFunctionName,
BfIRCmd_EnsureFunctionPatchable, BfIRCmd_EnsureFunctionPatchable,
BfIRCmd_RemapBindFunction, BfIRCmd_RemapBindFunction,
@ -293,10 +293,10 @@ enum BfIRCmd : uint8
BfIRCmd_CreateRetVoid, BfIRCmd_CreateRetVoid,
BfIRCmd_CreateUnreachable, BfIRCmd_CreateUnreachable,
BfIRCmd_Call_AddAttribute, BfIRCmd_Call_AddAttribute,
BfIRCmd_Call_AddAttribute1, BfIRCmd_Call_AddAttribute1,
BfIRCmd_Func_AddAttribute, BfIRCmd_Func_AddAttribute,
BfIRCmd_Func_AddAttribute1, BfIRCmd_Func_AddAttribute1,
BfIRCmd_Func_SetParamName, BfIRCmd_Func_SetParamName,
BfIRCmd_Func_DeleteBody, BfIRCmd_Func_DeleteBody,
BfIRCmd_Func_SafeRename, BfIRCmd_Func_SafeRename,
BfIRCmd_Func_SafeRenameFrom, BfIRCmd_Func_SafeRenameFrom,
@ -385,7 +385,7 @@ enum BfIRParamType : uint8
BfIRParamType_Arg, BfIRParamType_Arg,
BfIRParamType_StreamId_Abs8, BfIRParamType_StreamId_Abs8,
BfIRParamType_StreamId_Rel, BfIRParamType_StreamId_Rel,
BfIRParamType_StreamId_Back1, BfIRParamType_StreamId_Back1,
BfIRParamType_StreamId_Back_LAST = 0xFF, // Use remaining encoding BfIRParamType_StreamId_Back_LAST = 0xFF, // Use remaining encoding
}; };
@ -425,9 +425,9 @@ enum BfIRIntrinsic : uint8
BfIRIntrinsic_AtomicAnd, BfIRIntrinsic_AtomicAnd,
BfIRIntrinsic_AtomicCmpStore, BfIRIntrinsic_AtomicCmpStore,
BfIRIntrinsic_AtomicCmpStore_Weak, BfIRIntrinsic_AtomicCmpStore_Weak,
BfIRIntrinsic_AtomicCmpXChg, BfIRIntrinsic_AtomicCmpXChg,
BfIRIntrinsic_AtomicFence, BfIRIntrinsic_AtomicFence,
BfIRIntrinsic_AtomicLoad, BfIRIntrinsic_AtomicLoad,
BfIRIntrinsic_AtomicMax, BfIRIntrinsic_AtomicMax,
BfIRIntrinsic_AtomicMin, BfIRIntrinsic_AtomicMin,
BfIRIntrinsic_AtomicNAnd, BfIRIntrinsic_AtomicNAnd,
@ -440,14 +440,14 @@ enum BfIRIntrinsic : uint8
BfIRIntrinsic_AtomicXor, BfIRIntrinsic_AtomicXor,
BfIRIntrinsic_BSwap, BfIRIntrinsic_BSwap,
BfIRIntrinsic_Cast, BfIRIntrinsic_Cast,
BfIRIntrinsic_Cos, BfIRIntrinsic_Cos,
BfIRIntrinsic_DebugTrap, BfIRIntrinsic_DebugTrap,
BfIRIntrinsic_Div, BfIRIntrinsic_Div,
BfIRIntrinsic_Eq, BfIRIntrinsic_Eq,
BfIRIntrinsic_Floor, BfIRIntrinsic_Floor,
BfIRIntrinsic_Free, BfIRIntrinsic_Free,
BfIRIntrinsic_Gt, BfIRIntrinsic_Gt,
BfIRIntrinsic_GtE, BfIRIntrinsic_GtE,
BfIRIntrinsic_Index, BfIRIntrinsic_Index,
BfIRIntrinsic_Log, BfIRIntrinsic_Log,
BfIRIntrinsic_Log10, BfIRIntrinsic_Log10,
@ -459,7 +459,7 @@ enum BfIRIntrinsic : uint8
BfIRIntrinsic_MemMove, BfIRIntrinsic_MemMove,
BfIRIntrinsic_MemSet, BfIRIntrinsic_MemSet,
BfIRIntrinsic_Mod, BfIRIntrinsic_Mod,
BfIRIntrinsic_Mul, BfIRIntrinsic_Mul,
BfIRIntrinsic_Neq, BfIRIntrinsic_Neq,
BfIRIntrinsic_Not, BfIRIntrinsic_Not,
BfIRIntrinsic_Or, BfIRIntrinsic_Or,
@ -472,8 +472,8 @@ enum BfIRIntrinsic : uint8
BfIRIntrinsic_SHR, BfIRIntrinsic_SHR,
BfIRIntrinsic_Shuffle, BfIRIntrinsic_Shuffle,
BfIRIntrinsic_Sin, BfIRIntrinsic_Sin,
BfIRIntrinsic_Sqrt, BfIRIntrinsic_Sqrt,
BfIRIntrinsic_Sub, BfIRIntrinsic_Sub,
BfIRIntrinsic_VAArg, BfIRIntrinsic_VAArg,
BfIRIntrinsic_VAEnd, BfIRIntrinsic_VAEnd,
BfIRIntrinsic_VAStart, BfIRIntrinsic_VAStart,
@ -537,7 +537,7 @@ public:
ID_IMPLICIT = -3 ID_IMPLICIT = -3
}; };
public: public:
int mId; int mId;
BfIRValueFlags mFlags; BfIRValueFlags mFlags;
static BfIRValue sValueless; static BfIRValue sValueless;
@ -548,7 +548,7 @@ public:
public: public:
BfIRValue() BfIRValue()
{ {
mId = -1; mId = -1;
mFlags = BfIRValueFlags_None; mFlags = BfIRValueFlags_None;
#ifdef CHECK_CONSTHOLDER #ifdef CHECK_CONSTHOLDER
@ -557,7 +557,7 @@ public:
} }
BfIRValue(const BfIRValue& from) BfIRValue(const BfIRValue& from)
{ {
mFlags = from.mFlags; mFlags = from.mFlags;
mId = from.mId; mId = from.mId;
#ifdef CHECK_CONSTHOLDER #ifdef CHECK_CONSTHOLDER
@ -566,23 +566,23 @@ public:
} }
BfIRValue(BfIRValueFlags flags, int id) BfIRValue(BfIRValueFlags flags, int id)
{ {
mFlags = flags; mFlags = flags;
mId = id; mId = id;
} }
operator bool() const operator bool() const
{ {
return mFlags != BfIRValueFlags_None; return mFlags != BfIRValueFlags_None;
} }
bool IsFake() const; bool IsFake() const;
bool IsConst() const; bool IsConst() const;
bool IsArg() const; bool IsArg() const;
bool IsFromLLVM() const; bool IsFromLLVM() const;
bool operator==(const BfIRValue& rhs) const bool operator==(const BfIRValue& rhs) const
{ {
if (mFlags != rhs.mFlags) if (mFlags != rhs.mFlags)
return false; return false;
if (mId != rhs.mId) if (mId != rhs.mId)
@ -591,7 +591,7 @@ public:
} }
bool operator!=(const BfIRValue& rhs) const bool operator!=(const BfIRValue& rhs) const
{ {
if (mFlags != rhs.mFlags) if (mFlags != rhs.mFlags)
return true; return true;
if (mId != rhs.mId) if (mId != rhs.mId)
@ -608,7 +608,7 @@ struct BfIRTypeData
TypeKind_TypeId, TypeKind_TypeId,
TypeKind_TypeCode, TypeKind_TypeCode,
TypeKind_TypeInstId, TypeKind_TypeInstId,
TypeKind_TypeInstPtrId, TypeKind_TypeInstPtrId,
TypeKind_Stream, TypeKind_Stream,
TypeKind_SizedArray TypeKind_SizedArray
}; };
@ -624,12 +624,12 @@ struct BfIRTypeData
struct BfIRType : public BfIRTypeData struct BfIRType : public BfIRTypeData
{ {
public: public:
BfIRType() BfIRType()
{ {
mKind = TypeKind_None; mKind = TypeKind_None;
mId = -1; mId = -1;
} }
BfIRType(BfIRTypeData typeData) BfIRType(BfIRTypeData typeData)
{ {
@ -637,17 +637,17 @@ public:
mId = typeData.mId; mId = typeData.mId;
} }
BfIRType(const BfIRValue& val) { mKind = TypeKind_Stream; mId = val.mId; } BfIRType(const BfIRValue& val) { mKind = TypeKind_Stream; mId = val.mId; }
}; };
struct BfIRBlock : public BfIRValue struct BfIRBlock : public BfIRValue
{ {
public: public:
BfIRBlock(); BfIRBlock();
BfIRBlock(const BfIRValue& fromVal) : BfIRValue(fromVal) {} BfIRBlock(const BfIRValue& fromVal) : BfIRValue(fromVal) {}
}; };
enum BfIRAttribute enum BfIRAttribute
{ {
BfIRAttribute_NoReturn, BfIRAttribute_NoReturn,
BfIRAttribute_NoAlias, BfIRAttribute_NoAlias,
@ -670,83 +670,83 @@ enum BfIRAttribute
struct BfIRFunctionType struct BfIRFunctionType
{ {
public: public:
int mId; int mId;
public: public:
BfIRFunctionType(); BfIRFunctionType();
BfIRFunctionType(const BfIRValue& val) { mId = val.mId; } BfIRFunctionType(const BfIRValue& val) { mId = val.mId; }
operator bool() const operator bool() const
{ {
return mId != -1; return mId != -1;
} }
}; };
struct BfIRFunction : public BfIRRawValue struct BfIRFunction : public BfIRRawValue
{ {
public: public:
BfIRFunction(); BfIRFunction();
BfIRFunction(const BfIRValue& val) BfIRFunction(const BfIRValue& val)
{ {
BF_ASSERT((val.mFlags == BfIRValueFlags_None) || (val.mFlags == BfIRValueFlags_Value)); BF_ASSERT((val.mFlags == BfIRValueFlags_None) || (val.mFlags == BfIRValueFlags_Value));
mId = val.mId; mId = val.mId;
} }
//: BfIRValue(val) {} //: BfIRValue(val) {}
bool operator==(const BfIRFunction& rhs) const bool operator==(const BfIRFunction& rhs) const
{ {
if (mId != rhs.mId) if (mId != rhs.mId)
return false; return false;
return true; return true;
} }
bool operator!=(const BfIRFunction& rhs) const bool operator!=(const BfIRFunction& rhs) const
{ {
if (mId == rhs.mId) if (mId == rhs.mId)
return false; return false;
return true; return true;
} }
operator bool() const operator bool() const
{ {
return mId != -1; return mId != -1;
} }
operator BfIRValue() const operator BfIRValue() const
{ {
return BfIRValue((mId == -1) ? BfIRValueFlags_None : BfIRValueFlags_Value, mId); return BfIRValue((mId == -1) ? BfIRValueFlags_None : BfIRValueFlags_Value, mId);
} }
}; };
struct BfIRMDNode struct BfIRMDNode
{ {
public: public:
int mId; int mId;
BfIRMDNode() BfIRMDNode()
{ {
mId = -1; mId = -1;
} }
BfIRMDNode(const BfIRValue& val) BfIRMDNode(const BfIRValue& val)
{ {
mId = val.mId; mId = val.mId;
} }
operator bool() const operator bool() const
{ {
return mId != -1; return mId != -1;
} }
bool operator==(const BfIRMDNode& rhs) const bool operator==(const BfIRMDNode& rhs) const
{ {
if (mId != rhs.mId) if (mId != rhs.mId)
return false; return false;
return true; return true;
} }
bool operator!=(const BfIRMDNode& rhs) const bool operator!=(const BfIRMDNode& rhs) const
{ {
if (mId == rhs.mId) if (mId == rhs.mId)
return false; return false;
return true; return true;
@ -763,7 +763,7 @@ public:
public: public:
BfFileInstance() BfFileInstance()
{ {
mParser = NULL; mParser = NULL;
} }
}; };
@ -776,7 +776,7 @@ struct BfGlobalVar
BfIRLinkageType mLinkageType; BfIRLinkageType mLinkageType;
int mStreamId; int mStreamId;
BfIRValue mInitializer; BfIRValue mInitializer;
bool mIsTLS; bool mIsTLS;
int mAlignment; int mAlignment;
}; };
@ -789,7 +789,7 @@ struct BfGlobalVar_TypeInst
BfIRLinkageType mLinkageType; BfIRLinkageType mLinkageType;
int mStreamId; int mStreamId;
BfIRValue mInitializer; BfIRValue mInitializer;
bool mIsTLS; bool mIsTLS;
}; };
struct BfTypeOf_Const struct BfTypeOf_Const
@ -813,7 +813,7 @@ public:
{ {
BfTypeCode mTypeCode; BfTypeCode mTypeCode;
BfConstType mConstType; BfConstType mConstType;
}; };
union union
{ {
bool mBool; bool mBool;
@ -886,7 +886,7 @@ struct BfConstantGEP32_1
{ {
BfConstType mConstType; BfConstType mConstType;
int mTarget; int mTarget;
int mIdx0; int mIdx0;
}; };
struct BfConstantGEP32_2 struct BfConstantGEP32_2
@ -901,7 +901,7 @@ struct BfConstantExtractValue
{ {
BfConstType mConstType; BfConstType mConstType;
int mTarget; int mTarget;
int mIdx0; int mIdx0;
}; };
struct BfConstantAgg struct BfConstantAgg
@ -931,15 +931,15 @@ public:
BumpAllocatorT<256> mTempAlloc; BumpAllocatorT<256> mTempAlloc;
BfModule* mModule; BfModule* mModule;
Dictionary<String, BfIRValue> mGlobalVarMap; Dictionary<String, BfIRValue> mGlobalVarMap;
public: public:
void FixTypeCode(BfTypeCode& typeCode); void FixTypeCode(BfTypeCode& typeCode);
int GetSize(BfTypeCode typeCode); int GetSize(BfTypeCode typeCode);
static int GetSize(BfTypeCode typeCode, int ptrSize); static int GetSize(BfTypeCode typeCode, int ptrSize);
static bool IsInt(BfTypeCode typeCode); static bool IsInt(BfTypeCode typeCode);
static bool IsChar(BfTypeCode typeCode); static bool IsChar(BfTypeCode typeCode);
static bool IsIntable(BfTypeCode typeCode); static bool IsIntable(BfTypeCode typeCode);
static bool IsSigned(BfTypeCode typeCode); static bool IsSigned(BfTypeCode typeCode);
static bool IsFloat(BfTypeCode typeCode); static bool IsFloat(BfTypeCode typeCode);
const char* AllocStr(const StringImpl& str); const char* AllocStr(const StringImpl& str);
@ -951,7 +951,7 @@ public:
String ToString(BfIRType irType); String ToString(BfIRType irType);
void pv(const BfIRValue& irValue); void pv(const BfIRValue& irValue);
BfConstant* GetConstantById(int id); BfConstant* GetConstantById(int id);
BfConstant* GetConstant(BfIRValue id); BfConstant* GetConstant(BfIRValue id);
bool TryGetBool(BfIRValue id, bool& boolVal); bool TryGetBool(BfIRValue id, bool& boolVal);
int IsZero(BfIRValue val); int IsZero(BfIRValue val);
@ -961,7 +961,7 @@ public:
BfIRType GetSizedArrayType(BfIRType elementType, int length); BfIRType GetSizedArrayType(BfIRType elementType, int length);
BfIRValue CreateConst(BfTypeCode typeCode, uint64 val); BfIRValue CreateConst(BfTypeCode typeCode, uint64 val);
BfIRValue CreateConst(BfTypeCode typeCode, int val); BfIRValue CreateConst(BfTypeCode typeCode, int val);
BfIRValue CreateConst(BfTypeCode typeCode, double val); BfIRValue CreateConst(BfTypeCode typeCode, double val);
BfIRValue CreateConst(BfConstant* fromConst, BfIRConstHolder* fromHolder); BfIRValue CreateConst(BfConstant* fromConst, BfIRConstHolder* fromHolder);
@ -976,11 +976,11 @@ public:
BfIRValue CreateConstBox(BfIRValue val, BfIRType type); BfIRValue CreateConstBox(BfIRValue val, BfIRType type);
BfIRValue CreateTypeOf(BfType* type); BfIRValue CreateTypeOf(BfType* type);
BfIRValue CreateTypeOf(BfType* type, BfIRValue typeData); BfIRValue CreateTypeOf(BfType* type, BfIRValue typeData);
BfIRValue GetUndefConstValue(BfIRType type); BfIRValue GetUndefConstValue(BfIRType type);
BfIRValue CreateGlobalVariableConstant(BfIRType varType, bool isConstant, BfIRLinkageType linkageType, BfIRValue initializer, const StringImpl& name, bool isTLS = false); BfIRValue CreateGlobalVariableConstant(BfIRType varType, bool isConstant, BfIRLinkageType linkageType, BfIRValue initializer, const StringImpl& name, bool isTLS = false);
bool WriteConstant(BfIRValue val, void* ptr, BfType* type); bool WriteConstant(BfIRValue val, void* ptr, BfType* type);
BfIRValue ReadConstant(void* ptr, BfType* type); BfIRValue ReadConstant(void* ptr, BfType* type);
}; };
enum BfIRPopulateType enum BfIRPopulateType
@ -1011,16 +1011,16 @@ enum BfOverflowCheckKind : int8
class BfIRBuilder : public BfIRConstHolder class BfIRBuilder : public BfIRConstHolder
{ {
public: public:
bool mIgnoreWrites; bool mIgnoreWrites;
bool mDbgVerifyCodeGen; bool mDbgVerifyCodeGen;
int mCurFakeId; int mCurFakeId;
bool mHasGlobalDefs; bool mHasGlobalDefs;
bool mIsBeefBackend; bool mIsBeefBackend;
int mNumFunctionsWithBodies; int mNumFunctionsWithBodies;
int mBlockCount; int mBlockCount;
bool mHasStarted; bool mHasStarted;
int mCmdCount; int mCmdCount;
ChunkedDataBuffer mStream; ChunkedDataBuffer mStream;
BfIRBlock mActualInsertBlock; // Only when not ignoring writes BfIRBlock mActualInsertBlock; // Only when not ignoring writes
@ -1032,12 +1032,12 @@ public:
Dictionary<StringView, BfIRFunction> mFunctionMap; Dictionary<StringView, BfIRFunction> mFunctionMap;
Dictionary<BfType*, BfIRPopulateType> mTypeMap; Dictionary<BfType*, BfIRPopulateType> mTypeMap;
Dictionary<int, BfIRValue> mConstMemMap; Dictionary<int, BfIRValue> mConstMemMap;
Array<BfTypeInstance*> mDITemporaryTypes; Array<BfTypeInstance*> mDITemporaryTypes;
BfIRFunction mActiveFunction; BfIRFunction mActiveFunction;
bool mActiveFunctionHasBody; bool mActiveFunctionHasBody;
Array<BfFilePosition> mSavedDebugLocs; Array<BfFilePosition> mSavedDebugLocs;
Array<BfType*> mDeferredDbgTypeDefs; Array<BfType*> mDeferredDbgTypeDefs;
BfIRCodeGenBase* mIRCodeGen; BfIRCodeGenBase* mIRCodeGen;
BfIRCodeGen* mBfIRCodeGen; BfIRCodeGen* mBfIRCodeGen;
BeIRCodeGen* mBeIRCodeGen; BeIRCodeGen* mBeIRCodeGen;
@ -1050,7 +1050,7 @@ public:
public: public:
~BfIRBuilder(); ~BfIRBuilder();
void WriteSLEB128(int64 val); void WriteSLEB128(int64 val);
void WriteSLEB128(int32 val); void WriteSLEB128(int32 val);
void Write(uint8 val); void Write(uint8 val);
@ -1061,24 +1061,24 @@ public:
void Write(const StringImpl& str); void Write(const StringImpl& str);
void Write(const BfIRValue& irValue); void Write(const BfIRValue& irValue);
void Write(BfTypeCode typeCode); void Write(BfTypeCode typeCode);
void Write(const BfIRTypeData& type); void Write(const BfIRTypeData& type);
void Write(BfIRFunctionType func); void Write(BfIRFunctionType func);
void Write(BfIRFunction funcType); void Write(BfIRFunction funcType);
void Write(BfIRBlock block); void Write(BfIRBlock block);
void Write(BfIRMDNode node); void Write(BfIRMDNode node);
template <typename T> template <typename T>
void Write(const BfSizedArray<T>& sizedArray) void Write(const BfSizedArray<T>& sizedArray)
{ {
WriteSLEB128(sizedArray.mSize); WriteSLEB128(sizedArray.mSize);
for (int i = 0; i < sizedArray.mSize; i++) for (int i = 0; i < sizedArray.mSize; i++)
Write(sizedArray.mVals[i]); Write(sizedArray.mVals[i]);
} }
BfIRValue WriteCmd(BfIRCmd cmd); BfIRValue WriteCmd(BfIRCmd cmd);
template <typename T> template <typename T>
void WriteArg(const T& first) void WriteArg(const T& first)
{ {
Write(first); Write(first);
} }
template <typename T, typename... Args> template <typename T, typename... Args>
@ -1090,17 +1090,17 @@ public:
template <typename... Args> template <typename... Args>
BfIRValue WriteCmd(BfIRCmd cmd, const Args&... args) BfIRValue WriteCmd(BfIRCmd cmd, const Args&... args)
{ {
if (mIgnoreWrites) if (mIgnoreWrites)
return GetFakeVal(); return GetFakeVal();
//int dataPos = mStream.GetSize(); //int dataPos = mStream.GetSize();
auto result = WriteCmd(cmd); auto result = WriteCmd(cmd);
WriteArg(args...); WriteArg(args...);
return result; return result;
//return BfIRValue(BfIRValueFlags_Value, dataPos); //return BfIRValue(BfIRValueFlags_Value, dataPos);
} }
public: public:
void NewCmdInserted(); void NewCmdInserted();
BfIRMDNode CreateNamespaceScope(BfType* type, BfIRMDNode fileDIScope); BfIRMDNode CreateNamespaceScope(BfType* type, BfIRMDNode fileDIScope);
String GetDebugTypeName(BfTypeInstance* typeInstance, bool includeOuterTypeName); String GetDebugTypeName(BfTypeInstance* typeInstance, bool includeOuterTypeName);
@ -1114,18 +1114,18 @@ public:
BfIRPopulateType GetPopulateTypeState(BfType* type); BfIRPopulateType GetPopulateTypeState(BfType* type);
void PopulateType(BfType* type, BfIRPopulateType populateType = BfIRPopulateType_Full); void PopulateType(BfType* type, BfIRPopulateType populateType = BfIRPopulateType_Full);
void SetType(BfType* type, BfIRType irType); void SetType(BfType* type, BfIRType irType);
void SetInstType(BfType* type, BfIRType irType); void SetInstType(BfType* type, BfIRType irType);
int GetFakeId(); int GetFakeId();
BfIRValue GetFakeVal(); BfIRValue GetFakeVal();
BfIRValue GetFakeConst(); BfIRValue GetFakeConst();
BfIRType GetFakeType(); BfIRType GetFakeType();
BfIRType GetFakeBlock(); BfIRType GetFakeBlock();
BfIRFunctionType GetFakeFunctionType(); BfIRFunctionType GetFakeFunctionType();
BfIRFunction GetFakeFunction(); BfIRFunction GetFakeFunction();
public: public:
void OpFailed(); void OpFailed();
uint8 CheckedAdd(uint8 a, uint8 b); uint8 CheckedAdd(uint8 a, uint8 b);
uint16 CheckedAdd(uint16 a, uint16 b); uint16 CheckedAdd(uint16 a, uint16 b);
uint32 CheckedAdd(uint32 a, uint32 b); uint32 CheckedAdd(uint32 a, uint32 b);
@ -1169,7 +1169,7 @@ public:
int64 CheckedShl(int64 a, int64 b); int64 CheckedShl(int64 a, int64 b);
public: public:
BfIRBuilder(BfModule* module); BfIRBuilder(BfModule* module);
bool HasExports(); // Contains non-empty functions and/or non-empty globals bool HasExports(); // Contains non-empty functions and/or non-empty globals
String ToString(BfIRValue irValue); String ToString(BfIRValue irValue);
@ -1183,9 +1183,9 @@ public:
void pt(const BfIRType& irType); void pt(const BfIRType& irType);
void pbft(BfType* type); void pbft(BfType* type);
void pt(const BfIRFunction& irFun); void pt(const BfIRFunction& irFun);
void pft(const BfIRFunctionType& irType); void pft(const BfIRFunctionType& irType);
void pmd(const BfIRMDNode& irMDNode); void pmd(const BfIRMDNode& irMDNode);
void GetBufferData(Array<uint8>& outBuffer); void GetBufferData(Array<uint8>& outBuffer);
void ClearConstData(); void ClearConstData();
void ClearNonConstData(); void ClearNonConstData();
@ -1194,11 +1194,11 @@ public:
void SetBackend(bool isBeefBackend); void SetBackend(bool isBeefBackend);
void RemoveIRCodeGen(); void RemoveIRCodeGen();
void WriteIR(const StringImpl& fileName); void WriteIR(const StringImpl& fileName);
void Module_SetTargetTriple(const StringImpl& targetTriple, const StringImpl& targetCPU); void Module_SetTargetTriple(const StringImpl& targetTriple, const StringImpl& targetCPU);
void Module_AddModuleFlag(const StringImpl& flag, int val); void Module_AddModuleFlag(const StringImpl& flag, int val);
BfIRType GetPrimitiveType(BfTypeCode typeCode); BfIRType GetPrimitiveType(BfTypeCode typeCode);
BfIRType CreateStructType(const StringImpl& name); BfIRType CreateStructType(const StringImpl& name);
BfIRType CreateStructType(const BfSizedArray<BfIRType>& memberTypes); BfIRType CreateStructType(const BfSizedArray<BfIRType>& memberTypes);
void StructSetBody(BfIRType type, const BfSizedArray<BfIRType>& memberTypes, int size, int align, bool isPacked); void StructSetBody(BfIRType type, const BfSizedArray<BfIRType>& memberTypes, int size, int align, bool isPacked);
@ -1210,7 +1210,7 @@ public:
BfIRType GetPointerTo(BfIRType type); BfIRType GetPointerTo(BfIRType type);
BfIRType GetSizedArrayType(BfIRType elementType, int length); BfIRType GetSizedArrayType(BfIRType elementType, int length);
BfIRType GetVectorType(BfIRType elementType, int length); BfIRType GetVectorType(BfIRType elementType, int length);
BfIRValue CreateConstAgg_Value(BfIRType type, const BfSizedArray<BfIRValue>& values); BfIRValue CreateConstAgg_Value(BfIRType type, const BfSizedArray<BfIRValue>& values);
BfIRValue CreateConstString(const StringImpl& string); BfIRValue CreateConstString(const StringImpl& string);
BfIRValue ConstToMemory(BfIRValue constVal); BfIRValue ConstToMemory(BfIRValue constVal);
@ -1252,13 +1252,13 @@ public:
BfIRValue CreateExtractValue(BfIRValue val, int idx); BfIRValue CreateExtractValue(BfIRValue val, int idx);
BfIRValue CreateExtractValue(BfIRValue val, BfIRValue idx); BfIRValue CreateExtractValue(BfIRValue val, BfIRValue idx);
BfIRValue CreateInsertValue(BfIRValue agg, BfIRValue val, int idx); BfIRValue CreateInsertValue(BfIRValue agg, BfIRValue val, int idx);
BfIRValue CreateAlloca(BfIRType type); BfIRValue CreateAlloca(BfIRType type);
BfIRValue CreateAlloca(BfIRType type, BfIRValue arraySize); BfIRValue CreateAlloca(BfIRType type, BfIRValue arraySize);
void SetAllocaAlignment(BfIRValue val, int alignment); void SetAllocaAlignment(BfIRValue val, int alignment);
// When we do a dynamic alloca where we know the memory access patterns will not cause a page fault, we can omit the __chkstk call // When we do a dynamic alloca where we know the memory access patterns will not cause a page fault, we can omit the __chkstk call
// Generally, this is when we allocate less than 4k and we know there will be a write on this memory before the next alloca // Generally, this is when we allocate less than 4k and we know there will be a write on this memory before the next alloca
void SetAllocaNoChkStkHint(BfIRValue val); void SetAllocaNoChkStkHint(BfIRValue val);
void SetAllocaForceMem(BfIRValue val); void SetAllocaForceMem(BfIRValue val);
BfIRValue CreateAliasValue(BfIRValue val); BfIRValue CreateAliasValue(BfIRValue val);
BfIRValue CreateLifetimeStart(BfIRValue val); BfIRValue CreateLifetimeStart(BfIRValue val);
@ -1277,8 +1277,8 @@ public:
void CreateFence(BfIRFenceType fenceType); void CreateFence(BfIRFenceType fenceType);
BfIRValue CreateStackSave(); BfIRValue CreateStackSave();
BfIRValue CreateStackRestore(BfIRValue stackVal); BfIRValue CreateStackRestore(BfIRValue stackVal);
BfIRValue CreateGlobalVariable(BfIRType varType, bool isConstant, BfIRLinkageType linkageType, BfIRValue initializer, const StringImpl& name, bool isTLS = false); BfIRValue CreateGlobalVariable(BfIRType varType, bool isConstant, BfIRLinkageType linkageType, BfIRValue initializer, const StringImpl& name, bool isTLS = false);
void CreateGlobalVariable(BfIRValue irValue); void CreateGlobalVariable(BfIRValue irValue);
void GlobalVar_SetUnnamedAddr(BfIRValue val, bool unnamedAddr); void GlobalVar_SetUnnamedAddr(BfIRValue val, bool unnamedAddr);
void GlobalVar_SetInitializer(BfIRValue globalVar, BfIRValue initVal); void GlobalVar_SetInitializer(BfIRValue globalVar, BfIRValue initVal);
@ -1289,32 +1289,32 @@ public:
BfIRBlock CreateBlock(const StringImpl& name, bool addNow = false); BfIRBlock CreateBlock(const StringImpl& name, bool addNow = false);
BfIRBlock MaybeChainNewBlock(const StringImpl& name); // Creates new block if current block isn't empty BfIRBlock MaybeChainNewBlock(const StringImpl& name); // Creates new block if current block isn't empty
void AddBlock(BfIRBlock block); void AddBlock(BfIRBlock block);
void DropBlocks(BfIRBlock block); void DropBlocks(BfIRBlock block);
void MergeBlockDown(BfIRBlock fromBlock, BfIRBlock intoBlock); void MergeBlockDown(BfIRBlock fromBlock, BfIRBlock intoBlock);
void SetInsertPoint(BfIRValue value); void SetInsertPoint(BfIRValue value);
void SetInsertPoint(BfIRBlock block); void SetInsertPoint(BfIRBlock block);
void SetInsertPointAtStart(BfIRBlock block); void SetInsertPointAtStart(BfIRBlock block);
void EraseFromParent(BfIRBlock block); void EraseFromParent(BfIRBlock block);
void DeleteBlock(BfIRBlock block); void DeleteBlock(BfIRBlock block);
void EraseInstFromParent(BfIRValue val); void EraseInstFromParent(BfIRValue val);
BfIRValue CreateBr(BfIRBlock block); BfIRValue CreateBr(BfIRBlock block);
BfIRValue CreateBr_Fake(BfIRBlock block); BfIRValue CreateBr_Fake(BfIRBlock block);
BfIRValue CreateBr_NoCollapse(BfIRBlock block); BfIRValue CreateBr_NoCollapse(BfIRBlock block);
void CreateCondBr(BfIRValue val, BfIRBlock trueBlock, BfIRBlock falseBlock); void CreateCondBr(BfIRValue val, BfIRBlock trueBlock, BfIRBlock falseBlock);
BfIRBlock GetInsertBlock(); BfIRBlock GetInsertBlock();
void MoveBlockToEnd(BfIRBlock block); void MoveBlockToEnd(BfIRBlock block);
BfIRValue CreateSwitch(BfIRValue value, BfIRBlock dest, int numCases); BfIRValue CreateSwitch(BfIRValue value, BfIRBlock dest, int numCases);
BfIRValue AddSwitchCase(BfIRValue switchVal, BfIRValue caseVal, BfIRBlock caseBlock); BfIRValue AddSwitchCase(BfIRValue switchVal, BfIRValue caseVal, BfIRBlock caseBlock);
void SetSwitchDefaultDest(BfIRValue switchVal, BfIRBlock caseBlock); void SetSwitchDefaultDest(BfIRValue switchVal, BfIRBlock caseBlock);
BfIRValue CreatePhi(BfIRType type, int incomingCount); BfIRValue CreatePhi(BfIRType type, int incomingCount);
void AddPhiIncoming(BfIRValue phi, BfIRValue value, BfIRBlock comingFrom); void AddPhiIncoming(BfIRValue phi, BfIRValue value, BfIRBlock comingFrom);
BfIRFunction GetIntrinsic(String intrinName, int intrinId, BfIRType returnType, const BfSizedArray<BfIRType>& paramTypes); BfIRFunction GetIntrinsic(String intrinName, int intrinId, BfIRType returnType, const BfSizedArray<BfIRType>& paramTypes);
BfIRFunctionType MapMethod(BfMethodInstance* methodInstance); BfIRFunctionType MapMethod(BfMethodInstance* methodInstance);
BfIRFunctionType CreateFunctionType(BfIRType resultType, const BfSizedArray<BfIRType>& paramTypes, bool isVarArg = false); BfIRFunctionType CreateFunctionType(BfIRType resultType, const BfSizedArray<BfIRType>& paramTypes, bool isVarArg = false);
BfIRFunction CreateFunction(BfIRFunctionType funcType, BfIRLinkageType linkageType, const StringImpl& name); BfIRFunction CreateFunction(BfIRFunctionType funcType, BfIRLinkageType linkageType, const StringImpl& name);
void SetFunctionName(BfIRValue func, const StringImpl& name); void SetFunctionName(BfIRValue func, const StringImpl& name);
void EnsureFunctionPatchable(); void EnsureFunctionPatchable();
BfIRValue RemapBindFunction(BfIRValue func); BfIRValue RemapBindFunction(BfIRValue func);
@ -1328,18 +1328,18 @@ public:
void SetCallAttribute(BfIRValue callInst, int paramIdx, BfIRAttribute attribute); void SetCallAttribute(BfIRValue callInst, int paramIdx, BfIRAttribute attribute);
BfIRValue CreateRet(BfIRValue val); BfIRValue CreateRet(BfIRValue val);
BfIRValue CreateSetRet(BfIRValue val, int returnTypeId); BfIRValue CreateSetRet(BfIRValue val, int returnTypeId);
void CreateRetVoid(); void CreateRetVoid();
void CreateUnreachable(); void CreateUnreachable();
void Call_AddAttribute(BfIRValue callInst, int argIdx, BfIRAttribute attr); void Call_AddAttribute(BfIRValue callInst, int argIdx, BfIRAttribute attr);
void Call_AddAttribute(BfIRValue callInst, int argIdx, BfIRAttribute attr, int arg); void Call_AddAttribute(BfIRValue callInst, int argIdx, BfIRAttribute attr, int arg);
void Func_AddAttribute(BfIRFunction func, int argIdx, BfIRAttribute attr); void Func_AddAttribute(BfIRFunction func, int argIdx, BfIRAttribute attr);
void Func_AddAttribute(BfIRFunction func, int argIdx, BfIRAttribute attr, int arg); void Func_AddAttribute(BfIRFunction func, int argIdx, BfIRAttribute attr, int arg);
void Func_SetParamName(BfIRFunction func, int argIdx, const StringImpl& name); void Func_SetParamName(BfIRFunction func, int argIdx, const StringImpl& name);
void Func_DeleteBody(BfIRFunction func); void Func_DeleteBody(BfIRFunction func);
void Func_SafeRename(BfIRFunction func); void Func_SafeRename(BfIRFunction func);
void Func_SafeRenameFrom(BfIRFunction func, const StringImpl& prevName); void Func_SafeRenameFrom(BfIRFunction func, const StringImpl& prevName);
void Func_SetLinkage(BfIRFunction func, BfIRLinkageType linkage); void Func_SetLinkage(BfIRFunction func, BfIRLinkageType linkage);
void Comptime_Error(int errorKind); void Comptime_Error(int errorKind);
BfIRValue Comptime_GetBfType(int typeId, BfIRType resultType); BfIRValue Comptime_GetBfType(int typeId, BfIRType resultType);
BfIRValue Comptime_GetReflectType(int typeId, BfIRType resultType); BfIRValue Comptime_GetReflectType(int typeId, BfIRType resultType);
@ -1351,7 +1351,7 @@ public:
void RestoreDebugLocation(); void RestoreDebugLocation();
void DupDebugLocation(); void DupDebugLocation();
bool HasDebugLocation(); bool HasDebugLocation();
void ClearDebugLocation(); void ClearDebugLocation();
void ClearDebugLocation(BfIRValue inst); void ClearDebugLocation(BfIRValue inst);
void ClearDebugLocation_Last(); void ClearDebugLocation_Last();
void UpdateDebugLocation(BfIRValue inst); void UpdateDebugLocation(BfIRValue inst);
@ -1360,29 +1360,29 @@ public:
void CreateEnsureInstructionAt(); void CreateEnsureInstructionAt();
void CreateStatementStart(); void CreateStatementStart();
void CreateObjectAccessCheck(BfIRValue value, bool useAsm); void CreateObjectAccessCheck(BfIRValue value, bool useAsm);
void DbgInit(); void DbgInit();
void DbgFinalize(); void DbgFinalize();
bool DbgHasInfo(); bool DbgHasInfo();
bool DbgHasLineInfo(); bool DbgHasLineInfo();
String DbgGetStaticFieldName(BfFieldInstance* fieldInstance); String DbgGetStaticFieldName(BfFieldInstance* fieldInstance);
void DbgAddPrefix(String& name); void DbgAddPrefix(String& name);
BfIRMDNode DbgCreateCompileUnit(int lang, const StringImpl& filename, const StringImpl& directory, const StringImpl& producer, bool isOptimized, BfIRMDNode DbgCreateCompileUnit(int lang, const StringImpl& filename, const StringImpl& directory, const StringImpl& producer, bool isOptimized,
const StringImpl& flags, int runtimeVer, bool linesOnly); const StringImpl& flags, int runtimeVer, bool linesOnly);
BfIRMDNode DbgCreateFile(const StringImpl& fileName, const StringImpl& directory, const Val128& md5Hash); BfIRMDNode DbgCreateFile(const StringImpl& fileName, const StringImpl& directory, const Val128& md5Hash);
BfIRMDNode DbgGetCurrentLocation(); BfIRMDNode DbgGetCurrentLocation();
void DbgSetType(BfType * type, BfIRMDNode diType); void DbgSetType(BfType * type, BfIRMDNode diType);
void DbgSetInstType(BfType * type, BfIRMDNode diType); void DbgSetInstType(BfType * type, BfIRMDNode diType);
BfIRMDNode DbgCreateConstValue(int64 val); BfIRMDNode DbgCreateConstValue(int64 val);
BfIRMDNode DbgGetType(BfType* type, BfIRPopulateType populateType = BfIRPopulateType_Declaration); BfIRMDNode DbgGetType(BfType* type, BfIRPopulateType populateType = BfIRPopulateType_Declaration);
BfIRMDNode DbgGetTypeInst(BfTypeInstance* typeInst, BfIRPopulateType populateType = BfIRPopulateType_Declaration); BfIRMDNode DbgGetTypeInst(BfTypeInstance* typeInst, BfIRPopulateType populateType = BfIRPopulateType_Declaration);
void DbgTrackDITypes(BfType* type); void DbgTrackDITypes(BfType* type);
BfIRMDNode DbgCreateNameSpace(BfIRMDNode scope, const StringImpl& name, BfIRMDNode file, int lineNum); BfIRMDNode DbgCreateNameSpace(BfIRMDNode scope, const StringImpl& name, BfIRMDNode file, int lineNum);
BfIRMDNode DbgCreateImportedModule(BfIRMDNode context, BfIRMDNode namespaceNode, int line); BfIRMDNode DbgCreateImportedModule(BfIRMDNode context, BfIRMDNode namespaceNode, int line);
BfIRMDNode DbgCreateBasicType(const StringImpl& name, int64 sizeInBits, int64 alignInBits, int encoding); BfIRMDNode DbgCreateBasicType(const StringImpl& name, int64 sizeInBits, int64 alignInBits, int encoding);
BfIRMDNode DbgCreateStructType(BfIRMDNode context, const StringImpl& name, BfIRMDNode file, int lineNum, int64 sizeInBits, int64 alignInBits, BfIRMDNode DbgCreateStructType(BfIRMDNode context, const StringImpl& name, BfIRMDNode file, int lineNum, int64 sizeInBits, int64 alignInBits,
int flags, BfIRMDNode derivedFrom, const BfSizedArray<BfIRMDNode>& elements); int flags, BfIRMDNode derivedFrom, const BfSizedArray<BfIRMDNode>& elements);
BfIRMDNode DbgCreateEnumerationType(BfIRMDNode scope, const StringImpl& name, BfIRMDNode file, int lineNumber, int64 SizeInBits, int64 alignInBits, BfIRMDNode DbgCreateEnumerationType(BfIRMDNode scope, const StringImpl& name, BfIRMDNode file, int lineNumber, int64 SizeInBits, int64 alignInBits,
const BfSizedArray<BfIRMDNode>& elements, BfIRMDNode underlyingType); const BfSizedArray<BfIRMDNode>& elements, BfIRMDNode underlyingType);
BfIRMDNode DbgCreatePointerType(BfIRMDNode diType); BfIRMDNode DbgCreatePointerType(BfIRMDNode diType);
BfIRMDNode DbgCreateReferenceType(BfIRMDNode diType); BfIRMDNode DbgCreateReferenceType(BfIRMDNode diType);
@ -1397,14 +1397,14 @@ public:
void DbgDeleteTemporary(BfIRMDNode diNode); void DbgDeleteTemporary(BfIRMDNode diNode);
BfIRMDNode DbgMakePermanent(BfIRMDNode diNode, BfIRMDNode diBaseType, const BfSizedArray<BfIRMDNode>& elements); BfIRMDNode DbgMakePermanent(BfIRMDNode diNode, BfIRMDNode diBaseType, const BfSizedArray<BfIRMDNode>& elements);
BfIRMDNode DbgCreateEnumerator(const StringImpl& name, int64 val); BfIRMDNode DbgCreateEnumerator(const StringImpl& name, int64 val);
BfIRMDNode DbgCreateMemberType(BfIRMDNode scope, const StringImpl& name, BfIRMDNode file, int lineNumber, int64 sizeInBits, int64 alignInBits, BfIRMDNode DbgCreateMemberType(BfIRMDNode scope, const StringImpl& name, BfIRMDNode file, int lineNumber, int64 sizeInBits, int64 alignInBits,
int64 offsetInBits, int flags, BfIRMDNode type); int64 offsetInBits, int flags, BfIRMDNode type);
BfIRMDNode DbgCreateStaticMemberType(BfIRMDNode scope, const StringImpl& name, BfIRMDNode file, int lineNumber, BfIRMDNode type, int flags, BfIRValue val); BfIRMDNode DbgCreateStaticMemberType(BfIRMDNode scope, const StringImpl& name, BfIRMDNode file, int lineNumber, BfIRMDNode type, int flags, BfIRValue val);
BfIRMDNode DbgCreateInheritance(BfIRMDNode type, BfIRMDNode baseType, int64 baseOffset, int flags); BfIRMDNode DbgCreateInheritance(BfIRMDNode type, BfIRMDNode baseType, int64 baseOffset, int flags);
BfIRMDNode DbgCreateMethod(BfIRMDNode context, const StringImpl& name, const StringImpl& linkageName, BfIRMDNode file, int lineNum, BfIRMDNode type, BfIRMDNode DbgCreateMethod(BfIRMDNode context, const StringImpl& name, const StringImpl& linkageName, BfIRMDNode file, int lineNum, BfIRMDNode type,
bool isLocalToUnit, bool isDefinition, int vk, int vIndex, BfIRMDNode vTableHolder, int flags, bool isOptimized, BfIRValue fn, bool isLocalToUnit, bool isDefinition, int vk, int vIndex, BfIRMDNode vTableHolder, int flags, bool isOptimized, BfIRValue fn,
const BfSizedArray<BfIRMDNode>& genericArgs, const BfSizedArray<BfIRValue>& genericConstValueArgs); const BfSizedArray<BfIRMDNode>& genericArgs, const BfSizedArray<BfIRValue>& genericConstValueArgs);
BfIRMDNode DbgCreateFunction(BfIRMDNode context, const StringImpl& name, const StringImpl& linkageName, BfIRMDNode file, int lineNum, BfIRMDNode type, BfIRMDNode DbgCreateFunction(BfIRMDNode context, const StringImpl& name, const StringImpl& linkageName, BfIRMDNode file, int lineNum, BfIRMDNode type,
bool isLocalToUnit, bool isDefinition, int scopeLine, int flags, bool isOptimized, BfIRValue fn); bool isLocalToUnit, bool isDefinition, int scopeLine, int flags, bool isOptimized, BfIRValue fn);
BfIRMDNode DbgCreateParameterVariable(BfIRMDNode scope, const StringImpl& name, int argNo, BfIRMDNode file, int lineNum, BfIRMDNode type, BfIRMDNode DbgCreateParameterVariable(BfIRMDNode scope, const StringImpl& name, int argNo, BfIRMDNode file, int lineNum, BfIRMDNode type,
bool AlwaysPreserve = false, int flags = 0); bool AlwaysPreserve = false, int flags = 0);
@ -1414,14 +1414,13 @@ public:
BfIRValue DbgInsertValueIntrinsic(BfIRValue val, BfIRMDNode varInfo); BfIRValue DbgInsertValueIntrinsic(BfIRValue val, BfIRMDNode varInfo);
BfIRValue DbgInsertDeclare(BfIRValue val, BfIRMDNode varInfo, BfIRValue declareBefore = BfIRValue()); BfIRValue DbgInsertDeclare(BfIRValue val, BfIRMDNode varInfo, BfIRValue declareBefore = BfIRValue());
BfIRValue DbgLifetimeEnd(BfIRMDNode varInfo); BfIRValue DbgLifetimeEnd(BfIRMDNode varInfo);
void DbgCreateGlobalVariable(BfIRMDNode context, const StringImpl& name, const StringImpl& linkageName, BfIRMDNode file, int lineNumber, void DbgCreateGlobalVariable(BfIRMDNode context, const StringImpl& name, const StringImpl& linkageName, BfIRMDNode file, int lineNumber,
BfIRMDNode type, bool isLocalToUnit, BfIRValue val, BfIRMDNode Decl = BfIRMDNode()); BfIRMDNode type, bool isLocalToUnit, BfIRValue val, BfIRMDNode Decl = BfIRMDNode());
BfIRMDNode DbgCreateLexicalBlock(BfIRMDNode scope, BfIRMDNode file, int line, int col); BfIRMDNode DbgCreateLexicalBlock(BfIRMDNode scope, BfIRMDNode file, int line, int col);
void DbgCreateAnnotation(BfIRMDNode scope, const StringImpl& name, BfIRValue value); void DbgCreateAnnotation(BfIRMDNode scope, const StringImpl& name, BfIRValue value);
BfIRState GetState(); BfIRState GetState();
void SetState(const BfIRState& state); void SetState(const BfIRState& state);
}; };
NS_BF_END NS_BF_END

File diff suppressed because it is too large Load diff

View file

@ -20,7 +20,7 @@ namespace llvm
class AttributeList; class AttributeList;
class Module; class Module;
class LLVMContext; class LLVMContext;
class TargetMachine; class TargetMachine;
}; };
NS_BF_BEGIN NS_BF_BEGIN
@ -41,7 +41,7 @@ class BfIRIntrinsicData
public: public:
String mName; String mName;
BfIRIntrinsic mIntrinsic; BfIRIntrinsic mIntrinsic;
llvm::Type* mReturnType; llvm::Type* mReturnType;
}; };
struct BfIRCodeGenEntry struct BfIRCodeGenEntry
@ -52,7 +52,7 @@ struct BfIRCodeGenEntry
llvm::Value* mLLVMValue; llvm::Value* mLLVMValue;
llvm::Type* mLLVMType; llvm::Type* mLLVMType;
llvm::BasicBlock* mLLVMBlock; llvm::BasicBlock* mLLVMBlock;
llvm::MDNode* mLLVMMetadata; llvm::MDNode* mLLVMMetadata;
BfIRIntrinsicData* mIntrinsicData; BfIRIntrinsicData* mIntrinsicData;
}; };
}; };
@ -67,7 +67,7 @@ public:
llvm::DIType* mInstDIType; llvm::DIType* mInstDIType;
llvm::Type* mLLVMType; llvm::Type* mLLVMType;
llvm::Type* mAlignLLVMType; llvm::Type* mAlignLLVMType;
llvm::Type* mInstLLVMType; llvm::Type* mInstLLVMType;
public: public:
BfIRTypeEntry() BfIRTypeEntry()
@ -87,14 +87,14 @@ enum BfIRSizeAlignKind
{ {
BfIRSizeAlignKind_NoTransform, BfIRSizeAlignKind_NoTransform,
BfIRSizeAlignKind_Original, BfIRSizeAlignKind_Original,
BfIRSizeAlignKind_Aligned, BfIRSizeAlignKind_Aligned,
}; };
class BfIRCodeGen : public BfIRCodeGenBase class BfIRCodeGen : public BfIRCodeGenBase
{ {
public: public:
BfIRBuilder* mBfIRBuilder; BfIRBuilder* mBfIRBuilder;
BumpAllocator mAlloc; BumpAllocator mAlloc;
BfTargetTriple mTargetTriple; BfTargetTriple mTargetTriple;
String mTargetCPU; String mTargetCPU;
@ -113,7 +113,7 @@ public:
llvm::InlineAsm* mOverflowCheckAsm; llvm::InlineAsm* mOverflowCheckAsm;
llvm::DebugLoc mDebugLoc; llvm::DebugLoc mDebugLoc;
BfCodeGenOptions mCodeGenOptions; BfCodeGenOptions mCodeGenOptions;
bool mHasDebugLoc; bool mHasDebugLoc;
bool mIsCodeView; bool mIsCodeView;
bool mHadDLLExport; bool mHadDLLExport;
int mConstValIdx; int mConstValIdx;
@ -122,7 +122,7 @@ public:
Dictionary<int, BfIRCodeGenEntry> mResults; Dictionary<int, BfIRCodeGenEntry> mResults;
Dictionary<int, BfIRTypeEntry> mTypes; Dictionary<int, BfIRTypeEntry> mTypes;
Dictionary<int, llvm::Function*> mIntrinsicMap; Dictionary<int, llvm::Function*> mIntrinsicMap;
Dictionary<llvm::Function*, int> mIntrinsicReverseMap; Dictionary<llvm::Function*, int> mIntrinsicReverseMap;
Array<llvm::Constant*> mConfigConsts32; Array<llvm::Constant*> mConfigConsts32;
Array<llvm::Constant*> mConfigConsts64; Array<llvm::Constant*> mConfigConsts64;
Dictionary<llvm::Type*, llvm::Value*> mReflectDataMap; Dictionary<llvm::Type*, llvm::Value*> mReflectDataMap;
@ -131,7 +131,7 @@ public:
HashSet<llvm::BasicBlock*> mLockedBlocks; HashSet<llvm::BasicBlock*> mLockedBlocks;
OwnedArray<BfIRIntrinsicData> mIntrinsicData; OwnedArray<BfIRIntrinsicData> mIntrinsicData;
public: public:
void InitTarget(); void InitTarget();
void FixValues(llvm::StructType* structType, llvm::SmallVector<llvm::Value*, 8>& values); void FixValues(llvm::StructType* structType, llvm::SmallVector<llvm::Value*, 8>& values);
void FixIndexer(llvm::Value*& val); void FixIndexer(llvm::Value*& val);
@ -141,15 +141,15 @@ public:
BfIRTypeEntry* GetTypeEntry(llvm::Type* type); BfIRTypeEntry* GetTypeEntry(llvm::Type* type);
void SetResult(int id, llvm::Value* value); void SetResult(int id, llvm::Value* value);
void SetResultAligned(int id, llvm::Value* value); void SetResultAligned(int id, llvm::Value* value);
void SetResult(int id, llvm::Type* value); void SetResult(int id, llvm::Type* value);
void SetResult(int id, llvm::BasicBlock* value); void SetResult(int id, llvm::BasicBlock* value);
void SetResult(int id, llvm::MDNode* value); void SetResult(int id, llvm::MDNode* value);
void CreateMemSet(llvm::Value* addr, llvm::Value* val, llvm::Value* size, int alignment, bool isVolatile = false); void CreateMemSet(llvm::Value* addr, llvm::Value* val, llvm::Value* size, int alignment, bool isVolatile = false);
void AddNop(); void AddNop();
llvm::Value* TryToVector(llvm::Value* value); llvm::Value* TryToVector(llvm::Value* value);
llvm::Value* TryToVector(llvm::Value* value, llvm::Type* elemType); llvm::Value* TryToVector(llvm::Value* value, llvm::Type* elemType);
llvm::Type* GetElemType(llvm::Value* value); llvm::Type* GetElemType(llvm::Value* value);
bool TryMemCpy(llvm::Value* ptr, llvm::Value* val); bool TryMemCpy(llvm::Value* ptr, llvm::Value* val);
bool TryVectorCpy(llvm::Value* ptr, llvm::Value* val); bool TryVectorCpy(llvm::Value* ptr, llvm::Value* val);
llvm::Type* GetSizeAlignedType(BfIRTypeEntry* typeEntry); llvm::Type* GetSizeAlignedType(BfIRTypeEntry* typeEntry);
llvm::Value* GetAlignedPtr(llvm::Value* val); llvm::Value* GetAlignedPtr(llvm::Value* val);
@ -168,7 +168,7 @@ public:
void PrintFunction(); void PrintFunction();
int64 ReadSLEB128(); int64 ReadSLEB128();
void Read(StringImpl& str); void Read(StringImpl& str);
void Read(int& i); void Read(int& i);
void Read(int64& i); void Read(int64& i);
void Read(Val128& i); void Read(Val128& i);
@ -227,14 +227,14 @@ public:
llvm::BasicBlock* GetLLVMBlock(int streamId); llvm::BasicBlock* GetLLVMBlock(int streamId);
llvm::MDNode* GetLLVMMetadata(int streamId); llvm::MDNode* GetLLVMMetadata(int streamId);
llvm::Type* GetLLVMTypeById(int id); llvm::Type* GetLLVMTypeById(int id);
/// ///
bool WriteObjectFile(const StringImpl& outFileName); bool WriteObjectFile(const StringImpl& outFileName);
bool WriteIR(const StringImpl& outFileName, StringImpl& error); bool WriteIR(const StringImpl& outFileName, StringImpl& error);
static int GetIntrinsicId(const StringImpl& name); static int GetIntrinsicId(const StringImpl& name);
static const char* GetIntrinsicName(int intrinId); static const char* GetIntrinsicName(int intrinId);
static void SetAsmKind(BfAsmKind asmKind); static void SetAsmKind(BfAsmKind asmKind);
@ -242,4 +242,3 @@ public:
}; };
NS_BF_END NS_BF_END

File diff suppressed because it is too large Load diff

View file

@ -33,7 +33,7 @@ public:
Kind_MethodName, Kind_MethodName,
Kind_Prefix, Kind_Prefix,
Kind_PrimitivePrefix, Kind_PrimitivePrefix,
Kind_GenericParam Kind_GenericParam
}; };
public: public:
@ -54,7 +54,7 @@ public:
BfTypeInstance* mTypeInst; BfTypeInstance* mTypeInst;
BfMethodInstance* mMethodInstance; BfMethodInstance* mMethodInstance;
const char* mPrefix; const char* mPrefix;
}; };
public: public:
NameSubstitute(Kind kind, void* param) NameSubstitute(Kind kind, void* param)
@ -90,7 +90,7 @@ public:
class BfGNUMangler : public BfMangler class BfGNUMangler : public BfMangler
{ {
public: public:
class MangleContext class MangleContext
{ {
public: public:
@ -111,22 +111,22 @@ public:
mPrefixObjectPointer = false; mPrefixObjectPointer = false;
} }
}; };
static int ParseSubIdx(StringImpl& name, int strIdx); static int ParseSubIdx(StringImpl& name, int strIdx);
static void AddSubIdx(StringImpl& name, int strIdx); static void AddSubIdx(StringImpl& name, int strIdx);
static void AddSizedString(StringImpl& name, const StringImpl& addStr); static void AddSizedString(StringImpl& name, const StringImpl& addStr);
static BfTypeCode GetPrimTypeAt(MangleContext& mangleContext, StringImpl& name, int strIdx); static BfTypeCode GetPrimTypeAt(MangleContext& mangleContext, StringImpl& name, int strIdx);
static void AddPrefix(MangleContext& mangleContext, StringImpl& name, int startIdx, const char* prefix); static void AddPrefix(MangleContext& mangleContext, StringImpl& name, int startIdx, const char* prefix);
static void FindOrCreateNameSub(MangleContext& mangleContext, StringImpl& name, const NameSubstitute& newNameSub, int& curMatchIdx, bool& matchFailed); static void FindOrCreateNameSub(MangleContext& mangleContext, StringImpl& name, const NameSubstitute& newNameSub, int& curMatchIdx, bool& matchFailed);
static void FindOrCreateNameSub(MangleContext& mangleContext, StringImpl& name, BfTypeInstance* typeInst, int& curMatchIdx, bool& matchFailed); static void FindOrCreateNameSub(MangleContext& mangleContext, StringImpl& name, BfTypeInstance* typeInst, int& curMatchIdx, bool& matchFailed);
static void FindOrCreateNameSub(MangleContext& mangleContext, StringImpl& name, const NameSubstitute& newNameSub); static void FindOrCreateNameSub(MangleContext& mangleContext, StringImpl& name, const NameSubstitute& newNameSub);
public: public:
static void MangleTypeInst(MangleContext& mangleContext, StringImpl& name, BfTypeInstance* typeInst, BfTypeInstance* postfixTypeInst = NULL, bool* isEndOpen = NULL); static void MangleTypeInst(MangleContext& mangleContext, StringImpl& name, BfTypeInstance* typeInst, BfTypeInstance* postfixTypeInst = NULL, bool* isEndOpen = NULL);
static void Mangle(MangleContext& mangleContext, StringImpl& name, BfType* type, BfType* postfixType = NULL, bool isConst = false); static void Mangle(MangleContext& mangleContext, StringImpl& name, BfType* type, BfType* postfixType = NULL, bool isConst = false);
static String Mangle(BfType* type, BfModule* module = NULL); static String Mangle(BfType* type, BfModule* module = NULL);
static String Mangle(BfMethodInstance* methodRef); static String Mangle(BfMethodInstance* methodRef);
static String MangleMethodName(BfTypeInstance* type, const StringImpl& methodName); static String MangleMethodName(BfTypeInstance* type, const StringImpl& methodName);
static String Mangle(BfFieldInstance* methodRef); static String Mangle(BfFieldInstance* methodRef);
static String MangleStaticFieldName(BfTypeInstance* type, const StringImpl& fieldName); static String MangleStaticFieldName(BfTypeInstance* type, const StringImpl& fieldName);
@ -138,12 +138,12 @@ public:
class MangleContext class MangleContext
{ {
public: public:
bool mIsSafeMangle; bool mIsSafeMangle;
BfModule* mModule; BfModule* mModule;
bool mCCompat; bool mCCompat;
bool mCPPMangle; bool mCPPMangle;
bool mIs64Bit; bool mIs64Bit;
SizedArray<NameSubstitute, 10> mSubstituteList; SizedArray<NameSubstitute, 10> mSubstituteList;
SizedArray<BfType*, 10> mSubstituteTypeList; SizedArray<BfType*, 10> mSubstituteTypeList;
@ -154,7 +154,7 @@ public:
public: public:
MangleContext() MangleContext()
{ {
mIsSafeMangle = false; mIsSafeMangle = false;
mModule = NULL; mModule = NULL;
mCCompat = false; mCCompat = false;
mIs64Bit = false; mIs64Bit = false;
@ -164,11 +164,11 @@ public:
mInRet = false; mInRet = false;
} }
BfModule* GetUnreifiedModule(); BfModule* GetUnreifiedModule();
}; };
static void AddGenericArgs(MangleContext& mangleContext, StringImpl& name, const SizedArrayImpl<BfType*>& genericArgs, int numOuterGenericParams = 0); static void AddGenericArgs(MangleContext& mangleContext, StringImpl& name, const SizedArrayImpl<BfType*>& genericArgs, int numOuterGenericParams = 0);
static void AddStr(MangleContext& mangleContext, StringImpl& name, const StringImpl& str); static void AddStr(MangleContext& mangleContext, StringImpl& name, const StringImpl& str);
static void Mangle(MangleContext& mangleContext, StringImpl& name, BfType* type, bool useTypeList = false, bool isConst = false); static void Mangle(MangleContext& mangleContext, StringImpl& name, BfType* type, bool useTypeList = false, bool isConst = false);
static void Mangle(MangleContext& mangleContext, StringImpl& name, BfTypeInstance* typeInst, bool isAlreadyStarted, bool isOuterType = false); static void Mangle(MangleContext& mangleContext, StringImpl& name, BfTypeInstance* typeInst, bool isAlreadyStarted, bool isOuterType = false);
@ -176,8 +176,8 @@ public:
void AddPrefix(MangleContext & mangleContext, StringImpl& name, int startIdx, const char * prefix); void AddPrefix(MangleContext & mangleContext, StringImpl& name, int startIdx, const char * prefix);
static void AddSubIdx(StringImpl& name, int strIdx); static void AddSubIdx(StringImpl& name, int strIdx);
static void AddTypeStart(MangleContext & mangleContext, StringImpl& name, BfType* type); static void AddTypeStart(MangleContext & mangleContext, StringImpl& name, BfType* type);
static bool FindOrCreateNameSub(MangleContext& mangleContext, StringImpl& name, const NameSubstitute& newNameSub); static bool FindOrCreateNameSub(MangleContext& mangleContext, StringImpl& name, const NameSubstitute& newNameSub);
public: public:
@ -188,7 +188,7 @@ public:
static void MangleStaticFieldName(StringImpl& outStr, bool is64Bit, BfTypeInstance* type, const StringImpl& fieldName, BfType* fieldType = NULL); static void MangleStaticFieldName(StringImpl& outStr, bool is64Bit, BfTypeInstance* type, const StringImpl& fieldName, BfType* fieldType = NULL);
}; };
// A "safe mangle" is used for reconnecting deleted types to their previous id. We make sure we never force a // A "safe mangle" is used for reconnecting deleted types to their previous id. We make sure we never force a
// PopulateType with this kind of mangle, as referenced types may be deleted and marked as undefined // PopulateType with this kind of mangle, as referenced types may be deleted and marked as undefined
class BfSafeMangler : public BfMSMangler class BfSafeMangler : public BfMSMangler
{ {

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -6,14 +6,13 @@ USING_NS_BF;
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
void BfNamespaceVisitor::Visit(BfUsingDirective* usingDirective) void BfNamespaceVisitor::Visit(BfUsingDirective* usingDirective)
{ {
if (usingDirective->mNamespace == NULL) if (usingDirective->mNamespace == NULL)
{ {
return; return;
} }
String usingString = usingDirective->mNamespace->ToString(); String usingString = usingDirective->mNamespace->ToString();
BfAtomCompositeT<16> usingComposite; BfAtomCompositeT<16> usingComposite;
mSystem->ParseAtomComposite(usingString, usingComposite); mSystem->ParseAtomComposite(usingString, usingComposite);
@ -24,11 +23,11 @@ void BfNamespaceVisitor::Visit(BfUsingDirective* usingDirective)
} }
void BfNamespaceVisitor::Visit(BfUsingModDirective* usingDirective) void BfNamespaceVisitor::Visit(BfUsingModDirective* usingDirective)
{ {
BfAstNode* useNode = usingDirective->mTypeRef; BfAstNode* useNode = usingDirective->mTypeRef;
BfAstNode* checkNode = usingDirective->mTypeRef; BfAstNode* checkNode = usingDirective->mTypeRef;
while (true) while (true)
{ {
if (auto qualifiedTypeRef = BfNodeDynCast<BfQualifiedTypeReference>(checkNode)) if (auto qualifiedTypeRef = BfNodeDynCast<BfQualifiedTypeReference>(checkNode))
checkNode = qualifiedTypeRef->mLeft; checkNode = qualifiedTypeRef->mLeft;
else if (auto elementedTypeRef = BfNodeDynCast<BfElementedTypeRef>(checkNode)) else if (auto elementedTypeRef = BfNodeDynCast<BfElementedTypeRef>(checkNode))
@ -42,9 +41,9 @@ void BfNamespaceVisitor::Visit(BfUsingModDirective* usingDirective)
if (useNode == NULL) if (useNode == NULL)
return; return;
String usingString = useNode->ToString(); String usingString = useNode->ToString();
BfAtomCompositeT<16> usingComposite; BfAtomCompositeT<16> usingComposite;
if (mSystem->ParseAtomComposite(usingString, usingComposite)) if (mSystem->ParseAtomComposite(usingString, usingComposite))
mResolvePassData->HandleNamespaceReference(useNode, usingComposite); mResolvePassData->HandleNamespaceReference(useNode, usingComposite);
@ -53,7 +52,7 @@ void BfNamespaceVisitor::Visit(BfUsingModDirective* usingDirective)
void BfNamespaceVisitor::Visit(BfNamespaceDeclaration* namespaceDeclaration) void BfNamespaceVisitor::Visit(BfNamespaceDeclaration* namespaceDeclaration)
{ {
BfAtomCompositeT<16> prevNamespace = mNamespace; BfAtomCompositeT<16> prevNamespace = mNamespace;
if (namespaceDeclaration->mNameNode == NULL) if (namespaceDeclaration->mNameNode == NULL)
return; return;
@ -64,7 +63,7 @@ void BfNamespaceVisitor::Visit(BfNamespaceDeclaration* namespaceDeclaration)
if (dotIdx == -1) if (dotIdx == -1)
{ {
BfAtom* namespaceAtom = mSystem->FindAtom(namespaceLeft); BfAtom* namespaceAtom = mSystem->FindAtom(namespaceLeft);
mNamespace.Set(mNamespace.mParts, mNamespace.mSize, &namespaceAtom, 1); mNamespace.Set(mNamespace.mParts, mNamespace.mSize, &namespaceAtom, 1);
break; break;
} }
@ -76,7 +75,7 @@ void BfNamespaceVisitor::Visit(BfNamespaceDeclaration* namespaceDeclaration)
if (mResolvePassData->mAutoComplete != NULL) if (mResolvePassData->mAutoComplete != NULL)
mResolvePassData->mAutoComplete->CheckNamespace(namespaceDeclaration->mNameNode, mNamespace); mResolvePassData->mAutoComplete->CheckNamespace(namespaceDeclaration->mNameNode, mNamespace);
mResolvePassData->HandleNamespaceReference(namespaceDeclaration->mNameNode, mNamespace); mResolvePassData->HandleNamespaceReference(namespaceDeclaration->mNameNode, mNamespace);
VisitChild(namespaceDeclaration->mBody); VisitChild(namespaceDeclaration->mBody);
mNamespace = prevNamespace; mNamespace = prevNamespace;
} }
@ -88,4 +87,4 @@ void BfNamespaceVisitor::Visit(BfBlock* block)
void BfNamespaceVisitor::Visit(BfRootNode* rootNode) void BfNamespaceVisitor::Visit(BfRootNode* rootNode)
{ {
VisitMembers(rootNode); VisitMembers(rootNode);
} }

View file

@ -9,7 +9,7 @@ class BfResolvePassData;
class BfNamespaceVisitor : public BfStructuralVisitor class BfNamespaceVisitor : public BfStructuralVisitor
{ {
public: public:
BfSystem* mSystem; BfSystem* mSystem;
BfResolvePassData* mResolvePassData; BfResolvePassData* mResolvePassData;
BfAtomComposite mNamespace; BfAtomComposite mNamespace;
@ -20,7 +20,7 @@ public:
mSystem = NULL; mSystem = NULL;
mResolvePassData = NULL; mResolvePassData = NULL;
} }
virtual void Visit(BfUsingDirective* usingDirective) override; virtual void Visit(BfUsingDirective* usingDirective) override;
virtual void Visit(BfUsingModDirective* usingDirective) override; virtual void Visit(BfUsingModDirective* usingDirective) override;
virtual void Visit(BfNamespaceDeclaration* namespaceDeclaration) override; virtual void Visit(BfNamespaceDeclaration* namespaceDeclaration) override;

View file

@ -1,6 +1,5 @@
#pragma warning(disable:4996) #pragma warning(disable:4996)
#include "BfParser.h" #include "BfParser.h"
#include "BfReducer.h" #include "BfReducer.h"
#include "BfPrinter.h" #include "BfPrinter.h"
@ -158,7 +157,7 @@ void BfParserCache::ReportMemory(MemReporter* memReporter)
int allocPages = 0; int allocPages = 0;
int usedPages = 0; int usedPages = 0;
mAstAllocManager.GetStats(allocPages, usedPages); mAstAllocManager.GetStats(allocPages, usedPages);
OutputDebugStrF("Parsers: %d Chars: %d UsedAlloc: %dk BytesPerChar: %d SysAllocPages: %d SysUsedPages: %d (%dk) LargeAllocs: %dk\n", (int)mEntries.size(), srcLen, allocBytesUsed / 1024, OutputDebugStrF("Parsers: %d Chars: %d UsedAlloc: %dk BytesPerChar: %d SysAllocPages: %d SysUsedPages: %d (%dk) LargeAllocs: %dk\n", (int)mEntries.size(), srcLen, allocBytesUsed / 1024,
allocBytesUsed / BF_MAX(1, srcLen), allocPages, usedPages, (usedPages * BfAstAllocManager::PAGE_SIZE) / 1024, largeAllocs / 1024); allocBytesUsed / BF_MAX(1, srcLen), allocPages, usedPages, (usedPages * BfAstAllocManager::PAGE_SIZE) / 1024, largeAllocs / 1024);
@ -182,7 +181,6 @@ static int DecodeInt(uint8* buf, int& idx)
curByte = buf[idx++]; curByte = buf[idx++];
value |= ((curByte & 0x7f) << shift); value |= ((curByte & 0x7f) << shift);
shift += 7; shift += 7;
} while (curByte >= 128); } while (curByte >= 128);
// Sign extend negative numbers. // Sign extend negative numbers.
if (((curByte & 0x40) != 0) && (shift < 64)) if (((curByte & 0x40) != 0) && (shift < 64))
@ -192,14 +190,14 @@ static int DecodeInt(uint8* buf, int& idx)
static int gCurDataId = 0; static int gCurDataId = 0;
BfParserData::BfParserData() BfParserData::BfParserData()
{ {
mDataId = (int)BfpSystem_InterlockedExchangeAdd32((uint32*)&gCurDataId, 1) + 1; mDataId = (int)BfpSystem_InterlockedExchangeAdd32((uint32*)&gCurDataId, 1) + 1;
mHash = 0; mHash = 0;
mRefCount = -1; mRefCount = -1;
mJumpTable = NULL; mJumpTable = NULL;
mJumpTableSize = 0; mJumpTableSize = 0;
mFailed = false; mFailed = false;
mCharIdData = NULL; mCharIdData = NULL;
mUniqueParser = NULL; mUniqueParser = NULL;
mDidReduce = false; mDidReduce = false;
@ -239,7 +237,7 @@ int BfParserData::GetCharIdAtIndex(int findIndex)
} }
void BfParserData::GetLineCharAtIdx(int idx, int& line, int& lineChar) void BfParserData::GetLineCharAtIdx(int idx, int& line, int& lineChar)
{ {
if (mJumpTableSize <= 0) if (mJumpTableSize <= 0)
{ {
line = 0; line = 0;
@ -348,7 +346,7 @@ BfParser::BfParser(BfSystem* bfSystem, BfProject* bfProject) : BfSource(bfSystem
{ {
BfLogSys(bfSystem, "BfParser::BfParser %08X\n", this); BfLogSys(bfSystem, "BfParser::BfParser %08X\n", this);
gParserCount++; gParserCount++;
mTextVersion = -1; mTextVersion = -1;
mEmbedKind = BfSourceEmbedKind_None; mEmbedKind = BfSourceEmbedKind_None;
@ -374,15 +372,15 @@ BfParser::BfParser(BfSystem* bfSystem, BfProject* bfProject) : BfSource(bfSystem
mLineStart = 0; mLineStart = 0;
//mCurToken = (BfSyntaxToken)0; //mCurToken = (BfSyntaxToken)0;
mToken = BfToken_None; mToken = BfToken_None;
mSyntaxToken = BfSyntaxToken_None; mSyntaxToken = BfSyntaxToken_None;
mTokenStart = 0; mTokenStart = 0;
mTokenEnd = 0; mTokenEnd = 0;
mLineNum = 0; mLineNum = 0;
mCompatMode = false; mCompatMode = false;
mQuickCompatMode = false; mQuickCompatMode = false;
mLiteral.mWarnType = 0; mLiteral.mWarnType = 0;
mDataId = -1; mDataId = -1;
mTriviaStart = 0; mTriviaStart = 0;
mParsingFailed = false; mParsingFailed = false;
@ -397,7 +395,6 @@ BfParser::BfParser(BfSystem* bfSystem, BfProject* bfProject) : BfSource(bfSystem
} }
} }
//static std::set<BfAstNode*> gFoundNodes; //static std::set<BfAstNode*> gFoundNodes;
BfParser::~BfParser() BfParser::~BfParser()
@ -406,7 +403,6 @@ BfParser::~BfParser()
if (mParserData == NULL) if (mParserData == NULL)
{ {
} }
else if (mParserData->mRefCount == -1) else if (mParserData->mRefCount == -1)
{ {
@ -419,12 +415,12 @@ BfParser::~BfParser()
// Just never got added to the cache // Just never got added to the cache
delete mParserData; delete mParserData;
} }
else else
{ {
mParserData->Deref(); mParserData->Deref();
} }
mSourceData = NULL; mSourceData = NULL;
BfLogSys(mSystem, "BfParser::~BfParser %p\n", this); BfLogSys(mSystem, "BfParser::~BfParser %p\n", this);
} }
@ -470,9 +466,9 @@ void BfParser::TokenFail(const StringImpl& error, int offset)
void BfParser::Init(uint64 cacheHash) void BfParser::Init(uint64 cacheHash)
{ {
BF_ASSERT(mParserData == NULL); BF_ASSERT(mParserData == NULL);
mParserData = new BfParserData(); mParserData = new BfParserData();
mSourceData = mParserData; mSourceData = mParserData;
mParserData->mFileName = mFileName; mParserData->mFileName = mFileName;
if (mDataId != -1) if (mDataId != -1)
mParserData->mDataId = mDataId; mParserData->mDataId = mDataId;
@ -481,7 +477,7 @@ void BfParser::Init(uint64 cacheHash)
mParserData->mAstAllocManager = &gBfParserCache->mAstAllocManager; mParserData->mAstAllocManager = &gBfParserCache->mAstAllocManager;
mParserData->mSrc = mSrc; mParserData->mSrc = mSrc;
mParserData->mSrcLength = mSrcLength; mParserData->mSrcLength = mSrcLength;
if (cacheHash != 0) if (cacheHash != 0)
{ {
BfLogSysM("Creating cached parserData %p for %p %s\n", mParserData, this, mFileName.c_str()); BfLogSysM("Creating cached parserData %p for %p %s\n", mParserData, this, mFileName.c_str());
@ -503,9 +499,9 @@ void BfParser::Init(uint64 cacheHash)
mParserData->mJumpTable = mJumpTable; mParserData->mJumpTable = mJumpTable;
mParserData->mJumpTableSize = mJumpTableSize; mParserData->mJumpTableSize = mJumpTableSize;
mAlloc = &mParserData->mAlloc; mAlloc = &mParserData->mAlloc;
mAlloc->mSourceData = mSourceData; mAlloc->mSourceData = mSourceData;
} }
void BfParser::NewLine() void BfParser::NewLine()
@ -529,7 +525,7 @@ void BfParser::SetSource(const char* data, int length)
const int EXTRA_BUFFER_SIZE = 80; // Extra chars for a bit of AllocChars room const int EXTRA_BUFFER_SIZE = 80; // Extra chars for a bit of AllocChars room
//TODO: Check cache //TODO: Check cache
// Don't cache if we have a Cursorid set, // Don't cache if we have a Cursorid set,
// if mDataId != -1 // if mDataId != -1
// if BfParerFlag != 0 // if BfParerFlag != 0
@ -570,7 +566,7 @@ void BfParser::SetSource(const char* data, int length)
BfParserCache::DataEntry* dataEntryP; BfParserCache::DataEntry* dataEntryP;
if (gBfParserCache->mEntries.TryGetWith(lookupEntry, &dataEntryP)) if (gBfParserCache->mEntries.TryGetWith(lookupEntry, &dataEntryP))
{ {
mUsingCache = true; mUsingCache = true;
mParserData = dataEntryP->mParserData; mParserData = dataEntryP->mParserData;
@ -595,7 +591,7 @@ void BfParser::SetSource(const char* data, int length)
mSrcLength = length; mSrcLength = length;
mOrigSrcLength = length; mOrigSrcLength = length;
mSrcAllocSize = mSrcLength /*+ EXTRA_BUFFER_SIZE*/; mSrcAllocSize = mSrcLength /*+ EXTRA_BUFFER_SIZE*/;
char* ownedSrc = new char[mSrcAllocSize + 1]; char* ownedSrc = new char[mSrcAllocSize + 1];
if (data != NULL) if (data != NULL)
memcpy(ownedSrc, data, length); memcpy(ownedSrc, data, length);
@ -753,7 +749,7 @@ BfBlock* BfParser::ParseInlineBlock(int spaceIdx, int endIdx)
break; break;
if ((childNode->IsA<BfCommentNode>())) if ((childNode->IsA<BfCommentNode>()))
{ {
mSidechannelRootNode->Add(childNode); mSidechannelRootNode->Add(childNode);
mPendingSideNodes.push_back(childNode); mPendingSideNodes.push_back(childNode);
continue; continue;
} }
@ -798,7 +794,7 @@ void BfParser::HandlePragma(const StringImpl& pragma, BfBlock* block)
if (paramNode->ToStringView() == "warning") if (paramNode->ToStringView() == "warning")
{ {
++itr; ++itr;
//auto iterNode = paramNode->mNext; //auto iterNode = paramNode->mNext;
//BfAstNode* iterNode = parentNode->mChildArr.GetAs<BfAstNode*>(++curIdx); //BfAstNode* iterNode = parentNode->mChildArr.GetAs<BfAstNode*>(++curIdx);
BfAstNode* iterNode = itr.Get(); BfAstNode* iterNode = itr.Get();
@ -863,11 +859,11 @@ void BfParser::HandlePragma(const StringImpl& pragma, BfBlock* block)
} }
else if (paramNode->ToStringView() == "format") else if (paramNode->ToStringView() == "format")
{ {
++itr; ++itr;
BfAstNode* iterNode = itr.Get(); BfAstNode* iterNode = itr.Get();
if (iterNode) if (iterNode)
{ {
if ((iterNode->ToStringView() != "disable") && if ((iterNode->ToStringView() != "disable") &&
(iterNode->ToStringView() != "restore")) (iterNode->ToStringView() != "restore"))
{ {
mPassInstance->FailAfterAt("Expected \"disable\" or \"restore\" after \"format\"", mSourceData, paramNode->GetSrcEnd() - 1); mPassInstance->FailAfterAt("Expected \"disable\" or \"restore\" after \"format\"", mSourceData, paramNode->GetSrcEnd() - 1);
@ -881,13 +877,13 @@ void BfParser::HandlePragma(const StringImpl& pragma, BfBlock* block)
} }
void BfParser::HandleDefine(const StringImpl& name, BfAstNode* paramNode) void BfParser::HandleDefine(const StringImpl& name, BfAstNode* paramNode)
{ {
mPreprocessorDefines[name] = BfDefineState_ManualSet; mPreprocessorDefines[name] = BfDefineState_ManualSet;
} }
void BfParser::HandleUndefine(const StringImpl& name) void BfParser::HandleUndefine(const StringImpl& name)
{ {
mPreprocessorDefines[name] = BfDefineState_ManualUnset; mPreprocessorDefines[name] = BfDefineState_ManualUnset;
} }
MaybeBool BfParser::HandleIfDef(const StringImpl& name) MaybeBool BfParser::HandleIfDef(const StringImpl& name)
@ -925,16 +921,14 @@ MaybeBool BfParser::HandleProcessorCondition(BfBlock* paramNode)
void BfParser::HandleInclude(BfAstNode* paramNode) void BfParser::HandleInclude(BfAstNode* paramNode)
{ {
} }
void BfParser::HandleIncludeNext(BfAstNode* paramNode) void BfParser::HandleIncludeNext(BfAstNode* paramNode)
{ {
} }
bool BfParser::HandlePreprocessor() bool BfParser::HandlePreprocessor()
{ {
int triviaStart = mTriviaStart; int triviaStart = mTriviaStart;
int checkIdx = 0; int checkIdx = 0;
@ -958,7 +952,7 @@ bool BfParser::HandlePreprocessor()
String pragmaParam; String pragmaParam;
switch (mSrc[mSrcIdx - 1]) switch (mSrc[mSrcIdx - 1])
{ {
case '<': case '<':
if (mPreprocessorIgnoreDepth > 0) if (mPreprocessorIgnoreDepth > 0)
return false; return false;
@ -967,15 +961,15 @@ bool BfParser::HandlePreprocessor()
case '=': case '=':
if (mPreprocessorIgnoreDepth > 0) if (mPreprocessorIgnoreDepth > 0)
return false; return false;
pragma = "==="; pragma = "===";
break; break;
case '>': case '>':
if (mPreprocessorIgnoreDepth > 1) if (mPreprocessorIgnoreDepth > 1)
return false; return false;
pragma = ">>>"; pragma = ">>>";
break; break;
} }
bool atEnd = false; bool atEnd = false;
int startIdx = mSrcIdx - 1; int startIdx = mSrcIdx - 1;
@ -1003,7 +997,7 @@ bool BfParser::HandlePreprocessor()
} }
if (!hadSlash) if (!hadSlash)
break; break;
} }
if (c == '\0') if (c == '\0')
@ -1045,7 +1039,7 @@ bool BfParser::HandlePreprocessor()
BfBlock* paramNode = NULL; BfBlock* paramNode = NULL;
if (pragma.IsEmpty()) if (pragma.IsEmpty())
{ {
if (spaceIdx != -1) if (spaceIdx != -1)
{ {
pragma = String(mSrc + charIdx, mSrc + spaceIdx); pragma = String(mSrc + charIdx, mSrc + spaceIdx);
@ -1234,7 +1228,7 @@ bool BfParser::HandlePreprocessor()
mPreprocessorNodeStack.pop_back(); mPreprocessorNodeStack.pop_back();
} }
else if (pragma == "define") else if (pragma == "define")
{ {
if ((paramNode != NULL) && (!paramNode->mChildArr.IsEmpty())) if ((paramNode != NULL) && (!paramNode->mChildArr.IsEmpty()))
HandleDefine(paramNode->mChildArr[0]->ToString(), paramNode); HandleDefine(paramNode->mChildArr[0]->ToString(), paramNode);
wantedParam = true; wantedParam = true;
@ -1247,7 +1241,7 @@ bool BfParser::HandlePreprocessor()
} }
else if (pragma == "error") else if (pragma == "error")
{ {
wantsSingleParam = false; wantsSingleParam = false;
mPassInstance->FailAt(pragmaParam, mSourceData, startIdx, mSrcIdx - startIdx); mPassInstance->FailAt(pragmaParam, mSourceData, startIdx, mSrcIdx - startIdx);
wantedParam = true; wantedParam = true;
} }
@ -1370,7 +1364,6 @@ struct StrHashT<4>
{ {
const static int HASH = (StrHashT<3>::HASH) ^ Str[4]; const static int HASH = (StrHashT<3>::HASH) ^ Str[4];
}; };
}; };
// This is little endian only // This is little endian only
@ -1512,7 +1505,7 @@ void BfParser::NextToken(int endIdx, bool outerIsInterpolate, bool disablePrepro
if (mSrc[mSrcIdx + 1] == '=') if (mSrc[mSrcIdx + 1] == '=')
{ {
if (mSrc[mSrcIdx + 2] == '=') if (mSrc[mSrcIdx + 2] == '=')
{ {
if (HandlePreprocessor()) if (HandlePreprocessor())
{ {
// Conflict split // Conflict split
@ -1782,7 +1775,7 @@ void BfParser::NextToken(int endIdx, bool outerIsInterpolate, bool disablePrepro
} }
break; break;
case '$': case '$':
c = mSrc[mSrcIdx]; c = mSrc[mSrcIdx];
if ((c == '\"') || (c == '@') || (c == '$')) if ((c == '\"') || (c == '@') || (c == '$'))
{ {
@ -1795,7 +1788,7 @@ void BfParser::NextToken(int endIdx, bool outerIsInterpolate, bool disablePrepro
case '\'': case '\'':
{ {
SizedArray<BfUnscopedBlock*, 4> interpolateExpressions; SizedArray<BfUnscopedBlock*, 4> interpolateExpressions;
String lineHeader; String lineHeader;
String strLiteral; String strLiteral;
char startChar = c; char startChar = c;
@ -2139,9 +2132,9 @@ void BfParser::NextToken(int endIdx, bool outerIsInterpolate, bool disablePrepro
mPassInstance->FailAfterAt("Expected '}'", mSourceData, newBlock->GetSrcEnd() - 1); mPassInstance->FailAfterAt("Expected '}'", mSourceData, newBlock->GetSrcEnd() - 1);
} }
mInAsmBlock = false; mInAsmBlock = false;
interpolateExpressions.Add(newBlock); interpolateExpressions.Add(newBlock);
} }
if (interpolateSetting == 1) if (interpolateSetting == 1)
{ {
for (int i = 0; i < braceCount - 1; i++) for (int i = 0; i < braceCount - 1; i++)
@ -2169,7 +2162,7 @@ void BfParser::NextToken(int endIdx, bool outerIsInterpolate, bool disablePrepro
braceCount++; braceCount++;
mSrcIdx++; mSrcIdx++;
} }
bool isClosingBrace = false; bool isClosingBrace = false;
if (!interpolateExpressions.IsEmpty()) if (!interpolateExpressions.IsEmpty())
@ -2186,14 +2179,14 @@ void BfParser::NextToken(int endIdx, bool outerIsInterpolate, bool disablePrepro
isClosingBrace = true; isClosingBrace = true;
} }
else if (block->mCloseBrace->mSrcStart == mSrcIdx - braceCount) else if (block->mCloseBrace->mSrcStart == mSrcIdx - braceCount)
{ {
block->mCloseBrace->mSrcEnd = mSrcIdx - braceCount + interpolateSetting; block->mCloseBrace->mSrcEnd = mSrcIdx - braceCount + interpolateSetting;
isClosingBrace = true; isClosingBrace = true;
} }
} }
if (interpolateSetting == 1) if (interpolateSetting == 1)
{ {
for (int i = 0; i < braceCount - 1; i++) for (int i = 0; i < braceCount - 1; i++)
strLiteral += '}'; strLiteral += '}';
} }
@ -2222,7 +2215,7 @@ void BfParser::NextToken(int endIdx, bool outerIsInterpolate, bool disablePrepro
{ {
mTokenStart = stringStart; mTokenStart = stringStart;
stringStart = -1; stringStart = -1;
} }
mTriviaStart = triviaStart; mTriviaStart = triviaStart;
mTokenEnd = mSrcIdx; mTokenEnd = mSrcIdx;
@ -2246,7 +2239,7 @@ void BfParser::NextToken(int endIdx, bool outerIsInterpolate, bool disablePrepro
{ {
bool isGraphemeCluster = false; bool isGraphemeCluster = false;
// There's no explicit unicode limit to how many diacriticals a grapheme cluster can contain, // There's no explicit unicode limit to how many diacriticals a grapheme cluster can contain,
// but we apply a limit for sanity for the purpose of this error // but we apply a limit for sanity for the purpose of this error
if (strLiteral.length() < 64) if (strLiteral.length() < 64)
{ {
@ -2266,7 +2259,7 @@ void BfParser::NextToken(int endIdx, bool outerIsInterpolate, bool disablePrepro
{ {
mLiteral.mInt64 = (uint8)strLiteral[0]; mLiteral.mInt64 = (uint8)strLiteral[0];
} }
if (mLiteral.mInt64 >= 0x8000) // Use 0x8000 to remain UTF16-compatible if (mLiteral.mInt64 >= 0x8000) // Use 0x8000 to remain UTF16-compatible
mLiteral.mTypeCode = BfTypeCode_Char32; mLiteral.mTypeCode = BfTypeCode_Char32;
else if (mLiteral.mInt64 >= 0x80) // Use 0x80 to remain UTF8-compatible else if (mLiteral.mInt64 >= 0x80) // Use 0x80 to remain UTF8-compatible
@ -2289,7 +2282,7 @@ void BfParser::NextToken(int endIdx, bool outerIsInterpolate, bool disablePrepro
interpolateExpr->mTriviaStart = mTriviaStart; interpolateExpr->mTriviaStart = mTriviaStart;
interpolateExpr->mSrcStart = mTokenStart; interpolateExpr->mSrcStart = mTokenStart;
interpolateExpr->mSrcEnd = mSrcIdx; interpolateExpr->mSrcEnd = mSrcIdx;
BfSizedArrayInitIndirect(interpolateExpr->mExpressions, interpolateExpressions, mAlloc); BfSizedArrayInitIndirect(interpolateExpr->mExpressions, interpolateExpressions, mAlloc);
mGeneratedNode = interpolateExpr; mGeneratedNode = interpolateExpr;
mSyntaxToken = BfSyntaxToken_GeneratedNode; mSyntaxToken = BfSyntaxToken_GeneratedNode;
mToken = BfToken_None; mToken = BfToken_None;
@ -2321,10 +2314,10 @@ void BfParser::NextToken(int endIdx, bool outerIsInterpolate, bool disablePrepro
if (!mPendingSideNodes.IsEmpty()) if (!mPendingSideNodes.IsEmpty())
{ {
if (auto prevComment = BfNodeDynCast<BfCommentNode>(mPendingSideNodes.back())) if (auto prevComment = BfNodeDynCast<BfCommentNode>(mPendingSideNodes.back()))
{ {
// This is required for folding '///' style multi-line documentation into a single node // This is required for folding '///' style multi-line documentation into a single node
if (prevComment->GetTriviaStart() == mTriviaStart) if (prevComment->GetTriviaStart() == mTriviaStart)
{ {
auto prevCommentKind = GetCommentKind(prevComment->mSrcStart); auto prevCommentKind = GetCommentKind(prevComment->mSrcStart);
if ((!BfIsCommentBlock(commentKind)) && (commentKind == prevCommentKind)) if ((!BfIsCommentBlock(commentKind)) && (commentKind == prevCommentKind))
@ -2339,7 +2332,7 @@ void BfParser::NextToken(int endIdx, bool outerIsInterpolate, bool disablePrepro
if ((!handled) && (!disablePreprocessor)) if ((!handled) && (!disablePreprocessor))
{ {
auto bfCommentNode = mAlloc->Alloc<BfCommentNode>(); auto bfCommentNode = mAlloc->Alloc<BfCommentNode>();
bfCommentNode->Init(this); bfCommentNode->Init(this);
bfCommentNode->mCommentKind = commentKind; bfCommentNode->mCommentKind = commentKind;
mSidechannelRootNode->Add(bfCommentNode); mSidechannelRootNode->Add(bfCommentNode);
mPendingSideNodes.push_back(bfCommentNode); mPendingSideNodes.push_back(bfCommentNode);
@ -2547,7 +2540,7 @@ void BfParser::NextToken(int endIdx, bool outerIsInterpolate, bool disablePrepro
return; return;
default: default:
if (((c >= '0') && (c <= '9')) || (c == '-')) if (((c >= '0') && (c <= '9')) || (c == '-'))
{ {
bool prevIsDot = prevToken == BfToken_Dot; bool prevIsDot = prevToken == BfToken_Dot;
if (c == '-') if (c == '-')
@ -2577,7 +2570,7 @@ void BfParser::NextToken(int endIdx, bool outerIsInterpolate, bool disablePrepro
mTokenEnd = mSrcIdx; mTokenEnd = mSrcIdx;
return; return;
} }
bool hadOverflow = false; bool hadOverflow = false;
uint64 val = 0; uint64 val = 0;
int numberBase = 10; int numberBase = 10;
@ -2674,14 +2667,14 @@ void BfParser::NextToken(int endIdx, bool outerIsInterpolate, bool disablePrepro
{ {
// Skip float parsing if we have a double-dot `1..` case // Skip float parsing if we have a double-dot `1..` case
hasDot = false; hasDot = false;
} }
// The 'prevIsDot' helps tuple lookups like "tuple.0.0", interpreting those as two integers rather than a float // The 'prevIsDot' helps tuple lookups like "tuple.0.0", interpreting those as two integers rather than a float
if (((hasDot) && (!prevIsDot)) || (hasExp)) if (((hasDot) && (!prevIsDot)) || (hasExp))
{ {
// Switch to floating point mode // Switch to floating point mode
//double dVal = val; //double dVal = val;
//double dValScale = 0.1; //double dValScale = 0.1;
//if (hasExp) //if (hasExp)
//dVal *= pow(10, expVal); //dVal *= pow(10, expVal);
while (true) while (true)
@ -2796,7 +2789,7 @@ void BfParser::NextToken(int endIdx, bool outerIsInterpolate, bool disablePrepro
if (endNumber) if (endNumber)
{ {
mTokenEnd = mSrcIdx - 1; mTokenEnd = mSrcIdx - 1;
mSrcIdx--; mSrcIdx--;
if ((numberBase == 0x10) && if ((numberBase == 0x10) &&
((hexDigits >= 16) || ((hadSeps) && (hexDigits > 8)) || ((hadLeadingHexSep) && (hexDigits == 8)))) ((hexDigits >= 16) || ((hadSeps) && (hexDigits > 8)) || ((hadLeadingHexSep) && (hexDigits == 8))))
@ -2815,7 +2808,7 @@ void BfParser::NextToken(int endIdx, bool outerIsInterpolate, bool disablePrepro
mLiteral.mTypeCode = BfTypeCode_IntUnknown; mLiteral.mTypeCode = BfTypeCode_IntUnknown;
if ((numberBase == 0x10) && (hexDigits == 7)) if ((numberBase == 0x10) && (hexDigits == 7))
mLiteral.mWarnType = BfWarning_BF4201_Only7Hex; mLiteral.mWarnType = BfWarning_BF4201_Only7Hex;
if ((numberBase == 0x10) && (hexDigits == 9)) if ((numberBase == 0x10) && (hexDigits == 9))
mLiteral.mWarnType = BfWarning_BF4202_TooManyHexForInt; mLiteral.mWarnType = BfWarning_BF4202_TooManyHexForInt;
@ -2830,9 +2823,9 @@ void BfParser::NextToken(int endIdx, bool outerIsInterpolate, bool disablePrepro
mLiteral.mTypeCode = BfTypeCode_UInt64; mLiteral.mTypeCode = BfTypeCode_UInt64;
} }
else if (val > 0xFFFFFFFFLL) else if (val > 0xFFFFFFFFLL)
{ {
mLiteral.mTypeCode = BfTypeCode_Int64; mLiteral.mTypeCode = BfTypeCode_Int64;
} }
} }
mSyntaxToken = BfSyntaxToken_Literal; mSyntaxToken = BfSyntaxToken_Literal;
@ -2859,9 +2852,9 @@ void BfParser::NextToken(int endIdx, bool outerIsInterpolate, bool disablePrepro
val *= numberBase; val *= numberBase;
val += c - 'a' + 0xa; val += c - 'a' + 0xa;
} }
else if ((c == 'u') || (c == 'U')) else if ((c == 'u') || (c == 'U'))
{ {
if ((mSrc[mSrcIdx] == 'l') || (mSrc[mSrcIdx] == 'L')) if ((mSrc[mSrcIdx] == 'l') || (mSrc[mSrcIdx] == 'L'))
{ {
if (mSrc[mSrcIdx] == 'l') if (mSrc[mSrcIdx] == 'l')
@ -2888,7 +2881,7 @@ void BfParser::NextToken(int endIdx, bool outerIsInterpolate, bool disablePrepro
else if ((c == 'l') || (c == 'L')) else if ((c == 'l') || (c == 'L'))
{ {
if (c == 'l') if (c == 'l')
TokenFail("Uppercase 'L' required for int64"); TokenFail("Uppercase 'L' required for int64");
if ((mSrc[mSrcIdx] == 'u') || (mSrc[mSrcIdx] == 'U')) if ((mSrc[mSrcIdx] == 'u') || (mSrc[mSrcIdx] == 'U'))
{ {
mSrcIdx++; mSrcIdx++;
@ -2901,12 +2894,12 @@ void BfParser::NextToken(int endIdx, bool outerIsInterpolate, bool disablePrepro
mPassInstance->FailAt("Value doesn't fit into uint64", mSourceData, mTokenStart, mSrcIdx - mTokenStart); mPassInstance->FailAt("Value doesn't fit into uint64", mSourceData, mTokenStart, mSrcIdx - mTokenStart);
mSyntaxToken = BfSyntaxToken_Literal; mSyntaxToken = BfSyntaxToken_Literal;
return; return;
} }
mTokenEnd = mSrcIdx; mTokenEnd = mSrcIdx;
mLiteral.mTypeCode = BfTypeCode_Int64; mLiteral.mTypeCode = BfTypeCode_Int64;
mLiteral.mInt64 = (int64)val; mLiteral.mInt64 = (int64)val;
if (val == 0x8000000000000000) if (val == 0x8000000000000000)
mLiteral.mTypeCode = BfTypeCode_UInt64; mLiteral.mTypeCode = BfTypeCode_UInt64;
else if (val >= 0x8000000000000000) else if (val >= 0x8000000000000000)
hadOverflow = true; hadOverflow = true;
if (numberBase == 0x10) if (numberBase == 0x10)
@ -2938,14 +2931,14 @@ void BfParser::NextToken(int endIdx, bool outerIsInterpolate, bool disablePrepro
else else
{ {
mTokenEnd = mSrcIdx - 1; mTokenEnd = mSrcIdx - 1;
mSrcIdx--; mSrcIdx--;
mLiteral.mUInt64 = val; mLiteral.mUInt64 = val;
mLiteral.mTypeCode = BfTypeCode_IntUnknown; mLiteral.mTypeCode = BfTypeCode_IntUnknown;
mSyntaxToken = BfSyntaxToken_Literal; mSyntaxToken = BfSyntaxToken_Literal;
TokenFail("Unexpected character while parsing number", 0); TokenFail("Unexpected character while parsing number", 0);
return; return;
} }
if ((uint64)prevVal > (uint64)val) if ((uint64)prevVal > (uint64)val)
hadOverflow = true; hadOverflow = true;
} }
@ -3188,7 +3181,7 @@ void BfParser::NextToken(int endIdx, bool outerIsInterpolate, bool disablePrepro
if (SrcPtrHasToken("new")) if (SrcPtrHasToken("new"))
mToken = BfToken_New; mToken = BfToken_New;
break; break;
case TOKEN_HASH('n', 'u', 'l', 'l'): case TOKEN_HASH('n', 'u', 'l', 'l'):
if (SrcPtrHasToken("null")) if (SrcPtrHasToken("null"))
mToken = BfToken_Null; mToken = BfToken_Null;
else if (SrcPtrHasToken("nullable")) else if (SrcPtrHasToken("nullable"))
@ -3213,7 +3206,7 @@ void BfParser::NextToken(int endIdx, bool outerIsInterpolate, bool disablePrepro
case TOKEN_HASH('p', 'a', 'r', 'a'): case TOKEN_HASH('p', 'a', 'r', 'a'):
if ((!mCompatMode) && (SrcPtrHasToken("params"))) if ((!mCompatMode) && (SrcPtrHasToken("params")))
mToken = BfToken_Params; mToken = BfToken_Params;
break; break;
case TOKEN_HASH('p', 'r', 'i', 'v'): case TOKEN_HASH('p', 'r', 'i', 'v'):
if (SrcPtrHasToken("private")) if (SrcPtrHasToken("private"))
mToken = BfToken_Private; mToken = BfToken_Private;
@ -3460,7 +3453,7 @@ void BfParser::NextToken(int endIdx, bool outerIsInterpolate, bool disablePrepro
{ {
if (interpolateSetting == 0) if (interpolateSetting == 0)
stringStart = mTokenStart; stringStart = mTokenStart;
interpolateSetting++; interpolateSetting++;
} }
} }
} }
@ -3476,7 +3469,7 @@ void BfParser::ParseBlock(BfBlock* astNode, int depth, bool isInterpolate)
bool isAsmBlock = false; bool isAsmBlock = false;
bool isTernary = false; bool isTernary = false;
SizedArray<BfAstNode*, 32> childArr; SizedArray<BfAstNode*, 32> childArr;
int parenDepth = 0; int parenDepth = 0;
@ -3491,7 +3484,7 @@ void BfParser::ParseBlock(BfBlock* astNode, int depth, bool isInterpolate)
} }
NextToken(-1, isInterpolate && (parenDepth == 0)); NextToken(-1, isInterpolate && (parenDepth == 0));
if (mPreprocessorIgnoredSectionNode != NULL) if (mPreprocessorIgnoredSectionNode != NULL)
{ {
if (mSyntaxToken != BfSyntaxToken_EOF) if (mSyntaxToken != BfSyntaxToken_EOF)
@ -3508,7 +3501,7 @@ void BfParser::ParseBlock(BfBlock* astNode, int depth, bool isInterpolate)
gParseMemberIdx++; gParseMemberIdx++;
int memberIdx = gParseMemberIdx; int memberIdx = gParseMemberIdx;
auto childNode = CreateNode(); auto childNode = CreateNode();
if (childNode == NULL) if (childNode == NULL)
break; break;
@ -3556,12 +3549,12 @@ void BfParser::ParseBlock(BfBlock* astNode, int depth, bool isInterpolate)
} }
mInAsmBlock = false; mInAsmBlock = false;
astNode->Add(newBlock); astNode->Add(newBlock);
childArr.push_back(newBlock); childArr.push_back(newBlock);
} }
else if (mToken == BfToken_RBrace) else if (mToken == BfToken_RBrace)
{ {
if (depth == 0) if (depth == 0)
Fail("Unexpected ending brace"); Fail("Unexpected ending brace");
break; break;
} }
else else
@ -3578,7 +3571,7 @@ void BfParser::ParseBlock(BfBlock* astNode, int depth, bool isInterpolate)
bool endNow = false; bool endNow = false;
if (mToken == BfToken_Colon) if (mToken == BfToken_Colon)
{ {
endNow = true; endNow = true;
if (!childArr.IsEmpty()) if (!childArr.IsEmpty())
{ {
@ -3599,7 +3592,7 @@ void BfParser::ParseBlock(BfBlock* astNode, int depth, bool isInterpolate)
if (mToken == BfToken_Comma) if (mToken == BfToken_Comma)
endNow = true; endNow = true;
if (endNow) if (endNow)
{ {
mSrcIdx = mTokenStart; mSrcIdx = mTokenStart;
@ -3607,7 +3600,7 @@ void BfParser::ParseBlock(BfBlock* astNode, int depth, bool isInterpolate)
} }
} }
astNode->Add(childNode); astNode->Add(childNode);
childArr.Add(childNode); childArr.Add(childNode);
if ((mSyntaxToken == BfSyntaxToken_Token) && (mToken == BfToken_RBrace)) if ((mSyntaxToken == BfSyntaxToken_Token) && (mToken == BfToken_RBrace))
@ -3667,7 +3660,7 @@ void BfParser::Parse(BfPassInstance* passInstance)
mSyntaxToken = BfSyntaxToken_None; mSyntaxToken = BfSyntaxToken_None;
mPassInstance = passInstance; mPassInstance = passInstance;
int startIdx = mSrcIdx; int startIdx = mSrcIdx;
if (mUsingCache) if (mUsingCache)
{ {
@ -3708,7 +3701,7 @@ void BfParser::Parse(BfPassInstance* passInstance)
if ((mPassInstance->HasMessages()) || (mParsingFailed)) if ((mPassInstance->HasMessages()) || (mParsingFailed))
{ {
mParserData->mFailed = true; // Don't reuse cache if there were errors or warnings mParserData->mFailed = true; // Don't reuse cache if there were errors or warnings
} }
mPassInstance = NULL; mPassInstance = NULL;
@ -3739,18 +3732,18 @@ void BfParser::Close()
} }
else else
{ {
// It's possible two of the same entries were being parsed at the same time on different threads. // It's possible two of the same entries were being parsed at the same time on different threads.
// Just let the loser be deleted in the dtor // Just let the loser be deleted in the dtor
BfLogSys(mSystem, "Duplicate parser %p not added to cache\n", this); BfLogSys(mSystem, "Duplicate parser %p not added to cache\n", this);
} }
} }
} }
void BfParser::HadSrcRealloc() void BfParser::HadSrcRealloc()
{ {
int jumpTableSize = ((mSrcAllocSize + 1) + PARSER_JUMPTABLE_DIVIDE - 1) / PARSER_JUMPTABLE_DIVIDE; int jumpTableSize = ((mSrcAllocSize + 1) + PARSER_JUMPTABLE_DIVIDE - 1) / PARSER_JUMPTABLE_DIVIDE;
if (jumpTableSize > mJumpTableSize) if (jumpTableSize > mJumpTableSize)
{ {
auto jumpTable = new BfLineStartEntry[jumpTableSize]; auto jumpTable = new BfLineStartEntry[jumpTableSize];
memset(jumpTable, 0, jumpTableSize * sizeof(BfLineStartEntry)); memset(jumpTable, 0, jumpTableSize * sizeof(BfLineStartEntry));
memcpy(jumpTable, mJumpTable, mJumpTableSize * sizeof(BfLineStartEntry)); memcpy(jumpTable, mJumpTable, mJumpTableSize * sizeof(BfLineStartEntry));
@ -3763,7 +3756,6 @@ void BfParser::HadSrcRealloc()
mParserData->mJumpTable = mJumpTable; mParserData->mJumpTable = mJumpTable;
mParserData->mJumpTableSize = mJumpTableSize; mParserData->mJumpTableSize = mJumpTableSize;
} }
} }
void BfParser::GenerateAutoCompleteFrom(int srcPosition) void BfParser::GenerateAutoCompleteFrom(int srcPosition)
@ -3782,7 +3774,7 @@ void BfParser::ReportMemory(MemReporter* memReporter)
// if (!mUsingCache) // if (!mUsingCache)
// memReporter->AddBumpAlloc("AstAlloc", *mAlloc); // memReporter->AddBumpAlloc("AstAlloc", *mAlloc);
// //
// memReporter->Add("JumpTable", mJumpTableSize * sizeof(BfLineStartEntry)); // memReporter->Add("JumpTable", mJumpTableSize * sizeof(BfLineStartEntry));
memReporter->Add(sizeof(BfParser)); memReporter->Add(sizeof(BfParser));
@ -3917,7 +3909,7 @@ BF_EXPORT void BF_CALLTYPE BfParser_SetNextRevision(BfParser* bfParser, BfParser
BF_EXPORT void BF_CALLTYPE BfParser_SetCursorIdx(BfParser* bfParser, int cursorIdx) BF_EXPORT void BF_CALLTYPE BfParser_SetCursorIdx(BfParser* bfParser, int cursorIdx)
{ {
bfParser->SetCursorIdx(cursorIdx); bfParser->SetCursorIdx(cursorIdx);
} }
BF_EXPORT void BF_CALLTYPE BfParser_SetIsClassifying(BfParser* bfParser) BF_EXPORT void BF_CALLTYPE BfParser_SetIsClassifying(BfParser* bfParser)
@ -3961,7 +3953,7 @@ BF_EXPORT bool BF_CALLTYPE BfParser_Reduce(BfParser* bfParser, BfPassInstance* b
BP_ZONE("BfParser_Reduce"); BP_ZONE("BfParser_Reduce");
if (bfParser->mUsingCache) if (bfParser->mUsingCache)
return true; // Already reduced return true; // Already reduced
bfParser->FinishSideNodes(); bfParser->FinishSideNodes();
int startFailIdx = bfPassInstance->mFailedIdx; int startFailIdx = bfPassInstance->mFailedIdx;
int startWarningCount = bfPassInstance->mWarningCount; int startWarningCount = bfPassInstance->mWarningCount;
@ -4013,7 +4005,7 @@ BF_EXPORT const char* BF_CALLTYPE BfParser_DocPrep(BfParser* bfParser)
bfPrinter.mCharMapping = &gCharMapping; bfPrinter.mCharMapping = &gCharMapping;
bfPrinter.mDocPrep = true; bfPrinter.mDocPrep = true;
bfPrinter.Visit(bfParser->mRootNode); bfPrinter.Visit(bfParser->mRootNode);
outString = bfPrinter.mOutString; outString = bfPrinter.mOutString;
return outString.c_str(); return outString.c_str();
} }
@ -4094,7 +4086,7 @@ BF_EXPORT BfResolvePassData* BF_CALLTYPE BfParser_CreateResolvePassData(BfParser
} }
BF_EXPORT bool BF_CALLTYPE BfParser_BuildDefs(BfParser* bfParser, BfPassInstance* bfPassInstance, BfResolvePassData* resolvePassData, bool fullRefresh) BF_EXPORT bool BF_CALLTYPE BfParser_BuildDefs(BfParser* bfParser, BfPassInstance* bfPassInstance, BfResolvePassData* resolvePassData, bool fullRefresh)
{ {
if (bfParser->mCursorIdx != -1) if (bfParser->mCursorIdx != -1)
resolvePassData->mHasCursorIdx = true; resolvePassData->mHasCursorIdx = true;
@ -4108,7 +4100,6 @@ BF_EXPORT bool BF_CALLTYPE BfParser_BuildDefs(BfParser* bfParser, BfPassInstance
BF_EXPORT void BF_CALLTYPE BfParser_RemoveDefs(BfParser* bfParser) BF_EXPORT void BF_CALLTYPE BfParser_RemoveDefs(BfParser* bfParser)
{ {
} }
BF_EXPORT void BF_CALLTYPE BfParser_ClassifySource(BfParser* bfParser, BfSourceClassifier::CharData* charData, bool preserveFlags) BF_EXPORT void BF_CALLTYPE BfParser_ClassifySource(BfParser* bfParser, BfSourceClassifier::CharData* charData, bool preserveFlags)
@ -4117,18 +4108,18 @@ BF_EXPORT void BF_CALLTYPE BfParser_ClassifySource(BfParser* bfParser, BfSourceC
bfParser->Close(); bfParser->Close();
BfSourceClassifier bfSourceClassifier(bfParser, charData); BfSourceClassifier bfSourceClassifier(bfParser, charData);
bfSourceClassifier.mPreserveFlags = preserveFlags; bfSourceClassifier.mPreserveFlags = preserveFlags;
bfSourceClassifier.Visit(bfParser->mRootNode); bfSourceClassifier.Visit(bfParser->mRootNode);
bfSourceClassifier.mIsSideChannel = false; //? false or true? bfSourceClassifier.mIsSideChannel = false; //? false or true?
bfSourceClassifier.Visit(bfParser->mErrorRootNode); bfSourceClassifier.Visit(bfParser->mErrorRootNode);
bfSourceClassifier.mIsSideChannel = true; bfSourceClassifier.mIsSideChannel = true;
bfSourceClassifier.Visit(bfParser->mSidechannelRootNode); bfSourceClassifier.Visit(bfParser->mSidechannelRootNode);
} }
BF_EXPORT void BF_CALLTYPE BfParser_CreateClassifier(BfParser* bfParser, BfPassInstance* bfPassInstance, BfResolvePassData* resolvePassData, BfSourceClassifier::CharData* charData) BF_EXPORT void BF_CALLTYPE BfParser_CreateClassifier(BfParser* bfParser, BfPassInstance* bfPassInstance, BfResolvePassData* resolvePassData, BfSourceClassifier::CharData* charData)
{ {
resolvePassData->mIsClassifying = true; resolvePassData->mIsClassifying = true;
bfParser->mSourceClassifier = new BfSourceClassifier(bfParser, charData); bfParser->mSourceClassifier = new BfSourceClassifier(bfParser, charData);
bfParser->mSourceClassifier->mClassifierPassId = bfPassInstance->mClassifierPassId; bfParser->mSourceClassifier->mClassifierPassId = bfPassInstance->mClassifierPassId;
if ((resolvePassData->mParsers.IsEmpty()) || (bfParser != resolvePassData->mParsers[0])) if ((resolvePassData->mParsers.IsEmpty()) || (bfParser != resolvePassData->mParsers[0]))
@ -4140,7 +4131,7 @@ BF_EXPORT void BF_CALLTYPE BfParser_CreateClassifier(BfParser* bfParser, BfPassI
bfParser->mSourceClassifier->mSkipMethodInternals = true; bfParser->mSourceClassifier->mSkipMethodInternals = true;
bfParser->mSourceClassifier->mSkipTypeDeclarations = true; bfParser->mSourceClassifier->mSkipTypeDeclarations = true;
if (charData != NULL) if (charData != NULL)
{ {
if ((doClassifyPass) && (bfParser->mRootNode != NULL)) if ((doClassifyPass) && (bfParser->mRootNode != NULL))
bfParser->mSourceClassifier->Visit(bfParser->mRootNode); bfParser->mSourceClassifier->Visit(bfParser->mRootNode);
} }
@ -4179,4 +4170,4 @@ BF_EXPORT void BF_CALLTYPE BfParser_GenerateAutoCompletionFrom(BfParser* bfParse
BF_EXPORT void BF_CALLTYPE BfParser_SetCompleteParse(BfParser* bfParser) BF_EXPORT void BF_CALLTYPE BfParser_SetCompleteParse(BfParser* bfParser)
{ {
bfParser->mCompleteParse = true; bfParser->mCompleteParse = true;
} }

View file

@ -20,15 +20,15 @@ enum BfSyntaxToken
{ {
BfSyntaxToken_None, BfSyntaxToken_None,
BfSyntaxToken_Token, BfSyntaxToken_Token,
BfSyntaxToken_Identifier, BfSyntaxToken_Identifier,
BfSyntaxToken_CharQuote, BfSyntaxToken_CharQuote,
BfSyntaxToken_StringQuote, BfSyntaxToken_StringQuote,
BfSyntaxToken_ForwardSlash, BfSyntaxToken_ForwardSlash,
BfSyntaxToken_Literal, BfSyntaxToken_Literal,
BfSyntaxToken_CommentLine, BfSyntaxToken_CommentLine,
BfSyntaxToken_CommentBlock, BfSyntaxToken_CommentBlock,
BfSyntaxToken_GeneratedNode, BfSyntaxToken_GeneratedNode,
BfSyntaxToken_FAILED, BfSyntaxToken_FAILED,
BfSyntaxToken_HIT_END_IDX, BfSyntaxToken_HIT_END_IDX,
BfSyntaxToken_EOF BfSyntaxToken_EOF
}; };
@ -59,12 +59,12 @@ enum MaybeBool
{ {
MaybeBool_None = -1, MaybeBool_None = -1,
MaybeBool_False = 0, MaybeBool_False = 0,
MaybeBool_True = 1, MaybeBool_True = 1,
}; };
class BfParserData : public BfSourceData class BfParserData : public BfSourceData
{ {
public: public:
uint64 mHash; uint64 mHash;
int mDataId; int mDataId;
int mRefCount; // -1 = not cached int mRefCount; // -1 = not cached
@ -82,7 +82,7 @@ public:
Dictionary<int, BfParserWarningEnabledChange> mWarningEnabledChanges; Dictionary<int, BfParserWarningEnabledChange> mWarningEnabledChanges;
std::set<int> mUnwarns; std::set<int> mUnwarns;
bool mFailed; // Don't cache if there's a warning or an error bool mFailed; // Don't cache if there's a warning or an error
bool mDidReduce; bool mDidReduce;
public: public:
BfParserData(); BfParserData();
@ -95,11 +95,11 @@ public:
} }
virtual BfParser* ToParser() override; virtual BfParser* ToParser() override;
int GetCharIdAtIndex(int findIndex); int GetCharIdAtIndex(int findIndex);
void GetLineCharAtIdx(int idx, int& line, int& lineChar); void GetLineCharAtIdx(int idx, int& line, int& lineChar);
bool IsUnwarnedAt(BfAstNode* node); bool IsUnwarnedAt(BfAstNode* node);
bool IsWarningEnabledAtSrcIndex(int warningNumber, int srcIdx); bool IsWarningEnabledAtSrcIndex(int warningNumber, int srcIdx);
void ReportMemory(MemReporter* memReporter); void ReportMemory(MemReporter* memReporter);
}; };
class BfParserCache class BfParserCache
@ -115,7 +115,7 @@ public:
}; };
struct DataEntry struct DataEntry
{ {
BfParserData* mParserData; BfParserData* mParserData;
bool operator==(const LookupEntry& lookup) const; bool operator==(const LookupEntry& lookup) const;
@ -123,7 +123,7 @@ public:
{ {
return lookup.mParserData == mParserData; return lookup.mParserData == mParserData;
} }
}; };
public: public:
CritSect mCritSect; CritSect mCritSect;
@ -131,7 +131,7 @@ public:
BfAstAllocManager mAstAllocManager; BfAstAllocManager mAstAllocManager;
HashSet<DataEntry> mEntries; HashSet<DataEntry> mEntries;
public: public:
BfParserCache(); BfParserCache();
~BfParserCache(); ~BfParserCache();
void ReportMemory(MemReporter* memReporter); void ReportMemory(MemReporter* memReporter);
@ -153,30 +153,30 @@ enum BfSourceEmbedKind : int8
class BfParser : public BfSource class BfParser : public BfSource
{ {
public: public:
BfParserData* mParserData; BfParserData* mParserData;
bool mUsingCache; bool mUsingCache;
BfPassInstance* mPassInstance; BfPassInstance* mPassInstance;
BfSourceClassifier* mSourceClassifier; BfSourceClassifier* mSourceClassifier;
String mFileName; String mFileName;
int mTextVersion; int mTextVersion;
BfSourceEmbedKind mEmbedKind; BfSourceEmbedKind mEmbedKind;
bool mAwaitingDelete; bool mAwaitingDelete;
bool mCompatMode; // Does C++ compatible parsing bool mCompatMode; // Does C++ compatible parsing
bool mQuickCompatMode; bool mQuickCompatMode;
bool mScanOnly; bool mScanOnly;
bool mCompleteParse; bool mCompleteParse;
bool mIsEmitted; bool mIsEmitted;
BfLineStartEntry* mJumpTable; BfLineStartEntry* mJumpTable;
int mJumpTableSize; int mJumpTableSize;
int mOrigSrcLength; int mOrigSrcLength;
int mDataId; int mDataId;
int mSrcIdx; int mSrcIdx;
int mLineStart; int mLineStart;
int mLineNum; int mLineNum;
bool mInAsmBlock; bool mInAsmBlock;
BfParserFlag mParserFlags; BfParserFlag mParserFlags;
@ -186,43 +186,43 @@ public:
BfSyntaxToken mSyntaxToken; BfSyntaxToken mSyntaxToken;
int mTriviaStart; // mTriviaStart < mTokenStart when there's leading whitespace int mTriviaStart; // mTriviaStart < mTokenStart when there's leading whitespace
int mTokenStart; int mTokenStart;
int mTokenEnd; int mTokenEnd;
BfAstNode* mGeneratedNode; BfAstNode* mGeneratedNode;
BfVariant mLiteral; BfVariant mLiteral;
BfToken mToken; BfToken mToken;
BfPreprocesorIgnoredSectionNode* mPreprocessorIgnoredSectionNode; BfPreprocesorIgnoredSectionNode* mPreprocessorIgnoredSectionNode;
int mPreprocessorIgnoreDepth; int mPreprocessorIgnoreDepth;
Array< std::pair<BfAstNode*, bool> > mPreprocessorNodeStack; Array< std::pair<BfAstNode*, bool> > mPreprocessorNodeStack;
Dictionary<String, BfDefineState> mPreprocessorDefines; Dictionary<String, BfDefineState> mPreprocessorDefines;
std::set<int> mPreprocessorIgnoredSectionStarts; std::set<int> mPreprocessorIgnoredSectionStarts;
public: public:
virtual void HandleInclude(BfAstNode* paramNode); virtual void HandleInclude(BfAstNode* paramNode);
virtual void HandleIncludeNext(BfAstNode* paramNode); virtual void HandleIncludeNext(BfAstNode* paramNode);
virtual void HandlePragma(const StringImpl& pragma, BfBlock* block); virtual void HandlePragma(const StringImpl& pragma, BfBlock* block);
virtual void HandleDefine(const StringImpl& name, BfAstNode* paramNode); virtual void HandleDefine(const StringImpl& name, BfAstNode* paramNode);
virtual void HandleUndefine(const StringImpl& name); virtual void HandleUndefine(const StringImpl& name);
virtual MaybeBool HandleIfDef(const StringImpl& name); virtual MaybeBool HandleIfDef(const StringImpl& name);
virtual MaybeBool HandleProcessorCondition(BfBlock* paramNode); virtual MaybeBool HandleProcessorCondition(BfBlock* paramNode);
public: public:
void Init(uint64 cacheHash = 0); void Init(uint64 cacheHash = 0);
void NewLine(); void NewLine();
BfExpression* CreateInlineExpressionFromNode(BfBlock* block); BfExpression* CreateInlineExpressionFromNode(BfBlock* block);
bool EvaluatePreprocessor(BfExpression* expr); bool EvaluatePreprocessor(BfExpression* expr);
BfBlock* ParseInlineBlock(int spaceIdx, int endIdx); BfBlock* ParseInlineBlock(int spaceIdx, int endIdx);
bool HandlePreprocessor(); bool HandlePreprocessor();
bool IsUnwarnedAt(BfAstNode* node); bool IsUnwarnedAt(BfAstNode* node);
bool SrcPtrHasToken(const char* name); bool SrcPtrHasToken(const char* name);
uint32 GetTokenHash(); uint32 GetTokenHash();
void ParseBlock(BfBlock* astNode, int depth, bool isInterpolate = false); void ParseBlock(BfBlock* astNode, int depth, bool isInterpolate = false);
double ParseLiteralDouble(); double ParseLiteralDouble();
void AddErrorNode(int startIdx, int endIdx); void AddErrorNode(int startIdx, int endIdx);
BfCommentKind GetCommentKind(int startIdx); BfCommentKind GetCommentKind(int startIdx);
public: public:
BfParser(BfSystem* bfSystem, BfProject* bfProject = NULL); BfParser(BfSystem* bfSystem, BfProject* bfProject = NULL);
~BfParser(); ~BfParser();
@ -232,23 +232,23 @@ public:
void GetLineCharAtIdx(int idx, int& line, int& lineChar); void GetLineCharAtIdx(int idx, int& line, int& lineChar);
void Fail(const StringImpl& error, int offset = -1); void Fail(const StringImpl& error, int offset = -1);
void TokenFail(const StringImpl& error, int offset = -1); void TokenFail(const StringImpl& error, int offset = -1);
void SetSource(const char* data, int length); void SetSource(const char* data, int length);
void MoveSource(const char* data, int length); // Takes ownership of data ptr void MoveSource(const char* data, int length); // Takes ownership of data ptr
void RefSource(const char* data, int length); void RefSource(const char* data, int length);
void MakeNegative(uint64& val, bool& hadOverflow); void MakeNegative(uint64& val, bool& hadOverflow);
void NextToken(int endIdx = -1, bool outerIsInterpolate = false, bool disablePreprocessor = false); void NextToken(int endIdx = -1, bool outerIsInterpolate = false, bool disablePreprocessor = false);
BfAstNode* CreateNode(); BfAstNode* CreateNode();
void Parse(BfPassInstance* passInstance); void Parse(BfPassInstance* passInstance);
int GetCharIdAtIndex(int findIndex); int GetCharIdAtIndex(int findIndex);
virtual void Close() override; virtual void Close() override;
virtual void HadSrcRealloc() override; virtual void HadSrcRealloc() override;
void GenerateAutoCompleteFrom(int srcPosition); void GenerateAutoCompleteFrom(int srcPosition);
void ReportMemory(MemReporter* memReporter); void ReportMemory(MemReporter* memReporter);
void GetSrcPosition(int idx, int& lineNum, int& column); void GetSrcPosition(int idx, int& lineNum, int& column);
}; };

File diff suppressed because it is too large Load diff

View file

@ -5,7 +5,6 @@
NS_BF_BEGIN NS_BF_BEGIN
class BfPrinter : public BfElementVisitor class BfPrinter : public BfElementVisitor
{ {
public: public:
@ -26,10 +25,10 @@ public:
struct StateModify struct StateModify
{ {
public: public:
bool mExpectingSpace; bool mExpectingSpace;
int mWantNewLineIdx; int mWantNewLineIdx;
bool mDoingBlockOpen; bool mDoingBlockOpen;
bool mDoingBlockClose; bool mDoingBlockClose;
int mWantVirtualIndent; int mWantVirtualIndent;
BfAstNode* mQueuedNode; BfAstNode* mQueuedNode;
@ -43,18 +42,18 @@ public:
void Clear() void Clear()
{ {
mExpectingSpace = false; mExpectingSpace = false;
mDoingBlockOpen = false; mDoingBlockOpen = false;
mDoingBlockClose = false; mDoingBlockClose = false;
mQueuedNode = NULL; mQueuedNode = NULL;
} }
}; };
BfSourceData* mSource; BfSourceData* mSource;
BfParserData* mParser; BfParserData* mParser;
BfBlock::Iterator mSidechannelItr; BfBlock::Iterator mSidechannelItr;
BfAstNode* mSidechannelNextNode; BfAstNode* mSidechannelNextNode;
BfBlock::Iterator mErrorItr; BfBlock::Iterator mErrorItr;
BfAstNode* mErrorNextNode; BfAstNode* mErrorNextNode;
@ -65,18 +64,18 @@ public:
int mCurSrcIdx; int mCurSrcIdx;
Array<StateModify> mChildNodeQueue; Array<StateModify> mChildNodeQueue;
int mFormatStart; int mFormatStart;
int mFormatEnd; int mFormatEnd;
int mFormatDisableCount; int mFormatDisableCount;
StateModify mNextStateModify; StateModify mNextStateModify;
String mOutString; String mOutString;
bool mReformatting; bool mReformatting;
bool mIgnoreTrivia; bool mIgnoreTrivia;
bool mDocPrep; bool mDocPrep;
BlockState* mCurBlockState; BlockState* mCurBlockState;
int mCurIndentLevel; int mCurIndentLevel;
int mQueuedSpaceCount; int mQueuedSpaceCount;
int mLastSpaceOffset; // Indent difference from original to new int mLastSpaceOffset; // Indent difference from original to new
bool mExpectingNewLine; bool mExpectingNewLine;
int mCurCol; int mCurCol;
int mMaxCol; int mMaxCol;
@ -86,19 +85,19 @@ public:
bool mIsFirstStatementInBlock; bool mIsFirstStatementInBlock;
bool mForceUseTrivia; bool mForceUseTrivia;
bool mInSideChannel; bool mInSideChannel;
int mStateModifyVirtualIndentLevel; int mStateModifyVirtualIndentLevel;
int mVirtualIndentLevel; int mVirtualIndentLevel;
int mVirtualNewLineIdx; int mVirtualNewLineIdx;
Array<int>* mCharMapping; Array<int>* mCharMapping;
int mHighestCharId; int mHighestCharId;
public: public:
BfPrinter(BfRootNode* rootNode, BfRootNode* sidechannelRootNode, BfRootNode* errorRootNode); BfPrinter(BfRootNode* rootNode, BfRootNode* sidechannelRootNode, BfRootNode* errorRootNode);
public: public:
void Update(BfAstNode* bfAstNode); void Update(BfAstNode* bfAstNode);
bool CheckReplace(BfAstNode* astNode); bool CheckReplace(BfAstNode* astNode);
void FlushIndent(); void FlushIndent();
@ -106,7 +105,7 @@ public:
void Write(BfAstNode* node, int start, int len); void Write(BfAstNode* node, int start, int len);
void WriteSourceString(BfAstNode* node); void WriteSourceString(BfAstNode* node);
void QueueVisitChild(BfAstNode* astNode); void QueueVisitChild(BfAstNode* astNode);
void QueueVisitErrorNodes(BfRootNode* astNode); void QueueVisitErrorNodes(BfRootNode* astNode);
void FlushVisitChild(); void FlushVisitChild();
void VisitChildWithPrecedingSpace(BfAstNode* bfAstNode); void VisitChildWithPrecedingSpace(BfAstNode* bfAstNode);
void VisitChildWithProceedingSpace(BfAstNode* bfAstNode); void VisitChildWithProceedingSpace(BfAstNode* bfAstNode);
@ -117,9 +116,9 @@ public:
void VisitChildNextLine(BfAstNode* node); void VisitChildNextLine(BfAstNode* node);
void DoBlockOpen(BfAstNode* prevNode, BfTokenNode* blockOpen, BfTokenNode* blockClose, bool queue, BlockState& blockState); void DoBlockOpen(BfAstNode* prevNode, BfTokenNode* blockOpen, BfTokenNode* blockClose, bool queue, BlockState& blockState);
void DoBlockClose(BfAstNode* prevNode, BfTokenNode* blockOpen, BfTokenNode* blockClose, bool queue, BlockState& blockState); void DoBlockClose(BfAstNode* prevNode, BfTokenNode* blockOpen, BfTokenNode* blockClose, bool queue, BlockState& blockState);
void QueueMethodDeclaration(BfMethodDeclaration* methodDeclaration); void QueueMethodDeclaration(BfMethodDeclaration* methodDeclaration);
int CalcOrigLineSpacing(BfAstNode* bfAstNode, int* lineStartIdx); int CalcOrigLineSpacing(BfAstNode* bfAstNode, int* lineStartIdx);
void WriteIgnoredNode(BfAstNode* node); void WriteIgnoredNode(BfAstNode* node);
void CheckRawNode(BfAstNode* node); void CheckRawNode(BfAstNode* node);
virtual void Visit(BfAstNode* bfAstNode) override; virtual void Visit(BfAstNode* bfAstNode) override;
@ -130,20 +129,20 @@ public:
virtual void Visit(BfExpressionStatement* exprStmt) override; virtual void Visit(BfExpressionStatement* exprStmt) override;
virtual void Visit(BfNamedExpression* namedExpr) override; virtual void Visit(BfNamedExpression* namedExpr) override;
virtual void Visit(BfAttributedExpression* attribExpr) override; virtual void Visit(BfAttributedExpression* attribExpr) override;
virtual void Visit(BfStatement* stmt) override; virtual void Visit(BfStatement* stmt) override;
virtual void Visit(BfLabelableStatement* labelableStmt) override; virtual void Visit(BfLabelableStatement* labelableStmt) override;
virtual void Visit(BfCommentNode* commentNode) override; virtual void Visit(BfCommentNode* commentNode) override;
virtual void Visit(BfPreprocesorIgnoredSectionNode* preprocesorIgnoredSection) override; virtual void Visit(BfPreprocesorIgnoredSectionNode* preprocesorIgnoredSection) override;
virtual void Visit(BfPreprocessorNode* preprocessorNode) override; virtual void Visit(BfPreprocessorNode* preprocessorNode) override;
virtual void Visit(BfAttributeDirective* attributeDirective) override; virtual void Visit(BfAttributeDirective* attributeDirective) override;
virtual void Visit(BfGenericParamsDeclaration* genericParams) override; virtual void Visit(BfGenericParamsDeclaration* genericParams) override;
virtual void Visit(BfGenericOperatorConstraint* genericConstraints) override; virtual void Visit(BfGenericOperatorConstraint* genericConstraints) override;
virtual void Visit(BfGenericConstraintsDeclaration* genericConstraints) override; virtual void Visit(BfGenericConstraintsDeclaration* genericConstraints) override;
virtual void Visit(BfGenericArgumentsNode* genericArgumentsNode) override; virtual void Visit(BfGenericArgumentsNode* genericArgumentsNode) override;
virtual void Visit(BfEmptyStatement* emptyStmt) override; virtual void Visit(BfEmptyStatement* emptyStmt) override;
virtual void Visit(BfTokenNode* tokenNode) override; virtual void Visit(BfTokenNode* tokenNode) override;
virtual void Visit(BfTokenPairNode* tokenPairNode) override; virtual void Visit(BfTokenPairNode* tokenPairNode) override;
virtual void Visit(BfUsingSpecifierNode* usingSpecifier) override; virtual void Visit(BfUsingSpecifierNode* usingSpecifier) override;
@ -156,7 +155,7 @@ public:
virtual void Visit(BfMixinExpression* mixinExpr) override; virtual void Visit(BfMixinExpression* mixinExpr) override;
virtual void Visit(BfSizedArrayCreateExpression* createExpr) override; virtual void Visit(BfSizedArrayCreateExpression* createExpr) override;
virtual void Visit(BfInitializerExpression* initExpr) override; virtual void Visit(BfInitializerExpression* initExpr) override;
virtual void Visit(BfCollectionInitializerExpression* initExpr) override; virtual void Visit(BfCollectionInitializerExpression* initExpr) override;
virtual void Visit(BfTypeReference* typeRef) override; virtual void Visit(BfTypeReference* typeRef) override;
virtual void Visit(BfNamedTypeReference* typeRef) override; virtual void Visit(BfNamedTypeReference* typeRef) override;
virtual void Visit(BfQualifiedTypeReference* qualifiedType) override; virtual void Visit(BfQualifiedTypeReference* qualifiedType) override;
@ -172,7 +171,7 @@ public:
virtual void Visit(BfPointerTypeRef* typeRef) override; virtual void Visit(BfPointerTypeRef* typeRef) override;
virtual void Visit(BfNullableTypeRef* typeRef) override; virtual void Visit(BfNullableTypeRef* typeRef) override;
virtual void Visit(BfVariableDeclaration* varDecl) override; virtual void Visit(BfVariableDeclaration* varDecl) override;
virtual void Visit(BfParameterDeclaration* paramDecl) override; virtual void Visit(BfParameterDeclaration* paramDecl) override;
virtual void Visit(BfTypeOfExpression* typeOfExpr) override; virtual void Visit(BfTypeOfExpression* typeOfExpr) override;
virtual void Visit(BfSizeOfExpression* sizeOfExpr) override; virtual void Visit(BfSizeOfExpression* sizeOfExpr) override;
virtual void Visit(BfOffsetOfExpression* offsetOfExpr) override; virtual void Visit(BfOffsetOfExpression* offsetOfExpr) override;
@ -181,11 +180,11 @@ public:
virtual void Visit(BfCheckTypeExpression* checkTypeExpr) override; virtual void Visit(BfCheckTypeExpression* checkTypeExpr) override;
virtual void Visit(BfDynamicCastExpression* dynCastExpr) override; virtual void Visit(BfDynamicCastExpression* dynCastExpr) override;
virtual void Visit(BfCastExpression* castExpr) override; virtual void Visit(BfCastExpression* castExpr) override;
virtual void Visit(BfDelegateBindExpression* invocationExpr) override; virtual void Visit(BfDelegateBindExpression* invocationExpr) override;
virtual void Visit(BfLambdaBindExpression* lambdaBindExpr) override; virtual void Visit(BfLambdaBindExpression* lambdaBindExpr) override;
virtual void Visit(BfObjectCreateExpression* invocationExpr) override; virtual void Visit(BfObjectCreateExpression* invocationExpr) override;
virtual void Visit(BfBoxExpression* boxExpr) override; virtual void Visit(BfBoxExpression* boxExpr) override;
virtual void Visit(BfInvocationExpression* invocationExpr) override; virtual void Visit(BfInvocationExpression* invocationExpr) override;
virtual void Visit(BfSwitchCase* switchCase) override; virtual void Visit(BfSwitchCase* switchCase) override;
virtual void Visit(BfWhenExpression* whenExpr) override; virtual void Visit(BfWhenExpression* whenExpr) override;
virtual void Visit(BfSwitchStatement* switchStmt) override; virtual void Visit(BfSwitchStatement* switchStmt) override;

View file

@ -149,7 +149,7 @@ void BfReducer::ReplaceNode(BfAstNode* prevNode, BfAstNode* newNode)
if (!newNode->IsInitialized()) if (!newNode->IsInitialized())
{ {
#ifdef BF_AST_COMPACT #ifdef BF_AST_COMPACT
if (prevNode->mIsCompact) if (prevNode->mIsCompact)
{ {
newNode->mIsCompact = prevNode->mIsCompact; newNode->mIsCompact = prevNode->mIsCompact;
@ -224,9 +224,8 @@ void BfReducer::AddErrorNode(BfAstNode* astNode, bool removeNode)
astNode->RemoveSelf(); astNode->RemoveSelf();
} }
bool BfReducer::IsTypeReference(BfAstNode* checkNode, BfToken successToken, int endNode, int* retryNode, int* outEndNode, bool* couldBeExpr, bool* isGenericType, bool* isTuple) bool BfReducer::IsTypeReference(BfAstNode* checkNode, BfToken successToken, int endNode, int* retryNode, int* outEndNode, bool* couldBeExpr, bool* isGenericType, bool* isTuple)
{ {
AssertCurrentNode(checkNode); AssertCurrentNode(checkNode);
if (couldBeExpr != NULL) if (couldBeExpr != NULL)
@ -418,7 +417,7 @@ bool BfReducer::IsTypeReference(BfAstNode* checkNode, BfToken successToken, int
bool hadTupleComma = false; bool hadTupleComma = false;
bool hadIdentifier = false; bool hadIdentifier = false;
bool foundSuccessToken = false; bool foundSuccessToken = false;
bool hadUnexpectedIdentifier = false; bool hadUnexpectedIdentifier = false;
BfTokenNode* lastToken = NULL; BfTokenNode* lastToken = NULL;
SizedArray<BfToken, 8> tokenStack; SizedArray<BfToken, 8> tokenStack;
@ -459,7 +458,7 @@ bool BfReducer::IsTypeReference(BfAstNode* checkNode, BfToken successToken, int
if ((doEnding) && (tokenStack.size() == 1)) if ((doEnding) && (tokenStack.size() == 1))
doEnding = checkToken == tokenStack.back(); doEnding = checkToken == tokenStack.back();
if (doEnding) if (doEnding)
{ {
bool success = false; bool success = false;
if ((lastToken != NULL) && ((lastToken->GetToken() == BfToken_RChevron) || (lastToken->GetToken() == BfToken_RDblChevron))) if ((lastToken != NULL) && ((lastToken->GetToken() == BfToken_RChevron) || (lastToken->GetToken() == BfToken_RDblChevron)))
@ -469,7 +468,7 @@ bool BfReducer::IsTypeReference(BfAstNode* checkNode, BfToken successToken, int
} }
if (successToken == BfToken_RParen) if (successToken == BfToken_RParen)
{ {
success = (chevronDepth == 0) && (bracketDepth == 0) && (parenDepth == 1); success = (chevronDepth == 0) && (bracketDepth == 0) && (parenDepth == 1);
if (success) if (success)
@ -477,7 +476,7 @@ bool BfReducer::IsTypeReference(BfAstNode* checkNode, BfToken successToken, int
// Check identifierExpected - this catches (.) casts // Check identifierExpected - this catches (.) casts
if ((identifierExpected) && (couldBeExpr != NULL)) if ((identifierExpected) && (couldBeExpr != NULL))
*couldBeExpr = false; *couldBeExpr = false;
} }
} }
else if ((successToken == BfToken_Comma) || else if ((successToken == BfToken_Comma) ||
(successToken == BfToken_LBracket)) (successToken == BfToken_LBracket))
@ -575,7 +574,6 @@ bool BfReducer::IsTypeReference(BfAstNode* checkNode, BfToken successToken, int
return false; return false;
} }
} }
} }
else if ((checkToken == BfToken_Const) && (chevronDepth > 0)) else if ((checkToken == BfToken_Const) && (chevronDepth > 0))
{ {
@ -631,9 +629,9 @@ bool BfReducer::IsTypeReference(BfAstNode* checkNode, BfToken successToken, int
if (tokenStack.IsEmpty()) if (tokenStack.IsEmpty())
break; break;
for (int i = 0; i < ((checkToken == BfToken_RDblChevron) ? 2 : 1); i++) for (int i = 0; i < ((checkToken == BfToken_RDblChevron) ? 2 : 1); i++)
{ {
if (tokenStack.back() != BfToken_RChevron) if (tokenStack.back() != BfToken_RChevron)
{ {
if (outEndNode != NULL) if (outEndNode != NULL)
@ -900,7 +898,7 @@ bool BfReducer::IsTypeReference(BfAstNode* checkNode, BfToken successToken, int
else if ((checkToken == BfToken_DotDotDot) && (chevronDepth > 0)) else if ((checkToken == BfToken_DotDotDot) && (chevronDepth > 0))
{ {
isDone = true; isDone = true;
auto nextNode = mVisitorPos.Get(checkIdx + 1); auto nextNode = mVisitorPos.Get(checkIdx + 1);
if (auto nextToken = BfNodeDynCast<BfTokenNode>(nextNode)) if (auto nextToken = BfNodeDynCast<BfTokenNode>(nextNode))
{ {
@ -910,7 +908,6 @@ bool BfReducer::IsTypeReference(BfAstNode* checkNode, BfToken successToken, int
} }
else if (checkToken != BfToken_LBracket) else if (checkToken != BfToken_LBracket)
isDone = true; isDone = true;
if (isDone) if (isDone)
{ {
@ -961,7 +958,7 @@ bool BfReducer::IsTypeReference(BfAstNode* checkNode, BfToken successToken, int
{ {
// Allow // Allow
identifierExpected = false; identifierExpected = false;
} }
else else
{ {
bool mayBeExprPart = false; bool mayBeExprPart = false;
@ -1000,7 +997,7 @@ bool BfReducer::IsTypeReference(BfAstNode* checkNode, BfToken successToken, int
int retryNode = -1; int retryNode = -1;
if (IsTypeReference(checkNode, successToken, endNode, &retryNode, outEndNode, couldBeExpr, isGenericType, isTuple)) if (IsTypeReference(checkNode, successToken, endNode, &retryNode, outEndNode, couldBeExpr, isGenericType, isTuple))
return true; return true;
if ((retryNode != -1) && (successToken == BfToken_None)) if ((retryNode != -1) && (successToken == BfToken_None))
{ {
int newEndNode = -1; int newEndNode = -1;
@ -1063,7 +1060,6 @@ bool BfReducer::IsLocalMethod(BfAstNode* nameNode)
} }
else else
{ {
} }
checkIdx++; checkIdx++;
@ -1585,7 +1581,7 @@ BfExpression* BfReducer::CreateExpression(BfAstNode* node, CreateExprFlags creat
//if (!couldBeExpr) //if (!couldBeExpr)
{ {
auto endingTokenNode = BfNodeDynCast<BfTokenNode>(mVisitorPos.Get(outEndNode - 1)); auto endingTokenNode = BfNodeDynCast<BfTokenNode>(mVisitorPos.Get(outEndNode - 1));
// If the type ends with a * or a ? then it could be an expression // If the type ends with a * or a ? then it could be an expression
if (endingTokenNode == NULL) if (endingTokenNode == NULL)
{ {
isLocalVariable = true; isLocalVariable = true;
@ -1823,7 +1819,6 @@ BfExpression* BfReducer::CreateExpression(BfAstNode* node, CreateExprFlags creat
bool isLambdaBind = false; bool isLambdaBind = false;
bool isBoxing = false; bool isBoxing = false;
auto nextNode = mVisitorPos.GetNext(); auto nextNode = mVisitorPos.GetNext();
if (auto nextTokenNode = BfNodeDynCast<BfTokenNode>(nextNode)) if (auto nextTokenNode = BfNodeDynCast<BfTokenNode>(nextNode))
{ {
@ -1845,7 +1840,7 @@ BfExpression* BfReducer::CreateExpression(BfAstNode* node, CreateExprFlags creat
mVisitorPos.mReadPos--; mVisitorPos.mReadPos--;
} }
} }
if (auto interpExpr = BfNodeDynCastExact<BfStringInterpolationExpression>(nextNode)) if (auto interpExpr = BfNodeDynCastExact<BfStringInterpolationExpression>(nextNode))
{ {
mVisitorPos.MoveNext(); mVisitorPos.MoveNext();
@ -1854,8 +1849,8 @@ BfExpression* BfReducer::CreateExpression(BfAstNode* node, CreateExprFlags creat
interpExpr->mAllocNode = allocNode; interpExpr->mAllocNode = allocNode;
interpExpr->mTriviaStart = allocNode->mTriviaStart; interpExpr->mTriviaStart = allocNode->mTriviaStart;
interpExpr->mSrcStart = allocNode->mSrcStart; interpExpr->mSrcStart = allocNode->mSrcStart;
exprLeft = interpExpr; exprLeft = interpExpr;
} }
else if (isBoxing) else if (isBoxing)
@ -2000,7 +1995,7 @@ BfExpression* BfReducer::CreateExpression(BfAstNode* node, CreateExprFlags creat
auto expr = CreateExpressionAfter(isConstExpr); auto expr = CreateExpressionAfter(isConstExpr);
MEMBER_SET_CHECKED(isConstExpr, mExpression, expr); MEMBER_SET_CHECKED(isConstExpr, mExpression, expr);
tokenNode = ExpectTokenAfter(isConstExpr, BfToken_RParen); tokenNode = ExpectTokenAfter(isConstExpr, BfToken_RParen);
MEMBER_SET_CHECKED(isConstExpr, mCloseParen, tokenNode); MEMBER_SET_CHECKED(isConstExpr, mCloseParen, tokenNode);
exprLeft = isConstExpr; exprLeft = isConstExpr;
} }
else if (token == BfToken_Question) else if (token == BfToken_Question)
@ -2171,9 +2166,9 @@ BfExpression* BfReducer::CreateExpression(BfAstNode* node, CreateExprFlags creat
couldBeExpr = false; couldBeExpr = false;
isTuple = false; isTuple = false;
if ((createExprFlags & CreateExprFlags_NoCast) == 0) if ((createExprFlags & CreateExprFlags_NoCast) == 0)
isCastExpr = IsTypeReference(node, BfToken_RParen, -1, &endNodeIdx, &couldBeExpr, NULL, &isTuple); isCastExpr = IsTypeReference(node, BfToken_RParen, -1, &endNodeIdx, &couldBeExpr, NULL, &isTuple);
if (endNodeIdx != -1) if (endNodeIdx != -1)
endNode = mVisitorPos.Get(endNodeIdx); endNode = mVisitorPos.Get(endNodeIdx);
if (isCastExpr) if (isCastExpr)
{ {
bool isValidTupleCast = false; bool isValidTupleCast = false;
@ -2242,9 +2237,8 @@ BfExpression* BfReducer::CreateExpression(BfAstNode* node, CreateExprFlags creat
} }
} }
if (isCastExpr) if (isCastExpr)
{ {
BfCastExpression* bfCastExpr = NULL; BfCastExpression* bfCastExpr = NULL;
if (isTuple) if (isTuple)
{ {
@ -2284,7 +2278,7 @@ BfExpression* BfReducer::CreateExpression(BfAstNode* node, CreateExprFlags creat
unaryOpExpr = bfCastExpr; unaryOpExpr = bfCastExpr;
} }
} }
if (!isCastExpr) if (!isCastExpr)
{ {
if (auto nextToken = BfNodeDynCast<BfTokenNode>(mVisitorPos.GetNext())) if (auto nextToken = BfNodeDynCast<BfTokenNode>(mVisitorPos.GetNext()))
@ -2354,7 +2348,7 @@ BfExpression* BfReducer::CreateExpression(BfAstNode* node, CreateExprFlags creat
} }
else if (tokenNode->GetToken() == BfToken_NameOf) else if (tokenNode->GetToken() == BfToken_NameOf)
{ {
BfNameOfExpression* nameOfExpr = mAlloc->Alloc<BfNameOfExpression>(); BfNameOfExpression* nameOfExpr = mAlloc->Alloc<BfNameOfExpression>();
ReplaceNode(tokenNode, nameOfExpr); ReplaceNode(tokenNode, nameOfExpr);
nameOfExpr->mToken = tokenNode; nameOfExpr->mToken = tokenNode;
tokenNode = ExpectTokenAfter(nameOfExpr, BfToken_LParen); tokenNode = ExpectTokenAfter(nameOfExpr, BfToken_LParen);
@ -2364,7 +2358,7 @@ BfExpression* BfReducer::CreateExpression(BfAstNode* node, CreateExprFlags creat
int outEndNode = -1; int outEndNode = -1;
bool isTypeRef = IsTypeReference(mVisitorPos.GetCurrent(), BfToken_RParen, -1, &outEndNode); bool isTypeRef = IsTypeReference(mVisitorPos.GetCurrent(), BfToken_RParen, -1, &outEndNode);
mVisitorPos.mReadPos--; mVisitorPos.mReadPos--;
if ((isTypeRef) && (outEndNode > 0)) if ((isTypeRef) && (outEndNode > 0))
{ {
if (auto tokenNode = BfNodeDynCast<BfTokenNode>(mVisitorPos.Get(outEndNode - 1))) if (auto tokenNode = BfNodeDynCast<BfTokenNode>(mVisitorPos.Get(outEndNode - 1)))
@ -2375,17 +2369,17 @@ BfExpression* BfReducer::CreateExpression(BfAstNode* node, CreateExprFlags creat
auto typeRef = CreateTypeRefAfter(nameOfExpr); auto typeRef = CreateTypeRefAfter(nameOfExpr);
MEMBER_SET_CHECKED(nameOfExpr, mTarget, typeRef); MEMBER_SET_CHECKED(nameOfExpr, mTarget, typeRef);
} }
} }
} }
if (nameOfExpr->mTarget == NULL) if (nameOfExpr->mTarget == NULL)
{ {
auto expr = CreateExpressionAfter(nameOfExpr); auto expr = CreateExpressionAfter(nameOfExpr);
MEMBER_SET_CHECKED(nameOfExpr, mTarget, expr); MEMBER_SET_CHECKED(nameOfExpr, mTarget, expr);
} }
tokenNode = ExpectTokenAfter(nameOfExpr, BfToken_RParen); tokenNode = ExpectTokenAfter(nameOfExpr, BfToken_RParen);
MEMBER_SET_CHECKED(nameOfExpr, mCloseParen, tokenNode); MEMBER_SET_CHECKED(nameOfExpr, mCloseParen, tokenNode);
exprLeft = nameOfExpr; exprLeft = nameOfExpr;
} }
if (exprLeft == NULL) if (exprLeft == NULL)
@ -2393,7 +2387,7 @@ BfExpression* BfReducer::CreateExpression(BfAstNode* node, CreateExprFlags creat
BfUnaryOp unaryOp = BfTokenToUnaryOp(tokenNode->GetToken()); BfUnaryOp unaryOp = BfTokenToUnaryOp(tokenNode->GetToken());
if (unaryOp != BfUnaryOp_None) if (unaryOp != BfUnaryOp_None)
{ {
unaryOpExpr = mAlloc->Alloc<BfUnaryOperatorExpression>(); unaryOpExpr = mAlloc->Alloc<BfUnaryOperatorExpression>();
unaryOpExpr->mOp = unaryOp; unaryOpExpr->mOp = unaryOp;
unaryOpExpr->mOpToken = tokenNode; unaryOpExpr->mOpToken = tokenNode;
@ -2404,7 +2398,7 @@ BfExpression* BfReducer::CreateExpression(BfAstNode* node, CreateExprFlags creat
innerFlags = (CreateExprFlags)(innerFlags | (createExprFlags & CreateExprFlags_AllowVariableDecl)); innerFlags = (CreateExprFlags)(innerFlags | (createExprFlags & CreateExprFlags_AllowVariableDecl));
if (unaryOp == BfUnaryOp_PartialRangeThrough) // This allows for just a naked '...' if (unaryOp == BfUnaryOp_PartialRangeThrough) // This allows for just a naked '...'
innerFlags = (CreateExprFlags)(innerFlags | CreateExprFlags_AllowEmpty); innerFlags = (CreateExprFlags)(innerFlags | CreateExprFlags_AllowEmpty);
// Don't attempt binary or unary operations- they will always be lower precedence // Don't attempt binary or unary operations- they will always be lower precedence
unaryOpExpr->mExpression = CreateExpressionAfter(unaryOpExpr, innerFlags); unaryOpExpr->mExpression = CreateExpressionAfter(unaryOpExpr, innerFlags);
@ -2432,7 +2426,7 @@ BfExpression* BfReducer::CreateExpression(BfAstNode* node, CreateExprFlags creat
if (auto assignmentExpr = BfNodeDynCast<BfAssignmentExpression>(unaryOpExpr->mExpression)) if (auto assignmentExpr = BfNodeDynCast<BfAssignmentExpression>(unaryOpExpr->mExpression))
{ {
// Apply unary operator (likely a dereference) to LHS // Apply unary operator (likely a dereference) to LHS
assignmentExpr->RemoveSelf(); assignmentExpr->RemoveSelf();
ReplaceNode(unaryOpExpr, assignmentExpr); ReplaceNode(unaryOpExpr, assignmentExpr);
if (assignmentExpr->mLeft != NULL) if (assignmentExpr->mLeft != NULL)
@ -2495,23 +2489,23 @@ BfExpression* BfReducer::CreateExpression(BfAstNode* node, CreateExprFlags creat
{ {
BfToken token = tokenNode->GetToken(); BfToken token = tokenNode->GetToken();
if (((createExprFlags & CreateExprFlags_BreakOnRChevron) != 0) && if (((createExprFlags & CreateExprFlags_BreakOnRChevron) != 0) &&
((token == BfToken_RChevron) || (token == BfToken_RDblChevron))) ((token == BfToken_RChevron) || (token == BfToken_RDblChevron)))
return exprLeft; return exprLeft;
BfUnaryOp postUnaryOp = BfUnaryOp_None; BfUnaryOp postUnaryOp = BfUnaryOp_None;
if (token == BfToken_DblPlus) if (token == BfToken_DblPlus)
postUnaryOp = BfUnaryOp_PostIncrement; postUnaryOp = BfUnaryOp_PostIncrement;
if (token == BfToken_DblMinus) if (token == BfToken_DblMinus)
postUnaryOp = BfUnaryOp_PostDecrement; postUnaryOp = BfUnaryOp_PostDecrement;
if (token == BfToken_DotDotDot) if (token == BfToken_DotDotDot)
{ {
//TODO: Detect if this is a BfUnaryOp_PartialRangeFrom //TODO: Detect if this is a BfUnaryOp_PartialRangeFrom
} }
if (postUnaryOp != BfUnaryOp_None) if (postUnaryOp != BfUnaryOp_None)
{ {
auto unaryOpExpr = mAlloc->Alloc<BfUnaryOperatorExpression>(); auto unaryOpExpr = mAlloc->Alloc<BfUnaryOperatorExpression>();
ReplaceNode(exprLeft, unaryOpExpr); ReplaceNode(exprLeft, unaryOpExpr);
unaryOpExpr->mOp = postUnaryOp; unaryOpExpr->mOp = postUnaryOp;
@ -2523,7 +2517,7 @@ BfExpression* BfReducer::CreateExpression(BfAstNode* node, CreateExprFlags creat
} }
if (token == BfToken_As) if (token == BfToken_As)
{ {
auto dynCastExpr = mAlloc->Alloc<BfDynamicCastExpression>(); auto dynCastExpr = mAlloc->Alloc<BfDynamicCastExpression>();
ReplaceNode(exprLeft, dynCastExpr); ReplaceNode(exprLeft, dynCastExpr);
dynCastExpr->mTarget = exprLeft; dynCastExpr->mTarget = exprLeft;
@ -2537,7 +2531,7 @@ BfExpression* BfReducer::CreateExpression(BfAstNode* node, CreateExprFlags creat
} }
if (token == BfToken_Is) if (token == BfToken_Is)
{ {
auto checkTypeExpr = mAlloc->Alloc<BfCheckTypeExpression>(); auto checkTypeExpr = mAlloc->Alloc<BfCheckTypeExpression>();
ReplaceNode(exprLeft, checkTypeExpr); ReplaceNode(exprLeft, checkTypeExpr);
checkTypeExpr->mTarget = exprLeft; checkTypeExpr->mTarget = exprLeft;
@ -2788,7 +2782,7 @@ BfExpression* BfReducer::CreateExpression(BfAstNode* node, CreateExprFlags creat
continue; continue;
} }
// Could be a struct generic initializer, or a generic method invocation // Could be a struct generic initializer, or a generic method invocation
if (auto outToken = BfNodeDynCast<BfTokenNode>(outNode)) if (auto outToken = BfNodeDynCast<BfTokenNode>(outNode))
{ {
int endNodeIdx = -1; int endNodeIdx = -1;
@ -2857,7 +2851,7 @@ BfExpression* BfReducer::CreateExpression(BfAstNode* node, CreateExprFlags creat
binOpExpression->mLeft = exprLeft; binOpExpression->mLeft = exprLeft;
binOpExpression->mOp = binOp; binOpExpression->mOp = binOp;
MEMBER_SET(binOpExpression, mOpToken, tokenNode); MEMBER_SET(binOpExpression, mOpToken, tokenNode);
if (exprRight == NULL) if (exprRight == NULL)
return binOpExpression; return binOpExpression;
MEMBER_SET(binOpExpression, mRight, exprRight); MEMBER_SET(binOpExpression, mRight, exprRight);
@ -3239,7 +3233,7 @@ BfStatement* BfReducer::CreateForStatement(BfAstNode* node)
{ {
// Try to convert 'int i = 0, j = 0` into two variable declarations instead of a var decl and an assignment // Try to convert 'int i = 0, j = 0` into two variable declarations instead of a var decl and an assignment
if (auto prevExprStmt = BfNodeDynCast<BfExpressionStatement>(initializers.back())) if (auto prevExprStmt = BfNodeDynCast<BfExpressionStatement>(initializers.back()))
{ {
if (auto prevVarDecl = BfNodeDynCast<BfVariableDeclaration>(prevExprStmt->mExpression)) if (auto prevVarDecl = BfNodeDynCast<BfVariableDeclaration>(prevExprStmt->mExpression))
{ {
if (auto exprStmt = BfNodeDynCast<BfExpressionStatement>(stmt)) if (auto exprStmt = BfNodeDynCast<BfExpressionStatement>(stmt))
@ -3574,7 +3568,7 @@ BfSwitchStatement* BfReducer::CreateSwitchStatement(BfTokenNode* tokenNode)
token = tokenNode->GetToken(); token = tokenNode->GetToken();
if ((tokenNode == NULL) || if ((tokenNode == NULL) ||
((token != BfToken_Case) && (token != BfToken_When) && (token != BfToken_Default))) ((token != BfToken_Case) && (token != BfToken_When) && (token != BfToken_Default)))
{ {
Fail("Expected 'case'", child); Fail("Expected 'case'", child);
AddErrorNode(child); AddErrorNode(child);
isDone = !mVisitorPos.MoveNext(); isDone = !mVisitorPos.MoveNext();
@ -3623,7 +3617,7 @@ BfSwitchStatement* BfReducer::CreateSwitchStatement(BfTokenNode* tokenNode)
whenExpr->mWhenToken = whenToken; whenExpr->mWhenToken = whenToken;
ReplaceNode(whenToken, whenExpr); ReplaceNode(whenToken, whenExpr);
//mVisitorPos.MoveNext(); //mVisitorPos.MoveNext();
//auto exprAfter = wasWhenSet ? (BfAstNode*)switchCase : (BfAstNode*)whenExpr; //auto exprAfter = wasWhenSet ? (BfAstNode*)switchCase : (BfAstNode*)whenExpr;
if (expr == NULL) if (expr == NULL)
{ {
auto innerExpr = CreateExpressionAfter(whenToken); auto innerExpr = CreateExpressionAfter(whenToken);
@ -3727,7 +3721,7 @@ BfSwitchStatement* BfReducer::CreateSwitchStatement(BfTokenNode* tokenNode)
{ {
int token = tokenNode->GetToken(); int token = tokenNode->GetToken();
if ((token == BfToken_Case) || (token == BfToken_Default) || (token == BfToken_When)) if ((token == BfToken_Case) || (token == BfToken_Default) || (token == BfToken_When))
break; // Done! No fallthrough break; // Done! No fallthrough
} }
nextNode = mVisitorPos.GetNext(); nextNode = mVisitorPos.GetNext();
@ -3736,7 +3730,7 @@ BfSwitchStatement* BfReducer::CreateSwitchStatement(BfTokenNode* tokenNode)
hadEmptyCaseStatement = false; hadEmptyCaseStatement = false;
mVisitorPos.MoveNext(); mVisitorPos.MoveNext();
// We need to use CreateStmtFlags_NoCaseExpr because otherwise during typing a new statement at the end of one case, it // We need to use CreateStmtFlags_NoCaseExpr because otherwise during typing a new statement at the end of one case, it
// could interpret the 'case' token for the next case as being part of a case expression in the first case // could interpret the 'case' token for the next case as being part of a case expression in the first case
auto stmt = CreateStatement(nextNode, (CreateStmtFlags)(CreateStmtFlags_FindTrailingSemicolon | CreateStmtFlags_NoCaseExpr | CreateStmtFlags_AllowLocalFunction)); auto stmt = CreateStatement(nextNode, (CreateStmtFlags)(CreateStmtFlags_FindTrailingSemicolon | CreateStmtFlags_NoCaseExpr | CreateStmtFlags_AllowLocalFunction));
if (stmt == NULL) if (stmt == NULL)
@ -4113,7 +4107,7 @@ BfAstNode* BfReducer::DoCreateStatement(BfAstNode* node, CreateStmtFlags createS
{ {
auto flags = (CreateStmtFlags)(CreateStmtFlags_FindTrailingSemicolon | CreateStmtFlags_ForceVariableDecl); auto flags = (CreateStmtFlags)(CreateStmtFlags_FindTrailingSemicolon | CreateStmtFlags_ForceVariableDecl);
if (token == BfToken_Static) if (token == BfToken_Static)
flags = (CreateStmtFlags)(flags | CreateStmtFlags_AllowLocalFunction); flags = (CreateStmtFlags)(flags | CreateStmtFlags_AllowLocalFunction);
auto stmt = CreateStatementAfter(tokenNode, flags); auto stmt = CreateStatementAfter(tokenNode, flags);
if (auto exprStmt = BfNodeDynCast<BfExpressionStatement>(stmt)) if (auto exprStmt = BfNodeDynCast<BfExpressionStatement>(stmt))
{ {
@ -4512,7 +4506,7 @@ bool BfReducer::IsTerminatingExpression(BfAstNode* node)
chevronDepth++; chevronDepth++;
break; break;
case BfToken_RChevron: case BfToken_RChevron:
// If we find a < and > that are not separated by parens, that's a generic, which must be a // If we find a < and > that are not separated by parens, that's a generic, which must be a
// variable decl if it's not in parens // variable decl if it's not in parens
if ((parenDepth == 0) && (chevronDepth > 0)) if ((parenDepth == 0) && (chevronDepth > 0))
return false; return false;
@ -5003,7 +4997,7 @@ BfTypeReference* BfReducer::DoCreateTypeRef(BfAstNode* firstNode, CreateTypeRefF
} }
MEMBER_SET_CHECKED(delegateTypeRef, mCloseParen, closeNode); MEMBER_SET_CHECKED(delegateTypeRef, mCloseParen, closeNode);
mVisitorPos.MoveNext(); mVisitorPos.MoveNext();
isHandled = true; isHandled = true;
firstNode = delegateTypeRef; firstNode = delegateTypeRef;
@ -5026,7 +5020,7 @@ BfTypeReference* BfReducer::DoCreateTypeRef(BfAstNode* firstNode, CreateTypeRefF
firstNode = declTypeRef; firstNode = declTypeRef;
if ((createTypeRefFlags & CreateTypeRefFlags_EarlyExit) != 0) if ((createTypeRefFlags & CreateTypeRefFlags_EarlyExit) != 0)
return declTypeRef; return declTypeRef;
} }
else if (token == BfToken_LParen) else if (token == BfToken_LParen)
{ {
@ -5095,7 +5089,7 @@ BfTypeReference* BfReducer::DoCreateTypeRef(BfAstNode* firstNode, CreateTypeRefF
{ {
Fail("Expected type", firstNode); Fail("Expected type", firstNode);
return NULL; return NULL;
} }
} }
} }
@ -5518,7 +5512,7 @@ BfIdentifierNode* BfReducer::CompactQualifiedName(BfAstNode* leftNode)
auto rightIdentifier = BfNodeDynCast<BfIdentifierNode>(nextNextToken); auto rightIdentifier = BfNodeDynCast<BfIdentifierNode>(nextNextToken);
if (rightIdentifier == NULL) if (rightIdentifier == NULL)
{ {
if (auto rightToken = BfNodeDynCast<BfTokenNode>(nextNextToken)) if (auto rightToken = BfNodeDynCast<BfTokenNode>(nextNextToken))
{ {
if (BfTokenIsKeyword(rightToken->mToken)) if (BfTokenIsKeyword(rightToken->mToken))
{ {
@ -5526,16 +5520,16 @@ BfIdentifierNode* BfReducer::CompactQualifiedName(BfAstNode* leftNode)
ReplaceNode(rightToken, rightIdentifier); ReplaceNode(rightToken, rightIdentifier);
} }
} }
if (rightIdentifier == NULL) if (rightIdentifier == NULL)
return leftIdentifier; return leftIdentifier;
} }
// If the previous dotted span failed (IE: had chevrons) then don't insert qualified names in the middle of it // If the previous dotted span failed (IE: had chevrons) then don't insert qualified names in the middle of it
auto prevNodeToken = BfNodeDynCast<BfTokenNode>(prevNode); auto prevNodeToken = BfNodeDynCast<BfTokenNode>(prevNode);
if ((prevNodeToken != NULL) && if ((prevNodeToken != NULL) &&
((prevNodeToken->GetToken() == BfToken_Dot) || ((prevNodeToken->GetToken() == BfToken_Dot) ||
(prevNodeToken->GetToken() == BfToken_QuestionDot) || (prevNodeToken->GetToken() == BfToken_QuestionDot) ||
(prevNodeToken->GetToken() == BfToken_Arrow))) (prevNodeToken->GetToken() == BfToken_Arrow)))
return leftIdentifier; return leftIdentifier;
@ -5566,7 +5560,7 @@ void BfReducer::TryIdentifierConvert(int readPos)
ReplaceNode(tokenNode, identifierNode); ReplaceNode(tokenNode, identifierNode);
mVisitorPos.Set(readPos, identifierNode); mVisitorPos.Set(readPos, identifierNode);
} }
} }
} }
void BfReducer::CreateQualifiedNames(BfAstNode* node) void BfReducer::CreateQualifiedNames(BfAstNode* node)
@ -5691,7 +5685,7 @@ Do_RBracket:
mVisitorPos.MoveNext(); mVisitorPos.MoveNext();
} }
// Has another one- chain it // Has another one- chain it
auto nextAttribute = CreateAttributeDirective(tokenNode); auto nextAttribute = CreateAttributeDirective(tokenNode);
if (nextAttribute != NULL) if (nextAttribute != NULL)
{ {
@ -5706,14 +5700,14 @@ BfStatement* BfReducer::CreateAttributedStatement(BfTokenNode* tokenNode, Create
auto attrib = CreateAttributeDirective(tokenNode); auto attrib = CreateAttributeDirective(tokenNode);
if (attrib == NULL) if (attrib == NULL)
return NULL; return NULL;
BfAstNode* stmt = CreateStatementAfter(attrib, createStmtFlags); BfAstNode* stmt = CreateStatementAfter(attrib, createStmtFlags);
if (stmt != NULL) if (stmt != NULL)
{ {
if (auto localMethodDecl = BfNodeDynCastExact<BfLocalMethodDeclaration>(stmt)) if (auto localMethodDecl = BfNodeDynCastExact<BfLocalMethodDeclaration>(stmt))
{ {
BF_ASSERT(localMethodDecl->mMethodDeclaration->mAttributes == NULL); BF_ASSERT(localMethodDecl->mMethodDeclaration->mAttributes == NULL);
localMethodDecl->mSrcStart = attrib->mSrcStart; localMethodDecl->mSrcStart = attrib->mSrcStart;
MEMBER_SET(localMethodDecl->mMethodDeclaration, mAttributes, attrib); MEMBER_SET(localMethodDecl->mMethodDeclaration, mAttributes, attrib);
return localMethodDecl; return localMethodDecl;
} }
@ -5755,7 +5749,7 @@ BfExpression* BfReducer::CreateAttributedExpression(BfTokenNode* tokenNode, bool
return NULL; return NULL;
if (!onlyAllowIdentifier) if (!onlyAllowIdentifier)
{ {
BfExpression* expr = CreateExpressionAfter(attrib, CreateExprFlags_EarlyExit); BfExpression* expr = CreateExpressionAfter(attrib, CreateExprFlags_EarlyExit);
if (expr != NULL) if (expr != NULL)
{ {
@ -5780,7 +5774,7 @@ BfExpression* BfReducer::CreateAttributedExpression(BfTokenNode* tokenNode, bool
MEMBER_SET(attribExpr, mExpression, expr); MEMBER_SET(attribExpr, mExpression, expr);
return attribExpr; return attribExpr;
} }
} }
Fail("Prefixed attributes can only be used on allocations, invocations, blocks, or variable declarations", attrib); Fail("Prefixed attributes can only be used on allocations, invocations, blocks, or variable declarations", attrib);
@ -6156,7 +6150,7 @@ BfAstNode* BfReducer::ReadTypeMember(BfTokenNode* tokenNode, bool declStarted, i
ReplaceNode(tokenNode, ctorDecl); ReplaceNode(tokenNode, ctorDecl);
MEMBER_SET(ctorDecl, mThisToken, tokenNode); MEMBER_SET(ctorDecl, mThisToken, tokenNode);
if (auto block = BfNodeDynCast<BfBlock>(mVisitorPos.GetNext())) if (auto block = BfNodeDynCast<BfBlock>(mVisitorPos.GetNext()))
{ {
mVisitorPos.MoveNext(); mVisitorPos.MoveNext();
MEMBER_SET(ctorDecl, mBody, block); MEMBER_SET(ctorDecl, mBody, block);
@ -6443,7 +6437,7 @@ BfAstNode* BfReducer::ReadTypeMember(BfTokenNode* tokenNode, bool declStarted, i
} }
} }
SetProtection(memberDecl, memberDecl->mProtectionSpecifier, tokenNode); SetProtection(memberDecl, memberDecl->mProtectionSpecifier, tokenNode);
return memberDecl; return memberDecl;
} }
@ -6549,7 +6543,7 @@ BfAstNode* BfReducer::ReadTypeMember(BfTokenNode* tokenNode, bool declStarted, i
{ {
if (token == BfToken_Override) if (token == BfToken_Override)
{ {
// Must be typing an 'override' over a field declaration // Must be typing an 'override' over a field declaration
auto propDecl = mAlloc->Alloc<BfPropertyDeclaration>(); auto propDecl = mAlloc->Alloc<BfPropertyDeclaration>();
propDecl->mVirtualSpecifier = tokenNode; propDecl->mVirtualSpecifier = tokenNode;
typeMember = memberDecl = propDecl; typeMember = memberDecl = propDecl;
@ -6584,7 +6578,7 @@ BfAstNode* BfReducer::ReadTypeMember(BfTokenNode* tokenNode, bool declStarted, i
auto usingSpecifier = mAlloc->Alloc<BfUsingSpecifierNode>(); auto usingSpecifier = mAlloc->Alloc<BfUsingSpecifierNode>();
ReplaceNode(tokenNode, usingSpecifier); ReplaceNode(tokenNode, usingSpecifier);
MEMBER_SET(usingSpecifier, mUsingToken, tokenNode); MEMBER_SET(usingSpecifier, mUsingToken, tokenNode);
MEMBER_SET(fieldDecl, mConstSpecifier, usingSpecifier); MEMBER_SET(fieldDecl, mConstSpecifier, usingSpecifier);
handled = true; handled = true;
} }
@ -6759,10 +6753,10 @@ void BfReducer::ReadPropertyBlock(BfPropertyDeclaration* propertyDeclaration, Bf
BfAstNode* bodyAfterNode = accessorIdentifier; BfAstNode* bodyAfterNode = accessorIdentifier;
BfAstNode* body = NULL; BfAstNode* body = NULL;
auto tokenNode = BfNodeDynCast<BfTokenNode>(child); auto tokenNode = BfNodeDynCast<BfTokenNode>(child);
if ((tokenNode != NULL) && (tokenNode->GetToken() == BfToken_Ref) && (accessorName == "set")) if ((tokenNode != NULL) && (tokenNode->GetToken() == BfToken_Ref) && (accessorName == "set"))
{ {
refSpecifier = tokenNode; refSpecifier = tokenNode;
bodyAfterNode = tokenNode; bodyAfterNode = tokenNode;
@ -6782,8 +6776,8 @@ void BfReducer::ReadPropertyBlock(BfPropertyDeclaration* propertyDeclaration, Bf
mVisitorPos.MoveNext(); mVisitorPos.MoveNext();
child = mVisitorPos.GetNext(); child = mVisitorPos.GetNext();
} }
bool handled = false; bool handled = false;
BfTokenNode* fatArrowToken = NULL; BfTokenNode* fatArrowToken = NULL;
BfAstNode* endSemicolon = NULL; BfAstNode* endSemicolon = NULL;
@ -6796,7 +6790,7 @@ void BfReducer::ReadPropertyBlock(BfPropertyDeclaration* propertyDeclaration, Bf
mVisitorPos.MoveNext(); mVisitorPos.MoveNext();
} }
else if (tokenNode->mToken == BfToken_FatArrow) else if (tokenNode->mToken == BfToken_FatArrow)
{ {
handled = true; handled = true;
fatArrowToken = tokenNode; fatArrowToken = tokenNode;
mVisitorPos.MoveNext(); mVisitorPos.MoveNext();
@ -6806,9 +6800,9 @@ void BfReducer::ReadPropertyBlock(BfPropertyDeclaration* propertyDeclaration, Bf
{ {
body = expr; body = expr;
endSemicolon = ExpectTokenAfter(expr, BfToken_Semicolon); endSemicolon = ExpectTokenAfter(expr, BfToken_Semicolon);
} }
} }
} }
if (!handled) if (!handled)
{ {
@ -6822,7 +6816,7 @@ void BfReducer::ReadPropertyBlock(BfPropertyDeclaration* propertyDeclaration, Bf
{ {
body = accessorBlock; body = accessorBlock;
mVisitorPos.MoveNext(); mVisitorPos.MoveNext();
} }
if (body == NULL) if (body == NULL)
{ {
if (child != NULL) if (child != NULL)
@ -6831,7 +6825,7 @@ void BfReducer::ReadPropertyBlock(BfPropertyDeclaration* propertyDeclaration, Bf
AddErrorNode(child); AddErrorNode(child);
mVisitorPos.MoveNext(); mVisitorPos.MoveNext();
} }
} }
} }
} }
@ -6859,7 +6853,7 @@ void BfReducer::ReadPropertyBlock(BfPropertyDeclaration* propertyDeclaration, Bf
auto method = mAlloc->Alloc<BfPropertyMethodDeclaration>(); auto method = mAlloc->Alloc<BfPropertyMethodDeclaration>();
method->mPropertyDeclaration = propertyDeclaration; method->mPropertyDeclaration = propertyDeclaration;
if (fatArrowToken != NULL) if (fatArrowToken != NULL)
MEMBER_SET(method, mFatArrowToken, fatArrowToken); MEMBER_SET(method, mFatArrowToken, fatArrowToken);
if (endSemicolon != NULL) if (endSemicolon != NULL)
@ -6897,12 +6891,12 @@ BfAstNode* BfReducer::ReadTypeMember(BfAstNode* node, bool declStarted, int dept
BfTokenNode* refToken = NULL; BfTokenNode* refToken = NULL;
if (auto tokenNode = BfNodeDynCast<BfTokenNode>(node)) if (auto tokenNode = BfNodeDynCast<BfTokenNode>(node))
{ {
BfToken token = tokenNode->GetToken(); BfToken token = tokenNode->GetToken();
bool isTypeRef = false; bool isTypeRef = false;
if ((token == BfToken_Delegate) || (token == BfToken_Function)) if ((token == BfToken_Delegate) || (token == BfToken_Function))
{ {
// We need to differentiate between a delegate type reference and a delegate type declaration // We need to differentiate between a delegate type reference and a delegate type declaration
int endNodeIdx = -1; int endNodeIdx = -1;
if (IsTypeReference(node, BfToken_LParen, -1, &endNodeIdx)) if (IsTypeReference(node, BfToken_LParen, -1, &endNodeIdx))
{ {
@ -6939,7 +6933,7 @@ BfAstNode* BfReducer::ReadTypeMember(BfAstNode* node, bool declStarted, int dept
} }
else else
{ {
SetAndRestoreValue<BfAstNode*> prevTypeMemberNodeStart(mTypeMemberNodeStart, tokenNode, !declStarted); SetAndRestoreValue<BfAstNode*> prevTypeMemberNodeStart(mTypeMemberNodeStart, tokenNode, !declStarted);
return ReadTypeMember(tokenNode, declStarted, depth, deferredHeadNode); return ReadTypeMember(tokenNode, declStarted, depth, deferredHeadNode);
} }
} }
@ -6992,7 +6986,6 @@ BfAstNode* BfReducer::ReadTypeMember(BfAstNode* node, bool declStarted, int dept
node = typeRef; node = typeRef;
auto nextNode = mVisitorPos.GetNext(); auto nextNode = mVisitorPos.GetNext();
if (auto tokenNode = BfNodeDynCast<BfTokenNode>(nextNode)) if (auto tokenNode = BfNodeDynCast<BfTokenNode>(nextNode))
{ {
@ -7146,7 +7139,7 @@ BfAstNode* BfReducer::ReadTypeMember(BfAstNode* node, bool declStarted, int dept
} }
ParseMethod(operatorDecl, &params, &commas); ParseMethod(operatorDecl, &params, &commas);
if (params.size() == 1) if (params.size() == 1)
{ {
if (operatorDecl->mBinOp == BfBinaryOp_Add) if (operatorDecl->mBinOp == BfBinaryOp_Add)
@ -7158,7 +7151,7 @@ BfAstNode* BfReducer::ReadTypeMember(BfAstNode* node, bool declStarted, int dept
{ {
operatorDecl->mBinOp = BfBinaryOp_None; operatorDecl->mBinOp = BfBinaryOp_None;
operatorDecl->mUnaryOp = BfUnaryOp_Negate; operatorDecl->mUnaryOp = BfUnaryOp_Negate;
} }
} }
return operatorDecl; return operatorDecl;
@ -7235,7 +7228,7 @@ BfAstNode* BfReducer::ReadTypeMember(BfAstNode* node, bool declStarted, int dept
// If we don't have a token afterwards then still treat it as a property for autocomplete purposes // If we don't have a token afterwards then still treat it as a property for autocomplete purposes
if ((typeRef != NULL) && if ((typeRef != NULL) &&
((block != NULL) || (tokenNode == NULL) || (isExprBodyProp))) ((block != NULL) || (tokenNode == NULL) || (isExprBodyProp)))
{ {
if (propertyDeclaration == NULL) if (propertyDeclaration == NULL)
{ {
if ((block == NULL) && (!isExprBodyProp)) if ((block == NULL) && (!isExprBodyProp))
@ -7255,7 +7248,7 @@ BfAstNode* BfReducer::ReadTypeMember(BfAstNode* node, bool declStarted, int dept
//mVisitorPos.mReadPos--; //mVisitorPos.mReadPos--;
// WHY did we want to not set this? // WHY did we want to not set this?
// If we don't, then typing a new method name will end up treating the name node as a typeRef // If we don't, then typing a new method name will end up treating the name node as a typeRef
// which can autocomplete incorrectly // which can autocomplete incorrectly
MEMBER_SET(propDecl, mNameNode, nameIdentifier); MEMBER_SET(propDecl, mNameNode, nameIdentifier);
@ -7320,7 +7313,7 @@ BfAstNode* BfReducer::ReadTypeMember(BfAstNode* node, bool declStarted, int dept
if (tokenNode->mToken == BfToken_Mut) if (tokenNode->mToken == BfToken_Mut)
{ {
MEMBER_SET(propertyBodyExpr, mMutSpecifier, tokenNode); MEMBER_SET(propertyBodyExpr, mMutSpecifier, tokenNode);
tokenNode = ExpectTokenAfter(tokenNode, BfToken_FatArrow); tokenNode = ExpectTokenAfter(tokenNode, BfToken_FatArrow);
} }
if (tokenNode != NULL) if (tokenNode != NULL)
@ -7383,7 +7376,7 @@ BfAstNode* BfReducer::ReadTypeMember(BfAstNode* node, bool declStarted, int dept
{ {
if (token == BfToken_LChevron) if (token == BfToken_LChevron)
{ {
bool isTypeRef = IsTypeReference(nameIdentifier, BfToken_LParen); bool isTypeRef = IsTypeReference(nameIdentifier, BfToken_LParen);
if (!isTypeRef) if (!isTypeRef)
{ {
bool onNewLine = false; bool onNewLine = false;
@ -7395,7 +7388,7 @@ BfAstNode* BfReducer::ReadTypeMember(BfAstNode* node, bool declStarted, int dept
if (onNewLine) if (onNewLine)
{ {
// Actually it looks like a partially formed type declaration followed by a method // Actually it looks like a partially formed type declaration followed by a method
// which returns a generic type // which returns a generic type
FailAfter("Name expected", typeRef); FailAfter("Name expected", typeRef);
@ -7543,7 +7536,7 @@ BfInitializerExpression* BfReducer::TryCreateInitializerExpression(BfAstNode* ta
SetAndRestoreValue<BfVisitorPos> prevVisitorPos(mVisitorPos, BfVisitorPos(block)); SetAndRestoreValue<BfVisitorPos> prevVisitorPos(mVisitorPos, BfVisitorPos(block));
bool isDone = !mVisitorPos.MoveNext(); bool isDone = !mVisitorPos.MoveNext();
BfDeferredAstNodeSizedArray<BfExpression*> values(initializerExpr, initializerExpr->mValues, mAlloc); BfDeferredAstNodeSizedArray<BfExpression*> values(initializerExpr, initializerExpr->mValues, mAlloc);
BfDeferredAstNodeSizedArray<BfTokenNode*> commas(initializerExpr, initializerExpr->mCommas, mAlloc); BfDeferredAstNodeSizedArray<BfTokenNode*> commas(initializerExpr, initializerExpr->mCommas, mAlloc);
@ -7575,12 +7568,12 @@ BfInitializerExpression* BfReducer::TryCreateInitializerExpression(BfAstNode* ta
} }
} }
} }
} }
mVisitorPos.Trim(); mVisitorPos.Trim();
if (block->mCloseBrace != NULL) if (block->mCloseBrace != NULL)
MEMBER_SET(initializerExpr, mCloseBrace, block->mCloseBrace); MEMBER_SET(initializerExpr, mCloseBrace, block->mCloseBrace);
return initializerExpr; return initializerExpr;
} }
@ -7843,7 +7836,7 @@ bool BfReducer::SetProtection(BfAstNode* parentNode, BfAstNode*& protectionNodeR
((prevToken->mToken == BfToken_Internal) && (tokenNode->mToken == BfToken_Protected))) ((prevToken->mToken == BfToken_Internal) && (tokenNode->mToken == BfToken_Protected)))
{ {
auto tokenPair = mAlloc->Alloc<BfTokenPairNode>(); auto tokenPair = mAlloc->Alloc<BfTokenPairNode>();
if (prevToken->mSrcStart < tokenNode->mSrcStart) if (prevToken->mSrcStart < tokenNode->mSrcStart)
{ {
ReplaceNode(prevToken, tokenPair); ReplaceNode(prevToken, tokenPair);
@ -7863,7 +7856,7 @@ bool BfReducer::SetProtection(BfAstNode* parentNode, BfAstNode*& protectionNodeR
return true; return true;
} }
} }
Fail("Protection already specified", protectionNodeRef); Fail("Protection already specified", protectionNodeRef);
} }
protectionNodeRef = tokenNode; protectionNodeRef = tokenNode;
@ -8017,7 +8010,6 @@ BfAstNode* BfReducer::CreateAllocNode(BfTokenNode* allocToken)
MEMBER_SET(newNode, mAllocNode, identifier); MEMBER_SET(newNode, mAllocNode, identifier);
mVisitorPos.MoveNext(); mVisitorPos.MoveNext();
} }
} }
} }
@ -8112,7 +8104,7 @@ BfObjectCreateExpression* BfReducer::CreateObjectCreateExpression(BfAstNode* all
MEMBER_SET(objectCreateExpr, mCloseToken, block->mCloseBrace); MEMBER_SET(objectCreateExpr, mCloseToken, block->mCloseBrace);
objectCreateExpr->mSrcEnd = block->mSrcEnd; objectCreateExpr->mSrcEnd = block->mSrcEnd;
return objectCreateExpr; return objectCreateExpr;
} }
if (isArray) if (isArray)
{ {
@ -8127,13 +8119,13 @@ BfObjectCreateExpression* BfReducer::CreateObjectCreateExpression(BfAstNode* all
} }
else else
{ {
// Note- if there WERE an LBracket here then we'd have an 'isArray' case. We pass this in here for // Note- if there WERE an LBracket here then we'd have an 'isArray' case. We pass this in here for
// error display purposes // error display purposes
tokenNode = ExpectTokenAfter(objectCreateExpr, BfToken_LParen, BfToken_LBracket); tokenNode = ExpectTokenAfter(objectCreateExpr, BfToken_LParen, BfToken_LBracket);
if (tokenNode == NULL) if (tokenNode == NULL)
return objectCreateExpr; return objectCreateExpr;
} }
MEMBER_SET(objectCreateExpr, mOpenToken, tokenNode); MEMBER_SET(objectCreateExpr, mOpenToken, tokenNode);
BfToken endToken = (BfToken)(tokenNode->GetToken() + 1); BfToken endToken = (BfToken)(tokenNode->GetToken() + 1);
@ -8141,7 +8133,7 @@ BfObjectCreateExpression* BfReducer::CreateObjectCreateExpression(BfAstNode* all
if (tokenNode == NULL) if (tokenNode == NULL)
return objectCreateExpr; return objectCreateExpr;
MEMBER_SET(objectCreateExpr, mCloseToken, tokenNode); MEMBER_SET(objectCreateExpr, mCloseToken, tokenNode);
return objectCreateExpr; return objectCreateExpr;
} }
@ -8175,7 +8167,7 @@ BfExpression* BfReducer::CreateIndexerExpression(BfExpression* target)
if (attributeDirective != NULL) if (attributeDirective != NULL)
{ {
BfAttributedExpression* attribExpr = mAlloc->Alloc<BfAttributedExpression>(); BfAttributedExpression* attribExpr = mAlloc->Alloc<BfAttributedExpression>();
ReplaceNode(indexerExpr, attribExpr); ReplaceNode(indexerExpr, attribExpr);
attribExpr->mExpression = indexerExpr; attribExpr->mExpression = indexerExpr;
MEMBER_SET(attribExpr, mAttributes, attributeDirective); MEMBER_SET(attribExpr, mAttributes, attributeDirective);
return attribExpr; return attribExpr;
@ -8340,16 +8332,16 @@ BfAstNode* BfReducer::HandleTopLevel(BfBlock* node)
bool hadPrevFail = false; bool hadPrevFail = false;
bool isDone = !mVisitorPos.MoveNext(); bool isDone = !mVisitorPos.MoveNext();
auto parser = mSource->ToParser(); auto parser = mSource->ToParser();
if ((parser != NULL) && (parser->mEmbedKind == BfSourceEmbedKind_Type)) if ((parser != NULL) && (parser->mEmbedKind == BfSourceEmbedKind_Type))
{ {
while (!isDone) while (!isDone)
{ {
auto node = mVisitorPos.GetCurrent(); auto node = mVisitorPos.GetCurrent();
if (node == prevNode) if (node == prevNode)
{ {
// If we're stuck on an error and can't process any more nodes // If we're stuck on an error and can't process any more nodes
break; break;
} }
@ -8418,7 +8410,7 @@ BfAstNode* BfReducer::HandleTopLevel(BfBlock* node)
isDone = !mVisitorPos.MoveNext(); isDone = !mVisitorPos.MoveNext();
if (newNode != NULL) if (newNode != NULL)
mVisitorPos.Write(newNode); mVisitorPos.Write(newNode);
} }
mVisitorPos.Trim(); mVisitorPos.Trim();
return node; return node;
@ -8503,7 +8495,7 @@ BfAstNode* BfReducer::CreateTopLevelObject(BfTokenNode* tokenNode, BfAttributeDi
break; break;
} }
} }
} }
else if ((bracketDepth > 0) || (parenDepth > 0)) else if ((bracketDepth > 0) || (parenDepth > 0))
{ {
// Allow // Allow
@ -8627,7 +8619,7 @@ BfAstNode* BfReducer::CreateTopLevelObject(BfTokenNode* tokenNode, BfAttributeDi
bodyNode = ExpectTokenAfter(namespaceDeclaration, BfToken_Semicolon); bodyNode = ExpectTokenAfter(namespaceDeclaration, BfToken_Semicolon);
else else
bodyNode = blockNode = ExpectBlockAfter(namespaceDeclaration); bodyNode = blockNode = ExpectBlockAfter(namespaceDeclaration);
if (bodyNode == NULL) if (bodyNode == NULL)
return namespaceDeclaration; return namespaceDeclaration;
MoveNode(bodyNode, namespaceDeclaration); MoveNode(bodyNode, namespaceDeclaration);
@ -8653,7 +8645,7 @@ BfAstNode* BfReducer::CreateTopLevelObject(BfTokenNode* tokenNode, BfAttributeDi
FailAfter("Expected type declaration", tokenNode); FailAfter("Expected type declaration", tokenNode);
return NULL; return NULL;
} }
mVisitorPos.MoveNext(); mVisitorPos.MoveNext();
auto topLevelObject = CreateTopLevelObject(nextToken, attributes); auto topLevelObject = CreateTopLevelObject(nextToken, attributes);
if (topLevelObject == NULL) if (topLevelObject == NULL)
@ -8674,7 +8666,7 @@ BfAstNode* BfReducer::CreateTopLevelObject(BfTokenNode* tokenNode, BfAttributeDi
break; break;
case BfToken_Sealed: case BfToken_Sealed:
case BfToken_Abstract: case BfToken_Abstract:
case BfToken_Public: case BfToken_Public:
case BfToken_Private: case BfToken_Private:
case BfToken_Protected: case BfToken_Protected:
@ -8707,7 +8699,7 @@ BfAstNode* BfReducer::CreateTopLevelObject(BfTokenNode* tokenNode, BfAttributeDi
return NULL; return NULL;
} }
mVisitorPos.MoveNext(); mVisitorPos.MoveNext();
auto topLevelObject = CreateTopLevelObject(nextToken, attributes); auto topLevelObject = CreateTopLevelObject(nextToken, attributes);
if (topLevelObject == NULL) if (topLevelObject == NULL)
{ {
@ -8731,7 +8723,7 @@ BfAstNode* BfReducer::CreateTopLevelObject(BfTokenNode* tokenNode, BfAttributeDi
(token == BfToken_Private) || (token == BfToken_Private) ||
(token == BfToken_Internal)) (token == BfToken_Internal))
{ {
SetProtection(typeDeclaration, typeDeclaration->mProtectionSpecifier, tokenNode); SetProtection(typeDeclaration, typeDeclaration->mProtectionSpecifier, tokenNode);
} }
if (token == BfToken_Static) if (token == BfToken_Static)
@ -8822,8 +8814,6 @@ BfAstNode* BfReducer::CreateTopLevelObject(BfTokenNode* tokenNode, BfAttributeDi
//MEMBER_SET(methodDecl, mReturnType, retType); //MEMBER_SET(methodDecl, mReturnType, retType);
return typeDeclaration; return typeDeclaration;
} }
break; break;
@ -8961,15 +8951,15 @@ BfAstNode* BfReducer::CreateTopLevelObject(BfTokenNode* tokenNode, BfAttributeDi
{ {
if (tokenNode->mToken == BfToken_This) if (tokenNode->mToken == BfToken_This)
{ {
mVisitorPos.MoveNext(); mVisitorPos.MoveNext();
auto ctorDecl = mAlloc->Alloc<BfAutoConstructorDeclaration>(); auto ctorDecl = mAlloc->Alloc<BfAutoConstructorDeclaration>();
BfDeferredAstSizedArray<BfParameterDeclaration*> params(ctorDecl->mParams, mAlloc); BfDeferredAstSizedArray<BfParameterDeclaration*> params(ctorDecl->mParams, mAlloc);
BfDeferredAstSizedArray<BfTokenNode*> commas(ctorDecl->mCommas, mAlloc); BfDeferredAstSizedArray<BfTokenNode*> commas(ctorDecl->mCommas, mAlloc);
ctorDecl->mReturnType = NULL; ctorDecl->mReturnType = NULL;
ReplaceNode(tokenNode, ctorDecl); ReplaceNode(tokenNode, ctorDecl);
MEMBER_SET(ctorDecl, mThisToken, tokenNode); MEMBER_SET(ctorDecl, mThisToken, tokenNode);
ParseMethod(ctorDecl, &params, &commas); ParseMethod(ctorDecl, &params, &commas);
if (typeDeclaration->mAutoCtor == NULL) if (typeDeclaration->mAutoCtor == NULL)
{ {
MEMBER_SET(typeDeclaration, mAutoCtor, ctorDecl); MEMBER_SET(typeDeclaration, mAutoCtor, ctorDecl);
@ -9098,7 +9088,7 @@ BfAstNode* BfReducer::CreateTopLevelObject(BfTokenNode* tokenNode, BfAttributeDi
if (child == NULL) if (child == NULL)
break; break;
auto fieldDecl = mAlloc->Alloc<BfEnumEntryDeclaration>(); auto fieldDecl = mAlloc->Alloc<BfEnumEntryDeclaration>();
if (auto tokenNode = BfNodeDynCast<BfTokenNode>(child)) if (auto tokenNode = BfNodeDynCast<BfTokenNode>(child))
{ {
if (tokenNode->mToken == BfToken_LBracket) if (tokenNode->mToken == BfToken_LBracket)
@ -9114,7 +9104,7 @@ BfAstNode* BfReducer::CreateTopLevelObject(BfTokenNode* tokenNode, BfAttributeDi
break; break;
} }
} }
} }
mVisitorPos.MoveNext(); mVisitorPos.MoveNext();
mVisitorPos.Write(fieldDecl); mVisitorPos.Write(fieldDecl);
@ -9351,7 +9341,7 @@ BfCommentNode * BfReducer::FindDocumentation(BfAstNode* defNodeHead, BfAstNode*
return NULL; return NULL;
} }
if ((checkComment->mCommentKind != BfCommentKind_Documentation_Line_Pre) && if ((checkComment->mCommentKind != BfCommentKind_Documentation_Line_Pre) &&
(checkComment->mCommentKind != BfCommentKind_Documentation_Block_Pre)) (checkComment->mCommentKind != BfCommentKind_Documentation_Block_Pre))
{ {
// Skip this, not used // Skip this, not used
@ -9422,7 +9412,7 @@ BfTokenNode* BfReducer::ParseMethodParams(BfAstNode* node, SizedArrayImpl<BfPara
if ((paramIdx == 0) && ( if ((paramIdx == 0) && (
(token == BfToken_In) || (token == BfToken_Out) || (token == BfToken_Ref) || (token == BfToken_Mut) || (token == BfToken_In) || (token == BfToken_Out) || (token == BfToken_Ref) || (token == BfToken_Mut) ||
(token == BfToken_Delegate) || (token == BfToken_Function) || (token == BfToken_Delegate) || (token == BfToken_Function) ||
(token == BfToken_Comptype) || (token == BfToken_Decltype) || (token == BfToken_Comptype) || (token == BfToken_Decltype) ||
(token == BfToken_AllocType) || (token == BfToken_RetType) || (token == BfToken_AllocType) || (token == BfToken_RetType) ||
(token == BfToken_Params) || (token == BfToken_LParen) || (token == BfToken_Params) || (token == BfToken_LParen) ||
(token == BfToken_Var) || (token == BfToken_LBracket) || (token == BfToken_Var) || (token == BfToken_LBracket) ||
@ -9480,7 +9470,7 @@ BfTokenNode* BfReducer::ParseMethodParams(BfAstNode* node, SizedArrayImpl<BfPara
BfToken token = tokenNode->GetToken(); BfToken token = tokenNode->GetToken();
if ((token == BfToken_Var) || (token == BfToken_LParen) || if ((token == BfToken_Var) || (token == BfToken_LParen) ||
(token == BfToken_Delegate) || (token == BfToken_Function) || (token == BfToken_Delegate) || (token == BfToken_Function) ||
(token == BfToken_Comptype) || (token == BfToken_Decltype) || (token == BfToken_Comptype) || (token == BfToken_Decltype) ||
(token == BfToken_AllocType) || (token == BfToken_RetType) || (token == BfToken_AllocType) || (token == BfToken_RetType) ||
(token == BfToken_DotDotDot)) (token == BfToken_DotDotDot))
{ {
@ -9690,7 +9680,7 @@ BfTokenNode* BfReducer::ParseMethodParams(BfAstNode* node, SizedArrayImpl<BfPara
isFunction = true; isFunction = true;
else else
isDelegate = true; isDelegate = true;
} }
else if ((mCurTypeDecl->mTypeNode != NULL) && (mCurTypeDecl->mTypeNode->GetToken() == BfToken_Function)) else if ((mCurTypeDecl->mTypeNode != NULL) && (mCurTypeDecl->mTypeNode->GetToken() == BfToken_Function))
isFunction = true; isFunction = true;
else if ((mCurTypeDecl->mTypeNode != NULL) && (mCurTypeDecl->mTypeNode->GetToken() == BfToken_Delegate)) else if ((mCurTypeDecl->mTypeNode != NULL) && (mCurTypeDecl->mTypeNode->GetToken() == BfToken_Delegate))
@ -9728,13 +9718,13 @@ BfTokenNode* BfReducer::ParseMethodParams(BfAstNode* node, SizedArrayImpl<BfPara
if (nameIdentifierNode != NULL) if (nameIdentifierNode != NULL)
mVisitorPos.MoveNext(); mVisitorPos.MoveNext();
} }
if (nameIdentifierNode != NULL) if (nameIdentifierNode != NULL)
{ {
paramDecl->mNameNode = nameIdentifierNode; paramDecl->mNameNode = nameIdentifierNode;
MoveNode(nameIdentifierNode, paramDecl); MoveNode(nameIdentifierNode, paramDecl);
nameAfterNode = nameIdentifierNode; nameAfterNode = nameIdentifierNode;
} }
} }
node->mSrcEnd = paramDecl->mSrcEnd; node->mSrcEnd = paramDecl->mSrcEnd;
@ -9803,7 +9793,7 @@ bool BfReducer::ParseMethod(BfMethodDeclaration* methodDeclaration, SizedArrayIm
methodDeclaration->mCloseParen = ParseMethodParams(methodDeclaration, params, commas, BfToken_RParen, true); methodDeclaration->mCloseParen = ParseMethodParams(methodDeclaration, params, commas, BfToken_RParen, true);
// RParen // RParen
if (methodDeclaration->mCloseParen == NULL) if (methodDeclaration->mCloseParen == NULL)
{ {
auto nextNode = mVisitorPos.GetNext(); auto nextNode = mVisitorPos.GetNext();
@ -9908,7 +9898,7 @@ bool BfReducer::ParseMethod(BfMethodDeclaration* methodDeclaration, SizedArrayIm
if (ctorDecl->mInitializer != NULL) if (ctorDecl->mInitializer != NULL)
{ {
MEMBER_SET(attribExpr, mExpression, ctorDecl->mInitializer); MEMBER_SET(attribExpr, mExpression, ctorDecl->mInitializer);
} }
MEMBER_SET(ctorDecl, mInitializer, attribExpr); MEMBER_SET(ctorDecl, mInitializer, attribExpr);
} }
} }
@ -10121,44 +10111,44 @@ BfGenericConstraintsDeclaration* BfReducer::CreateGenericConstraintsDeclaration(
// ReplaceNode(tokenNode, genericConstraint); // ReplaceNode(tokenNode, genericConstraint);
// genericConstraint->mWhereToken = tokenNode; // genericConstraint->mWhereToken = tokenNode;
// constraintsDeclaration->mHasExpressions = true; // constraintsDeclaration->mHasExpressions = true;
// //
// genericConstraintsArr.push_back(genericConstraint); // genericConstraintsArr.push_back(genericConstraint);
// //
// auto expr = CreateExpressionAfter(genericConstraint, CreateExprFlags_EarlyExit); // auto expr = CreateExpressionAfter(genericConstraint, CreateExprFlags_EarlyExit);
// if (expr == NULL) // if (expr == NULL)
// break; // break;
// //
// MEMBER_SET(genericConstraint, mExpression, expr); // MEMBER_SET(genericConstraint, mExpression, expr);
// //
// BfTokenNode* nextWhereToken = NULL; // BfTokenNode* nextWhereToken = NULL;
// if (auto checkToken = BfNodeDynCast<BfTokenNode>(mVisitorPos.GetNext())) // if (auto checkToken = BfNodeDynCast<BfTokenNode>(mVisitorPos.GetNext()))
// { // {
// if (checkToken->mToken != BfToken_Where) // if (checkToken->mToken != BfToken_Where)
// nextWhereToken = checkToken; // nextWhereToken = checkToken;
// } // }
// //
// auto nextNode = mVisitorPos.GetNext(); // auto nextNode = mVisitorPos.GetNext();
// if (BfNodeDynCast<BfBlock>(nextNode)) // if (BfNodeDynCast<BfBlock>(nextNode))
// break; // break;
// //
// bool handled = false; // bool handled = false;
// if (auto tokenNode = BfNodeDynCast<BfTokenNode>(nextNode)) // if (auto tokenNode = BfNodeDynCast<BfTokenNode>(nextNode))
// { // {
// if (tokenNode->mToken == BfToken_FatArrow) // if (tokenNode->mToken == BfToken_FatArrow)
// break; // break;
// } // }
// //
// tokenNode = ExpectTokenAfter(genericConstraint, BfToken_LBrace, BfToken_Where, BfToken_Semicolon); // tokenNode = ExpectTokenAfter(genericConstraint, BfToken_LBrace, BfToken_Where, BfToken_Semicolon);
// if (tokenNode == NULL) // if (tokenNode == NULL)
// break; // break;
// //
// BfToken token = tokenNode->GetToken(); // BfToken token = tokenNode->GetToken();
// if (token != BfToken_Where) // if (token != BfToken_Where)
// { // {
// mVisitorPos.mReadPos--; // mVisitorPos.mReadPos--;
// break; // break;
// } // }
// //
// continue; // continue;
// } // }
// } // }
@ -10170,7 +10160,7 @@ BfGenericConstraintsDeclaration* BfReducer::CreateGenericConstraintsDeclaration(
ReplaceNode(tokenNode, genericConstraint); ReplaceNode(tokenNode, genericConstraint);
genericConstraint->mWhereToken = tokenNode; genericConstraint->mWhereToken = tokenNode;
genericConstraintsArr.push_back(genericConstraint); genericConstraintsArr.push_back(genericConstraint);
auto genericParamName = CreateTypeRefAfter(genericConstraint); auto genericParamName = CreateTypeRefAfter(genericConstraint);
if (genericParamName != NULL) if (genericParamName != NULL)
@ -10206,7 +10196,7 @@ BfGenericConstraintsDeclaration* BfReducer::CreateGenericConstraintsDeclaration(
{ {
isDone = true; isDone = true;
break; break;
} }
} }
tokenNode = ExpectTokenAfter(genericConstraint, BfToken_Comma, BfToken_LBrace, BfToken_Where, BfToken_Semicolon); tokenNode = ExpectTokenAfter(genericConstraint, BfToken_Comma, BfToken_LBrace, BfToken_Where, BfToken_Semicolon);
@ -10960,4 +10950,4 @@ BfInlineAsmStatement* BfReducer::CreateInlineAsmStatement(BfAstNode* asmNode)
} }
return asmStatement; return asmStatement;
} }

View file

@ -36,8 +36,8 @@ public:
CreateStmtFlags_NoCaseExpr = 1, CreateStmtFlags_NoCaseExpr = 1,
CreateStmtFlags_FindTrailingSemicolon = 2, CreateStmtFlags_FindTrailingSemicolon = 2,
CreateStmtFlags_AllowUnterminatedExpression = 4, CreateStmtFlags_AllowUnterminatedExpression = 4,
CreateStmtFlags_AllowLocalFunction = 8, CreateStmtFlags_AllowLocalFunction = 8,
CreateStmtFlags_ForceVariableDecl = 0x10, CreateStmtFlags_ForceVariableDecl = 0x10,
CreateStmtFlags_To_CreateExprFlags_Mask = 1 CreateStmtFlags_To_CreateExprFlags_Mask = 1
}; };
@ -127,7 +127,7 @@ public:
} }
}; };
public: public:
BfAstAllocator* mAlloc; BfAstAllocator* mAlloc;
BfSystem* mSystem; BfSystem* mSystem;
BfSource* mSource; BfSource* mSource;
@ -141,12 +141,12 @@ public:
BfMethodDeclaration* mCurMethodDecl; BfMethodDeclaration* mCurMethodDecl;
BfAstNode* mLastBlockNode; BfAstNode* mLastBlockNode;
bool mStmtHasError; bool mStmtHasError;
bool mPrevStmtHadError; bool mPrevStmtHadError;
bool mCompatMode; // Does C++ compatible parsing bool mCompatMode; // Does C++ compatible parsing
bool mAllowTypeWildcard; bool mAllowTypeWildcard;
bool mIsFieldInitializer; bool mIsFieldInitializer;
bool mInParenExpr; bool mInParenExpr;
bool mSkipCurrentNodeAssert; bool mSkipCurrentNodeAssert;
BfVisitorPos mVisitorPos; BfVisitorPos mVisitorPos;
int mDocumentCheckIdx; int mDocumentCheckIdx;
SizedArray<BfNamespaceDeclaration*, 4> mCurNamespaceStack; SizedArray<BfNamespaceDeclaration*, 4> mCurNamespaceStack;
@ -154,15 +154,15 @@ public:
int mAssertCurrentNodeIdx; int mAssertCurrentNodeIdx;
public: public:
BfAstNode* Fail(const StringImpl& errorMsg, BfAstNode* refNode); BfAstNode* Fail(const StringImpl& errorMsg, BfAstNode* refNode);
BfAstNode* FailAfter(const StringImpl& errorMsg, BfAstNode* refNode); BfAstNode* FailAfter(const StringImpl& errorMsg, BfAstNode* refNode);
void AddErrorNode(BfAstNode* astNode, bool removeNode = true); void AddErrorNode(BfAstNode* astNode, bool removeNode = true);
public: public:
bool StringEquals(BfAstNode* node, BfAstNode* node2); bool StringEquals(BfAstNode* node, BfAstNode* node2);
bool IsSemicolon(BfAstNode* node); bool IsSemicolon(BfAstNode* node);
BfTokenNode* ExpectTokenAfter(BfAstNode* node, BfToken token); BfTokenNode* ExpectTokenAfter(BfAstNode* node, BfToken token);
BfTokenNode* ExpectTokenAfter(BfAstNode* node, BfToken tokenA, BfToken tokenB); BfTokenNode* ExpectTokenAfter(BfAstNode* node, BfToken tokenA, BfToken tokenB);
BfTokenNode* ExpectTokenAfter(BfAstNode* node, BfToken tokenA, BfToken tokenB, BfToken tokenC); BfTokenNode* ExpectTokenAfter(BfAstNode* node, BfToken tokenA, BfToken tokenB, BfToken tokenC);
BfTokenNode* ExpectTokenAfter(BfAstNode* node, BfToken tokenA, BfToken tokenB, BfToken tokenC, BfToken tokenD); BfTokenNode* ExpectTokenAfter(BfAstNode* node, BfToken tokenA, BfToken tokenB, BfToken tokenC, BfToken tokenD);
@ -176,8 +176,8 @@ public:
bool IsNodeRelevant(BfAstNode* astNode); bool IsNodeRelevant(BfAstNode* astNode);
bool IsNodeRelevant(BfAstNode* startNode, BfAstNode* endNode); bool IsNodeRelevant(BfAstNode* startNode, BfAstNode* endNode);
void MoveNode(BfAstNode* srcNode, BfAstNode* newOwner); void MoveNode(BfAstNode* srcNode, BfAstNode* newOwner);
void ReplaceNode(BfAstNode* prevNode, BfAstNode* newNode); void ReplaceNode(BfAstNode* prevNode, BfAstNode* newNode);
bool SetProtection(BfAstNode* parentNode, BfAstNode*& protectionNodeRef, BfTokenNode* tokenNode); bool SetProtection(BfAstNode* parentNode, BfAstNode*& protectionNodeRef, BfTokenNode* tokenNode);
BfAstNode* CreateAllocNode(BfTokenNode* newNode); BfAstNode* CreateAllocNode(BfTokenNode* newNode);
BfAstNode* ReplaceTokenStarter(BfAstNode* astNode, int idx = -1, bool allowIn = false); BfAstNode* ReplaceTokenStarter(BfAstNode* astNode, int idx = -1, bool allowIn = false);
@ -195,12 +195,12 @@ public:
void CreateQualifiedNames(BfAstNode* node); void CreateQualifiedNames(BfAstNode* node);
BfFieldDtorDeclaration* CreateFieldDtorDeclaration(BfAstNode* srcNode); BfFieldDtorDeclaration* CreateFieldDtorDeclaration(BfAstNode* srcNode);
BfFieldDeclaration* CreateFieldDeclaration(BfTokenNode* tokenNode, BfTypeReference* typeRef, BfIdentifierNode* nameIdentifier, BfFieldDeclaration* prevFieldDeclaration); BfFieldDeclaration* CreateFieldDeclaration(BfTokenNode* tokenNode, BfTypeReference* typeRef, BfIdentifierNode* nameIdentifier, BfFieldDeclaration* prevFieldDeclaration);
BfAttributeDirective* CreateAttributeDirective(BfTokenNode* startToken); BfAttributeDirective* CreateAttributeDirective(BfTokenNode* startToken);
BfStatement* CreateAttributedStatement(BfTokenNode* tokenNode, CreateStmtFlags createStmtFlags = CreateStmtFlags_None); BfStatement* CreateAttributedStatement(BfTokenNode* tokenNode, CreateStmtFlags createStmtFlags = CreateStmtFlags_None);
BfExpression* CreateAttributedExpression(BfTokenNode* tokenNode, bool onlyAllowIdentifier); BfExpression* CreateAttributedExpression(BfTokenNode* tokenNode, bool onlyAllowIdentifier);
BfDelegateBindExpression* CreateDelegateBindExpression(BfAstNode* allocNode); BfDelegateBindExpression* CreateDelegateBindExpression(BfAstNode* allocNode);
BfLambdaBindExpression* CreateLambdaBindExpression(BfAstNode* allocNode, BfTokenNode* parenToken = NULL); BfLambdaBindExpression* CreateLambdaBindExpression(BfAstNode* allocNode, BfTokenNode* parenToken = NULL);
BfCollectionInitializerExpression* CreateCollectionInitializerExpression(BfBlock* block); BfCollectionInitializerExpression* CreateCollectionInitializerExpression(BfBlock* block);
BfCollectionInitializerExpression* CreateCollectionInitializerExpression(BfTokenNode* openToken); BfCollectionInitializerExpression* CreateCollectionInitializerExpression(BfTokenNode* openToken);
BfObjectCreateExpression* CreateObjectCreateExpression(BfAstNode* allocNode); BfObjectCreateExpression* CreateObjectCreateExpression(BfAstNode* allocNode);
BfScopedInvocationTarget* CreateScopedInvocationTarget(BfAstNode*& targetRef, BfTokenNode* colonToken); BfScopedInvocationTarget* CreateScopedInvocationTarget(BfAstNode*& targetRef, BfTokenNode* colonToken);
@ -225,7 +225,7 @@ public:
BfTypeReference* DoCreateTypeRef(BfAstNode* identifierNode, CreateTypeRefFlags createTypeRefFlags = CreateTypeRefFlags_None, int endNode = -1); BfTypeReference* DoCreateTypeRef(BfAstNode* identifierNode, CreateTypeRefFlags createTypeRefFlags = CreateTypeRefFlags_None, int endNode = -1);
BfTypeReference* CreateTypeRef(BfAstNode* identifierNode, CreateTypeRefFlags createTypeRefFlags = CreateTypeRefFlags_None); BfTypeReference* CreateTypeRef(BfAstNode* identifierNode, CreateTypeRefFlags createTypeRefFlags = CreateTypeRefFlags_None);
BfTypeReference* CreateTypeRefAfter(BfAstNode* astNode, CreateTypeRefFlags createTypeRefFlags = CreateTypeRefFlags_None); BfTypeReference* CreateTypeRefAfter(BfAstNode* astNode, CreateTypeRefFlags createTypeRefFlags = CreateTypeRefFlags_None);
BfTypeReference* CreateRefTypeRef(BfTypeReference* elementType, BfTokenNode* refToken); BfTypeReference* CreateRefTypeRef(BfTypeReference* elementType, BfTokenNode* refToken);
bool ParseMethod(BfMethodDeclaration* methodDeclaration, SizedArrayImpl<BfParameterDeclaration*>* params, SizedArrayImpl<BfTokenNode*>* commas, bool alwaysIncludeBlock = false); bool ParseMethod(BfMethodDeclaration* methodDeclaration, SizedArrayImpl<BfParameterDeclaration*>* params, SizedArrayImpl<BfTokenNode*>* commas, bool alwaysIncludeBlock = false);
BfGenericArgumentsNode* CreateGenericArguments(BfTokenNode* tokenNode, bool allowPartial = false); BfGenericArgumentsNode* CreateGenericArguments(BfTokenNode* tokenNode, bool allowPartial = false);
BfGenericParamsDeclaration* CreateGenericParamsDeclaration(BfTokenNode* tokenNode); BfGenericParamsDeclaration* CreateGenericParamsDeclaration(BfTokenNode* tokenNode);

View file

@ -1,14 +1,14 @@
#include "BfResolvePass.h" #include "BfResolvePass.h"
#include "BfParser.h" #include "BfParser.h"
#include "BfModule.h" #include "BfModule.h"
USING_NS_BF; USING_NS_BF;
BfResolvePassData::BfResolvePassData() BfResolvePassData::BfResolvePassData()
{ {
mGetSymbolReferenceKind = BfGetSymbolReferenceKind_None; mGetSymbolReferenceKind = BfGetSymbolReferenceKind_None;
mSymbolReferenceTypeDef = NULL; mSymbolReferenceTypeDef = NULL;
mSymbolReferenceLocalIdx = -1; mSymbolReferenceLocalIdx = -1;
mSymbolReferenceFieldIdx = -1; mSymbolReferenceFieldIdx = -1;
@ -31,7 +31,7 @@ BfResolvePassData::~BfResolvePassData()
auto parser = emitEntryKV.mValue.mParser; auto parser = emitEntryKV.mValue.mParser;
if (parser != NULL) if (parser != NULL)
{ {
delete parser->mSourceClassifier; delete parser->mSourceClassifier;
parser->mSourceClassifier = NULL; parser->mSourceClassifier = NULL;
parser->mParserFlags = ParserFlag_None; parser->mParserFlags = ParserFlag_None;
parser->mCursorCheckIdx = -1; parser->mCursorCheckIdx = -1;
@ -56,7 +56,7 @@ void BfResolvePassData::RecordReplaceNode(BfAstNode* node)
auto parser = node->GetSourceData()->ToParserData(); auto parser = node->GetSourceData()->ToParserData();
if (node->GetSrcStart() >= parser->mSrcLength) if (node->GetSrcStart() >= parser->mSrcLength)
return; return;
while (true) while (true)
{ {
if (auto qualifiedName = BfNodeDynCast<BfQualifiedNameNode>(node)) if (auto qualifiedName = BfNodeDynCast<BfQualifiedNameNode>(node))
@ -65,35 +65,35 @@ void BfResolvePassData::RecordReplaceNode(BfAstNode* node)
} }
else else
break; break;
} }
RecordReplaceNode(parser, node->GetSrcStart(), node->GetSrcLength()); RecordReplaceNode(parser, node->GetSrcStart(), node->GetSrcLength());
} }
void BfResolvePassData::HandleMethodReference(BfAstNode* node, BfTypeDef* typeDef, BfMethodDef* methodDef) void BfResolvePassData::HandleMethodReference(BfAstNode* node, BfTypeDef* typeDef, BfMethodDef* methodDef)
{ {
if ((mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Method) && (mSymbolReferenceTypeDef == typeDef->GetDefinition()) && if ((mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Method) && (mSymbolReferenceTypeDef == typeDef->GetDefinition()) &&
(mSymbolReferenceMethodIdx == methodDef->mIdx)) (mSymbolReferenceMethodIdx == methodDef->mIdx))
RecordReplaceNode(node); RecordReplaceNode(node);
} }
void BfResolvePassData::HandleFieldReference(BfAstNode* node, BfTypeDef* typeDef, BfFieldDef* fieldDef) void BfResolvePassData::HandleFieldReference(BfAstNode* node, BfTypeDef* typeDef, BfFieldDef* fieldDef)
{ {
if ((mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Field) && (mSymbolReferenceTypeDef == typeDef->GetDefinition()) && if ((mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Field) && (mSymbolReferenceTypeDef == typeDef->GetDefinition()) &&
(mSymbolReferenceFieldIdx == fieldDef->mIdx)) (mSymbolReferenceFieldIdx == fieldDef->mIdx))
RecordReplaceNode(node); RecordReplaceNode(node);
} }
void BfResolvePassData::HandlePropertyReference(BfAstNode* node, BfTypeDef* typeDef, BfPropertyDef* propDef) void BfResolvePassData::HandlePropertyReference(BfAstNode* node, BfTypeDef* typeDef, BfPropertyDef* propDef)
{ {
if ((mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Property) && (mSymbolReferenceTypeDef == typeDef->GetDefinition()) && if ((mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Property) && (mSymbolReferenceTypeDef == typeDef->GetDefinition()) &&
(mSymbolReferencePropertyIdx == propDef->mIdx)) (mSymbolReferencePropertyIdx == propDef->mIdx))
RecordReplaceNode(node); RecordReplaceNode(node);
} }
void BfResolvePassData::HandleLocalReference(BfIdentifierNode* identifier, BfTypeDef* typeDef, BfMethodDef* methodDef, int localVarIdx) void BfResolvePassData::HandleLocalReference(BfIdentifierNode* identifier, BfTypeDef* typeDef, BfMethodDef* methodDef, int localVarIdx)
{ {
if ((mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Local) && (mSymbolReferenceTypeDef == typeDef->GetDefinition()) && if ((mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Local) && (mSymbolReferenceTypeDef == typeDef->GetDefinition()) &&
(mSymbolReferenceMethodIdx == methodDef->mIdx) && (localVarIdx == mSymbolReferenceLocalIdx)) (mSymbolReferenceMethodIdx == methodDef->mIdx) && (localVarIdx == mSymbolReferenceLocalIdx))
RecordReplaceNode(identifier); RecordReplaceNode(identifier);
} }
@ -106,14 +106,14 @@ void BfResolvePassData::HandleTypeGenericParam(BfAstNode* node, BfTypeDef* typeD
void BfResolvePassData::HandleMethodGenericParam(BfAstNode* node, BfTypeDef* typeDef, BfMethodDef* methodDef, int genericParamIdx) void BfResolvePassData::HandleMethodGenericParam(BfAstNode* node, BfTypeDef* typeDef, BfMethodDef* methodDef, int genericParamIdx)
{ {
if ((mGetSymbolReferenceKind == BfGetSymbolReferenceKind_MethodGenericParam) && (mSymbolReferenceTypeDef == typeDef->GetDefinition()) && if ((mGetSymbolReferenceKind == BfGetSymbolReferenceKind_MethodGenericParam) && (mSymbolReferenceTypeDef == typeDef->GetDefinition()) &&
(mSymbolReferenceMethodIdx == methodDef->mIdx) && (genericParamIdx == mSymbolMethodGenericParamIdx)) (mSymbolReferenceMethodIdx == methodDef->mIdx) && (genericParamIdx == mSymbolMethodGenericParamIdx))
RecordReplaceNode(node); RecordReplaceNode(node);
} }
void BfResolvePassData::HandleLocalReference(BfIdentifierNode* identifier, BfIdentifierNode* origNameNode, BfTypeDef* typeDef, BfMethodDef* methodDef, int localVarIdx) void BfResolvePassData::HandleLocalReference(BfIdentifierNode* identifier, BfIdentifierNode* origNameNode, BfTypeDef* typeDef, BfMethodDef* methodDef, int localVarIdx)
{ {
if ((mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Local) && (mSymbolReferenceTypeDef == typeDef->GetDefinition()) && if ((mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Local) && (mSymbolReferenceTypeDef == typeDef->GetDefinition()) &&
(mSymbolReferenceMethodIdx == methodDef->mIdx) && (localVarIdx == mSymbolReferenceLocalIdx)) (mSymbolReferenceMethodIdx == methodDef->mIdx) && (localVarIdx == mSymbolReferenceLocalIdx))
{ {
if (origNameNode == NULL) if (origNameNode == NULL)
@ -122,7 +122,7 @@ void BfResolvePassData::HandleLocalReference(BfIdentifierNode* identifier, BfIde
int origLen = origNameNode->GetSrcLength(); int origLen = origNameNode->GetSrcLength();
int refLen = identifier->GetSrcLength(); int refLen = identifier->GetSrcLength();
// The lengths can be different if we have one or more @'s prepended // The lengths can be different if we have one or more @'s prepended
RecordReplaceNode(identifier->GetSourceData()->ToParserData(), identifier->GetSrcStart() + (refLen - origLen), origLen); RecordReplaceNode(identifier->GetSourceData()->ToParserData(), identifier->GetSrcStart() + (refLen - origLen), origLen);
} }
} }
@ -215,4 +215,4 @@ BfSourceClassifier* BfResolvePassData::GetSourceClassifier(BfParser* parser)
if (parser == NULL) if (parser == NULL)
return NULL; return NULL;
return parser->mSourceClassifier; return parser->mSourceClassifier;
} }

View file

@ -14,7 +14,7 @@ enum BfResolveType
BfResolveType_Autocomplete, BfResolveType_Autocomplete,
BfResolveType_Autocomplete_HighPri, BfResolveType_Autocomplete_HighPri,
BfResolveType_GoToDefinition, BfResolveType_GoToDefinition,
BfResolveType_GetSymbolInfo, BfResolveType_GetSymbolInfo,
BfResolveType_RenameSymbol, BfResolveType_RenameSymbol,
BfResolveType_ShowFileSymbolReferences, BfResolveType_ShowFileSymbolReferences,
BfResolveType_GetNavigationData, BfResolveType_GetNavigationData,
@ -68,14 +68,14 @@ public:
BfAutoComplete* mAutoComplete; BfAutoComplete* mAutoComplete;
Array<BfTypeDef*> mAutoCompleteTempTypes; // Contains multiple values when we have nested types Array<BfTypeDef*> mAutoCompleteTempTypes; // Contains multiple values when we have nested types
Dictionary<BfTypeDef*, BfStaticSearch> mStaticSearchMap; Dictionary<BfTypeDef*, BfStaticSearch> mStaticSearchMap;
Dictionary<BfTypeDef*, BfInternalAccessSet> mInternalAccessMap; Dictionary<BfTypeDef*, BfInternalAccessSet> mInternalAccessMap;
Array<BfAstNode*> mExteriorAutocompleteCheckNodes; Array<BfAstNode*> mExteriorAutocompleteCheckNodes;
BfGetSymbolReferenceKind mGetSymbolReferenceKind; BfGetSymbolReferenceKind mGetSymbolReferenceKind;
String mQueuedReplaceTypeDef; String mQueuedReplaceTypeDef;
BfTypeDef* mSymbolReferenceTypeDef; BfTypeDef* mSymbolReferenceTypeDef;
String mQueuedSymbolReferenceNamespace; String mQueuedSymbolReferenceNamespace;
BfAtomComposite mSymbolReferenceNamespace; BfAtomComposite mSymbolReferenceNamespace;
int mSymbolReferenceLocalIdx; int mSymbolReferenceLocalIdx;
int mSymbolReferenceFieldIdx; int mSymbolReferenceFieldIdx;
int mSymbolReferenceMethodIdx; int mSymbolReferenceMethodIdx;
@ -85,7 +85,7 @@ public:
bool mIsClassifying; bool mIsClassifying;
bool mHasCursorIdx; bool mHasCursorIdx;
bool mHadEmits; bool mHadEmits;
typedef Dictionary<BfParserData*, String> FoundSymbolReferencesParserDataMap; typedef Dictionary<BfParserData*, String> FoundSymbolReferencesParserDataMap;
FoundSymbolReferencesParserDataMap mFoundSymbolReferencesParserData; FoundSymbolReferencesParserDataMap mFoundSymbolReferencesParserData;
//std::vector<BfIdentifierNode*> mSymbolReferenceIdentifiers; //std::vector<BfIdentifierNode*> mSymbolReferenceIdentifiers;
@ -94,7 +94,7 @@ public:
public: public:
void RecordReplaceNode(BfParserData* parser, int srcStart, int srcLen); void RecordReplaceNode(BfParserData* parser, int srcStart, int srcLen);
void RecordReplaceNode(BfAstNode* node); void RecordReplaceNode(BfAstNode* node);
BfAstNode* FindBaseNode(BfAstNode* node); BfAstNode* FindBaseNode(BfAstNode* node);
public: public:
@ -108,7 +108,7 @@ public:
void HandleMethodReference(BfAstNode* node, BfTypeDef* typeDef, BfMethodDef* methodDef); void HandleMethodReference(BfAstNode* node, BfTypeDef* typeDef, BfMethodDef* methodDef);
void HandleFieldReference(BfAstNode* node, BfTypeDef* typeDef, BfFieldDef* fieldDef); void HandleFieldReference(BfAstNode* node, BfTypeDef* typeDef, BfFieldDef* fieldDef);
void HandlePropertyReference(BfAstNode* node, BfTypeDef* typeDef, BfPropertyDef* propDef); void HandlePropertyReference(BfAstNode* node, BfTypeDef* typeDef, BfPropertyDef* propDef);
void HandleTypeReference(BfAstNode* node, BfTypeDef* typeDef); void HandleTypeReference(BfAstNode* node, BfTypeDef* typeDef);
void HandleNamespaceReference(BfAstNode* node, const BfAtomComposite& namespaceName); void HandleNamespaceReference(BfAstNode* node, const BfAtomComposite& namespaceName);
BfSourceClassifier* GetSourceClassifier(BfAstNode* astNode); BfSourceClassifier* GetSourceClassifier(BfAstNode* astNode);

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -16,7 +16,7 @@ BfSource::BfSource(BfSystem* bfSystem)
if (bfSystem != NULL) if (bfSystem != NULL)
mAstAllocManager = &gBfParserCache->mAstAllocManager; mAstAllocManager = &gBfParserCache->mAstAllocManager;
mSrc = NULL; mSrc = NULL;
mSrcLength = 0; mSrcLength = 0;
mSrcAllocSize = -1; mSrcAllocSize = -1;
@ -36,7 +36,7 @@ BfSource::BfSource(BfSystem* bfSystem)
BfSource::~BfSource() BfSource::~BfSource()
{ {
int sourceCount = gSourceCount--; int sourceCount = gSourceCount--;
delete mSourceData; delete mSourceData;
@ -65,7 +65,7 @@ BfErrorNode* BfSource::CreateErrorNode(BfAstNode* astNode)
} }
void BfSource::AddErrorNode(BfAstNode* astNode) void BfSource::AddErrorNode(BfAstNode* astNode)
{ {
mPendingErrorNodes.push_back(CreateErrorNode(astNode)); mPendingErrorNodes.push_back(CreateErrorNode(astNode));
} }
@ -85,10 +85,10 @@ int BfSource::AllocChars(int charCount)
mSrcAllocSize = newAllocSize; mSrcAllocSize = newAllocSize;
BF_ASSERT(mSourceData->ToParser() != NULL); BF_ASSERT(mSourceData->ToParser() != NULL);
mSourceData->mSrc = mSrc; mSourceData->mSrc = mSrc;
HadSrcRealloc(); HadSrcRealloc();
} }
int retVal = mSrcLength; int retVal = mSrcLength;
mSrcLength += charCount; mSrcLength += charCount;
@ -130,7 +130,7 @@ void BfSource::FinishSideNodes()
} }
void BfSource::Close() void BfSource::Close()
{ {
// if (mAlloc->mSource == NULL) // if (mAlloc->mSource == NULL)
// { // {
// BF_ASSERT(mErrorRootNode == NULL); // BF_ASSERT(mErrorRootNode == NULL);
@ -149,4 +149,4 @@ void BfSource::Close()
} }
mIsClosed = true; mIsClosed = true;
} }

View file

@ -21,7 +21,7 @@ public:
ExternalNodesState_Failed ExternalNodesState_Failed
}; };
public: public:
const char* mSrc; const char* mSrc;
int mSrcLength; int mSrcLength;
BfAstAllocManager* mAstAllocManager; BfAstAllocManager* mAstAllocManager;
@ -30,7 +30,7 @@ public:
BfRootNode* mSidechannelRootNode; // Holds comments and preprocessor nodes BfRootNode* mSidechannelRootNode; // Holds comments and preprocessor nodes
BfRootNode* mRootNode; BfRootNode* mRootNode;
BfRootNode* mErrorRootNode; BfRootNode* mErrorRootNode;
BfSizedArray<BfExteriorNode> mExteriorNodes; BfSizedArray<BfExteriorNode> mExteriorNodes;
int mExteriorNodesCheckIdx; // 0 = unchecked, -1 = failed, >0 means success and equals the BfSystem.mTypesIdx int mExteriorNodesCheckIdx; // 0 = unchecked, -1 = failed, >0 means success and equals the BfSystem.mTypesIdx
@ -76,7 +76,7 @@ public:
BfAstAllocator* mAlloc; BfAstAllocator* mAlloc;
const char* mSrc; const char* mSrc;
int mSrcLength; int mSrcLength;
int mSrcAllocSize; int mSrcAllocSize;
bool mParsingFailed; bool mParsingFailed;
bool mIsClosed; bool mIsClosed;
uint8* mAstScratch; uint8* mAstScratch;
@ -86,28 +86,28 @@ public:
BfRootNode* mSidechannelRootNode; // Holds comments and preprocessor nodes BfRootNode* mSidechannelRootNode; // Holds comments and preprocessor nodes
BfRootNode* mRootNode; BfRootNode* mRootNode;
BfRootNode* mErrorRootNode; BfRootNode* mErrorRootNode;
BfParser* mNextRevision; BfParser* mNextRevision;
BfParser* mPrevRevision; BfParser* mPrevRevision;
SizedArray<BfAstNode*, 8> mPendingSideNodes; SizedArray<BfAstNode*, 8> mPendingSideNodes;
SizedArray<BfAstNode*, 8> mPendingErrorNodes; SizedArray<BfAstNode*, 8> mPendingErrorNodes;
public: public:
bool WantsStats(); bool WantsStats();
public: public:
BfSource(BfSystem* bfSystem); BfSource(BfSystem* bfSystem);
virtual ~BfSource(); virtual ~BfSource();
virtual BfParser* ToParser() { return NULL; } virtual BfParser* ToParser() { return NULL; }
virtual void HadSrcRealloc() {} virtual void HadSrcRealloc() {}
BfErrorNode* CreateErrorNode(BfAstNode* astNode); BfErrorNode* CreateErrorNode(BfAstNode* astNode);
void AddErrorNode(BfAstNode* astNode); void AddErrorNode(BfAstNode* astNode);
int AllocChars(int charCount); int AllocChars(int charCount);
void FinishSideNodes(); void FinishSideNodes();
virtual void Close(); // Writing done, return unused pages but retain used pages virtual void Close(); // Writing done, return unused pages but retain used pages
}; };
NS_BF_END; NS_BF_END;

View file

@ -8,7 +8,7 @@ BfSourceClassifier::BfSourceClassifier(BfParser* bfParser, CharData* charData)
{ {
mParser = bfParser; mParser = bfParser;
mCharData = charData; mCharData = charData;
mSkipMethodInternals = false; mSkipMethodInternals = false;
mSkipTypeDeclarations = false; mSkipTypeDeclarations = false;
mSkipAttributes = false; mSkipAttributes = false;
mIsSideChannel = false; mIsSideChannel = false;
@ -23,7 +23,7 @@ BfSourceClassifier::BfSourceClassifier(BfParser* bfParser, CharData* charData)
void BfSourceClassifier::ModifyFlags(BfAstNode* node, uint8 andFlags, uint8 orFlags) void BfSourceClassifier::ModifyFlags(BfAstNode* node, uint8 andFlags, uint8 orFlags)
{ {
if (node != NULL) if (node != NULL)
{ {
ModifyFlags(node->GetSrcStart(), node->GetSrcEnd(), andFlags, orFlags); ModifyFlags(node->GetSrcStart(), node->GetSrcEnd(), andFlags, orFlags);
} }
} }
@ -35,8 +35,8 @@ void BfSourceClassifier::ModifyFlags(int startPos, int endPos, uint8 andFlags, u
endPos = std::min(endPos, mParser->mOrigSrcLength); endPos = std::min(endPos, mParser->mOrigSrcLength);
for (int i = startPos; i < endPos; i++) for (int i = startPos; i < endPos; i++)
{ {
mCharData[i].mDisplayPassId = mClassifierPassId; mCharData[i].mDisplayPassId = mClassifierPassId;
mCharData[i].mDisplayFlags = (mCharData[i].mDisplayFlags & andFlags) | orFlags; mCharData[i].mDisplayFlags = (mCharData[i].mDisplayFlags & andFlags) | orFlags;
} }
} }
@ -62,13 +62,13 @@ void BfSourceClassifier::SetElementType(BfAstNode * node, BfTypeCode typeCode)
} }
void BfSourceClassifier::SetHighestElementType(int startPos, int endPos, BfSourceElementType elementType) void BfSourceClassifier::SetHighestElementType(int startPos, int endPos, BfSourceElementType elementType)
{ {
if (!mEnabled) if (!mEnabled)
return; return;
endPos = BF_MIN(endPos, mParser->mOrigSrcLength); endPos = BF_MIN(endPos, mParser->mOrigSrcLength);
for (int i = startPos; i < endPos; i++) for (int i = startPos; i < endPos; i++)
{ {
auto& charData = mCharData[i]; auto& charData = mCharData[i];
charData.mDisplayPassId = mClassifierPassId; charData.mDisplayPassId = mClassifierPassId;
charData.mDisplayTypeId = BF_MAX(charData.mDisplayTypeId, (uint8)elementType); charData.mDisplayTypeId = BF_MAX(charData.mDisplayTypeId, (uint8)elementType);
@ -100,15 +100,15 @@ void BfSourceClassifier::VisitMembers(BfBlock* node)
{ {
mPrevNode = NULL; mPrevNode = NULL;
for (auto& childNodeRef : *node) for (auto& childNodeRef : *node)
{ {
BfAstNode* child = childNodeRef; BfAstNode* child = childNodeRef;
child->Accept(this); child->Accept(this);
mPrevNode = child; mPrevNode = child;
} }
} }
bool BfSourceClassifier::IsInterestedInMember(BfAstNode* node, bool forceSkip) bool BfSourceClassifier::IsInterestedInMember(BfAstNode* node, bool forceSkip)
{ {
if ((mSkipMethodInternals || forceSkip) && (mParser->mCursorIdx != -1) && if ((mSkipMethodInternals || forceSkip) && (mParser->mCursorIdx != -1) &&
(!node->Contains(mParser->mCursorIdx, 1, 0))) (!node->Contains(mParser->mCursorIdx, 1, 0)))
return false; return false;
@ -121,16 +121,16 @@ void BfSourceClassifier::HandleLeafNode(BfAstNode* node)
return; return;
int nodeStart = node->GetSrcStart(); int nodeStart = node->GetSrcStart();
int srcStart = nodeStart; int srcStart = nodeStart;
int triviaStart = node->GetTriviaStart(); int triviaStart = node->GetTriviaStart();
if (triviaStart != -1) if (triviaStart != -1)
{ {
srcStart = triviaStart; srcStart = triviaStart;
if ((mIsSideChannel) && (mPrevNode != NULL)) if ((mIsSideChannel) && (mPrevNode != NULL))
srcStart = std::max(mPrevNode->GetSrcEnd(), srcStart); srcStart = std::max(mPrevNode->GetSrcEnd(), srcStart);
} }
if (nodeStart != srcStart) if (nodeStart != srcStart)
SetElementType(srcStart, nodeStart, BfSourceElementType_Normal); SetElementType(srcStart, nodeStart, BfSourceElementType_Normal);
//SetElementType(srcStart, node->GetSrcEnd(), BfSourceElementType_Normal); //SetElementType(srcStart, node->GetSrcEnd(), BfSourceElementType_Normal);
@ -140,7 +140,6 @@ void BfSourceClassifier::HandleLeafNode(BfAstNode* node)
void BfSourceClassifier::Visit(BfAstNode* node) void BfSourceClassifier::Visit(BfAstNode* node)
{ {
} }
void BfSourceClassifier::Visit(BfErrorNode* errorNode) void BfSourceClassifier::Visit(BfErrorNode* errorNode)
@ -153,7 +152,7 @@ void BfSourceClassifier::Visit(BfFieldDeclaration* fieldDecl)
{ {
if (!IsInterestedInMember(fieldDecl)) if (!IsInterestedInMember(fieldDecl))
return; return;
BfElementVisitor::Visit(fieldDecl); BfElementVisitor::Visit(fieldDecl);
VisitChild(fieldDecl->mConstSpecifier); VisitChild(fieldDecl->mConstSpecifier);
@ -188,12 +187,12 @@ void BfSourceClassifier::Visit(BfPreprocessorNode* preprocessorNode)
if (!mPreserveFlags) if (!mPreserveFlags)
ModifyFlags(preprocessorNode, ~BfSourceElementFlag_CompilerFlags_Mask, 0); ModifyFlags(preprocessorNode, ~BfSourceElementFlag_CompilerFlags_Mask, 0);
SetElementType(preprocessorNode, BfSourceElementType_Normal); SetElementType(preprocessorNode, BfSourceElementType_Normal);
Visit(preprocessorNode->ToBase()); Visit(preprocessorNode->ToBase());
} }
void BfSourceClassifier::Visit(BfCommentNode* commentNode) void BfSourceClassifier::Visit(BfCommentNode* commentNode)
{ {
HandleLeafNode(commentNode); HandleLeafNode(commentNode);
Visit(commentNode->ToBase()); Visit(commentNode->ToBase());
@ -236,7 +235,7 @@ void BfSourceClassifier::Visit(BfAttributeDirective* attributeDirective)
} }
} }
BfElementVisitor::Visit(attributeDirective); BfElementVisitor::Visit(attributeDirective);
VisitChild(attributeDirective->mAttrCloseToken); VisitChild(attributeDirective->mAttrCloseToken);
@ -262,7 +261,7 @@ void BfSourceClassifier::Visit(BfAttributeDirective* attributeDirective)
for (auto& arg : attributeDirective->mArguments) for (auto& arg : attributeDirective->mArguments)
VisitChild(arg); VisitChild(arg);
for (auto& comma : attributeDirective->mCommas) for (auto& comma : attributeDirective->mCommas)
VisitChild(comma); VisitChild(comma);
VisitChild(attributeDirective->mNextAttribute); VisitChild(attributeDirective->mNextAttribute);
} }
@ -280,7 +279,7 @@ void BfSourceClassifier::Visit(BfIdentifierNode* identifier)
} }
void BfSourceClassifier::Visit(BfQualifiedNameNode* qualifiedName) void BfSourceClassifier::Visit(BfQualifiedNameNode* qualifiedName)
{ {
Visit((BfAstNode*)qualifiedName); Visit((BfAstNode*)qualifiedName);
VisitChild(qualifiedName->mLeft); VisitChild(qualifiedName->mLeft);
@ -406,11 +405,11 @@ void BfSourceClassifier::Visit(BfLiteralExpression* literalExpr)
void BfSourceClassifier::Visit(BfStringInterpolationExpression* stringInterpolationExpression) void BfSourceClassifier::Visit(BfStringInterpolationExpression* stringInterpolationExpression)
{ {
HandleLeafNode(stringInterpolationExpression); HandleLeafNode(stringInterpolationExpression);
Visit(stringInterpolationExpression->ToBase()); Visit(stringInterpolationExpression->ToBase());
SetElementType(stringInterpolationExpression, BfSourceElementType_Literal); SetElementType(stringInterpolationExpression, BfSourceElementType_Literal);
VisitChild(stringInterpolationExpression->mAllocNode); VisitChild(stringInterpolationExpression->mAllocNode);
for (auto& expr : stringInterpolationExpression->mExpressions) for (auto& expr : stringInterpolationExpression->mExpressions)
{ {
SetElementType(expr, BfSourceElementType_Normal); SetElementType(expr, BfSourceElementType_Normal);
@ -423,7 +422,7 @@ void BfSourceClassifier::Visit(BfTokenNode* tokenNode)
HandleLeafNode(tokenNode); HandleLeafNode(tokenNode);
Visit(tokenNode->ToBase()); Visit(tokenNode->ToBase());
if (BfTokenIsKeyword(tokenNode->GetToken())) if (BfTokenIsKeyword(tokenNode->GetToken()))
SetElementType(tokenNode, BfSourceElementType_Keyword); SetElementType(tokenNode, BfSourceElementType_Keyword);
else else
@ -436,15 +435,15 @@ void BfSourceClassifier::Visit(BfInvocationExpression* invocationExpr)
Visit(invocationExpr->ToBase()); Visit(invocationExpr->ToBase());
//BP_ZONE("BfSourceClassifier BfInvocationExpression"); //BP_ZONE("BfSourceClassifier BfInvocationExpression");
BfAstNode* target = invocationExpr->mTarget; BfAstNode* target = invocationExpr->mTarget;
if (target == NULL) if (target == NULL)
return; return;
VisitChild(invocationExpr->mOpenParen); VisitChild(invocationExpr->mOpenParen);
VisitChild(invocationExpr->mCloseParen); VisitChild(invocationExpr->mCloseParen);
VisitChild(invocationExpr->mGenericArgs); VisitChild(invocationExpr->mGenericArgs);
if (auto scopedTarget = BfNodeDynCast<BfScopedInvocationTarget>(target)) if (auto scopedTarget = BfNodeDynCast<BfScopedInvocationTarget>(target))
{ {
VisitChild(target); VisitChild(target);
@ -458,27 +457,27 @@ void BfSourceClassifier::Visit(BfInvocationExpression* invocationExpr)
VisitChild(qualifiedName->mLeft); VisitChild(qualifiedName->mLeft);
VisitChild(qualifiedName->mDot); VisitChild(qualifiedName->mDot);
VisitChild(qualifiedName->mRight); VisitChild(qualifiedName->mRight);
identifier = qualifiedName->mRight; identifier = qualifiedName->mRight;
} }
else if ((identifier = BfNodeDynCast<BfIdentifierNode>(target))) else if ((identifier = BfNodeDynCast<BfIdentifierNode>(target)))
{ {
VisitChild(target); VisitChild(target);
// Leave as BfAttributedIdentifierNode if that's the case // Leave as BfAttributedIdentifierNode if that's the case
identifier = target; identifier = target;
} }
else if (auto qualifiedName = BfNodeDynCast<BfQualifiedNameNode>(target)) else if (auto qualifiedName = BfNodeDynCast<BfQualifiedNameNode>(target))
{ {
VisitChild(qualifiedName->mLeft); VisitChild(qualifiedName->mLeft);
VisitChild(qualifiedName->mDot); VisitChild(qualifiedName->mDot);
VisitChild(qualifiedName->mRight); VisitChild(qualifiedName->mRight);
identifier = qualifiedName->mRight; identifier = qualifiedName->mRight;
} }
else if (auto memberRefExpr = BfNodeDynCast<BfMemberReferenceExpression>(target)) else if (auto memberRefExpr = BfNodeDynCast<BfMemberReferenceExpression>(target))
{ {
VisitChild(memberRefExpr->mTarget); VisitChild(memberRefExpr->mTarget);
VisitChild(memberRefExpr->mDotToken); VisitChild(memberRefExpr->mDotToken);
VisitChild(memberRefExpr->mMemberName); VisitChild(memberRefExpr->mMemberName);
identifier = memberRefExpr->mMemberName; identifier = memberRefExpr->mMemberName;
} }
else else
{ {
@ -490,9 +489,9 @@ void BfSourceClassifier::Visit(BfInvocationExpression* invocationExpr)
if (auto attrIdentifier = BfNodeDynCast<BfAttributedIdentifierNode>(identifier)) if (auto attrIdentifier = BfNodeDynCast<BfAttributedIdentifierNode>(identifier))
{ {
VisitChild(attrIdentifier->mAttributes); VisitChild(attrIdentifier->mAttributes);
identifier = attrIdentifier->mIdentifier; identifier = attrIdentifier->mIdentifier;
} }
if (identifier != NULL) if (identifier != NULL)
SetElementType(identifier, BfSourceElementType_Method); SetElementType(identifier, BfSourceElementType_Method);
} }
@ -551,7 +550,7 @@ void BfSourceClassifier::Visit(BfDestructorDeclaration* dtorDeclaration)
} }
void BfSourceClassifier::Visit(BfMethodDeclaration* methodDeclaration) void BfSourceClassifier::Visit(BfMethodDeclaration* methodDeclaration)
{ {
if (!IsInterestedInMember(methodDeclaration)) if (!IsInterestedInMember(methodDeclaration))
return; return;
@ -559,8 +558,8 @@ void BfSourceClassifier::Visit(BfMethodDeclaration* methodDeclaration)
SetAndRestoreValue<BfAstNode*> prevMember(mCurMember, methodDeclaration); SetAndRestoreValue<BfAstNode*> prevMember(mCurMember, methodDeclaration);
BfElementVisitor::Visit(methodDeclaration); BfElementVisitor::Visit(methodDeclaration);
SetElementType(methodDeclaration->mNameNode, BfSourceElementType_Method); SetElementType(methodDeclaration->mNameNode, BfSourceElementType_Method);
if (methodDeclaration->mGenericParams != NULL) if (methodDeclaration->mGenericParams != NULL)
@ -582,7 +581,7 @@ void BfSourceClassifier::Visit(BfMethodDeclaration* methodDeclaration)
if (typeRef != NULL) if (typeRef != NULL)
{ {
if (auto namedTypeRef = BfNodeDynCast<BfNamedTypeReference>(typeRef)) if (auto namedTypeRef = BfNodeDynCast<BfNamedTypeReference>(typeRef))
SetElementType(typeRef, BfSourceElementType_GenericParam); SetElementType(typeRef, BfSourceElementType_GenericParam);
else else
VisitChild(typeRef); VisitChild(typeRef);
} }
@ -651,7 +650,7 @@ void BfSourceClassifier::Handle(BfTypeDeclaration* typeDeclaration)
llvm::SmallVector<BfTypeReference*, 2> mBaseClasses; llvm::SmallVector<BfTypeReference*, 2> mBaseClasses;
llvm::SmallVector<BfAstNode*, 2> mBaseClassCommas; llvm::SmallVector<BfAstNode*, 2> mBaseClassCommas;
if (typeDeclaration->mGenericParams != NULL) if (typeDeclaration->mGenericParams != NULL)
{ {
for (auto& genericParam : typeDeclaration->mGenericParams->mGenericParams) for (auto& genericParam : typeDeclaration->mGenericParams->mGenericParams)
@ -712,7 +711,7 @@ void BfSourceClassifier::Visit(BfTypeAliasDeclaration* typeDeclaration)
if (typeDeclaration->mIgnoreDeclaration) if (typeDeclaration->mIgnoreDeclaration)
return; return;
BfElementVisitor::Visit(typeDeclaration); BfElementVisitor::Visit(typeDeclaration);
} }
void BfSourceClassifier::Visit(BfUsingDirective* usingDirective) void BfSourceClassifier::Visit(BfUsingDirective* usingDirective)
@ -735,7 +734,7 @@ void BfSourceClassifier::Visit(BfUsingDirective* usingDirective)
void BfSourceClassifier::Visit(BfUsingModDirective* usingDirective) void BfSourceClassifier::Visit(BfUsingModDirective* usingDirective)
{ {
BfElementVisitor::Visit(usingDirective); BfElementVisitor::Visit(usingDirective);
} }
void BfSourceClassifier::Visit(BfNamespaceDeclaration* namespaceDeclaration) void BfSourceClassifier::Visit(BfNamespaceDeclaration* namespaceDeclaration)
@ -760,7 +759,7 @@ bool BfSourceClassifier::WantsSkipParentMethod(BfAstNode* node)
{ {
if (!mSkipMethodInternals) if (!mSkipMethodInternals)
return false; return false;
#ifdef BF_AST_HAS_PARENT_MEMBER #ifdef BF_AST_HAS_PARENT_MEMBER
if (node->mParent->IsA<BfMethodDeclaration>()) if (node->mParent->IsA<BfMethodDeclaration>())
{ {
@ -798,7 +797,7 @@ void BfSourceClassifier::Visit(BfGenericConstraintsDeclaration* genericConstrain
} }
void BfSourceClassifier::Visit(BfBlock* block) void BfSourceClassifier::Visit(BfBlock* block)
{ {
if (WantsSkipParentMethod(block)) if (WantsSkipParentMethod(block))
return; return;
if (block->mOpenBrace != NULL) if (block->mOpenBrace != NULL)
@ -813,7 +812,7 @@ void BfSourceClassifier::Visit(BfRootNode* rootNode)
// Clear off the flags at the end // Clear off the flags at the end
ModifyFlags(mParser->mRootNode->GetSrcEnd(), mParser->mOrigSrcLength, 0, 0); ModifyFlags(mParser->mRootNode->GetSrcEnd(), mParser->mOrigSrcLength, 0, 0);
VisitMembers(rootNode); VisitMembers(rootNode);
} }
void BfSourceClassifier::Visit(BfInlineAsmStatement* asmStmt) void BfSourceClassifier::Visit(BfInlineAsmStatement* asmStmt)
@ -822,7 +821,7 @@ void BfSourceClassifier::Visit(BfInlineAsmStatement* asmStmt)
Visit(asmStmt->mOpenBrace); Visit(asmStmt->mOpenBrace);
if (asmStmt->mCloseBrace != NULL) if (asmStmt->mCloseBrace != NULL)
Visit(asmStmt->mCloseBrace); Visit(asmStmt->mCloseBrace);
//VisitMembers(asmStmt); //VisitMembers(asmStmt);
} }

View file

@ -12,7 +12,7 @@ enum BfSourceElementType
BfSourceElementType_Normal, BfSourceElementType_Normal,
BfSourceElementType_Keyword, BfSourceElementType_Keyword,
BfSourceElementType_Literal, BfSourceElementType_Literal,
BfSourceElementType_Identifier, BfSourceElementType_Identifier,
BfSourceElementType_Comment, BfSourceElementType_Comment,
BfSourceElementType_Method, BfSourceElementType_Method,
BfSourceElementType_Type, BfSourceElementType_Type,
@ -48,7 +48,7 @@ class BfSourceClassifier : public BfElementVisitor
public: public:
struct CharData struct CharData
{ {
char mChar; char mChar;
uint8 mDisplayPassId; uint8 mDisplayPassId;
uint8 mDisplayTypeId; uint8 mDisplayTypeId;
uint8 mDisplayFlags; uint8 mDisplayFlags;
@ -58,8 +58,8 @@ public:
}; };
public: public:
BfParser* mParser; BfParser* mParser;
CharData* mCharData; CharData* mCharData;
bool mEnabled; bool mEnabled;
bool mSkipMethodInternals; bool mSkipMethodInternals;
bool mSkipTypeDeclarations; bool mSkipTypeDeclarations;
@ -96,7 +96,7 @@ public:
virtual void Visit(BfGenericConstraintsDeclaration* genericConstraints) override; virtual void Visit(BfGenericConstraintsDeclaration* genericConstraints) override;
virtual void Visit(BfAstNode* node) override; virtual void Visit(BfAstNode* node) override;
virtual void Visit(BfErrorNode* errorNode) override; virtual void Visit(BfErrorNode* errorNode) override;
virtual void Visit(BfFieldDeclaration* fieldDecl) override; virtual void Visit(BfFieldDeclaration* fieldDecl) override;
virtual void Visit(BfFieldDtorDeclaration* fieldDtorDecl) override; virtual void Visit(BfFieldDtorDeclaration* fieldDtorDecl) override;
virtual void Visit(BfPreprocesorIgnoredSectionNode* preprocesorIgnoredSection) override; virtual void Visit(BfPreprocesorIgnoredSectionNode* preprocesorIgnoredSection) override;
@ -104,10 +104,10 @@ public:
virtual void Visit(BfCommentNode* commentNode) override; virtual void Visit(BfCommentNode* commentNode) override;
virtual void Visit(BfAttributeDirective* attributeDirective) override; virtual void Visit(BfAttributeDirective* attributeDirective) override;
virtual void Visit(BfIdentifierNode* identifier) override; virtual void Visit(BfIdentifierNode* identifier) override;
virtual void Visit(BfQualifiedNameNode* identifier) override; virtual void Visit(BfQualifiedNameNode* identifier) override;
virtual void Visit(BfThisExpression* thisExpr) override; virtual void Visit(BfThisExpression* thisExpr) override;
virtual void Visit(BfBaseExpression* baseExpr) override; virtual void Visit(BfBaseExpression* baseExpr) override;
virtual void Visit(BfMemberReferenceExpression* memberRefExpr) override; virtual void Visit(BfMemberReferenceExpression* memberRefExpr) override;
virtual void Visit(BfQualifiedTypeReference* qualifiedType) override; virtual void Visit(BfQualifiedTypeReference* qualifiedType) override;
virtual void Visit(BfRefTypeRef* typeRef) override; virtual void Visit(BfRefTypeRef* typeRef) override;
virtual void Visit(BfArrayTypeRef* arrayType) override; virtual void Visit(BfArrayTypeRef* arrayType) override;
@ -118,11 +118,11 @@ public:
virtual void Visit(BfLiteralExpression* literalExpr) override; virtual void Visit(BfLiteralExpression* literalExpr) override;
virtual void Visit(BfStringInterpolationExpression* stringInterpolationExpression) override; virtual void Visit(BfStringInterpolationExpression* stringInterpolationExpression) override;
virtual void Visit(BfTokenNode* tokenNode) override; virtual void Visit(BfTokenNode* tokenNode) override;
virtual void Visit(BfInvocationExpression* invocationExpr) override; virtual void Visit(BfInvocationExpression* invocationExpr) override;
virtual void Visit(BfIndexerExpression* indexerExpr) override; virtual void Visit(BfIndexerExpression* indexerExpr) override;
virtual void Visit(BfConstructorDeclaration* ctorDeclaration) override; virtual void Visit(BfConstructorDeclaration* ctorDeclaration) override;
virtual void Visit(BfDestructorDeclaration* dtorDeclaration) override; virtual void Visit(BfDestructorDeclaration* dtorDeclaration) override;
virtual void Visit(BfMethodDeclaration* methodDeclaration) override; virtual void Visit(BfMethodDeclaration* methodDeclaration) override;
virtual void Visit(BfPropertyMethodDeclaration* propertyMethodDeclaration) override; virtual void Visit(BfPropertyMethodDeclaration* propertyMethodDeclaration) override;
virtual void Visit(BfPropertyDeclaration* propertyDeclaration) override; virtual void Visit(BfPropertyDeclaration* propertyDeclaration) override;
virtual void Visit(BfTypeDeclaration* typeDeclaration) override; virtual void Visit(BfTypeDeclaration* typeDeclaration) override;

View file

@ -13,5 +13,5 @@ BfSourcePositionFinder::BfSourcePositionFinder(BfParser* bfParser, int findPosit
void BfSourcePositionFinder::Visit(BfAstNode* node) void BfSourcePositionFinder::Visit(BfAstNode* node)
{ {
if ((mFindPosition >= node->GetSrcStart()) && (mFindPosition <= node->GetSrcEnd())) if ((mFindPosition >= node->GetSrcStart()) && (mFindPosition <= node->GetSrcEnd()))
mClosestElement = node; mClosestElement = node;
} }

View file

@ -16,7 +16,7 @@ public:
BfSourcePositionFinder(BfParser* bfParser, int findPosition); BfSourcePositionFinder(BfParser* bfParser, int findPosition);
using BfStructuralVisitor::Visit; using BfStructuralVisitor::Visit;
virtual void Visit(BfAstNode* node) override; virtual void Visit(BfAstNode* node) override;
}; };
NS_BF_END NS_BF_END

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -56,7 +56,7 @@ public:
uint32 mAtomUpdateIdx; uint32 mAtomUpdateIdx;
bool mIsSystemType; bool mIsSystemType;
Dictionary<BfAtom*, int> mPrevNamesMap; Dictionary<BfAtom*, int> mPrevNamesMap;
public: public:
~BfAtom(); ~BfAtom();
const StringView& ToString() const StringView& ToString()
@ -68,7 +68,7 @@ public:
str += mString; str += mString;
} }
void Ref(); void Ref();
}; };
class BfAtomComposite class BfAtomComposite
@ -80,15 +80,15 @@ public:
bool mOwns; bool mOwns;
public: public:
BfAtomComposite(); BfAtomComposite();
BfAtomComposite(BfAtomComposite&& rhs); BfAtomComposite(BfAtomComposite&& rhs);
BfAtomComposite(const BfAtomComposite& rhs); BfAtomComposite(const BfAtomComposite& rhs);
BfAtomComposite(BfAtom* atom); BfAtomComposite(BfAtom* atom);
BfAtomComposite(const BfAtomComposite& left, const BfAtomComposite& right); BfAtomComposite(const BfAtomComposite& left, const BfAtomComposite& right);
BfAtomComposite(const BfAtomComposite& left, BfAtom* right); BfAtomComposite(const BfAtomComposite& left, BfAtom* right);
~BfAtomComposite(); ~BfAtomComposite();
void Set(const BfAtomComposite& left, const BfAtomComposite& right); void Set(const BfAtomComposite& left, const BfAtomComposite& right);
void Set(BfAtom** atomsA, int countA, BfAtom** atomsB, int countB); void Set(BfAtom** atomsA, int countA, BfAtom** atomsB, int countB);
BfAtomComposite& operator=(const BfAtomComposite& rhs); BfAtomComposite& operator=(const BfAtomComposite& rhs);
bool operator==(const BfAtomComposite& other) const; bool operator==(const BfAtomComposite& other) const;
@ -102,7 +102,7 @@ public:
bool EndsWith(const BfAtomComposite& other) const; bool EndsWith(const BfAtomComposite& other) const;
BfAtomComposite GetSub(int start, int len) const; BfAtomComposite GetSub(int start, int len) const;
void Reference(const BfAtomComposite& other); void Reference(const BfAtomComposite& other);
uint32 GetAtomUpdateIdx(); uint32 GetAtomUpdateIdx();
}; };
@ -138,17 +138,17 @@ class BfSizedAtomComposite : public BfAtomComposite
public: public:
BfAtom* mInitialAlloc[8]; BfAtom* mInitialAlloc[8];
BfSizedAtomComposite(); BfSizedAtomComposite();
~BfSizedAtomComposite(); ~BfSizedAtomComposite();
}; };
struct BfAtomCompositeHash struct BfAtomCompositeHash
{ {
size_t operator()(const BfAtomComposite& composite) const size_t operator()(const BfAtomComposite& composite) const
{ {
int curHash = 0; int curHash = 0;
for (int i = 0; i < (int)composite.mSize; i++) for (int i = 0; i < (int)composite.mSize; i++)
curHash = ((curHash ^ (int)(intptr)composite.mParts[i]->mHash) << 5) - curHash; curHash = ((curHash ^ (int)(intptr)composite.mParts[i]->mHash) << 5) - curHash;
return curHash; return curHash;
} }
}; };
@ -179,7 +179,7 @@ enum BfCompilerOptionFlags
BfCompilerOptionFlag_EmitLineInfo = 2, BfCompilerOptionFlag_EmitLineInfo = 2,
BfCompilerOptionFlag_WriteIR = 4, BfCompilerOptionFlag_WriteIR = 4,
BfCompilerOptionFlag_GenerateOBJ = 8, BfCompilerOptionFlag_GenerateOBJ = 8,
BfCompilerOptionFlag_GenerateBitcode = 0x10, BfCompilerOptionFlag_GenerateBitcode = 0x10,
BfCompilerOptionFlag_ClearLocalVars = 0x20, BfCompilerOptionFlag_ClearLocalVars = 0x20,
BfCompilerOptionFlag_RuntimeChecks = 0x40, BfCompilerOptionFlag_RuntimeChecks = 0x40,
BfCompilerOptionFlag_EmitDynamicCastCheck = 0x80, BfCompilerOptionFlag_EmitDynamicCastCheck = 0x80,
@ -190,7 +190,7 @@ enum BfCompilerOptionFlags
BfCompilerOptionFlag_EnableSideStack = 0x1000, BfCompilerOptionFlag_EnableSideStack = 0x1000,
BfCompilerOptionFlag_EnableHotSwapping = 0x2000, BfCompilerOptionFlag_EnableHotSwapping = 0x2000,
BfCompilerOptionFlag_IncrementalBuild = 0x4000, BfCompilerOptionFlag_IncrementalBuild = 0x4000,
BfCompilerOptionFlag_DebugAlloc = 0x8000, BfCompilerOptionFlag_DebugAlloc = 0x8000,
BfCompilerOptionFlag_OmitDebugHelpers = 0x10000, BfCompilerOptionFlag_OmitDebugHelpers = 0x10000,
BfCompilerOptionFlag_NoFramePointerElim = 0x20000, BfCompilerOptionFlag_NoFramePointerElim = 0x20000,
BfCompilerOptionFlag_ArithmeticChecks = 0x40000, BfCompilerOptionFlag_ArithmeticChecks = 0x40000,
@ -234,7 +234,7 @@ enum BfMethodFlags
BfMethodFlags_FastCall = 0x2000, BfMethodFlags_FastCall = 0x2000,
BfMethodFlags_ThisCall = 0x3000, BfMethodFlags_ThisCall = 0x3000,
BfMethodFlags_Mutating = 0x4000, BfMethodFlags_Mutating = 0x4000,
BfMethodFlags_Constructor = 0x8000 BfMethodFlags_Constructor = 0x8000
}; };
enum BfObjectFlags : uint8 enum BfObjectFlags : uint8
@ -344,7 +344,7 @@ enum BfLTOType
}; };
enum BfCFLAAType enum BfCFLAAType
{ {
BfCFLAAType_None, BfCFLAAType_None,
BfCFLAAType_Steensgaard, BfCFLAAType_Steensgaard,
BfCFLAAType_Andersen, BfCFLAAType_Andersen,
@ -354,11 +354,11 @@ enum BfCFLAAType
enum BfRelocType enum BfRelocType
{ {
BfRelocType_NotSet, BfRelocType_NotSet,
BfRelocType_Static, BfRelocType_Static,
BfRelocType_PIC, BfRelocType_PIC,
BfRelocType_DynamicNoPIC, BfRelocType_DynamicNoPIC,
BfRelocType_ROPI, BfRelocType_ROPI,
BfRelocType_RWPI, BfRelocType_RWPI,
BfRelocType_ROPI_RWPI BfRelocType_ROPI_RWPI
}; };
@ -366,32 +366,32 @@ enum BfPICLevel
{ {
BfPICLevel_NotSet, BfPICLevel_NotSet,
BfPICLevel_Not, BfPICLevel_Not,
BfPICLevel_Small, BfPICLevel_Small,
BfPICLevel_Big BfPICLevel_Big
}; };
struct BfCodeGenOptions struct BfCodeGenOptions
{ {
bool mIsHotCompile; bool mIsHotCompile;
bool mWriteObj; bool mWriteObj;
bool mWriteBitcode; bool mWriteBitcode;
BfAsmKind mAsmKind; BfAsmKind mAsmKind;
bool mWriteToLib; bool mWriteToLib;
bool mWriteLLVMIR; bool mWriteLLVMIR;
int16 mVirtualMethodOfs; int16 mVirtualMethodOfs;
int16 mDynSlotOfs; int16 mDynSlotOfs;
BfRelocType mRelocType; BfRelocType mRelocType;
BfPICLevel mPICLevel; BfPICLevel mPICLevel;
BfSIMDSetting mSIMDSetting; BfSIMDSetting mSIMDSetting;
BfOptLevel mOptLevel; BfOptLevel mOptLevel;
BfLTOType mLTOType; BfLTOType mLTOType;
int mSizeLevel; int mSizeLevel;
BfCFLAAType mUseCFLAA; BfCFLAAType mUseCFLAA;
bool mUseNewSROA; bool mUseNewSROA;
bool mDisableTailCalls; bool mDisableTailCalls;
bool mDisableUnitAtATime; bool mDisableUnitAtATime;
bool mDisableUnrollLoops; bool mDisableUnrollLoops;
@ -410,7 +410,7 @@ struct BfCodeGenOptions
bool mUseGVNAfterVectorization; bool mUseGVNAfterVectorization;
bool mEnableLoopInterchange; bool mEnableLoopInterchange;
bool mEnableLoopLoadElim; bool mEnableLoopLoadElim;
bool mExtraVectorizerPasses; bool mExtraVectorizerPasses;
bool mEnableEarlyCSEMemSSA; bool mEnableEarlyCSEMemSSA;
bool mEnableGVNHoist; bool mEnableGVNHoist;
bool mEnableGVNSink; bool mEnableGVNSink;
@ -427,8 +427,8 @@ struct BfCodeGenOptions
Val128 mHash; Val128 mHash;
BfCodeGenOptions() BfCodeGenOptions()
{ {
mIsHotCompile = false; mIsHotCompile = false;
mWriteObj = true; mWriteObj = true;
mWriteBitcode = false; mWriteBitcode = false;
mAsmKind = BfAsmKind_None; mAsmKind = BfAsmKind_None;
@ -436,7 +436,7 @@ struct BfCodeGenOptions
mWriteLLVMIR = false; mWriteLLVMIR = false;
mVirtualMethodOfs = 0; mVirtualMethodOfs = 0;
mDynSlotOfs = 0; mDynSlotOfs = 0;
mRelocType = BfRelocType_NotSet; mRelocType = BfRelocType_NotSet;
mPICLevel = BfPICLevel_NotSet; mPICLevel = BfPICLevel_NotSet;
mSIMDSetting = BfSIMDSetting_None; mSIMDSetting = BfSIMDSetting_None;
@ -445,7 +445,7 @@ struct BfCodeGenOptions
mSizeLevel = 0; mSizeLevel = 0;
mUseCFLAA = BfCFLAAType_None; mUseCFLAA = BfCFLAAType_None;
mUseNewSROA = false; mUseNewSROA = false;
mDisableTailCalls = false; mDisableTailCalls = false;
mDisableUnitAtATime = false; mDisableUnitAtATime = false;
mDisableUnrollLoops = false; mDisableUnrollLoops = false;
@ -480,7 +480,7 @@ struct BfCodeGenOptions
} }
void GenerateHash() void GenerateHash()
{ {
HashContext hashCtx; HashContext hashCtx;
hashCtx.Mixin(mWriteObj); hashCtx.Mixin(mWriteObj);
@ -524,7 +524,6 @@ struct BfCodeGenOptions
} }
}; };
enum BfParamKind : uint8 enum BfParamKind : uint8
{ {
BfParamKind_Normal, BfParamKind_Normal,
@ -547,7 +546,7 @@ class BfParameterDef
{ {
public: public:
String mName; String mName;
BfTypeReference* mTypeRef; BfTypeReference* mTypeRef;
BfParameterDeclaration* mParamDeclaration; BfParameterDeclaration* mParamDeclaration;
int mMethodGenericParamIdx; int mMethodGenericParamIdx;
BfParamKind mParamKind; BfParamKind mParamKind;
@ -559,7 +558,7 @@ public:
mTypeRef = NULL; mTypeRef = NULL;
mMethodGenericParamIdx = -1; mMethodGenericParamIdx = -1;
mParamKind = BfParamKind_Normal; mParamKind = BfParamKind_Normal;
mParamDeclaration = NULL; mParamDeclaration = NULL;
mNamePrefixCount = 0; mNamePrefixCount = 0;
} }
void SetName(BfAstNode* nameNode); void SetName(BfAstNode* nameNode);
@ -579,7 +578,7 @@ public:
bool mIsStatic; bool mIsStatic;
BfShow mShow; BfShow mShow;
bool mIsReadOnly; bool mIsReadOnly;
bool mHasMultiDefs; bool mHasMultiDefs;
public: public:
BfMemberDef() BfMemberDef()
@ -603,25 +602,25 @@ public:
class BfFieldDef : public BfMemberDef class BfFieldDef : public BfMemberDef
{ {
public: public:
int mIdx; int mIdx;
bool mIsConst; // Note: Consts are also all considered Static bool mIsConst; // Note: Consts are also all considered Static
BfTypeReference* mTypeRef; BfTypeReference* mTypeRef;
BfProtection mUsingProtection; BfProtection mUsingProtection;
bool mIsInline; bool mIsInline;
bool mIsVolatile; bool mIsVolatile;
bool mIsExtern; bool mIsExtern;
bool mIsAppend; bool mIsAppend;
bool mIsProperty; bool mIsProperty;
BfAstNode* mFieldDeclaration; BfAstNode* mFieldDeclaration;
// It may seem that fields and properties don't need a 'mNextWithSameName', but with extensions it's possible // It may seem that fields and properties don't need a 'mNextWithSameName', but with extensions it's possible
// to have two libraries which each add a field to a type with the same name // to have two libraries which each add a field to a type with the same name
BfFieldDef* mNextWithSameName; BfFieldDef* mNextWithSameName;
public: public:
BfFieldDef() BfFieldDef()
{ {
mIdx = 0; mIdx = 0;
mIsConst = false; mIsConst = false;
mTypeRef = NULL; mTypeRef = NULL;
mUsingProtection = BfProtection_Hidden; mUsingProtection = BfProtection_Hidden;
mIsInline = false; mIsInline = false;
@ -686,7 +685,7 @@ public:
return paramDecl->mInitializer; return paramDecl->mInitializer;
return NULL; return NULL;
} }
BfAstNode* GetNameNode() BfAstNode* GetNameNode()
{ {
if (auto fieldDecl = GetFieldDeclaration()) if (auto fieldDecl = GetFieldDeclaration())
@ -699,18 +698,18 @@ public:
class BfPropertyDef : public BfFieldDef class BfPropertyDef : public BfFieldDef
{ {
public: public:
Array<BfMethodDef*> mMethods; Array<BfMethodDef*> mMethods;
BfPropertyDef* mNextWithSameName; BfPropertyDef* mNextWithSameName;
public: public:
BfPropertyDef() BfPropertyDef()
{ {
mNextWithSameName = NULL; mNextWithSameName = NULL;
} }
bool IsVirtual(); bool IsVirtual();
bool HasExplicitInterface(); bool HasExplicitInterface();
bool IsExpressionBodied(); bool IsExpressionBodied();
BfAstNode* GetRefNode(); BfAstNode* GetRefNode();
}; };
@ -722,7 +721,7 @@ enum BfGenericParamFlags : uint16
BfGenericParamFlag_Struct = 2, BfGenericParamFlag_Struct = 2,
BfGenericParamFlag_StructPtr = 4, BfGenericParamFlag_StructPtr = 4,
BfGenericParamFlag_Enum = 8, BfGenericParamFlag_Enum = 8,
BfGenericParamFlag_Interface = 0x10, BfGenericParamFlag_Interface = 0x10,
BfGenericParamFlag_Concrete = 0x20, BfGenericParamFlag_Concrete = 0x20,
BfGenericParamFlag_New = 0x40, BfGenericParamFlag_New = 0x40,
BfGenericParamFlag_Delete = 0x80, BfGenericParamFlag_Delete = 0x80,
@ -768,10 +767,10 @@ public:
class BfGenericParamDef : public BfConstraintDef class BfGenericParamDef : public BfConstraintDef
{ {
public: public:
String mName; String mName;
Array<BfIdentifierNode*> mNameNodes; // 0 is always the def name Array<BfIdentifierNode*> mNameNodes; // 0 is always the def name
bool operator==(const BfGenericParamDef& other) const bool operator==(const BfGenericParamDef& other) const
{ {
if (mName != other.mName) if (mName != other.mName)
@ -788,7 +787,7 @@ public:
class BfExternalConstraintDef : public BfConstraintDef class BfExternalConstraintDef : public BfConstraintDef
{ {
public: public:
BfTypeReference* mTypeRef; BfTypeReference* mTypeRef;
}; };
// CTOR is split into two for Objects - Ctor clears and sets up VData, Ctor_Body executes ctor body code // CTOR is split into two for Objects - Ctor clears and sets up VData, Ctor_Body executes ctor body code
@ -814,7 +813,7 @@ enum BfCallingConvention : uint8
BfCallingConvention_Unspecified, BfCallingConvention_Unspecified,
BfCallingConvention_Cdecl, BfCallingConvention_Cdecl,
BfCallingConvention_Stdcall, BfCallingConvention_Stdcall,
BfCallingConvention_Fastcall, BfCallingConvention_Fastcall,
}; };
#define BF_METHODNAME_MARKMEMBERS "GCMarkMembers" #define BF_METHODNAME_MARKMEMBERS "GCMarkMembers"
@ -866,9 +865,9 @@ enum BfComptimeFlags : int8
class BfMethodDef : public BfMemberDef class BfMethodDef : public BfMemberDef
{ {
public: public:
BfAstNode* mMethodDeclaration; BfAstNode* mMethodDeclaration;
BfAstNode* mBody; BfAstNode* mBody;
BfTypeReference* mExplicitInterface; BfTypeReference* mExplicitInterface;
BfTypeReference* mReturnTypeRef; BfTypeReference* mReturnTypeRef;
@ -893,7 +892,7 @@ public:
bool mWantsBody; bool mWantsBody;
bool mCLink; bool mCLink;
bool mHasAppend; bool mHasAppend;
bool mAlwaysInline; bool mAlwaysInline;
bool mIsNoReturn; bool mIsNoReturn;
bool mIsMutating; bool mIsMutating;
bool mIsNoSplat; bool mIsNoSplat;
@ -901,14 +900,14 @@ public:
bool mIsSkipCall; bool mIsSkipCall;
bool mHasComptime; bool mHasComptime;
bool mIsOperator; bool mIsOperator;
bool mIsExtern; bool mIsExtern;
bool mIsNoDiscard; bool mIsNoDiscard;
bool mHasExplicitThis; bool mHasExplicitThis;
bool mAddedAfterEmit; bool mAddedAfterEmit;
BfCommutableKind mCommutableKind; BfCommutableKind mCommutableKind;
BfCheckedKind mCheckedKind; BfCheckedKind mCheckedKind;
BfImportKind mImportKind; BfImportKind mImportKind;
BfCallingConvention mCallingConvention; BfCallingConvention mCallingConvention;
public: public:
BfMethodDef() BfMethodDef()
@ -923,7 +922,7 @@ public:
mIsStatic = false; mIsStatic = false;
mIsNew = false; mIsNew = false;
mIsPartial = false; mIsPartial = false;
mCLink = false; mCLink = false;
mIsNoReturn = false; mIsNoReturn = false;
mIsMutating = false; mIsMutating = false;
mIsNoSplat = false; mIsNoSplat = false;
@ -958,16 +957,16 @@ public:
bool HasNoThisSplat() { return mIsMutating || mIsNoSplat; } bool HasNoThisSplat() { return mIsMutating || mIsNoSplat; }
void Reset(); void Reset();
void FreeMembers(); void FreeMembers();
BfMethodDeclaration* GetMethodDeclaration(); BfMethodDeclaration* GetMethodDeclaration();
BfPropertyMethodDeclaration* GetPropertyMethodDeclaration(); BfPropertyMethodDeclaration* GetPropertyMethodDeclaration();
BfPropertyDeclaration* GetPropertyDeclaration(); BfPropertyDeclaration* GetPropertyDeclaration();
BfAstNode* GetRefNode(); BfAstNode* GetRefNode();
BfTokenNode* GetMutNode(); BfTokenNode* GetMutNode();
bool HasBody(); bool HasBody();
bool IsEmptyPartial(); bool IsEmptyPartial();
bool IsDefaultCtor(); bool IsDefaultCtor();
bool IsCtorOrInit(); bool IsCtorOrInit();
String ToString(); String ToString();
int GetExplicitParamCount(); int GetExplicitParamCount();
void BuildParamNameMap(); void BuildParamNameMap();
}; };
@ -975,7 +974,7 @@ public:
class BfOperatorDef : public BfMethodDef class BfOperatorDef : public BfMethodDef
{ {
public: public:
BfOperatorDeclaration* mOperatorDeclaration; BfOperatorDeclaration* mOperatorDeclaration;
public: public:
BfOperatorDef() BfOperatorDef()
@ -996,7 +995,7 @@ public:
struct BfTypeDefLookupContext struct BfTypeDefLookupContext
{ {
public: public:
int mBestPri; int mBestPri;
BfTypeDef* mBestTypeDef; BfTypeDef* mBestTypeDef;
BfTypeDef* mAmbiguousTypeDef; BfTypeDef* mAmbiguousTypeDef;
@ -1005,8 +1004,8 @@ public:
{ {
mBestPri = (int)0x80000000; mBestPri = (int)0x80000000;
mBestTypeDef = NULL; mBestTypeDef = NULL;
mAmbiguousTypeDef = NULL; mAmbiguousTypeDef = NULL;
} }
bool HasValidMatch() bool HasValidMatch()
{ {
@ -1036,12 +1035,12 @@ struct BfMemberSetEntry
class BfTypeDefMemberSet : public HashSet<BfMemberSetEntry> class BfTypeDefMemberSet : public HashSet<BfMemberSetEntry>
{ {
public: public:
int mSourceSize; int mSourceSize;
public: public:
BfTypeDefMemberSet() BfTypeDefMemberSet()
{ {
mSourceSize = 0; mSourceSize = 0;
} }
@ -1052,7 +1051,7 @@ public:
} }
}; };
// For partial classes, the first entry in the map will contain the combined data // For partial classes, the first entry in the map will contain the combined data
class BfTypeDef class BfTypeDef
{ {
public: public:
@ -1073,16 +1072,16 @@ public:
public: public:
BfTypeDef* mNextRevision; BfTypeDef* mNextRevision;
BfSystem* mSystem; BfSystem* mSystem;
BfProject* mProject; BfProject* mProject;
BfTypeDeclaration* mTypeDeclaration; BfTypeDeclaration* mTypeDeclaration;
BfSource* mSource; BfSource* mSource;
DefState mDefState; DefState mDefState;
Val128 mSignatureHash; // Data, methods, etc Val128 mSignatureHash; // Data, methods, etc
Val128 mFullHash; Val128 mFullHash;
Val128 mInlineHash; Val128 mInlineHash;
BfTypeDef* mEmitParent; BfTypeDef* mEmitParent;
BfTypeDef* mOuterType; BfTypeDef* mOuterType;
BfAtomComposite mNamespace; BfAtomComposite mNamespace;
@ -1101,13 +1100,13 @@ public:
BfTypeDefMemberSet mFieldSet; BfTypeDefMemberSet mFieldSet;
BfTypeDefMemberSet mPropertySet; BfTypeDefMemberSet mPropertySet;
Array<BfOperatorDef*> mOperators; Array<BfOperatorDef*> mOperators;
Array<BfGenericParamDef*> mGenericParamDefs; Array<BfGenericParamDef*> mGenericParamDefs;
Array<BfExternalConstraintDef> mExternalConstraints; Array<BfExternalConstraintDef> mExternalConstraints;
Array<BfTypeReference*> mBaseTypes; Array<BfTypeReference*> mBaseTypes;
Array<BfTypeDef*> mNestedTypes; Array<BfTypeDef*> mNestedTypes;
Array<BfDirectStrTypeReference*> mDirectAllocNodes; Array<BfDirectStrTypeReference*> mDirectAllocNodes;
Array<BfTypeDef*> mPartials; // Only valid for mIsCombinedPartial Array<BfTypeDef*> mPartials; // Only valid for mIsCombinedPartial
int mHash; int mHash;
int mPartialIdx; int mPartialIdx;
int mNestDepth; int mNestDepth;
@ -1123,29 +1122,29 @@ public:
bool mIsDelegate; bool mIsDelegate;
bool mIsFunction; bool mIsFunction;
bool mIsClosure; bool mIsClosure;
bool mIsAbstract; bool mIsAbstract;
bool mIsStatic; bool mIsStatic;
bool mHasCEOnCompile; bool mHasCEOnCompile;
bool mHasAppendCtor; bool mHasAppendCtor;
bool mHasCtorNoBody; bool mHasCtorNoBody;
bool mHasExtensionMethods; bool mHasExtensionMethods;
bool mHasOverrideMethods; bool mHasOverrideMethods;
bool mHasUsingFields; bool mHasUsingFields;
bool mIsOpaque; bool mIsOpaque;
bool mIsNextRevision; bool mIsNextRevision;
bool mInDeleteQueue; bool mInDeleteQueue;
bool mForceUseNextRevision; bool mForceUseNextRevision;
public: public:
BfTypeDef() BfTypeDef()
{ {
Init(); Init();
} }
~BfTypeDef(); ~BfTypeDef();
void Init() void Init()
{ {
mName = NULL; mName = NULL;
mNameEx = NULL; mNameEx = NULL;
mSystem = NULL; mSystem = NULL;
@ -1158,11 +1157,11 @@ public:
mIsPartial = false; mIsPartial = false;
mIsCombinedPartial = false; mIsCombinedPartial = false;
mTypeDeclaration = NULL; mTypeDeclaration = NULL;
mSource = NULL; mSource = NULL;
mDefState = DefState_New; mDefState = DefState_New;
mHash = 0; mHash = 0;
mPartialIdx = -1; mPartialIdx = -1;
mIsAbstract = false; mIsAbstract = false;
mIsDelegate = false; mIsDelegate = false;
mIsFunction = false; mIsFunction = false;
mIsClosure = false; mIsClosure = false;
@ -1176,29 +1175,29 @@ public:
mIsOpaque = false; mIsOpaque = false;
mPartialUsed = false; mPartialUsed = false;
mIsNextRevision = false; mIsNextRevision = false;
mInDeleteQueue = false; mInDeleteQueue = false;
mForceUseNextRevision = false; mForceUseNextRevision = false;
mDupDetectedRevision = -1; mDupDetectedRevision = -1;
mNestDepth = 0; mNestDepth = 0;
mEmitParent = NULL; mEmitParent = NULL;
mOuterType = NULL; mOuterType = NULL;
mTypeDeclaration = NULL; mTypeDeclaration = NULL;
mNextRevision = NULL; mNextRevision = NULL;
mProtection = BfProtection_Public; mProtection = BfProtection_Public;
} }
BfSource* GetLastSource(); BfSource* GetLastSource();
bool IsGlobalsContainer(); bool IsGlobalsContainer();
void Reset(); void Reset();
void FreeMembers(); void FreeMembers();
void PopulateMemberSets(); void PopulateMemberSets();
void ClearMemberSets(); void ClearMemberSets();
void RemoveGenericParamDef(BfGenericParamDef* genericParamDef); void RemoveGenericParamDef(BfGenericParamDef* genericParamDef);
int GetSelfGenericParamCount(); int GetSelfGenericParamCount();
String ToString(); String ToString();
BfMethodDef* GetMethodByName(const StringImpl& name, int paramCount = -1); BfMethodDef* GetMethodByName(const StringImpl& name, int paramCount = -1);
BfFieldDef* GetFieldByName(const StringImpl& name); BfFieldDef* GetFieldByName(const StringImpl& name);
bool HasAutoProperty(BfPropertyDeclaration* propertyDeclaration); bool HasAutoProperty(BfPropertyDeclaration* propertyDeclaration);
bool ContainsPartial(BfTypeDef* partialTypeDef); bool ContainsPartial(BfTypeDef* partialTypeDef);
bool HasParsingFailed(); bool HasParsingFailed();
String GetAutoPropertyName(BfPropertyDeclaration* propertyDeclaration); String GetAutoPropertyName(BfPropertyDeclaration* propertyDeclaration);
@ -1274,7 +1273,7 @@ public:
SkipEntry() SkipEntry()
{ {
mIndex = -1; mIndex = -1;
mRevision = -1; mRevision = -1;
} }
SkipEntry(int index, int revision) SkipEntry(int index, int revision)
@ -1337,12 +1336,12 @@ public:
enum BfTargetType enum BfTargetType
{ {
BfTargetType_BeefConsoleApplication, BfTargetType_BeefConsoleApplication,
BfTargetType_BeefWindowsApplication, BfTargetType_BeefWindowsApplication,
BfTargetType_BeefLib, BfTargetType_BeefLib,
BfTargetType_CustomBuild, BfTargetType_CustomBuild,
BfTargetType_BeefTest, BfTargetType_BeefTest,
BfTargetType_C_ConsoleApplication, BfTargetType_C_ConsoleApplication,
BfTargetType_C_WindowsApplication, BfTargetType_C_WindowsApplication,
BfTargetType_BeefApplication_StaticLib, BfTargetType_BeefApplication_StaticLib,
BfTargetType_BeefApplication_DynamicLib, BfTargetType_BeefApplication_DynamicLib,
BfTargetType_BeefLib_StaticLib, BfTargetType_BeefLib_StaticLib,
@ -1372,14 +1371,14 @@ public:
DeleteStage_AwaitingRefs, DeleteStage_AwaitingRefs,
}; };
public: public:
BfSystem* mSystem; BfSystem* mSystem;
String mName; String mName;
String mSafeName; String mSafeName;
String mDirectory; String mDirectory;
Array<BfProject*> mDependencies; Array<BfProject*> mDependencies;
BfTargetType mTargetType; BfTargetType mTargetType;
BfCodeGenOptions mCodeGenOptions; BfCodeGenOptions mCodeGenOptions;
bool mDisabled; bool mDisabled;
bool mSingleModule; bool mSingleModule;
bool mAlwaysIncludeAll; bool mAlwaysIncludeAll;
@ -1387,11 +1386,11 @@ public:
int mIdx; int mIdx;
String mStartupObject; String mStartupObject;
Array<String> mPreprocessorMacros; Array<String> mPreprocessorMacros;
Dictionary<BfAtomComposite, int> mNamespaces; Dictionary<BfAtomComposite, int> mNamespaces;
HashSet<BfModule*> mUsedModules; HashSet<BfModule*> mUsedModules;
HashSet<BfType*> mReferencedTypeData; HashSet<BfType*> mReferencedTypeData;
Val128 mBuildConfigHash; Val128 mBuildConfigHash;
Val128 mVDataConfigHash; Val128 mVDataConfigHash;
@ -1403,7 +1402,7 @@ public:
~BfProject(); ~BfProject();
bool ContainsReference(BfProject* refProject); bool ContainsReference(BfProject* refProject);
bool ReferencesOrReferencedBy(BfProject* refProject); bool ReferencesOrReferencedBy(BfProject* refProject);
bool IsTestProject(); bool IsTestProject();
}; };
@ -1415,7 +1414,7 @@ enum BfWarning
BfWarning_CS0162_UnreachableCode = 162, BfWarning_CS0162_UnreachableCode = 162,
BfWarning_CS0168_VariableDeclaredButNeverUsed = 168, BfWarning_CS0168_VariableDeclaredButNeverUsed = 168,
BfWarning_CS0472_ValueTypeNullCompare = 472, BfWarning_CS0472_ValueTypeNullCompare = 472,
BfWarning_CS1030_PragmaWarning = 1030, BfWarning_CS1030_PragmaWarning = 1030,
BfWarning_BF4201_Only7Hex = 4201, BfWarning_BF4201_Only7Hex = 4201,
BfWarning_BF4202_TooManyHexForInt = 4202, BfWarning_BF4202_TooManyHexForInt = 4202,
BfWarning_BF4203_UnnecessaryDynamicCast = 4203, BfWarning_BF4203_UnnecessaryDynamicCast = 4203,
@ -1438,9 +1437,9 @@ class BfErrorBase
public: public:
bool mIsWarning; bool mIsWarning;
bool mIsDeferred; bool mIsDeferred;
BfSourceData* mSource; BfSourceData* mSource;
int mSrcStart; int mSrcStart;
int mSrcEnd; int mSrcEnd;
BfErrorLocation* mLocation; BfErrorLocation* mLocation;
public: public:
@ -1448,7 +1447,7 @@ public:
{ {
mIsWarning = false; mIsWarning = false;
mIsDeferred = false; mIsDeferred = false;
mSource = NULL; mSource = NULL;
mSrcStart = -1; mSrcStart = -1;
mSrcEnd = -1; mSrcEnd = -1;
mLocation = NULL; mLocation = NULL;
@ -1466,11 +1465,11 @@ public:
class BfError : public BfErrorBase class BfError : public BfErrorBase
{ {
public: public:
bool mIsAfter; bool mIsAfter;
bool mIsPersistent; bool mIsPersistent;
BfWhileSpecializingFlags mIsWhileSpecializing; BfWhileSpecializingFlags mIsWhileSpecializing;
bool mIgnore; bool mIgnore;
BfProject* mProject; BfProject* mProject;
String mError; String mError;
int mWarningNumber; int mWarningNumber;
@ -1479,10 +1478,10 @@ public:
public: public:
BfError() BfError()
{ {
mIsAfter = false; mIsAfter = false;
mIsPersistent = false; mIsPersistent = false;
mIsWhileSpecializing = BfWhileSpecializingFlag_None; mIsWhileSpecializing = BfWhileSpecializingFlag_None;
mIgnore = false; mIgnore = false;
mProject = NULL; mProject = NULL;
mWarningNumber = 0; mWarningNumber = 0;
} }
@ -1540,16 +1539,16 @@ public:
BfSystem* mSystem; BfSystem* mSystem;
BfCompiler* mCompiler; BfCompiler* mCompiler;
bool mTrimMessagesToCursor; bool mTrimMessagesToCursor;
int mFailedIdx; int mFailedIdx;
int mWarnIdx; int mWarnIdx;
Dictionary<BfSourceData*, String> mSourceFileNameMap; Dictionary<BfSourceData*, String> mSourceFileNameMap;
HashSet<BfErrorEntry> mErrorSet; HashSet<BfErrorEntry> mErrorSet;
Array<BfError*> mErrors; Array<BfError*> mErrors;
int mIgnoreCount; int mIgnoreCount;
int mWarningCount; int mWarningCount;
int mDeferredErrorCount; int mDeferredErrorCount;
Deque<String> mOutStream; Deque<String> mOutStream;
bool mLastWasDisplayed; bool mLastWasDisplayed;
bool mLastWasAdded; bool mLastWasAdded;
uint8 mClassifierPassId; uint8 mClassifierPassId;
@ -1567,9 +1566,9 @@ public:
mLastWasDisplayed = false; mLastWasDisplayed = false;
mLastWasAdded = false; mLastWasAdded = false;
mClassifierPassId = 0; mClassifierPassId = 0;
mWarningCount = 0; mWarningCount = 0;
mDeferredErrorCount = 0; mDeferredErrorCount = 0;
mIgnoreCount = 0; mIgnoreCount = 0;
mHadSignatureChanges = false; mHadSignatureChanges = false;
} }
@ -1594,7 +1593,7 @@ public:
BfError* Warn(int warningNumber, const StringImpl& warning, BfAstNode* refNode, bool isDeferred = false); BfError* Warn(int warningNumber, const StringImpl& warning, BfAstNode* refNode, bool isDeferred = false);
BfError* DeferWarn(int warningNumber, const StringImpl& warning, BfAstNode* refNode); BfError* DeferWarn(int warningNumber, const StringImpl& warning, BfAstNode* refNode);
BfError* WarnAfter(int warningNumber, const StringImpl& warning, BfAstNode* refNode); BfError* WarnAfter(int warningNumber, const StringImpl& warning, BfAstNode* refNode);
BfError* WarnAfterAt(int warningNumber, const StringImpl& error, BfSourceData* bfSource, int srcIdx); BfError* WarnAfterAt(int warningNumber, const StringImpl& error, BfSourceData* bfSource, int srcIdx);
BfMoreInfo* MoreInfoAt(const StringImpl& info, BfSourceData* bfSource, int srcIdx, int srcLen, BfFailFlags flags = BfFailFlag_None); BfMoreInfo* MoreInfoAt(const StringImpl& info, BfSourceData* bfSource, int srcIdx, int srcLen, BfFailFlags flags = BfFailFlag_None);
BfMoreInfo* MoreInfo(const StringImpl& info, bool forceQueue = false); BfMoreInfo* MoreInfo(const StringImpl& info, bool forceQueue = false);
@ -1608,7 +1607,7 @@ public:
BfError* FailAfter(const StringImpl& error, BfAstNode* refNode); BfError* FailAfter(const StringImpl& error, BfAstNode* refNode);
BfError* DeferFail(const StringImpl& error, BfAstNode* refNode); BfError* DeferFail(const StringImpl& error, BfAstNode* refNode);
void SilentFail(); void SilentFail();
void TryFlushDeferredError(); void TryFlushDeferredError();
void WriteErrorSummary(); void WriteErrorSummary();
}; };
@ -1635,7 +1634,6 @@ enum BfOptionFlags
BfOptionFlags_Reflect_MethodMask = BfOptionFlags_ReflectStaticMethods | BfOptionFlags_ReflectNonStaticMethods | BfOptionFlags_ReflectConstructors, BfOptionFlags_Reflect_MethodMask = BfOptionFlags_ReflectStaticMethods | BfOptionFlags_ReflectNonStaticMethods | BfOptionFlags_ReflectConstructors,
BfOptionFlags_Mask = 0x3FFF BfOptionFlags_Mask = 0x3FFF
}; };
enum BfFieldFlags enum BfFieldFlags
@ -1661,7 +1659,7 @@ enum BfReflectKind
BfReflectKind_DefaultConstructor = 8, BfReflectKind_DefaultConstructor = 8,
BfReflectKind_Constructors = 0x10, BfReflectKind_Constructors = 0x10,
BfReflectKind_StaticMethods = 0x20, BfReflectKind_StaticMethods = 0x20,
BfReflectKind_Methods = 0x40, BfReflectKind_Methods = 0x40,
BfReflectKind_DynamicBoxing = 0x80, BfReflectKind_DynamicBoxing = 0x80,
BfReflectKind_User = 0x100, BfReflectKind_User = 0x100,
BfReflectKind_All = 0x1FF, BfReflectKind_All = 0x1FF,
@ -1682,15 +1680,15 @@ public:
public: public:
Array<String> mTypeFilters; Array<String> mTypeFilters;
Array<String> mAttributeFilters; Array<String> mAttributeFilters;
Array<int> mMatchedIndices; Array<int> mMatchedIndices;
int mSIMDSetting; int mSIMDSetting;
int mOptimizationLevel; int mOptimizationLevel;
int mEmitDebugInfo; int mEmitDebugInfo;
BfOptionFlags mAndFlags; BfOptionFlags mAndFlags;
BfOptionFlags mOrFlags; BfOptionFlags mOrFlags;
Array<MethodFilter> mReflectMethodFilters; Array<MethodFilter> mReflectMethodFilters;
Array<MethodFilter> mReflectMethodAttributeFilters; Array<MethodFilter> mReflectMethodAttributeFilters;
int mAllocStackTraceDepth; int mAllocStackTraceDepth;
public: public:
static int Apply(int val, int applyVal) static int Apply(int val, int applyVal)
@ -1698,7 +1696,7 @@ public:
if (applyVal != -1) if (applyVal != -1)
return applyVal; return applyVal;
return val; return val;
} }
bool Apply(bool val, BfOptionFlags flags) bool Apply(bool val, BfOptionFlags flags)
{ {
@ -1722,10 +1720,10 @@ enum BfFindTypeDefFlags
class BfSystem class BfSystem
{ {
public: public:
int mPtrSize; int mPtrSize;
bool mIsResolveOnly; bool mIsResolveOnly;
CritSect mDataLock; // short-lived, hold only while active modifying data CritSect mDataLock; // short-lived, hold only while active modifying data
// The following are protected by mDataLock: // The following are protected by mDataLock:
HashSet<String> mUsedSafeProjectNames; HashSet<String> mUsedSafeProjectNames;
@ -1753,11 +1751,11 @@ public:
uint32 mYieldTickCount; uint32 mYieldTickCount;
int mHighestYieldTime; int mHighestYieldTime;
// The following are protected by mSystemLock - can only be accessed by the compiling thread // The following are protected by mSystemLock - can only be accessed by the compiling thread
Dictionary<String, BfTypeDef*> mSystemTypeDefs; Dictionary<String, BfTypeDef*> mSystemTypeDefs;
BfTypeDefMap mTypeDefs; BfTypeDefMap mTypeDefs;
bool mNeedsTypesHandledByCompiler; bool mNeedsTypesHandledByCompiler;
BumpAllocator mAlloc; BumpAllocator mAlloc;
int mAtomCreateIdx; int mAtomCreateIdx;
Dictionary<StringView, BfAtom*> mAtomMap; Dictionary<StringView, BfAtom*> mAtomMap;
Array<BfAtom*> mAtomGraveyard; Array<BfAtom*> mAtomGraveyard;
uint32 mAtomUpdateIdx; uint32 mAtomUpdateIdx;
@ -1792,7 +1790,7 @@ public:
BfTypeDef* mTypeChar16; BfTypeDef* mTypeChar16;
BfTypeDef* mTypeChar32; BfTypeDef* mTypeChar32;
BfTypeDef* mTypeSingle; BfTypeDef* mTypeSingle;
BfTypeDef* mTypeDouble; BfTypeDef* mTypeDouble;
BfDirectStrTypeReference* mDirectVoidTypeRef; BfDirectStrTypeReference* mDirectVoidTypeRef;
BfDirectStrTypeReference* mDirectBoolTypeRef; BfDirectStrTypeReference* mDirectBoolTypeRef;
@ -1808,58 +1806,57 @@ public:
public: public:
BfSystem(); BfSystem();
~BfSystem(); ~BfSystem();
BfAtom* GetAtom(const StringImpl& string); BfAtom* GetAtom(const StringImpl& string);
BfAtom* FindAtom(const StringImpl& string); // Doesn't create a ref BfAtom* FindAtom(const StringImpl& string); // Doesn't create a ref
BfAtom* FindAtom(const StringView& string); // Doesn't create a ref BfAtom* FindAtom(const StringView& string); // Doesn't create a ref
void ReleaseAtom(BfAtom* atom); void ReleaseAtom(BfAtom* atom);
void ProcessAtomGraveyard(); void ProcessAtomGraveyard();
void RefAtomComposite(const BfAtomComposite& atomComposite); void RefAtomComposite(const BfAtomComposite& atomComposite);
void ReleaseAtomComposite(const BfAtomComposite& atomComposite); void ReleaseAtomComposite(const BfAtomComposite& atomComposite);
void SanityCheckAtomComposite(const BfAtomComposite& atomComposite); void SanityCheckAtomComposite(const BfAtomComposite& atomComposite);
void TrackName(BfTypeDef* typeDef); void TrackName(BfTypeDef* typeDef);
void UntrackName(BfTypeDef* typeDef); void UntrackName(BfTypeDef* typeDef);
bool ParseAtomComposite(const StringView& name, BfAtomComposite& composite, bool addRefs = false); bool ParseAtomComposite(const StringView& name, BfAtomComposite& composite, bool addRefs = false);
void CreateBasicTypes(); void CreateBasicTypes();
bool DoesLiteralFit(BfTypeCode typeCode, int64 value); bool DoesLiteralFit(BfTypeCode typeCode, int64 value);
bool DoesLiteralFit(BfTypeCode typeCode, uint64 value); bool DoesLiteralFit(BfTypeCode typeCode, uint64 value);
bool DoesLiteralFit(BfTypeCode typeCode, const BfVariant& variant); bool DoesLiteralFit(BfTypeCode typeCode, const BfVariant& variant);
BfParser* CreateParser(BfProject* bfProject); BfParser* CreateParser(BfProject* bfProject);
BfCompiler* CreateCompiler(bool isResolveOnly); BfCompiler* CreateCompiler(bool isResolveOnly);
BfProject* GetProject(const StringImpl& projName); BfProject* GetProject(const StringImpl& projName);
BfTypeReference* GetTypeRefElement(BfTypeReference* typeRef); BfTypeReference* GetTypeRefElement(BfTypeReference* typeRef);
BfTypeDef* FilterDeletedTypeDef(BfTypeDef* typeDef); BfTypeDef* FilterDeletedTypeDef(BfTypeDef* typeDef);
bool CheckTypeDefReference(BfTypeDef* typeDef, BfProject* project); bool CheckTypeDefReference(BfTypeDef* typeDef, BfProject* project);
BfTypeDef* FindTypeDef(const BfAtomComposite& findName, int numGenericArgs = 0, BfProject* project = NULL, const Array<BfAtomComposite>& namespaceSearch = Array<BfAtomComposite>(), BfTypeDef** ambiguousTypeDef = NULL, BfFindTypeDefFlags flags = BfFindTypeDefFlag_None); BfTypeDef* FindTypeDef(const BfAtomComposite& findName, int numGenericArgs = 0, BfProject* project = NULL, const Array<BfAtomComposite>& namespaceSearch = Array<BfAtomComposite>(), BfTypeDef** ambiguousTypeDef = NULL, BfFindTypeDefFlags flags = BfFindTypeDefFlag_None);
bool FindTypeDef(const BfAtomComposite& findName, int numGenericArgs, BfProject* project, const BfAtomComposite& checkNamespace, bool allowPrivate, BfTypeDefLookupContext* ctx); bool FindTypeDef(const BfAtomComposite& findName, int numGenericArgs, BfProject* project, const BfAtomComposite& checkNamespace, bool allowPrivate, BfTypeDefLookupContext* ctx);
BfTypeDef* FindTypeDef(const StringImpl& typeName, int numGenericArgs = 0, BfProject* project = NULL, const Array<BfAtomComposite>& namespaceSearch = Array<BfAtomComposite>(), BfTypeDef** ambiguousTypeDef = NULL, BfFindTypeDefFlags flags = BfFindTypeDefFlag_None); BfTypeDef* FindTypeDef(const StringImpl& typeName, int numGenericArgs = 0, BfProject* project = NULL, const Array<BfAtomComposite>& namespaceSearch = Array<BfAtomComposite>(), BfTypeDef** ambiguousTypeDef = NULL, BfFindTypeDefFlags flags = BfFindTypeDefFlag_None);
BfTypeDef* FindTypeDef(const StringImpl& typeName, BfProject* project); BfTypeDef* FindTypeDef(const StringImpl& typeName, BfProject* project);
BfTypeDef* FindTypeDefEx(const StringImpl& typeName); BfTypeDef* FindTypeDefEx(const StringImpl& typeName);
void ClearTypeDefCache(); void ClearTypeDefCache();
void FindFixitNamespaces(const StringImpl& typeName, int numGenericArgs, BfProject* project, std::set<String>& fixitNamespaces); void FindFixitNamespaces(const StringImpl& typeName, int numGenericArgs, BfProject* project, std::set<String>& fixitNamespaces);
void RemoveTypeDef(BfTypeDef* typeDef); void RemoveTypeDef(BfTypeDef* typeDef);
//BfTypeDefMap::Iterator RemoveTypeDef(BfTypeDefMap::Iterator typeDefItr); //BfTypeDefMap::Iterator RemoveTypeDef(BfTypeDefMap::Iterator typeDefItr);
void AddNamespaceUsage(const BfAtomComposite& namespaceStr, BfProject* bfProject); void AddNamespaceUsage(const BfAtomComposite& namespaceStr, BfProject* bfProject);
void RemoveNamespaceUsage(const BfAtomComposite& namespaceStr, BfProject* bfProject); void RemoveNamespaceUsage(const BfAtomComposite& namespaceStr, BfProject* bfProject);
bool ContainsNamespace(const BfAtomComposite& namespaceStr, BfProject* bfProject); bool ContainsNamespace(const BfAtomComposite& namespaceStr, BfProject* bfProject);
void InjectNewRevision(BfTypeDef* typeDef); void InjectNewRevision(BfTypeDef* typeDef);
void AddToCompositePartial(BfPassInstance* passInstance, BfTypeDef* compositeTypeDef, BfTypeDef* partialTypeDef); void AddToCompositePartial(BfPassInstance* passInstance, BfTypeDef* compositeTypeDef, BfTypeDef* partialTypeDef);
void FinishCompositePartial(BfTypeDef* compositeTypeDef); void FinishCompositePartial(BfTypeDef* compositeTypeDef);
void CopyTypeDef(BfTypeDef* typeDef, BfTypeDef* nextTypeDef); void CopyTypeDef(BfTypeDef* typeDef, BfTypeDef* nextTypeDef);
void UpdateEmittedTypeDef(BfTypeDef* typeDef); void UpdateEmittedTypeDef(BfTypeDef* typeDef);
BfTypeDef* GetCombinedPartial(BfTypeDef* typeDef); BfTypeDef* GetCombinedPartial(BfTypeDef* typeDef);
BfTypeDef* GetOuterTypeNonPartial(BfTypeDef* typeDef); BfTypeDef* GetOuterTypeNonPartial(BfTypeDef* typeDef);
int GetGenericParamIdx(const Array<BfGenericParamDef*>& genericParams, const StringImpl& name); int GetGenericParamIdx(const Array<BfGenericParamDef*>& genericParams, const StringImpl& name);
int GetGenericParamIdx(const Array<BfGenericParamDef*>& genericParams, BfTypeReference* typeRef); int GetGenericParamIdx(const Array<BfGenericParamDef*>& genericParams, BfTypeReference* typeRef);
void StartYieldSection(); void StartYieldSection();
void CheckLockYield(); // Yields to a higher priority request void CheckLockYield(); // Yields to a higher priority request
void SummarizeYieldSection(); void SummarizeYieldSection();
@ -1888,7 +1885,7 @@ public:
public: public:
AutoDisallowYield(BfSystem* system) AutoDisallowYield(BfSystem* system)
{ {
mSystem = system; mSystem = system;
mSystem->mYieldDisallowCount++; mSystem->mYieldDisallowCount++;
mHeld = true; mHeld = true;
@ -1921,7 +1918,6 @@ public:
} }
}; };
#ifdef _DEBUG #ifdef _DEBUG
#ifdef BF_PLATFORM_WINDOWS #ifdef BF_PLATFORM_WINDOWS
@ -1959,7 +1955,6 @@ public:
#define BfLogX(logIdx, fmt, ...) {} // Nothing #define BfLogX(logIdx, fmt, ...) {} // Nothing
#endif #endif
#ifdef BF_WANTS_LOG_SYS #ifdef BF_WANTS_LOG_SYS
#define BfLogSys(sys, fmt, ...) DoBfLog((sys)->mIsResolveOnly ? 1 : 2, fmt, ##__VA_ARGS__) #define BfLogSys(sys, fmt, ...) DoBfLog((sys)->mIsResolveOnly ? 1 : 2, fmt, ##__VA_ARGS__)
#define BfLogSysM(fmt, ...) DoBfLog(mSystem->mIsResolveOnly ? 1 : 2, fmt, ##__VA_ARGS__) #define BfLogSysM(fmt, ...) DoBfLog(mSystem->mIsResolveOnly ? 1 : 2, fmt, ##__VA_ARGS__)
@ -2035,7 +2030,6 @@ namespace std
}; };
} }
namespace std namespace std
{ {
template<> template<>

View file

@ -39,4 +39,4 @@ BfMachineType BfTargetTriple::GetMachineType()
if (!mParsed) if (!mParsed)
Parse(); Parse();
return mMachineType; return mMachineType;
} }

View file

@ -3,5 +3,4 @@
NS_BF_BEGIN NS_BF_BEGIN
NS_BF_END NS_BF_END

View file

@ -60,7 +60,7 @@ String Beefy::EncodeFileName(const StringImpl& fromStr)
path.Insert(0, fromStr.mPtr, 80); path.Insert(0, fromStr.mPtr, 80);
else else
path += fromStr; path += fromStr;
path.Replace("$", "\\"); path.Replace("$", "\\");
for (auto& c : path) for (auto& c : path)
{ {
@ -178,7 +178,7 @@ bool Beefy::BfCheckWildcard(const StringImpl& wildcard, const StringImpl& checkS
break; break;
} }
prevFilterC = filterC; prevFilterC = filterC;
} }
return matched; return matched;

View file

@ -41,7 +41,7 @@ public:
public: public:
SetAndRestoreValue() SetAndRestoreValue()
{ {
mVarPtr = NULL; mVarPtr = NULL;
} }
SetAndRestoreValue(T& varRef) SetAndRestoreValue(T& varRef)
@ -54,14 +54,14 @@ public:
SetAndRestoreValue(T& varRef, T newVal) SetAndRestoreValue(T& varRef, T newVal)
{ {
mPrevVal = varRef; mPrevVal = varRef;
mVarPtr = &varRef; mVarPtr = &varRef;
varRef = newVal; varRef = newVal;
mNewVal = newVal; mNewVal = newVal;
} }
SetAndRestoreValue(T& varRef, T newVal, bool doSet) SetAndRestoreValue(T& varRef, T newVal, bool doSet)
{ {
mPrevVal = varRef; mPrevVal = varRef;
mVarPtr = &varRef; mVarPtr = &varRef;
if (doSet) if (doSet)
varRef = newVal; varRef = newVal;
@ -183,14 +183,14 @@ public:
mVals.pop_back(); mVals.pop_back();
return val; return val;
} }
if (mZeroAlloc) if (mZeroAlloc)
{ {
void* addr = malloc(sizeof(T)); void* addr = malloc(sizeof(T));
memset(addr, 0, sizeof(T)); memset(addr, 0, sizeof(T));
val = new(addr) T(); val = new(addr) T();
} }
else else
val = new T(); val = new T();
if (mOwnsAll) if (mOwnsAll)
mVals.push_back(val); mVals.push_back(val);
@ -226,15 +226,15 @@ inline void EncodeSLEB128(uint8*& buf, int value)
bool hasMore; bool hasMore;
do do
{ {
uint8 curByte = (uint8)(value & 0x7f); uint8 curByte = (uint8)(value & 0x7f);
value >>= 7; value >>= 7;
hasMore = !((((value == 0) && ((curByte & 0x40) == 0)) || hasMore = !((((value == 0) && ((curByte & 0x40) == 0)) ||
((value == -1) && ((curByte & 0x40) != 0)))); ((value == -1) && ((curByte & 0x40) != 0))));
if (hasMore) if (hasMore)
curByte |= 0x80; curByte |= 0x80;
*(buf++) = curByte; *(buf++) = curByte;
} }
while (hasMore); while (hasMore);
} }
inline void EncodeSLEB128(uint8*& buf, int64_t value) inline void EncodeSLEB128(uint8*& buf, int64_t value)
@ -242,15 +242,15 @@ inline void EncodeSLEB128(uint8*& buf, int64_t value)
bool hasMore; bool hasMore;
do do
{ {
uint8 curByte = (uint8)(value & 0x7f); uint8 curByte = (uint8)(value & 0x7f);
value >>= 7; value >>= 7;
hasMore = !((((value == 0) && ((curByte & 0x40) == 0)) || hasMore = !((((value == 0) && ((curByte & 0x40) == 0)) ||
((value == -1) && ((curByte & 0x40) != 0)))); ((value == -1) && ((curByte & 0x40) != 0))));
if (hasMore) if (hasMore)
curByte |= 0x80; curByte |= 0x80;
*(buf++) = curByte; *(buf++) = curByte;
} }
while (hasMore); while (hasMore);
} }
#pragma warning(push) #pragma warning(push)
@ -258,7 +258,7 @@ inline void EncodeSLEB128(uint8*& buf, int64_t value)
/// Utility function to decode a SLEB128 value. /// Utility function to decode a SLEB128 value.
inline int64_t DecodeSLEB128(const uint8*& p) inline int64_t DecodeSLEB128(const uint8*& p)
{ {
int value = 0; int value = 0;
int shift = 0; int shift = 0;
int curByte; int curByte;
@ -267,7 +267,6 @@ inline int64_t DecodeSLEB128(const uint8*& p)
curByte = (uint8_t)*p++; curByte = (uint8_t)*p++;
value |= ((curByte & 0x7f) << shift); value |= ((curByte & 0x7f) << shift);
shift += 7; shift += 7;
} while (curByte >= 128); } while (curByte >= 128);
// Sign extend negative numbers. // Sign extend negative numbers.
if (((curByte & 0x40) != 0) && (shift < 64)) if (((curByte & 0x40) != 0) && (shift < 64))

View file

@ -10,4 +10,4 @@ BfVarDeclChecker::BfVarDeclChecker()
void BfVarDeclChecker::Visit(BfVariableDeclaration * binOpExpr) void BfVarDeclChecker::Visit(BfVariableDeclaration * binOpExpr)
{ {
mHasVarDecl = true; mHasVarDecl = true;
} }

View file

@ -17,5 +17,4 @@ public:
virtual void Visit(BfVariableDeclaration* binOpExpr) override; virtual void Visit(BfVariableDeclaration* binOpExpr) override;
}; };
NS_BF_END NS_BF_END

File diff suppressed because it is too large Load diff

View file

@ -29,7 +29,7 @@ public:
class CeBreakpoint : public Breakpoint class CeBreakpoint : public Breakpoint
{ {
public: public:
uintptr mCurBindAddr; uintptr mCurBindAddr;
bool mHasBound; bool mHasBound;
int mIdx; int mIdx;
@ -37,7 +37,7 @@ public:
public: public:
CeBreakpoint() CeBreakpoint()
{ {
mCurBindAddr = 1; mCurBindAddr = 1;
mHasBound = false; mHasBound = false;
mIdx = -1; mIdx = -1;
@ -62,7 +62,7 @@ struct CeFormatInfo
intptr mArrayLength; intptr mArrayLength;
intptr mOverrideCount; intptr mOverrideCount;
intptr mMaxCount; intptr mMaxCount;
DwDisplayType mDisplayType; DwDisplayType mDisplayType;
int mTotalSummaryLength; int mTotalSummaryLength;
String mReferenceId; String mReferenceId;
String mSubjectExpr; String mSubjectExpr;
@ -86,7 +86,7 @@ struct CeFormatInfo
mMaxCount = -1; mMaxCount = -1;
mTotalSummaryLength = 0; mTotalSummaryLength = 0;
mDisplayType = DwDisplayType_NotSpecified; mDisplayType = DwDisplayType_NotSpecified;
mExpandItemDepth = 0; mExpandItemDepth = 0;
} }
}; };
@ -99,7 +99,7 @@ public:
BfPassInstance* mPassInstance; BfPassInstance* mPassInstance;
BfExprEvaluator* mExprEvaluator; BfExprEvaluator* mExprEvaluator;
BfExpression* mExprNode; BfExpression* mExprNode;
BfTypedValue mResultOverride; BfTypedValue mResultOverride;
String mExprString; String mExprString;
BfTypedValue mExplicitThis; BfTypedValue mExplicitThis;
@ -110,7 +110,7 @@ public:
void Init(CeDebugger* winDebugger, const StringImpl& expr, CeFormatInfo* formatInfo = NULL, BfTypedValue contextValue = BfTypedValue()); void Init(CeDebugger* winDebugger, const StringImpl& expr, CeFormatInfo* formatInfo = NULL, BfTypedValue contextValue = BfTypedValue());
bool HasExpression(); bool HasExpression();
~CeEvaluationContext(); ~CeEvaluationContext();
BfTypedValue EvaluateInContext(BfTypedValue contextTypedValue, CeDbgState* dbgState = NULL); BfTypedValue EvaluateInContext(BfTypedValue contextTypedValue, CeDbgState* dbgState = NULL);
String GetErrorStr(); String GetErrorStr();
bool HadError(); bool HadError();
}; };
@ -153,9 +153,9 @@ public:
BfAstNode* mExprNode; BfAstNode* mExprNode;
String mReferenceId; String mReferenceId;
int mCallStackIdx; int mCallStackIdx;
String mResult; String mResult;
int mIdleTicks; int mIdleTicks;
String mException; String mException;
bool mDone; bool mDone;
CePendingExpr(); CePendingExpr();
@ -197,7 +197,7 @@ public:
{ {
public: public:
int mFieldIdx; int mFieldIdx;
int64 mVal; int64 mVal;
}; };
public: public:
@ -243,16 +243,16 @@ public:
CeMachine* mCeMachine; CeMachine* mCeMachine;
DebugManager* mDebugManager; DebugManager* mDebugManager;
CePendingExpr* mDebugPendingExpr; CePendingExpr* mDebugPendingExpr;
CeDbgState* mCurDbgState; CeDbgState* mCurDbgState;
Array<CeBreakpoint*> mBreakpoints; Array<CeBreakpoint*> mBreakpoints;
Dictionary<String, CeFileInfo*> mFileInfo; Dictionary<String, CeFileInfo*> mFileInfo;
Dictionary<int, CeDbgTypeInfo> mDbgTypeInfoMap; Dictionary<int, CeDbgTypeInfo> mDbgTypeInfoMap;
Array<CeDbgStackInfo> mDbgCallStack; Array<CeDbgStackInfo> mDbgCallStack;
CeEvaluationContext* mCurEvaluationContext; CeEvaluationContext* mCurEvaluationContext;
CeBreakpoint* mActiveBreakpoint; CeBreakpoint* mActiveBreakpoint;
int mBreakpointVersion; int mBreakpointVersion;
bool mBreakpointCacheDirty; bool mBreakpointCacheDirty;
bool mBreakpointFramesDirty; bool mBreakpointFramesDirty;
int mCurDisasmFuncId; int mCurDisasmFuncId;
int mPendingActiveFrameOffset; int mPendingActiveFrameOffset;
@ -270,7 +270,7 @@ public:
bool CheckConditionalBreakpoint(CeBreakpoint* breakpoint); bool CheckConditionalBreakpoint(CeBreakpoint* breakpoint);
bool SetupStep(int frameIdx = 0); bool SetupStep(int frameIdx = 0);
CeFrame* GetFrame(int callStackIdx); CeFrame* GetFrame(int callStackIdx);
String DoEvaluate(CePendingExpr* pendingExpr, bool inCompilerThread); String DoEvaluate(CePendingExpr* pendingExpr, bool inCompilerThread);
String Evaluate(const StringImpl& expr, CeFormatInfo formatInfo, int callStackIdx, int cursorPos, int language, DwEvalExpressionFlags expressionFlags); String Evaluate(const StringImpl& expr, CeFormatInfo formatInfo, int callStackIdx, int cursorPos, int language, DwEvalExpressionFlags expressionFlags);
DwDisplayInfo* GetDisplayInfo(const StringImpl& referenceId); DwDisplayInfo* GetDisplayInfo(const StringImpl& referenceId);
@ -296,7 +296,7 @@ public:
void UpdateBreakpointCache(); void UpdateBreakpointCache();
void UpdateBreakpointFrames(); void UpdateBreakpointFrames();
void UpdateBreakpointAddrs(); void UpdateBreakpointAddrs();
void UpdateBreakpoints(CeFunction* ceFunction); void UpdateBreakpoints(CeFunction* ceFunction);
void Continue(); void Continue();
CeDbgTypeInfo* GetDbgTypeInfo(int typeId); CeDbgTypeInfo* GetDbgTypeInfo(int typeId);
CeDbgTypeInfo* GetDbgTypeInfo(BfIRType irType); CeDbgTypeInfo* GetDbgTypeInfo(BfIRType irType);
@ -346,7 +346,7 @@ public:
virtual void StepIntoSpecific(intptr addr) override; virtual void StepIntoSpecific(intptr addr) override;
virtual void StepOver(bool inAssembly) override; virtual void StepOver(bool inAssembly) override;
virtual void StepOut(bool inAssembly) override; virtual void StepOut(bool inAssembly) override;
virtual void SetNextStatement(bool inAssembly, const StringImpl& fileName, int64 lineNumOrAsmAddr, int wantColumn) override; virtual void SetNextStatement(bool inAssembly, const StringImpl& fileName, int64 lineNumOrAsmAddr, int wantColumn) override;
//virtual DbgTypedValue GetRegister(const StringImpl& regName, CPURegisters* registers, Array<RegForm>* regForms = NULL) override; //virtual DbgTypedValue GetRegister(const StringImpl& regName, CPURegisters* registers, Array<RegForm>* regForms = NULL) override;
virtual String Evaluate(const StringImpl& expr, int callStackIdx, int cursorPos, int language, DwEvalExpressionFlags expressionFlags) override; virtual String Evaluate(const StringImpl& expr, int callStackIdx, int cursorPos, int language, DwEvalExpressionFlags expressionFlags) override;
virtual String EvaluateContinue() override; virtual String EvaluateContinue() override;

File diff suppressed because it is too large Load diff

View file

@ -80,17 +80,17 @@ enum CeOp : int16
CeOp_JmpIf, CeOp_JmpIf,
CeOp_JmpIfNot, CeOp_JmpIfNot,
CeOp_Error, CeOp_Error,
CeOp_DynamicCastCheck, CeOp_DynamicCastCheck,
CeOp_GetReflectType, CeOp_GetReflectType,
CeOp_GetString, CeOp_GetString,
CeOp_Malloc, CeOp_Malloc,
CeOp_Free, CeOp_Free,
CeOp_MemSet, CeOp_MemSet,
CeOp_MemSet_Const, CeOp_MemSet_Const,
CeOp_MemCpy, CeOp_MemCpy,
CeOp_FrameAddr_32, CeOp_FrameAddr_32,
CeOp_FrameAddr_64, CeOp_FrameAddr_64,
CeOp_FrameAddrOfs_32, CeOp_FrameAddrOfs_32,
@ -116,7 +116,7 @@ enum CeOp : int16
CeOp_GetMethod_Virt, CeOp_GetMethod_Virt,
CeOp_GetMethod_IFace, CeOp_GetMethod_IFace,
CeOp_Call, CeOp_Call,
CeOp_Conv_I8_I16, CeOp_Conv_I8_I16,
CeOp_Conv_I8_I32, CeOp_Conv_I8_I32,
CeOp_Conv_I8_I64, CeOp_Conv_I8_I64,
@ -128,7 +128,7 @@ enum CeOp : int16
CeOp_Conv_I16_F64, CeOp_Conv_I16_F64,
CeOp_Conv_I32_I64, CeOp_Conv_I32_I64,
CeOp_Conv_I32_F32, CeOp_Conv_I32_F32,
CeOp_Conv_I32_F64, CeOp_Conv_I32_F64,
CeOp_Conv_I64_F32, CeOp_Conv_I64_F32,
CeOp_Conv_I64_F64, CeOp_Conv_I64_F64,
CeOp_Conv_U8_U16, CeOp_Conv_U8_U16,
@ -168,7 +168,7 @@ enum CeOp : int16
CEOP_SIZED_NUMERIC_PLUSF(AddConst), CEOP_SIZED_NUMERIC_PLUSF(AddConst),
CEOP_SIZED_NUMERIC_PLUSF(Add), CEOP_SIZED_NUMERIC_PLUSF(Add),
CEOP_SIZED_NUMERIC_PLUSF(Sub), CEOP_SIZED_NUMERIC_PLUSF(Sub),
CEOP_SIZED_NUMERIC_PLUSF(Mul), CEOP_SIZED_NUMERIC_PLUSF(Mul),
CEOP_SIZED_NUMERIC_PLUSF(Div), CEOP_SIZED_NUMERIC_PLUSF(Div),
CEOP_SIZED_UNUMERIC(Div), CEOP_SIZED_UNUMERIC(Div),
CEOP_SIZED_NUMERIC_PLUSF(Mod), CEOP_SIZED_NUMERIC_PLUSF(Mod),
@ -179,7 +179,7 @@ enum CeOp : int16
CEOP_SIZED_NUMERIC(Shl), CEOP_SIZED_NUMERIC(Shl),
CEOP_SIZED_NUMERIC(Shr), CEOP_SIZED_NUMERIC(Shr),
CEOP_SIZED_UNUMERIC(Shr), CEOP_SIZED_UNUMERIC(Shr),
CEOP_SIZED_FLOAT(Acos), CEOP_SIZED_FLOAT(Acos),
CEOP_SIZED_FLOAT(Asin), CEOP_SIZED_FLOAT(Asin),
CEOP_SIZED_FLOAT(Atan), CEOP_SIZED_FLOAT(Atan),
@ -190,7 +190,7 @@ enum CeOp : int16
CEOP_SIZED_FLOAT(Exp), CEOP_SIZED_FLOAT(Exp),
CEOP_SIZED_FLOAT(Floor), CEOP_SIZED_FLOAT(Floor),
CEOP_SIZED_FLOAT(Log), CEOP_SIZED_FLOAT(Log),
CEOP_SIZED_FLOAT(Log10), CEOP_SIZED_FLOAT(Log10),
CEOP_SIZED_FLOAT(Pow), CEOP_SIZED_FLOAT(Pow),
CEOP_SIZED_FLOAT(Round), CEOP_SIZED_FLOAT(Round),
CEOP_SIZED_FLOAT(Sin), CEOP_SIZED_FLOAT(Sin),
@ -198,7 +198,7 @@ enum CeOp : int16
CEOP_SIZED_FLOAT(Sqrt), CEOP_SIZED_FLOAT(Sqrt),
CEOP_SIZED_FLOAT(Tan), CEOP_SIZED_FLOAT(Tan),
CEOP_SIZED_FLOAT(Tanh), CEOP_SIZED_FLOAT(Tanh),
CEOP_SIZED_NUMERIC_PLUSF(Cmp_EQ), CEOP_SIZED_NUMERIC_PLUSF(Cmp_EQ),
CEOP_SIZED_NUMERIC_PLUSF(Cmp_NE), CEOP_SIZED_NUMERIC_PLUSF(Cmp_NE),
CEOP_SIZED_NUMERIC_PLUSF(Cmp_SLT), CEOP_SIZED_NUMERIC_PLUSF(Cmp_SLT),
@ -307,7 +307,7 @@ public:
}; };
struct CeDbgInlineEntry struct CeDbgInlineEntry
{ {
int mScope; int mScope;
int mLine; int mLine;
int mColumn; int mColumn;
@ -329,7 +329,7 @@ public:
mCeFunction = NULL; mCeFunction = NULL;
mRefCount = 0; mRefCount = 0;
} }
~CeFunctionInfo(); ~CeFunctionInfo();
BfTypeInstance* GetOwner() BfTypeInstance* GetOwner()
@ -447,14 +447,14 @@ enum CeFunctionKind
CeFunctionKind_Method_GetInfo, CeFunctionKind_Method_GetInfo,
CeFunctionKind_Method_GetParamInfo, CeFunctionKind_Method_GetParamInfo,
CeFunctionKind_Method_GetGenericArg, CeFunctionKind_Method_GetGenericArg,
CeFunctionKind_SetReturnType, CeFunctionKind_SetReturnType,
CeFunctionKind_EmitTypeBody, CeFunctionKind_EmitTypeBody,
CeFunctionKind_EmitAddInterface, CeFunctionKind_EmitAddInterface,
CeFunctionKind_EmitMethodEntry, CeFunctionKind_EmitMethodEntry,
CeFunctionKind_EmitMethodExit, CeFunctionKind_EmitMethodExit,
CeFunctionKind_EmitMixin, CeFunctionKind_EmitMixin,
CeFunctionKind_BfpDirectory_Create, CeFunctionKind_BfpDirectory_Create,
CeFunctionKind_BfpDirectory_Rename, CeFunctionKind_BfpDirectory_Rename,
CeFunctionKind_BfpDirectory_Delete, CeFunctionKind_BfpDirectory_Delete,
@ -483,7 +483,7 @@ enum CeFunctionKind
CeFunctionKind_BfpFile_GetTempFileName, CeFunctionKind_BfpFile_GetTempFileName,
CeFunctionKind_BfpFile_GetFullPath, CeFunctionKind_BfpFile_GetFullPath,
CeFunctionKind_BfpFile_GetActualPath, CeFunctionKind_BfpFile_GetActualPath,
CeFunctionKind_BfpFindFileData_FindFirstFile, CeFunctionKind_BfpFindFileData_FindFirstFile,
CeFunctionKind_BfpFindFileData_FindNextFile, CeFunctionKind_BfpFindFileData_FindNextFile,
CeFunctionKind_BfpFindFileData_GetFileName, CeFunctionKind_BfpFindFileData_GetFileName,
@ -521,7 +521,7 @@ enum CeFunctionKind
CeFunctionKind_Math_Asin, CeFunctionKind_Math_Asin,
CeFunctionKind_Math_Atan, CeFunctionKind_Math_Atan,
CeFunctionKind_Math_Atan2, CeFunctionKind_Math_Atan2,
CeFunctionKind_Math_Ceiling, CeFunctionKind_Math_Ceiling,
CeFunctionKind_Math_Cos, CeFunctionKind_Math_Cos,
CeFunctionKind_Math_Cosh, CeFunctionKind_Math_Cosh,
CeFunctionKind_Math_Exp, CeFunctionKind_Math_Exp,
@ -535,7 +535,7 @@ enum CeFunctionKind
CeFunctionKind_Math_Sinh, CeFunctionKind_Math_Sinh,
CeFunctionKind_Math_Sqrt, CeFunctionKind_Math_Sqrt,
CeFunctionKind_Math_Tan, CeFunctionKind_Math_Tan,
CeFunctionKind_Math_Tanh, CeFunctionKind_Math_Tanh,
}; };
class CeConstStructFixup class CeConstStructFixup
@ -596,14 +596,14 @@ public:
{ {
mTypeId = -1; mTypeId = -1;
mSize = 0; mSize = 0;
mAddr = 0; mAddr = 0;
mBindExecuteId = -1; mBindExecuteId = -1;
} }
}; };
class CeDbgVariable class CeDbgVariable
{ {
public: public:
String mName; String mName;
CeOperand mValue; CeOperand mValue;
BfType* mType; BfType* mType;
@ -641,17 +641,17 @@ public:
CeMachine* mCeMachine; CeMachine* mCeMachine;
CeFunctionInfo* mCeFunctionInfo; CeFunctionInfo* mCeFunctionInfo;
CeInnerFunctionInfo* mCeInnerFunctionInfo; CeInnerFunctionInfo* mCeInnerFunctionInfo;
BfMethodInstance* mMethodInstance; BfMethodInstance* mMethodInstance;
CeFunctionKind mFunctionKind; CeFunctionKind mFunctionKind;
InitializeState mInitializeState; InitializeState mInitializeState;
bool mFailed; bool mFailed;
bool mIsVarReturn; bool mIsVarReturn;
Array<uint8> mCode; Array<uint8> mCode;
Array<CeDbgScope> mDbgScopes; Array<CeDbgScope> mDbgScopes;
Array<CeDbgInlineEntry> mDbgInlineTable; Array<CeDbgInlineEntry> mDbgInlineTable;
Array<CeDbgMethodRef> mDbgMethodRefTable; Array<CeDbgMethodRef> mDbgMethodRefTable;
Array<CeEmitEntry> mEmitTable; Array<CeEmitEntry> mEmitTable;
Array<CeCallEntry> mCallTable; Array<CeCallEntry> mCallTable;
Array<CeStringEntry> mStringTable; Array<CeStringEntry> mStringTable;
Array<CeConstStructData> mConstStructTable; Array<CeConstStructData> mConstStructTable;
Array<CeStaticFieldEntry> mStaticFieldTable; Array<CeStaticFieldEntry> mStaticFieldTable;
@ -659,7 +659,7 @@ public:
Array<CeFunction*> mInnerFunctions; Array<CeFunction*> mInnerFunctions;
Dictionary<int, CeBreakpointBind> mBreakpoints; Dictionary<int, CeBreakpointBind> mBreakpoints;
String mGenError; String mGenError;
int mFrameSize; int mFrameSize;
int mMaxReturnSize; int mMaxReturnSize;
int mId; int mId;
int mBreakpointVersion; int mBreakpointVersion;
@ -671,7 +671,7 @@ public:
mCeMachine = NULL; mCeMachine = NULL;
mCeFunctionInfo = NULL; mCeFunctionInfo = NULL;
mCeInnerFunctionInfo = NULL; mCeInnerFunctionInfo = NULL;
mFunctionKind = CeFunctionKind_NotSet; mFunctionKind = CeFunctionKind_NotSet;
mInitializeState = InitializeState_None; mInitializeState = InitializeState_None;
mMethodInstance = NULL; mMethodInstance = NULL;
mFailed = false; mFailed = false;
@ -681,7 +681,7 @@ public:
mBreakpointVersion = 0; mBreakpointVersion = 0;
mId = -1; mId = -1;
mDbgInfo = NULL; mDbgInfo = NULL;
} }
~CeFunction(); ~CeFunction();
void Print(); void Print();
@ -747,7 +747,7 @@ enum CeSizeClass
class CeDumpContext class CeDumpContext
{ {
public: public:
Dictionary<int, CeDbgVariable*> mVarMap; Dictionary<int, CeDbgVariable*> mVarMap;
CeFunction* mCeFunction; CeFunction* mCeFunction;
String mStr; String mStr;
@ -765,13 +765,13 @@ public:
void DumpOperandInfo(CeOperandInfoKind operandInfoKind); void DumpOperandInfo(CeOperandInfoKind operandInfoKind);
void Next(); void Next();
void Dump(); void Dump();
}; };
struct CePhiOutgoing struct CePhiOutgoing
{ {
BeValue* mPhiValue; BeValue* mPhiValue;
BePhiInst* mPhiInst; BePhiInst* mPhiInst;
int mPhiBlockIdx; int mPhiBlockIdx;
}; };
@ -784,7 +784,7 @@ public:
public: public:
CeBlock() CeBlock()
{ {
mEmitOfs = -1; mEmitOfs = -1;
} }
}; };
@ -811,7 +811,7 @@ struct CeDbgInlineLookup
mDbgFile = NULL; mDbgFile = NULL;
mInlineAtIdx = -1; mInlineAtIdx = -1;
} }
bool operator==(const CeDbgInlineLookup& second) const bool operator==(const CeDbgInlineLookup& second) const
{ {
return (mDbgFile == second.mDbgFile) && (mDbgFile == second.mDbgFile); return (mDbgFile == second.mDbgFile) && (mDbgFile == second.mDbgFile);
@ -820,18 +820,18 @@ struct CeDbgInlineLookup
class CeBuilder class CeBuilder
{ {
public: public:
CeBuilder* mParentBuilder; CeBuilder* mParentBuilder;
CeMachine* mCeMachine; CeMachine* mCeMachine;
CeFunction* mCeFunction; CeFunction* mCeFunction;
BeFunction* mBeFunction; BeFunction* mBeFunction;
CeOperand mReturnVal; CeOperand mReturnVal;
BeType* mIntPtrType; BeType* mIntPtrType;
int mPtrSize; int mPtrSize;
String mError; String mError;
BeDbgLoc* mCurDbgLoc; BeDbgLoc* mCurDbgLoc;
Array<CeBlock> mBlocks; Array<CeBlock> mBlocks;
Array<CeJumpEntry> mJumpTable; Array<CeJumpEntry> mJumpTable;
Dictionary<BeValue*, CeOperand> mValueToOperand; Dictionary<BeValue*, CeOperand> mValueToOperand;
int mFrameSize; int mFrameSize;
@ -845,7 +845,7 @@ public:
Dictionary<BeGlobalVariable*, int> mStaticFieldMap; Dictionary<BeGlobalVariable*, int> mStaticFieldMap;
Dictionary<String, BfFieldInstance*> mStaticFieldInstanceMap; Dictionary<String, BfFieldInstance*> mStaticFieldInstanceMap;
Dictionary<BeValue*, int> mDbgVariableMap; Dictionary<BeValue*, int> mDbgVariableMap;
public: public:
CeBuilder() CeBuilder()
{ {
@ -857,7 +857,7 @@ public:
mCurDbgLoc = NULL; mCurDbgLoc = NULL;
mFrameSize = 0; mFrameSize = 0;
} }
void Fail(const StringImpl& error); void Fail(const StringImpl& error);
CeOperand FrameAlloc(BeType* type); CeOperand FrameAlloc(BeType* type);
@ -871,7 +871,7 @@ public:
int GetCodePos(); int GetCodePos();
void HandleParams(); void HandleParams();
void Emit(uint8 val); void Emit(uint8 val);
void Emit(CeOp val); void Emit(CeOp val);
void EmitSizedOp(CeOp val, int size); void EmitSizedOp(CeOp val, int size);
@ -881,7 +881,7 @@ public:
void Emit(void* ptr, int size); void Emit(void* ptr, int size);
void EmitZeroes(int size); void EmitZeroes(int size);
void EmitJump(CeOp op, const CeOperand& block); void EmitJump(CeOp op, const CeOperand& block);
void EmitBinarySwitchSection(BeSwitchInst* switchInst, int startIdx, int endIdx); void EmitBinarySwitchSection(BeSwitchInst* switchInst, int startIdx, int endIdx);
void EmitFrameOffset(const CeOperand& val); void EmitFrameOffset(const CeOperand& val);
void FlushPhi(CeBlock* ceBlock, int targetBlockIdx); void FlushPhi(CeBlock* ceBlock, int targetBlockIdx);
@ -920,7 +920,7 @@ public:
class CeStaticFieldInfo class CeStaticFieldInfo
{ {
public: public:
addr_ce mAddr; addr_ce mAddr;
public: public:
@ -970,16 +970,16 @@ public:
class CeEmitContext class CeEmitContext
{ {
public: public:
BfType* mType; BfType* mType;
BfMethodInstance* mMethodInstance; BfMethodInstance* mMethodInstance;
Array<int32> mInterfaces; Array<int32> mInterfaces;
String mEmitData; String mEmitData;
String mExitEmitData; String mExitEmitData;
bool mFailed; bool mFailed;
CeEmitContext() CeEmitContext()
{ {
mType = NULL; mType = NULL;
mMethodInstance = NULL; mMethodInstance = NULL;
mFailed = false; mFailed = false;
} }
@ -1088,15 +1088,15 @@ public:
int mExecuteId; int mExecuteId;
CeEvalFlags mCurEvalFlags; CeEvalFlags mCurEvalFlags;
// These are only valid for the current execution // These are only valid for the current execution
ContiguousHeap* mHeap; ContiguousHeap* mHeap;
Array<CeFrame> mCallStack; Array<CeFrame> mCallStack;
Array<uint8> mMemory; Array<uint8> mMemory;
int mStackSize; int mStackSize;
Dictionary<int, addr_ce> mStringMap; Dictionary<int, addr_ce> mStringMap;
Dictionary<int, addr_ce> mReflectMap; Dictionary<int, addr_ce> mReflectMap;
Dictionary<Val128, addr_ce> mConstDataMap; Dictionary<Val128, addr_ce> mConstDataMap;
HashSet<int> mStaticCtorExecSet; HashSet<int> mStaticCtorExecSet;
Dictionary<String, CeStaticFieldInfo> mStaticFieldMap; Dictionary<String, CeStaticFieldInfo> mStaticFieldMap;
Dictionary<int, CeInternalData*> mInternalDataMap; Dictionary<int, CeInternalData*> mInternalDataMap;
int mCurHandleId; int mCurHandleId;
@ -1109,16 +1109,16 @@ public:
CeCallSource* mCurCallSource; CeCallSource* mCurCallSource;
BfModule* mCurModule; BfModule* mCurModule;
CeFrame* mCurFrame; CeFrame* mCurFrame;
CeEmitContext* mCurEmitContext; CeEmitContext* mCurEmitContext;
String mWorkingDir; String mWorkingDir;
public: public:
CeContext(); CeContext();
~CeContext(); ~CeContext();
BfError* Fail(const StringImpl& error); BfError* Fail(const StringImpl& error);
BfError* Fail(const CeFrame& curFrame, const StringImpl& error); BfError* Fail(const CeFrame& curFrame, const StringImpl& error);
void CalcWorkingDir(); void CalcWorkingDir();
void FixRelativePath(StringImpl& path); void FixRelativePath(StringImpl& path);
bool AddRebuild(const CeRebuildKey& key, const CeRebuildValue& value); bool AddRebuild(const CeRebuildKey& key, const CeRebuildValue& value);
@ -1143,8 +1143,8 @@ public:
bool GetCustomAttribute(BfModule* module, BfIRConstHolder* constHolder, BfCustomAttributes* customAttributes, int attributeIdx, addr_ce resultAddr); bool GetCustomAttribute(BfModule* module, BfIRConstHolder* constHolder, BfCustomAttributes* customAttributes, int attributeIdx, addr_ce resultAddr);
BfType* GetCustomAttributeType(BfCustomAttributes* customAttributes, int attributeIdx); BfType* GetCustomAttributeType(BfCustomAttributes* customAttributes, int attributeIdx);
bool WriteConstant(BfModule* module, addr_ce addr, BfConstant* constant, BfType* type, bool isParams = false); bool WriteConstant(BfModule* module, addr_ce addr, BfConstant* constant, BfType* type, bool isParams = false);
BfIRValue CreateConstant(BfModule* module, uint8* ptr, BfType* type, BfType** outType = NULL); BfIRValue CreateConstant(BfModule* module, uint8* ptr, BfType* type, BfType** outType = NULL);
BfIRValue CreateAttribute(BfAstNode* targetSrc, BfModule* module, BfIRConstHolder* constHolder, BfCustomAttribute* customAttribute, addr_ce ceAttrAddr = 0); BfIRValue CreateAttribute(BfAstNode* targetSrc, BfModule* module, BfIRConstHolder* constHolder, BfCustomAttribute* customAttribute, addr_ce ceAttrAddr = 0);
bool Execute(CeFunction* startFunction, uint8* startStackPtr, uint8* startFramePtr, BfType*& returnType, BfType*& castReturnType); bool Execute(CeFunction* startFunction, uint8* startStackPtr, uint8* startFramePtr, BfType*& returnType, BfType*& castReturnType);
@ -1173,14 +1173,14 @@ public:
Kind_Evaluate Kind_Evaluate
}; };
Kind mKind; Kind mKind;
int mNextInstIdx; int mNextInstIdx;
int mStartDepth; int mStartDepth;
public: public:
CeStepState() CeStepState()
{ {
mKind = Kind_None; mKind = Kind_None;
mNextInstIdx = -1; mNextInstIdx = -1;
mStartDepth = 0; mStartDepth = 0;
} }
@ -1194,24 +1194,24 @@ public:
Dictionary<int, CeFunction*> mFunctionIdMap; // Only used for 32-bit and debugging Dictionary<int, CeFunction*> mFunctionIdMap; // Only used for 32-bit and debugging
Dictionary<BfType*, CeTypeInfo> mTypeInfoMap; Dictionary<BfType*, CeTypeInfo> mTypeInfoMap;
HashSet<BfMethodInstance*> mMethodInstanceSet; HashSet<BfMethodInstance*> mMethodInstanceSet;
HashSet<BfFieldInstance*> mFieldInstanceSet; HashSet<BfFieldInstance*> mFieldInstanceSet;
Array<CeContext*> mContextList; Array<CeContext*> mContextList;
BfCompiler* mCompiler; BfCompiler* mCompiler;
BfModule* mCeModule; BfModule* mCeModule;
int mRevision; int mRevision;
int mMethodBindRevision; int mMethodBindRevision;
int mRevisionExecuteTime; int mRevisionExecuteTime;
int mCurFunctionId; int mCurFunctionId;
int mExecuteId; int mExecuteId;
CeAppendAllocInfo* mAppendAllocInfo; CeAppendAllocInfo* mAppendAllocInfo;
CeContext* mCurContext; CeContext* mCurContext;
CeEmitContext* mCurEmitContext; CeEmitContext* mCurEmitContext;
CeCallSource* mCurCallSource; CeCallSource* mCurCallSource;
CeBuilder* mCurBuilder; CeBuilder* mCurBuilder;
CeFunction* mPreparingFunction; CeFunction* mPreparingFunction;
BfParser* mTempParser; BfParser* mTempParser;
BfReducer* mTempReducer; BfReducer* mTempReducer;
@ -1221,27 +1221,27 @@ public:
SyncEvent mDebugEvent; SyncEvent mDebugEvent;
CeStepState mStepState; CeStepState mStepState;
CeDebugger* mDebugger; CeDebugger* mDebugger;
bool mDbgPaused; bool mDbgPaused;
bool mSpecialCheck; bool mSpecialCheck;
bool mDbgWantBreak; bool mDbgWantBreak;
public: public:
CeMachine(BfCompiler* compiler); CeMachine(BfCompiler* compiler);
~CeMachine(); ~CeMachine();
void Init(); void Init();
BeContext* GetBeContext(); BeContext* GetBeContext();
BeModule* GetBeModule(); BeModule* GetBeModule();
int GetInstSize(CeFunction* ceFunction, int instIdx); int GetInstSize(CeFunction* ceFunction, int instIdx);
void DerefMethodInfo(CeFunctionInfo* ceFunctionInfo); void DerefMethodInfo(CeFunctionInfo* ceFunctionInfo);
void RemoveFunc(CeFunction* ceFunction); void RemoveFunc(CeFunction* ceFunction);
void RemoveMethod(BfMethodInstance* methodInstance); void RemoveMethod(BfMethodInstance* methodInstance);
void CreateFunction(BfMethodInstance* methodInstance, CeFunction* ceFunction); void CreateFunction(BfMethodInstance* methodInstance, CeFunction* ceFunction);
CeErrorKind WriteConstant(CeConstStructData& data, BeConstant* constVal, CeContext* ceContext); CeErrorKind WriteConstant(CeConstStructData& data, BeConstant* constVal, CeContext* ceContext);
void CheckFunctionKind(CeFunction* ceFunction); void CheckFunctionKind(CeFunction* ceFunction);
void PrepareFunction(CeFunction* methodInstance, CeBuilder* parentBuilder); void PrepareFunction(CeFunction* methodInstance, CeBuilder* parentBuilder);
void MapFunctionId(CeFunction* ceFunction); void MapFunctionId(CeFunction* ceFunction);
void CheckFunctions(); void CheckFunctions();
@ -1249,14 +1249,14 @@ public:
CeFunction* GetPreparedFunction(BfMethodInstance* methodInstance); CeFunction* GetPreparedFunction(BfMethodInstance* methodInstance);
CeTypeInfo* GetTypeInfo(BfType* type); CeTypeInfo* GetTypeInfo(BfType* type);
BfMethodInstance* GetMethodInstance(int64 methodHandle); BfMethodInstance* GetMethodInstance(int64 methodHandle);
BfFieldInstance* GetFieldInstance(int64 fieldHandle); BfFieldInstance* GetFieldInstance(int64 fieldHandle);
public: public:
void CompileStarted(); void CompileStarted();
void CompileDone(); void CompileDone();
CeFunction* QueueMethod(BfMethodInstance* methodInstance, BfIRValue func); CeFunction* QueueMethod(BfMethodInstance* methodInstance, BfIRValue func);
void QueueMethod(BfModuleMethodInstance moduleMethodInstance); void QueueMethod(BfModuleMethodInstance moduleMethodInstance);
void QueueStaticField(BfFieldInstance* fieldInstance, const StringImpl& mangledFieldName); void QueueStaticField(BfFieldInstance* fieldInstance, const StringImpl& mangledFieldName);
void SetAppendAllocInfo(BfModule* module, BfIRValue allocValue, BfIRValue appendSizeValue); void SetAppendAllocInfo(BfModule* module, BfIRValue allocValue, BfIRValue appendSizeValue);
void ClearAppendAllocInfo(); void ClearAppendAllocInfo();
@ -1277,7 +1277,7 @@ namespace std
{ {
return BeefHash<Beefy::String>()(key.mString) ^ (size_t)key.mKind; return BeefHash<Beefy::String>()(key.mString) ^ (size_t)key.mKind;
} }
}; };
template <> template <>
struct hash<Beefy::CeDbgInlineLookup> struct hash<Beefy::CeDbgInlineLookup>

View file

@ -16,7 +16,7 @@ MemReporter::~MemReporter()
int MemReporter::GetChildSizes(Entry* entry) int MemReporter::GetChildSizes(Entry* entry)
{ {
int childSizes = 0; int childSizes = 0;
for (auto& childPair : entry->mChildren) for (auto& childPair : entry->mChildren)
{ {
auto child = childPair.mValue; auto child = childPair.mValue;
childSizes += child->mSize + GetChildSizes(child); childSizes += child->mSize + GetChildSizes(child);
@ -29,10 +29,10 @@ void MemReporter::Report(int depth, Entry* entry)
String str; String str;
for (int i = 0; i < depth; i++) for (int i = 0; i < depth; i++)
str += " "; str += " ";
str += entry->mName; str += entry->mName;
while (str.length() < 64) while (str.length() < 64)
str += ' '; str += ' ';
if (entry->mChildSize == -1) if (entry->mChildSize == -1)
entry->mChildSize = GetChildSizes(entry); entry->mChildSize = GetChildSizes(entry);
@ -45,7 +45,7 @@ void MemReporter::Report(int depth, Entry* entry)
Array<Entry*> entries; Array<Entry*> entries;
for (auto& kv : entry->mChildren) for (auto& kv : entry->mChildren)
{ {
auto* entry = kv.mValue; auto* entry = kv.mValue;
entry->mChildSize = GetChildSizes(entry); entry->mChildSize = GetChildSizes(entry);
entries.Add(kv.mValue); entries.Add(kv.mValue);
@ -63,7 +63,7 @@ void MemReporter::BeginSection(const StringView& name)
{ {
Entry** entryPtr; Entry** entryPtr;
if (!mCurEntry->mChildren.TryAdd(StringImpl::MakeRef(name), NULL, &entryPtr)) if (!mCurEntry->mChildren.TryAdd(StringImpl::MakeRef(name), NULL, &entryPtr))
{ {
mCurEntry = *entryPtr; mCurEntry = *entryPtr;
mCurEntry->mCount++; mCurEntry->mCount++;
return; return;
@ -95,6 +95,6 @@ void MemReporter::EndSection()
} }
void MemReporter::Report() void MemReporter::Report()
{ {
Report(0, &mRoot); Report(0, &mRoot);
} }

View file

@ -36,24 +36,24 @@ public:
Entry* mCurEntry; Entry* mCurEntry;
bool mShowInKB; bool mShowInKB;
public: public:
int GetChildSizes(Entry* entry); int GetChildSizes(Entry* entry);
void Report(int depth, Entry* entry); void Report(int depth, Entry* entry);
public: public:
MemReporter(); MemReporter();
~MemReporter(); ~MemReporter();
void BeginSection(const StringView& name); void BeginSection(const StringView& name);
void Add(int size); void Add(int size);
void Add(const StringView& name, int size); void Add(const StringView& name, int size);
template <typename T> template <typename T>
void AddVec(const T& vec, bool addContainerSize = true) void AddVec(const T& vec, bool addContainerSize = true)
{ {
Add((addContainerSize ? sizeof(T) : 0) + (int)vec.mAllocSize * sizeof(typename T::value_type)); Add((addContainerSize ? sizeof(T) : 0) + (int)vec.mAllocSize * sizeof(typename T::value_type));
} }
template <typename T> template <typename T>
void AddVec(const StringView& name, const T& vec, bool addContainerSize = true) void AddVec(const StringView& name, const T& vec, bool addContainerSize = true)
{ {
@ -61,21 +61,21 @@ public:
Add((addContainerSize ? sizeof(T) : 0) + (int)vec.mAllocSize * sizeof(typename T::value_type)); Add((addContainerSize ? sizeof(T) : 0) + (int)vec.mAllocSize * sizeof(typename T::value_type));
EndSection(); EndSection();
} }
template <typename T> template <typename T>
void AddVecPtr(const std::vector<T>& vec, bool addContainerSize = true) void AddVecPtr(const std::vector<T>& vec, bool addContainerSize = true)
{ {
Add((addContainerSize ? sizeof(T) : 0) + Add((addContainerSize ? sizeof(T) : 0) +
(int)vec.capacity() * sizeof(T) + (int)vec.capacity() * sizeof(T) +
(int)vec.size() * sizeof(typename std::remove_pointer<T>::type)); //-V220 (int)vec.size() * sizeof(typename std::remove_pointer<T>::type)); //-V220
} }
template <typename T> template <typename T>
void AddVecPtr(const Array<T>& vec, bool addContainerSize = true) void AddVecPtr(const Array<T>& vec, bool addContainerSize = true)
{ {
Add((addContainerSize ? sizeof(T) : 0) + Add((addContainerSize ? sizeof(T) : 0) +
(int)vec.mAllocSize * sizeof(T) + (int)vec.mAllocSize * sizeof(T) +
(int)vec.size() * sizeof(typename std::remove_pointer<T>::type)); //-V220 (int)vec.size() * sizeof(typename std::remove_pointer<T>::type)); //-V220
} }
template <typename T> template <typename T>
@ -83,12 +83,12 @@ public:
{ {
Add(name, (addContainerSize ? sizeof(T) : 0) + Add(name, (addContainerSize ? sizeof(T) : 0) +
(int)vec.mAllocSize * sizeof(T) + (int)vec.mAllocSize * sizeof(T) +
(int)vec.size() * sizeof(typename std::remove_pointer<T>::type)); //-V220 (int)vec.size() * sizeof(typename std::remove_pointer<T>::type)); //-V220
} }
template <typename T> template <typename T>
void AddMap(const StringView& name, const T& map, bool addContainerSize = true) void AddMap(const StringView& name, const T& map, bool addContainerSize = true)
{ {
Add(name, (addContainerSize ? sizeof(T) : 0) + map.mAllocSize * (sizeof(typename T::EntryPair) + sizeof(typename T::int_cosize))); Add(name, (addContainerSize ? sizeof(T) : 0) + map.mAllocSize * (sizeof(typename T::EntryPair) + sizeof(typename T::int_cosize)));
} }
@ -109,7 +109,7 @@ public:
{ {
Add((addContainerSize ? sizeof(T) : 0) + map.mAllocSize * (sizeof(typename T::Entry) + sizeof(typename T::int_cosize))); Add((addContainerSize ? sizeof(T) : 0) + map.mAllocSize * (sizeof(typename T::Entry) + sizeof(typename T::int_cosize)));
} }
void AddStr(const StringImpl& str, bool addContainerSize = true) void AddStr(const StringImpl& str, bool addContainerSize = true)
{ {
Add((addContainerSize ? sizeof(StringImpl) : 0) + (int)str.GetAllocSize()); Add((addContainerSize ? sizeof(StringImpl) : 0) + (int)str.GetAllocSize());
@ -123,12 +123,11 @@ public:
void EndSection(); void EndSection();
void Report(); void Report();
template <typename T> template <typename T>
void AddBumpAlloc(const StringView& name, const T& alloc) void AddBumpAlloc(const StringView& name, const T& alloc)
{ {
BeginSection(name); BeginSection(name);
int usedSize = alloc.CalcUsedSize(); int usedSize = alloc.CalcUsedSize();
#ifdef BUMPALLOC_TRACKALLOCS #ifdef BUMPALLOC_TRACKALLOCS
@ -162,9 +161,9 @@ public:
Add("Unaccounted", usedSizeLeft); Add("Unaccounted", usedSizeLeft);
#else #else
Add("Used", usedSize); Add("Used", usedSize);
#endif #endif
Add("Waste", alloc.GetAllocSize() - usedSize); Add("Waste", alloc.GetAllocSize() - usedSize);
Add("Unused", alloc.GetTotalAllocSize() - alloc.GetAllocSize()); Add("Unused", alloc.GetTotalAllocSize() - alloc.GetAllocSize());
EndSection(); EndSection();
} }
@ -173,7 +172,7 @@ public:
class AutoMemReporter class AutoMemReporter
{ {
public: public:
MemReporter* mMemReporter; MemReporter* mMemReporter;
public: public:
AutoMemReporter(MemReporter* memReporter, const StringImpl& name) AutoMemReporter(MemReporter* memReporter, const StringImpl& name)

View file

@ -3,7 +3,7 @@
USING_NS_BF; USING_NS_BF;
enum DbgMiniDumpFlags enum DbgMiniDumpFlags
{ {
DbgMiniDumpFlag_MiniDumpNormal = 0x00000000, DbgMiniDumpFlag_MiniDumpNormal = 0x00000000,
DbgMiniDumpFlag_MiniDumpWithDataSegs = 0x00000001, DbgMiniDumpFlag_MiniDumpWithDataSegs = 0x00000001,
@ -41,18 +41,18 @@ bool DbgMiniDump::StartLoad(const StringImpl& path)
uint32 mVersion; uint32 mVersion;
uint32 mNumberOfStreams; uint32 mNumberOfStreams;
uint32 mStreamDirectoryRVA; uint32 mStreamDirectoryRVA;
uint32 mCheckSum; uint32 mCheckSum;
uint32 TimeDateStamp; uint32 TimeDateStamp;
uint64 Flags; uint64 Flags;
}; };
_Header& header = *(_Header*)((uint8*)mMF.mData); _Header& header = *(_Header*)((uint8*)mMF.mData);
if (header.mSignature != 'PMDM') if (header.mSignature != 'PMDM')
return false; return false;
mDirectory.mVals = (StreamDirectoryEntry*)((uint8*)mMF.mData + header.mStreamDirectoryRVA); mDirectory.mVals = (StreamDirectoryEntry*)((uint8*)mMF.mData + header.mStreamDirectoryRVA);
mDirectory.mSize = header.mNumberOfStreams; mDirectory.mSize = header.mNumberOfStreams;
return true; return true;
} }
@ -72,4 +72,4 @@ int DbgMiniDump::GetTargetBitCount()
} }
return 0; return 0;
} }

View file

@ -46,7 +46,7 @@ public:
bool StartLoad(const StringImpl& path); bool StartLoad(const StringImpl& path);
int GetTargetBitCount(); int GetTargetBitCount();
template <typename T> template <typename T>
T& GetStreamData(const StreamDirectoryEntry& entry) T& GetStreamData(const StreamDirectoryEntry& entry)
{ {
return *(T*)((uint8*)mMF.mData + entry.mDataRVA); return *(T*)((uint8*)mMF.mData + entry.mDataRVA);

View file

@ -80,7 +80,7 @@ DebugManager::DebugManager()
mStepOverExternalFiles = false; mStepOverExternalFiles = false;
mDebugger32 = NULL; mDebugger32 = NULL;
mDebugger64 = NULL; mDebugger64 = NULL;
mNetManager = new NetManager(); mNetManager = new NetManager();
mNetManager->mDebugManager = this; mNetManager->mDebugManager = this;
@ -106,12 +106,11 @@ DebugManager::~DebugManager()
delete mNetManager; delete mNetManager;
delete mDebugger64; delete mDebugger64;
delete mDebugger32; delete mDebugger32;
/*for (auto stepFilter : mStepFilters) /*for (auto stepFilter : mStepFilters)
{ {
}*/ }*/
delete mDebugVisualizers; delete mDebugVisualizers;
} }
void DebugManager::OutputMessage(const StringImpl& msg) void DebugManager::OutputMessage(const StringImpl& msg)
@ -144,7 +143,6 @@ void DebugManager::SetSourceServerCacheDir()
#endif #endif
} }
//#define CAPTURE_ALLOC_BACKTRACE //#define CAPTURE_ALLOC_BACKTRACE
//#define CAPTURE_ALLOC_SOURCES //#define CAPTURE_ALLOC_SOURCES
@ -153,7 +151,7 @@ const int sNumAllocAddrs = 0x300000;
const int sCaptureDepth = 14; const int sCaptureDepth = 14;
const int sCaptureOffset = 4; const int sCaptureOffset = 4;
static intptr gAllocAddrs[sNumAllocAddrs][sCaptureDepth]; static intptr gAllocAddrs[sNumAllocAddrs][sCaptureDepth];
#endif #endif
#ifdef CAPTURE_ALLOC_SOURCES #ifdef CAPTURE_ALLOC_SOURCES
#include <Dbghelp.h> #include <Dbghelp.h>
@ -191,7 +189,7 @@ static void ReallocEntry(long oldRequest, long newRequest, int newSize)
entry->mAllocSize = newSize; entry->mAllocSize = newSize;
gBfCaptureSourceAllocMap[newRequest] = *entry; gBfCaptureSourceAllocMap[newRequest] = *entry;
gBfCaptureSourceAllocMap.erase(itr); gBfCaptureSourceAllocMap.erase(itr);
} }
} }
static void RemoveAllocEntry(long lRequest) static void RemoveAllocEntry(long lRequest)
@ -203,13 +201,11 @@ static void RemoveAllocEntry(long lRequest)
entry->mLoc->mTotalSize -= entry->mAllocSize; entry->mLoc->mTotalSize -= entry->mAllocSize;
gBfCaptureSourceAllocMap.erase(itr); gBfCaptureSourceAllocMap.erase(itr);
} }
} }
//const LOC_HASHES //const LOC_HASHES
#endif #endif
static int gBfNumAllocs = 0; static int gBfNumAllocs = 0;
@ -246,7 +242,7 @@ static int BfAllocHook(int nAllocType, void *pvData,
if (hProcess == NULL) if (hProcess == NULL)
{ {
hProcess = GetCurrentProcess(); hProcess = GetCurrentProcess();
BOOL worked = SymInitialize(hProcess, NULL, TRUE); BOOL worked = SymInitialize(hProcess, NULL, TRUE);
} }
if (nAllocType == _HOOK_ALLOC) if (nAllocType == _HOOK_ALLOC)
@ -317,7 +313,6 @@ static int BfAllocHook(int nAllocType, void *pvData,
if ((captureAllocLoc->mIsEndpoint) && (foundSym)) if ((captureAllocLoc->mIsEndpoint) && (foundSym))
{ {
} }
gHashCaptureAllocSize[hashVal] = captureAllocLoc; gHashCaptureAllocSize[hashVal] = captureAllocLoc;
@ -330,7 +325,6 @@ static int BfAllocHook(int nAllocType, void *pvData,
continue; continue;
} }
captureAllocLoc->mTotalSize += (int)nSize; captureAllocLoc->mTotalSize += (int)nSize;
CaptureAllocEntry entry; CaptureAllocEntry entry;
@ -433,19 +427,18 @@ static int BfAllocHook(int nAllocType, void *pvData,
#endif //BF_PLATFORM_WINDOWS #endif //BF_PLATFORM_WINDOWS
void BfReportMemory() void BfReportMemory()
{ {
BfLogDbg("Used: %.2fM NumAllocs: %d Allocs: %.2fM\n", (gBfAllocCount - gBfFreeCount) / (1024.0 * 1024.0), gBfNumAllocs, gBfAllocCount / (1024.0 * 1024.0)); BfLogDbg("Used: %.2fM NumAllocs: %d Allocs: %.2fM\n", (gBfAllocCount - gBfFreeCount) / (1024.0 * 1024.0), gBfNumAllocs, gBfAllocCount / (1024.0 * 1024.0));
} }
void BfFullReportMemory() void BfFullReportMemory()
{ {
/*OutputDebugStrF("Testing OOB\n"); /*OutputDebugStrF("Testing OOB\n");
char* str = new char[12]; char* str = new char[12];
delete str; delete str;
char c = str[1];*/ char c = str[1];*/
if (gBfParserCache != NULL) if (gBfParserCache != NULL)
{ {
MemReporter memReporter; MemReporter memReporter;
@ -457,7 +450,7 @@ void BfFullReportMemory()
OutputDebugStrF("Used: %.2fM NumAllocs: %d Allocs: %.2fM\n", (gBfAllocCount - gBfFreeCount) / (1024.0 * 1024.0), gBfNumAllocs, gBfAllocCount / (1024.0 * 1024.0)); OutputDebugStrF("Used: %.2fM NumAllocs: %d Allocs: %.2fM\n", (gBfAllocCount - gBfFreeCount) / (1024.0 * 1024.0), gBfNumAllocs, gBfAllocCount / (1024.0 * 1024.0));
OutputDebugStrF("ChunkedDataBuffer allocated blocks: %d\n", ChunkedDataBuffer::sBlocksAllocated); OutputDebugStrF("ChunkedDataBuffer allocated blocks: %d\n", ChunkedDataBuffer::sBlocksAllocated);
if (gDebugManager != NULL) if (gDebugManager != NULL)
{ {
MemReporter memReporter; MemReporter memReporter;
@ -493,7 +486,7 @@ void BfFullReportMemory()
for (auto kv : byNameMap) for (auto kv : byNameMap)
{ {
//OutputDebugStrF("%dk %s\n", (kv.second + 1023) / 1024, kv.first.c_str()); //OutputDebugStrF("%dk %s\n", (kv.second + 1023) / 1024, kv.first.c_str());
bySizeMap.insert(std::multimap<int, String>::value_type(-kv.second, kv.first)); bySizeMap.insert(std::multimap<int, String>::value_type(-kv.second, kv.first));
} }
@ -528,7 +521,7 @@ struct _CrtMemBlockHeader
//static _CrtMemBlockHeader* __acrt_last_block; //static _CrtMemBlockHeader* __acrt_last_block;
void ShowMemoryUsage() void ShowMemoryUsage()
{ {
#ifdef BF_PLATFORM_WINDOWS #ifdef BF_PLATFORM_WINDOWS
PROCESS_MEMORY_COUNTERS processMemCounters; PROCESS_MEMORY_COUNTERS processMemCounters;
processMemCounters.cb = sizeof(PROCESS_MEMORY_COUNTERS); processMemCounters.cb = sizeof(PROCESS_MEMORY_COUNTERS);
@ -538,7 +531,7 @@ void ShowMemoryUsage()
static bool hasCheckpoint = true; static bool hasCheckpoint = true;
_CrtMemState memState; _CrtMemState memState;
_CrtMemCheckpoint(&memState); _CrtMemCheckpoint(&memState);
//OutputDebugStrF("Crt Size: %dk\n", (int)(memState.lTotalCount / 1024)); //OutputDebugStrF("Crt Size: %dk\n", (int)(memState.lTotalCount / 1024));
char* names[6] = { "_FREE_BLOCK", "_NORMAL_BLOCK", "_CRT_BLOCK", "_IGNORE_BLOCK", "_CLIENT_BLOCK", "_MAX_BLOCKS" }; char* names[6] = { "_FREE_BLOCK", "_NORMAL_BLOCK", "_CRT_BLOCK", "_IGNORE_BLOCK", "_CLIENT_BLOCK", "_MAX_BLOCKS" };
@ -546,7 +539,7 @@ void ShowMemoryUsage()
{ {
OutputDebugStrF("%s : %d %dk\n", names[i], memState.lCounts[i], memState.lSizes[i] / 1024); OutputDebugStrF("%s : %d %dk\n", names[i], memState.lCounts[i], memState.lSizes[i] / 1024);
} }
#ifdef _DEBUG #ifdef _DEBUG
// int64 totalCrtSize = 0; // int64 totalCrtSize = 0;
// int64 totalUseCrtSize = 0; // int64 totalUseCrtSize = 0;
@ -568,9 +561,9 @@ void ShowMemoryUsage()
while ((heapStatus = _heapwalk(&heapInfo)) == _HEAPOK) while ((heapStatus = _heapwalk(&heapInfo)) == _HEAPOK)
{ {
heapSize += (int64)heapInfo._size; heapSize += (int64)heapInfo._size;
} }
OutputDebugStrF("WALKED HEAP SIZE: %dk\n", heapSize / 1024); OutputDebugStrF("WALKED HEAP SIZE: %dk\n", heapSize / 1024);
//_CrtMemDumpStatistics(&memState); //_CrtMemDumpStatistics(&memState);
#endif #endif
} }
@ -591,9 +584,7 @@ BOOL WINAPI DllMain(
HANDLE hDllHandle, HANDLE hDllHandle,
DWORD dwReason, DWORD dwReason,
LPVOID lpreserved) LPVOID lpreserved)
{ {
if (dwReason == DLL_PROCESS_ATTACH) if (dwReason == DLL_PROCESS_ATTACH)
{ {
BpInit("127.0.0.1", "Beef IDE"); BpInit("127.0.0.1", "Beef IDE");
@ -638,13 +629,13 @@ namespace BeefyDbg64
static _CrtMemState gStartMemCheckpoint; static _CrtMemState gStartMemCheckpoint;
#endif #endif
BF_EXPORT void BF_CALLTYPE Debugger_Create() BF_EXPORT void BF_CALLTYPE Debugger_Create()
{ {
//TODO: Very slow, remove //TODO: Very slow, remove
//_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_CHECK_ALWAYS_DF); //_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_CHECK_ALWAYS_DF);
//_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_CHECK_EVERY_16_DF); //_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_CHECK_EVERY_16_DF);
//TODO: _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF /*| _CRTDBG_CHECK_EVERY_16_DF*/); //TODO: _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF /*| _CRTDBG_CHECK_EVERY_16_DF*/);
//_CrtSetAllocHook(BfAllocHook); //_CrtSetAllocHook(BfAllocHook);
#ifdef BF_PLATFORM_WINDOWS #ifdef BF_PLATFORM_WINDOWS
_CrtMemCheckpoint(&gStartMemCheckpoint); _CrtMemCheckpoint(&gStartMemCheckpoint);
#endif #endif
@ -661,7 +652,7 @@ BF_EXPORT void BF_CALLTYPE Debugger_Create()
gDebugManager->mDebugger64 = NULL; gDebugManager->mDebugger64 = NULL;
#else #else
gDebugManager->mDebugger64 = CreateDebugger64(gDebugManager, NULL); gDebugManager->mDebugger64 = CreateDebugger64(gDebugManager, NULL);
#endif #endif
#ifdef BF_PLATFORM_WINDOWS #ifdef BF_PLATFORM_WINDOWS
::AllowSetForegroundWindow(ASFW_ANY); ::AllowSetForegroundWindow(ASFW_ANY);
@ -672,12 +663,11 @@ BF_EXPORT void BF_CALLTYPE Debugger_Create()
BF_EXPORT void BF_CALLTYPE Debugger_SetCallbacks(void* callback) BF_EXPORT void BF_CALLTYPE Debugger_SetCallbacks(void* callback)
{ {
} }
BF_EXPORT void BF_CALLTYPE Debugger_FullReportMemory() BF_EXPORT void BF_CALLTYPE Debugger_FullReportMemory()
{ {
//WdAllocTest(); //WdAllocTest();
ShowMemoryUsage(); ShowMemoryUsage();
BfFullReportMemory(); BfFullReportMemory();
} }
@ -777,7 +767,7 @@ BF_EXPORT bool BF_CALLTYPE Debugger_OpenFile(const char* launchPath, const char*
Array<uint8> envBlock; Array<uint8> envBlock;
if (envBlockPtr != NULL) if (envBlockPtr != NULL)
{ {
if (envBlockSize != 0) if (envBlockSize != 0)
envBlock.Insert(0, (uint8*)envBlockPtr, envBlockSize); envBlock.Insert(0, (uint8*)envBlockPtr, envBlockSize);
} }
@ -787,7 +777,7 @@ BF_EXPORT bool BF_CALLTYPE Debugger_OpenFile(const char* launchPath, const char*
} }
BF_EXPORT bool BF_CALLTYPE Debugger_ComptimeAttach(void* bfCompiler) BF_EXPORT bool BF_CALLTYPE Debugger_ComptimeAttach(void* bfCompiler)
{ {
gDebugger = new CeDebugger(gDebugManager, (BfCompiler*)bfCompiler); gDebugger = new CeDebugger(gDebugManager, (BfCompiler*)bfCompiler);
return true; return true;
} }
@ -808,12 +798,12 @@ BF_EXPORT void BF_CALLTYPE Debugger_SetSymSrvOptions(const char* symCacheDir, co
if (!symStr.IsEmpty()) if (!symStr.IsEmpty())
symServers.Add(symStr); symServers.Add(symStr);
startStr = cPtr; startStr = cPtr;
} }
if (*cPtr == 0) if (*cPtr == 0)
break; break;
} }
AutoCrit autoCrit(gDebugManager->mCritSect); AutoCrit autoCrit(gDebugManager->mCritSect);
gDebugManager->mSymSrvOptions.mCacheDir = symCacheDir; gDebugManager->mSymSrvOptions.mCacheDir = symCacheDir;
@ -834,12 +824,11 @@ BF_EXPORT void BF_CALLTYPE Debugger_SetSymSrvOptions(const char* symCacheDir, co
} }
gDebugManager->SetSourceServerCacheDir(); gDebugManager->SetSourceServerCacheDir();
} }
BF_EXPORT bool BF_CALLTYPE Debugger_OpenMiniDump(const char* fileName) BF_EXPORT bool BF_CALLTYPE Debugger_OpenMiniDump(const char* fileName)
{ {
#ifdef BF_PLATFORM_WINDOWS #ifdef BF_PLATFORM_WINDOWS
DbgMiniDump* dbgMiniDump = new DbgMiniDump(); DbgMiniDump* dbgMiniDump = new DbgMiniDump();
bool result = dbgMiniDump->StartLoad(fileName); bool result = dbgMiniDump->StartLoad(fileName);
if (!result) if (!result)
@ -847,7 +836,6 @@ BF_EXPORT bool BF_CALLTYPE Debugger_OpenMiniDump(const char* fileName)
delete dbgMiniDump; delete dbgMiniDump;
return false; return false;
} }
if (dbgMiniDump->GetTargetBitCount() == 32) if (dbgMiniDump->GetTargetBitCount() == 32)
gDebugger = CreateDebugger32(gDebugManager, dbgMiniDump); gDebugger = CreateDebugger32(gDebugManager, dbgMiniDump);
@ -875,7 +863,7 @@ BF_EXPORT bool BF_CALLTYPE Debugger_Attach(int processId, BfDbgAttachFlags attac
gDebugger = gDebugManager->mDebugger32; gDebugger = gDebugManager->mDebugger32;
return true; return true;
} }
return false; return false;
} }
@ -886,7 +874,7 @@ BF_EXPORT void BF_CALLTYPE Debugger_Run()
BF_EXPORT bool BF_CALLTYPE Debugger_HotLoad(const char* fileNamesStr, int hotIdx) BF_EXPORT bool BF_CALLTYPE Debugger_HotLoad(const char* fileNamesStr, int hotIdx)
{ {
//DbgModule* dwarf = new DbgModule(gDebugger); //DbgModule* dwarf = new DbgModule(gDebugger);
//dwarf->ReadPE(fileName); //dwarf->ReadPE(fileName);
Array<String> fileNames; Array<String> fileNames;
@ -919,8 +907,8 @@ BF_EXPORT bool BF_CALLTYPE Debugger_HotLoad(const char* fileNamesStr, int hotIdx
BF_EXPORT bool BF_CALLTYPE Debugger_LoadDebugVisualizers(const char* fileName) BF_EXPORT bool BF_CALLTYPE Debugger_LoadDebugVisualizers(const char* fileName)
{ {
String fn = fileName; String fn = fileName;
bool worked = false; bool worked = false;
worked = gDebugManager->mDebugVisualizers->Load(fileName); worked = gDebugManager->mDebugVisualizers->Load(fileName);
if (!gDebugManager->mDebugVisualizers->mErrorString.empty()) if (!gDebugManager->mDebugVisualizers->mErrorString.empty())
{ {
gDebugManager->mOutMessages.push_back(StrFormat("msg ERROR: %s\n", gDebugManager->mDebugVisualizers->mErrorString.c_str())); gDebugManager->mOutMessages.push_back(StrFormat("msg ERROR: %s\n", gDebugManager->mDebugVisualizers->mErrorString.c_str()));
@ -999,7 +987,7 @@ BF_EXPORT void BF_CALLTYPE Breakpoint_HotBindBreakpoint(Breakpoint* breakpoint,
BF_EXPORT void BF_CALLTYPE Breakpoint_SetThreadId(Breakpoint* breakpoint, intptr threadId) BF_EXPORT void BF_CALLTYPE Breakpoint_SetThreadId(Breakpoint* breakpoint, intptr threadId)
{ {
BfLogDbg("Breakpoint %p set ThreadId=%d\n", breakpoint, threadId); BfLogDbg("Breakpoint %p set ThreadId=%d\n", breakpoint, threadId);
breakpoint->mThreadId = threadId; breakpoint->mThreadId = threadId;
gDebugger->CheckBreakpoint(breakpoint); gDebugger->CheckBreakpoint(breakpoint);
} }
@ -1064,19 +1052,19 @@ BF_EXPORT void BF_CALLTYPE Breakpoint_Disable(Breakpoint* wdBreakpoint)
BF_EXPORT void BF_CALLTYPE Debugger_CreateStepFilter(const char* filter, bool isGlobal, BfStepFilterKind filterKind) BF_EXPORT void BF_CALLTYPE Debugger_CreateStepFilter(const char* filter, bool isGlobal, BfStepFilterKind filterKind)
{ {
AutoCrit autoCrit(gDebugManager->mCritSect); AutoCrit autoCrit(gDebugManager->mCritSect);
StepFilter stepFilter; StepFilter stepFilter;
stepFilter.mFilterKind = filterKind; stepFilter.mFilterKind = filterKind;
gDebugManager->mStepFilters[filter] = stepFilter; gDebugManager->mStepFilters[filter] = stepFilter;
gDebugManager->mStepFilterVersion++; gDebugManager->mStepFilterVersion++;
} }
BF_EXPORT void BF_CALLTYPE StepFilter_Delete(const char* filter) BF_EXPORT void BF_CALLTYPE StepFilter_Delete(const char* filter)
{ {
AutoCrit autoCrit(gDebugManager->mCritSect); AutoCrit autoCrit(gDebugManager->mCritSect);
bool didRemove = gDebugManager->mStepFilters.Remove(filter); bool didRemove = gDebugManager->mStepFilters.Remove(filter);
BF_ASSERT(didRemove); BF_ASSERT(didRemove);
gDebugManager->mStepFilterVersion++; gDebugManager->mStepFilterVersion++;
} }
@ -1110,7 +1098,7 @@ BF_EXPORT const char* BF_CALLTYPE Debugger_PopMessage()
BF_EXPORT bool BF_CALLTYPE Debugger_HasMessages() BF_EXPORT bool BF_CALLTYPE Debugger_HasMessages()
{ {
AutoCrit autoCrit(gDebugManager->mCritSect); AutoCrit autoCrit(gDebugManager->mCritSect);
return gDebugManager->mOutMessages.size() != 0; return gDebugManager->mOutMessages.size() != 0;
} }
BF_EXPORT const char* BF_CALLTYPE Debugger_GetCurrentException() BF_EXPORT const char* BF_CALLTYPE Debugger_GetCurrentException()
@ -1177,7 +1165,7 @@ BF_EXPORT void BF_CALLTYPE Debugger_SetDisplayTypes(const char* referenceId, con
displayInfo = &gDebugManager->mDefaultDisplayInfo; displayInfo = &gDebugManager->mDefaultDisplayInfo;
else else
gDebugManager->mDisplayInfos.TryAdd(referenceId, NULL, &displayInfo); gDebugManager->mDisplayInfos.TryAdd(referenceId, NULL, &displayInfo);
if (formatStr != NULL) if (formatStr != NULL)
displayInfo->mFormatStr = formatStr; displayInfo->mFormatStr = formatStr;
displayInfo->mIntDisplayType = (DwIntDisplayType)intDisplayType; displayInfo->mIntDisplayType = (DwIntDisplayType)intDisplayType;
@ -1246,11 +1234,11 @@ BF_EXPORT const char* BF_CALLTYPE Debugger_EvaluateContinue()
BF_EXPORT void BF_CALLTYPE Debugger_EvaluateContinueKeep() BF_EXPORT void BF_CALLTYPE Debugger_EvaluateContinueKeep()
{ {
auto debugger = gDebugger; auto debugger = gDebugger;
debugger->EvaluateContinueKeep(); debugger->EvaluateContinueKeep();
} }
BF_EXPORT StringView BF_CALLTYPE Debugger_Evaluate(const char* expr, int callStackIdx, int cursorPos, int32 language, uint16 expressionFlags) BF_EXPORT StringView BF_CALLTYPE Debugger_Evaluate(const char* expr, int callStackIdx, int cursorPos, int32 language, uint16 expressionFlags)
{ {
auto debugger = gDebugger; auto debugger = gDebugger;
if (debugger == NULL) if (debugger == NULL)
@ -1291,39 +1279,37 @@ BF_EXPORT const char* BF_CALLTYPE Debugger_EvaluateAtAddress(const char* expr, i
BF_EXPORT const char* BF_CALLTYPE Debugger_GetAutoExpressions(int callStackIdx, uint64 memoryRangeStart, uint64 memoryRangeLen) BF_EXPORT const char* BF_CALLTYPE Debugger_GetAutoExpressions(int callStackIdx, uint64 memoryRangeStart, uint64 memoryRangeLen)
{ {
String& outString = *gTLStrReturn.Get(); String& outString = *gTLStrReturn.Get();
outString = gDebugger->GetAutoExpressions(callStackIdx, memoryRangeStart, memoryRangeLen); outString = gDebugger->GetAutoExpressions(callStackIdx, memoryRangeStart, memoryRangeLen);
return outString.c_str(); return outString.c_str();
} }
BF_EXPORT const char* BF_CALLTYPE Debugger_GetAutoLocals(int callStackIdx, bool showRegs) BF_EXPORT const char* BF_CALLTYPE Debugger_GetAutoLocals(int callStackIdx, bool showRegs)
{ {
String& outString = *gTLStrReturn.Get(); String& outString = *gTLStrReturn.Get();
outString = gDebugger->GetAutoLocals(callStackIdx, showRegs); outString = gDebugger->GetAutoLocals(callStackIdx, showRegs);
return outString.c_str(); return outString.c_str();
} }
BF_EXPORT const char* BF_CALLTYPE Debugger_CompactChildExpression(const char* expr, const char* parentExpr, int callStackIdx) BF_EXPORT const char* BF_CALLTYPE Debugger_CompactChildExpression(const char* expr, const char* parentExpr, int callStackIdx)
{ {
String& outString = *gTLStrReturn.Get(); String& outString = *gTLStrReturn.Get();
outString = gDebugger->CompactChildExpression(expr, parentExpr, callStackIdx); outString = gDebugger->CompactChildExpression(expr, parentExpr, callStackIdx);
return outString.c_str(); return outString.c_str();
} }
BF_EXPORT const char* BF_CALLTYPE Debugger_GetCollectionContinuation(const char* continuationData, int callStackIdx, int count) BF_EXPORT const char* BF_CALLTYPE Debugger_GetCollectionContinuation(const char* continuationData, int callStackIdx, int count)
{ {
String& outString = *gTLStrReturn.Get(); String& outString = *gTLStrReturn.Get();
outString = gDebugger->GetCollectionContinuation(continuationData, callStackIdx, count); outString = gDebugger->GetCollectionContinuation(continuationData, callStackIdx, count);
return outString.c_str(); return outString.c_str();
} }
BF_EXPORT void BF_CALLTYPE Debugger_ForegroundTarget() BF_EXPORT void BF_CALLTYPE Debugger_ForegroundTarget()
{ {
gDebugger->ForegroundTarget(); gDebugger->ForegroundTarget();
//BOOL worked = EnumThreadWindows(gDebugger->mProcessInfo.dwThreadId, WdEnumWindowsProc, 0); //BOOL worked = EnumThreadWindows(gDebugger->mProcessInfo.dwThreadId, WdEnumWindowsProc, 0);
//BF_ASSERT(worked); //BF_ASSERT(worked);
} }
@ -1394,7 +1380,7 @@ BF_EXPORT int BF_CALLTYPE CallStack_GetBreakStackFrameIdx()
BF_EXPORT const char* BF_CALLTYPE CallStack_GetStackFrameInfo(int stackFrameIdx, intptr* addr, const char** outFile, int32* outHotIdx, int32* outDefLineStart, int32* outDefLineEnd, BF_EXPORT const char* BF_CALLTYPE CallStack_GetStackFrameInfo(int stackFrameIdx, intptr* addr, const char** outFile, int32* outHotIdx, int32* outDefLineStart, int32* outDefLineEnd,
int32* outLine, int32* outColumn, int32* outLanguage, int32* outStackSize, int8* outFlags) int32* outLine, int32* outColumn, int32* outLanguage, int32* outStackSize, int8* outFlags)
{ {
String& outString = *gTLStrReturn.Get(); String& outString = *gTLStrReturn.Get();
String& outString2 = *gTLStrReturn2.Get(); String& outString2 = *gTLStrReturn2.Get();
@ -1413,7 +1399,7 @@ BF_EXPORT const char* BF_CALLTYPE CallStack_GetStackFrameId(int stackFrameIdx)
BF_EXPORT const char* BF_CALLTYPE Callstack_GetStackFrameOldFileInfo(int stackFrameIdx) BF_EXPORT const char* BF_CALLTYPE Callstack_GetStackFrameOldFileInfo(int stackFrameIdx)
{ {
String& outString = *gTLStrReturn.Get(); String& outString = *gTLStrReturn.Get();
outString = gDebugger->Callstack_GetStackFrameOldFileInfo(stackFrameIdx); outString = gDebugger->Callstack_GetStackFrameOldFileInfo(stackFrameIdx);
return outString.c_str(); return outString.c_str();
} }
@ -1531,7 +1517,7 @@ BF_EXPORT int BF_CALLTYPE Debugger_LoadDebugInfoForModuleWith(const char* module
} }
BF_EXPORT void BF_CALLTYPE Debugger_SetStepOverExternalFiles(bool stepOverExternalFiles) BF_EXPORT void BF_CALLTYPE Debugger_SetStepOverExternalFiles(bool stepOverExternalFiles)
{ {
gDebugManager->mStepOverExternalFiles = stepOverExternalFiles; gDebugManager->mStepOverExternalFiles = stepOverExternalFiles;
gDebugManager->mStepFilterVersion++; gDebugManager->mStepFilterVersion++;
} }
@ -1552,7 +1538,7 @@ BF_EXPORT Profiler* BF_CALLTYPE Debugger_StartProfiling(intptr threadId, char* d
Profiler* profiler = gDebugger->StartProfiling(); Profiler* profiler = gDebugger->StartProfiling();
profiler->mTargetThreadId = threadId; profiler->mTargetThreadId = threadId;
if (desc != NULL) if (desc != NULL)
profiler->mDescription = desc; profiler->mDescription = desc;
profiler->mSamplesPerSecond = sampleRate; profiler->mSamplesPerSecond = sampleRate;
profiler->Start(); profiler->Start();
return profiler; return profiler;
@ -1560,7 +1546,7 @@ BF_EXPORT Profiler* BF_CALLTYPE Debugger_StartProfiling(intptr threadId, char* d
BF_EXPORT Profiler* BF_CALLTYPE Debugger_PopProfiler() BF_EXPORT Profiler* BF_CALLTYPE Debugger_PopProfiler()
{ {
Profiler* profiler = gDebugger->PopProfiler(); Profiler* profiler = gDebugger->PopProfiler();
return profiler; return profiler;
} }
@ -1570,7 +1556,6 @@ BF_EXPORT void BF_CALLTYPE Debugger_InitiateHotResolve(int flags)
gDebugger->InitiateHotResolve((DbgHotResolveFlags)flags); gDebugger->InitiateHotResolve((DbgHotResolveFlags)flags);
} }
BF_EXPORT intptr BF_CALLTYPE Debugger_GetDbgAllocHeapSize() BF_EXPORT intptr BF_CALLTYPE Debugger_GetDbgAllocHeapSize()
{ {
AutoCrit autoCrit(gDebugManager->mCritSect); AutoCrit autoCrit(gDebugManager->mCritSect);
@ -1580,7 +1565,7 @@ BF_EXPORT intptr BF_CALLTYPE Debugger_GetDbgAllocHeapSize()
BF_EXPORT const char* BF_CALLTYPE Debugger_GetDbgAllocInfo() BF_EXPORT const char* BF_CALLTYPE Debugger_GetDbgAllocInfo()
{ {
AutoCrit autoCrit(gDebugManager->mCritSect); AutoCrit autoCrit(gDebugManager->mCritSect);
String& outString = *gTLStrReturn.Get(); String& outString = *gTLStrReturn.Get();
outString = gDebugger->GetDbgAllocInfo(); outString = gDebugger->GetDbgAllocInfo();
return outString.c_str(); return outString.c_str();
@ -1640,7 +1625,7 @@ BF_EXPORT NetResult* HTTP_GetFile(char* url, char* destPath)
{ {
AutoCrit autoCrit(gDebugManager->mNetManager->mThreadPool.mCritSect); AutoCrit autoCrit(gDebugManager->mNetManager->mThreadPool.mCritSect);
auto netResult = gDebugManager->mNetManager->QueueGet(url, destPath, false); auto netResult = gDebugManager->mNetManager->QueueGet(url, destPath, false);
netResult->mDoneEvent = new SyncEvent(); netResult->mDoneEvent = new SyncEvent();
return netResult; return netResult;
} }
@ -1674,7 +1659,7 @@ BF_EXPORT void HTTP_Delete(NetResult* netResult)
netResult->mCurRequest->Cancel(); netResult->mCurRequest->Cancel();
} }
netResult->mDoneEvent->WaitFor(-1); netResult->mDoneEvent->WaitFor(-1);
} }
delete netResult; delete netResult;
} }
@ -1738,12 +1723,12 @@ BF_EXPORT void BF_CALLTYPE TimeTest(uint32 startTime)
} }
BF_EXPORT void BF_CALLTYPE BFTest() BF_EXPORT void BF_CALLTYPE BFTest()
{ {
struct DeferredResolveEntry2 struct DeferredResolveEntry2
{ {
BfFieldDef* mFieldDef; BfFieldDef* mFieldDef;
int mTypeArrayIdx; int mTypeArrayIdx;
}; };
DeferredResolveEntry2 entry = { NULL, 333 }; DeferredResolveEntry2 entry = { NULL, 333 };
@ -1752,10 +1737,10 @@ BF_EXPORT void BF_CALLTYPE BFTest()
vec.push_back(DeferredResolveEntry2 { NULL, 222 } ); vec.push_back(DeferredResolveEntry2 { NULL, 222 } );
} }
/// ///
// __attribute__((weak)) // __attribute__((weak))
// Debugger* Beefy::CreateDebugger32(DebugManager* debugManager, DbgMiniDump* miniDump) // Debugger* Beefy::CreateDebugger32(DebugManager* debugManager, DbgMiniDump* miniDump)
// { // {
// return NULL; // return NULL;
// } // }

View file

@ -44,7 +44,7 @@ public:
StepFilter() StepFilter()
{ {
// Set global / local // Set global / local
mFilterKind = BfStepFilterKind_Filtered; mFilterKind = BfStepFilterKind_Filtered;
} }
bool IsFiltered(bool defaultValue) bool IsFiltered(bool defaultValue)
@ -65,11 +65,11 @@ class DebugManager
{ {
public: public:
Debugger* mDebugger32; Debugger* mDebugger32;
Debugger* mDebugger64; Debugger* mDebugger64;
CritSect mCritSect; CritSect mCritSect;
Dictionary<String, StepFilter> mStepFilters; Dictionary<String, StepFilter> mStepFilters;
int mStepFilterVersion; int mStepFilterVersion;
std::deque<String> mOutMessages; std::deque<String> mOutMessages;
DebugVisualizers* mDebugVisualizers; DebugVisualizers* mDebugVisualizers;

View file

@ -5,7 +5,7 @@ USING_NS_BF;
void DebugVisualizers::Fail(const StringImpl& error) void DebugVisualizers::Fail(const StringImpl& error)
{ {
if (mErrorString.length() != 0) if (mErrorString.length() != 0)
return; return;
mErrorString = StrFormat("Debug visualizer failure: %s in %s", error.c_str(), mCurFileName.c_str()); mErrorString = StrFormat("Debug visualizer failure: %s in %s", error.c_str(), mCurFileName.c_str());
} }
@ -125,7 +125,7 @@ bool DebugVisualizers::ReadFileTOML(const StringImpl& fileName)
else if ((name == "DisplayString") | (name == "StringView")) else if ((name == "DisplayString") | (name == "StringView"))
{ {
bool isStringView = name == "StringView"; bool isStringView = name == "StringView";
if (value.is<toml::Array>()) if (value.is<toml::Array>())
{ {
for (auto& displayValue : ExpectArray(value)) for (auto& displayValue : ExpectArray(value))
@ -143,7 +143,7 @@ bool DebugVisualizers::ReadFileTOML(const StringImpl& fileName)
else else
Fail("Unexpected entry", value); Fail("Unexpected entry", value);
} }
if (isStringView) if (isStringView)
entry->mStringViews.push_back(displayStringEntry); entry->mStringViews.push_back(displayStringEntry);
else else
@ -158,7 +158,7 @@ bool DebugVisualizers::ReadFileTOML(const StringImpl& fileName)
entry->mStringViews.push_back(displayStringEntry); entry->mStringViews.push_back(displayStringEntry);
else else
entry->mDisplayStrings.push_back(displayStringEntry); entry->mDisplayStrings.push_back(displayStringEntry);
} }
} }
else if (name == "Action") else if (name == "Action")
{ {
@ -193,7 +193,7 @@ bool DebugVisualizers::ReadFileTOML(const StringImpl& fileName)
else if (name == "Condition") else if (name == "Condition")
expandItem->mCondition = ExpectString(value); expandItem->mCondition = ExpectString(value);
else else
Fail("Unexpected entry", value); Fail("Unexpected entry", value);
} }
} }
} }
@ -234,7 +234,7 @@ bool DebugVisualizers::ReadFileTOML(const StringImpl& fileName)
else if (name == "LowerDimSizes") else if (name == "LowerDimSizes")
{ {
for (auto& dimValue : ExpectArray(value)) for (auto& dimValue : ExpectArray(value))
entry->mLowerDimSizes.push_back(ExpectString(dimValue)); entry->mLowerDimSizes.push_back(ExpectString(dimValue));
} }
else if (name == "ValueNode") else if (name == "ValueNode")
entry->mValuePointer = ExpectString(value); entry->mValuePointer = ExpectString(value);
@ -364,7 +364,7 @@ bool DebugVisualizers::Load(const StringImpl& fileNamesStr)
fileNames.Add(fileNamesStr.Substring(startIdx, crPos - startIdx)); fileNames.Add(fileNamesStr.Substring(startIdx, crPos - startIdx));
startIdx = crPos + 1; startIdx = crPos + 1;
} }
HashContext hashCtx; HashContext hashCtx;
for (auto fileName : fileNames) for (auto fileName : fileNames)
{ {
@ -376,7 +376,7 @@ bool DebugVisualizers::Load(const StringImpl& fileNamesStr)
} }
hashCtx.Mixin(lastWrite); hashCtx.Mixin(lastWrite);
} }
Val128 hash = hashCtx.Finish128(); Val128 hash = hashCtx.Finish128();
if ((hash == mHash) && (!hasError)) if ((hash == mHash) && (!hasError))
return true; return true;
@ -394,13 +394,12 @@ bool DebugVisualizers::Load(const StringImpl& fileNamesStr)
return success; return success;
} }
DebugVisualizerEntry* DebugVisualizers::FindEntryForType(const StringImpl& typeName, DbgFlavor wantFlavor, Array<String>* wildcardCaptures) DebugVisualizerEntry* DebugVisualizers::FindEntryForType(const StringImpl& typeName, DbgFlavor wantFlavor, Array<String>* wildcardCaptures)
{ {
//TODO: Do smarter name matching. Right now we just compare up to the '*' //TODO: Do smarter name matching. Right now we just compare up to the '*'
for (auto entry : mDebugVisualizers) for (auto entry : mDebugVisualizers)
{ {
if ((entry->mFlavor != DbgFlavor_Unknown) && (entry->mFlavor != wantFlavor)) if ((entry->mFlavor != DbgFlavor_Unknown) && (entry->mFlavor != wantFlavor))
continue; continue;
@ -435,7 +434,7 @@ DebugVisualizerEntry* DebugVisualizers::FindEntryForType(const StringImpl& typeN
int openDepth = 0; int openDepth = 0;
String wildcardCapture; String wildcardCapture;
while (true) while (true)
{ {
typeC = *typeCharP; typeC = *typeCharP;
bool isSep = typeC == ','; bool isSep = typeC == ',';
@ -459,7 +458,7 @@ DebugVisualizerEntry* DebugVisualizers::FindEntryForType(const StringImpl& typeN
{ {
typeCharP--; typeCharP--;
break; break;
} }
wildcardCapture += typeC; wildcardCapture += typeC;
typeCharP++; typeCharP++;
@ -476,14 +475,14 @@ DebugVisualizerEntry* DebugVisualizers::FindEntryForType(const StringImpl& typeN
} }
else if (entryC != typeC) else if (entryC != typeC)
break; break;
typeCharP++; typeCharP++;
entryCharP++; entryCharP++;
} }
if (wildcardCaptures != NULL) if (wildcardCaptures != NULL)
wildcardCaptures->Clear(); wildcardCaptures->Clear();
} }
return NULL; return NULL;
} }
@ -504,4 +503,4 @@ String DebugVisualizers::DoStringReplace(const StringImpl& origStr, const Array<
} }
} }
return newString; return newString;
} }

View file

@ -48,7 +48,7 @@ public:
OwnedVector<ExpandItem> mExpandItems; OwnedVector<ExpandItem> mExpandItems;
CollectionType mCollectionType; CollectionType mCollectionType;
String mSize; String mSize;
Array<String> mLowerDimSizes; Array<String> mLowerDimSizes;
String mNextPointer; String mNextPointer;
@ -58,11 +58,11 @@ public:
String mRightPointer; String mRightPointer;
String mValueType; String mValueType;
String mValuePointer; String mValuePointer;
String mTargetPointer; String mTargetPointer;
String mCondition; String mCondition;
String mBuckets; String mBuckets;
String mEntries; String mEntries;
String mKey; String mKey;
bool mShowedError; bool mShowedError;
bool mShowElementAddrs; bool mShowElementAddrs;
@ -76,7 +76,7 @@ public:
mCollectionType = CollectionType_None; mCollectionType = CollectionType_None;
mShowedError = false; mShowedError = false;
mShowElementAddrs = false; mShowElementAddrs = false;
} }
}; };
class DebugVisualizers class DebugVisualizers
@ -87,9 +87,9 @@ public:
String mCurFileName; String mCurFileName;
const char* mSrcStr; const char* mSrcStr;
OwnedVector<DebugVisualizerEntry> mDebugVisualizers; OwnedVector<DebugVisualizerEntry> mDebugVisualizers;
void Fail(const StringImpl& error); void Fail(const StringImpl& error);
void Fail(const StringImpl& error, const toml::Value& value); void Fail(const StringImpl& error, const toml::Value& value);
String ExpectString(const toml::Value& value); String ExpectString(const toml::Value& value);
bool ExpectBool(const toml::Value& value); bool ExpectBool(const toml::Value& value);

View file

@ -5,7 +5,7 @@
USING_NS_BF; USING_NS_BF;
DbgModuleMemoryCache::DbgModuleMemoryCache(uintptr addr, int size) DbgModuleMemoryCache::DbgModuleMemoryCache(uintptr addr, int size)
{ {
mAddr = addr; mAddr = addr;
mSize = size; mSize = size;
@ -27,7 +27,7 @@ DbgModuleMemoryCache::DbgModuleMemoryCache(uintptr addr, int size)
// mBlocks = new uint8*[1]; // mBlocks = new uint8*[1];
// mFlags = new DbgMemoryFlags[1]; // mFlags = new DbgMemoryFlags[1];
// mSize = size; // mSize = size;
// //
// if (makeCopy) // if (makeCopy)
// { // {
// uint8* dataCopy = new uint8[size]; // uint8* dataCopy = new uint8[size];
@ -40,8 +40,8 @@ DbgModuleMemoryCache::DbgModuleMemoryCache(uintptr addr, int size)
// else // else
// { // {
// mBlocks[0] = data; // mBlocks[0] = data;
// } // }
// //
// mOwns = makeCopy; // mOwns = makeCopy;
// mBlockCount = 1; // mBlockCount = 1;
// } // }
@ -75,7 +75,7 @@ DbgMemoryFlags DbgModuleMemoryCache::Read(uintptr addr, uint8* data, int size)
int relAddr = (int)(addr - mAddr); int relAddr = (int)(addr - mAddr);
int blockIdx = relAddr / mBlockSize; int blockIdx = relAddr / mBlockSize;
int curOffset = relAddr % mBlockSize; int curOffset = relAddr % mBlockSize;
while (sizeLeft > 0) while (sizeLeft > 0)
{ {
uint8* block = mBlocks[blockIdx]; uint8* block = mBlocks[blockIdx];
@ -98,7 +98,7 @@ DbgMemoryFlags DbgModuleMemoryCache::Read(uintptr addr, uint8* data, int size)
} }
sizeLeft -= readSize; sizeLeft -= readSize;
curOffset = 0; curOffset = 0;
blockIdx++; blockIdx++;
} }
return flags; return flags;
@ -114,4 +114,4 @@ void DbgModuleMemoryCache::ReportMemory(MemReporter * memReporter)
totalMemory += mBlockSize; totalMemory += mBlockSize;
} }
memReporter->Add(totalMemory); memReporter->Add(totalMemory);
} }

View file

@ -29,7 +29,7 @@ public:
int mPendingHotBindIdx; int mPendingHotBindIdx;
int mHitCount; int mHitCount;
int mTargetHitCount; int mTargetHitCount;
DbgHitCountBreakKind mHitCountBreakKind; DbgHitCountBreakKind mHitCountBreakKind;
String mLogging; String mLogging;
bool mBreakAfterLogging; bool mBreakAfterLogging;
@ -40,7 +40,7 @@ public:
Breakpoint* mLinkedSibling; // For things like templates with multiple imps on same source line Breakpoint* mLinkedSibling; // For things like templates with multiple imps on same source line
bool mIsLinkedSibling; // Not in breakpoint list bool mIsLinkedSibling; // Not in breakpoint list
public: public:
Breakpoint() Breakpoint()
{ {
mRequestedLineNum = -1; mRequestedLineNum = -1;
@ -50,11 +50,11 @@ public:
mPendingHotBindIdx = -1; mPendingHotBindIdx = -1;
mHitCount = 0; mHitCount = 0;
mTargetHitCount = 0; mTargetHitCount = 0;
mHitCountBreakKind = DbgHitCountBreakKind_None; mHitCountBreakKind = DbgHitCountBreakKind_None;
mThreadId = -1; mThreadId = -1;
mHead = NULL; mHead = NULL;
mLinkedSibling = NULL; mLinkedSibling = NULL;
mIsLinkedSibling = false; mIsLinkedSibling = false;
mBreakAfterLogging = false; mBreakAfterLogging = false;
} }
@ -62,7 +62,6 @@ public:
virtual bool IsMemoryBreakpointBound() = 0; virtual bool IsMemoryBreakpointBound() = 0;
}; };
enum DbgTypeKindFlags enum DbgTypeKindFlags
{ {
DbgTypeKindFlag_None = 0, DbgTypeKindFlag_None = 0,
@ -97,7 +96,7 @@ enum DwFloatDisplayType : int8
{ {
DwFloatDisplayType_Default, DwFloatDisplayType_Default,
DwFloatDisplayType_Minimal, DwFloatDisplayType_Minimal,
DwFloatDisplayType_Full, DwFloatDisplayType_Full,
DwFloatDisplayType_HexUpper, DwFloatDisplayType_HexUpper,
DwFloatDisplayType_HexLower, DwFloatDisplayType_HexLower,
@ -126,7 +125,7 @@ enum DwEvalExpressionFlags : int16
DwEvalExpressionFlag_MemoryAddress = 0x40, DwEvalExpressionFlag_MemoryAddress = 0x40,
DwEvalExpressionFlag_MemoryWatch = 0x80, DwEvalExpressionFlag_MemoryWatch = 0x80,
DwEvalExpressionFlag_Symbol = 0x100, DwEvalExpressionFlag_Symbol = 0x100,
DwEvalExpressionFlag_StepIntoCalls = 0x200, DwEvalExpressionFlag_StepIntoCalls = 0x200,
DwEvalExpressionFlag_RawStr = 0x400, DwEvalExpressionFlag_RawStr = 0x400,
DwEvalExpressionFlag_AllowStringView = 0x800 DwEvalExpressionFlag_AllowStringView = 0x800
}; };
@ -148,7 +147,7 @@ struct DwDisplayInfo
enum RunState enum RunState
{ {
RunState_NotStarted, RunState_NotStarted,
RunState_Running, RunState_Running,
RunState_Running_ToTempBreakpoint, RunState_Running_ToTempBreakpoint,
RunState_Paused, RunState_Paused,
@ -158,7 +157,7 @@ enum RunState
RunState_HotStep, RunState_HotStep,
RunState_Exception, RunState_Exception,
RunState_Terminating, RunState_Terminating,
RunState_Terminated, RunState_Terminated,
RunState_SearchingSymSrv, RunState_SearchingSymSrv,
RunState_HotResolve RunState_HotResolve
}; };
@ -203,16 +202,15 @@ enum DbgMemoryFlags : uint8
class DbgModuleMemoryCache class DbgModuleMemoryCache
{ {
public: public:
public: public:
uintptr mAddr; uintptr mAddr;
int mSize; int mSize;
int mBlockSize; int mBlockSize;
uint8** mBlocks; uint8** mBlocks;
DbgMemoryFlags* mFlags; DbgMemoryFlags* mFlags;
int mBlockCount; int mBlockCount;
bool mOwns; bool mOwns;
public: public:
DbgModuleMemoryCache(uintptr addr, int size); DbgModuleMemoryCache(uintptr addr, int size);
@ -229,7 +227,7 @@ public:
struct TypeData struct TypeData
{ {
intptr mCount; intptr mCount;
intptr mSize; intptr mSize;
TypeData() TypeData()
{ {
@ -249,7 +247,7 @@ class Debugger
{ {
public: public:
DebugManager* mDebugManager; DebugManager* mDebugManager;
RunState mRunState; RunState mRunState;
DbgHotResolveData* mHotResolveData; DbgHotResolveData* mHotResolveData;
bool mHadImageFindError; bool mHadImageFindError;
@ -257,7 +255,7 @@ public:
Debugger() Debugger()
{ {
mDebugManager = NULL; mDebugManager = NULL;
mRunState = RunState_NotStarted; mRunState = RunState_NotStarted;
mHotResolveData = NULL; mHotResolveData = NULL;
mHadImageFindError = false; mHadImageFindError = false;
} }
@ -283,7 +281,7 @@ public:
virtual Breakpoint* CreateAddressBreakpoint(intptr address) = 0; virtual Breakpoint* CreateAddressBreakpoint(intptr address) = 0;
virtual void CheckBreakpoint(Breakpoint* breakpoint) = 0; virtual void CheckBreakpoint(Breakpoint* breakpoint) = 0;
virtual void HotBindBreakpoint(Breakpoint* wdBreakpoint, int lineNum, int hotIdx) = 0; virtual void HotBindBreakpoint(Breakpoint* wdBreakpoint, int lineNum, int hotIdx) = 0;
virtual void DeleteBreakpoint(Breakpoint* wdBreakpoint) = 0; virtual void DeleteBreakpoint(Breakpoint* wdBreakpoint) = 0;
virtual void DetachBreakpoint(Breakpoint* wdBreakpoint) = 0; virtual void DetachBreakpoint(Breakpoint* wdBreakpoint) = 0;
virtual void MoveBreakpoint(Breakpoint* wdBreakpoint, int lineNum, int wantColumn, bool rebindNow) = 0; virtual void MoveBreakpoint(Breakpoint* wdBreakpoint, int lineNum, int wantColumn, bool rebindNow) = 0;
virtual void MoveMemoryBreakpoint(Breakpoint* wdBreakpoint, intptr addr, int byteCount) = 0; virtual void MoveMemoryBreakpoint(Breakpoint* wdBreakpoint, intptr addr, int byteCount) = 0;
@ -306,13 +304,13 @@ public:
virtual void EvaluateContinueKeep() = 0; virtual void EvaluateContinueKeep() = 0;
virtual String EvaluateToAddress(const StringImpl& expr, int callStackIdx, int cursorPos) = 0; virtual String EvaluateToAddress(const StringImpl& expr, int callStackIdx, int cursorPos) = 0;
virtual String EvaluateAtAddress(const StringImpl& expr, intptr atAddr, int cursorPos) = 0; virtual String EvaluateAtAddress(const StringImpl& expr, intptr atAddr, int cursorPos) = 0;
virtual String GetCollectionContinuation(const StringImpl& continuationData, int callStackIdx, int count) = 0; virtual String GetCollectionContinuation(const StringImpl& continuationData, int callStackIdx, int count) = 0;
virtual String GetAutoExpressions(int callStackIdx, uint64 memoryRangeStart, uint64 memoryRangeLen) = 0; virtual String GetAutoExpressions(int callStackIdx, uint64 memoryRangeStart, uint64 memoryRangeLen) = 0;
virtual String GetAutoLocals(int callStackIdx, bool showRegs) = 0; virtual String GetAutoLocals(int callStackIdx, bool showRegs) = 0;
virtual String CompactChildExpression(const StringImpl& expr, const StringImpl& parentExpr, int callStackIdx) = 0; virtual String CompactChildExpression(const StringImpl& expr, const StringImpl& parentExpr, int callStackIdx) = 0;
virtual String GetProcessInfo() = 0; virtual String GetProcessInfo() = 0;
virtual String GetThreadInfo() = 0; virtual String GetThreadInfo() = 0;
virtual void SetActiveThread(int threadId) = 0; virtual void SetActiveThread(int threadId) = 0;
virtual int GetActiveThread() = 0; virtual int GetActiveThread() = 0;
virtual void FreezeThread(int threadId) = 0; virtual void FreezeThread(int threadId) = 0;
virtual void ThawThread(int threadId) = 0; virtual void ThawThread(int threadId) = 0;
@ -321,12 +319,12 @@ public:
virtual void UpdateCallStack(bool slowEarlyOut = true) = 0; virtual void UpdateCallStack(bool slowEarlyOut = true) = 0;
virtual int GetCallStackCount() = 0; virtual int GetCallStackCount() = 0;
virtual int GetRequestedStackFrameIdx() = 0; virtual int GetRequestedStackFrameIdx() = 0;
virtual int GetBreakStackFrameIdx() = 0; virtual int GetBreakStackFrameIdx() = 0;
virtual bool ReadMemory(intptr address, uint64 length, void* dest, bool local = false) = 0; virtual bool ReadMemory(intptr address, uint64 length, void* dest, bool local = false) = 0;
virtual bool WriteMemory(intptr address, void* src, uint64 length) = 0; virtual bool WriteMemory(intptr address, void* src, uint64 length) = 0;
virtual DbgMemoryFlags GetMemoryFlags(intptr address) = 0; virtual DbgMemoryFlags GetMemoryFlags(intptr address) = 0;
virtual void UpdateRegisterUsage(int stackFrameIdx) = 0; virtual void UpdateRegisterUsage(int stackFrameIdx) = 0;
virtual void UpdateCallStackMethod(int stackFrameIdx) = 0; virtual void UpdateCallStackMethod(int stackFrameIdx) = 0;
virtual void GetCodeAddrInfo(intptr addr, intptr inlineCallAddr, String* outFile, int* outHotIdx, int* outDefLineStart, int* outDefLineEnd, int* outLine, int* outColumn) = 0; virtual void GetCodeAddrInfo(intptr addr, intptr inlineCallAddr, String* outFile, int* outHotIdx, int* outDefLineStart, int* outDefLineEnd, int* outLine, int* outColumn) = 0;
virtual void GetStackAllocInfo(intptr addr, int* outThreadId, int* outStackIdx) = 0; virtual void GetStackAllocInfo(intptr addr, int* outThreadId, int* outStackIdx) = 0;
virtual String GetStackFrameInfo(int stackFrameIdx, intptr* addr, String* outFile, int32* outHotIdx, int32* outDefLineStart, int32* outDefLineEnd, int32* outLine, int32* outColumn, int32* outLanguage, int32* outStackSize, int8* outFlags) = 0; virtual String GetStackFrameInfo(int stackFrameIdx, intptr* addr, String* outFile, int32* outHotIdx, int32* outDefLineStart, int32* outDefLineEnd, int32* outLine, int32* outColumn, int32* outLanguage, int32* outStackSize, int8* outFlags) = 0;
@ -340,8 +338,8 @@ public:
virtual String GetAddressSymbolName(intptr address, bool demangle) = 0; virtual String GetAddressSymbolName(intptr address, bool demangle) = 0;
virtual String DisassembleAtRaw(intptr address) = 0; virtual String DisassembleAtRaw(intptr address) = 0;
virtual String DisassembleAt(intptr address) = 0; virtual String DisassembleAt(intptr address) = 0;
virtual String FindLineCallAddresses(intptr address) = 0; virtual String FindLineCallAddresses(intptr address) = 0;
virtual String GetCurrentException() = 0; virtual String GetCurrentException() = 0;
virtual String GetModulesInfo() = 0; virtual String GetModulesInfo() = 0;
virtual void SetAliasPath(const StringImpl& origPath, const StringImpl& localPath) = 0; virtual void SetAliasPath(const StringImpl& origPath, const StringImpl& localPath) = 0;
virtual void CancelSymSrv() = 0; virtual void CancelSymSrv() = 0;
@ -351,7 +349,7 @@ public:
virtual int LoadDebugInfoForModule(const StringImpl& moduleName, const StringImpl& debugFileName) = 0; virtual int LoadDebugInfoForModule(const StringImpl& moduleName, const StringImpl& debugFileName) = 0;
virtual void StopDebugging() = 0; virtual void StopDebugging() = 0;
virtual void Terminate() = 0; virtual void Terminate() = 0;
virtual void Detach() = 0; virtual void Detach() = 0;
virtual Profiler* StartProfiling() = 0; virtual Profiler* StartProfiling() = 0;
virtual Profiler* PopProfiler() = 0; // Profiler requested by target program virtual Profiler* PopProfiler() = 0; // Profiler requested by target program
virtual void ReportMemory(MemReporter* memReporter) = 0; virtual void ReportMemory(MemReporter* memReporter) = 0;
@ -380,7 +378,7 @@ public:
virtual bool IsSampling() = 0; virtual bool IsSampling() = 0;
virtual String GetOverview() = 0; virtual String GetOverview() = 0;
virtual String GetThreadList() = 0; virtual String GetThreadList() = 0;
virtual String GetCallTree(int threadId, bool reverse) = 0; virtual String GetCallTree(int threadId, bool reverse) = 0;
}; };
NS_BF_END NS_BF_END

View file

@ -18,13 +18,13 @@
NS_BF_BEGIN NS_BF_BEGIN
/// raw_null_ostream - A raw_ostream that discards all output. /// raw_null_ostream - A raw_ostream that discards all output.
class debug_ostream : public llvm::raw_ostream class debug_ostream : public llvm::raw_ostream
{ {
/// write_impl - See raw_ostream::write_impl. /// write_impl - See raw_ostream::write_impl.
void write_impl(const char *Ptr, size_t size) override void write_impl(const char *Ptr, size_t size) override
{ {
StringT<1024> str; StringT<1024> str;
str.Append(Ptr, size); str.Append(Ptr, size);
OutputDebugStr(str); OutputDebugStr(str);
} }
@ -33,7 +33,7 @@ class debug_ostream : public llvm::raw_ostream
uint64_t current_pos() const override uint64_t current_pos() const override
{ {
return 0; return 0;
} }
}; };
NS_BF_END NS_BF_END

View file

@ -83,10 +83,10 @@ void NetRequest::Cleanup()
{ {
if (mCURLMulti != NULL) if (mCURLMulti != NULL)
curl_multi_remove_handle(mCURLMulti, mCURL); curl_multi_remove_handle(mCURLMulti, mCURL);
if (mCURL != NULL) if (mCURL != NULL)
curl_easy_cleanup(mCURL); curl_easy_cleanup(mCURL);
if (mCURLMulti != NULL) if (mCURLMulti != NULL)
curl_multi_cleanup(mCURLMulti); curl_multi_cleanup(mCURLMulti);
mCURL = NULL; mCURL = NULL;
mCURLMulti = NULL; mCURLMulti = NULL;
@ -160,7 +160,7 @@ void NetRequest::DoTransfer()
// mFailed = true; // mFailed = true;
// return; // return;
// } // }
response_code = 0; response_code = 0;
curl_easy_getinfo(mCURL, CURLINFO_RESPONSE_CODE, &response_code); curl_easy_getinfo(mCURL, CURLINFO_RESPONSE_CODE, &response_code);
mNetManager->mDebugManager->OutputRawMessage(StrFormat("msgLo Result for '%s': %d\n", mURL.c_str(), response_code)); mNetManager->mDebugManager->OutputRawMessage(StrFormat("msgLo Result for '%s': %d\n", mURL.c_str(), response_code));
@ -199,20 +199,20 @@ void NetRequest::DoTransfer()
} }
if (response_code != 200) if (response_code != 200)
{ {
mOutFile.Close(); mOutFile.Close();
// Bad result // Bad result
mFailed = true; mFailed = true;
return; return;
} }
BfLogDbg("NetManager successfully completed %s\n", mURL.c_str()); BfLogDbg("NetManager successfully completed %s\n", mURL.c_str());
if (mCancelOnSuccess != NULL) if (mCancelOnSuccess != NULL)
mNetManager->Cancel(mCancelOnSuccess); mNetManager->Cancel(mCancelOnSuccess);
if (!mOutFile.IsOpen()) if (!mOutFile.IsOpen())
{ {
mFailed = true; mFailed = true;
return; // No data return; // No data
} }
@ -223,14 +223,14 @@ void NetRequest::DoTransfer()
BfpFile_Rename(mOutTempPath.c_str(), mOutPath.c_str(), &renameResult); BfpFile_Rename(mOutTempPath.c_str(), mOutPath.c_str(), &renameResult);
if (renameResult != BfpFileResult_Ok) if (renameResult != BfpFileResult_Ok)
{ {
mFailed = true; mFailed = true;
} }
} }
void NetRequest::Perform() void NetRequest::Perform()
{ {
DoTransfer(); DoTransfer();
} }
#elif defined BF_PLATFORM_WINDOWS #elif defined BF_PLATFORM_WINDOWS
@ -263,16 +263,16 @@ void NetRequest::Perform()
Fail("Invalid URL"); Fail("Invalid URL");
return; return;
} }
protoName = mURL.Substring(0, colonPos); protoName = mURL.Substring(0, colonPos);
serverName = mURL.Substring(colonPos + 3); serverName = mURL.Substring(colonPos + 3);
int slashPos = (int)serverName.IndexOf('/'); int slashPos = (int)serverName.IndexOf('/');
if (slashPos != -1) if (slashPos != -1)
{ {
objectName = serverName.Substring(slashPos); objectName = serverName.Substring(slashPos);
serverName.RemoveToEnd(slashPos); serverName.RemoveToEnd(slashPos);
} }
mOutTempPath = mOutPath + "__partial"; mOutTempPath = mOutPath + "__partial";
@ -291,8 +291,8 @@ void NetRequest::Perform()
if (mOutFile.IsOpen()) if (mOutFile.IsOpen())
mOutFile.Close(); mOutFile.Close();
}; };
bool isHttp = protoName.Equals("http", StringImpl::CompareKind_OrdinalIgnoreCase); bool isHttp = protoName.Equals("http", StringImpl::CompareKind_OrdinalIgnoreCase);
bool isHttps = protoName.Equals("https", StringImpl::CompareKind_OrdinalIgnoreCase); bool isHttps = protoName.Equals("https", StringImpl::CompareKind_OrdinalIgnoreCase);
if ((!isHttp) && (!isHttps)) if ((!isHttp) && (!isHttps))
@ -350,23 +350,23 @@ void NetRequest::Perform()
} }
if (mShowTracking) if (mShowTracking)
{ {
mNetManager->mDebugManager->OutputRawMessage(StrFormat("symsrv Getting '%s'", mURL.c_str())); mNetManager->mDebugManager->OutputRawMessage(StrFormat("symsrv Getting '%s'", mURL.c_str()));
} }
uint8 buffer[4096]; uint8 buffer[4096];
while (true) while (true)
{ {
DWORD dwBytesRead = 0; DWORD dwBytesRead = 0;
BOOL bRead = InternetReadFile(hHttpFile, buffer, 4096, &dwBytesRead); BOOL bRead = InternetReadFile(hHttpFile, buffer, 4096, &dwBytesRead);
if (dwBytesRead == 0) if (dwBytesRead == 0)
break; break;
if (!bRead) if (!bRead)
{ {
//printf("InternetReadFile error : <%lu>\n", GetLastError()); //printf("InternetReadFile error : <%lu>\n", GetLastError());
Fail("Failed to receive"); Fail("Failed to receive");
return; return;
} }
if (!mOutFile.IsOpen()) if (!mOutFile.IsOpen())
{ {
@ -378,7 +378,7 @@ void NetRequest::Perform()
} }
} }
mOutFile.Write(buffer, (int)dwBytesRead); mOutFile.Write(buffer, (int)dwBytesRead);
} }
BfLogDbg("NetManager successfully completed %s\n", mURL.c_str()); BfLogDbg("NetManager successfully completed %s\n", mURL.c_str());
@ -402,7 +402,6 @@ void NetRequest::Perform()
void NetRequest::Cleanup() void NetRequest::Cleanup()
{ {
} }
#else #else
@ -414,7 +413,6 @@ void NetRequest::Perform()
void NetRequest::Cleanup() void NetRequest::Cleanup()
{ {
} }
#endif #endif
@ -437,7 +435,7 @@ NetRequest::~NetRequest()
delete mResult; delete mResult;
} }
mNetManager->mRequestDoneEvent.Set(); mNetManager->mRequestDoneEvent.Set();
} }
void NetRequest::Fail(const StringImpl& error) void NetRequest::Fail(const StringImpl& error)
@ -456,7 +454,7 @@ bool NetRequest::Cancel()
} }
void NetRequest::ShowTracking() void NetRequest::ShowTracking()
{ {
//mNetManager->mDebugManager->OutputMessage(StrFormat("Getting '%s'\n", mURL.c_str())); //mNetManager->mDebugManager->OutputMessage(StrFormat("Getting '%s'\n", mURL.c_str()));
mNetManager->mDebugManager->OutputRawMessage(StrFormat("symsrv Getting '%s'", mURL.c_str())); mNetManager->mDebugManager->OutputRawMessage(StrFormat("symsrv Getting '%s'", mURL.c_str()));
mShowTracking = true; mShowTracking = true;
@ -464,7 +462,6 @@ void NetRequest::ShowTracking()
void NetManagerThread() void NetManagerThread()
{ {
} }
NetManager::NetManager() : mThreadPool(8, 1*1024*1024) NetManager::NetManager() : mThreadPool(8, 1*1024*1024)
@ -480,13 +477,13 @@ NetManager::~NetManager()
for (auto kv : mCachedResults) for (auto kv : mCachedResults)
{ {
delete kv.mValue; delete kv.mValue;
} }
} }
NetRequest* NetManager::CreateGetRequest(const StringImpl& url, const StringImpl& destPath, bool useCache) NetRequest* NetManager::CreateGetRequest(const StringImpl& url, const StringImpl& destPath, bool useCache)
{ {
AutoCrit autoCrit(mThreadPool.mCritSect); AutoCrit autoCrit(mThreadPool.mCritSect);
NetRequest* netRequest = new NetRequest(); NetRequest* netRequest = new NetRequest();
netRequest->mNetManager = this; netRequest->mNetManager = this;
netRequest->mURL = url; netRequest->mURL = url;
@ -520,7 +517,7 @@ NetRequest* NetManager::CreateGetRequest(const StringImpl& url, const StringImpl
NetResult* NetManager::QueueGet(const StringImpl& url, const StringImpl& destPath, bool useCache) NetResult* NetManager::QueueGet(const StringImpl& url, const StringImpl& destPath, bool useCache)
{ {
BfLogDbg("NetManager queueing %s %d\n", url.c_str(), useCache); BfLogDbg("NetManager queueing %s %d\n", url.c_str(), useCache);
auto netRequest = CreateGetRequest(url, destPath, useCache); auto netRequest = CreateGetRequest(url, destPath, useCache);
auto netResult = netRequest->mResult; auto netResult = netRequest->mResult;
mThreadPool.AddJob(netRequest); mThreadPool.AddJob(netRequest);
@ -528,7 +525,7 @@ NetResult* NetManager::QueueGet(const StringImpl& url, const StringImpl& destPat
} }
bool NetManager::Get(const StringImpl& url, const StringImpl& destPath) bool NetManager::Get(const StringImpl& url, const StringImpl& destPath)
{ {
NetRequest* netRequest = NULL; NetRequest* netRequest = NULL;
int waitCount = 0; int waitCount = 0;
while (true) while (true)
@ -539,7 +536,7 @@ bool NetManager::Get(const StringImpl& url, const StringImpl& destPath)
mWaitingResult = NULL; mWaitingResult = NULL;
NetResult* netResult; NetResult* netResult;
if (mCachedResults.TryGetValue(url, &netResult)) if (mCachedResults.TryGetValue(url, &netResult))
{ {
if (netResult->mCurRequest == NULL) if (netResult->mCurRequest == NULL)
{ {
@ -547,7 +544,7 @@ bool NetManager::Get(const StringImpl& url, const StringImpl& destPath)
return (!netResult->mFailed) && (FileExists(netResult->mOutPath)); return (!netResult->mFailed) && (FileExists(netResult->mOutPath));
} }
else if (!netResult->mCurRequest->mShowTracking) // Is done? else if (!netResult->mCurRequest->mShowTracking) // Is done?
{ {
if (!netResult->mCurRequest->mProcessing) if (!netResult->mCurRequest->mProcessing)
{ {
BfLogDbg("NetManager::Get pulling queued request into current thread %s\n", url.c_str()); BfLogDbg("NetManager::Get pulling queued request into current thread %s\n", url.c_str());
@ -557,9 +554,9 @@ bool NetManager::Get(const StringImpl& url, const StringImpl& destPath)
break; break;
} }
mWaitingResult = netResult; mWaitingResult = netResult;
netResult->mCurRequest->ShowTracking(); netResult->mCurRequest->ShowTracking();
} }
} }
else else
{ {
@ -597,12 +594,12 @@ void NetManager::CancelAll()
AutoCrit autoCrit(mThreadPool.mCritSect); AutoCrit autoCrit(mThreadPool.mCritSect);
if (mWaitingRequest != NULL) if (mWaitingRequest != NULL)
mWaitingRequest->Cancel(); mWaitingRequest->Cancel();
mThreadPool.CancelAll(); mThreadPool.CancelAll();
} }
void NetManager::Clear() void NetManager::Clear()
{ {
AutoCrit autoCrit(mThreadPool.mCritSect); AutoCrit autoCrit(mThreadPool.mCritSect);
BF_ASSERT(mWaitingResult == NULL); // The debugger thread shouldn't be waiting on anything, it should be detached at this point BF_ASSERT(mWaitingResult == NULL); // The debugger thread shouldn't be waiting on anything, it should be detached at this point
for (auto job : mThreadPool.mJobs) for (auto job : mThreadPool.mJobs)
@ -649,7 +646,7 @@ void NetManager::SetCancelOnSuccess(NetResult* dependentResult, NetResult* cance
{ {
AutoCrit autoCrit(mThreadPool.mCritSect); AutoCrit autoCrit(mThreadPool.mCritSect);
if (dependentResult->mCurRequest != NULL) if (dependentResult->mCurRequest != NULL)
{ {
dependentResult->mCurRequest->mCancelOnSuccess = cancelOnSucess; dependentResult->mCurRequest->mCancelOnSuccess = cancelOnSucess;
} }
} }

View file

@ -52,10 +52,10 @@ public:
#else #else
#endif #endif
mCancelling = false; mCancelling = false;
mFailed = false; mFailed = false;
mShowTracking = false; mShowTracking = false;
mResult = NULL; mResult = NULL;
mCancelOnSuccess = NULL; mCancelOnSuccess = NULL;
} }
~NetRequest(); ~NetRequest();
@ -63,7 +63,7 @@ public:
void Cleanup(); void Cleanup();
void Fail(const StringImpl& error); void Fail(const StringImpl& error);
bool Cancel() override; bool Cancel() override;
void Perform() override; void Perform() override;
void ShowTracking(); void ShowTracking();
}; };
@ -113,7 +113,7 @@ public:
NetRequest* CreateGetRequest(const StringImpl& url, const StringImpl& destPath, bool useCache); NetRequest* CreateGetRequest(const StringImpl& url, const StringImpl& destPath, bool useCache);
NetResult* QueueGet(const StringImpl& url, const StringImpl& destPath, bool useCache); NetResult* QueueGet(const StringImpl& url, const StringImpl& destPath, bool useCache);
bool Get(const StringImpl& url, const StringImpl& destPath); bool Get(const StringImpl& url, const StringImpl& destPath);
void CancelAll(); void CancelAll();
void Clear(); void Clear();
void CancelCurrent(); void CancelCurrent();

View file

@ -26,9 +26,9 @@ BF_EXPORT SpellChecker* BF_CALLTYPE SpellChecker_Create(const char* langPath)
return NULL; return NULL;
} }
SpellChecker* spellChecker = new SpellChecker(); SpellChecker* spellChecker = new SpellChecker();
spellChecker->mHunHandle = hunHandle; spellChecker->mHunHandle = hunHandle;
return spellChecker; return spellChecker;
} }

View file

@ -13,7 +13,7 @@ public:
Beefy::BumpAllocator mAlloc; Beefy::BumpAllocator mAlloc;
struct Entry struct Entry
{ {
T mValue; T mValue;
Entry* mNext; Entry* mNext;
}; };
@ -30,7 +30,7 @@ public:
{ {
mMap = map; mMap = map;
mCurBucket = 0; mCurBucket = 0;
mCurEntry = NULL; mCurEntry = NULL;
} }
Iterator& operator++() Iterator& operator++()
@ -67,7 +67,7 @@ public:
public: public:
int GetHash(const char* str, const char* strEnd) int GetHash(const char* str, const char* strEnd)
{ {
if (str == NULL) if (str == NULL)
return 0; return 0;
@ -83,20 +83,20 @@ public:
return curHash & 0x7FFFFFFF; return curHash & 0x7FFFFFFF;
} }
public: public:
Entry** mHashHeads; Entry** mHashHeads;
public: public:
StrBloomMap() StrBloomMap()
{ {
mHashHeads = NULL; mHashHeads = NULL;
} }
void InsertUnique(int hash, T value) void InsertUnique(int hash, T value)
{ {
if (mHashHeads == NULL) if (mHashHeads == NULL)
mHashHeads = (Entry**)mAlloc.AllocBytes(sizeof(Entry*) * HashSize, alignof(Entry*)); mHashHeads = (Entry**)mAlloc.AllocBytes(sizeof(Entry*) * HashSize, alignof(Entry*));
int hashIdx = hash % HashSize; int hashIdx = hash % HashSize;
Entry* headEntry = mHashHeads[hashIdx]; Entry* headEntry = mHashHeads[hashIdx];
@ -116,12 +116,12 @@ public:
} }
Entry* FindFirst(const char* name) Entry* FindFirst(const char* name)
{ {
if (mHashHeads == NULL) if (mHashHeads == NULL)
return NULL; return NULL;
int hash = GetHash(name, NULL) % HashSize; int hash = GetHash(name, NULL) % HashSize;
return mHashHeads[hash]; return mHashHeads[hash];
} }
Iterator begin() Iterator begin()
@ -138,4 +138,3 @@ public:
}; };
NS_BF_DBG_END NS_BF_DBG_END

View file

@ -8,10 +8,10 @@ NS_BF_DBG_BEGIN
template <typename T> template <typename T>
class StrHashMap class StrHashMap
{ {
public: public:
struct Entry struct Entry
{ {
T mValue; T mValue;
Entry* mNext; Entry* mNext;
int mHash; int mHash;
}; };
@ -102,7 +102,7 @@ public:
public: public:
Beefy::BumpAllocator mAlloc; Beefy::BumpAllocator mAlloc;
Entry** mHashHeads; Entry** mHashHeads;
int mHashSize; int mHashSize;
int mCount; int mCount;
public: public:
@ -140,7 +140,7 @@ public:
Entry* checkEntry = mHashHeads[hashIdx]; Entry* checkEntry = mHashHeads[hashIdx];
while (checkEntry != NULL) while (checkEntry != NULL)
{ {
auto nextEntry = checkEntry->mNext; auto nextEntry = checkEntry->mNext;
int newHashIdx = checkEntry->mHash % newHashSize; int newHashIdx = checkEntry->mHash % newHashSize;
checkEntry->mNext = newHashHeads[newHashIdx]; checkEntry->mNext = newHashHeads[newHashIdx];
newHashHeads[newHashIdx] = checkEntry; newHashHeads[newHashIdx] = checkEntry;
@ -197,5 +197,4 @@ public:
} }
}; };
NS_BF_DBG_END NS_BF_DBG_END

View file

@ -56,7 +56,7 @@
struct Find_Result { struct Find_Result {
int windows_sdk_version = 0; // Zero if no Windows SDK found. int windows_sdk_version = 0; // Zero if no Windows SDK found.
wchar_t *windows_sdk_root = NULL; wchar_t *windows_sdk_root = NULL;
wchar_t* vs_version = NULL; wchar_t* vs_version = NULL;
wchar_t *vs_exe32_path = NULL; wchar_t *vs_exe32_path = NULL;
@ -68,7 +68,7 @@ struct Find_Result {
Find_Result find_visual_studio_and_windows_sdk(); Find_Result find_visual_studio_and_windows_sdk();
void free_resources(Find_Result *result) { void free_resources(Find_Result *result) {
free(result->windows_sdk_root); free(result->windows_sdk_root);
free(result->vs_version); free(result->vs_version);
free(result->vs_exe32_path); free(result->vs_exe32_path);
free(result->vs_exe64_path); free(result->vs_exe64_path);
@ -95,10 +95,10 @@ void free_resources(Find_Result *result) {
// I am not making this up: https://github.com/Microsoft/vswhere // I am not making this up: https://github.com/Microsoft/vswhere
// //
// Several people have therefore found the need to solve this problem // Several people have therefore found the need to solve this problem
// themselves. We referred to some of these other solutions when // themselves. We referred to some of these other solutions when
// figuring out what to do, most prominently ziglang's version, // figuring out what to do, most prominently ziglang's version,
// by Ryan Saunderson. // by Ryan Saunderson.
// //
// I hate this kind of code. The fact that we have to do this at all // I hate this kind of code. The fact that we have to do this at all
// is stupid, and the actual maneuvers we need to go through // is stupid, and the actual maneuvers we need to go through
// are just painful. If programming were like this all the time, // are just painful. If programming were like this all the time,
@ -148,7 +148,6 @@ public:
#define defer const auto& CONCAT(defer__, __LINE__) = ExitScopeHelp() + [&]() #define defer const auto& CONCAT(defer__, __LINE__) = ExitScopeHelp() + [&]()
// COM objects for the ridiculous Microsoft craziness. // COM objects for the ridiculous Microsoft craziness.
struct DECLSPEC_UUID("B41463C3-8866-43B5-BC33-2B0676F7F42E") DECLSPEC_NOVTABLE ISetupInstance : public IUnknown struct DECLSPEC_UUID("B41463C3-8866-43B5-BC33-2B0676F7F42E") DECLSPEC_NOVTABLE ISetupInstance : public IUnknown
@ -178,7 +177,6 @@ struct DECLSPEC_UUID("42843719-DB4C-46C2-8E7C-64F1816EFD5B") DECLSPEC_NOVTABLE I
STDMETHOD(GetInstanceForPath)(_In_z_ LPCWSTR wzPath, _Out_ ISetupInstance** ppInstance) = 0; STDMETHOD(GetInstanceForPath)(_In_z_ LPCWSTR wzPath, _Out_ ISetupInstance** ppInstance) = 0;
}; };
// The beginning of the actual code that does things. // The beginning of the actual code that does things.
struct Version_Data { struct Version_Data {
@ -224,7 +222,6 @@ wchar_t *concat(wchar_t *a, wchar_t *b, wchar_t *c = nullptr, wchar_t *d = nullp
typedef void(*Visit_Proc_W)(wchar_t *short_name, wchar_t *full_name, Version_Data *data); typedef void(*Visit_Proc_W)(wchar_t *short_name, wchar_t *full_name, Version_Data *data);
bool visit_files_w(wchar_t *dir_name, Version_Data *data, Visit_Proc_W proc) { bool visit_files_w(wchar_t *dir_name, Version_Data *data, Visit_Proc_W proc) {
// Visit everything in one folder (non-recursively). If it's a directory // Visit everything in one folder (non-recursively). If it's a directory
// that doesn't start with ".", call the visit proc on it. The visit proc // that doesn't start with ".", call the visit proc on it. The visit proc
// will see if the filename conforms to the expected versioning pattern. // will see if the filename conforms to the expected versioning pattern.
@ -253,7 +250,6 @@ bool visit_files_w(wchar_t *dir_name, Version_Data *data, Visit_Proc_W proc) {
return true; return true;
} }
wchar_t *find_windows_kit_root(HKEY key, wchar_t *version) { wchar_t *find_windows_kit_root(HKEY key, wchar_t *version) {
// Given a key to an already opened registry entry, // Given a key to an already opened registry entry,
// get the value stored under the 'version' subkey. // get the value stored under the 'version' subkey.
@ -340,7 +336,7 @@ void find_windows_kit_root(Find_Result *result) {
// is stored in the same place in the registry. We open a key // is stored in the same place in the registry. We open a key
// to that place, first checking preferentially for a Windows 10 kit, // to that place, first checking preferentially for a Windows 10 kit,
// then, if that's not found, a Windows 8 kit. // then, if that's not found, a Windows 8 kit.
HKEY main_key; HKEY main_key;
auto rc = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows Kits\\Installed Roots", auto rc = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows Kits\\Installed Roots",
@ -386,7 +382,6 @@ void find_windows_kit_root(Find_Result *result) {
// If we get here, we failed to find anything. // If we get here, we failed to find anything.
} }
void find_visual_studio_by_fighting_through_microsoft_craziness(Find_Result *result) { void find_visual_studio_by_fighting_through_microsoft_craziness(Find_Result *result) {
// The name of this procedure is kind of cryptic. Its purpose is // The name of this procedure is kind of cryptic. Its purpose is
// to fight through Microsoft craziness. The things that the fine // to fight through Microsoft craziness. The things that the fine
@ -449,7 +444,7 @@ void find_visual_studio_by_fighting_through_microsoft_craziness(Find_Result *res
if (!success) continue; if (!success) continue;
auto version_bytes = (tools_file_size.QuadPart + 1) * 2; // Warning: This multiplication by 2 presumes there is no variable-length encoding in the wchars (wacky characters in the file could betray this expectation). auto version_bytes = (tools_file_size.QuadPart + 1) * 2; // Warning: This multiplication by 2 presumes there is no variable-length encoding in the wchars (wacky characters in the file could betray this expectation).
wchar_t *version = (wchar_t *)malloc(version_bytes); wchar_t *version = (wchar_t *)malloc(version_bytes);
auto read_result = fgetws(version, (int)version_bytes, f); auto read_result = fgetws(version, (int)version_bytes, f);
if (!read_result) continue; if (!read_result) continue;
@ -465,15 +460,15 @@ void find_visual_studio_by_fighting_through_microsoft_craziness(Find_Result *res
bool use = false; bool use = false;
if ((os_file_exists(library_file)) && (os_file_exists(vs_exe64_link_path))) if ((os_file_exists(library_file)) && (os_file_exists(vs_exe64_link_path)))
{ {
if (result->vs_version == NULL) if (result->vs_version == NULL)
{ {
use = true; use = true;
} }
else if (wcscmp(version, result->vs_version) > 0) else if (wcscmp(version, result->vs_version) > 0)
{ {
use = true; use = true;
} }
} }
if (use) if (use)
@ -492,7 +487,7 @@ void find_visual_studio_by_fighting_through_microsoft_craziness(Find_Result *res
free(library32_path); free(library32_path);
free(library64_path); free(library64_path);
} }
free(library_file); free(library_file);
free(vs_exe64_link_path); free(vs_exe64_link_path);
@ -562,7 +557,6 @@ void find_visual_studio_by_fighting_through_microsoft_craziness(Find_Result *res
// If we get here, we failed to find anything. // If we get here, we failed to find anything.
} }
Find_Result find_visual_studio_and_windows_sdk() { Find_Result find_visual_studio_and_windows_sdk() {
Find_Result result; Find_Result result;
@ -582,7 +576,7 @@ BF_EXPORT const char* BF_CALLTYPE VSSupport_Find()
{ {
Beefy::String& outString = *Beefy::gTLStrReturn.Get(); Beefy::String& outString = *Beefy::gTLStrReturn.Get();
outString.clear(); outString.clear();
Find_Result findResult = find_visual_studio_and_windows_sdk(); Find_Result findResult = find_visual_studio_and_windows_sdk();
auto _AddPath = [&](wchar_t* str) auto _AddPath = [&](wchar_t* str)
@ -593,11 +587,11 @@ BF_EXPORT const char* BF_CALLTYPE VSSupport_Find()
outString += Beefy::UTF8Encode(str); outString += Beefy::UTF8Encode(str);
} }
}; };
if (findResult.vs_exe32_path != NULL) if (findResult.vs_exe32_path != NULL)
outString += "TOOL32\t" + Beefy::UTF8Encode(findResult.vs_exe32_path) + "\n"; outString += "TOOL32\t" + Beefy::UTF8Encode(findResult.vs_exe32_path) + "\n";
if (findResult.vs_exe64_path != NULL) if (findResult.vs_exe64_path != NULL)
outString += "TOOL64\t" + Beefy::UTF8Encode(findResult.vs_exe64_path) + "\n"; outString += "TOOL64\t" + Beefy::UTF8Encode(findResult.vs_exe64_path) + "\n";
if (findResult.windows_sdk_root != NULL) if (findResult.windows_sdk_root != NULL)
{ {
@ -630,7 +624,7 @@ BF_EXPORT const char* BF_CALLTYPE VSSupport_Find()
outString += Beefy::UTF8Encode(findResult.vs_library64_path); outString += Beefy::UTF8Encode(findResult.vs_library64_path);
outString += "\n"; outString += "\n";
} }
free_resources(&findResult); free_resources(&findResult);
return outString.c_str(); return outString.c_str();

View file

@ -54,7 +54,7 @@ const char* X64CPURegisters::sCPURegisterNames[] =
"NONE", "NONE",
// integer general registers (DO NOT REORDER THESE; must exactly match DbgModule x86 register mappings) // integer general registers (DO NOT REORDER THESE; must exactly match DbgModule x86 register mappings)
"RAX", "RAX",
"RDX", "RDX",
"RCX", "RCX",
"RBX", "RBX",
@ -69,7 +69,7 @@ const char* X64CPURegisters::sCPURegisterNames[] =
"R12", "R12",
"R13", "R13",
"R14", "R14",
"R15", "R15",
"RIP", "RIP",
"EFL", "EFL",
"GS", "GS",
@ -88,7 +88,7 @@ const char* X64CPURegisters::sCPURegisterNames[] =
"R13D", "R13D",
"R14D", "R14D",
"R15D", "R15D",
"AX", "AX",
"DX", "DX",
"CX", "CX",
@ -141,7 +141,7 @@ const char* X64CPURegisters::sCPURegisterNames[] =
"MM4", "MM4",
"MM5", "MM5",
"MM6", "MM6",
"MM7", "MM7",
"XMM0_f64", "XMM0_f64",
"XMM1_f64", "XMM1_f64",
@ -354,7 +354,7 @@ bool X64Instr::IsRep(bool& isPrefixOnly)
bool X64Instr::IsReturn() bool X64Instr::IsReturn()
{ {
const MCInstrDesc &instDesc = mX64->mInstrInfo->get(mMCInst.getOpcode()); const MCInstrDesc &instDesc = mX64->mInstrInfo->get(mMCInst.getOpcode());
return (instDesc.getFlags() & (1 << MCID::Return)) != 0; return (instDesc.getFlags() & (1 << MCID::Return)) != 0;
} }
@ -402,7 +402,7 @@ static int ConvertRegNum(const MCOperand& operand)
return X64Reg_RBP; return X64Reg_RBP;
case llvm::X86::RSP: case llvm::X86::RSP:
return X64Reg_RSP; return X64Reg_RSP;
case llvm::X86::R8: case llvm::X86::R8:
case llvm::X86::R8D: case llvm::X86::R8D:
case llvm::X86::R8W: case llvm::X86::R8W:
@ -507,7 +507,7 @@ static int ConvertRegNum(const MCOperand& operand)
case llvm::X86::XMM14: case llvm::X86::XMM14:
return X64Reg_M128_XMM14; return X64Reg_M128_XMM14;
case llvm::X86::XMM15: case llvm::X86::XMM15:
return X64Reg_M128_XMM15; return X64Reg_M128_XMM15;
} }
return -1; return -1;
@ -573,13 +573,13 @@ bool X64Instr::GetImmediate(uint64* outImm)
int X64Instr::GetJmpState(int flags) int X64Instr::GetJmpState(int flags)
{ {
const MCInstrDesc &instDesc = mX64->mInstrInfo->get(mMCInst.getOpcode()); const MCInstrDesc &instDesc = mX64->mInstrInfo->get(mMCInst.getOpcode());
if ((instDesc.getFlags() & (1 << MCID::Branch)) == 0) if ((instDesc.getFlags() & (1 << MCID::Branch)) == 0)
return -1; return -1;
if (mMCInst.getNumOperands() < 1) if (mMCInst.getNumOperands() < 1)
return 0; return 0;
#define FLAGVAR(abbr, name) int flag##abbr = ((flags & ((uint64)1 << X64CPURegisters::GetFlagBitForRegister(X64Reg_FLAG_##abbr##_##name))) != 0) ? 1 : 0 #define FLAGVAR(abbr, name) int flag##abbr = ((flags & ((uint64)1 << X64CPURegisters::GetFlagBitForRegister(X64Reg_FLAG_##abbr##_##name))) != 0) ? 1 : 0
FLAGVAR(CF, CARRY); FLAGVAR(CF, CARRY);
FLAGVAR(PF, PARITY); FLAGVAR(PF, PARITY);
@ -641,10 +641,10 @@ void X64Instr::MarkRegsUsed(Array<RegForm>& regsUsed, bool overrideForm)
int opCode = instDesc.getOpcode(); int opCode = instDesc.getOpcode();
auto form = (instDesc.TSFlags & llvm::X86II::FormMask); auto form = (instDesc.TSFlags & llvm::X86II::FormMask);
/*if (opCode == 1724) /*if (opCode == 1724)
{ {
// MOVAPSrr is emitted for all moves between XMM registers, regardless of // MOVAPSrr is emitted for all moves between XMM registers, regardless of
// their actual format, so we just copy the actual RegForm form here // their actual format, so we just copy the actual RegForm form here
if (instDesc.getNumOperands() != 2) if (instDesc.getNumOperands() != 2)
return; return;
@ -655,7 +655,7 @@ void X64Instr::MarkRegsUsed(Array<RegForm>& regsUsed, bool overrideForm)
int regNumFrom = ConvertRegNum(operand); int regNumFrom = ConvertRegNum(operand);
if (regNumFrom == -1) // ?? if (regNumFrom == -1) // ??
return; return;
while (std::max(regNumFrom, regNumTo) >= (int)regsUsed.size()) while (std::max(regNumFrom, regNumTo) >= (int)regsUsed.size())
regsUsed.push_back(RegForm_Invalid); regsUsed.push_back(RegForm_Invalid);
@ -680,7 +680,7 @@ void X64Instr::MarkRegsUsed(Array<RegForm>& regsUsed, bool overrideForm)
int checkIdx = opCode * 3; int checkIdx = opCode * 3;
//const MCInstrDesc &instDesc = mX64->mInstrInfo->get(mMCInst.getOpcode()); //const MCInstrDesc &instDesc = mX64->mInstrInfo->get(mMCInst.getOpcode());
//auto form = (instDesc.TSFlags & llvm::X86II::FormMask); //auto form = (instDesc.TSFlags & llvm::X86II::FormMask);
for (int opIdx = 0; opIdx < std::min((int)instDesc.getNumOperands(), 3); opIdx++) for (int opIdx = 0; opIdx < std::min((int)instDesc.getNumOperands(), 3); opIdx++)
{ {
@ -696,7 +696,7 @@ void X64Instr::MarkRegsUsed(Array<RegForm>& regsUsed, bool overrideForm)
regsUsed[regNum] = regForm; regsUsed[regNum] = regForm;
checkIdx++; checkIdx++;
} }
} }
} }
@ -733,7 +733,7 @@ uint64 X64Instr::GetTarget(Debugger* debugger, X64CPURegisters* registers)
if (operand.isImm()) if (operand.isImm())
{ {
auto targetAddr = (uint64)operand.getImm(); auto targetAddr = (uint64)operand.getImm();
if (instDesc.OpInfo[opIdx].OperandType == MCOI::OPERAND_PCREL) if (instDesc.OpInfo[opIdx].OperandType == MCOI::OPERAND_PCREL)
targetAddr += mAddress + mSize; targetAddr += mAddress + mSize;
return targetAddr; return targetAddr;
@ -756,10 +756,10 @@ bool X64Instr::PartialSimulate(Debugger* debugger, X64CPURegisters* registers)
// auto form = (instDesc.TSFlags & llvm::X86II::FormMask); // auto form = (instDesc.TSFlags & llvm::X86II::FormMask);
// //
// if ((form == llvm::X86II::MRMSrcMem) && (instDesc.NumOperands == 6)) // if ((form == llvm::X86II::MRMSrcMem) && (instDesc.NumOperands == 6))
// { // {
// auto destReg = mMCInst.getOperand(llvm::X86::AddrBaseReg); // auto destReg = mMCInst.getOperand(llvm::X86::AddrBaseReg);
// if (destReg.isReg()) // if (destReg.isReg())
// { // {
// int regNum = 0; // int regNum = 0;
// int offset = 0; // int offset = 0;
// if (GetIndexRegisterAndOffset(&regNum, &offset)) // if (GetIndexRegisterAndOffset(&regNum, &offset))
@ -767,7 +767,7 @@ bool X64Instr::PartialSimulate(Debugger* debugger, X64CPURegisters* registers)
// uint64 addr = registers->mIntRegsArray[regNum] + offset; // uint64 addr = registers->mIntRegsArray[regNum] + offset;
// uint64 val = 0; // uint64 val = 0;
// debugger->ReadMemory(addr, 8, &val); // debugger->ReadMemory(addr, 8, &val);
// //
// switch (destReg.getReg()) // switch (destReg.getReg())
// { // {
// //
@ -779,7 +779,7 @@ bool X64Instr::PartialSimulate(Debugger* debugger, X64CPURegisters* registers)
//// if ((form == llvm::X86II::MRMDestMem) || (form == llvm::X86II::MRMSrcMem) || //// if ((form == llvm::X86II::MRMDestMem) || (form == llvm::X86II::MRMSrcMem) ||
//// ((form >= llvm::X86II::MRM0m) && (form <= llvm::X86II::MRM7m))) //// ((form >= llvm::X86II::MRM0m) && (form <= llvm::X86II::MRM7m)))
//// { //// {
//// } //// }
// } // }
// //
// if (instDesc.getOpcode() == X86::XOR8rr) // if (instDesc.getOpcode() == X86::XOR8rr)
@ -792,7 +792,7 @@ bool X64Instr::PartialSimulate(Debugger* debugger, X64CPURegisters* registers)
// if ((destReg.isReg()) && (srcReg.isReg())) // if ((destReg.isReg()) && (srcReg.isReg()))
// { // {
// if (destReg.getReg() == srcReg.getReg()) // if (destReg.getReg() == srcReg.getReg())
// { // {
// switch (destReg.getReg()) // switch (destReg.getReg())
// { // {
// case X86::AL: // case X86::AL:
@ -817,8 +817,8 @@ X64CPU::X64CPU() :
mInstrInfo = NULL; mInstrInfo = NULL;
mInstPrinter = NULL; mInstPrinter = NULL;
//InitializeAllTargets(); //InitializeAllTargets();
auto& TheX86_64Target = llvm::getTheX86_64Target(); auto& TheX86_64Target = llvm::getTheX86_64Target();
const char* triple = "x86_64-pc-mingw32"; const char* triple = "x86_64-pc-mingw32";
@ -835,7 +835,7 @@ X64CPU::X64CPU() :
return; return;
mInstrInfo = TheX86_64Target.createMCInstrInfo(); mInstrInfo = TheX86_64Target.createMCInstrInfo();
mMCContext = new MCContext(Triple(triple), mAsmInfo, mRegisterInfo, mSubtargetInfo); mMCContext = new MCContext(Triple(triple), mAsmInfo, mRegisterInfo, mSubtargetInfo);
mMCObjectFileInfo = TheX86_64Target.createMCObjectFileInfo(*mMCContext, false); mMCObjectFileInfo = TheX86_64Target.createMCObjectFileInfo(*mMCContext, false);
@ -875,11 +875,11 @@ X64CPU::~X64CPU()
} }
bool X64CPU::Decode(uint64 address, DbgModuleMemoryCache* memoryCache, X64Instr* inst) bool X64CPU::Decode(uint64 address, DbgModuleMemoryCache* memoryCache, X64Instr* inst)
{ {
inst->mAddress = address; inst->mAddress = address;
inst->mX64 = this; inst->mX64 = this;
uint64 size = 0; uint64 size = 0;
uint8 data[15]; uint8 data[15];
memoryCache->Read(address, data, 15); memoryCache->Read(address, data, 15);
@ -939,7 +939,6 @@ void X64CPU::GetNextPC(uint64 baseAddress, const uint8* dataBase, int dataLength
mDisAsm->CommentStream = &nulls(); mDisAsm->CommentStream = &nulls();
ArrayRef<uint8_t> dataArrayRef(dataPtr, dataLength - (dataPtr - dataBase)); ArrayRef<uint8_t> dataArrayRef(dataPtr, dataLength - (dataPtr - dataBase));
MCDisassembler::DecodeStatus S = mDisAsm->getInstruction(mcInst, size, dataArrayRef, address, nulls()); MCDisassembler::DecodeStatus S = mDisAsm->getInstruction(mcInst, size, dataArrayRef, address, nulls());
} }
bool X64CPU::IsReturnInstruction(X64Instr* inst) bool X64CPU::IsReturnInstruction(X64Instr* inst)
@ -957,7 +956,7 @@ String X64CPU::InstructionToString(X64Instr* inst, uint64 addr)
//mInstPrinter->CurPCRelImmOffset = addr + inst->GetLength(); //mInstPrinter->CurPCRelImmOffset = addr + inst->GetLength();
mInstPrinter->printInst(&inst->mMCInst, addr, annotationsStr, *mSubtargetInfo, OS); mInstPrinter->printInst(&inst->mMCInst, addr, annotationsStr, *mSubtargetInfo, OS);
//OS.flush(); //OS.flush();
//llvm::StringRef str = OS.str(); //llvm::StringRef str = OS.str();
String result; String result;
for (int idx = 0; idx < (int)insnStr.size(); idx++) for (int idx = 0; idx < (int)insnStr.size(); idx++)
@ -991,21 +990,21 @@ String X64CPU::InstructionToString(X64Instr* inst, uint64 addr)
} }
DbgBreakKind X64CPU::GetDbgBreakKind(uint64 address, DbgModuleMemoryCache* memoryCache, int64* regs, int64* outObjectPtr) DbgBreakKind X64CPU::GetDbgBreakKind(uint64 address, DbgModuleMemoryCache* memoryCache, int64* regs, int64* outObjectPtr)
{ {
// We've looking for a CMP BYTE PTR [<reg>], -0x80 // We've looking for a CMP BYTE PTR [<reg>], -0x80
// if <reg> is R12 then encoding takes an extra 2 bytes // if <reg> is R12 then encoding takes an extra 2 bytes
X64Instr inst; X64Instr inst;
for (int checkLen = 5; checkLen >= 3; checkLen--) for (int checkLen = 5; checkLen >= 3; checkLen--)
{ {
int offset = -3 - checkLen; int offset = -3 - checkLen;
if (!Decode(address + offset, memoryCache, &inst)) if (!Decode(address + offset, memoryCache, &inst))
continue; continue;
if (inst.GetLength() != checkLen) if (inst.GetLength() != checkLen)
continue; continue;
const MCInstrDesc &instDesc = mInstrInfo->get(inst.mMCInst.getOpcode()); const MCInstrDesc &instDesc = mInstrInfo->get(inst.mMCInst.getOpcode());
if (!instDesc.isCompare()) if (!instDesc.isCompare())
continue; continue;
@ -1052,18 +1051,18 @@ DbgBreakKind X64CPU::GetDbgBreakKind(uint64 address, DbgModuleMemoryCache* memor
for (int offset = 3; offset <= 3; offset++) for (int offset = 3; offset <= 3; offset++)
{ {
if (!Decode(address - offset, memoryCache, &inst)) if (!Decode(address - offset, memoryCache, &inst))
continue; continue;
if (inst.GetLength() != 2) if (inst.GetLength() != 2)
continue; continue;
const MCInstrDesc &instDesc = mInstrInfo->get(inst.mMCInst.getOpcode()); const MCInstrDesc &instDesc = mInstrInfo->get(inst.mMCInst.getOpcode());
if (!instDesc.isBranch()) if (!instDesc.isBranch())
continue; continue;
auto immediateType = (instDesc.TSFlags & llvm::X86II::ImmMask); auto immediateType = (instDesc.TSFlags & llvm::X86II::ImmMask);
if ((immediateType == llvm::X86II::Imm8PCRel) && (inst.mMCInst.getNumOperands() == 2)) if ((immediateType == llvm::X86II::Imm8PCRel) && (inst.mMCInst.getNumOperands() == 2))
{ {
auto immOp = inst.mMCInst.getOperand(1); auto immOp = inst.mMCInst.getOperand(1);
if (!immOp.isImm()) if (!immOp.isImm())
continue; continue;
@ -1181,4 +1180,4 @@ bool X64CPU::ParseInlineAsmInstructionLLVM(const StringImpl&asmInst, String& out
//outError = StrFormat("%s: \"%s\"", diagMessage.c_str(), diagLineContents.c_str()); //outError = StrFormat("%s: \"%s\"", diagMessage.c_str(), diagLineContents.c_str());
return result; return result;
} }

View file

@ -36,7 +36,7 @@ enum X64CPURegister
X64Reg_None = -1, X64Reg_None = -1,
// integer general registers (DO NOT REORDER THESE; must exactly match DbgModule X64 register mappings) // integer general registers (DO NOT REORDER THESE; must exactly match DbgModule X64 register mappings)
X64Reg_RAX = 0, X64Reg_RAX = 0,
X64Reg_RDX, X64Reg_RDX,
X64Reg_RCX, X64Reg_RCX,
X64Reg_RBX, X64Reg_RBX,
@ -51,7 +51,7 @@ enum X64CPURegister
X64Reg_R12, X64Reg_R12,
X64Reg_R13, X64Reg_R13,
X64Reg_R14, X64Reg_R14,
X64Reg_R15, X64Reg_R15,
X64Reg_RIP, X64Reg_RIP,
X64Reg_EFL, X64Reg_EFL,
X64Reg_GS, X64Reg_GS,
@ -74,7 +74,7 @@ enum X64CPURegister
X64Reg_AX, X64Reg_AX,
X64Reg_DX, X64Reg_DX,
X64Reg_CX, X64Reg_CX,
X64Reg_BX, X64Reg_BX,
X64Reg_SI, X64Reg_SI,
X64Reg_DI, X64Reg_DI,
X64Reg_R8W, X64Reg_R8W,
@ -93,7 +93,7 @@ enum X64CPURegister
X64Reg_AH, X64Reg_AH,
X64Reg_DH, X64Reg_DH,
X64Reg_CH, X64Reg_CH,
X64Reg_BH, X64Reg_BH,
X64Reg_SIL, X64Reg_SIL,
X64Reg_DIL, X64Reg_DIL,
X64Reg_R8B, X64Reg_R8B,
@ -159,7 +159,7 @@ enum X64CPURegister
X64Reg_XMM12_f32, X64Reg_XMM12_f32,
X64Reg_XMM13_f32, X64Reg_XMM13_f32,
X64Reg_XMM14_f32, X64Reg_XMM14_f32,
X64Reg_XMM15_f32, X64Reg_XMM15_f32,
// xmm registers // xmm registers
X64Reg_XMM00, X64Reg_XMM00,
@ -298,14 +298,14 @@ public:
struct IntRegs struct IntRegs
{ {
int64 rax; int64 rax;
int64 rdx; int64 rdx;
int64 rcx; int64 rcx;
int64 rbx; int64 rbx;
int64 rsi; int64 rsi;
int64 rdi; int64 rdi;
uint64 rbp; uint64 rbp;
uint64 rsp; uint64 rsp;
int64 r8; int64 r8;
int64 r9; int64 r9;
int64 r10; int64 r10;
@ -395,7 +395,7 @@ public:
X64Reg_RSP, X64Reg_RSP,
X64Reg_RBP, X64Reg_RBP,
X64Reg_RSI, X64Reg_RSI,
X64Reg_RDI, X64Reg_RDI,
X64Reg_R8, X64Reg_R8,
X64Reg_R9, X64Reg_R9,
X64Reg_R10, X64Reg_R10,
@ -466,7 +466,7 @@ public:
bool IsCall(); bool IsCall();
bool IsRep(bool& isPrefixOnly); bool IsRep(bool& isPrefixOnly);
bool IsReturn(); bool IsReturn();
bool IsLoadAddress(); bool IsLoadAddress();
bool GetIndexRegisterAndOffset(int* outRegister, int* outOffset); // IE: [ebp + 0x4] bool GetIndexRegisterAndOffset(int* outRegister, int* outOffset); // IE: [ebp + 0x4]
bool GetImmediate(uint64* outImm); bool GetImmediate(uint64* outImm);
int GetJmpState(int flags); int GetJmpState(int flags);
@ -476,7 +476,6 @@ public:
bool PartialSimulate(Debugger* debugger, X64CPURegisters* registers); bool PartialSimulate(Debugger* debugger, X64CPURegisters* registers);
}; };
class X64CPU class X64CPU
{ {
public: public:

View file

@ -159,10 +159,10 @@ bool X86Instr::StackAdjust(uint32& adjust)
if (mMCInst.getOpcode() != X86::SUB32ri8) if (mMCInst.getOpcode() != X86::SUB32ri8)
return true; return true;
auto operand0 = mMCInst.getOperand(0); auto operand0 = mMCInst.getOperand(0);
if (operand0.getReg() != llvm::X86::ESP) if (operand0.getReg() != llvm::X86::ESP)
return true; return true;
auto operand2 = mMCInst.getOperand(2); auto operand2 = mMCInst.getOperand(2);
if (!operand2.isImm()) if (!operand2.isImm())
return false; return false;
@ -191,7 +191,7 @@ bool X86Instr::IsReturn()
} }
bool X86Instr::IsRep(bool& isPrefixOnly) bool X86Instr::IsRep(bool& isPrefixOnly)
{ {
auto instFlags = mMCInst.getFlags(); auto instFlags = mMCInst.getFlags();
if ((instFlags & (X86::IP_HAS_REPEAT_NE | X86::IP_HAS_REPEAT)) != 0) if ((instFlags & (X86::IP_HAS_REPEAT_NE | X86::IP_HAS_REPEAT)) != 0)
{ {
@ -208,7 +208,7 @@ bool X86Instr::IsRep(bool& isPrefixOnly)
} }
bool X86Instr::IsLoadAddress() bool X86Instr::IsLoadAddress()
{ {
const MCInstrDesc &instDesc = mX86->mInstrInfo->get(mMCInst.getOpcode()); const MCInstrDesc &instDesc = mX86->mInstrInfo->get(mMCInst.getOpcode());
if (instDesc.NumOperands >= 6) if (instDesc.NumOperands >= 6)
{ {
@ -234,25 +234,25 @@ static int ConvertRegNum(const MCOperand& operand)
case llvm::X86::CL: case llvm::X86::CL:
case llvm::X86::CH: case llvm::X86::CH:
case llvm::X86::ECX: case llvm::X86::ECX:
return X86Reg_ECX; return X86Reg_ECX;
case llvm::X86::DL: case llvm::X86::DL:
case llvm::X86::DH: case llvm::X86::DH:
case llvm::X86::EDX: case llvm::X86::EDX:
return X86Reg_EDX; return X86Reg_EDX;
case llvm::X86::BL: case llvm::X86::BL:
case llvm::X86::BH: case llvm::X86::BH:
case llvm::X86::EBX: case llvm::X86::EBX:
return X86Reg_EBX; return X86Reg_EBX;
case llvm::X86::ESP: case llvm::X86::ESP:
return X86Reg_ESP; return X86Reg_ESP;
case llvm::X86::EBP: case llvm::X86::EBP:
return X86Reg_EBP; return X86Reg_EBP;
case llvm::X86::ESI: case llvm::X86::ESI:
return X86Reg_ESI; return X86Reg_ESI;
case llvm::X86::EDI: case llvm::X86::EDI:
return X86Reg_EDI; return X86Reg_EDI;
case llvm::X86::EIP: case llvm::X86::EIP:
return X86Reg_EIP; return X86Reg_EIP;
case llvm::X86::EFLAGS: case llvm::X86::EFLAGS:
return X86Reg_EFL; return X86Reg_EFL;
@ -272,7 +272,7 @@ static int ConvertRegNum(const MCOperand& operand)
return X86Reg_FPST6; return X86Reg_FPST6;
case llvm::X86::ST7: case llvm::X86::ST7:
return X86Reg_FPST7; return X86Reg_FPST7;
case llvm::X86::XMM0: case llvm::X86::XMM0:
return X86Reg_M128_XMM0; return X86Reg_M128_XMM0;
case llvm::X86::XMM1: case llvm::X86::XMM1:
@ -299,9 +299,9 @@ bool X86Instr::GetIndexRegisterAndOffset(int* outRegister, int* outOffset)
const MCInstrDesc &instDesc = mX86->mInstrInfo->get(mMCInst.getOpcode()); const MCInstrDesc &instDesc = mX86->mInstrInfo->get(mMCInst.getOpcode());
auto form = (instDesc.TSFlags & llvm::X86II::FormMask); auto form = (instDesc.TSFlags & llvm::X86II::FormMask);
if ((form == llvm::X86II::MRMDestMem) || (form == llvm::X86II::MRMSrcMem) || if ((form == llvm::X86II::MRMDestMem) || (form == llvm::X86II::MRMSrcMem) ||
((form >= llvm::X86II::MRM0m) && (form <= llvm::X86II::MRM7m))) ((form >= llvm::X86II::MRM0m) && (form <= llvm::X86II::MRM7m)))
{ {
auto baseReg = mMCInst.getOperand(llvm::X86::AddrBaseReg); auto baseReg = mMCInst.getOperand(llvm::X86::AddrBaseReg);
auto scaleAmt = mMCInst.getOperand(llvm::X86::AddrScaleAmt); auto scaleAmt = mMCInst.getOperand(llvm::X86::AddrScaleAmt);
auto indexReg = mMCInst.getOperand(llvm::X86::AddrIndexReg); auto indexReg = mMCInst.getOperand(llvm::X86::AddrIndexReg);
@ -320,12 +320,12 @@ bool X86Instr::GetIndexRegisterAndOffset(int* outRegister, int* outOffset)
if ((baseReg.isReg()) && if ((baseReg.isReg()) &&
(scaleAmt.isImm()) && (scaleAmt.getImm() == 1) && (scaleAmt.isImm()) && (scaleAmt.getImm() == 1) &&
(indexReg.isReg()) && (indexReg.getReg() == llvm::X86::NoRegister) && (indexReg.isReg()) && (indexReg.getReg() == llvm::X86::NoRegister) &&
(addrDisp.isImm())) (addrDisp.isImm()))
{ {
int regNum = ConvertRegNum(baseReg); int regNum = ConvertRegNum(baseReg);
if (regNum == -1) if (regNum == -1)
return false; return false;
*outRegister = regNum; *outRegister = regNum;
*outOffset = (int)addrDisp.getImm(); *outOffset = (int)addrDisp.getImm();
return true; return true;
} }
@ -336,11 +336,11 @@ bool X86Instr::GetIndexRegisterAndOffset(int* outRegister, int* outOffset)
bool X86Instr::GetImmediate(uint32* outImm) bool X86Instr::GetImmediate(uint32* outImm)
{ {
const MCInstrDesc &instDesc = mX86->mInstrInfo->get(mMCInst.getOpcode()); const MCInstrDesc &instDesc = mX86->mInstrInfo->get(mMCInst.getOpcode());
auto immediateType = (instDesc.TSFlags & llvm::X86II::ImmMask); auto immediateType = (instDesc.TSFlags & llvm::X86II::ImmMask);
if ((immediateType == 0) && (mMCInst.getNumOperands() < 6)) if ((immediateType == 0) && (mMCInst.getNumOperands() < 6))
return false; return false;
auto immOp = mMCInst.getOperand(5); auto immOp = mMCInst.getOperand(5);
if (!immOp.isImm()) if (!immOp.isImm())
return false; return false;
@ -376,9 +376,9 @@ void X86Instr::MarkRegsUsed(Array<RegForm>& regsUsed, bool overrideForm)
} }
uint32 X86Instr::GetTarget(Debugger* debugger, X86CPURegisters* registers) uint32 X86Instr::GetTarget(Debugger* debugger, X86CPURegisters* registers)
{ {
const MCInstrDesc &instDesc = mX86->mInstrInfo->get(mMCInst.getOpcode()); const MCInstrDesc &instDesc = mX86->mInstrInfo->get(mMCInst.getOpcode());
if (mMCInst.getNumOperands() < 1) if (mMCInst.getNumOperands() < 1)
return 0; return 0;
@ -389,7 +389,7 @@ uint32 X86Instr::GetTarget(Debugger* debugger, X86CPURegisters* registers)
opIdx = 4; opIdx = 4;
operand = mMCInst.getOperand(opIdx); operand = mMCInst.getOperand(opIdx);
} }
if (operand.isImm()) if (operand.isImm())
{ {
auto targetAddr = (uint32)operand.getImm(); auto targetAddr = (uint32)operand.getImm();
@ -418,7 +418,7 @@ X86CPU::X86CPU() :
mInstrInfo = NULL; mInstrInfo = NULL;
mInstPrinter = NULL; mInstPrinter = NULL;
//InitializeAllTargets(); //InitializeAllTargets();
auto& TheX86_32Target = getTheX86_32Target(); auto& TheX86_32Target = getTheX86_32Target();
@ -438,7 +438,7 @@ X86CPU::X86CPU() :
//TargetOptions targetOptions; //TargetOptions targetOptions;
//TargetMachine* targetMachine = TheX86_32Target.createTargetMachine(triple, "x86", "", targetOptions); //TargetMachine* targetMachine = TheX86_32Target.createTargetMachine(triple, "x86", "", targetOptions);
//const MCInstrInfo* MII = targetMachine->getSubtargetImpl()->getInstrInfo(); //const MCInstrInfo* MII = targetMachine->getSubtargetImpl()->getInstrInfo();
//STI->getIntr //STI->getIntr
mInstrInfo = TheX86_32Target.createMCInstrInfo(); mInstrInfo = TheX86_32Target.createMCInstrInfo();
@ -452,11 +452,11 @@ X86CPU::X86CPU() :
mMCContext->setObjectFileInfo(mMCObjectFileInfo); mMCContext->setObjectFileInfo(mMCObjectFileInfo);
MCDisassembler *disAsm = TheX86_32Target.createMCDisassembler(*mSubtargetInfo, *mMCContext); MCDisassembler *disAsm = TheX86_32Target.createMCDisassembler(*mSubtargetInfo, *mMCContext);
mDisAsm = disAsm; mDisAsm = disAsm;
//TODO: LLVM3.8 - changed params //TODO: LLVM3.8 - changed params
/*mInstPrinter = TheX86_32Target.createMCInstPrinter(1, *mAsmInfo, /*mInstPrinter = TheX86_32Target.createMCInstPrinter(1, *mAsmInfo,
*mInstrInfo, *mRegisterInfo, *mSubtargetInfo);*/ *mInstrInfo, *mRegisterInfo, *mSubtargetInfo);*/
mInstPrinter = TheX86_32Target.createMCInstPrinter(Triple(triple), 1, *mAsmInfo, mInstPrinter = TheX86_32Target.createMCInstPrinter(Triple(triple), 1, *mAsmInfo,
*mInstrInfo, *mRegisterInfo); *mInstrInfo, *mRegisterInfo);
@ -471,7 +471,7 @@ X86CPU::X86CPU() :
extern "C" void LLVMShutdown(); extern "C" void LLVMShutdown();
X86CPU::~X86CPU() X86CPU::~X86CPU()
{ {
delete mInstPrinter; delete mInstPrinter;
delete mDisAsm; delete mDisAsm;
delete mMCContext; delete mMCContext;
@ -485,11 +485,11 @@ X86CPU::~X86CPU()
} }
bool X86CPU::Decode(uint32 address, DbgModuleMemoryCache* memoryCache, X86Instr* inst) bool X86CPU::Decode(uint32 address, DbgModuleMemoryCache* memoryCache, X86Instr* inst)
{ {
inst->mAddress = address; inst->mAddress = address;
inst->mX86 = this; inst->mX86 = this;
uint64 size = 0; uint64 size = 0;
uint8 data[15]; uint8 data[15];
memoryCache->Read(address, data, 15); memoryCache->Read(address, data, 15);
@ -504,15 +504,15 @@ bool X86CPU::Decode(uint32 address, DbgModuleMemoryCache* memoryCache, X86Instr*
bool X86CPU::Decode(uint32 baseAddress, const uint8* dataBase, int dataLength, const uint8* dataPtr, X86Instr* inst) bool X86CPU::Decode(uint32 baseAddress, const uint8* dataBase, int dataLength, const uint8* dataPtr, X86Instr* inst)
{ {
//X86GenericDisassembler assembler; //X86GenericDisassembler assembler;
//DisasmMemoryObject region((uint8*)dataBase, dataLength, baseAddress); //DisasmMemoryObject region((uint8*)dataBase, dataLength, baseAddress);
//std::memorystream //std::memorystream
uint32 address = baseAddress + (uint32)(dataPtr - dataBase); uint32 address = baseAddress + (uint32)(dataPtr - dataBase);
inst->mAddress = address; inst->mAddress = address;
inst->mX86 = this; inst->mX86 = this;
uint64 size = 0; uint64 size = 0;
//TODO: LLVM3.8 //TODO: LLVM3.8
//MCDisassembler::DecodeStatus S = mDisAsm->getInstruction(inst->mMCInst, size, region, address, nulls(), inst->mAnnotationStream); //MCDisassembler::DecodeStatus S = mDisAsm->getInstruction(inst->mMCInst, size, region, address, nulls(), inst->mAnnotationStream);
@ -526,7 +526,7 @@ bool X86CPU::Decode(uint32 baseAddress, const uint8* dataBase, int dataLength, c
void X86CPU::GetNextPC(uint32 baseAddress, const uint8* dataBase, int dataLength, const uint8* dataPtr, uint32* regs, uint32 nextPCs[2]) void X86CPU::GetNextPC(uint32 baseAddress, const uint8* dataBase, int dataLength, const uint8* dataPtr, uint32* regs, uint32 nextPCs[2])
{ {
//DisasmMemoryObject region((uint8*) dataBase, dataLength, baseAddress); //DisasmMemoryObject region((uint8*) dataBase, dataLength, baseAddress);
uint32 address = baseAddress + (uint32)(dataPtr - dataBase); uint32 address = baseAddress + (uint32)(dataPtr - dataBase);
uint64 size = 0; uint64 size = 0;
@ -535,17 +535,16 @@ void X86CPU::GetNextPC(uint32 baseAddress, const uint8* dataBase, int dataLength
mDisAsm->CommentStream = &nulls(); mDisAsm->CommentStream = &nulls();
ArrayRef<uint8_t> dataArrayRef(dataPtr, dataLength - (dataPtr - dataBase)); ArrayRef<uint8_t> dataArrayRef(dataPtr, dataLength - (dataPtr - dataBase));
MCDisassembler::DecodeStatus S = mDisAsm->getInstruction(mcInst, size, dataArrayRef, address, nulls()); MCDisassembler::DecodeStatus S = mDisAsm->getInstruction(mcInst, size, dataArrayRef, address, nulls());
} }
bool X86CPU::IsReturnInstruction(X86Instr* inst) bool X86CPU::IsReturnInstruction(X86Instr* inst)
{ {
const MCInstrDesc &instDesc = mInstrInfo->get(inst->mMCInst.getOpcode()); const MCInstrDesc &instDesc = mInstrInfo->get(inst->mMCInst.getOpcode());
return (instDesc.getFlags() & (1<<MCID::Return)) != 0; return (instDesc.getFlags() & (1<<MCID::Return)) != 0;
} }
String X86CPU::InstructionToString(X86Instr* inst, uint32 addr) String X86CPU::InstructionToString(X86Instr* inst, uint32 addr)
{ {
StringRef annotationsStr; StringRef annotationsStr;
SmallVector<char, 256> insnStr; SmallVector<char, 256> insnStr;
@ -553,8 +552,8 @@ String X86CPU::InstructionToString(X86Instr* inst, uint32 addr)
//mInstPrinter->CurPCRelImmOffset = addr + inst->GetLength(); //mInstPrinter->CurPCRelImmOffset = addr + inst->GetLength();
mInstPrinter->printInst(&inst->mMCInst, addr, annotationsStr, *mSubtargetInfo, OS); mInstPrinter->printInst(&inst->mMCInst, addr, annotationsStr, *mSubtargetInfo, OS);
//OS.flush(); //OS.flush();
//llvm::StringRef str = OS.str(); //llvm::StringRef str = OS.str();
String result; String result;
for (int idx = 0; idx < (int)insnStr.size(); idx++) for (int idx = 0; idx < (int)insnStr.size(); idx++)
{ {
@ -570,8 +569,8 @@ String X86CPU::InstructionToString(X86Instr* inst, uint32 addr)
else else
result.Append(c); result.Append(c);
} }
/*String result = String(insnStr.data(), insnStr.size()); /*String result = String(insnStr.data(), insnStr.size());
for (int i = 0; i < (int)result.length(); i++) for (int i = 0; i < (int)result.length(); i++)
{ {
if (result[i] == '\t') if (result[i] == '\t')
@ -671,12 +670,12 @@ int X86CPU::GetOpcodesForMnemonic(const StringImpl& mnemonic, Array<int>& outOpc
String s(mnemonic); String s(mnemonic);
std::transform(s.begin(), s.end(), s.begin(), ::tolower); std::transform(s.begin(), s.end(), s.begin(), ::tolower);
std::pair<StringToOpcodeMap::iterator, StringToOpcodeMap::iterator> range = mStringToOpcodeMap.equal_range(s); std::pair<StringToOpcodeMap::iterator, StringToOpcodeMap::iterator> range = mStringToOpcodeMap.equal_range(s);
outOpcodes.Clear(); outOpcodes.Clear();
for (StringToOpcodeMap::iterator it = range.first; it != range.second; ++it) for (StringToOpcodeMap::iterator it = range.first; it != range.second; ++it)
outOpcodes.push_back(it->second); outOpcodes.push_back(it->second);
return (int)outOpcodes.size(); return (int)outOpcodes.size();
} }
void X86CPU::GetClobbersForMnemonic(const StringImpl& mnemonic, int argCount, Array<int>& outImplicitClobberRegNums, int& outClobberArgCount, bool& outMayClobberMem) void X86CPU::GetClobbersForMnemonic(const StringImpl& mnemonic, int argCount, Array<int>& outImplicitClobberRegNums, int& outClobberArgCount, bool& outMayClobberMem)

View file

@ -193,7 +193,7 @@ public:
struct XmmDReg struct XmmDReg
{ {
double d[2]; double d[2];
}; };
struct XmmI32Reg struct XmmI32Reg
{ {
@ -289,7 +289,7 @@ public:
llvm::raw_svector_ostream mAnnotationStream; llvm::raw_svector_ostream mAnnotationStream;
static uint8 sRegForm[]; static uint8 sRegForm[];
X86Instr() : X86Instr() :
mAnnotationStream(mAnnotationStr) mAnnotationStream(mAnnotationStr)
{ {
mX86 = NULL; mX86 = NULL;
@ -297,7 +297,7 @@ public:
mSize = 0; mSize = 0;
} }
int GetLength(); int GetLength();
bool StackAdjust(uint32& adjust); bool StackAdjust(uint32& adjust);
bool IsBranch(); bool IsBranch();
bool IsCall(); bool IsCall();
@ -340,7 +340,7 @@ public:
bool Decode(uint32 baseAddress, const uint8* dataBase, int dataLength, const uint8* dataPtr, X86Instr* inst); bool Decode(uint32 baseAddress, const uint8* dataBase, int dataLength, const uint8* dataPtr, X86Instr* inst);
uint32 DecodeThunk(uint32 address, DbgModuleMemoryCache* memoryCache) { return 0; } uint32 DecodeThunk(uint32 address, DbgModuleMemoryCache* memoryCache) { return 0; }
bool IsReturnInstruction(X86Instr* inst); bool IsReturnInstruction(X86Instr* inst);
String InstructionToString(X86Instr* inst, uint32 addr); String InstructionToString(X86Instr* inst, uint32 addr);
void GetNextPC(uint32 baseAddress, const uint8* dataBase, int dataLength, const uint8* dataPtr, uint32* regs, uint32 nextPCs[2]); void GetNextPC(uint32 baseAddress, const uint8* dataBase, int dataLength, const uint8* dataPtr, uint32* regs, uint32 nextPCs[2]);

View file

@ -103,4 +103,4 @@ X86Target::~X86Target()
{ {
delete mX86CPU; delete mX86CPU;
delete mX64CPU; delete mX64CPU;
} }