Mon, 03 Mar 2014 01:04:16 +0200
- reformatting... again
--- a/namedenums/NamedEnumerations.cc Wed Feb 26 18:31:53 2014 +0200 +++ b/namedenums/NamedEnumerations.cc Mon Mar 03 01:04:16 2014 +0200 @@ -219,21 +219,21 @@ auto pos = std::unique (filesToInclude.begin(), filesToInclude.end()); filesToInclude.resize (std::distance (filesToInclude.begin(), pos)); - for (const string & a : filesToInclude) + for (const string& a : filesToInclude) fprintf (fp, "#include \"%s\"\n", basename (a.c_str())); - for (NamedEnumInfo & e : namedEnumerations) + for (NamedEnumInfo& e : namedEnumerations) { - fprintf (fp, "\nstatic const char* g%sNames[] =\n{\n", e.name.c_str()); + fprintf (fp, "\nstatic const char* g_%sNames[] =\n{\n", e.name.c_str()); - for (const string & a : e.enumerators) + for (const string& a : e.enumerators) fprintf (fp, "\t\"%s\",\n", a.c_str()); fprintf (fp, "};\n\n"); - fprintf (fp, "inline const char* Get%sString (%s a)\n" + fprintf (fp, "inline const char* get%sString (%s a)\n" "{\n" - "\treturn g%sNames[a];\n" + "\treturn g_%sNames[a];\n" "}\n", e.name.c_str(), e.name.c_str(), e.name.c_str()); }
--- a/src/Commands.cc Wed Feb 26 18:31:53 2014 +0200 +++ b/src/Commands.cc Mon Mar 03 01:04:16 2014 +0200 @@ -38,12 +38,12 @@ // ============================================================================ // -void AddCommandDefinition (CommandInfo* comm) +void addCommandDefinition (CommandInfo* comm) { // Ensure that there is no conflicts for (CommandInfo* it : gCommands) if (it->number == comm->number) - Error ("Attempted to redefine command #%1 (%2) as %3", + error ("Attempted to redefine command #%1 (%2) as %3", gCommands[comm->number]->name, comm->name); gCommands << comm; @@ -51,11 +51,11 @@ // ============================================================================ // Finds a command by name -CommandInfo* FindCommandByName (String fname) +CommandInfo* findCommandByName (String fname) { for (CommandInfo* comm : gCommands) { - if (fname.ToUppercase() == comm->name.ToUppercase()) + if (fname.toUppercase() == comm->name.toUppercase()) return comm; } @@ -66,21 +66,21 @@ // // Returns the prototype of the command // -String CommandInfo::GetSignature() +String CommandInfo::signature() { String text; - text += DataTypeName (returnvalue); + text += dataTypeName (returnvalue); text += ' '; text += name; - if (args.IsEmpty() == false) + if (args.isEmpty() == false) text += ' '; text += '('; bool hasoptionals = false; - for (int i = 0; i < args.Size(); i++) + for (int i = 0; i < args.size(); i++) { if (i == minargs) { @@ -91,22 +91,21 @@ if (i) text += ", "; - text += DataTypeName (args[i].type); + text += dataTypeName (args[i].type); text += ' '; text += args[i].name; if (i >= minargs) { + bool isString = args[i].type == TYPE_String; text += " = "; - bool is_string = args[i].type == TYPE_String; - - if (is_string) + if (isString) text += '"'; - text += String::FromNumber (args[i].defvalue); + text += String::fromNumber (args[i].defvalue); - if (is_string) + if (isString) text += '"'; } } @@ -118,7 +117,7 @@ return text; } -const List<CommandInfo*>& GetCommands() +const List<CommandInfo*>& getCommands() { return gCommands; }
--- a/src/Commands.h Wed Feb 26 18:31:53 2014 +0200 +++ b/src/Commands.h Mon Mar 03 01:04:16 2014 +0200 @@ -48,11 +48,11 @@ List<CommandArgument> args; String origin; - String GetSignature(); + String signature(); }; -void AddCommandDefinition (CommandInfo* comm); -CommandInfo* FindCommandByName (String a); -const List<CommandInfo*>& GetCommands(); +void addCommandDefinition (CommandInfo* comm); +CommandInfo* findCommandByName (String a); +const List<CommandInfo*>& getCommands(); #endif // BOTC_COMMANDS_H
--- a/src/Containers.h Wed Feb 26 18:31:53 2014 +0200 +++ b/src/Containers.h Mon Mar 03 01:04:16 2014 +0200 @@ -34,17 +34,17 @@ #include <deque> #include <initializer_list> -template<class T> +template<typename T> class List { public: - using ListType = typename std::deque<T>; - using Iterator = typename ListType::iterator; - using ConstIterator = typename ListType::const_iterator; - using ReverseIterator = typename ListType::reverse_iterator; - using ConstReverseIterator = typename ListType::const_reverse_iterator; + using WrappedList = typename std::deque<T>; + using Iterator = typename WrappedList::iterator; + using ConstIterator = typename WrappedList::const_iterator; + using ReverseIterator = typename WrappedList::reverse_iterator; + using ConstReverseIterator = typename WrappedList::const_reverse_iterator; using ValueType = T; - using SelfType = List<T>; + using Self = List<T>; // ===================================================================== // @@ -59,7 +59,7 @@ // ===================================================================== // - List (const ListType& a) : + List (const WrappedList& a) : m_data (a) {} // ===================================================================== @@ -120,15 +120,15 @@ // ===================================================================== // - inline void RemoveAt (int pos) + inline void removeAt (int pos) { - assert (pos < Size()); + assert (pos < size()); m_data.erase (m_data.begin() + pos); } // ===================================================================== // - ValueType& Prepend (const ValueType& value) + ValueType& prepend (const ValueType& value) { m_data.push_front (value); return m_data[0]; @@ -136,7 +136,7 @@ // ===================================================================== // - ValueType& Append (const ValueType& value) + ValueType& append (const ValueType& value) { m_data.push_back (value); return m_data[m_data.size() - 1]; @@ -144,51 +144,51 @@ // ===================================================================== // - void Merge (const SelfType& other) + void merge (const Self& other) { - m_data.resize (Size() + other.Size()); - std::copy (other.begin(), other.end(), begin() + other.Size()); + resize (size() + other.size()); + std::copy (other.begin(), other.end(), begin() + other.size()); } // ===================================================================== // - bool Pop (T& val) + bool pop (T& val) { - if (IsEmpty()) + if (isEmpty()) return false; - val = m_data[Size() - 1]; + val = m_data[size() - 1]; m_data.erase (m_data.end() - 1); return true; } // ===================================================================== // - SelfType& operator<< (const T& value) + Self& operator<< (const T& value) { - Append (value); + append (value); return *this; } // ===================================================================== // - void operator<< (const SelfType& vals) + void operator<< (const Self& vals) { - Merge (vals); + merge (vals); } // ===================================================================== // bool operator>> (T& value) { - return Pop (value); + return pop (value); } // ===================================================================== // - SelfType Reverse() const + Self reverse() const { - SelfType rev; + Self rev; for (const T & val : *this) val >> rev; @@ -198,32 +198,32 @@ // ===================================================================== // - void Clear() + void clear() { m_data.clear(); } // ===================================================================== // - void Insert (int pos, const ValueType& value) + void insert (int pos, const ValueType& value) { m_data.insert (m_data.begin() + pos, value); } // ===================================================================== // - void RemoveDuplicates() + void removeDuplicates() { // Remove duplicate entries. For this to be effective, the vector must be // sorted first. - Sort(); + sort(); Iterator pos = std::unique (begin(), end()); - Resize (std::distance (begin(), pos)); + resize (std::distance (begin(), pos)); } // ===================================================================== // - int Size() const + int size() const { return m_data.size(); } @@ -232,7 +232,7 @@ // ValueType& operator[] (int n) { - assert (n < Size()); + assert (n < size()); return m_data[n]; } @@ -240,27 +240,27 @@ // const ValueType& operator[] (int n) const { - assert (n < Size()); + assert (n < size()); return m_data[n]; } // ===================================================================== // - void Resize (int size) + void resize (int size) { m_data.resize (size); } // ===================================================================== // - void Sort() + void sort() { std::sort (begin(), end()); } // ===================================================================== // - int Find (const ValueType& needle) const + int find (const ValueType& needle) const { int i = 0; @@ -277,27 +277,27 @@ // ===================================================================== // - void Remove (const ValueType& it) + void removeOne (const ValueType& it) { int idx; - if ((idx = Find (it)) != -1) - RemoveAt (idx); + if ((idx = find (it)) != -1) + removeAt (idx); } // ===================================================================== // - inline bool IsEmpty() const + inline bool isEmpty() const { - return Size() == 0; + return size() == 0; } // ===================================================================== // - SelfType Mid (int a, int b) const + Self splice (int a, int b) const { - assert (a >= 0 && b >= 0 && a < Size() && b < Size() && a <= b); - SelfType result; + assert (a >= 0 && b >= 0 && a < size() && b < size() && a <= b); + Self result; for (int i = a; i <= b; ++i) result << operator[] (i); @@ -307,51 +307,51 @@ // ===================================================================== // - inline const ListType& GetDeque() const + inline const WrappedList& deque() const { return m_data; } // ===================================================================== // - inline const ValueType& First() const + inline const ValueType& first() const { return *m_data.begin(); } // ===================================================================== // - inline const ValueType& Last() const + inline const ValueType& last() const { return *(m_data.end() - 1); } // ===================================================================== // - inline bool Contains (const ValueType& a) const + inline bool contains (const ValueType& a) const { - return Find (a) != -1; + return find (a) != -1; } // ===================================================================== // - SelfType operator+ (const SelfType& other) const + Self operator+ (const Self& other) const { - SelfType out (*this); - out.Merge (other); + Self out (*this); + out.merge (other); return out; } private: - ListType m_data; + WrappedList m_data; }; // ============================================================================= // -template<class T> +template<typename T> List<T>& operator>> (const T& value, List<T>& haystack) { - haystack.push_front (value); + haystack.prepend (value); return haystack; }
--- a/src/DataBuffer.cc Wed Feb 26 18:31:53 2014 +0200 +++ b/src/DataBuffer.cc Mon Mar 03 01:04:16 2014 +0200 @@ -32,31 +32,31 @@ // DataBuffer::DataBuffer (int size) { - SetBuffer (new char[size]); - SetPosition (&Buffer()[0]); - SetAllocatedSize (size); + setBuffer (new char[size]); + setPosition (&buffer()[0]); + setAllocatedSize (size); } // ============================================================================ // DataBuffer::~DataBuffer() { - assert (Marks().Size() == 0 && References().Size() == 0); - delete Buffer(); + assert (marks().isEmpty() && references().isEmpty()); + delete buffer(); } // ============================================================================ // -void DataBuffer::MergeAndDestroy (DataBuffer* other) +void DataBuffer::mergeAndDestroy (DataBuffer* other) { - if (!other) + if (other == null) return; // Note: We transfer the marks before the buffer is copied, so that the // offset uses the proper value (which is the written size of @other, which // we don't want our written size to be added to yet). - other->TransferMarks (this); - CopyBuffer (other); + other->transferMarksTo (this); + copyBuffer (other); delete other; } @@ -65,177 +65,177 @@ // Clones this databuffer to a new one and returns it. Note that the original // transfers its marks and references and loses them in the process. // -DataBuffer* DataBuffer::Clone() +DataBuffer* DataBuffer::clone() { DataBuffer* other = new DataBuffer; - TransferMarks (other); - other->CopyBuffer (this); + transferMarksTo (other); + other->copyBuffer (this); return other; } // ============================================================================ // -void DataBuffer::CopyBuffer (const DataBuffer* buf) +void DataBuffer::copyBuffer (const DataBuffer* buf) { - CheckSpace (buf->WrittenSize()); - memcpy (mPosition, buf->Buffer(), buf->WrittenSize()); - mPosition += buf->WrittenSize(); + checkSpace (buf->writtenSize()); + memcpy (m_position, buf->buffer(), buf->writtenSize()); + m_position += buf->writtenSize(); } // ============================================================================ // -void DataBuffer::TransferMarks (DataBuffer* other) +void DataBuffer::transferMarksTo (DataBuffer* dest) { - int offset = other->WrittenSize(); + int offset = dest->writtenSize(); - for (ByteMark* mark : Marks()) + for (ByteMark* mark : marks()) { mark->pos += offset; - other->mMarks << mark; + dest->m_marks << mark; } - for (MarkReference* ref : References()) + for (MarkReference* ref : references()) { ref->pos += offset; - other->mReferences << ref; + dest->m_references << ref; } - mMarks.Clear(); - mReferences.Clear(); + m_marks.clear(); + m_references.clear(); } // ============================================================================ // -ByteMark* DataBuffer::AddMark (String name) +ByteMark* DataBuffer::addMark (const String& name) { ByteMark* mark = new ByteMark; mark->name = name; - mark->pos = WrittenSize(); - mMarks << mark; + mark->pos = writtenSize(); + m_marks << mark; return mark; } // ============================================================================ // -MarkReference* DataBuffer::AddReference (ByteMark* mark) +MarkReference* DataBuffer::addReference (ByteMark* mark) { MarkReference* ref = new MarkReference; ref->target = mark; - ref->pos = WrittenSize(); - mReferences << ref; + ref->pos = writtenSize(); + m_references << ref; // Write a dummy placeholder for the reference - WriteDWord (0xBEEFCAFE); + writeDWord (0xBEEFCAFE); return ref; } // ============================================================================ // -void DataBuffer::AdjustMark (ByteMark* mark) +void DataBuffer::adjustMark (ByteMark* mark) { - mark->pos = WrittenSize(); + mark->pos = writtenSize(); } // ============================================================================ // -void DataBuffer::OffsetMark (ByteMark* mark, int offset) +void DataBuffer::offsetMark (ByteMark* mark, int position) { - mark->pos += offset; + mark->pos += position; } // ============================================================================ // -void DataBuffer::WriteStringIndex (const String& a) +void DataBuffer::writeStringIndex (const String& a) { - WriteDWord (DH_PushStringIndex); - WriteDWord (StringTableIndex (a)); + writeDWord (DH_PushStringIndex); + writeDWord (getStringTableIndex (a)); } // ============================================================================ // -void DataBuffer::Dump() +void DataBuffer::dump() { - for (int i = 0; i < WrittenSize(); ++i) - printf ("%d. [0x%X]\n", i, Buffer()[i]); + for (int i = 0; i < writtenSize(); ++i) + printf ("%d. [0x%X]\n", i, buffer()[i]); } // ============================================================================ // -void DataBuffer::CheckSpace (int bytes) +void DataBuffer::checkSpace (int bytes) { - int writesize = WrittenSize(); + int writesize = writtenSize(); - if (writesize + bytes < AllocatedSize()) + if (writesize + bytes < allocatedSize()) return; // We don't have enough space in the buffer to write // the stuff - thus resize. First, store the old // buffer temporarily: - char* copy = new char[AllocatedSize()]; - memcpy (copy, Buffer(), AllocatedSize()); + char* copy = new char[allocatedSize()]; + memcpy (copy, buffer(), allocatedSize()); // Remake the buffer with the new size. Have enough space // for the stuff we're going to write, as well as a bit // of leeway so we don't have to resize immediately again. - int newsize = AllocatedSize() + bytes + 512; + int newsize = allocatedSize() + bytes + 512; - delete Buffer(); - SetBuffer (new char[newsize]); - SetAllocatedSize (newsize); + delete buffer(); + setBuffer (new char[newsize]); + setAllocatedSize (newsize); // Now, copy the stuff back. - memcpy (mBuffer, copy, AllocatedSize()); - SetPosition (Buffer() + writesize); + memcpy (m_buffer, copy, allocatedSize()); + setPosition (buffer() + writesize); delete copy; } // ============================================================================= // -void DataBuffer::WriteByte (int8_t data) +void DataBuffer::writeByte (int8_t data) { - CheckSpace (1); - *mPosition++ = data; + checkSpace (1); + *m_position++ = data; } // ============================================================================= // -void DataBuffer::WriteWord (int16_t data) +void DataBuffer::writeWord (int16_t data) { - CheckSpace (2); + checkSpace (2); for (int i = 0; i < 2; ++i) - *mPosition++ = (data >> (i * 8)) & 0xFF; + *m_position++ = (data >> (i * 8)) & 0xFF; } // ============================================================================= // -void DataBuffer::WriteDWord (int32_t data) +void DataBuffer::writeDWord (int32_t data) { - CheckSpace (4); + checkSpace (4); for (int i = 0; i < 4; ++i) - *mPosition++ = (data >> (i * 8)) & 0xFF; + *m_position++ = (data >> (i * 8)) & 0xFF; } // ============================================================================= // -void DataBuffer::WriteString (const String& a) +void DataBuffer::writeString (const String& a) { - CheckSpace (a.Length() + 4); - WriteDWord (a.Length()); + checkSpace (a.length() + 4); + writeDWord (a.length()); for (char c : a) - WriteByte (c); + writeByte (c); } // ============================================================================= // -ByteMark* DataBuffer::FindMarkByName (const String& target) +ByteMark* DataBuffer::findMarkByName (const String& name) { - for (ByteMark* mark : Marks()) - if (mark->name == target) + for (ByteMark* mark : marks()) + if (mark->name == name) return mark; return null;
--- a/src/DataBuffer.h Wed Feb 26 18:31:53 2014 +0200 +++ b/src/DataBuffer.h Mon Mar 03 01:04:16 2014 +0200 @@ -34,57 +34,124 @@ #include "Main.h" #include "StringTable.h" -// ============================================================================ -// data_buffer: A dynamic data buffer. -// -// Notes: -// -// - A mark is a "pointer" to a particular position in the bytecode. The actual -// permanent position cannot be predicted in any way or form, thus these things -// are used to "mark" a position like that for future use. -// -// - A reference is another "mark" that references a mark. When the bytecode -// is written to file, they are changed into their marks' current -// positions. Marks themselves are never written to files, only refs are -// +/** + * @class DataBuffer + * @brief Stores a buffer of bytecode + * + * The DataBuffer class stores a section of bytecode. Buffers are allocated on + * the heap and written to using the @c write* functions. Buffers can be cut and + * pasted together with @c mergeAndDestroy, note that this function destroys the + * parameter buffer in the process + * + * A mark is a "pointer" to a particular position in the bytecode. The actual + * permanent position cannot be predicted in any way or form, thus these things + * are used to "bookmark" a position like that for future use. + * + * A reference acts as a pointer to a mark. The reference is four bytes in the + * bytecode which will be replaced with its mark's position when the bytecode + * is written to the output file. + * + * This mark/reference system is used to know bytecode offset values when + * compiling, even though actual final positions cannot be known. + */ class DataBuffer { - PROPERTY (private, char*, Buffer, SetBuffer, STOCK_WRITE) - PROPERTY (private, int, AllocatedSize, SetAllocatedSize, STOCK_WRITE) - PROPERTY (private, char*, Position, SetPosition, STOCK_WRITE) - PROPERTY (private, List<ByteMark*>, Marks, SetMarks, STOCK_WRITE) - PROPERTY (private, List<MarkReference*>, References, SetReferences, STOCK_WRITE) + //! @ + PROPERTY (private, char*, buffer, setBuffer, STOCK_WRITE) + PROPERTY (private, int, allocatedSize, setAllocatedSize, STOCK_WRITE) + PROPERTY (private, char*, position, setPosition, STOCK_WRITE) + PROPERTY (private, List<ByteMark*>, marks, setMarks, STOCK_WRITE) + PROPERTY (private, List<MarkReference*>, references, setReferences, STOCK_WRITE) public: + //! Constructs a new databuffer with @c size bytes. DataBuffer (int size = 128); + + //! Destructs the databuffer. ~DataBuffer(); - // ==================================================================== - // Merge another data buffer into this one. - // Note: @other is destroyed in the process! - void MergeAndDestroy (DataBuffer* other); + //! Adds a new mark to the current position with the name @c name. + //! @param name the name of the new mark + //! @return a pointer to the new mark + ByteMark* addMark (const String& name); + + //! Adds a new reference to @c mark at the current position. This + //! function will write 4 bytes to the buffer whose value will + //! be determined at final output writing. + //! @param mark the mark which the new reference will attach to + //! @return a pointer to the new reference + MarkReference* addReference (ByteMark* mark); + + //! Moves @c mark to the current bytecode position. + //! @param mark the mark to adjust + void adjustMark (ByteMark* mark); + + //! Ensures there's at least @c bytes left in the buffer. Will resize + //! if necessary, no-op if not. On resize, 512 extra bytes are allocated + //! to reduce the amount of resizes. + //! @param bytes the amount of space in bytes to ensure allocated + void checkSpace (int bytes); + + //! Creates a clone of this data buffer. + //! @note All marks will be moved into the new databuffer as marks are + //! @note never duplicated. + //! @return The newly cloned databuffer. + DataBuffer* clone(); + + //! Prints the buffer to stdout. Useful for debugging. + void dump(); + + //! Finds the given mark by name. + //! @param name the name of the mark to find + ByteMark* findMarkByName (const String& name); + + //! Merge another data buffer into this one. + //! Note: @c other is destroyed in the process. + //! @param other the buffer to merge in + void mergeAndDestroy (DataBuffer* other); - ByteMark* AddMark (String name); - MarkReference* AddReference (ByteMark* mark); - void CheckSpace (int bytes); - DataBuffer* Clone(); - void DeleteMark (int marknum); - void AdjustMark (ByteMark* mark); - void OffsetMark (ByteMark* mark, int offset); - ByteMark* FindMarkByName (const String& target); - void Dump(); - void TransferMarks (DataBuffer* other); - void WriteStringIndex (const String& a); - void WriteString (const String& a); - void WriteByte (int8_t data); - void WriteWord (int16_t data); - void WriteDWord (int32_t data); - void CopyBuffer (const DataBuffer* buf); + //! Moves @c mark to the given bytecode position. + //! @param mark the mark to adjust + //! @param position where to adjust the mark + void offsetMark (ByteMark* mark, int position); + + //! Transfers all marks of this buffer to @c other. + //! @param other the data buffer to transfer marks to + void transferMarksTo (DataBuffer* other); + + //! Writes the index of the given string to the databuffer. + //! 4 bytes will be written to the bytecode. + //! @param a the string whose index to write + void writeStringIndex (const String& a); + + //! Writes the given string as-is into the databuffer. + //! @c a.length + 4 bytes will be written to the buffer. + //! @param a the string to write + void writeString (const String& a); - inline int WrittenSize() const + //! Writes the given byte to the buffer. 1 byte will be written. + //! @c data the byte to write + void writeByte (int8_t data); + + //! Writes the given word to the buffer. 2 byte will be written. + //! @c data the word to write + void writeWord (int16_t data); + + //! Writes the given double word to the buffer. 4 bytes will be written. + //! @c data the double word to write + void writeDWord (int32_t data); + + //! @return the amount of bytes written to this buffer. + inline int writtenSize() const { - return Position() - Buffer(); + return position() - buffer(); } + + protected: + //! Writes the buffer's contents from @c buf. + //! @c buf.writtenSize() bytes will be written. + //! @param buf the buffer to copy + void copyBuffer (const DataBuffer* buf); }; #endif // BOTC_DATABUFFER_H
--- a/src/Events.cc Wed Feb 26 18:31:53 2014 +0200 +++ b/src/Events.cc Mon Mar 03 01:04:16 2014 +0200 @@ -26,6 +26,8 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +// TODO: this file is a freeloader, I should probably get rid of it + #include <stdlib.h> #include <stdio.h> #include "Main.h" @@ -33,32 +35,32 @@ #include "Events.h" #include "Lexer.h" -static List<EventDefinition*> gEvents; +static List<EventDefinition*> g_Events; // ============================================================================ // -void AddEvent (EventDefinition* e) +void addEvent (EventDefinition* e) { - gEvents << e; + g_Events << e; } // ============================================================================ // // Finds an event definition by index // -EventDefinition* FindEventByIndex (int idx) +EventDefinition* findEventByIndex (int idx) { - return gEvents[idx]; + return g_Events[idx]; } // ============================================================================ // // Finds an event definition by name // -EventDefinition* FindEventByName (String a) +EventDefinition* findEventByName (String a) { - for (EventDefinition* e : gEvents) - if (a.ToUppercase() == e->name.ToUppercase()) + for (EventDefinition* e : g_Events) + if (a.toUppercase() == e->name.toUppercase()) return e; return null;
--- a/src/Events.h Wed Feb 26 18:31:53 2014 +0200 +++ b/src/Events.h Mon Mar 03 01:04:16 2014 +0200 @@ -37,8 +37,8 @@ int number; }; -void AddEvent (EventDefinition* e); -EventDefinition* FindEventByIndex (int idx); -EventDefinition* FindEventByName (String a); +void addEvent (EventDefinition* e); +EventDefinition* findEventByIndex (int idx); +EventDefinition* findEventByName (String a); #endif // BOTC_EVENTS_H
--- a/src/Expression.cc Wed Feb 26 18:31:53 2014 +0200 +++ b/src/Expression.cc Mon Mar 03 01:04:16 2014 +0200 @@ -10,7 +10,7 @@ DataHeader header; }; -static const OperatorInfo gOperators[] = +static const OperatorInfo g_Operators[] = { {TK_ExclamationMark, 0, 1, DH_NegateLogical, }, {TK_Minus, 0, 1, DH_UnaryMinus, }, @@ -38,31 +38,31 @@ // ============================================================================= // Expression::Expression (BotscriptParser* parser, Lexer* lx, DataType reqtype) : - mParser (parser), - mLexer (lx), - mType (reqtype) + m_parser (parser), + m_lexer (lx), + m_type (reqtype) { ExpressionSymbol* sym; - while ((sym = ParseSymbol()) != null) - mSymbols << sym; + while ((sym = parseSymbol()) != null) + m_symbols << sym; // If we were unable to get any expression symbols, something's wonky with // the script. Report an error. mBadTokenText is set to the token that // ParseSymbol ends at when it returns false. - if (mSymbols.IsEmpty()) - Error ("unknown identifier '%1'", mBadTokenText); + if (m_symbols.isEmpty()) + error ("unknown identifier '%1'", m_badTokenText); - AdjustOperators(); - Verify(); - Evaluate(); + adjustOperators(); + verify(); + evaluate(); } // ============================================================================= // Expression::~Expression() { - for (ExpressionSymbol* sym : mSymbols) + for (ExpressionSymbol* sym : m_symbols) delete sym; } @@ -71,171 +71,171 @@ // Try to parse an expression symbol (i.e. an OPER_erator or OPER_erand or a colon) // from the lexer. // -ExpressionSymbol* Expression::ParseSymbol() +ExpressionSymbol* Expression::parseSymbol() { - int pos = mLexer->Position(); + int pos = m_lexer->position(); ExpressionValue* op = null; - if (mLexer->Next (TK_Colon)) + if (m_lexer->next (TK_Colon)) return new ExpressionColon; // Check for OPER_erator - for (const OperatorInfo& op : gOperators) - if (mLexer->Next (op.token)) - return new ExpressionOperator ((ExpressionOperatorType) (&op - &gOperators[0])); + for (const OperatorInfo& op : g_Operators) + if (m_lexer->next (op.token)) + return new ExpressionOperator ((ExpressionOperatorType) (&op - &g_Operators[0])); // Check sub-expression - if (mLexer->Next (TK_ParenStart)) + if (m_lexer->next (TK_ParenStart)) { - Expression expr (mParser, mLexer, mType); - mLexer->MustGetNext (TK_ParenEnd); - return expr.Result()->Clone(); + Expression expr (m_parser, m_lexer, m_type); + m_lexer->mustGetNext (TK_ParenEnd); + return expr.getResult()->clone(); } - op = new ExpressionValue (mType); + op = new ExpressionValue (m_type); // Check function - if (CommandInfo* comm = FindCommandByName (mLexer->PeekNextString())) + if (CommandInfo* comm = findCommandByName (m_lexer->peekNextString())) { - mLexer->Skip(); + m_lexer->skip(); - if (mType != TYPE_Unknown && comm->returnvalue != mType) - Error ("%1 returns an incompatible data type", comm->name); + if (m_type != TYPE_Unknown && comm->returnvalue != m_type) + error ("%1 returns an incompatible data type", comm->name); - op->SetBuffer (mParser->ParseCommand (comm)); + op->setBuffer (m_parser->parseCommand (comm)); return op; } // Check for variables - if (mLexer->Next (TK_DollarSign)) + if (m_lexer->next (TK_DollarSign)) { - mLexer->MustGetNext (TK_Symbol); - Variable* var = mParser->FindVariable (TokenString()); + m_lexer->mustGetNext (TK_Symbol); + Variable* var = m_parser->findVariable (getTokenString()); if (var == null) - Error ("unknown variable %1", TokenString()); + error ("unknown variable %1", getTokenString()); - if (var->type != mType) - Error ("expression requires %1, variable $%2 is of type %3", - DataTypeName (mType), var->name, DataTypeName (var->type)); + if (var->type != m_type) + error ("expression requires %1, variable $%2 is of type %3", + dataTypeName (m_type), var->name, dataTypeName (var->type)); if (var->isarray) { - mLexer->MustGetNext (TK_BracketStart); - Expression expr (mParser, mLexer, TYPE_Int); - expr.Result()->ConvertToBuffer(); - DataBuffer* buf = expr.Result()->Buffer()->Clone(); - buf->WriteDWord (DH_PushGlobalArray); - buf->WriteDWord (var->index); - op->SetBuffer (buf); - mLexer->MustGetNext (TK_BracketEnd); + m_lexer->mustGetNext (TK_BracketStart); + Expression expr (m_parser, m_lexer, TYPE_Int); + expr.getResult()->convertToBuffer(); + DataBuffer* buf = expr.getResult()->buffer()->clone(); + buf->writeDWord (DH_PushGlobalArray); + buf->writeDWord (var->index); + op->setBuffer (buf); + m_lexer->mustGetNext (TK_BracketEnd); } elif (var->writelevel == WRITE_Constexpr) - op->SetValue (var->value); + op->setValue (var->value); else { DataBuffer* buf = new DataBuffer (8); if (var->IsGlobal()) - buf->WriteDWord (DH_PushGlobalVar); + buf->writeDWord (DH_PushGlobalVar); else - buf->WriteDWord (DH_PushLocalVar); + buf->writeDWord (DH_PushLocalVar); - buf->WriteDWord (var->index); - op->SetBuffer (buf); + buf->writeDWord (var->index); + op->setBuffer (buf); } return op; } // Check for literal - switch (mType) + switch (m_type) { case TYPE_Void: case TYPE_Unknown: { - Error ("unknown identifier `%1` (expected keyword, function or variable)", TokenString()); + error ("unknown identifier `%1` (expected keyword, function or variable)", getTokenString()); break; } case TYPE_Bool: { - if (mLexer->Next (TK_True) || mLexer->Next (TK_False)) + if (m_lexer->next (TK_True) || m_lexer->next (TK_False)) { - ETokenType tt = mLexer->TokenType(); - op->SetValue (tt == TK_True ? 1 : 0); + ETokenType tt = m_lexer->tokenType(); + op->setValue (tt == TK_True ? 1 : 0); return op; } } case TYPE_Int: { - if (mLexer->Next (TK_Number)) + if (m_lexer->next (TK_Number)) { - op->SetValue (TokenString().ToLong()); + op->setValue (getTokenString().toLong()); return op; } } case TYPE_String: { - if (mLexer->Next (TK_String)) + if (m_lexer->next (TK_String)) { - op->SetValue (StringTableIndex (TokenString())); + op->setValue (getStringTableIndex (getTokenString())); return op; } } } - mBadTokenText = mLexer->Token()->text; - mLexer->SetPosition (pos); + m_badTokenText = m_lexer->token()->text; + m_lexer->setPosition (pos); delete op; return null; } // ============================================================================= // -// The symbol parsing process only does token-based checking for OPER_erators. Thus -// ALL minus OPER_erators are actually unary minuses simply because both have -//TK_Minus as their token and the unary minus is prior to the binary minus in -// the OPER_erator table. Now that we have all symbols present, we can correct -// cases like this. +// The symbol parsing process only does token-based checking for OPER_erators. +// Thus ALL minus OPER_erators are actually unary minuses simply because both +// have TK_Minus as their token and the unary minus is prior to the binary minus +// in the OPER_erator table. Now that we have all symbols present, we can +// correct cases like this. // -void Expression::AdjustOperators() +void Expression::adjustOperators() { - for (auto it = mSymbols.begin() + 1; it != mSymbols.end(); ++it) + for (auto it = m_symbols.begin() + 1; it != m_symbols.end(); ++it) { - if ((*it)->Type() != EXPRSYM_Operator) + if ((*it)->type() != EXPRSYM_Operator) continue; ExpressionOperator* op = static_cast<ExpressionOperator*> (*it); // Unary minus with a value as the previous symbol cannot really be // unary; replace with binary minus. - if (op->ID() == OPER_UnaryMinus && (*(it - 1))->Type() == EXPRSYM_Value) - op->SetID (OPER_Subtraction); + if (op->id() == OPER_UnaryMinus && (*(it - 1))->type() == EXPRSYM_Value) + op->setID (OPER_Subtraction); } } // ============================================================================= // -// Verifies a single value. Helper function for Expression::Verify. +// Verifies a single value. Helper function for Expression::verify. // -void Expression::TryVerifyValue (bool* verified, SymbolList::Iterator it) +void Expression::tryVerifyValue (bool* verified, SymbolList::Iterator it) { // If it's an unary OPER_erator we skip to its value. The actual OPER_erator will // be verified separately. - if ((*it)->Type() == EXPRSYM_Operator && - gOperators[static_cast<ExpressionOperator*> (*it)->ID()].numoperands == 1) + if ((*it)->type() == EXPRSYM_Operator && + g_Operators[static_cast<ExpressionOperator*> (*it)->id()].numoperands == 1) { ++it; } - int i = it - mSymbols.begin(); + int i = it - m_symbols.begin(); // Ensure it's an actual value - if ((*it)->Type() != EXPRSYM_Value) - Error ("malformed expression (symbol #%1 is not a value)", i); + if ((*it)->type() != EXPRSYM_Value) + error ("malformed expression (symbol #%1 is not a value)", i); verified[i] = true; } @@ -245,33 +245,33 @@ // Ensures the expression is valid and well-formed and not OMGWTFBBQ. Throws an // error if this is not the case. // -void Expression::Verify() +void Expression::verify() { - if (mSymbols.Size() == 1) + if (m_symbols.size() == 1) { - if (mSymbols[0]->Type() != EXPRSYM_Value) - Error ("bad expression"); + if (m_symbols[0]->type() != EXPRSYM_Value) + error ("bad expression"); return; } - if (mType == TYPE_String) - Error ("Cannot perform OPER_erations on strings"); + if (m_type == TYPE_String) + error ("Cannot perform OPER_erations on strings"); - bool* verified = new bool[mSymbols.Size()]; - memset (verified, 0, mSymbols.Size() * sizeof (decltype (*verified))); - const auto last = mSymbols.end() - 1; - const auto first = mSymbols.begin(); + bool* verified = new bool[m_symbols.size()]; + memset (verified, 0, m_symbols.size() * sizeof (decltype (*verified))); + const auto last = m_symbols.end() - 1; + const auto first = m_symbols.begin(); - for (auto it = mSymbols.begin(); it != mSymbols.end(); ++it) + for (auto it = m_symbols.begin(); it != m_symbols.end(); ++it) { int i = (it - first); - if ((*it)->Type() != EXPRSYM_Operator) + if ((*it)->type() != EXPRSYM_Operator) continue; ExpressionOperator* op = static_cast<ExpressionOperator*> (*it); - int numoperands = gOperators[op->ID()].numoperands; + int numoperands = g_Operators[op->id()].numoperands; switch (numoperands) { @@ -281,10 +281,10 @@ // - unary OPER_erator is not the last symbol // - unary OPER_erator is succeeded by a value symbol // - neither symbol overlaps with something already verified - TryVerifyValue (verified, it + 1); + tryVerifyValue (verified, it + 1); if (it == last || verified[i] == true) - Error ("malformed expression"); + error ("malformed expression"); verified[i] = true; break; @@ -299,10 +299,10 @@ // // Basically similar logic as above. if (it == first || it == last || verified[i] == true) - Error ("malformed expression"); + error ("malformed expression"); - TryVerifyValue (verified, it + 1); - TryVerifyValue (verified, it - 1); + tryVerifyValue (verified, it + 1); + tryVerifyValue (verified, it - 1); verified[i] = true; break; } @@ -323,17 +323,17 @@ // - the value after the colon (+3) is valid // - none of the five tokens are verified // - TryVerifyValue (verified, it - 1); - TryVerifyValue (verified, it + 1); - TryVerifyValue (verified, it + 3); + tryVerifyValue (verified, it - 1); + tryVerifyValue (verified, it + 1); + tryVerifyValue (verified, it + 3); if (it == first || - it >= mSymbols.end() - 3 || + it >= m_symbols.end() - 3 || verified[i] == true || verified[i + 2] == true || - (*(it + 2))->Type() != EXPRSYM_Colon) + (*(it + 2))->type() != EXPRSYM_Colon) { - Error ("malformed expression"); + error ("malformed expression"); } verified[i] = true; @@ -342,13 +342,13 @@ } default: - Error ("WTF OPER_erator with %1 OPER_erands", numoperands); + error ("WTF OPER_erator with %1 OPER_erands", numoperands); } } - for (int i = 0; i < mSymbols.Size(); ++i) + for (int i = 0; i < m_symbols.size(); ++i) if (verified[i] == false) - Error ("malformed expression: expr symbol #%1 is was left unverified", i); + error ("malformed expression: expr symbol #%1 is was left unverified", i); delete verified; } @@ -356,20 +356,20 @@ // ============================================================================= // -// Which OPER_erator to evaluate? +// Which operator to evaluate? // -Expression::SymbolList::Iterator Expression::FindPrioritizedOperator() +Expression::SymbolList::Iterator Expression::findPrioritizedOperator() { - SymbolList::Iterator best = mSymbols.end(); + SymbolList::Iterator best = m_symbols.end(); int bestpriority = __INT_MAX__; - for (SymbolList::Iterator it = mSymbols.begin(); it != mSymbols.end(); ++it) + for (SymbolList::Iterator it = m_symbols.begin(); it != m_symbols.end(); ++it) { - if ((*it)->Type() != EXPRSYM_Operator) + if ((*it)->type() != EXPRSYM_Operator) continue; ExpressionOperator* op = static_cast<ExpressionOperator*> (*it); - const OperatorInfo* info = &gOperators[op->ID()]; + const OperatorInfo* info = &g_Operators[op->id()]; if (info->priority < bestpriority) { @@ -385,16 +385,16 @@ // // Process the given OPER_erator and values into a new value. // -ExpressionValue* Expression::EvaluateOperator (const ExpressionOperator* op, +ExpressionValue* Expression::evaluateOperator (const ExpressionOperator* op, const List<ExpressionValue*>& values) { - const OperatorInfo* info = &gOperators[op->ID()]; + const OperatorInfo* info = &g_Operators[op->id()]; bool isconstexpr = true; - assert (values.Size() == info->numoperands); + assert (values.size() == info->numoperands); for (ExpressionValue* val : values) { - if (val->IsConstexpr() == false) + if (val->isConstexpr() == false) { isconstexpr = false; break; @@ -404,41 +404,41 @@ // If not all of the values are constant expressions, none of them shall be. if (isconstexpr == false) for (ExpressionValue* val : values) - val->ConvertToBuffer(); + val->convertToBuffer(); - ExpressionValue* newval = new ExpressionValue (mType); + ExpressionValue* newval = new ExpressionValue (m_type); if (isconstexpr == false) { // This is not a constant expression so we'll have to use databuffers // to convey the expression to bytecode. Actual value cannot be evaluated // until Zandronum processes it at run-time. - newval->SetBuffer (new DataBuffer); + newval->setBuffer (new DataBuffer); - if (op->ID() == OPER_Ternary) + if (op->id() == OPER_Ternary) { // There isn't a dataheader for ternary OPER_erator. Instead, we use DH_IfNotGoto // to create an "if-block" inside an expression. // Behold, big block of writing madness! :P // - DataBuffer* buf = newval->Buffer(); - DataBuffer* b0 = values[0]->Buffer(); - DataBuffer* b1 = values[1]->Buffer(); - DataBuffer* b2 = values[2]->Buffer(); - ByteMark* mark1 = buf->AddMark (""); // start of "else" case - ByteMark* mark2 = buf->AddMark (""); // end of expression - buf->MergeAndDestroy (b0); - buf->WriteDWord (DH_IfNotGoto); // if the first OPER_erand (condition) - buf->AddReference (mark1); // didn't eval true, jump into mark1 - buf->MergeAndDestroy (b1); // otherwise, perform second OPER_erand (true case) - buf->WriteDWord (DH_Goto); // afterwards, jump to the end, which is - buf->AddReference (mark2); // marked by mark2. - buf->AdjustMark (mark1); // move mark1 at the end of the true case - buf->MergeAndDestroy (b2); // perform third OPER_erand (false case) - buf->AdjustMark (mark2); // move the ending mark2 here + DataBuffer* buf = newval->buffer(); + DataBuffer* b0 = values[0]->buffer(); + DataBuffer* b1 = values[1]->buffer(); + DataBuffer* b2 = values[2]->buffer(); + ByteMark* mark1 = buf->addMark (""); // start of "else" case + ByteMark* mark2 = buf->addMark (""); // end of expression + buf->mergeAndDestroy (b0); + buf->writeDWord (DH_IfNotGoto); // if the first OPER_erand (condition) + buf->addReference (mark1); // didn't eval true, jump into mark1 + buf->mergeAndDestroy (b1); // otherwise, perform second OPER_erand (true case) + buf->writeDWord (DH_Goto); // afterwards, jump to the end, which is + buf->addReference (mark2); // marked by mark2. + buf->adjustMark (mark1); // move mark1 at the end of the true case + buf->mergeAndDestroy (b2); // perform third OPER_erand (false case) + buf->adjustMark (mark2); // move the ending mark2 here for (int i = 0; i < 3; ++i) - values[i]->SetBuffer (null); + values[i]->setBuffer (null); } else { @@ -446,14 +446,14 @@ // data header. for (ExpressionValue* val : values) { - newval->Buffer()->MergeAndDestroy (val->Buffer()); + newval->buffer()->mergeAndDestroy (val->buffer()); // Null the pointer out so that the value's destructor will not // attempt to double-free it. - val->SetBuffer (null); + val->setBuffer (null); } - newval->Buffer()->WriteDWord (info->header); + newval->buffer()->writeDWord (info->header); } } else @@ -464,11 +464,11 @@ int a; for (ExpressionValue* val : values) - nums << val->Value(); + nums << val->value(); - switch (op->ID()) + switch (op->id()) { - case OPER_Addition: a = nums[0] + nums[1]; break; + case OPER_Addition: a = nums[0] + nums[1]; break; case OPER_Subtraction: a = nums[0] - nums[1]; break; case OPER_Multiplication: a = nums[0] * nums[1]; break; case OPER_UnaryMinus: a = -nums[0]; break; @@ -480,7 +480,7 @@ case OPER_CompareAtLeast: a = (nums[0] <= nums[1]) ? 1 : 0; break; case OPER_CompareAtMost: a = (nums[0] >= nums[1]) ? 1 : 0; break; case OPER_CompareEquals: a = (nums[0] == nums[1]) ? 1 : 0; break; - case OPER_CompareNotEquals: a = (nums[0] != nums[1]) ? 1 : 0; break; + case OPER_CompareNotEquals: a = (nums[0] != nums[1]) ? 1 : 0; break; case OPER_BitwiseAnd: a = nums[0] & nums[1]; break; case OPER_BitwiseOr: a = nums[0] | nums[1]; break; case OPER_BitwiseXOr: a = nums[0] ^ nums[1]; break; @@ -491,7 +491,7 @@ case OPER_Division: { if (nums[1] == 0) - Error ("division by zero in constant expression"); + error ("division by zero in constant expression"); a = nums[0] / nums[1]; break; @@ -500,14 +500,14 @@ case OPER_Modulus: { if (nums[1] == 0) - Error ("modulus by zero in constant expression"); + error ("modulus by zero in constant expression"); a = nums[0] % nums[1]; break; } } - newval->SetValue (a); + newval->setValue (a); } // The new value has been generated. We don't need the old stuff anymore. @@ -520,16 +520,16 @@ // ============================================================================= // -ExpressionValue* Expression::Evaluate() +ExpressionValue* Expression::evaluate() { SymbolList::Iterator it; - while ((it = FindPrioritizedOperator()) != mSymbols.end()) + while ((it = findPrioritizedOperator()) != m_symbols.end()) { - int i = it - mSymbols.begin(); + int i = it - m_symbols.begin(); List<SymbolList::Iterator> OPER_erands; ExpressionOperator* op = static_cast<ExpressionOperator*> (*it); - const OperatorInfo* info = &gOperators[op->ID()]; + const OperatorInfo* info = &g_Operators[op->id()]; int lower, upper; // Boundaries of area to replace switch (info->numoperands) @@ -571,76 +571,76 @@ values << static_cast<ExpressionValue*> (*it); // Note: @op and all of @values are invalid after this call. - ExpressionValue* newvalue = EvaluateOperator (op, values); + ExpressionValue* newvalue = evaluateOperator (op, values); for (int i = upper; i >= lower; --i) - mSymbols.RemoveAt (i); + m_symbols.removeAt (i); - mSymbols.Insert (lower, newvalue); + m_symbols.insert (lower, newvalue); } - assert (mSymbols.Size() == 1 && mSymbols.First()->Type() == EXPRSYM_Value); - ExpressionValue* val = static_cast<ExpressionValue*> (mSymbols.First()); + assert (m_symbols.size() == 1 && m_symbols.first()->type() == EXPRSYM_Value); + ExpressionValue* val = static_cast<ExpressionValue*> (m_symbols.first()); return val; } // ============================================================================= // -ExpressionValue* Expression::Result() +ExpressionValue* Expression::getResult() { - return static_cast<ExpressionValue*> (mSymbols.First()); + return static_cast<ExpressionValue*> (m_symbols.first()); } // ============================================================================= // -String Expression::TokenString() +String Expression::getTokenString() { - return mLexer->Token()->text; + return m_lexer->token()->text; } // ============================================================================= // ExpressionOperator::ExpressionOperator (ExpressionOperatorType id) : ExpressionSymbol (EXPRSYM_Operator), - mID (id) {} + m_id (id) {} // ============================================================================= // ExpressionValue::ExpressionValue (DataType valuetype) : ExpressionSymbol (EXPRSYM_Value), - mBuffer (null), - mValueType (valuetype) {} + m_buffer (null), + m_valueType (valuetype) {} // ============================================================================= // ExpressionValue::~ExpressionValue() { - delete mBuffer; + delete m_buffer; } // ============================================================================= // -void ExpressionValue::ConvertToBuffer() +void ExpressionValue::convertToBuffer() { - if (IsConstexpr() == false) + if (isConstexpr() == false) return; - SetBuffer (new DataBuffer); + setBuffer (new DataBuffer); - switch (mValueType) + switch (m_valueType) { case TYPE_Bool: case TYPE_Int: - Buffer()->WriteDWord (DH_PushNumber); - Buffer()->WriteDWord (abs (mValue)); + buffer()->writeDWord (DH_PushNumber); + buffer()->writeDWord (abs (value())); - if (mValue < 0) - Buffer()->WriteDWord (DH_UnaryMinus); + if (value() < 0) + buffer()->writeDWord (DH_UnaryMinus); break; case TYPE_String: - Buffer()->WriteDWord (DH_PushStringIndex); - Buffer()->WriteDWord (mValue); + buffer()->writeDWord (DH_PushStringIndex); + buffer()->writeDWord (value()); break; case TYPE_Void:
--- a/src/Expression.h Wed Feb 26 18:31:53 2014 +0200 +++ b/src/Expression.h Mon Mar 03 01:04:16 2014 +0200 @@ -50,24 +50,24 @@ Expression (BotscriptParser* parser, Lexer* lx, DataType reqtype); ~Expression(); - ExpressionValue* Result(); + ExpressionValue* getResult(); private: - BotscriptParser* mParser; - Lexer* mLexer; - SymbolList mSymbols; - DataType mType; - String mBadTokenText; + BotscriptParser* m_parser; + Lexer* m_lexer; + SymbolList m_symbols; + DataType m_type; + String m_badTokenText; - ExpressionValue* Evaluate(); // Process the expression and yield a result - ExpressionSymbol* ParseSymbol(); - String TokenString(); - void AdjustOperators(); - void Verify(); // Ensure the expr is valid - void TryVerifyValue (bool* verified, SymbolList::Iterator it); - ExpressionValue* EvaluateOperator (const ExpressionOperator* op, + ExpressionValue* evaluate(); // Process the expression and yield a result + ExpressionSymbol* parseSymbol(); + String getTokenString(); + void adjustOperators(); + void verify(); // Ensure the expr is valid + void tryVerifyValue (bool* verified, SymbolList::Iterator it); + ExpressionValue* evaluateOperator (const ExpressionOperator* op, const List<ExpressionValue*>& values); - SymbolList::Iterator FindPrioritizedOperator(); + SymbolList::Iterator findPrioritizedOperator(); }; // ============================================================================= @@ -76,16 +76,16 @@ { public: ExpressionSymbol (ExpressionSymbolType type) : - mType (type) {} + m_type (type) {} - PROPERTY (private, ExpressionSymbolType, Type, SetType, STOCK_WRITE) + PROPERTY (private, ExpressionSymbolType, type, setType, STOCK_WRITE) }; // ============================================================================= // class ExpressionOperator final : public ExpressionSymbol { - PROPERTY (public, ExpressionOperatorType, ID, SetID, STOCK_WRITE) + PROPERTY (public, ExpressionOperatorType, id, setID, STOCK_WRITE) public: ExpressionOperator (ExpressionOperatorType id); @@ -95,24 +95,24 @@ // class ExpressionValue final : public ExpressionSymbol { - PROPERTY (public, int, Value, SetValue, STOCK_WRITE) - PROPERTY (public, DataBuffer*, Buffer, SetBuffer, STOCK_WRITE) - PROPERTY (public, DataType, ValueType, SetValueType, STOCK_WRITE) + PROPERTY (public, int, value, setValue, STOCK_WRITE) + PROPERTY (public, DataBuffer*, buffer, setBuffer, STOCK_WRITE) + PROPERTY (public, DataType, valueType, setValueType, STOCK_WRITE) public: ExpressionValue (DataType valuetype); ~ExpressionValue(); - void ConvertToBuffer(); + void convertToBuffer(); - inline ExpressionValue* Clone() const + inline ExpressionValue* clone() const { return new ExpressionValue (*this); } - inline bool IsConstexpr() const + inline bool isConstexpr() const { - return Buffer() == null; + return buffer() == null; } };
--- a/src/Format.cc Wed Feb 26 18:31:53 2014 +0200 +++ b/src/Format.cc Mon Mar 03 01:04:16 2014 +0200 @@ -33,32 +33,32 @@ // ============================================================================= // -static void FormatError (String fmtstr, const String errdescribe, int pos) +static void formatError (String fmtstr, const String errdescribe, int pos) { - fmtstr.Replace ("\n", " "); - fmtstr.Replace ("\t", " "); + fmtstr.replace ("\n", " "); + fmtstr.replace ("\t", " "); String errmsg ("With format string:\n" + fmtstr + "\n"); for (int x = 0; x < pos; ++x) errmsg += "-"; errmsg += "^\n" + errdescribe; - throw std::logic_error (errmsg.STDString()); + throw std::logic_error (errmsg.stdString()); } // ============================================================================= // -String FormatArgs (const String& fmtstr, const std::vector<String>& args) +String formatArgs (const String& fmtstr, const std::vector<String>& args) { String fmt = fmtstr; String out; int pos = 0; - while ((pos = fmt.FirstIndexOf ("%", pos)) != -1) + while ((pos = fmt.firstIndexOf ("%", pos)) != -1) { if (fmt[pos + 1] == '%') { - fmt.Replace (pos, 2, "%"); + fmt.replace (pos, 2, "%"); pos++; continue; } @@ -74,26 +74,26 @@ } if (!isdigit (fmt[pos + ofs])) - FormatError (fmtstr, "bad format string, expected digit with optional " + formatError (fmtstr, "bad format string, expected digit with optional " "modifier after '%%'", pos); int i = fmt[pos + ofs] - '0'; if (i > static_cast<signed> (args.size())) - FormatError (fmtstr, String ("Format argument #") + i + " used but not defined.", pos); + formatError (fmtstr, String ("Format argument #") + i + " used but not defined.", pos); String replacement = args[i - 1]; switch (mod) { case 's': replacement = (replacement == "1") ? "" : "s"; break; - case 'd': replacement.SPrintf ("%d", replacement[0]); break; - case 'x': replacement.SPrintf ("0x%X", replacement.ToLong()); break; + case 'd': replacement.sprintf ("%d", replacement[0]); break; + case 'x': replacement.sprintf ("0x%X", replacement.toLong()); break; default: break; } - fmt.Replace (pos, 1 + ofs, replacement); - pos += replacement.Length(); + fmt.replace (pos, 1 + ofs, replacement); + pos += replacement.length(); } return fmt; @@ -101,15 +101,15 @@ // ============================================================================= // -void Error (String msg) +void error (String msg) { - Lexer* lx = Lexer::GetCurrentLexer(); + Lexer* lx = Lexer::getCurrentLexer(); String fileinfo; - if (lx != null && lx->HasValidToken()) + if (lx != null && lx->hasValidToken()) { - Lexer::TokenInfo* tk = lx->Token(); - fileinfo = Format ("%1:%2:%3: ", tk->file, tk->line, tk->column); + Lexer::TokenInfo* tk = lx->token(); + fileinfo = format ("%1:%2:%3: ", tk->file, tk->line, tk->column); } throw std::runtime_error (fileinfo + msg);
--- a/src/Format.h Wed Feb 26 18:31:53 2014 +0200 +++ b/src/Format.h Mon Mar 03 01:04:16 2014 +0200 @@ -35,50 +35,50 @@ class FormatArgument { public: - FormatArgument (const String& a) : mText (a) {} - FormatArgument (char a) : mText (a) {} - FormatArgument (int a) : mText (String::FromNumber (a)) {} - FormatArgument (long a) : mText (String::FromNumber (a)) {} - FormatArgument (const char* a) : mText (a) {} + FormatArgument (const String& a) : m_text (a) {} + FormatArgument (char a) : m_text (a) {} + FormatArgument (int a) : m_text (String::fromNumber (a)) {} + FormatArgument (long a) : m_text (String::fromNumber (a)) {} + FormatArgument (const char* a) : m_text (a) {} FormatArgument (void* a) { - mText.SPrintf ("%p", a); + m_text.sprintf ("%p", a); } FormatArgument (const void* a) { - mText.SPrintf ("%p", a); + m_text.sprintf ("%p", a); } template<class T> FormatArgument (const List<T>& list) { - if (list.IsEmpty()) + if (list.isEmpty()) { - mText = "{}"; + m_text = "{}"; return; } - mText = "{ "; + m_text = "{ "; - for (const T & a : list) + for (const T& a : list) { if (&a != &list[0]) - mText += ", "; + m_text += ", "; - mText += FormatArgument (a).AsString(); + m_text += FormatArgument (a).text(); } - mText += " }"; + m_text += " }"; } - inline const String& AsString() const + inline const String& text() const { - return mText; + return m_text; } private: - String mText; + String m_text; }; #ifndef IN_IDE_PARSER @@ -105,7 +105,7 @@ * @param args Args to format with the string. * @see format() */ -String FormatArgs (const String& fmtstr, const std::vector<String>& args); +String formatArgs (const String& fmtstr, const std::vector<String>& args); /** * Expands the given arguments into a vector of strings. @@ -115,17 +115,17 @@ * @param rest... Rest of the arguments. */ template<typename T, typename... RestTypes> -void ExpandFormatArguments (std::vector<String>& data, const T& arg, const RestTypes& ... rest) +void expandFormatArguments (std::vector<String>& data, const T& arg, const RestTypes& ... rest) { - data.push_back (FormatArgument (arg).AsString()); - ExpandFormatArguments (data, rest...); + data.push_back (FormatArgument (arg).text()); + expandFormatArguments (data, rest...); } /** * This is an overload of @c ExpandFormatArguments for end-of-args support. */ -static void ExpandFormatArguments (std::vector<String>& data) __attribute__ ( (unused)); -static void ExpandFormatArguments (std::vector<String>& data) +static void expandFormatArguments (std::vector<String>& data) __attribute__ ( (unused)); +static void expandFormatArguments (std::vector<String>& data) { (void) data; } @@ -161,49 +161,49 @@ * @see PrintTo */ template<typename... argtypes> -String Format (const String& fmtstr, const argtypes&... raw_args) +String format (const String& fmtstr, const argtypes&... raw_args) { std::vector<String> args; - ExpandFormatArguments (args, raw_args...); + expandFormatArguments (args, raw_args...); assert (args.size() == sizeof... (raw_args)); - return FormatArgs (fmtstr, args); + return formatArgs (fmtstr, args); } /** - * This is an overload of @c Format where no arguments are supplied. + * This is an overload of @c format where no arguments are supplied. * @return the formatter string as-is. */ -static String Format (const String& fmtstr) __attribute__ ( (unused)); -static String Format (const String& fmtstr) +static String format (const String& fmtstr) __attribute__ ( (unused)); +static String format (const String& fmtstr) { return fmtstr; } /** - * Processes the given formatter string using @c Format and prints it to the + * Processes the given formatter string using @c format and prints it to the * specified file pointer. * * @param fp File pointer to print the formatted string to - * @param fmtstr Formatter string for @c Format + * @param fmtstr Formatter string for @c format * @param args Arguments for @c fmtstr */ template<typename... argtypes> -void PrintTo (FILE* fp, const String& fmtstr, const argtypes&... args) +void printTo (FILE* fp, const String& fmtstr, const argtypes&... args) { - fprintf (fp, "%s", Format (fmtstr, args...).c_str()); + fprintf (fp, "%s", format (fmtstr, args...).c_str()); } /** - * Processes the given formatter string using @c Format and prints the result to + * Processes the given formatter string using @c format and prints the result to * @c stdout. * - * @param fmtstr Formatter string for @c Format + * @param fmtstr Formatter string for @c format * @param args Arguments for @c fmtstr */ template<typename... argtypes> -void Print (const String& fmtstr, const argtypes&... args) +void print (const String& fmtstr, const argtypes&... args) { - PrintTo (stdout, fmtstr, args...); + printTo (stdout, fmtstr, args...); } /** @@ -216,9 +216,9 @@ * @see Format */ template<typename... argtypes> -void Error (const String& fmtstr, const argtypes&... args) +void error (const String& fmtstr, const argtypes&... args) { - Error (Format (fmtstr, args...)); + error (format (fmtstr, args...)); } /** @@ -226,6 +226,6 @@ * * @param msg The error message. */ -void Error (String msg); +void error (String msg); #endif // BOTC_FORMAT_H
--- a/src/Lexer.cc Wed Feb 26 18:31:53 2014 +0200 +++ b/src/Lexer.cc Mon Mar 03 01:04:16 2014 +0200 @@ -49,114 +49,114 @@ // ============================================================================= // -void Lexer::ProcessFile (String fileName) +void Lexer::processFile (String fileName) { gFileNameStack << fileName; FILE* fp = fopen (fileName, "r"); if (fp == null) - Error ("couldn't open %1 for reading: %2", fileName, strerror (errno)); + error ("couldn't open %1 for reading: %2", fileName, strerror (errno)); LexerScanner sc (fp); - CheckFileHeader (sc); + checkFileHeader (sc); - while (sc.GetNextToken()) + while (sc.getNextToken()) { // Preprocessor commands: - if (sc.GetTokenType() ==TK_Hash) + if (sc.getTokenType() ==TK_Hash) { - MustGetFromScanner (sc,TK_Symbol); + mustGetFromScanner (sc,TK_Symbol); - if (sc.GetTokenText() == "include") + if (sc.getTokenText() == "include") { - MustGetFromScanner (sc,TK_String); - String fileName = sc.GetTokenText(); + mustGetFromScanner (sc,TK_String); + String fileName = sc.getTokenText(); - if (gFileNameStack.Contains (fileName)) - Error ("attempted to #include %1 recursively", sc.GetTokenText()); + if (gFileNameStack.contains (fileName)) + error ("attempted to #include %1 recursively", sc.getTokenText()); - ProcessFile (fileName); + processFile (fileName); } else - Error ("unknown preprocessor directive \"#%1\"", sc.GetTokenText()); + error ("unknown preprocessor directive \"#%1\"", sc.getTokenText()); } else { TokenInfo tok; tok.file = fileName; - tok.line = sc.GetLine(); - tok.column = sc.GetColumn(); - tok.type = sc.GetTokenType(); - tok.text = sc.GetTokenText(); + tok.line = sc.getLine(); + tok.column = sc.getColumn(); + tok.type = sc.getTokenType(); + tok.text = sc.getTokenText(); - // devf ("Token #%1: %2:%3:%4: %5 (%6)\n", mTokens.Size(), + // devf ("Token #%1: %2:%3:%4: %5 (%6)\n", mTokens.size(), // tok.file, tok.line, tok.column, DescribeToken (&tok), // GetTokenTypeString (tok.type)); - mTokens << tok; + m_tokens << tok; } } - mTokenPosition = mTokens.begin() - 1; - gFileNameStack.Remove (fileName); + m_tokenPosition = m_tokens.begin() - 1; + gFileNameStack.removeOne (fileName); } // ============================================================================ // static bool IsValidHeader (String header) { - if (header.EndsWith ("\n")) - header.RemoveFromEnd (1); + if (header.endsWith ("\n")) + header.removeFromEnd (1); - StringList tokens = header.Split (" "); + StringList tokens = header.split (" "); - if (tokens.Size() != 2 || tokens[0] != "#!botc" || tokens[1].IsEmpty()) + if (tokens.size() != 2 || tokens[0] != "#!botc" || tokens[1].isEmpty()) return false; - StringList nums = tokens[1].Split ("."); + StringList nums = tokens[1].split ("."); - if (nums.Size() == 2) + if (nums.size() == 2) nums << "0"; - elif (nums.Size() != 3) + elif (nums.size() != 3) return false; bool okA, okB, okC; - long major = nums[0].ToLong (&okA); - long minor = nums[1].ToLong (&okB); - long patch = nums[2].ToLong (&okC); + long major = nums[0].toLong (&okA); + long minor = nums[1].toLong (&okB); + long patch = nums[2].toLong (&okC); if (!okA || !okB || !okC) return false; if (VERSION_NUMBER < MAKE_VERSION_NUMBER (major, minor, patch)) - Error ("The script file requires " APPNAME " v%1, this is v%2", - MakeVersionString (major, minor, patch), GetVersionString (false)); + error ("The script file requires " APPNAME " v%1, this is v%2", + makeVersionString (major, minor, patch), versionString (false)); return true; } // ============================================================================ // -void Lexer::CheckFileHeader (LexerScanner& sc) +void Lexer::checkFileHeader (LexerScanner& sc) { - if (!IsValidHeader (sc.ReadLine())) - Error ("Not a valid botscript file! File must start with '#!botc <version>'"); + if (!IsValidHeader (sc.readLine())) + error ("Not a valid botscript file! File must start with '#!botc <version>'"); } // ============================================================================= // -bool Lexer::Next (ETokenType req) +bool Lexer::next (ETokenType req) { - Iterator pos = mTokenPosition; + Iterator pos = m_tokenPosition; - if (mTokens.IsEmpty()) + if (m_tokens.isEmpty()) return false; - mTokenPosition++; + m_tokenPosition++; - if (IsAtEnd() || (req !=TK_Any && TokenType() != req)) + if (isAtEnd() || (req !=TK_Any && tokenType() != req)) { - mTokenPosition = pos; + m_tokenPosition = pos; return false; } @@ -165,99 +165,99 @@ // ============================================================================= // -void Lexer::MustGetNext (ETokenType tok) +void Lexer::mustGetNext (ETokenType tok) { - if (!Next()) - Error ("unexpected EOF"); + if (!next()) + error ("unexpected EOF"); if (tok !=TK_Any) - TokenMustBe (tok); + tokenMustBe (tok); } // ============================================================================= // eugh.. // -void Lexer::MustGetFromScanner (LexerScanner& sc, ETokenType tt) +void Lexer::mustGetFromScanner (LexerScanner& sc, ETokenType tt) { - if (!sc.GetNextToken()) - Error ("unexpected EOF"); + if (sc.getNextToken() == false) + error ("unexpected EOF"); - if (tt !=TK_Any && sc.GetTokenType() != tt) + if (tt != TK_Any && sc.getTokenType() != tt) { // TODO TokenInfo tok; - tok.type = sc.GetTokenType(); - tok.text = sc.GetTokenText(); + tok.type = sc.getTokenType(); + tok.text = sc.getTokenText(); - Error ("at %1:%2: expected %3, got %4", - gFileNameStack.Last(), - sc.GetLine(), - DescribeTokenType (tt), - DescribeToken (&tok)); + error ("at %1:%2: expected %3, got %4", + gFileNameStack.last(), + sc.getLine(), + describeTokenType (tt), + describeToken (&tok)); } } // ============================================================================= // -void Lexer::MustGetAnyOf (const List<ETokenType>& toks) +void Lexer::mustGetAnyOf (const List<ETokenType>& toks) { - if (!Next()) - Error ("unexpected EOF"); + if (!next()) + error ("unexpected EOF"); for (ETokenType tok : toks) - if (TokenType() == tok) + if (tokenType() == tok) return; String toknames; for (const ETokenType& tokType : toks) { - if (&tokType == &toks.Last()) + if (&tokType == &toks.last()) toknames += " or "; - elif (toknames.IsEmpty() == false) + elif (toknames.isEmpty() == false) toknames += ", "; - toknames += DescribeTokenType (tokType); + toknames += describeTokenType (tokType); } - Error ("expected %1, got %2", toknames, DescribeToken (Token())); + error ("expected %1, got %2", toknames, describeToken (token())); } // ============================================================================= // -int Lexer::GetOneSymbol (const StringList& syms) +int Lexer::getOneSymbol (const StringList& syms) { - if (!Next()) - Error ("unexpected EOF"); + if (!next()) + error ("unexpected EOF"); - if (TokenType() ==TK_Symbol) + if (tokenType() ==TK_Symbol) { - for (int i = 0; i < syms.Size(); ++i) + for (int i = 0; i < syms.size(); ++i) { - if (syms[i] == Token()->text) + if (syms[i] == token()->text) return i; } } - Error ("expected one of %1, got %2", syms, DescribeToken (Token())); + error ("expected one of %1, got %2", syms, describeToken (token())); return -1; } // ============================================================================= // -void Lexer::TokenMustBe (ETokenType tok) +void Lexer::tokenMustBe (ETokenType tok) { - if (TokenType() != tok) - Error ("expected %1, got %2", DescribeTokenType (tok), - DescribeToken (Token())); + if (tokenType() != tok) + error ("expected %1, got %2", describeTokenType (tok), + describeToken (token())); } // ============================================================================= // -String Lexer::DescribeTokenPrivate (ETokenType tokType, Lexer::TokenInfo* tok) +String Lexer::describeTokenPrivate (ETokenType tokType, Lexer::TokenInfo* tok) { if (tokType <gLastNamedToken) - return "\"" + LexerScanner::GetTokenString (tokType) + "\""; + return "\"" + LexerScanner::getTokenString (tokType) + "\""; switch (tokType) { @@ -273,63 +273,63 @@ // ============================================================================= // -bool Lexer::PeekNext (Lexer::TokenInfo* tk) +bool Lexer::peekNext (Lexer::TokenInfo* tk) { - Iterator pos = mTokenPosition; - bool r = Next(); + Iterator pos = m_tokenPosition; + bool r = next(); if (r && tk != null) - *tk = *mTokenPosition; + *tk = *m_tokenPosition; - mTokenPosition = pos; + m_tokenPosition = pos; return r; } // ============================================================================= // -bool Lexer::PeekNextType (ETokenType req) +bool Lexer::peekNextType (ETokenType req) { - Iterator pos = mTokenPosition; + Iterator pos = m_tokenPosition; bool result = false; - if (Next() && TokenType() == req) + if (next() && tokenType() == req) result = true; - mTokenPosition = pos; + m_tokenPosition = pos; return result; } // ============================================================================= // -Lexer* Lexer::GetCurrentLexer() +Lexer* Lexer::getCurrentLexer() { return gMainLexer; } // ============================================================================= // -String Lexer::PeekNextString (int a) +String Lexer::peekNextString (int a) { - if (mTokenPosition + a >= mTokens.end()) + if (m_tokenPosition + a >= m_tokens.end()) return ""; - Iterator oldpos = mTokenPosition; - mTokenPosition += a; - String result = Token()->text; - mTokenPosition = oldpos; + Iterator oldpos = m_tokenPosition; + m_tokenPosition += a; + String result = token()->text; + m_tokenPosition = oldpos; return result; } // ============================================================================= // -String Lexer::DescribeCurrentPosition() +String Lexer::describeCurrentPosition() { - return Token()->file + ":" + Token()->line; + return token()->file + ":" + token()->line; } // ============================================================================= // -String Lexer::DescribeTokenPosition() +String Lexer::describeTokenPosition() { - return Format ("%1 / %2", mTokenPosition - mTokens.begin(), mTokens.Size()); + return format ("%1 / %2", m_tokenPosition - m_tokens.begin(), m_tokens.size()); }
--- a/src/Lexer.h Wed Feb 26 18:31:53 2014 +0200 +++ b/src/Lexer.h Mon Mar 03 01:04:16 2014 +0200 @@ -51,76 +51,76 @@ Lexer(); ~Lexer(); - void ProcessFile (String file_name); - bool Next (ETokenType req = TK_Any); - void MustGetNext (ETokenType tok); - void MustGetAnyOf (const List<ETokenType>& toks); - int GetOneSymbol (const StringList& syms); - void TokenMustBe (ETokenType tok); - bool PeekNext (TokenInfo* tk = null); - bool PeekNextType (ETokenType req); - String PeekNextString (int a = 1); - String DescribeCurrentPosition(); - String DescribeTokenPosition(); + void processFile (String fileName); + bool next (ETokenType req = TK_Any); + void mustGetNext (ETokenType tok); + void mustGetAnyOf (const List<ETokenType>& toks); + int getOneSymbol (const StringList& syms); + void tokenMustBe (ETokenType tok); + bool peekNext (TokenInfo* tk = null); + bool peekNextType (ETokenType req); + String peekNextString (int a = 1); + String describeCurrentPosition(); + String describeTokenPosition(); - static Lexer* GetCurrentLexer(); + static Lexer* getCurrentLexer(); - inline bool HasValidToken() const + inline bool hasValidToken() const { - return (mTokenPosition < mTokens.end() && mTokenPosition >= mTokens.begin()); + return (m_tokenPosition < m_tokens.end() && m_tokenPosition >= m_tokens.begin()); } - inline TokenInfo* Token() const + inline TokenInfo* token() const { - assert (HasValidToken() == true); - return &(*mTokenPosition); + assert (hasValidToken() == true); + return &(*m_tokenPosition); } - inline bool IsAtEnd() const + inline bool isAtEnd() const { - return mTokenPosition == mTokens.end(); + return m_tokenPosition == m_tokens.end(); } - inline ETokenType TokenType() const + inline ETokenType tokenType() const { - return Token()->type; + return token()->type; } - inline void Skip (int a = 1) + inline void skip (int a = 1) { - mTokenPosition += a; + m_tokenPosition += a; } - inline int Position() + inline int position() { - return mTokenPosition - mTokens.begin(); + return m_tokenPosition - m_tokens.begin(); } - inline void SetPosition (int pos) + inline void setPosition (int pos) { - mTokenPosition = mTokens.begin() + pos; + m_tokenPosition = m_tokens.begin() + pos; } // If @tok is given, describes the token. If not, describes @tok_type. - static inline String DescribeTokenType (ETokenType toktype) + static inline String describeTokenType (ETokenType toktype) { - return DescribeTokenPrivate (toktype, null); + return describeTokenPrivate (toktype, null); } - static inline String DescribeToken (TokenInfo* tok) + static inline String describeToken (TokenInfo* tok) { - return DescribeTokenPrivate (tok->type, tok); + return describeTokenPrivate (tok->type, tok); } private: - TokenList mTokens; - Iterator mTokenPosition; + TokenList m_tokens; + Iterator m_tokenPosition; // read a mandatory token from scanner - void MustGetFromScanner (LexerScanner& sc, ETokenType tt =TK_Any); - void CheckFileHeader (LexerScanner& sc); + void mustGetFromScanner (LexerScanner& sc, ETokenType tt =TK_Any); + void checkFileHeader (LexerScanner& sc); - static String DescribeTokenPrivate (ETokenType tok_type, TokenInfo* tok); + static String describeTokenPrivate (ETokenType tok_type, TokenInfo* tok); }; #endif // BOTC_LEXER_H
--- a/src/LexerScanner.cc Wed Feb 26 18:31:53 2014 +0200 +++ b/src/LexerScanner.cc Mon Mar 03 01:04:16 2014 +0200 @@ -116,16 +116,16 @@ // ============================================================================= // LexerScanner::LexerScanner (FILE* fp) : - mLine (1) + m_line (1) { long fsize, bytes; fseek (fp, 0l, SEEK_END); fsize = ftell (fp); rewind (fp); - mData = new char[fsize]; - mPosition = mLineBreakPosition = &mData[0]; - bytes = fread (mData, 1, fsize, fp); + m_data = new char[fsize]; + m_position = m_lineBreakPosition = &m_data[0]; + bytes = fread (m_data, 1, fsize, fp); assert (bytes >= fsize); } @@ -133,57 +133,57 @@ // LexerScanner::~LexerScanner() { - delete mData; + delete m_data; } // ============================================================================= // -bool LexerScanner::CheckString (const char* c, int flags) +bool LexerScanner::checkString (const char* c, int flags) { - bool r = strncmp (mPosition, c, strlen (c)) == 0; + bool r = strncmp (m_position, c, strlen (c)) == 0; // There is to be a non-symbol character after words - if (r && (flags & FCheckWord) && IsSymbolChar (mPosition[strlen (c)], true)) + if (r && (flags & FCheckWord) && isSymbolChar (m_position[strlen (c)], true)) r = false; // Advance the cursor unless we want to just peek if (r && !(flags & FCheckPeek)) - mPosition += strlen (c); + m_position += strlen (c); return r; } // ============================================================================= // -bool LexerScanner::GetNextToken() +bool LexerScanner::getNextToken() { - mTokenText = ""; + m_tokenText = ""; - while (isspace (*mPosition)) - Skip(); + while (isspace (*m_position)) + skip(); // Check for comments - if (strncmp (mPosition, "//", 2) == 0) + if (strncmp (m_position, "//", 2) == 0) { - mPosition += 2; + m_position += 2; - while (*mPosition != '\n') - Skip(); + while (*m_position != '\n') + skip(); - return GetNextToken(); + return getNextToken(); } - elif (strncmp (mPosition, "/*", 2) == 0) + elif (strncmp (m_position, "/*", 2) == 0) { - Skip (2); // skip the start symbols + skip (2); // skip the start symbols - while (strncmp (mPosition, "*/", 2) != 0) - Skip(); + while (strncmp (m_position, "*/", 2) != 0) + skip(); - Skip (2); // skip the end symbols - return GetNextToken(); + skip (2); // skip the end symbols + return getNextToken(); } - if (*mPosition == '\0') + if (*m_position == '\0') return false; // Check tokens @@ -194,100 +194,100 @@ if (i >= gFirstNamedToken) flags |= FCheckWord; - if (CheckString (gTokenStrings[i], flags)) + if (checkString (gTokenStrings[i], flags)) { - mTokenText = gTokenStrings[i]; - mTokenType = (ETokenType) i; + m_tokenText = gTokenStrings[i]; + m_tokenType = (ETokenType) i; return true; } } // Check and parse string - if (*mPosition == '\"') + if (*m_position == '\"') { - mPosition++; + m_position++; - while (*mPosition != '\"') + while (*m_position != '\"') { - if (!*mPosition) - Error ("unterminated string"); + if (!*m_position) + error ("unterminated string"); - if (CheckString ("\\n")) + if (checkString ("\\n")) { - mTokenText += '\n'; + m_tokenText += '\n'; continue; } - elif (CheckString ("\\t")) + elif (checkString ("\\t")) { - mTokenText += '\t'; + m_tokenText += '\t'; continue; } - elif (CheckString ("\\\"")) + elif (checkString ("\\\"")) { - mTokenText += '"'; + m_tokenText += '"'; continue; } - mTokenText += *mPosition++; + m_tokenText += *m_position++; } - mTokenType =TK_String; - Skip(); // skip the final quote + m_tokenType =TK_String; + skip(); // skip the final quote return true; } - if (isdigit (*mPosition)) + if (isdigit (*m_position)) { - while (isdigit (*mPosition)) - mTokenText += *mPosition++; + while (isdigit (*m_position)) + m_tokenText += *m_position++; - mTokenType =TK_Number; + m_tokenType =TK_Number; return true; } - if (IsSymbolChar (*mPosition, false)) + if (isSymbolChar (*m_position, false)) { - mTokenType =TK_Symbol; + m_tokenType =TK_Symbol; do { - if (!IsSymbolChar (*mPosition, true)) + if (!isSymbolChar (*m_position, true)) break; - mTokenText += *mPosition++; - } while (*mPosition != '\0'); + m_tokenText += *m_position++; + } while (*m_position != '\0'); return true; } - Error ("unknown character \"%1\"", *mPosition); + error ("unknown character \"%1\"", *m_position); return false; } // ============================================================================= // -void LexerScanner::Skip() +void LexerScanner::skip() { - if (*mPosition == '\n') + if (*m_position == '\n') { - mLine++; - mLineBreakPosition = mPosition; + m_line++; + m_lineBreakPosition = m_position; } - mPosition++; + m_position++; } // ============================================================================= // -void LexerScanner::Skip (int chars) +void LexerScanner::skip (int chars) { for (int i = 0; i < chars; ++i) - Skip(); + skip(); } // ============================================================================= // -String LexerScanner::GetTokenString (ETokenType a) +String LexerScanner::getTokenString (ETokenType a) { assert ((int) a <= gLastNamedToken); return gTokenStrings[a]; @@ -295,12 +295,12 @@ // ============================================================================= // -String LexerScanner::ReadLine() +String LexerScanner::readLine() { String line; - while (*mPosition != '\n') - line += *(mPosition++); + while (*m_position != '\n') + line += *(m_position++); return line; }
--- a/src/LexerScanner.h Wed Feb 26 18:31:53 2014 +0200 +++ b/src/LexerScanner.h Mon Mar 03 01:04:16 2014 +0200 @@ -34,11 +34,10 @@ class LexerScanner { - types: + public: struct PositionInfo { char* pos; - char* line_break_pos; int line; }; @@ -49,8 +48,7 @@ FCheckPeek = (1 << 1), // don't advance cursor }; - public: - static inline bool IsSymbolChar (char c, bool allownumbers) + static inline bool isSymbolChar (char c, bool allownumbers) { if (allownumbers && (c >= '0' && c <= '9')) return true; @@ -62,53 +60,53 @@ LexerScanner (FILE* fp); ~LexerScanner(); - bool GetNextToken(); - String ReadLine(); + bool getNextToken(); + String readLine(); - inline const String& GetTokenText() const + inline const String& getTokenText() const { - return mTokenText; + return m_tokenText; } - inline int GetLine() const + inline int getLine() const { - return mLine; + return m_line; } - inline int GetColumn() const + inline int getColumn() const { - return mPosition - mLineBreakPosition; + return m_position - m_lineBreakPosition; } - inline ETokenType GetTokenType() const + inline ETokenType getTokenType() const { - return mTokenType; + return m_tokenType; } - static String GetTokenString (ETokenType a); + static String getTokenString (ETokenType a); private: - char* mData; - char* mPosition; - char* mLineBreakPosition; - String mTokenText, - mLastToken; - ETokenType mTokenType; - int mLine; + char* m_data; + char* m_position; + char* m_lineBreakPosition; + String m_tokenText, + m_lastToken; + ETokenType m_tokenType; + int m_line; - bool CheckString (const char* c, int flags = 0); + bool checkString (const char* c, int flags = 0); // Yields a copy of the current position information. - PositionInfo GetPosition() const; + PositionInfo getPosition() const; // Sets the current position based on given data. - void SetPosition (const PositionInfo& a); + void setPosition (const PositionInfo& a); // Skips one character - void Skip(); + void skip(); // Skips many characters - void Skip (int chars); + void skip (int chars); }; #endif // BOTC_LEXER_SCANNER_H
--- a/src/Main.cc Wed Feb 26 18:31:53 2014 +0200 +++ b/src/Main.cc Mon Mar 03 01:04:16 2014 +0200 @@ -44,35 +44,35 @@ // I guess there should be a better way to do this. if (argc == 2 && String (argv[1]) == "-l") { - Print ("Begin list of commands:\n"); - Print ("------------------------------------------------------\n"); + print ("Begin list of commands:\n"); + print ("------------------------------------------------------\n"); BotscriptParser parser; - parser.SetReadOnly (true); - parser.ParseBotscript ("botc_defs.bts"); + parser.setReadOnly (true); + parser.parseBotscript ("botc_defs.bts"); - for (CommandInfo* comm : GetCommands()) - Print ("%1\n", comm->GetSignature()); + for (CommandInfo* comm : getCommands()) + print ("%1\n", comm->signature()); - Print ("------------------------------------------------------\n"); - Print ("End of command list\n"); + print ("------------------------------------------------------\n"); + print ("End of command list\n"); exit (0); } // Print header String header; String headerline; - header = Format (APPNAME " version %1", GetVersionString (true)); + header = format (APPNAME " version %1", versionString (true)); #ifdef DEBUG header += " (debug build)"; #endif - for (int i = 0; i < header.Length() / 2; ++i) + for (int i = 0; i < header.length() / 2; ++i) headerline += "-="; headerline += '-'; - Print ("%2\n\n%1\n\n%2\n\n", header, headerline); + print ("%2\n\n%1\n\n%2\n\n", header, headerline); if (argc < 2) { @@ -84,7 +84,7 @@ String outfile; if (argc < 3) - outfile = MakeObjectFileName (argv[1]); + outfile = makeObjectFileName (argv[1]); else outfile = argv[2]; @@ -92,21 +92,21 @@ BotscriptParser* parser = new BotscriptParser; // We're set, begin parsing :) - Print ("Parsing script...\n"); - parser->ParseBotscript (argv[1]); - Print ("Script parsed successfully.\n"); + print ("Parsing script...\n"); + parser->parseBotscript (argv[1]); + print ("Script parsed successfully.\n"); // Parse done, print statistics and write to file - int globalcount = parser->GetHighestVarIndex (true) + 1; - int statelocalcount = parser->GetHighestVarIndex (false) + 1; - int stringcount = CountStringsInTable(); - Print ("%1 / %2 strings\n", stringcount, gMaxStringlistSize); - Print ("%1 / %2 global variable indices\n", globalcount, gMaxGlobalVars); - Print ("%1 / %2 state variable indices\n", statelocalcount, gMaxGlobalVars); - Print ("%1 / %2 events\n", parser->GetNumEvents(), gMaxEvents); - Print ("%1 state%s1\n", parser->GetNumStates()); + int globalcount = parser->getHighestVarIndex (true) + 1; + int statelocalcount = parser->getHighestVarIndex (false) + 1; + int stringcount = countStringsInTable(); + print ("%1 / %2 strings\n", stringcount, gMaxStringlistSize); + print ("%1 / %2 global variable indices\n", globalcount, gMaxGlobalVars); + print ("%1 / %2 state variable indices\n", statelocalcount, gMaxGlobalVars); + print ("%1 / %2 events\n", parser->numEvents(), gMaxEvents); + print ("%1 state%s1\n", parser->numStates()); - parser->WriteToFile (outfile); + parser->writeToFile (outfile); delete parser; return 0; } @@ -121,13 +121,13 @@ // // Mutates given filename to an object filename // -String MakeObjectFileName (String s) +String makeObjectFileName (String s) { // Locate the extension and chop it out - int extdot = s.LastIndexOf ("."); + int extdot = s.lastIndexOf ("."); - if (extdot >= s.Length() - 4) - s -= (s.Length() - extdot); + if (extdot >= s.length() - 4) + s -= (s.length() - extdot); s += ".o"; return s; @@ -135,13 +135,13 @@ // ============================================================================ // -DataType GetTypeByName (String t) +DataType getTypeByName (String token) { - t = t.ToLowercase(); - return (t == "int") ? TYPE_Int : - (t == "str") ? TYPE_String : - (t == "void") ? TYPE_Void : - (t == "bool") ? TYPE_Bool : + token = token.toLowercase(); + return (token == "int") ? TYPE_Int : + (token == "str") ? TYPE_String : + (token == "void") ? TYPE_Void : + (token == "bool") ? TYPE_Bool : TYPE_Unknown; } @@ -150,7 +150,7 @@ // // Inverse operation - type name by value // -String DataTypeName (DataType type) +String dataTypeName (DataType type) { switch (type) { @@ -166,9 +166,9 @@ // ============================================================================= // -String MakeVersionString (int major, int minor, int patch) +String makeVersionString (int major, int minor, int patch) { - String ver = Format ("%1.%2", major, minor); + String ver = format ("%1.%2", major, minor); if (patch != 0) { @@ -181,13 +181,13 @@ // ============================================================================= // -String GetVersionString (bool longform) +String versionString (bool longform) { String tag (GIT_DESCRIPTION); String version = tag; - if (longform && tag.EndsWith ("-pre")) - version += "-" + String (GIT_HASH).Mid (0, 8); + if (longform && tag.endsWith ("-pre")) + version += "-" + String (GIT_HASH).mid (0, 8); return version; }
--- a/src/Main.h Wed Feb 26 18:31:53 2014 +0200 +++ b/src/Main.h Mon Mar 03 01:04:16 2014 +0200 @@ -41,11 +41,11 @@ #include "BotStuff.h" #include "Tokens.h" -String MakeObjectFileName (String s); -DataType GetTypeByName (String token); -String DataTypeName (DataType type); -String GetVersionString (bool longform); -String MakeVersionString (int major, int minor, int patch); +String makeObjectFileName (String s); +DataType getTypeByName (String token); +String dataTypeName (DataType type); +String versionString (bool longform); +String makeVersionString (int major, int minor, int patch); template<typename T> inline T max (T a, T b)
--- a/src/Parser.cc Wed Feb 26 18:31:53 2014 +0200 +++ b/src/Parser.cc Mon Mar 03 01:04:16 2014 +0200 @@ -35,47 +35,47 @@ #include "DataBuffer.h" #include "Expression.h" -#define SCOPE(n) (mScopeStack[mScopeCursor - n]) +#define SCOPE(n) (m_scopeStack[m_scopeCursor - n]) // ============================================================================ // BotscriptParser::BotscriptParser() : - mIsReadOnly (false), - mMainBuffer (new DataBuffer), - mOnEnterBuffer (new DataBuffer), - mMainLoopBuffer (new DataBuffer), - mLexer (new Lexer), - mNumStates (0), - mNumEvents (0), - mCurrentMode (PARSERMODE_TopLevel), - mStateSpawnDefined (false), - mGotMainLoop (false), - mScopeCursor (-1), - mCanElse (false), - mHighestGlobalVarIndex (0), - mHighestStateVarIndex (0) {} + m_isReadOnly (false), + m_mainBuffer (new DataBuffer), + m_onenterBuffer (new DataBuffer), + m_mainLoopBuffer (new DataBuffer), + m_lexer (new Lexer), + m_numStates (0), + m_numEvents (0), + m_currentMode (PARSERMODE_TopLevel), + m_isStateSpawnDefined (false), + m_gotMainLoop (false), + m_scopeCursor (-1), + m_isElseAllowed (false), + m_highestGlobalVarIndex (0), + m_highestStateVarIndex (0) {} // ============================================================================ // BotscriptParser::~BotscriptParser() { - delete mLexer; + delete m_lexer; } // ============================================================================ // -void BotscriptParser::CheckToplevel() +void BotscriptParser::checkToplevel() { - if (mCurrentMode != PARSERMODE_TopLevel) - Error ("%1-statements may only be defined at top level!", GetTokenString()); + if (m_currentMode != PARSERMODE_TopLevel) + error ("%1-statements may only be defined at top level!", getTokenString()); } // ============================================================================ // -void BotscriptParser::CheckNotToplevel() +void BotscriptParser::checkNotToplevel() { - if (mCurrentMode == PARSERMODE_TopLevel) - Error ("%1-statements must not be defined at top level!", GetTokenString()); + if (m_currentMode == PARSERMODE_TopLevel) + error ("%1-statements must not be defined at top level!", getTokenString()); } // ============================================================================ @@ -84,94 +84,94 @@ // and writes the data to the object file via Objwriter - which also takes care // of necessary buffering so stuff is written in the correct order. // -void BotscriptParser::ParseBotscript (String fileName) +void BotscriptParser::parseBotscript (String fileName) { // Lex and preprocess the file - mLexer->ProcessFile (fileName); - PushScope(); + m_lexer->processFile (fileName); + pushScope(); - while (mLexer->Next()) + while (m_lexer->next()) { // Check if else is potentically valid - if (TokenIs (TK_Else) && mCanElse == false) - Error ("else without preceding if"); + if (tokenIs (TK_Else) && m_isElseAllowed == false) + error ("else without preceding if"); - if (TokenIs (TK_Else) == false) - mCanElse = false; + if (tokenIs (TK_Else) == false) + m_isElseAllowed = false; - switch (mLexer->Token()->type) + switch (m_lexer->token()->type) { case TK_State: - ParseStateBlock(); + parseStateBlock(); break; case TK_Event: - ParseEventBlock(); + parseEventBlock(); break; case TK_Mainloop: - ParseMainloop(); + parseMainloop(); break; case TK_Onenter: case TK_Onexit: - ParseOnEnterExit(); + parseOnEnterExit(); break; case TK_Var: - ParseVar(); + parseVar(); break; case TK_If: - ParseIf(); + parseIf(); break; case TK_Else: - ParseElse(); + parseElse(); break; case TK_While: - ParseWhileBlock(); + parseWhileBlock(); break; case TK_For: - ParseForBlock(); + parseForBlock(); break; case TK_Do: - ParseDoBlock(); + parseDoBlock(); break; case TK_Switch: - ParseSwitchBlock(); + parseSwitchBlock(); break; case TK_Case: - ParseSwitchCase(); + parseSwitchCase(); break; case TK_Default: - ParseSwitchDefault(); + parseSwitchDefault(); break; case TK_Break: - ParseBreak(); + parseBreak(); break; case TK_Continue: - ParseContinue(); + parseContinue(); break; case TK_BraceEnd: - ParseBlockEnd(); + parseBlockEnd(); break; case TK_Eventdef: - ParseEventdef(); + parseEventdef(); break; case TK_Funcdef: - ParseFuncdef(); + parseFuncdef(); break; case TK_Semicolon: @@ -180,27 +180,27 @@ default: { // Check if it's a command - CommandInfo* comm = FindCommandByName (GetTokenString()); + CommandInfo* comm = findCommandByName (getTokenString()); if (comm) { - buffer()->MergeAndDestroy (ParseCommand (comm)); - mLexer->MustGetNext (TK_Semicolon); + currentBuffer()->mergeAndDestroy (parseCommand (comm)); + m_lexer->mustGetNext (TK_Semicolon); continue; } // If nothing else, parse it as a statement - mLexer->Skip (-1); - DataBuffer* b = ParseStatement(); + m_lexer->skip (-1); + DataBuffer* b = parseStatement(); if (b == false) { - mLexer->Next(); - Error ("unknown token `%1`", GetTokenString()); + m_lexer->next(); + error ("unknown token `%1`", getTokenString()); } - buffer()->MergeAndDestroy (b); - mLexer->MustGetNext (TK_Semicolon); + currentBuffer()->mergeAndDestroy (b); + m_lexer->mustGetNext (TK_Semicolon); break; } } @@ -208,131 +208,131 @@ // =============================================================================== // Script file ended. Do some last checks and write the last things to main buffer - if (mCurrentMode != PARSERMODE_TopLevel) - Error ("script did not end at top level; a `}` is missing somewhere"); + if (m_currentMode != PARSERMODE_TopLevel) + error ("script did not end at top level; a `}` is missing somewhere"); - if (IsReadOnly() == false) + if (isReadOnly() == false) { // stateSpawn must be defined! - if (mStateSpawnDefined == false) - Error ("script must have a state named `stateSpawn`!"); + if (m_isStateSpawnDefined == false) + error ("script must have a state named `stateSpawn`!"); // Dump the last state's onenter and mainloop writeMemberBuffers(); // String table - WriteStringTable(); + writeStringTable(); } } // ============================================================================ // -void BotscriptParser::ParseStateBlock() +void BotscriptParser::parseStateBlock() { - CheckToplevel(); - mLexer->MustGetNext (TK_String); - String statename = GetTokenString(); + checkToplevel(); + m_lexer->mustGetNext (TK_String); + String statename = getTokenString(); // State name must be a word. - if (statename.FirstIndexOf (" ") != -1) - Error ("state name must be a single word, got `%1`", statename); + if (statename.firstIndexOf (" ") != -1) + error ("state name must be a single word, got `%1`", statename); // stateSpawn is special - it *must* be defined. If we // encountered it, then mark down that we have it. - if (statename.ToLowercase() == "statespawn") - mStateSpawnDefined = true; + if (statename.toLowercase() == "statespawn") + m_isStateSpawnDefined = true; // Must end in a colon - mLexer->MustGetNext (TK_Colon); + m_lexer->mustGetNext (TK_Colon); // write the previous state's onenter and // mainloop buffers to file now - if (mCurrentState.IsEmpty() == false) + if (m_currentState.isEmpty() == false) writeMemberBuffers(); - buffer()->WriteDWord (DH_StateName); - buffer()->WriteString (statename); - buffer()->WriteDWord (DH_StateIndex); - buffer()->WriteDWord (mNumStates); + currentBuffer()->writeDWord (DH_StateName); + currentBuffer()->writeString (statename); + currentBuffer()->writeDWord (DH_StateIndex); + currentBuffer()->writeDWord (m_numStates); - mNumStates++; - mCurrentState = statename; - mGotMainLoop = false; + m_numStates++; + m_currentState = statename; + m_gotMainLoop = false; } // ============================================================================ // -void BotscriptParser::ParseEventBlock() +void BotscriptParser::parseEventBlock() { - CheckToplevel(); - mLexer->MustGetNext (TK_String); + checkToplevel(); + m_lexer->mustGetNext (TK_String); - EventDefinition* e = FindEventByName (GetTokenString()); + EventDefinition* e = findEventByName (getTokenString()); if (e == null) - Error ("bad event, got `%1`\n", GetTokenString()); + error ("bad event, got `%1`\n", getTokenString()); - mLexer->MustGetNext (TK_BraceStart); - mCurrentMode = PARSERMODE_Event; - buffer()->WriteDWord (DH_Event); - buffer()->WriteDWord (e->number); - mNumEvents++; + m_lexer->mustGetNext (TK_BraceStart); + m_currentMode = PARSERMODE_Event; + currentBuffer()->writeDWord (DH_Event); + currentBuffer()->writeDWord (e->number); + m_numEvents++; } // ============================================================================ // -void BotscriptParser::ParseMainloop() +void BotscriptParser::parseMainloop() { - CheckToplevel(); - mLexer->MustGetNext (TK_BraceStart); + checkToplevel(); + m_lexer->mustGetNext (TK_BraceStart); - mCurrentMode = PARSERMODE_MainLoop; - mMainLoopBuffer->WriteDWord (DH_MainLoop); + m_currentMode = PARSERMODE_MainLoop; + m_mainLoopBuffer->writeDWord (DH_MainLoop); } // ============================================================================ // -void BotscriptParser::ParseOnEnterExit() +void BotscriptParser::parseOnEnterExit() { - CheckToplevel(); - bool onenter = (TokenIs (TK_Onenter)); - mLexer->MustGetNext (TK_BraceStart); + checkToplevel(); + bool onenter = (tokenIs (TK_Onenter)); + m_lexer->mustGetNext (TK_BraceStart); - mCurrentMode = onenter ? PARSERMODE_Onenter : PARSERMODE_Onexit; - buffer()->WriteDWord (onenter ? DH_OnEnter : DH_OnExit); + m_currentMode = onenter ? PARSERMODE_Onenter : PARSERMODE_Onexit; + currentBuffer()->writeDWord (onenter ? DH_OnEnter : DH_OnExit); } // ============================================================================ // -void BotscriptParser::ParseVar() +void BotscriptParser::parseVar() { Variable* var = new Variable; - var->origin = mLexer->DescribeCurrentPosition(); + var->origin = m_lexer->describeCurrentPosition(); var->isarray = false; - const bool isconst = mLexer->Next (TK_Const); - mLexer->MustGetAnyOf ({TK_Int,TK_Str,TK_Void}); + const bool isconst = m_lexer->next (TK_Const); + m_lexer->mustGetAnyOf ({TK_Int,TK_Str,TK_Void}); - DataType vartype = (TokenIs (TK_Int)) ? TYPE_Int : - (TokenIs (TK_Str)) ? TYPE_String : + DataType vartype = (tokenIs (TK_Int)) ? TYPE_Int : + (tokenIs (TK_Str)) ? TYPE_String : TYPE_Bool; - mLexer->MustGetNext (TK_DollarSign); - mLexer->MustGetNext (TK_Symbol); - String name = GetTokenString(); + m_lexer->mustGetNext (TK_DollarSign); + m_lexer->mustGetNext (TK_Symbol); + String name = getTokenString(); - if (mLexer->Next (TK_BracketStart)) + if (m_lexer->next (TK_BracketStart)) { - mLexer->MustGetNext (TK_BracketEnd); + m_lexer->mustGetNext (TK_BracketEnd); var->isarray = true; if (isconst) - Error ("arrays cannot be const"); + error ("arrays cannot be const"); } for (Variable* var : SCOPE(0).globalVariables + SCOPE(0).localVariables) { if (var->name == name) - Error ("Variable $%1 is already declared on this scope; declared at %2", + error ("Variable $%1 is already declared on this scope; declared at %2", var->name, var->origin); } @@ -346,20 +346,20 @@ } else { - mLexer->MustGetNext (TK_Assign); - Expression expr (this, mLexer, vartype); + m_lexer->mustGetNext (TK_Assign); + Expression expr (this, m_lexer, vartype); // If the expression was constexpr, we know its value and thus // can store it in the variable. - if (expr.Result()->IsConstexpr()) + if (expr.getResult()->isConstexpr()) { var->writelevel = WRITE_Constexpr; - var->value = expr.Result()->Value(); + var->value = expr.getResult()->value(); } else { // TODO: might need a VM-wise oninit for this... - Error ("const variables must be constexpr"); + error ("const variables must be constexpr"); } } @@ -368,51 +368,51 @@ // so they need no index. if (var->writelevel != WRITE_Constexpr) { - bool isglobal = IsInGlobalState(); + bool isglobal = isInGlobalState(); var->index = isglobal ? SCOPE(0).globalVarIndexBase++ : SCOPE(0).localVarIndexBase++; if ((isglobal == true && var->index >= gMaxGlobalVars) || (isglobal == false && var->index >= gMaxStateVars)) { - Error ("too many %1 variables", isglobal ? "global" : "state-local"); + error ("too many %1 variables", isglobal ? "global" : "state-local"); } } - if (IsInGlobalState()) + if (isInGlobalState()) SCOPE(0).globalVariables << var; else SCOPE(0).localVariables << var; - SuggestHighestVarIndex (IsInGlobalState(), var->index); - mLexer->MustGetNext (TK_Semicolon); - Print ("Declared %3 variable #%1 $%2\n", var->index, var->name, IsInGlobalState() ? "global" : "state-local"); + suggestHighestVarIndex (isInGlobalState(), var->index); + m_lexer->mustGetNext (TK_Semicolon); + print ("Declared %3 variable #%1 $%2\n", var->index, var->name, isInGlobalState() ? "global" : "state-local"); } // ============================================================================ // -void BotscriptParser::ParseIf() +void BotscriptParser::parseIf() { - CheckNotToplevel(); - PushScope(); + checkNotToplevel(); + pushScope(); // Condition - mLexer->MustGetNext (TK_ParenStart); + m_lexer->mustGetNext (TK_ParenStart); // Read the expression and write it. - DataBuffer* c = ParseExpression (TYPE_Int); - buffer()->MergeAndDestroy (c); + DataBuffer* c = parseExpression (TYPE_Int); + currentBuffer()->mergeAndDestroy (c); - mLexer->MustGetNext (TK_ParenEnd); - mLexer->MustGetNext (TK_BraceStart); + m_lexer->mustGetNext (TK_ParenEnd); + m_lexer->mustGetNext (TK_BraceStart); // Add a mark - to here temporarily - and add a reference to it. // Upon a closing brace, the mark will be adjusted. - ByteMark* mark = buffer()->AddMark (""); + ByteMark* mark = currentBuffer()->addMark (""); // Use DH_IfNotGoto - if the expression is not true, we goto the mark // we just defined - and this mark will be at the end of the scope block. - buffer()->WriteDWord (DH_IfNotGoto); - buffer()->AddReference (mark); + currentBuffer()->writeDWord (DH_IfNotGoto); + currentBuffer()->addReference (mark); // Store it SCOPE (0).mark1 = mark; @@ -421,54 +421,54 @@ // ============================================================================ // -void BotscriptParser::ParseElse() +void BotscriptParser::parseElse() { - CheckNotToplevel(); - mLexer->MustGetNext (TK_BraceStart); - PushScope (eNoReset); + checkNotToplevel(); + m_lexer->mustGetNext (TK_BraceStart); + pushScope (eNoReset); if (SCOPE (0).type != SCOPE_If) - Error ("else without preceding if"); + error ("else without preceding if"); // write down to jump to the end of the else statement // Otherwise we have fall-throughs - SCOPE (0).mark2 = buffer()->AddMark (""); + SCOPE (0).mark2 = currentBuffer()->addMark (""); // Instruction to jump to the end after if block is complete - buffer()->WriteDWord (DH_Goto); - buffer()->AddReference (SCOPE (0).mark2); + currentBuffer()->writeDWord (DH_Goto); + currentBuffer()->addReference (SCOPE (0).mark2); // Move the ifnot mark here and set type to else - buffer()->AdjustMark (SCOPE (0).mark1); + currentBuffer()->adjustMark (SCOPE (0).mark1); SCOPE (0).type = SCOPE_Else; } // ============================================================================ // -void BotscriptParser::ParseWhileBlock() +void BotscriptParser::parseWhileBlock() { - CheckNotToplevel(); - PushScope(); + checkNotToplevel(); + pushScope(); // While loops need two marks - one at the start of the loop and one at the // end. The condition is checked at the very start of the loop, if it fails, // we use goto to skip to the end of the loop. At the end, we loop back to // the beginning with a go-to statement. - ByteMark* mark1 = buffer()->AddMark (""); // start - ByteMark* mark2 = buffer()->AddMark (""); // end + ByteMark* mark1 = currentBuffer()->addMark (""); // start + ByteMark* mark2 = currentBuffer()->addMark (""); // end // Condition - mLexer->MustGetNext (TK_ParenStart); - DataBuffer* expr = ParseExpression (TYPE_Int); - mLexer->MustGetNext (TK_ParenEnd); - mLexer->MustGetNext (TK_BraceStart); + m_lexer->mustGetNext (TK_ParenStart); + DataBuffer* expr = parseExpression (TYPE_Int); + m_lexer->mustGetNext (TK_ParenEnd); + m_lexer->mustGetNext (TK_BraceStart); // write condition - buffer()->MergeAndDestroy (expr); + currentBuffer()->mergeAndDestroy (expr); // Instruction to go to the end if it fails - buffer()->WriteDWord (DH_IfNotGoto); - buffer()->AddReference (mark2); + currentBuffer()->writeDWord (DH_IfNotGoto); + currentBuffer()->addReference (mark2); // Store the needed stuff SCOPE (0).mark1 = mark1; @@ -478,48 +478,48 @@ // ============================================================================ // -void BotscriptParser::ParseForBlock() +void BotscriptParser::parseForBlock() { - CheckNotToplevel(); - PushScope(); + checkNotToplevel(); + pushScope(); // Initializer - mLexer->MustGetNext (TK_ParenStart); - DataBuffer* init = ParseStatement(); + m_lexer->mustGetNext (TK_ParenStart); + DataBuffer* init = parseStatement(); if (init == null) - Error ("bad statement for initializer of for"); + error ("bad statement for initializer of for"); - mLexer->MustGetNext (TK_Semicolon); + m_lexer->mustGetNext (TK_Semicolon); // Condition - DataBuffer* cond = ParseExpression (TYPE_Int); + DataBuffer* cond = parseExpression (TYPE_Int); if (cond == null) - Error ("bad statement for condition of for"); + error ("bad statement for condition of for"); - mLexer->MustGetNext (TK_Semicolon); + m_lexer->mustGetNext (TK_Semicolon); // Incrementor - DataBuffer* incr = ParseStatement(); + DataBuffer* incr = parseStatement(); if (incr == null) - Error ("bad statement for incrementor of for"); + error ("bad statement for incrementor of for"); - mLexer->MustGetNext (TK_ParenEnd); - mLexer->MustGetNext (TK_BraceStart); + m_lexer->mustGetNext (TK_ParenEnd); + m_lexer->mustGetNext (TK_BraceStart); // First, write out the initializer - buffer()->MergeAndDestroy (init); + currentBuffer()->mergeAndDestroy (init); // Init two marks - ByteMark* mark1 = buffer()->AddMark (""); - ByteMark* mark2 = buffer()->AddMark (""); + ByteMark* mark1 = currentBuffer()->addMark (""); + ByteMark* mark2 = currentBuffer()->addMark (""); // Add the condition - buffer()->MergeAndDestroy (cond); - buffer()->WriteDWord (DH_IfNotGoto); - buffer()->AddReference (mark2); + currentBuffer()->mergeAndDestroy (cond); + currentBuffer()->writeDWord (DH_IfNotGoto); + currentBuffer()->addReference (mark2); // Store the marks and incrementor SCOPE (0).mark1 = mark1; @@ -530,18 +530,18 @@ // ============================================================================ // -void BotscriptParser::ParseDoBlock() +void BotscriptParser::parseDoBlock() { - CheckNotToplevel(); - PushScope(); - mLexer->MustGetNext (TK_BraceStart); - SCOPE (0).mark1 = buffer()->AddMark (""); + checkNotToplevel(); + pushScope(); + m_lexer->mustGetNext (TK_BraceStart); + SCOPE (0).mark1 = currentBuffer()->addMark (""); SCOPE (0).type = SCOPE_Do; } // ============================================================================ // -void BotscriptParser::ParseSwitchBlock() +void BotscriptParser::parseSwitchBlock() { // This gets a bit tricky. switch is structured in the // bytecode followingly: @@ -556,34 +556,34 @@ // casemark3: ... // mark1: // end mark - CheckNotToplevel(); - PushScope(); - mLexer->MustGetNext (TK_ParenStart); - buffer()->MergeAndDestroy (ParseExpression (TYPE_Int)); - mLexer->MustGetNext (TK_ParenEnd); - mLexer->MustGetNext (TK_BraceStart); + checkNotToplevel(); + pushScope(); + m_lexer->mustGetNext (TK_ParenStart); + currentBuffer()->mergeAndDestroy (parseExpression (TYPE_Int)); + m_lexer->mustGetNext (TK_ParenEnd); + m_lexer->mustGetNext (TK_BraceStart); SCOPE (0).type = SCOPE_Switch; - SCOPE (0).mark1 = buffer()->AddMark (""); // end mark + SCOPE (0).mark1 = currentBuffer()->addMark (""); // end mark SCOPE (0).buffer1 = null; // default header } // ============================================================================ // -void BotscriptParser::ParseSwitchCase() +void BotscriptParser::parseSwitchCase() { // case is only allowed inside switch if (SCOPE (0).type != SCOPE_Switch) - Error ("case label outside switch"); + error ("case label outside switch"); // Get a literal value for the case block. Zandronum does not support // expressions here. - mLexer->MustGetNext (TK_Number); - int num = mLexer->Token()->text.ToLong(); - mLexer->MustGetNext (TK_Colon); + m_lexer->mustGetNext (TK_Number); + int num = m_lexer->token()->text.toLong(); + m_lexer->mustGetNext (TK_Colon); for (const CaseInfo& info : SCOPE(0).cases) if (info.number == num) - Error ("multiple case %1 labels in one switch", num); + error ("multiple case %1 labels in one switch", num); // Write down the expression and case-go-to. This builds // the case tree. The closing event will write the actual @@ -595,24 +595,24 @@ // // We null the switch buffer for the case-go-to statement as // we want it all under the switch, not into the case-buffers. - mSwitchBuffer = null; - buffer()->WriteDWord (DH_CaseGoto); - buffer()->WriteDWord (num); - AddSwitchCase (null); + m_switchBuffer = null; + currentBuffer()->writeDWord (DH_CaseGoto); + currentBuffer()->writeDWord (num); + addSwitchCase (null); SCOPE (0).casecursor->number = num; } // ============================================================================ // -void BotscriptParser::ParseSwitchDefault() +void BotscriptParser::parseSwitchDefault() { if (SCOPE (0).type != SCOPE_Switch) - Error ("default label outside switch"); + error ("default label outside switch"); if (SCOPE (0).buffer1 != null) - Error ("multiple default labels in one switch"); + error ("multiple default labels in one switch"); - mLexer->MustGetNext (TK_Colon); + m_lexer->mustGetNext (TK_Colon); // The default header is buffered into buffer1, since // it has to be the last of the case headers @@ -623,19 +623,19 @@ // a default. DataBuffer* buf = new DataBuffer; SCOPE (0).buffer1 = buf; - buf->WriteDWord (DH_Drop); - buf->WriteDWord (DH_Goto); - AddSwitchCase (buf); + buf->writeDWord (DH_Drop); + buf->writeDWord (DH_Goto); + addSwitchCase (buf); } // ============================================================================ // -void BotscriptParser::ParseBreak() +void BotscriptParser::parseBreak() { - if (mScopeCursor == 0) - Error ("unexpected `break`"); + if (m_scopeCursor == 0) + error ("unexpected `break`"); - buffer()->WriteDWord (DH_Goto); + currentBuffer()->writeDWord (DH_Goto); // switch and if use mark1 for the closing point, // for and while use mark2. @@ -644,44 +644,44 @@ case SCOPE_If: case SCOPE_Switch: { - buffer()->AddReference (SCOPE (0).mark1); + currentBuffer()->addReference (SCOPE (0).mark1); } break; case SCOPE_For: case SCOPE_While: { - buffer()->AddReference (SCOPE (0).mark2); + currentBuffer()->addReference (SCOPE (0).mark2); } break; default: { - Error ("unexpected `break`"); + error ("unexpected `break`"); } break; } - mLexer->MustGetNext (TK_Semicolon); + m_lexer->mustGetNext (TK_Semicolon); } // ============================================================================ // -void BotscriptParser::ParseContinue() +void BotscriptParser::parseContinue() { - mLexer->MustGetNext (TK_Semicolon); + m_lexer->mustGetNext (TK_Semicolon); int curs; bool found = false; // Fall through the scope until we find a loop block - for (curs = mScopeCursor; curs > 0 && !found; curs--) + for (curs = m_scopeCursor; curs > 0 && !found; curs--) { - switch (mScopeStack[curs].type) + switch (m_scopeStack[curs].type) { case SCOPE_For: case SCOPE_While: case SCOPE_Do: { - buffer()->WriteDWord (DH_Goto); - buffer()->AddReference (mScopeStack[curs].mark1); + currentBuffer()->writeDWord (DH_Goto); + currentBuffer()->addReference (m_scopeStack[curs].mark1); found = true; } break; @@ -692,26 +692,26 @@ // No loop blocks if (found == false) - Error ("`continue`-statement not inside a loop"); + error ("`continue`-statement not inside a loop"); } // ============================================================================ // -void BotscriptParser::ParseBlockEnd() +void BotscriptParser::parseBlockEnd() { // Closing brace // If we're in the block stack, we're descending down from it now - if (mScopeCursor > 0) + if (m_scopeCursor > 0) { switch (SCOPE (0).type) { case SCOPE_If: { // Adjust the closing mark. - buffer()->AdjustMark (SCOPE (0).mark1); + currentBuffer()->adjustMark (SCOPE (0).mark1); // We're returning from `if`, thus `else` follow - mCanElse = true; + m_isElseAllowed = true; break; } @@ -719,36 +719,36 @@ { // else instead uses mark1 for itself (so if expression // fails, jump to else), mark2 means end of else - buffer()->AdjustMark (SCOPE (0).mark2); + currentBuffer()->adjustMark (SCOPE (0).mark2); break; } case SCOPE_For: { // write the incrementor at the end of the loop block - buffer()->MergeAndDestroy (SCOPE (0).buffer1); + currentBuffer()->mergeAndDestroy (SCOPE (0).buffer1); } case SCOPE_While: { // write down the instruction to go back to the start of the loop - buffer()->WriteDWord (DH_Goto); - buffer()->AddReference (SCOPE (0).mark1); + currentBuffer()->writeDWord (DH_Goto); + currentBuffer()->addReference (SCOPE (0).mark1); // Move the closing mark here since we're at the end of the while loop - buffer()->AdjustMark (SCOPE (0).mark2); + currentBuffer()->adjustMark (SCOPE (0).mark2); break; } case SCOPE_Do: { - mLexer->MustGetNext (TK_While); - mLexer->MustGetNext (TK_ParenStart); - DataBuffer* expr = ParseExpression (TYPE_Int); - mLexer->MustGetNext (TK_ParenEnd); - mLexer->MustGetNext (TK_Semicolon); + m_lexer->mustGetNext (TK_While); + m_lexer->mustGetNext (TK_ParenStart); + DataBuffer* expr = parseExpression (TYPE_Int); + m_lexer->mustGetNext (TK_ParenEnd); + m_lexer->mustGetNext (TK_Semicolon); // If the condition runs true, go back to the start. - buffer()->MergeAndDestroy (expr); - buffer()->WriteDWord (DH_IfGoto); - buffer()->AddReference (SCOPE (0).mark1); + currentBuffer()->mergeAndDestroy (expr); + currentBuffer()->writeDWord (DH_IfGoto); + currentBuffer()->addReference (SCOPE (0).mark1); break; } @@ -757,32 +757,32 @@ // Switch closes. Move down to the record buffer of // the lower block. if (SCOPE (1).casecursor != SCOPE (1).cases.begin() - 1) - mSwitchBuffer = SCOPE (1).casecursor->data; + m_switchBuffer = SCOPE (1).casecursor->data; else - mSwitchBuffer = null; + m_switchBuffer = null; // If there was a default in the switch, write its header down now. // If not, write instruction to jump to the end of switch after // the headers (thus won't fall-through if no case matched) if (SCOPE (0).buffer1) - buffer()->MergeAndDestroy (SCOPE (0).buffer1); + currentBuffer()->mergeAndDestroy (SCOPE (0).buffer1); else { - buffer()->WriteDWord (DH_Drop); - buffer()->WriteDWord (DH_Goto); - buffer()->AddReference (SCOPE (0).mark1); + currentBuffer()->writeDWord (DH_Drop); + currentBuffer()->writeDWord (DH_Goto); + currentBuffer()->addReference (SCOPE (0).mark1); } // Go through all of the buffers we // recorded down and write them. for (CaseInfo& info : SCOPE (0).cases) { - buffer()->AdjustMark (info.mark); - buffer()->MergeAndDestroy (info.data); + currentBuffer()->adjustMark (info.mark); + currentBuffer()->mergeAndDestroy (info.data); } // Move the closing mark here - buffer()->AdjustMark (SCOPE (0).mark1); + currentBuffer()->adjustMark (SCOPE (0).mark1); break; } @@ -791,103 +791,103 @@ } // Descend down the stack - mScopeCursor--; + m_scopeCursor--; return; } - int dataheader = (mCurrentMode == PARSERMODE_Event) ? DH_EndEvent : - (mCurrentMode == PARSERMODE_MainLoop) ? DH_EndMainLoop : - (mCurrentMode == PARSERMODE_Onenter) ? DH_EndOnEnter : - (mCurrentMode == PARSERMODE_Onexit) ? DH_EndOnExit : -1; + int dataheader = (m_currentMode == PARSERMODE_Event) ? DH_EndEvent : + (m_currentMode == PARSERMODE_MainLoop) ? DH_EndMainLoop : + (m_currentMode == PARSERMODE_Onenter) ? DH_EndOnEnter : + (m_currentMode == PARSERMODE_Onexit) ? DH_EndOnExit : -1; if (dataheader == -1) - Error ("unexpected `}`"); + error ("unexpected `}`"); // Data header must be written before mode is changed because // onenter and mainloop go into special buffers, and we want // the closing data headers into said buffers too. - buffer()->WriteDWord (dataheader); - mCurrentMode = PARSERMODE_TopLevel; - mLexer->Next (TK_Semicolon); + currentBuffer()->writeDWord (dataheader); + m_currentMode = PARSERMODE_TopLevel; + m_lexer->next (TK_Semicolon); } // ============================================================================= // -void BotscriptParser::ParseEventdef() +void BotscriptParser::parseEventdef() { EventDefinition* e = new EventDefinition; - mLexer->MustGetNext (TK_Number); - e->number = GetTokenString().ToLong(); - mLexer->MustGetNext (TK_Colon); - mLexer->MustGetNext (TK_Symbol); - e->name = mLexer->Token()->text; - mLexer->MustGetNext (TK_ParenStart); - mLexer->MustGetNext (TK_ParenEnd); - mLexer->MustGetNext (TK_Semicolon); - AddEvent (e); + m_lexer->mustGetNext (TK_Number); + e->number = getTokenString().toLong(); + m_lexer->mustGetNext (TK_Colon); + m_lexer->mustGetNext (TK_Symbol); + e->name = m_lexer->token()->text; + m_lexer->mustGetNext (TK_ParenStart); + m_lexer->mustGetNext (TK_ParenEnd); + m_lexer->mustGetNext (TK_Semicolon); + addEvent (e); } // ============================================================================= // -void BotscriptParser::ParseFuncdef() +void BotscriptParser::parseFuncdef() { CommandInfo* comm = new CommandInfo; - comm->origin = mLexer->DescribeCurrentPosition(); + comm->origin = m_lexer->describeCurrentPosition(); // Return value - mLexer->MustGetAnyOf ({TK_Int,TK_Void,TK_Bool,TK_Str}); - comm->returnvalue = GetTypeByName (mLexer->Token()->text); // TODO + m_lexer->mustGetAnyOf ({TK_Int,TK_Void,TK_Bool,TK_Str}); + comm->returnvalue = getTypeByName (m_lexer->token()->text); // TODO assert (comm->returnvalue != -1); // Number - mLexer->MustGetNext (TK_Number); - comm->number = mLexer->Token()->text.ToLong(); - mLexer->MustGetNext (TK_Colon); + m_lexer->mustGetNext (TK_Number); + comm->number = m_lexer->token()->text.toLong(); + m_lexer->mustGetNext (TK_Colon); // Name - mLexer->MustGetNext (TK_Symbol); - comm->name = mLexer->Token()->text; + m_lexer->mustGetNext (TK_Symbol); + comm->name = m_lexer->token()->text; // Arguments - mLexer->MustGetNext (TK_ParenStart); + m_lexer->mustGetNext (TK_ParenStart); comm->minargs = 0; - while (mLexer->PeekNextType (TK_ParenEnd) == false) + while (m_lexer->peekNextType (TK_ParenEnd) == false) { - if (comm->args.IsEmpty() == false) - mLexer->MustGetNext (TK_Comma); + if (comm->args.isEmpty() == false) + m_lexer->mustGetNext (TK_Comma); CommandArgument arg; - mLexer->MustGetAnyOf ({TK_Int,TK_Bool,TK_Str}); - DataType type = GetTypeByName (mLexer->Token()->text); // TODO + m_lexer->mustGetAnyOf ({TK_Int,TK_Bool,TK_Str}); + DataType type = getTypeByName (m_lexer->token()->text); // TODO assert (type != -1 && type != TYPE_Void); arg.type = type; - mLexer->MustGetNext (TK_Symbol); - arg.name = mLexer->Token()->text; + m_lexer->mustGetNext (TK_Symbol); + arg.name = m_lexer->token()->text; // If this is an optional parameter, we need the default value. - if (comm->minargs < comm->args.Size() || mLexer->PeekNextType (TK_Assign)) + if (comm->minargs < comm->args.size() || m_lexer->peekNextType (TK_Assign)) { - mLexer->MustGetNext (TK_Assign); + m_lexer->mustGetNext (TK_Assign); switch (type) { case TYPE_Int: case TYPE_Bool: - mLexer->MustGetNext (TK_Number); + m_lexer->mustGetNext (TK_Number); break; case TYPE_String: - Error ("string arguments cannot have default values"); + error ("string arguments cannot have default values"); case TYPE_Unknown: case TYPE_Void: break; } - arg.defvalue = mLexer->Token()->text.ToLong(); + arg.defvalue = m_lexer->token()->text.toLong(); } else comm->minargs++; @@ -895,60 +895,60 @@ comm->args << arg; } - mLexer->MustGetNext (TK_ParenEnd); - mLexer->MustGetNext (TK_Semicolon); - AddCommandDefinition (comm); + m_lexer->mustGetNext (TK_ParenEnd); + m_lexer->mustGetNext (TK_Semicolon); + addCommandDefinition (comm); } // ============================================================================ // Parses a command call -DataBuffer* BotscriptParser::ParseCommand (CommandInfo* comm) +DataBuffer* BotscriptParser::parseCommand (CommandInfo* comm) { DataBuffer* r = new DataBuffer (64); - if (mCurrentMode == PARSERMODE_TopLevel && comm->returnvalue == TYPE_Void) - Error ("command call at top level"); + if (m_currentMode == PARSERMODE_TopLevel && comm->returnvalue == TYPE_Void) + error ("command call at top level"); - mLexer->MustGetNext (TK_ParenStart); - mLexer->MustGetNext (TK_Any); + m_lexer->mustGetNext (TK_ParenStart); + m_lexer->mustGetNext (TK_Any); int curarg = 0; for (;;) { - if (TokenIs (TK_ParenEnd)) + if (tokenIs (TK_ParenEnd)) { if (curarg < comm->minargs) - Error ("too few arguments passed to %1\n\tusage is: %2", - comm->name, comm->GetSignature()); + error ("too few arguments passed to %1\n\tusage is: %2", + comm->name, comm->signature()); break; } - if (curarg >= comm->args.Size()) - Error ("too many arguments (%3) passed to %1\n\tusage is: %2", - comm->name, comm->GetSignature()); + if (curarg >= comm->args.size()) + error ("too many arguments (%3) passed to %1\n\tusage is: %2", + comm->name, comm->signature()); - r->MergeAndDestroy (ParseExpression (comm->args[curarg].type, true)); - mLexer->MustGetNext (TK_Any); + r->mergeAndDestroy (parseExpression (comm->args[curarg].type, true)); + m_lexer->mustGetNext (TK_Any); if (curarg < comm->minargs - 1) { - mLexer->TokenMustBe (TK_Comma); - mLexer->MustGetNext (TK_Any); + m_lexer->tokenMustBe (TK_Comma); + m_lexer->mustGetNext (TK_Any); } - else if (curarg < comm->args.Size() - 1) + else if (curarg < comm->args.size() - 1) { // Can continue, but can terminate as well. - if (TokenIs (TK_ParenEnd)) + if (tokenIs (TK_ParenEnd)) { curarg++; break; } else { - mLexer->TokenMustBe (TK_Comma); - mLexer->MustGetNext (TK_Any); + m_lexer->tokenMustBe (TK_Comma); + m_lexer->mustGetNext (TK_Any); } } @@ -956,35 +956,35 @@ } // If the script skipped any optional arguments, fill in defaults. - while (curarg < comm->args.Size()) + while (curarg < comm->args.size()) { - r->WriteDWord (DH_PushNumber); - r->WriteDWord (comm->args[curarg].defvalue); + r->writeDWord (DH_PushNumber); + r->writeDWord (comm->args[curarg].defvalue); curarg++; } - r->WriteDWord (DH_Command); - r->WriteDWord (comm->number); - r->WriteDWord (comm->args.Size()); + r->writeDWord (DH_Command); + r->writeDWord (comm->number); + r->writeDWord (comm->args.size()); return r; } // ============================================================================ // -String BotscriptParser::ParseFloat() +String BotscriptParser::parseFloat() { - mLexer->TokenMustBe (TK_Number); - String floatstring = GetTokenString(); + m_lexer->tokenMustBe (TK_Number); + String floatstring = getTokenString(); Lexer::TokenInfo tok; // Go after the decimal point - if (mLexer->PeekNext (&tok) && tok.type ==TK_Dot) + if (m_lexer->peekNext (&tok) && tok.type ==TK_Dot) { - mLexer->Skip(); - mLexer->MustGetNext (TK_Number); + m_lexer->skip(); + m_lexer->mustGetNext (TK_Number); floatstring += "."; - floatstring += GetTokenString(); + floatstring += getTokenString(); } return floatstring; @@ -994,7 +994,7 @@ // // Parses an assignment operator. // -AssignmentOperator BotscriptParser::ParseAssignmentOperator() +AssignmentOperator BotscriptParser::parseAssignmentOperator() { const List<ETokenType> tokens = { @@ -1008,9 +1008,9 @@ TK_DoubleMinus, }; - mLexer->MustGetAnyOf (tokens); + m_lexer->mustGetAnyOf (tokens); - switch (mLexer->TokenType()) + switch (m_lexer->tokenType()) { case TK_Assign: return ASSIGNOP_Assign; case TK_AddAssign: return ASSIGNOP_Add; @@ -1049,7 +1049,7 @@ { ASSIGNOP_Decrease, DH_DecreaseLocalVar, DH_DecreaseGlobalVar, DH_DecreaseGlobalArray }, }; -DataHeader BotscriptParser::GetAssigmentDataHeader (AssignmentOperator op, Variable* var) +DataHeader BotscriptParser::getAssigmentDataHeader (AssignmentOperator op, Variable* var) { for (const auto& a : gAssignmentDataHeaders) { @@ -1065,7 +1065,7 @@ return a.local; } - Error ("WTF: couldn't find data header for operator #%1", op); + error ("WTF: couldn't find data header for operator #%1", op); return (DataHeader) 0; } @@ -1075,37 +1075,37 @@ // by an assignment operator, followed by an expression value. Expects current // token to be the name of the variable, and expects the variable to be given. // -DataBuffer* BotscriptParser::ParseAssignment (Variable* var) +DataBuffer* BotscriptParser::parseAssignment (Variable* var) { DataBuffer* retbuf = new DataBuffer; DataBuffer* arrayindex = null; if (var->writelevel != WRITE_Mutable) - Error ("cannot alter read-only variable $%1", var->name); + error ("cannot alter read-only variable $%1", var->name); if (var->isarray) { - mLexer->MustGetNext (TK_BracketStart); - Expression expr (this, mLexer, TYPE_Int); - expr.Result()->ConvertToBuffer(); - arrayindex = expr.Result()->Buffer()->Clone(); - mLexer->MustGetNext (TK_BracketEnd); + m_lexer->mustGetNext (TK_BracketStart); + Expression expr (this, m_lexer, TYPE_Int); + expr.getResult()->convertToBuffer(); + arrayindex = expr.getResult()->buffer()->clone(); + m_lexer->mustGetNext (TK_BracketEnd); } // Get an operator - AssignmentOperator oper = ParseAssignmentOperator(); + AssignmentOperator oper = parseAssignmentOperator(); - if (mCurrentMode == PARSERMODE_TopLevel) - Error ("can't alter variables at top level"); + if (m_currentMode == PARSERMODE_TopLevel) + error ("can't alter variables at top level"); if (var->isarray) - retbuf->MergeAndDestroy (arrayindex); + retbuf->mergeAndDestroy (arrayindex); // Parse the right operand if (oper != ASSIGNOP_Increase && oper != ASSIGNOP_Decrease) { - DataBuffer* expr = ParseExpression (var->type); - retbuf->MergeAndDestroy (expr); + DataBuffer* expr = parseExpression (var->type); + retbuf->mergeAndDestroy (expr); } #if 0 @@ -1120,22 +1120,22 @@ retbuf->WriteDWord (var->index); #endif - DataHeader dh = GetAssigmentDataHeader (oper, var); - retbuf->WriteDWord (dh); - retbuf->WriteDWord (var->index); + DataHeader dh = getAssigmentDataHeader (oper, var); + retbuf->writeDWord (dh); + retbuf->writeDWord (var->index); return retbuf; } // ============================================================================ // -void BotscriptParser::PushScope (EReset reset) +void BotscriptParser::pushScope (EReset reset) { - mScopeCursor++; + m_scopeCursor++; - if (mScopeStack.Size() < mScopeCursor + 1) + if (m_scopeStack.size() < m_scopeCursor + 1) { ScopeInfo newscope; - mScopeStack << newscope; + m_scopeStack << newscope; reset = SCOPE_Reset; } @@ -1146,51 +1146,51 @@ info->mark1 = null; info->mark2 = null; info->buffer1 = null; - info->cases.Clear(); + info->cases.clear(); info->casecursor = info->cases.begin() - 1; } // Reset variable stuff in any case - SCOPE(0).globalVarIndexBase = (mScopeCursor == 0) ? 0 : SCOPE(1).globalVarIndexBase; - SCOPE(0).localVarIndexBase = (mScopeCursor == 0) ? 0 : SCOPE(1).localVarIndexBase; + SCOPE(0).globalVarIndexBase = (m_scopeCursor == 0) ? 0 : SCOPE(1).globalVarIndexBase; + SCOPE(0).localVarIndexBase = (m_scopeCursor == 0) ? 0 : SCOPE(1).localVarIndexBase; for (Variable* var : SCOPE(0).globalVariables + SCOPE(0).localVariables) delete var; - SCOPE(0).localVariables.Clear(); - SCOPE(0).globalVariables.Clear(); + SCOPE(0).localVariables.clear(); + SCOPE(0).globalVariables.clear(); } // ============================================================================ // -DataBuffer* BotscriptParser::ParseExpression (DataType reqtype, bool fromhere) +DataBuffer* BotscriptParser::parseExpression (DataType reqtype, bool fromhere) { // hehe if (fromhere == true) - mLexer->Skip (-1); + m_lexer->skip (-1); - Expression expr (this, mLexer, reqtype); - expr.Result()->ConvertToBuffer(); + Expression expr (this, m_lexer, reqtype); + expr.getResult()->convertToBuffer(); // The buffer will be destroyed once the function ends so we need to // clone it now. - return expr.Result()->Buffer()->Clone(); + return expr.getResult()->buffer()->clone(); } // ============================================================================ // -DataBuffer* BotscriptParser::ParseStatement() +DataBuffer* BotscriptParser::parseStatement() { // If it's a variable, expect assignment. - if (mLexer->Next (TK_DollarSign)) + if (m_lexer->next (TK_DollarSign)) { - mLexer->MustGetNext (TK_Symbol); - Variable* var = FindVariable (GetTokenString()); + m_lexer->mustGetNext (TK_Symbol); + Variable* var = findVariable (getTokenString()); if (var == null) - Error ("unknown variable $%1", var->name); + error ("unknown variable $%1", var->name); - return ParseAssignment (var); + return parseAssignment (var); } return null; @@ -1198,65 +1198,65 @@ // ============================================================================ // -void BotscriptParser::AddSwitchCase (DataBuffer* casebuffer) +void BotscriptParser::addSwitchCase (DataBuffer* casebuffer) { ScopeInfo* info = &SCOPE (0); CaseInfo casedata; // Init a mark for the case buffer - ByteMark* casemark = buffer()->AddMark (""); + ByteMark* casemark = currentBuffer()->addMark (""); casedata.mark = casemark; // Add a reference to the mark. "case" and "default" both // add the necessary bytecode before the reference. if (casebuffer != null) - casebuffer->AddReference (casemark); + casebuffer->addReference (casemark); else - buffer()->AddReference (casemark); + currentBuffer()->addReference (casemark); // Init a buffer for the case block and tell the object // writer to record all written data to it. - casedata.data = mSwitchBuffer = new DataBuffer; + casedata.data = m_switchBuffer = new DataBuffer; SCOPE(0).cases << casedata; info->casecursor++; } // ============================================================================ // -bool BotscriptParser::TokenIs (ETokenType a) +bool BotscriptParser::tokenIs (ETokenType a) { - return (mLexer->TokenType() == a); + return (m_lexer->tokenType() == a); } // ============================================================================ // -String BotscriptParser::GetTokenString() +String BotscriptParser::getTokenString() { - return mLexer->Token()->text; + return m_lexer->token()->text; } // ============================================================================ // -String BotscriptParser::DescribePosition() const +String BotscriptParser::describePosition() const { - Lexer::TokenInfo* tok = mLexer->Token(); + Lexer::TokenInfo* tok = m_lexer->token(); return tok->file + ":" + String (tok->line) + ":" + String (tok->column); } // ============================================================================ // -DataBuffer* BotscriptParser::buffer() +DataBuffer* BotscriptParser::currentBuffer() { - if (mSwitchBuffer != null) - return mSwitchBuffer; + if (m_switchBuffer != null) + return m_switchBuffer; - if (mCurrentMode == PARSERMODE_MainLoop) - return mMainLoopBuffer; + if (m_currentMode == PARSERMODE_MainLoop) + return m_mainLoopBuffer; - if (mCurrentMode == PARSERMODE_Onenter) - return mOnEnterBuffer; + if (m_currentMode == PARSERMODE_Onenter) + return m_onenterBuffer; - return mMainBuffer; + return m_mainBuffer; } // ============================================================================ @@ -1264,64 +1264,64 @@ void BotscriptParser::writeMemberBuffers() { // If there was no mainloop defined, write a dummy one now. - if (mGotMainLoop == false) + if (m_gotMainLoop == false) { - mMainLoopBuffer->WriteDWord (DH_MainLoop); - mMainLoopBuffer->WriteDWord (DH_EndMainLoop); + m_mainLoopBuffer->writeDWord (DH_MainLoop); + m_mainLoopBuffer->writeDWord (DH_EndMainLoop); } // Write the onenter and mainloop buffers, in that order in particular. - for (DataBuffer** bufp : List<DataBuffer**> ({&mOnEnterBuffer, &mMainLoopBuffer})) + for (DataBuffer** bufp : List<DataBuffer**> ({&m_onenterBuffer, &m_mainLoopBuffer})) { - buffer()->MergeAndDestroy (*bufp); + currentBuffer()->mergeAndDestroy (*bufp); // Clear the buffer afterwards for potential next state *bufp = new DataBuffer; } // Next state definitely has no mainloop yet - mGotMainLoop = false; + m_gotMainLoop = false; } // ============================================================================ // // Write string table // -void BotscriptParser::WriteStringTable() +void BotscriptParser::writeStringTable() { - int stringcount = CountStringsInTable(); + int stringcount = countStringsInTable(); if (stringcount == 0) return; // Write header - mMainBuffer->WriteDWord (DH_StringList); - mMainBuffer->WriteDWord (stringcount); + m_mainBuffer->writeDWord (DH_StringList); + m_mainBuffer->writeDWord (stringcount); // Write all strings for (int i = 0; i < stringcount; i++) - mMainBuffer->WriteString (GetStringTable()[i]); + m_mainBuffer->writeString (getStringTable()[i]); } // ============================================================================ // // Write the compiled bytecode to a file // -void BotscriptParser::WriteToFile (String outfile) +void BotscriptParser::writeToFile (String outfile) { FILE* fp = fopen (outfile, "wb"); if (fp == null) - Error ("couldn't open %1 for writing: %2", outfile, strerror (errno)); + error ("couldn't open %1 for writing: %2", outfile, strerror (errno)); // First, resolve references - for (MarkReference* ref : mMainBuffer->References()) + for (MarkReference* ref : m_mainBuffer->references()) for (int i = 0; i < 4; ++i) - mMainBuffer->Buffer()[ref->pos + i] = (ref->target->pos >> (8 * i)) & 0xFF; + m_mainBuffer->buffer()[ref->pos + i] = (ref->target->pos >> (8 * i)) & 0xFF; // Then, dump the main buffer to the file - fwrite (mMainBuffer->Buffer(), 1, mMainBuffer->WrittenSize(), fp); - Print ("-- %1 byte%s1 written to %2\n", mMainBuffer->WrittenSize(), outfile); + fwrite (m_mainBuffer->buffer(), 1, m_mainBuffer->writtenSize(), fp); + print ("-- %1 byte%s1 written to %2\n", m_mainBuffer->writtenSize(), outfile); fclose (fp); } @@ -1330,11 +1330,11 @@ // Attempt to find the variable by the given name. Looks from current scope // downwards. // -Variable* BotscriptParser::FindVariable (const String& name) +Variable* BotscriptParser::findVariable (const String& name) { - for (int i = mScopeCursor; i >= 0; --i) + for (int i = m_scopeCursor; i >= 0; --i) { - for (Variable* var : mScopeStack[i].globalVariables + mScopeStack[i].localVariables) + for (Variable* var : m_scopeStack[i].globalVariables + m_scopeStack[i].localVariables) { if (var->name == name) return var; @@ -1348,27 +1348,27 @@ // // Is the parser currently in global state (i.e. not in any specific state)? // -bool BotscriptParser::IsInGlobalState() const +bool BotscriptParser::isInGlobalState() const { - return mCurrentState.IsEmpty(); + return m_currentState.isEmpty(); } // ============================================================================ // -void BotscriptParser::SuggestHighestVarIndex (bool global, int index) +void BotscriptParser::suggestHighestVarIndex (bool global, int index) { if (global) - mHighestGlobalVarIndex = max (mHighestGlobalVarIndex, index); + m_highestGlobalVarIndex = max (m_highestGlobalVarIndex, index); else - mHighestStateVarIndex = max (mHighestStateVarIndex, index); + m_highestStateVarIndex = max (m_highestStateVarIndex, index); } // ============================================================================ // -int BotscriptParser::GetHighestVarIndex (bool global) +int BotscriptParser::getHighestVarIndex (bool global) { if (global) - return mHighestGlobalVarIndex; + return m_highestGlobalVarIndex; - return mHighestStateVarIndex; + return m_highestStateVarIndex; }
--- a/src/Parser.h Wed Feb 26 18:31:53 2014 +0200 +++ b/src/Parser.h Mon Mar 03 01:04:16 2014 +0200 @@ -110,7 +110,7 @@ inline bool IsGlobal() const { - return statename.IsEmpty(); + return statename.isEmpty(); } }; @@ -149,7 +149,7 @@ // class BotscriptParser { - PROPERTY (public, bool, IsReadOnly, SetReadOnly, STOCK_WRITE) + PROPERTY (public, bool, isReadOnly, setReadOnly, STOCK_WRITE) public: enum EReset @@ -160,100 +160,96 @@ BotscriptParser(); ~BotscriptParser(); - void ParseBotscript (String fileName); - DataBuffer* ParseCommand (CommandInfo* comm); - DataBuffer* ParseAssignment (Variable* var); - AssignmentOperator ParseAssignmentOperator(); - String ParseFloat(); - void PushScope (EReset reset = SCOPE_Reset); - DataBuffer* ParseStatement(); - void AddSwitchCase (DataBuffer* b); - void CheckToplevel(); - void CheckNotToplevel(); - bool TokenIs (ETokenType a); - String GetTokenString(); - String DescribePosition() const; - void WriteToFile (String outfile); - Variable* FindVariable (const String& name); - bool IsInGlobalState() const; - void SuggestHighestVarIndex (bool global, int index); - int GetHighestVarIndex (bool global); + void parseBotscript (String fileName); + DataBuffer* parseCommand (CommandInfo* comm); + DataBuffer* parseAssignment (Variable* var); + AssignmentOperator parseAssignmentOperator(); + String parseFloat(); + void pushScope (EReset reset = SCOPE_Reset); + DataBuffer* parseStatement(); + void addSwitchCase (DataBuffer* b); + void checkToplevel(); + void checkNotToplevel(); + bool tokenIs (ETokenType a); + String getTokenString(); + String describePosition() const; + void writeToFile (String outfile); + Variable* findVariable (const String& name); + bool isInGlobalState() const; + void suggestHighestVarIndex (bool global, int index); + int getHighestVarIndex (bool global); - inline ScopeInfo& GSCOPE_t (int offset) + inline ScopeInfo& scope (int offset) { - return mScopeStack[mScopeCursor - offset]; + return m_scopeStack[m_scopeCursor - offset]; } - inline int GetNumEvents() const + inline int numEvents() const { - return mNumEvents; + return m_numEvents; } - inline int GetNumStates() const + inline int numStates() const { - return mNumStates; + return m_numStates; } private: // The main buffer - the contents of this is what we // write to file after parsing is complete - DataBuffer* mMainBuffer; + DataBuffer* m_mainBuffer; - // onenter buffer - the contents of the onenter{} block + // onenter buffer - the contents of the onenter {} block // is buffered here and is merged further at the end of state - DataBuffer* mOnEnterBuffer; + DataBuffer* m_onenterBuffer; - // Mainloop buffer - the contents of the mainloop{} block + // Mainloop buffer - the contents of the mainloop {} block // is buffered here and is merged further at the end of state - DataBuffer* mMainLoopBuffer; + DataBuffer* m_mainLoopBuffer; // Switch buffer - switch case data is recorded to this // buffer initially, instead of into main buffer. - DataBuffer* mSwitchBuffer; + DataBuffer* m_switchBuffer; - Lexer* mLexer; - int mNumStates; - int mNumEvents; - ParserMode mCurrentMode; - String mCurrentState; - bool mStateSpawnDefined; - bool mGotMainLoop; - int mScopeCursor; - bool mCanElse; - int mHighestGlobalVarIndex; - int mHighestStateVarIndex; - - // How many bytes have we written to file? - int mNumWrittenBytes; - - // Scope data - List<ScopeInfo> mScopeStack; + Lexer* m_lexer; + int m_numStates; + int m_numEvents; + ParserMode m_currentMode; + String m_currentState; + bool m_isStateSpawnDefined; + bool m_gotMainLoop; + int m_scopeCursor; + bool m_isElseAllowed; + int m_highestGlobalVarIndex; + int m_highestStateVarIndex; + int m_numWrittenBytes; + List<ScopeInfo> m_scopeStack; - DataBuffer* buffer(); - void ParseStateBlock(); - void ParseEventBlock(); - void ParseMainloop(); - void ParseOnEnterExit(); - void ParseVar(); - void ParseGoto(); - void ParseIf(); - void ParseElse(); - void ParseWhileBlock(); - void ParseForBlock(); - void ParseDoBlock(); - void ParseSwitchBlock(); - void ParseSwitchCase(); - void ParseSwitchDefault(); - void ParseBreak(); - void ParseContinue(); - void ParseBlockEnd(); - void ParseLabel(); - void ParseEventdef(); - void ParseFuncdef(); + DataBuffer* currentBuffer(); + void parseStateBlock(); + void parseEventBlock(); + void parseMainloop(); + void parseOnEnterExit(); + void parseVar(); + void parseGoto(); + void parseIf(); + void parseElse(); + void parseWhileBlock(); + void parseForBlock(); + void parseDoBlock(); + void parseSwitchBlock(); + void parseSwitchCase(); + void parseSwitchDefault(); + void parseBreak(); + void parseContinue(); + void parseBlockEnd(); + void parseLabel(); + void parseEventdef(); + void parseFuncdef(); void writeMemberBuffers(); - void WriteStringTable(); - DataBuffer* ParseExpression (DataType reqtype, bool fromhere = false); - DataHeader GetAssigmentDataHeader (AssignmentOperator op, Variable* var); + void writeStringTable(); + DataBuffer* parseExpression (DataType reqtype, bool fromhere = false); + DataHeader getAssigmentDataHeader (AssignmentOperator op, Variable* var); }; #endif // BOTC_PARSER_H
--- a/src/Property.h Wed Feb 26 18:31:53 2014 +0200 +++ b/src/Property.h Mon Mar 03 01:04:16 2014 +0200 @@ -30,12 +30,12 @@ #define PROPERTY( ACCESS, TYPE, READ, WRITE, WRITETYPE ) \ private: \ - TYPE m##READ; \ + TYPE m_##READ; \ \ public: \ inline TYPE const& READ() const \ { \ - return m##READ; \ + return m_##READ; \ } \ \ ACCESS: \ @@ -43,7 +43,7 @@ #define PROPERTY_STOCK_WRITE( READ ) \ { \ - m##READ = a; \ + m_##READ = a; \ } #define PROPERTY_CUSTOM_WRITE( READ ) ; \ No newline at end of file
--- a/src/String.cc Wed Feb 26 18:31:53 2014 +0200 +++ b/src/String.cc Mon Mar 03 01:04:16 2014 +0200 @@ -32,31 +32,31 @@ // ============================================================================= // -int String::Compare (const String& other) const +int String::compare (const String& other) const { - return mString.compare (other.STDString()); + return m_string.compare (other.stdString()); } // ============================================================================= // -void String::Trim (int n) +void String::trim (int n) { if (n > 0) - mString = Mid (0, Length() - n).STDString(); + m_string = mid (0, length() - n).stdString(); else - mString = Mid (n, -1).STDString(); + m_string = mid (n, -1).stdString(); } // ============================================================================= // -String String::Strip (const List< char >& unwanted) +String String::strip (const List< char >& unwanted) { - String copy (mString); + String copy (m_string); for (char c : unwanted) - for (int i = 0; i < copy.Length(); ++i) + for (int i = 0; i < copy.length(); ++i) if (copy[i] == c) - copy.RemoveAt (i); + copy.removeAt (i); /* int pos = 0; @@ -69,9 +69,9 @@ // ============================================================================= // -String String::ToUppercase() const +String String::toUppercase() const { - String newstr = mString; + String newstr = m_string; for (char& c : newstr) if (c >= 'a' && c <= 'z') @@ -82,9 +82,9 @@ // ============================================================================= // -String String::ToLowercase() const +String String::toLowercase() const { - String newstr = mString; + String newstr = m_string; for (char & c : newstr) if (c >= 'A' && c <= 'Z') @@ -95,16 +95,16 @@ // ============================================================================= // -StringList String::Split (char del) const +StringList String::split (char del) const { String delimstr; delimstr += del; - return Split (delimstr); + return split (delimstr); } // ============================================================================= // -StringList String::Split (String del) const +StringList String::split (const String& del) const { StringList res; long a = 0; @@ -112,43 +112,43 @@ // Find all separators and store the text left to them. for (;;) { - long b = FirstIndexOf (del, a); + long b = firstIndexOf (del, a); if (b == -1) break; - String sub = Mid (a, b); + String sub = mid (a, b); - if (sub.Length() > 0) - res.Append (Mid (a, b)); + if (sub.length() > 0) + res.append (mid (a, b)); - a = b + del.Length(); + a = b + del.length(); } // Add the string at the right of the last separator - if (a < (int) Length()) - res.Append (Mid (a, Length())); + if (a < (int) length()) + res.append (mid (a, length())); return res; } // ============================================================================= // -void String::Replace (const char* a, const char* b) +void String::replace (const char* a, const char* b) { long pos; - while ( (pos = FirstIndexOf (a)) != -1) - mString = mString.replace (pos, strlen (a), b); + while ((pos = firstIndexOf (a)) != -1) + m_string = m_string.replace (pos, strlen (a), b); } // ============================================================================= // -int String::Count (char needle) const +int String::count (char needle) const { int needles = 0; - for (const char & c : mString) + for (const char & c : m_string) if (c == needle) needles++; @@ -157,10 +157,10 @@ // ============================================================================= // -String String::Mid (long a, long b) const +String String::mid (long a, long b) const { if (b == -1) - b = Length(); + b = length(); if (b == a) return ""; @@ -174,7 +174,7 @@ } char* newstr = new char[b - a + 1]; - strncpy (newstr, mString.c_str() + a, b - a); + strncpy (newstr, m_string.c_str() + a, b - a); newstr[b - a] = '\0'; String other (newstr); @@ -184,13 +184,13 @@ // ============================================================================= // -int String::WordPosition (int n) const +int String::wordPosition (int n) const { int count = 0; - for (int i = 0; i < Length(); ++i) + for (int i = 0; i < length(); ++i) { - if (mString[i] != ' ') + if (m_string[i] != ' ') continue; if (++count < n) @@ -204,10 +204,10 @@ // ============================================================================= // -int String::FirstIndexOf (const char* c, int a) const +int String::firstIndexOf (const char* c, int a) const { - for (; a < Length(); a++) - if (mString[a] == c[0] && strncmp (mString.c_str() + a, c, strlen (c)) == 0) + for (; a < length(); a++) + if (m_string[a] == c[0] && strncmp (m_string.c_str() + a, c, strlen (c)) == 0) return a; return -1; @@ -215,13 +215,13 @@ // ============================================================================= // -int String::LastIndexOf (const char* c, int a) const +int String::lastIndexOf (const char* c, int a) const { - if (a == -1 || a >= Length()) - a = Length() - 1; + if (a == -1 || a >= length()) + a = length() - 1; for (; a > 0; a--) - if (mString[a] == c[0] && strncmp (mString.c_str() + a, c, strlen (c)) == 0) + if (m_string[a] == c[0] && strncmp (m_string.c_str() + a, c, strlen (c)) == 0) return a; return -1; @@ -229,22 +229,22 @@ // ============================================================================= // -void String::Dump() const +void String::dump() const { - Print ("`%1`:\n", CString()); + print ("`%1`:\n", chars()); int i = 0; - for (char u : mString) - Print ("\t%1. [%d2] `%3`\n", i++, u, String (u)); + for (char u : m_string) + print ("\t%1. [%d2] `%3`\n", i++, u, String (u)); } // ============================================================================= // -long String::ToLong (bool* ok, int base) const +long String::toLong (bool* ok, int base) const { errno = 0; char* endptr; - long i = strtol (mString.c_str(), &endptr, base); + long i = strtol (m_string.c_str(), &endptr, base); if (ok) *ok = (errno == 0 && *endptr == '\0'); @@ -254,11 +254,11 @@ // ============================================================================= // -float String::ToFloat (bool* ok) const +float String::toFloat (bool* ok) const { errno = 0; char* endptr; - float i = strtof (mString.c_str(), &endptr); + float i = strtof (m_string.c_str(), &endptr); if (ok) *ok = (errno == 0 && *endptr == '\0'); @@ -268,11 +268,11 @@ // ============================================================================= // -double String::ToDouble (bool* ok) const +double String::toDouble (bool* ok) const { errno = 0; char* endptr; - double i = strtod (mString.c_str(), &endptr); + double i = strtod (m_string.c_str(), &endptr); if (ok) *ok = (errno == 0 && *endptr == '\0'); @@ -285,7 +285,7 @@ String String::operator+ (const String& data) const { String newString = *this; - newString.Append (data); + newString.append (data); return newString; } @@ -294,20 +294,20 @@ String String::operator+ (const char* data) const { String newstr = *this; - newstr.Append (data); + newstr.append (data); return newstr; } // ============================================================================= // -bool String::IsNumeric() const +bool String::isNumeric() const { bool gotDot = false; - for (const char & c : mString) + for (const char & c : m_string) { // Allow leading hyphen for negatives - if (&c == &mString[0] && c == '-') + if (&c == &m_string[0] && c == '-') continue; // Check for decimal point @@ -330,28 +330,28 @@ // ============================================================================= // -bool String::EndsWith (const String& other) +bool String::endsWith (const String& other) { - if (Length() < other.Length()) + if (length() < other.length()) return false; - const int ofs = Length() - other.Length(); - return strncmp (CString() + ofs, other.CString(), other.Length()) == 0; + const int ofs = length() - other.length(); + return strncmp (chars() + ofs, other.chars(), other.length()) == 0; } // ============================================================================= // -bool String::StartsWith (const String& other) +bool String::startsWith (const String& other) { - if (Length() < other.Length()) + if (length() < other.length()) return false; - return strncmp (CString(), other.CString(), other.Length()) == 0; + return strncmp (chars(), other.chars(), other.length()) == 0; } // ============================================================================= // -void String::SPrintf (const char* fmtstr, ...) +void String::sprintf (const char* fmtstr, ...) { char* buf; int bufsize = 256; @@ -363,19 +363,19 @@ while (vsnprintf (buf, bufsize, fmtstr, va) >= bufsize); va_end (va); - mString = buf; + m_string = buf; delete[] buf; } // ============================================================================= // -String StringList::Join (const String& delim) +String StringList::join (const String& delim) { String result; - for (const String& it : GetDeque()) + for (const String& it : deque()) { - if (result.IsEmpty() == false) + if (result.isEmpty() == false) result += delim; result += it; @@ -386,15 +386,15 @@ // ============================================================================= // -bool String::MaskAgainst (const String& pattern) const +bool String::maskAgainst (const String& pattern) const { // Elevate to uppercase for case-insensitive matching - String pattern_upper = pattern.ToUppercase(); - String this_upper = ToUppercase(); - const char* maskstring = pattern_upper.CString(); + String pattern_upper = pattern.toUppercase(); + String this_upper = toUppercase(); + const char* maskstring = pattern_upper.chars(); const char* mptr = &maskstring[0]; - for (const char* sptr = this_upper.CString(); *sptr != '\0'; sptr++) + for (const char* sptr = this_upper.chars(); *sptr != '\0'; sptr++) { if (*mptr == '?') { @@ -434,18 +434,18 @@ // ============================================================================= // -String String::FromNumber (int a) +String String::fromNumber (int a) { char buf[32]; - sprintf (buf, "%d", a); + ::sprintf (buf, "%d", a); return String (buf); } // ============================================================================= // -String String::FromNumber (long a) +String String::fromNumber (long a) { char buf[32]; - sprintf (buf, "%ld", a); + ::sprintf (buf, "%ld", a); return String (buf); }
--- a/src/String.h Wed Feb 26 18:31:53 2014 +0200 +++ b/src/String.h Mon Mar 03 01:04:16 2014 +0200 @@ -50,160 +50,160 @@ String() {} explicit String (char a) : - mString (&a) {} + m_string (&a) {} String (const char* data) : - mString (data) {} + m_string (data) {} String (const StringType& data) : - mString (data) {} + m_string (data) {} - void Dump() const; - int Compare (const String& other) const; - bool EndsWith (const String& other); - int Count (char needle) const; - int FirstIndexOf (const char* c, int a = 0) const; - int LastIndexOf (const char* c, int a = -1) const; - String ToLowercase() const; - bool IsNumeric() const; - bool MaskAgainst (const String& pattern) const; - int WordPosition (int n) const; - void Replace (const char* a, const char* b); - StringList Split (String del) const; - StringList Split (char del) const; - void SPrintf (const char* fmtstr, ...); - bool StartsWith (const String& other); - String Strip (const List<char>& unwanted); - String Mid (long a, long b = -1) const; - double ToDouble (bool* ok = nullptr) const; - float ToFloat (bool* ok = nullptr) const; - long ToLong (bool* ok = nullptr, int base = 10) const; - void Trim (int n); - String ToUppercase() const; + void dump() const; + int compare (const String& other) const; + bool endsWith (const String& other); + int count (char needle) const; + int firstIndexOf (const char* c, int a = 0) const; + int lastIndexOf (const char* c, int a = -1) const; + String toLowercase() const; + bool isNumeric() const; + bool maskAgainst (const String& pattern) const; + int wordPosition (int n) const; + void replace (const char* a, const char* b); + StringList split (const String& del) const; + StringList split (char del) const; + void sprintf (const char* fmtstr, ...); + bool startsWith (const String& other); + String strip (const List<char>& unwanted); + String mid (long a, long b = -1) const; + double toDouble (bool* ok = nullptr) const; + float toFloat (bool* ok = nullptr) const; + long toLong (bool* ok = nullptr, int base = 10) const; + void trim (int n); + String toUppercase() const; String operator+ (const String& data) const; String operator+ (const char* data) const; - static String FromNumber (int a); - static String FromNumber (long a); + static String fromNumber (int a); + static String fromNumber (long a); - inline bool IsEmpty() const + inline bool isEmpty() const { - return mString[0] == '\0'; + return m_string[0] == '\0'; } - inline void Append (const char* data) + inline void append (const char* data) { - mString.append (data); + m_string.append (data); } - inline void Append (const char data) + inline void append (char data) { - mString.push_back (data); + m_string.push_back (data); } - inline void Append (const String& data) + inline void append (const String& data) { - mString.append (data.CString()); + m_string.append (data.chars()); } inline Iterator begin() { - return mString.begin(); + return m_string.begin(); } inline ConstIterator begin() const { - return mString.cbegin(); + return m_string.cbegin(); } - inline const char* CString() const + inline const char* chars() const { - return mString.c_str(); + return m_string.c_str(); } inline const char* c_str() const { - return mString.c_str(); + return m_string.c_str(); } inline Iterator end() { - return mString.end(); + return m_string.end(); } inline ConstIterator end() const { - return mString.end(); + return m_string.end(); } - inline void Clear() + inline void clear() { - mString.clear(); + m_string.clear(); } - inline void RemoveAt (int pos) + inline void removeAt (int pos) { - mString.erase (mString.begin() + pos); + m_string.erase (m_string.begin() + pos); } - inline void Insert (int pos, char c) + inline void insert (int pos, char c) { - mString.insert (mString.begin() + pos, c); + m_string.insert (m_string.begin() + pos, c); } - inline int Length() const + inline int length() const { - return mString.length(); + return m_string.length(); } - inline void Remove (int pos, int len) + inline void remove (int pos, int len) { - mString.replace (pos, len, ""); + m_string.replace (pos, len, ""); } - inline void RemoveFromStart (int len) + inline void removeFromStart (int len) { - Remove (0, len); + remove (0, len); } - inline void RemoveFromEnd (int len) + inline void removeFromEnd (int len) { - Remove (Length() - len, len); + remove (length() - len, len); } - inline void Replace (int pos, int n, const String& a) + inline void replace (int pos, int n, const String& a) { - mString.replace (pos, n, a.CString()); + m_string.replace (pos, n, a.chars()); } - inline void ShrinkToFit() + inline void shrinkToFit() { - mString.shrink_to_fit(); + m_string.shrink_to_fit(); } - inline const StringType& STDString() const + inline const StringType& stdString() const { - return mString; + return m_string; } - inline String Strip (char unwanted) + inline String strip (char unwanted) { - return Strip ({unwanted}); + return strip ({unwanted}); } // ============================================================================= // inline String operator+ (int num) const { - return *this + String::FromNumber (num); + return *this + String::fromNumber (num); } // ============================================================================= // inline String& operator+= (const String data) { - Append (data); + append (data); return *this; } @@ -211,7 +211,7 @@ // inline String& operator+= (const char* data) { - Append (data); + append (data); return *this; } @@ -219,21 +219,21 @@ // inline String& operator+= (int num) { - return operator+= (String::FromNumber (num)); + return operator+= (String::fromNumber (num)); } // ============================================================================= // - inline void Prepend (String a) + inline void prepend (String a) { - mString = (a + mString).STDString(); + m_string = (a + m_string).stdString(); } // ============================================================================= // inline String& operator+= (const char data) { - Append (data); + append (data); return *this; } @@ -241,7 +241,7 @@ // inline String operator- (int n) const { - String newString = mString; + String newString = m_string; newString -= n; return newString; } @@ -250,7 +250,7 @@ // inline String& operator-= (int n) { - Trim (n); + trim (n); return *this; } @@ -258,21 +258,21 @@ // inline String operator+() const { - return ToUppercase(); + return toUppercase(); } // ============================================================================= // inline String operator-() const { - return ToLowercase(); + return toLowercase(); } // ============================================================================= // inline bool operator== (const String& other) const { - return STDString() == other.STDString(); + return stdString() == other.stdString(); } // ============================================================================= @@ -286,7 +286,7 @@ // inline bool operator!= (const String& other) const { - return STDString() != other.STDString(); + return stdString() != other.stdString(); } // ============================================================================= @@ -300,28 +300,28 @@ // inline bool operator> (const String& other) const { - return STDString() > other.STDString(); + return stdString() > other.stdString(); } // ============================================================================= // inline bool operator< (const String& other) const { - return STDString() < other.STDString(); + return stdString() < other.stdString(); } // ============================================================================= // inline operator const char*() const { - return CString(); + return chars(); } // ============================================================================= // inline operator const StringType&() const { - return STDString(); + return stdString(); } // ============================================================================= @@ -329,14 +329,14 @@ // Difference between indices @a and @b. @b can be -1, in which // case it will be length() - 1. // - inline int IndexDifference (int a, int b) + inline int indexDifference (int a, int b) { assert (b == -1 || b >= a); - return (b != -1 ? b - a : Length() - 1 - a); + return (b != -1 ? b - a : length() - 1 - a); } private: - StringType mString; + StringType m_string; }; // ============================================================================= @@ -347,10 +347,10 @@ StringList() {} StringList (std::initializer_list<String> vals) : List<String> (vals) {} - StringList (const List<String>& a) : List<String> (a.GetDeque()) {} - StringList (const ListType& a) : List<String> (a) {} + StringList (const List<String>& a) : List<String> (a.deque()) {} + StringList (const WrappedList& a) : List<String> (a) {} - String Join (const String& delim); + String join (const String& delim); };
--- a/src/StringTable.cc Wed Feb 26 18:31:53 2014 +0200 +++ b/src/StringTable.cc Mon Mar 03 01:04:16 2014 +0200 @@ -26,55 +26,57 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +// TODO: Another freeloader... + #include <stdio.h> #include <stdlib.h> #include <string.h> #include "StringTable.h" -static StringList gStringTable; +static StringList g_StringTable; // ============================================================================ // -const StringList& GetStringTable() +const StringList& getStringTable() { - return gStringTable; + return g_StringTable; } // ============================================================================ // // Potentially adds a string to the table and returns the index of it. // -int StringTableIndex (const String& a) +int getStringTableIndex (const String& a) { // Find a free slot in the table. int idx; - for (idx = 0; idx < gStringTable.Size(); idx++) + for (idx = 0; idx < g_StringTable.size(); idx++) { // String is already in the table, thus return it. - if (gStringTable[idx] == a) + if (g_StringTable[idx] == a) return idx; } // Must not be too long. - if (a.Length() >= gMaxStringLength) - Error ("string `%1` too long (%2 characters, max is %3)\n", - a, a.Length(), gMaxStringLength); + if (a.length() >= gMaxStringLength) + error ("string `%1` too long (%2 characters, max is %3)\n", + a, a.length(), gMaxStringLength); // Check if the table is already full - if (gStringTable.Size() == gMaxStringlistSize - 1) - Error ("too many strings!\n"); + if (g_StringTable.size() == gMaxStringlistSize - 1) + error ("too many strings!\n"); // Now, dump the string into the slot - gStringTable.Append (a); - return (gStringTable.Size() - 1); + g_StringTable.append (a); + return (g_StringTable.size() - 1); } // ============================================================================ // // Counts the amount of strings in the table. // -int CountStringsInTable() +int countStringsInTable() { - return gStringTable.Size(); + return g_StringTable.size(); }
--- a/src/StringTable.h Wed Feb 26 18:31:53 2014 +0200 +++ b/src/StringTable.h Mon Mar 03 01:04:16 2014 +0200 @@ -31,8 +31,8 @@ #include "Main.h" -int StringTableIndex (const String& a); -const StringList& GetStringTable(); -int CountStringsInTable(); +int getStringTableIndex (const String& a); +const StringList& getStringTable(); +int countStringsInTable(); #endif // BOTC_STRINGTABLE_H