diff options
| author | jsmall-nvidia <jsmall@nvidia.com> | 2019-04-29 17:03:46 -0400 |
|---|---|---|
| committer | Tim Foley <tfoleyNV@users.noreply.github.com> | 2019-04-29 14:03:46 -0700 |
| commit | 4880789e3003441732cca4471091563f36531635 (patch) | |
| tree | 8e0d3ed58a561373b35729d24787afe6b39732e3 /source | |
| parent | ded340beb4b5197b559626acc39920abb2d39e77 (diff) | |
String/List closer to conventions, and use Index type (#959)
* List made members m_
Tweaked types to closer match conventions.
* Use asserts for checking conditions on List.
Other small improvements.
* List<T>.Count() -> getSize()
* List<T>
Add -> add
First -> getFirst
Last -> getLast
RemoveLast -> removeLast
ReleaseBuffer -> detachBuffer
GetArrayView -> getArrayView
* List<T>::
AddRange -> addRange
Capacity -> getCapacity
Insert -> insert
InsertRange -> insertRange
AddRange -> addRange
RemoveRange -> removeRange
RemoveAt -> removeAt
Remove -> remove
Reverse -> reverse
FastRemove -> fastRemove
FastRemoveAt -> fastRemoveAt
Clear -> clear
* List<T>
FreeBuffer -> _deallocateBuffer
Free -> clearAndDeallocate
SwapWith -> swapWith
* List<T>
SetSize -> setSize
Reserve -> reserve
GrowToSize growToSize
* UnsafeShrinkToSize -> unsafeShrinkToSize
Compress -> compress
FindLast -> findLastIndex
FindLast -> findLastIndex
Simplify Contains
* List<T>
Removed m_allocator (wasn't used)
Swap -> swapElements
Sort -> sort
Contains -> contains
ForEach -> forEach
QuickSort -> quickSort
InsertionSort -> insertionSort
BinarySearch -> binarySearch
Max -> calcMax
Min -> calcMin
* Initializer::Initialize -> initialize
List<T>::
Allocate -> _allocate
Init -> _init
IndexOf -> indexOf
* * Put #include <assert.h> in common.h, and remove unneeded inclusions
* Small refactor of ArrayView - remove stride as not used
* getSize -> getCount
setSize -> setCount
unsafeShrinkToSize->unsafeShrinkToCount
growToSize -> growToCount
m_size -> m_count
* Some tidy up around Allocator.
* Use Index type on List.
* Refactor of IntSet.
First tentative look at using Index.
* Made Index an Int
Did preliminary fixes.
Made String use Index.
* Partial refactor of String.
* String::Buffer -> getBuffer
ToWString -> toWString
* Small improvements to String.
String::
Buffer() -> getBuffer()
Equals() -> equals
* Try to use Index where appropriate.
* Fix warnings on windows x86 builds.
Diffstat (limited to 'source')
77 files changed, 1871 insertions, 1869 deletions
diff --git a/source/core/allocator.h b/source/core/allocator.h index 3306d3780..5832d0b84 100644 --- a/source/core/allocator.h +++ b/source/core/allocator.h @@ -8,7 +8,7 @@ namespace Slang { - inline void * AlignedAlloc(size_t size, size_t alignment) + inline void* alignedAllocate(size_t size, size_t alignment) { #ifdef _MSC_VER return _aligned_malloc(size, alignment); @@ -23,7 +23,7 @@ namespace Slang #endif } - inline void AlignedFree(void * ptr) + inline void alignedDeallocate(void* ptr) { #ifdef _MSC_VER _aligned_free(ptr); @@ -36,29 +36,29 @@ namespace Slang { public: // not really called - void * Alloc(size_t size) + void* allocate(size_t size) { - return malloc(size); + return ::malloc(size); } - void Free(void * ptr) + void deallocate(void * ptr) { - return free(ptr); + return ::free(ptr); } }; - template<int alignment> + template<int ALIGNMENT> class AlignedAllocator { public: - void * Alloc(size_t size) + void* allocate(size_t size) { - return AlignedAlloc(size, alignment); + return alignedAllocate(size, ALIGNMENT); } - void Free(void * ptr) + void deallocate(void * ptr) { - return AlignedFree(ptr); + return alignedDeallocate(ptr); } }; } -#endif
\ No newline at end of file +#endif diff --git a/source/core/array-view.h b/source/core/array-view.h index 193aedbbb..ad9673e2e 100644 --- a/source/core/array-view.h +++ b/source/core/array-view.h @@ -1,7 +1,7 @@ #ifndef CORE_LIB_ARRAY_VIEW_H #define CORE_LIB_ARRAY_VIEW_H -#include "exception.h" +#include "common.h" namespace Slang { @@ -9,104 +9,87 @@ namespace Slang class ArrayView { private: - T * _buffer; - int _count; - int stride; + T* m_buffer; + int m_count; public: - T* begin() const - { - return _buffer; - } - T* end() const - { - return (T*)((char*)_buffer + _count*stride); - } + const T* begin() const { return m_buffer; } + T* begin() { return m_buffer; } + + const T* end() const { return m_buffer + m_count; } + T* end() { return m_buffer + m_count; } + public: - ArrayView() - { - _buffer = 0; - _count = 0; - } - ArrayView(const T & singleObj) - { - SetData((T*)&singleObj, 1, sizeof(T)); - } - ArrayView(T * buffer, int count) - { - SetData(buffer, count, sizeof(T)); + ArrayView(): + m_buffer(nullptr), + m_count(0) + { } - ArrayView(void * buffer, int count, int _stride) - { - SetData(buffer, count, _stride); - } - void SetData(void * buffer, int count, int _stride) - { - this->_buffer = (T*)buffer; - this->_count = count; - this->stride = _stride; - } - inline int GetCapacity() const - { - return _count; + ArrayView(T& singleObj): + m_buffer(&singleObj), + m_count(1) + { } - inline int Count() const + ArrayView(T* buffer, int size): + m_buffer(buffer), + m_count(size) { - return _count; } + + inline int getCount() const { return m_count; } - inline T & operator [](int id) const + inline const T& operator [](int idx) const { -#if _DEBUG - if (id >= _count || id < 0) - throw IndexOutofRangeException("Operator[]: Index out of Range."); -#endif - return *(T*)((char*)_buffer+id*stride); + SLANG_ASSERT(idx >= 0 && idx <= m_count); + return m_buffer[idx]; } + inline T& operator [](int idx) + { + SLANG_ASSERT(idx >= 0 && idx <= m_count); + return m_buffer[idx]; + } - inline T* Buffer() const - { - return _buffer; - } + inline const T* getBuffer() const { return m_buffer; } + inline T* getBuffer() { return m_buffer; } template<typename T2> - int IndexOf(const T2 & val) const + int indexOf(const T2 & val) const { - for (int i = 0; i < _count; i++) + for (int i = 0; i < m_count; i++) { - if (*(T*)((char*)_buffer + i*stride) == val) + if (m_buffer[i] == val) return i; } return -1; } template<typename T2> - int LastIndexOf(const T2 & val) const + int lastIndexOf(const T2 & val) const { - for (int i = _count - 1; i >= 0; i--) + for (int i = m_count - 1; i >= 0; i--) { - if (*(T*)((char*)_buffer + i*stride) == val) + if (m_buffer[i] == val) return i; } return -1; } template<typename Func> - int FindFirst(const Func & predicate) const + int findFirstIndex(const Func& predicate) const { - for (int i = 0; i < _count; i++) + for (int i = 0; i < m_count; i++) { - if (predicate(_buffer[i])) + if (predicate(m_buffer[i])) return i; } return -1; } template<typename Func> - int FindLast(const Func & predicate) const + int findLastIndex(const Func& predicate) const { - for (int i = _count - 1; i >= 0; i--) + for (int i = m_count - 1; i >= 0; i--) { - if (predicate(_buffer[i])) + if (predicate(m_buffer[i])) return i; } return -1; @@ -114,16 +97,16 @@ namespace Slang }; template<typename T> - ArrayView<T> MakeArrayView(const T & obj) + ArrayView<T> makeArrayView(T& obj) { return ArrayView<T>(obj); } template<typename T> - ArrayView<T> MakeArrayView(T * buffer, int count) + ArrayView<T> makeArrayView(T* buffer, int count) { return ArrayView<T>(buffer, count); } } -#endif
\ No newline at end of file +#endif diff --git a/source/core/array.h b/source/core/array.h index 96508879f..2a5fa0aa7 100644 --- a/source/core/array.h +++ b/source/core/array.h @@ -6,138 +6,130 @@ namespace Slang { - template<typename T, int size> + template<typename T, int COUNT> class Array { private: - T _buffer[size]; - int _count = 0; + T m_buffer[COUNT]; + int m_count = 0; public: - T* begin() const - { - return (T*)_buffer; - } - T* end() const - { - return (T*)_buffer + _count; - } + T* begin() { return m_buffer; } + const T* begin() const { return m_buffer; } + + const T* end() const { return m_buffer + m_count; } + T* end() { return m_buffer + m_count; } + public: - inline int GetCapacity() const + inline int getCapacity() const { return COUNT; } + inline int getCount() const { return m_count; } + inline const T& getFirst() const { - return size; + SLANG_ASSERT(m_count > 0); + return m_buffer[0]; } - inline int Count() const + inline T& getFirst() + { + SLANG_ASSERT(m_count > 0); + return m_buffer[0]; + } + inline const T& getLast() const { - return _count; + SLANG_ASSERT(m_count > 0); + return m_buffer[m_count - 1]; } - inline T & First() const + inline T& getLast() + { + SLANG_ASSERT(m_count > 0); + return m_buffer[m_count - 1]; + } + inline void setCount(int newCount) { - return const_cast<T&>(_buffer[0]); + SLANG_ASSERT(newCount >= 0 && newCount <= COUNT); + m_count = newCount; } - inline T & Last() const + inline void add(const T & item) { - return const_cast<T&>(_buffer[_count - 1]); + SLANG_ASSERT(m_count < COUNT); + m_buffer[m_count++] = item; } - inline void SetSize(int newSize) + inline void add(T && item) { -#ifdef _DEBUG - if (newSize > size) - throw IndexOutofRangeException("size too large."); -#endif - _count = newSize; - } - inline void Add(const T & item) - { -#ifdef _DEBUG - if (_count == size) - throw IndexOutofRangeException("out of range access to static array."); -#endif - _buffer[_count++] = item; - } - inline void Add(T && item) - { -#ifdef _DEBUG - if (_count == size) - throw IndexOutofRangeException("out of range access to static array."); -#endif - _buffer[_count++] = _Move(item); + SLANG_ASSERT(m_count < COUNT); + m_buffer[m_count++] = _Move(item); } - inline T & operator [](int id) const + inline const T& operator [](int idx) const { -#if _DEBUG - if (id >= _count || id < 0) - throw IndexOutofRangeException("Operator[]: Index out of Range."); -#endif - return ((T*)_buffer)[id]; + SLANG_ASSERT(idx >= 0 && idx < m_count); + return m_buffer[idx]; } + inline T& operator [](int idx) + { + SLANG_ASSERT(idx >= 0 && idx < m_count); + return m_buffer[idx]; + } - inline T* Buffer() const - { - return (T*)_buffer; - } + inline const T* getBuffer() const { return m_buffer; } + inline T* getBuffer() { return m_buffer; } - inline void Clear() - { - _count = 0; - } + inline void clear() { m_count = 0; } template<typename T2> - int IndexOf(const T2 & val) const + int indexOf(const T2& val) const { - for (int i = 0; i < _count; i++) + for (int i = 0; i < m_count; i++) { - if (_buffer[i] == val) + if (m_buffer[i] == val) return i; } return -1; } template<typename T2> - int LastIndexOf(const T2 & val) const + int lastIndexOf(const T2& val) const { - for (int i = _count - 1; i >= 0; i--) + for (int i = m_count - 1; i >= 0; i--) { - if (_buffer[i] == val) + if (m_buffer[i] == val) return i; } return -1; } - inline ArrayView<T> GetArrayView() const + inline ArrayView<T> getArrayView() const { - return ArrayView<T>((T*)_buffer, _count); + return ArrayView<T>((T*)m_buffer, m_count); } - inline ArrayView<T> GetArrayView(int start, int count) const + inline ArrayView<T> getArrayView(int start, int count) const { - return ArrayView<T>((T*)_buffer + start, count); + return ArrayView<T>((T*)m_buffer + start, count); } }; template<typename T, typename ...TArgs> struct FirstType { - typedef T type; + typedef T Type; }; - template<typename T, int size> - void InsertArray(Array<T, size> &) {} + template<typename T, int SIZE> + void insertArray(Array<T, SIZE>&) {} - template<typename T, typename ...TArgs, int size> - void InsertArray(Array<T, size> & arr, const T & val, TArgs... args) + template<typename T, typename ...TArgs, int SIZE> + void insertArray(Array<T, SIZE>& arr, const T& val, TArgs... args) { - arr.Add(val); - InsertArray(arr, args...); + arr.add(val); + insertArray(arr, args...); } template<typename ...TArgs> - auto MakeArray(TArgs ...args) -> Array<typename FirstType<TArgs...>::type, sizeof...(args)> + auto makeArray(TArgs ...args) -> Array<typename FirstType<TArgs...>::Type, sizeof...(args)> { - Array<typename FirstType<TArgs...>::type, sizeof...(args)> rs; - InsertArray(rs, args...); + Array<typename FirstType<TArgs...>::Type, sizeof...(args)> rs; + insertArray(rs, args...); return rs; } } -#endif
\ No newline at end of file +#endif diff --git a/source/core/common.h b/source/core/common.h index ba7cd9836..0e5396caf 100644 --- a/source/core/common.h +++ b/source/core/common.h @@ -3,6 +3,8 @@ #include "../../slang.h" +#include <assert.h> + #include <cstdint> #ifdef __GNUC__ @@ -29,6 +31,9 @@ namespace Slang typedef intptr_t PtrInt; + // Type used for indexing, in arrays/views etc + typedef Int Index; + template <typename T> inline T&& _Move(T & obj) { diff --git a/source/core/dictionary.h b/source/core/dictionary.h index 6d97bc2b3..a38699368 100644 --- a/source/core/dictionary.h +++ b/source/core/dictionary.h @@ -91,25 +91,25 @@ namespace Slang } inline bool IsDeleted(int pos) const { - return marks.Contains((pos << 1) + 1); + return marks.contains((pos << 1) + 1); } inline bool IsEmpty(int pos) const { - return !marks.Contains((pos << 1)); + return !marks.contains((pos << 1)); } inline void SetDeleted(int pos, bool val) { if (val) - marks.Add((pos << 1) + 1); + marks.add((pos << 1) + 1); else - marks.Remove((pos << 1) + 1); + marks.remove((pos << 1) + 1); } inline void SetEmpty(int pos, bool val) { if (val) - marks.Remove((pos << 1)); + marks.remove((pos << 1)); else - marks.Add((pos << 1)); + marks.add((pos << 1)); } struct FindPositionResult { @@ -180,7 +180,7 @@ namespace Slang Dictionary<TKey, TValue> newDict; newDict.bucketSizeMinusOne = newSize - 1; newDict.hashMap = new KeyValuePair<TKey, TValue>[newSize]; - newDict.marks.SetMax(newSize * 2); + newDict.marks.setMax(newSize * 2); if (hashMap) { for (auto & kvPair : *this) @@ -326,7 +326,7 @@ namespace Slang { _count = 0; - marks.Clear(); + marks.clear(); } TValue* TryGetValueOrAdd(const TKey& key, const TValue& value) diff --git a/source/core/int-set.h b/source/core/int-set.h index 6b6f5e7a8..6b6243552 100644 --- a/source/core/int-set.h +++ b/source/core/int-set.h @@ -10,154 +10,200 @@ namespace Slang { + /* The set works by storing as a bit per integer */ class IntSet { private: - List<int> buffer; + typedef uint32_t Element; ///< Type that holds the bits + enum + { + ELEMENT_SHIFT = 5, ///< How many bits to shift to get Element index from an index + ELEMENT_SIZE = sizeof(Element) * 8, ///< The number of bits in an element + ELEMENT_MASK = ELEMENT_SIZE - 1, ///< Mask to get shift from an index + }; + + // Make sure they are correct for the Element type + SLANG_COMPILE_TIME_ASSERT( (1 << ELEMENT_SHIFT) == ELEMENT_SIZE); + + List<Element> m_buffer; + public: IntSet() {} - IntSet(const IntSet & other) + IntSet(const IntSet& other) { - buffer = other.buffer; + m_buffer = other.m_buffer; } IntSet(IntSet && other) { *this = (_Move(other)); } - IntSet & operator = (IntSet && other) + IntSet& operator=(IntSet&& other) { - buffer = _Move(other.buffer); + m_buffer = _Move(other.m_buffer); return *this; } - IntSet & operator = (const IntSet & other) + IntSet& operator=(const IntSet& other) { - buffer = other.buffer; + m_buffer = other.m_buffer; return *this; } int GetHashCode() { int rs = 0; - for (auto val : buffer) + for (auto val : m_buffer) rs ^= val; return rs; } - IntSet(int maxVal) + IntSet(Int maxVal) { - SetMax(maxVal); + setMax(maxVal); } - UInt Size() const + Int getCount() const { - return buffer.Count()*32; + return Int(m_buffer.getCount()) * ELEMENT_SIZE; } - void SetMax(int val) + void setMax(Int val) { - Resize(val); - Clear(); + resize(val); + clear(); } - void SetAll() + void setAll() { - for (UInt i = 0; i<buffer.Count(); i++) - buffer[i] = 0xFFFFFFFF; + for (Index i = 0; i < m_buffer.getCount(); i++) + m_buffer[i] = ~Element(0); } - void Resize(UInt size) + void resize(Int size) { - UInt oldBufferSize = buffer.Count(); - buffer.SetSize((size+31)>>5); - if (buffer.Count() > oldBufferSize) - memset(buffer.Buffer()+oldBufferSize, 0, (buffer.Count()-oldBufferSize) * sizeof(int)); + const Index oldBufferSize = m_buffer.getCount(); + const Index newCount = Index((size + ELEMENT_MASK) >> ELEMENT_SHIFT); + m_buffer.setCount(newCount); + + if (newCount > oldBufferSize) + memset(m_buffer.getBuffer() + oldBufferSize, 0, (newCount - oldBufferSize) * sizeof(Element)); } - void Clear() + void clear() { - for (UInt i = 0; i<buffer.Count(); i++) - buffer[i] = 0; + for (Index i = 0; i < m_buffer.getCount(); i++) + m_buffer[i] = 0; } - void Add(UInt val) + void clearAndDeallocate() + { + m_buffer.clearAndDeallocate(); + } + void add(Int val) { - UInt id = val>>5; - if (id < buffer.Count()) - buffer[id] |= (1<<(val&31)); + Index id = Index(val >> 5); + if (id < m_buffer.getCount()) + m_buffer[id] |= Element(1) << (val & ELEMENT_MASK); else { - UInt oldSize = buffer.Count(); - buffer.SetSize(id+1); - memset(buffer.Buffer() + oldSize, 0, (buffer.Count()-oldSize)*sizeof(int)); - buffer[id] |= (1<<(val&31)); + Index oldCount = m_buffer.getCount(); + m_buffer.setCount(id + 1); + memset(m_buffer.getBuffer() + oldCount, 0, (m_buffer.getCount() - oldCount) * sizeof(Element)); + m_buffer[id] |= Element(1) << (val & ELEMENT_MASK); } } - void Remove(UInt val) + void remove(Int val) { - if ((val>>5) < buffer.Count()) - buffer[(val>>5)] &= ~(1<<(val&31)); + const Index idx = Index(val >> ELEMENT_SHIFT); + if (idx < m_buffer.getCount()) + m_buffer[idx] &= ~(Element(1) << (val & ELEMENT_MASK)); } - bool Contains(UInt val) const + bool contains(Int val) const { - if ((val>>5) >= buffer.Count()) + const Index idx = Index(val >> ELEMENT_SHIFT); + if (idx >= m_buffer.getCount()) return false; - return (buffer[(val>>5)] & (1<<(val&31))) != 0; + return (m_buffer[idx] & (Element(1) << (val & ELEMENT_MASK))) != 0; } - void UnionWith(const IntSet & set) + void unionWith(const IntSet& set) { - for (UInt i = 0; i<Math::Min(set.buffer.Count(), buffer.Count()); i++) + const Index minCount = Math::Min(set.m_buffer.getCount(), m_buffer.getCount()); + for (Index i = 0; i < minCount; i++) { - buffer[i] |= set.buffer[i]; + m_buffer[i] |= set.m_buffer[i]; } - if (set.buffer.Count() > buffer.Count()) - buffer.AddRange(set.buffer.Buffer()+buffer.Count(), set.buffer.Count()-buffer.Count()); + if (set.m_buffer.getCount() > m_buffer.getCount()) + m_buffer.addRange(set.m_buffer.getBuffer()+m_buffer.getCount(), set.m_buffer.getCount()-m_buffer.getCount()); } - bool operator == (const IntSet & set) + bool operator==(const IntSet& set) const { - if (buffer.Count() != set.buffer.Count()) - return false; - for (UInt i = 0; i<buffer.Count(); i++) - if (buffer[i] != set.buffer[i]) - return false; - return true; + Index minCount = Math::Min(set.m_buffer.getCount(), m_buffer.getCount()); + if (::memcmp(m_buffer.getBuffer(), set.m_buffer.getBuffer(), minCount * sizeof(Element)) != 0) + { + return false; + } + return m_buffer.getCount() == set.m_buffer.getCount() || (_areRemainingZeros(m_buffer, minCount) && _areRemainingZeros(set.m_buffer, minCount)); } - bool operator != (const IntSet & set) + bool operator!=(const IntSet& set) const { return !(*this == set); } - void IntersectWith(const IntSet & set) + void intersectWith(const IntSet& set) { - if (set.buffer.Count() < buffer.Count()) - memset(buffer.Buffer() + set.buffer.Count(), 0, (buffer.Count()-set.buffer.Count())*sizeof(int)); - for (UInt i = 0; i<Math::Min(set.buffer.Count(), buffer.Count()); i++) + if (set.m_buffer.getCount() < m_buffer.getCount()) + memset(m_buffer.getBuffer() + set.m_buffer.getCount(), 0, (m_buffer.getCount() - set.m_buffer.getCount()) * sizeof(Element)); + + const Index minCount = Math::Min(set.m_buffer.getCount(), m_buffer.getCount()); + for (Index i = 0; i < minCount; i++) { - buffer[i] &= set.buffer[i]; + m_buffer[i] &= set.m_buffer[i]; } } - static void Union(IntSet & rs, const IntSet & set1, const IntSet & set2) + static void calcUnion(IntSet& outRs, const IntSet& set1, const IntSet& set2) { - rs.buffer.SetSize(Math::Max(set1.buffer.Count(), set2.buffer.Count())); - rs.Clear(); - for (UInt i = 0; i<set1.buffer.Count(); i++) - rs.buffer[i] |= set1.buffer[i]; - for (UInt i = 0; i<set2.buffer.Count(); i++) - rs.buffer[i] |= set2.buffer[i]; + outRs.m_buffer.setCount(Math::Max(set1.m_buffer.getCount(), set2.m_buffer.getCount())); + outRs.clear(); + for (Index i = 0; i < set1.m_buffer.getCount(); i++) + outRs.m_buffer[i] |= set1.m_buffer[i]; + for (Index i = 0; i < set2.m_buffer.getCount(); i++) + outRs.m_buffer[i] |= set2.m_buffer[i]; } - static void Intersect(IntSet & rs, const IntSet & set1, const IntSet & set2) + static void calcIntersection(IntSet& outRs, const IntSet& set1, const IntSet& set2) { - rs.buffer.SetSize(Math::Min(set1.buffer.Count(), set2.buffer.Count())); - for (UInt i = 0; i<rs.buffer.Count(); i++) - rs.buffer[i] = set1.buffer[i] & set2.buffer[i]; + const Index minCount = Math::Min(set1.m_buffer.getCount(), set2.m_buffer.getCount()); + outRs.m_buffer.setCount(minCount); + + for (Index i = 0; i < minCount; i++) + outRs.m_buffer[i] = set1.m_buffer[i] & set2.m_buffer[i]; } - static void Subtract(IntSet & rs, const IntSet & set1, const IntSet & set2) + static void calcSubtract(IntSet& outRs, const IntSet& set1, const IntSet& set2) { - rs.buffer.SetSize(set1.buffer.Count()); - for (UInt i = 0; i<Math::Min(set1.buffer.Count(), set2.buffer.Count()); i++) - rs.buffer[i] = set1.buffer[i] & (~set2.buffer[i]); + outRs.m_buffer.setCount(set1.m_buffer.getCount()); + + const Index minCount = Math::Min(set1.m_buffer.getCount(), set2.m_buffer.getCount()); + for (Index i = 0; i < minCount; i++) + outRs.m_buffer[i] = set1.m_buffer[i] & (~set2.m_buffer[i]); } - static bool HasIntersection(const IntSet & set1, const IntSet & set2) + static bool hasIntersection(const IntSet& set1, const IntSet& set2) { - for (UInt i = 0; i<Math::Min(set1.buffer.Count(), set2.buffer.Count()); i++) + const Index minCount = Math::Min(set1.m_buffer.getCount(), set2.m_buffer.getCount()); + for (Index i = 0; i < minCount; i++) { - if (set1.buffer[i] & set2.buffer[i]) + if (set1.m_buffer[i] & set2.m_buffer[i]) return true; } return false; } + + private: + static bool _areRemainingZeros(const List<Element>& elems, Index minCount) + { + const Index count = elems.getCount(); + const Element* base = elems.getBuffer(); + + for (Index i = minCount; i < count; ++i) + { + if (base[i]) + { + return false; + } + } + return true; + } + }; } -#endif
\ No newline at end of file +#endif diff --git a/source/core/list.h b/source/core/list.h index 11d798dcf..7ba313305 100644 --- a/source/core/list.h +++ b/source/core/list.h @@ -1,4 +1,4 @@ -#ifndef FUNDAMENTAL_LIB_LIST_H +#ifndef FUNDAMENTAL_LIB_LIST_H #define FUNDAMENTAL_LIB_LIST_H #include "../../slang.h" @@ -11,10 +11,10 @@ #include <new> #include <type_traits> -const int MIN_QSORT_SIZE = 32; namespace Slang { + template<typename T, int isPOD> class Initializer { @@ -25,7 +25,7 @@ namespace Slang class Initializer<T, 0> { public: - static void Initialize(T * buffer, int size) + static void initialize(T* buffer, int size) { for (int i = 0; i<size; i++) new (buffer + i) T(); @@ -35,7 +35,7 @@ namespace Slang class Initializer<T, 1> { public: - static void Initialize(T * buffer, int size) + static void initialize(T* buffer, int size) { // It's pod so no initialization required //for (int i = 0; i < size; i++) @@ -47,22 +47,22 @@ namespace Slang class AllocateMethod { public: - static inline T* Alloc(UInt size) + static inline T* allocateArray(Index count) { TAllocator allocator; - T * rs = (T*)allocator.Alloc(size*sizeof(T)); - Initializer<T, std::is_pod<T>::value>::Initialize(rs, size); + T * rs = (T*)allocator.allocate(count * sizeof(T)); + Initializer<T, std::is_pod<T>::value>::initialize(rs, count); return rs; } - static inline void Free(T * ptr, UInt bufferSize) + static inline void deallocateArray(T* ptr, Index count) { TAllocator allocator; if (!std::is_trivially_destructible<T>::value) { - for (UInt i = 0; i<bufferSize; i++) + for (Index i = 0; i < count; i++) ptr[i].~T(); } - allocator.Free(ptr); + allocator.deallocate(ptr); } }; @@ -70,11 +70,11 @@ namespace Slang class AllocateMethod<T, StandardAllocator> { public: - static inline T* Alloc(UInt size) + static inline T* allocateArray(Index count) { - return new T[size]; + return new T[count]; } - static inline void Free(T* ptr, UInt /*bufferSize*/) + static inline void deallocateArray(T* ptr, Index /*bufferSize*/) { delete [] ptr; } @@ -84,226 +84,177 @@ namespace Slang template<typename T, typename TAllocator = StandardAllocator> class List { - private: + private: + static const Index kInitialCount = 16; - inline T * Allocate(UInt size) - { - return AllocateMethod<T, TAllocator>::Alloc(size); - - } - private: - static const int InitialSize = 16; - TAllocator allocator; - private: - T* buffer; - UInt _count; - UInt bufferSize; - void FreeBuffer() - { - AllocateMethod<T, TAllocator>::Free(buffer, bufferSize); - buffer = 0; - } - void Free() - { - if (buffer) - { - FreeBuffer(); - } - buffer = 0; - _count = bufferSize = 0; - } - public: - T* begin() const - { - return buffer; - } - T* end() const - { - return buffer+_count; - } - private: - template<typename... Args> - void Init(const T & val, Args... args) - { - Add(val); - Init(args...); - } public: List() - : buffer(0), _count(0), bufferSize(0) + : m_buffer(nullptr), m_count(0), m_capacity(0) { } template<typename... Args> - List(const T & val, Args... args) + List(const T& val, Args... args) { - Init(val, args...); + _init(val, args...); } - List(const List<T> & list) - : buffer(0), _count(0), bufferSize(0) + List(const List<T>& list) + : m_buffer(nullptr), m_count(0), m_capacity(0) { this->operator=(list); } - List(List<T> && list) - : buffer(0), _count(0), bufferSize(0) + List(List<T>&& list) + : m_buffer(nullptr), m_count(0), m_capacity(0) { this->operator=(static_cast<List<T>&&>(list)); } - static List<T> Create(const T & val, int count) + static List<T> makeRepeated(const T& val, Index count) { List<T> rs; - rs.SetSize(count); - for (int i = 0; i < count; i++) + rs.setCount(count); + for (Index i = 0; i < count; i++) rs[i] = val; return rs; } ~List() { - Free(); + _deallocateBuffer(); } - List<T> & operator=(const List<T> & list) + List<T>& operator=(const List<T>& list) { - Free(); - AddRange(list); - + clearAndDeallocate(); + addRange(list); return *this; } - List<T> & operator=(List<T> && list) + List<T>& operator=(List<T>&& list) { - Free(); - _count = list._count; - bufferSize = list.bufferSize; - buffer = list.buffer; + // Could just do a swap here, and memory would be freed on rhs dtor + + _deallocateBuffer(); + m_count = list.m_count; + m_capacity = list.m_capacity; + m_buffer = list.m_buffer; - list.buffer = 0; - list._count = 0; - list.bufferSize = 0; + list.m_buffer = nullptr; + list.m_count = 0; + list.m_capacity = 0; return *this; } - T & First() const + // TODO(JS): These should be made const safe but some other code depends on this behavior for now. + T* begin() const { return m_buffer; } + T* end() const { return m_buffer + m_count; } + + const T& getFirst() const { -#ifdef _DEBUG - if (_count == 0) - throw "Index out of range."; -#endif - return buffer[0]; + SLANG_ASSERT(m_count > 0); + return m_buffer[0]; } - T & Last() const + const T& getLast() const { -#ifdef _DEBUG - if (_count == 0) - throw "Index out of range."; -#endif - return buffer[_count-1]; + SLANG_ASSERT(m_count > 0); + return m_buffer[m_count-1]; } - void RemoveLast() + T& getFirst() + { + SLANG_ASSERT(m_count > 0); + return m_buffer[0]; + } + + T& getLast() + { + SLANG_ASSERT(m_count > 0); + return m_buffer[m_count - 1]; + } + + void removeLast() { -#ifdef _DEBUG - if (_count == 0) - throw "Index out of range."; -#endif - _count--; + SLANG_ASSERT(m_count > 0); + m_count--; } - inline void SwapWith(List<T, TAllocator> & other) + inline void swapWith(List<T, TAllocator>& other) { - T* tmpBuffer = this->buffer; - this->buffer = other.buffer; - other.buffer = tmpBuffer; - auto tmpBufferSize = this->bufferSize; - this->bufferSize = other.bufferSize; - other.bufferSize = tmpBufferSize; - auto tmpCount = this->_count; - this->_count = other._count; - other._count = tmpCount; - TAllocator tmpAlloc = _Move(this->allocator); - this->allocator = _Move(other.allocator); - other.allocator = _Move(tmpAlloc); + T* buffer = m_buffer; + m_buffer = other.m_buffer; + other.m_buffer = buffer; + + auto bufferSize = m_capacity; + m_capacity = other.m_capacity; + other.m_capacity = bufferSize; + + auto count = m_count; + m_count = other.m_count; + other.m_count = count; } - T* ReleaseBuffer() + T* detachBuffer() { - T* rs = buffer; - buffer = nullptr; - _count = 0; - bufferSize = 0; + T* rs = m_buffer; + m_buffer = nullptr; + m_count = 0; + m_capacity = 0; return rs; } - inline ArrayView<T> GetArrayView() const + inline ArrayView<T> getArrayView() const { - return ArrayView<T>(buffer, _count); + return ArrayView<T>(m_buffer, m_count); } - inline ArrayView<T> GetArrayView(int start, int count) const + inline ArrayView<T> getArrayView(Index start, Index count) const { -#ifdef _DEBUG - if (start + count > _count || start < 0 || count < 0) - throw "Index out of range."; -#endif - return ArrayView<T>(buffer + start, count); + SLANG_ASSERT(start >= 0 && count >= 0 && start + count <= m_count); + return ArrayView<T>(m_buffer + start, count); } - void Add(T && obj) + void add(T&& obj) { - if (bufferSize < _count + 1) + if (m_capacity < m_count + 1) { - UInt newBufferSize = InitialSize; - if (bufferSize) - newBufferSize = (bufferSize << 1); + Index newBufferSize = kInitialCount; + if (m_capacity) + newBufferSize = (m_capacity << 1); - Reserve(newBufferSize); + reserve(newBufferSize); } - buffer[_count++] = static_cast<T&&>(obj); + m_buffer[m_count++] = static_cast<T&&>(obj); } - void Add(const T & obj) + void add(const T& obj) { - if (bufferSize < _count + 1) + if (m_capacity < m_count + 1) { - UInt newBufferSize = InitialSize; - if (bufferSize) - newBufferSize = (bufferSize << 1); + Index newBufferSize = kInitialCount; + if (m_capacity) + newBufferSize = (m_capacity << 1); - Reserve(newBufferSize); + reserve(newBufferSize); } - buffer[_count++] = obj; + m_buffer[m_count++] = obj; } - UInt Count() const - { - return _count; - } + Index getCount() const { return m_count; } + Index getCapacity() const { return m_capacity; } - T * Buffer() const - { - return buffer; - } + const T* getBuffer() const { return m_buffer; } + T* getBuffer() { return m_buffer; } - UInt Capacity() const - { - return bufferSize; - } + void insert(Index idx, const T& val) { insertRange(idx, &val, 1); } - void Insert(UInt id, const T & val) + void insertRange(Index idx, const T* vals, Index n) { - InsertRange(id, &val, 1); - } - - void InsertRange(UInt id, const T * vals, UInt n) - { - if (bufferSize < _count + n) + if (m_capacity < m_count + n) { - UInt newBufferSize = InitialSize; - while (newBufferSize < _count + n) - newBufferSize = newBufferSize << 1; + Index newBufferCount = kInitialCount; + while (newBufferCount < m_count + n) + newBufferCount = newBufferCount << 1; - T * newBuffer = Allocate(newBufferSize); - if (bufferSize) + T* newBuffer = _allocate(newBufferCount); + if (m_capacity) { /*if (std::has_trivial_copy_assign<T>::value && std::has_trivial_destructor<T>::value) { @@ -312,15 +263,15 @@ namespace Slang } else*/ { - for (UInt i = 0; i < id; i++) - newBuffer[i] = buffer[i]; - for (UInt i = id; i < _count; i++) - newBuffer[i + n] = T(static_cast<T&&>(buffer[i])); + for (Index i = 0; i < idx; i++) + newBuffer[i] = m_buffer[i]; + for (Index i = idx; i < m_count; i++) + newBuffer[i + n] = T(static_cast<T&&>(m_buffer[i])); } - FreeBuffer(); + _deallocateBuffer(); } - buffer = newBuffer; - bufferSize = newBufferSize; + m_buffer = newBuffer; + m_capacity = newBufferCount; } else { @@ -328,17 +279,17 @@ namespace Slang memmove(buffer + id + n, buffer + id, sizeof(T) * (_count - id)); else*/ { - for (UInt i = _count; i > id; i--) - buffer[i + n - 1] = static_cast<T&&>(buffer[i - 1]); + for (Index i = m_count; i > idx; i--) + m_buffer[i + n - 1] = static_cast<T&&>(m_buffer[i - 1]); } } /*if (std::has_trivial_copy_assign<T>::value && std::has_trivial_destructor<T>::value) memcpy(buffer + id, vals, sizeof(T) * n); else*/ - for (UInt i = 0; i < n; i++) - buffer[id + i] = vals[i]; + for (Index i = 0; i < n; i++) + m_buffer[idx + i] = vals[i]; - _count += n; + m_count += n; } //slower than original edition @@ -347,261 +298,238 @@ namespace Slang // InsertRange(_count, &val, 1); //} - void InsertRange(int id, const List<T> & list) - { - InsertRange(id, list.buffer, list._count); - } + void insertRange(Index id, const List<T>& list) { insertRange(id, list.m_buffer, list.m_count); } - void AddRange(ArrayView<T> list) - { - InsertRange(_count, list.Buffer(), list.Count()); - } + void addRange(ArrayView<T> list) { insertRange(m_count, list.getBuffer(), list.Count()); } - void AddRange(const T * vals, UInt n) - { - InsertRange(_count, vals, n); - } + void addRange(const T* vals, Index n) { insertRange(m_count, vals, n); } - void AddRange(const List<T> & list) - { - InsertRange(_count, list.buffer, list._count); - } + void addRange(const List<T>& list) { insertRange(m_count, list.m_buffer, list.m_count); } - void RemoveRange(UInt id, UInt deleteCount) + void removeRange(Index idx, Index count) { -#if _DEBUG - if (id >= _count) - throw "Remove: Index out of range."; -#endif - UInt actualDeleteCount = ((id + deleteCount) >= _count)? (_count - id) : deleteCount; - for (UInt i = id + actualDeleteCount; i < _count; i++) - buffer[i - actualDeleteCount] = static_cast<T&&>(buffer[i]); - _count -= actualDeleteCount; - } + SLANG_ASSERT(idx >= 0 && idx <= m_count); - void RemoveAt(UInt id) - { - RemoveRange(id, 1); + const Index actualDeleteCount = ((idx + count) >= m_count)? (m_count - idx) : count; + for (Index i = idx + actualDeleteCount; i < m_count; i++) + m_buffer[i - actualDeleteCount] = static_cast<T&&>(m_buffer[i]); + m_count -= actualDeleteCount; } - void Remove(const T & val) + void removeAt(Index id) { removeRange(id, 1); } + + void remove(const T& val) { - int idx = IndexOf(val); + Index idx = indexOf(val); if (idx != -1) - RemoveAt(idx); + removeAt(idx); } - void Reverse() + void reverse() { - for (UInt i = 0; i < (_count >> 1); i++) + for (Index i = 0; i < (m_count >> 1); i++) { - Swap(buffer, i, _count - i - 1); + swapElements(m_buffer, i, m_count - i - 1); } } - void FastRemove(const T & val) + void fastRemove(const T& val) { - int idx = IndexOf(val); - FastRemoveAt(idx); + Index idx = indexOf(val); + fastRemoveAt(idx); } - void FastRemoveAt(UInt idx) + void fastRemoveAt(Index idx) { - if (idx != -1 && _count - 1 != idx) + if (idx != -1 && m_count - 1 != idx) { - buffer[idx] = _Move(buffer[_count - 1]); + m_buffer[idx] = _Move(m_buffer[m_count - 1]); } - _count--; + m_count--; } - void Clear() - { - _count = 0; - } + void clear() { m_count = 0; } - void Reserve(UInt size) + void clearAndDeallocate() + { + _deallocateBuffer(); + m_count = m_capacity = 0; + } + + void reserve(Index size) { - if(size > bufferSize) + if(size > m_capacity) { - T * newBuffer = Allocate(size); - if (bufferSize) + T* newBuffer = _allocate(size); + if (m_capacity) { /*if (std::has_trivial_copy_assign<T>::value && std::has_trivial_destructor<T>::value) memcpy(newBuffer, buffer, _count * sizeof(T)); else*/ { - for (UInt i = 0; i < _count; i++) - newBuffer[i] = static_cast<T&&>(buffer[i]); + for (Index i = 0; i < m_count; i++) + newBuffer[i] = static_cast<T&&>(m_buffer[i]); // Default-initialize the remaining elements - for(UInt i = _count; i < size; i++) + for(Index i = m_count; i < size; i++) { new(newBuffer + i) T(); } } - FreeBuffer(); + _deallocateBuffer(); } - buffer = newBuffer; - bufferSize = size; + m_buffer = newBuffer; + m_capacity = size; } } - void GrowToSize(UInt size) + void growToCount(Index count) { - UInt newBufferSize = UInt(1) << Math::Log2Ceil(size); - if (bufferSize < newBufferSize) + Index newBufferCount = Index(1) << Math::Log2Ceil(count); + if (m_capacity < newBufferCount) { - Reserve(newBufferSize); + reserve(newBufferCount); } - this->_count = size; + m_count = count; } - void SetSize(UInt size) + void setCount(Index count) { - Reserve(size); - _count = size; + reserve(count); + m_count = count; } - void UnsafeShrinkToSize(UInt size) - { - _count = size; - } + void unsafeShrinkToCount(Index count) { m_count = count; } - void Compress() + void compress() { - if (bufferSize > _count && _count > 0) + if (m_capacity > m_count && m_count > 0) { - T * newBuffer = Allocate(_count); - for (UInt i = 0; i < _count; i++) - newBuffer[i] = static_cast<T&&>(buffer[i]); - FreeBuffer(); - buffer = newBuffer; - bufferSize = _count; + T* newBuffer = _allocate(m_count); + for (Index i = 0; i < m_count; i++) + newBuffer[i] = static_cast<T&&>(m_buffer[i]); + + _deallocateBuffer(); + m_buffer = newBuffer; + m_capacity = m_count; } } - SLANG_FORCE_INLINE T & operator [](UInt id) const + SLANG_FORCE_INLINE T& operator [](Index idx) const { -#if _DEBUG - if(id >= _count) - throw IndexOutofRangeException("Operator[]: Index out of Range."); -#endif - return buffer[id]; + SLANG_ASSERT(idx >= 0 && idx <= m_count); + return m_buffer[idx]; } template<typename Func> - UInt FindFirst(const Func & predicate) const + Index findFirstIndex(const Func& predicate) const { - for (UInt i = 0; i < _count; i++) + for (Index i = 0; i < m_count; i++) { - if (predicate(buffer[i])) + if (predicate(m_buffer[i])) return i; } - return (UInt)-1; + return (Index)-1; } template<typename Func> - UInt FindLast(const Func & predicate) const + Index findLastIndex(const Func& predicate) const { - for (UInt i = _count; i > 0; i--) + for (Index i = m_count; i > 0; i--) { - if (predicate(buffer[i-1])) + if (predicate(m_buffer[i-1])) return i-1; } - return (UInt)-1; + return (Index)-1; } template<typename T2> - UInt IndexOf(const T2 & val) const + Index indexOf(const T2& val) const { - for (UInt i = 0; i < _count; i++) + for (Index i = 0; i < m_count; i++) { - if (buffer[i] == val) + if (m_buffer[i] == val) return i; } - return (UInt)-1; + return (Index)-1; } template<typename T2> - UInt LastIndexOf(const T2 & val) const + Index lastIndexOf(const T2& val) const { - for (int i = _count; i > 0; i--) + for (Index i = m_count; i > 0; i--) { - if(buffer[i-1] == val) + if(m_buffer[i-1] == val) return i-1; } - return (UInt)-1; + return (Index)-1; } - void Sort() + void sort() { - Sort([](T const& t1, T const& t2){return t1<t2;}); + sort([](const T& t1, const T& t2){return t1 < t2;}); } - bool Contains(const T & val) - { - for (UInt i = 0; i<_count; i++) - if (buffer[i] == val) - return true; - return false; - } + bool contains(const T& val) const { return indexOf(val) != Index(-1); } template<typename Comparer> - void Sort(Comparer compare) + void sort(Comparer compare) { - //InsertionSort(buffer, 0, _count - 1); - //QuickSort(buffer, 0, _count - 1, compare); - std::sort(buffer, buffer + _count, compare); + //insertionSort(buffer, 0, _count - 1); + //quickSort(buffer, 0, _count - 1, compare); + std::sort(m_buffer, m_buffer + m_count, compare); } template <typename IterateFunc> - void ForEach(IterateFunc f) const + void forEach(IterateFunc f) const { - for (int i = 0; i<_count; i++) - f(buffer[i]); + for (Index i = 0; i< m_count; i++) + f(m_buffer[i]); } template<typename Comparer> - void QuickSort(T * vals, int startIndex, int endIndex, Comparer comparer) + void quickSort(T* vals, Index startIndex, Index endIndex, Comparer comparer) { + static const Index kMinQSortSize = 32; + if(startIndex < endIndex) { - if (endIndex - startIndex < MIN_QSORT_SIZE) - InsertionSort(vals, startIndex, endIndex, comparer); + if (endIndex - startIndex < kMinQSortSize) + insertionSort(vals, startIndex, endIndex, comparer); else { - int pivotIndex = (startIndex + endIndex) >> 1; - int pivotNewIndex = Partition(vals, startIndex, endIndex, pivotIndex, comparer); - QuickSort(vals, startIndex, pivotNewIndex - 1, comparer); - QuickSort(vals, pivotNewIndex + 1, endIndex, comparer); + Index pivotIndex = (startIndex + endIndex) >> 1; + Index pivotNewIndex = partition(vals, startIndex, endIndex, pivotIndex, comparer); + quickSort(vals, startIndex, pivotNewIndex - 1, comparer); + quickSort(vals, pivotNewIndex + 1, endIndex, comparer); } } } template<typename Comparer> - int Partition(T * vals, int left, int right, int pivotIndex, Comparer comparer) + Index partition(T* vals, Index left, Index right, Index pivotIndex, Comparer comparer) { T pivotValue = vals[pivotIndex]; - Swap(vals, right, pivotIndex); - int storeIndex = left; - for (int i = left; i < right; i++) + swapElements(vals, right, pivotIndex); + Index storeIndex = left; + for (Index i = left; i < right; i++) { if (comparer(vals[i], pivotValue)) { - Swap(vals, i, storeIndex); + swapElements(vals, i, storeIndex); storeIndex++; } } - Swap(vals, storeIndex, right); + swapElements(vals, storeIndex, right); return storeIndex; } template<typename Comparer> - void InsertionSort(T * vals, int startIndex, int endIndex, Comparer comparer) + void insertionSort(T* vals, Index startIndex, Index endIndex, Comparer comparer) { - for (int i = startIndex + 1; i <= endIndex; i++) + for (Index i = startIndex + 1; i <= endIndex; i++) { T insertValue = static_cast<T&&>(vals[i]); - int insertIndex = i - 1; + Index insertIndex = i - 1; while (insertIndex >= startIndex && comparer(insertValue, vals[insertIndex])) { vals[insertIndex + 1] = static_cast<T&&>(vals[insertIndex]); @@ -611,7 +539,7 @@ namespace Slang } } - inline void Swap(T * vals, int index1, int index2) + inline void swapElements(T* vals, Index index1, Index index2) { if (index1 != index2) { @@ -622,13 +550,13 @@ namespace Slang } template<typename T2, typename Comparer> - int BinarySearch(const T2 & obj, Comparer comparer) + Index binarySearch(const T2& obj, Comparer comparer) { - int imin = 0, imax = _count - 1; + Index imin = 0, imax = m_count - 1; while (imax >= imin) { - int imid = (imin + imax) >> 1; - int compareResult = comparer(buffer[imid], obj); + Index imid = (imin + imax) >> 1; + int compareResult = comparer(m_buffer[imid], obj); if (compareResult == 0) return imid; else if (compareResult < 0) @@ -640,9 +568,9 @@ namespace Slang } template<typename T2> - int BinarySearch(const T2 & obj) + int binarySearch(const T2& obj) { - return BinarySearch(obj, + return binarySearch(obj, [](T & curObj, const T2 & thatObj)->int { if (curObj < thatObj) @@ -653,23 +581,47 @@ namespace Slang return 1; }); } + private: + T* m_buffer; ///< A new T[N] allocated buffer. NOTE! All elements up to capacity are in some valid form for T. + Index m_capacity; ///< The total capacity of elements + Index m_count; ///< The amount of elements + + void _deallocateBuffer() + { + if (m_buffer) + { + AllocateMethod<T, TAllocator>::deallocateArray(m_buffer, m_capacity); + m_buffer = nullptr; + } + } + static inline T* _allocate(Index count) + { + return AllocateMethod<T, TAllocator>::allocateArray(count); + } + + template<typename... Args> + void _init(const T& val, Args... args) + { + add(val); + _init(args...); + } }; template<typename T> - T Min(const List<T> & list) + T calcMin(const List<T>& list) { - T minVal = list.First(); - for (int i = 1; i<list.Count(); i++) + T minVal = list.getFirst(); + for (Index i = 1; i < list.getCount(); i++) if (list[i] < minVal) minVal = list[i]; return minVal; } template<typename T> - T Max(const List<T> & list) + T calcMax(const List<T>& list) { - T maxVal = list.First(); - for (int i = 1; i<list.Count(); i++) + T maxVal = list.getFirst(); + for (Index i = 1; i< list.getCount(); i++) if (list[i] > maxVal) maxVal = list[i]; return maxVal; diff --git a/source/core/platform.cpp b/source/core/platform.cpp index 238fccd08..0deec8ed6 100644 --- a/source/core/platform.cpp +++ b/source/core/platform.cpp @@ -52,7 +52,7 @@ SLANG_COMPILE_TIME_ASSERT(E_OUTOFMEMORY == SLANG_E_OUT_OF_MEMORY); { builderOut << " "; // Convert to string - builderOut.Append(String::FromWString(buffer)); + builderOut.Append(String::fromWString(buffer)); LocalFree(buffer); return SLANG_OK; } diff --git a/source/core/slang-byte-encode-util.cpp b/source/core/slang-byte-encode-util.cpp index 6eabdc16f..47ab824a4 100644 --- a/source/core/slang-byte-encode-util.cpp +++ b/source/core/slang-byte-encode-util.cpp @@ -100,7 +100,7 @@ namespace Slang { /* static */void ByteEncodeUtil::encodeLiteUInt32(const uint32_t* in, size_t num, List<uint8_t>& encodeArrayOut) { // Make sure there is at least enough space for all bytes - encodeArrayOut.SetSize(num); + encodeArrayOut.setCount(num); uint8_t* encodeOut = encodeArrayOut.begin(); uint8_t* encodeOutEnd = encodeArrayOut.end(); @@ -112,13 +112,13 @@ namespace Slang { { const size_t offset = size_t(encodeOut - encodeArrayOut.begin()); - const UInt oldCapacity = encodeArrayOut.Capacity(); + const UInt oldCapacity = encodeArrayOut.getCapacity(); // Make some more space - encodeArrayOut.Reserve(oldCapacity + (oldCapacity >> 1) + kMaxLiteEncodeUInt32); + encodeArrayOut.reserve(oldCapacity + (oldCapacity >> 1) + kMaxLiteEncodeUInt32); // Make the size the capacity - const UInt capacity = encodeArrayOut.Capacity(); - encodeArrayOut.SetSize(capacity); + const UInt capacity = encodeArrayOut.getCapacity(); + encodeArrayOut.setCount(capacity); encodeOut = encodeArrayOut.begin() + offset; encodeOutEnd = encodeArrayOut.end(); @@ -152,8 +152,8 @@ namespace Slang { } } - encodeArrayOut.SetSize(UInt(encodeOut - encodeArrayOut.begin())); - encodeArrayOut.Compress(); + encodeArrayOut.setCount(UInt(encodeOut - encodeArrayOut.begin())); + encodeArrayOut.compress(); } /* static */int ByteEncodeUtil::encodeLiteUInt32(uint32_t in, uint8_t out[kMaxLiteEncodeUInt32]) diff --git a/source/core/slang-free-list.h b/source/core/slang-free-list.h index dfa924797..62c2b9d93 100644 --- a/source/core/slang-free-list.h +++ b/source/core/slang-free-list.h @@ -1,9 +1,9 @@ -#ifndef SLANG_FREE_LIST_H +#ifndef SLANG_FREE_LIST_H #define SLANG_FREE_LIST_H #include "../../slang.h" -#include <assert.h> +#include "common.h" #include <stdlib.h> #include <string.h> @@ -141,4 +141,4 @@ SLANG_FORCE_INLINE void FreeList::deallocate(void* data) } // namespace Slang -#endif // SLANG_FREE_LIST_H
\ No newline at end of file +#endif // SLANG_FREE_LIST_H diff --git a/source/core/slang-io.cpp b/source/core/slang-io.cpp index 332718cea..82a2e5a35 100644 --- a/source/core/slang-io.cpp +++ b/source/core/slang-io.cpp @@ -35,28 +35,28 @@ namespace Slang { #ifdef _WIN32 struct _stat32 statVar; - return ::_wstat32(((String)fileName).ToWString(), &statVar) != -1; + return ::_wstat32(((String)fileName).toWString(), &statVar) != -1; #else struct stat statVar; - return ::stat(fileName.Buffer(), &statVar) == 0; + return ::stat(fileName.getBuffer(), &statVar) == 0; #endif } String Path::truncateExt(const String& path) { - UInt dotPos = path.LastIndexOf('.'); + UInt dotPos = path.lastIndexOf('.'); if (dotPos != -1) - return path.SubString(0, dotPos); + return path.subString(0, dotPos); else return path; } String Path::replaceExt(const String& path, const char* newExt) { - StringBuilder sb(path.Length()+10); - UInt dotPos = path.LastIndexOf('.'); + StringBuilder sb(path.getLength()+10); + UInt dotPos = path.lastIndexOf('.'); if (dotPos == -1) - dotPos = path.Length(); - sb.Append(path.Buffer(), dotPos); + dotPos = path.getLength(); + sb.Append(path.getBuffer(), dotPos); sb.Append('.'); sb.Append(newExt); return sb.ProduceString(); @@ -64,8 +64,8 @@ namespace Slang static UInt findLastSeparator(String const& path) { - UInt slashPos = path.LastIndexOf('/'); - UInt backslashPos = path.LastIndexOf('\\'); + UInt slashPos = path.lastIndexOf('/'); + UInt backslashPos = path.lastIndexOf('\\'); if (slashPos == -1) return backslashPos; if (backslashPos == -1) return slashPos; @@ -83,7 +83,7 @@ namespace Slang if (pos != -1) { pos = pos + 1; - return path.SubString(pos, path.Length() - pos); + return path.subString(pos, path.getLength() - pos); } else { @@ -93,16 +93,16 @@ namespace Slang String Path::getFileNameWithoutExt(const String& path) { String fileName = getFileName(path); - UInt dotPos = fileName.LastIndexOf('.'); + UInt dotPos = fileName.lastIndexOf('.'); if (dotPos == -1) return fileName; - return fileName.SubString(0, dotPos); + return fileName.subString(0, dotPos); } String Path::getFileExt(const String& path) { - UInt dotPos = path.LastIndexOf('.'); + UInt dotPos = path.lastIndexOf('.'); if (dotPos != -1) - return path.SubString(dotPos+1, path.Length()-dotPos-1); + return path.subString(dotPos+1, path.getLength()-dotPos-1); else return ""; } @@ -110,28 +110,28 @@ namespace Slang { UInt pos = findLastSeparator(path); if (pos != -1) - return path.SubString(0, pos); + return path.subString(0, pos); else return ""; } String Path::combine(const String& path1, const String& path2) { - if (path1.Length() == 0) return path2; - StringBuilder sb(path1.Length()+path2.Length()+2); + if (path1.getLength() == 0) return path2; + StringBuilder sb(path1.getLength()+path2.getLength()+2); sb.Append(path1); - if (!path1.EndsWith('\\') && !path1.EndsWith('/')) + if (!path1.endsWith('\\') && !path1.endsWith('/')) sb.Append(kPathDelimiter); sb.Append(path2); return sb.ProduceString(); } String Path::combine(const String& path1, const String& path2, const String& path3) { - StringBuilder sb(path1.Length()+path2.Length()+path3.Length()+3); + StringBuilder sb(path1.getLength()+path2.getLength()+path3.getLength()+3); sb.Append(path1); - if (!path1.EndsWith('\\') && !path1.EndsWith('/')) + if (!path1.endsWith('\\') && !path1.endsWith('/')) sb.Append(kPathDelimiter); sb.Append(path2); - if (!path2.EndsWith('\\') && !path2.EndsWith('/')) + if (!path2.endsWith('\\') && !path2.endsWith('/')) sb.Append(kPathDelimiter); sb.Append(path3); return sb.ProduceString(); @@ -191,7 +191,7 @@ namespace Slang /* static */void Path::split(const UnownedStringSlice& path, List<UnownedStringSlice>& splitOut) { - splitOut.Clear(); + splitOut.clear(); const char* start = path.begin(); const char* end = path.end(); @@ -202,21 +202,21 @@ namespace Slang // Find the split while (cur < end && !isDelimiter(*cur)) cur++; - splitOut.Add(UnownedStringSlice(start, cur)); + splitOut.add(UnownedStringSlice(start, cur)); // Next start = cur + 1; } // Okay if the end is empty. And we aren't with a spec like // or c:/ , then drop the final slash - if (splitOut.Count() > 1 && splitOut.Last().size() == 0) + if (splitOut.getCount() > 1 && splitOut.getLast().size() == 0) { - if (splitOut.Count() == 2 && isDriveSpecification(splitOut[0])) + if (splitOut.getCount() == 2 && isDriveSpecification(splitOut[0])) { return; } // Remove the last - splitOut.RemoveLast(); + splitOut.removeLast(); } } @@ -241,13 +241,13 @@ namespace Slang split(path, splitPath); // Strictly speaking we could do something about case on platforms like window, but here we won't worry about that - for (int i = 0; i < int(splitPath.Count()); i++) + for (Index i = 0; i < splitPath.getCount(); i++) { const UnownedStringSlice& cur = splitPath[i]; - if (cur == "." && splitPath.Count() > 1) + if (cur == "." && splitPath.getCount() > 1) { // Just remove it - splitPath.RemoveAt(i); + splitPath.removeAt(i); i--; } else if (cur == ".." && i > 0) @@ -259,20 +259,20 @@ namespace Slang // Can't do it continue; } - splitPath.RemoveRange(i - 1, 2); + splitPath.removeRange(i - 1, 2); i -= 2; } } // If its empty it must be . - if (splitPath.Count() == 0) + if (splitPath.getCount() == 0) { - splitPath.Add(UnownedStringSlice::fromLiteral(".")); + splitPath.add(UnownedStringSlice::fromLiteral(".")); } // Reconstruct the string StringBuilder builder; - for (int i = 0; i < int(splitPath.Count()); i++) + for (Index i = 0; i < splitPath.getCount(); i++) { if (i > 0) { @@ -287,9 +287,9 @@ namespace Slang bool Path::createDirectory(const String& path) { #if defined(_WIN32) - return _wmkdir(path.ToWString()) == 0; + return _wmkdir(path.toWString()) == 0; #else - return mkdir(path.Buffer(), 0777) == 0; + return mkdir(path.getBuffer(), 0777) == 0; #endif } @@ -298,7 +298,7 @@ namespace Slang #ifdef _WIN32 // https://msdn.microsoft.com/en-us/library/14h5k7ff.aspx struct _stat32 statVar; - if (::_wstat32(String(path).ToWString(), &statVar) == 0) + if (::_wstat32(String(path).toWString(), &statVar) == 0) { if (statVar.st_mode & _S_IFDIR) { @@ -316,7 +316,7 @@ namespace Slang return SLANG_E_NOT_FOUND; #else struct stat statVar; - if (::stat(path.Buffer(), &statVar) == 0) + if (::stat(path.getBuffer(), &statVar) == 0) { if (S_ISDIR(statVar.st_mode)) { @@ -340,13 +340,13 @@ namespace Slang { #if defined(_WIN32) // https://msdn.microsoft.com/en-us/library/506720ff.aspx - wchar_t* absPath = ::_wfullpath(nullptr, path.ToWString(), 0); + wchar_t* absPath = ::_wfullpath(nullptr, path.toWString(), 0); if (!absPath) { return SLANG_FAIL; } - canonicalPathOut = String::FromWString(absPath); + canonicalPathOut = String::fromWString(absPath); ::free(absPath); return SLANG_OK; #else @@ -432,15 +432,15 @@ namespace Slang return SLANG_OK; # else String text = Slang::File::readAllText("/proc/self/maps"); - UInt startIndex = text.IndexOf('/'); - if (startIndex == UInt(-1)) + Index startIndex = text.indexOf('/'); + if (startIndex == Index(-1)) { return SLANG_FAIL; } - UInt endIndex = text.IndexOf("\n", startIndex); - endIndex = (endIndex == UInt(-1)) ? text.Length() : endIndex; + Index endIndex = text.indexOf("\n", startIndex); + endIndex = (endIndex == Index(-1)) ? text.getLength() : endIndex; - auto path = text.SubString(startIndex, endIndex - startIndex); + auto path = text.subString(startIndex, endIndex - startIndex); if (path.getLength() < bufferSize) { @@ -476,17 +476,17 @@ namespace Slang { List<char> buffer; // Guess an initial buffer size - buffer.SetSize(1024); + buffer.setCount(1024); while (true) { - const size_t size = buffer.Count(); + const size_t size = size_t(buffer.getCount()); size_t bufferSize = size; - SlangResult res = _calcExectuablePath(buffer.Buffer(), &bufferSize); + SlangResult res = _calcExectuablePath(buffer.getBuffer(), &bufferSize); if (SLANG_SUCCEEDED(res)) { - return String(buffer.Buffer()); + return String(buffer.getBuffer()); } if (res != SLANG_E_BUFFER_TOO_SMALL) @@ -497,7 +497,7 @@ namespace Slang // If bufferSize changed it should be the exact fit size, else we just make the buffer bigger by a guess (50% bigger) bufferSize = (bufferSize > size) ? bufferSize : (bufferSize + bufferSize / 2); - buffer.SetSize(bufferSize); + buffer.setCount(Index(bufferSize)); } } @@ -522,7 +522,7 @@ namespace Slang unsigned char ch; int read = (int)fs->Read(&ch, 1); if (read) - buffer.Add(ch); + buffer.add(ch); else break; } diff --git a/source/core/slang-memory-arena.h b/source/core/slang-memory-arena.h index 52400f9ed..b9066e198 100644 --- a/source/core/slang-memory-arena.h +++ b/source/core/slang-memory-arena.h @@ -3,8 +3,6 @@ #include "../../slang.h" -#include <assert.h> - #include <stdlib.h> #include <string.h> diff --git a/source/core/slang-object-scope-manager.cpp b/source/core/slang-object-scope-manager.cpp index 313bd4cd5..2e7b7dfe3 100644 --- a/source/core/slang-object-scope-manager.cpp +++ b/source/core/slang-object-scope-manager.cpp @@ -5,8 +5,8 @@ namespace Slang { void ObjectScopeManager::_releaseAll() { RefObject*const* objs = m_objs.begin(); - const int numObjs = int(m_objs.Count()); - for (int i = 0; i < numObjs; ++i) + const Index numObjs = m_objs.getCount(); + for (Index i = 0; i < numObjs; ++i) { objs[i]->decreaseReference(); } diff --git a/source/core/slang-object-scope-manager.h b/source/core/slang-object-scope-manager.h index 14008a490..660a7cace 100644 --- a/source/core/slang-object-scope-manager.h +++ b/source/core/slang-object-scope-manager.h @@ -1,4 +1,4 @@ -#ifndef SLANG_OBJECT_SCOPE_MANAGER_H +#ifndef SLANG_OBJECT_SCOPE_MANAGER_H #define SLANG_OBJECT_SCOPE_MANAGER_H #include "smart-pointer.h" @@ -48,7 +48,7 @@ RefObject* ObjectScopeManager::addMaybeNull(RefObject* obj) if (obj) { obj->addReference(); - m_objs.Add(obj); + m_objs.add(obj); } return obj; } @@ -58,10 +58,10 @@ RefObject* ObjectScopeManager::add(RefObject* obj) { SLANG_ASSERT(obj); obj->addReference(); - m_objs.Add(obj); + m_objs.add(obj); return obj; } } // namespace Slang -#endif // SLANG_OBJECT_SCOPE_MANAGER_H
\ No newline at end of file +#endif // SLANG_OBJECT_SCOPE_MANAGER_H diff --git a/source/core/slang-random-generator.h b/source/core/slang-random-generator.h index 7b3e42288..cc25aadf3 100644 --- a/source/core/slang-random-generator.h +++ b/source/core/slang-random-generator.h @@ -3,8 +3,6 @@ #include "../../slang.h" -#include <assert.h> - #include <stdlib.h> #include <string.h> @@ -94,4 +92,4 @@ typedef Mt19937RandomGenerator DefaultRandomGenerator; } // namespace Slang -#endif // SLANG_RANDOM_GENERATOR_H
\ No newline at end of file +#endif // SLANG_RANDOM_GENERATOR_H diff --git a/source/core/slang-render-api-util.cpp b/source/core/slang-render-api-util.cpp index 80f2225d9..05def0fe3 100644 --- a/source/core/slang-render-api-util.cpp +++ b/source/core/slang-render-api-util.cpp @@ -62,7 +62,7 @@ UnownedStringSlice RenderApiUtil::getApiName(RenderApiType type) if (names.indexOf(',') >= 0) { StringUtil::split(names, ',', namesList); - if (namesList.IndexOf(name) != UInt(-1)) + if (namesList.indexOf(name) != Index(-1)) { return apiInfo.type; } diff --git a/source/core/slang-string-slice-pool.cpp b/source/core/slang-string-slice-pool.cpp index 797da5a0f..e3d9d8809 100644 --- a/source/core/slang-string-slice-pool.cpp +++ b/source/core/slang-string-slice-pool.cpp @@ -16,7 +16,7 @@ StringSlicePool::StringSlicePool() : void StringSlicePool::clear() { - m_slices.SetSize(2); + m_slices.setCount(2); m_slices[0] = UnownedStringSlice((const char*)nullptr, (const char*)nullptr); m_slices[1] = UnownedStringSlice::fromLiteral(""); @@ -38,9 +38,9 @@ StringSlicePool::Handle StringSlicePool::add(const Slice& slice) // Create a scoped copy UnownedStringSlice scopePath(m_arena.allocateString(slice.begin(), slice.size()), slice.size()); - const int index = int(m_slices.Count()); + const auto index = m_slices.getCount(); - m_slices.Add(scopePath); + m_slices.add(scopePath); m_map.Add(scopePath, Handle(index)); return Handle(index); } diff --git a/source/core/slang-string-slice-pool.h b/source/core/slang-string-slice-pool.h index 08cd819ab..cf8f63c81 100644 --- a/source/core/slang-string-slice-pool.h +++ b/source/core/slang-string-slice-pool.h @@ -46,7 +46,7 @@ public: const List<UnownedStringSlice>& getSlices() const { return m_slices; } /// Get the number of slices - int getNumSlices() const { return int(m_slices.Count()); } + int getNumSlices() const { return int(m_slices.getCount()); } /// Convert a handle to and index. (A handle is just an index!) static int asIndex(Handle handle) { return int(handle); } diff --git a/source/core/slang-string-util.cpp b/source/core/slang-string-util.cpp index b7c6780e1..11d6846f0 100644 --- a/source/core/slang-string-util.cpp +++ b/source/core/slang-string-util.cpp @@ -17,7 +17,7 @@ static const Guid IID_ISlangBlob = SLANG_UUID_ISlangBlob; /* static */void StringUtil::split(const UnownedStringSlice& in, char splitChar, List<UnownedStringSlice>& slicesOut) { - slicesOut.Clear(); + slicesOut.clear(); const char* start = in.begin(); const char* end = in.end(); @@ -32,7 +32,7 @@ static const Guid IID_ISlangBlob = SLANG_UUID_ISlangBlob; } // Add to output - slicesOut.Add(UnownedStringSlice(start, cur)); + slicesOut.add(UnownedStringSlice(start, cur)); // Skip the split character, if at end we are okay anyway start = cur + 1; @@ -178,13 +178,13 @@ ComPtr<ISlangBlob> StringUtil::createStringBlob(const String& string) return slice; } - const UInt numChars = slice.size(); + const Index numChars = slice.size(); const char* srcChars = slice.begin(); StringBuilder builder; char* dstChars = builder.prepareForAppend(numChars); - for (UInt i = 0; i < numChars; ++i) + for (Index i = 0; i < numChars; ++i) { char c = srcChars[i]; dstChars[i] = (c == fromChar) ? toChar : c; @@ -196,7 +196,7 @@ ComPtr<ISlangBlob> StringUtil::createStringBlob(const String& string) /* static */String StringUtil::calcCharReplaced(const String& string, char fromChar, char toChar) { - return (fromChar == toChar || string.IndexOf(fromChar) == UInt(-1)) ? string : calcCharReplaced(string.getUnownedSlice(), fromChar, toChar); + return (fromChar == toChar || string.indexOf(fromChar) == Index(-1)) ? string : calcCharReplaced(string.getUnownedSlice(), fromChar, toChar); } diff --git a/source/core/slang-string-util.h b/source/core/slang-string-util.h index 3288899fc..40fda31c4 100644 --- a/source/core/slang-string-util.h +++ b/source/core/slang-string-util.h @@ -20,8 +20,8 @@ public: SLANG_REF_OBJECT_IUNKNOWN_ALL // ISlangBlob - SLANG_NO_THROW void const* SLANG_MCALL getBufferPointer() SLANG_OVERRIDE { return m_string.Buffer(); } - SLANG_NO_THROW size_t SLANG_MCALL getBufferSize() SLANG_OVERRIDE { return m_string.Length(); } + SLANG_NO_THROW void const* SLANG_MCALL getBufferPointer() SLANG_OVERRIDE { return m_string.getBuffer(); } + SLANG_NO_THROW size_t SLANG_MCALL getBufferSize() SLANG_OVERRIDE { return m_string.getLength(); } /// Get the contained string SLANG_FORCE_INLINE const String& getString() const { return m_string; } diff --git a/source/core/slang-string.cpp b/source/core/slang-string.cpp index 28acde6ac..9a908c93e 100644 --- a/source/core/slang-string.cpp +++ b/source/core/slang-string.cpp @@ -14,20 +14,20 @@ namespace Slang // OSString OSString::OSString() - : beginData(0) - , endData(0) + : m_begin(0) + , m_end(0) {} OSString::OSString(wchar_t* begin, wchar_t* end) - : beginData(begin) - , endData(end) + : m_begin(begin) + , m_end(end) {} OSString::~OSString() { - if (beginData) + if (m_begin) { - delete[] beginData; + delete[] m_begin; } } @@ -35,12 +35,12 @@ namespace Slang wchar_t const* OSString::begin() const { - return beginData ? beginData : kEmptyOSString; + return m_begin ? m_begin : kEmptyOSString; } wchar_t const* OSString::end() const { - return endData ? endData : kEmptyOSString; + return m_end ? m_end : kEmptyOSString; } // UnownedStringSlice @@ -89,13 +89,13 @@ namespace Slang {} StringSlice::StringSlice(String const& str) - : representation(str.buffer) + : representation(str.m_buffer) , beginIndex(0) - , endIndex(str.Length()) + , endIndex(str.getLength()) {} StringSlice::StringSlice(String const& str, UInt beginIndex, UInt endIndex) - : representation(str.buffer) + : representation(str.m_buffer) , beginIndex(beginIndex) , endIndex(endIndex) {} @@ -128,25 +128,25 @@ namespace Slang int StringToInt(const String & str, int radix) { - if (str.StartsWith("0x")) - return (int)strtoll(str.Buffer(), NULL, 16); + if (str.startsWith("0x")) + return (int)strtoll(str.getBuffer(), NULL, 16); else - return (int)strtoll(str.Buffer(), NULL, radix); + return (int)strtoll(str.getBuffer(), NULL, radix); } unsigned int StringToUInt(const String & str, int radix) { - if (str.StartsWith("0x")) - return (unsigned int)strtoull(str.Buffer(), NULL, 16); + if (str.startsWith("0x")) + return (unsigned int)strtoull(str.getBuffer(), NULL, 16); else - return (unsigned int)strtoull(str.Buffer(), NULL, radix); + return (unsigned int)strtoull(str.getBuffer(), NULL, radix); } double StringToDouble(const String & str) { - return (double)strtod(str.Buffer(), NULL); + return (double)strtod(str.getBuffer(), NULL); } float StringToFloat(const String & str) { - return strtof(str.Buffer(), NULL); + return strtof(str.getBuffer(), NULL); } #if 0 @@ -165,7 +165,7 @@ namespace Slang } #endif - String String::FromWString(const wchar_t * wstr) + String String::fromWString(const wchar_t * wstr) { #ifdef _WIN32 return Slang::Encoding::UTF16->ToString((const char*)wstr, (int)(wcslen(wstr) * sizeof(wchar_t))); @@ -174,7 +174,7 @@ namespace Slang #endif } - String String::FromWString(const wchar_t * wstr, const wchar_t * wend) + String String::fromWString(const wchar_t * wstr, const wchar_t * wend) { #ifdef _WIN32 return Slang::Encoding::UTF16->ToString((const char*)wstr, (int)((wend - wstr) * sizeof(wchar_t))); @@ -183,7 +183,7 @@ namespace Slang #endif } - String String::FromWChar(const wchar_t ch) + String String::fromWChar(const wchar_t ch) { #ifdef _WIN32 return Slang::Encoding::UTF16->ToString((const char*)&ch, (int)(sizeof(wchar_t))); @@ -192,7 +192,7 @@ namespace Slang #endif } - String String::FromUnicodePoint(unsigned int codePoint) + String String::fromUnicodePoint(unsigned int codePoint) { char buf[6]; int len = Slang::EncodeUnicodePointToUTF8(buf, (int)codePoint); @@ -200,9 +200,9 @@ namespace Slang return String(buf); } - OSString String::ToWString(UInt* outLength) const + OSString String::toWString(Index* outLength) const { - if (!buffer) + if (!m_buffer) { return OSString(); } @@ -223,17 +223,17 @@ namespace Slang break; } - auto length = buf.Count() / sizeof(wchar_t); + auto length = Index(buf.getCount() / sizeof(wchar_t)); if (outLength) *outLength = length; for(int ii = 0; ii < sizeof(wchar_t); ++ii) - buf.Add(0); + buf.add(0); - wchar_t* beginData = (wchar_t*)buf.Buffer(); + wchar_t* beginData = (wchar_t*)buf.getBuffer(); wchar_t* endData = beginData + length; - buf.ReleaseBuffer(); + buf.detachBuffer(); return OSString(beginData, endData); } @@ -241,55 +241,55 @@ namespace Slang // - void String::ensureUniqueStorageWithCapacity(UInt requiredCapacity) + void String::ensureUniqueStorageWithCapacity(Index requiredCapacity) { - if (buffer && buffer->isUniquelyReferenced() && buffer->capacity >= requiredCapacity) + if (m_buffer && m_buffer->isUniquelyReferenced() && m_buffer->capacity >= requiredCapacity) return; - UInt newCapacity = buffer ? 2*buffer->capacity : 16; + Index newCapacity = m_buffer ? 2 * m_buffer->capacity : 16; if (newCapacity < requiredCapacity) { newCapacity = requiredCapacity; } - UInt length = getLength(); + Index length = getLength(); StringRepresentation* newRepresentation = StringRepresentation::createWithCapacityAndLength(newCapacity, length); - if (buffer) + if (m_buffer) { - memcpy(newRepresentation->getData(), buffer->getData(), length + 1); + memcpy(newRepresentation->getData(), m_buffer->getData(), length + 1); } - buffer = newRepresentation; + m_buffer = newRepresentation; } - char* String::prepareForAppend(UInt count) + char* String::prepareForAppend(Index count) { auto oldLength = getLength(); auto newLength = oldLength + count; ensureUniqueStorageWithCapacity(newLength); return getData() + oldLength; } - void String::appendInPlace(const char* chars, UInt count) + void String::appendInPlace(const char* chars, Index count) { SLANG_UNUSED(chars); if (count > 0) { - SLANG_ASSERT(buffer && buffer->isUniquelyReferenced()); + SLANG_ASSERT(m_buffer && m_buffer->isUniquelyReferenced()); auto oldLength = getLength(); auto newLength = oldLength + count; - char* dst = buffer->getData(); + char* dst = m_buffer->getData(); // Make sure the input buffer is the same one returned from prepareForAppend SLANG_ASSERT(chars == dst + oldLength); // It has to fit within the capacity - SLANG_ASSERT(newLength <= buffer->capacity); + SLANG_ASSERT(newLength <= m_buffer->capacity); // We just need to modify the length - buffer->length = newLength; + m_buffer->length = newLength; // And mark with a terminating 0 dst[newLength] = 0; @@ -307,7 +307,7 @@ namespace Slang memcpy(getData() + oldLength, textBegin, textLength); getData()[newLength] = 0; - buffer->length = newLength; + m_buffer->length = newLength; } void String::append(char const* str) @@ -325,9 +325,9 @@ namespace Slang void String::append(String const& str) { - if (!buffer) + if (!m_buffer) { - buffer = str.buffer; + m_buffer = str.m_buffer; return; } @@ -350,7 +350,7 @@ namespace Slang char* data = prepareForAppend(kCount); auto count = IntToAscii(data, value, radix); ReverseInternalAscii(data, count); - buffer->length += count; + m_buffer->length += count; } void String::append(uint32_t value, int radix) @@ -359,7 +359,7 @@ namespace Slang char* data = prepareForAppend(kCount); auto count = IntToAscii(data, value, radix); ReverseInternalAscii(data, count); - buffer->length += count; + m_buffer->length += count; } void String::append(int64_t value, int radix) @@ -368,7 +368,7 @@ namespace Slang char* data = prepareForAppend(kCount); auto count = IntToAscii(data, value, radix); ReverseInternalAscii(data, count); - buffer->length += count; + m_buffer->length += count; } void String::append(uint64_t value, int radix) @@ -377,7 +377,7 @@ namespace Slang char* data = prepareForAppend(kCount); auto count = IntToAscii(data, value, radix); ReverseInternalAscii(data, count); - buffer->length += count; + m_buffer->length += count; } void String::append(float val, const char * format) @@ -385,7 +385,7 @@ namespace Slang enum { kCount = 128 }; char* data = prepareForAppend(kCount); sprintf_s(data, kCount, format, val); - buffer->length += strnlen_s(data, kCount); + m_buffer->length += strnlen_s(data, kCount); } void String::append(double val, const char * format) @@ -393,6 +393,6 @@ namespace Slang enum { kCount = 128 }; char* data = prepareForAppend(kCount); sprintf_s(data, kCount, format, val); - buffer->length += strnlen_s(data, kCount); + m_buffer->length += strnlen_s(data, kCount); } } diff --git a/source/core/slang-string.h b/source/core/slang-string.h index 4c87ce81e..82eda74ac 100644 --- a/source/core/slang-string.h +++ b/source/core/slang-string.h @@ -66,44 +66,44 @@ namespace Slang { public: UnownedStringSlice() - : beginData(nullptr) - , endData(nullptr) + : m_begin(nullptr) + , m_end(nullptr) {} explicit UnownedStringSlice(char const* a) : - beginData(a), - endData(a + strlen(a)) + m_begin(a), + m_end(a + strlen(a)) {} UnownedStringSlice(char const* b, char const* e) - : beginData(b) - , endData(e) + : m_begin(b) + , m_end(e) {} UnownedStringSlice(char const* b, size_t len) - : beginData(b) - , endData(b + len) + : m_begin(b) + , m_end(b + len) {} char const* begin() const { - return beginData; + return m_begin; } char const* end() const { - return endData; + return m_end; } - UInt size() const + Index size() const { - return endData - beginData; + return Index(m_end - m_begin); } int indexOf(char c) const { - const int size = int(endData - beginData); + const int size = int(m_end - m_begin); for (int i = 0; i < size; ++i) { - if (beginData[i] == c) + if (m_begin[i] == c) { return i; } @@ -111,10 +111,10 @@ namespace Slang return -1; } - const char& operator[](UInt i) const + const char& operator[](Index i) const { - assert(i < UInt(endData - beginData)); - return beginData[i]; + assert(i >= 0 && i < Index(m_end - m_begin)); + return m_begin[i]; } bool operator==(UnownedStringSlice const& other) const @@ -125,7 +125,7 @@ namespace Slang bool operator==(char const* str) const { - return (*this) == UnownedStringSlice(str, str + strlen(str)); + return (*this) == UnownedStringSlice(str, str + ::strlen(str)); } bool operator!=(UnownedStringSlice const& other) const @@ -141,15 +141,15 @@ namespace Slang int GetHashCode() const { - return Slang::GetHashCode(beginData, size_t(endData - beginData)); + return Slang::GetHashCode(m_begin, size_t(m_end - m_begin)); } template <size_t SIZE> SLANG_FORCE_INLINE static UnownedStringSlice fromLiteral(const char (&in)[SIZE]) { return UnownedStringSlice(in, SIZE - 1); } private: - char const* beginData; - char const* endData; + char const* m_begin; + char const* m_end; }; // A `StringRepresentation` provides the backing storage for @@ -157,10 +157,10 @@ namespace Slang class StringRepresentation : public RefObject { public: - UInt length; - UInt capacity; + Index length; + Index capacity; - SLANG_FORCE_INLINE UInt getLength() const + SLANG_FORCE_INLINE Index getLength() const { return length; } @@ -189,7 +189,7 @@ namespace Slang return (a == b) || asSlice(a) == asSlice(b); } - static StringRepresentation* createWithCapacityAndLength(UInt capacity, UInt length) + static StringRepresentation* createWithCapacityAndLength(Index capacity, Index length) { SLANG_ASSERT(capacity >= length); void* allocation = operator new(sizeof(StringRepresentation) + capacity + 1); @@ -200,17 +200,17 @@ namespace Slang return obj; } - static StringRepresentation* createWithCapacity(UInt capacity) + static StringRepresentation* createWithCapacity(Index capacity) { return createWithCapacityAndLength(capacity, 0); } - static StringRepresentation* createWithLength(UInt length) + static StringRepresentation* createWithLength(Index length) { return createWithCapacityAndLength(length, length); } - StringRepresentation* cloneWithCapacity(UInt newCapacity) + StringRepresentation* cloneWithCapacity(Index newCapacity) { StringRepresentation* newObj = createWithCapacityAndLength(newCapacity, length); memcpy(getData(), newObj->getData(), length + 1); @@ -222,11 +222,11 @@ namespace Slang return cloneWithCapacity(length); } - StringRepresentation* ensureCapacity(UInt required) + StringRepresentation* ensureCapacity(Index required) { if (capacity >= required) return this; - UInt newCapacity = capacity; + Index newCapacity = capacity; if (!newCapacity) newCapacity = 16; // TODO: figure out good value for minimum capacity while (newCapacity < required) @@ -305,8 +305,8 @@ namespace Slang wchar_t const* end() const; private: - wchar_t* beginData; - wchar_t* endData; + wchar_t* m_begin; + wchar_t* m_end; }; /*! @@ -322,38 +322,34 @@ namespace Slang char* getData() const { - return buffer ? buffer->getData() : (char*)""; + return m_buffer ? m_buffer->getData() : (char*)""; } - UInt getLength() const - { - return buffer ? buffer->getLength() : 0; - } - - void ensureUniqueStorageWithCapacity(UInt capacity); - RefPtr<StringRepresentation> buffer; + void ensureUniqueStorageWithCapacity(Index capacity); + + RefPtr<StringRepresentation> m_buffer; public: explicit String(StringRepresentation* buffer) - : buffer(buffer) + : m_buffer(buffer) {} - static String FromWString(const wchar_t * wstr); - static String FromWString(const wchar_t * wstr, const wchar_t * wend); - static String FromWChar(const wchar_t ch); - static String FromUnicodePoint(unsigned int codePoint); + static String fromWString(const wchar_t * wstr); + static String fromWString(const wchar_t * wstr, const wchar_t * wend); + static String fromWChar(const wchar_t ch); + static String fromUnicodePoint(unsigned int codePoint); String() { } /// Returns a buffer which can hold at least count chars - char* prepareForAppend(UInt count); + char* prepareForAppend(Index count); /// Append data written to buffer output via 'prepareForAppend' directly written 'inplace' - void appendInPlace(const char* chars, UInt count); + void appendInPlace(const char* chars, Index count); - SLANG_FORCE_INLINE StringRepresentation* getStringRepresentation() const { return buffer; } + SLANG_FORCE_INLINE StringRepresentation* getStringRepresentation() const { return m_buffer; } const char * begin() const { @@ -439,14 +435,14 @@ namespace Slang } String(String const& str) { - buffer = str.buffer; + m_buffer = str.m_buffer; #if 0 this->operator=(str); #endif } String(String&& other) { - buffer = _Move(other.buffer); + m_buffer = _Move(other.m_buffer); } String(StringSlice const& slice) @@ -461,74 +457,79 @@ namespace Slang ~String() { - buffer = 0; + m_buffer = 0; } String & operator=(const String & str) { - buffer = str.buffer; + m_buffer = str.m_buffer; return *this; } String & operator=(String&& other) { - buffer = _Move(other.buffer); + m_buffer = _Move(other.m_buffer); return *this; } - char operator[](UInt id) const + char operator[](Index id) const { -#if _DEBUG - if (id < 0 || id >= getLength()) - throw "Operator[]: index out of range."; -#endif + SLANG_ASSERT(id >= 0 && id < getLength()); return begin()[id]; } + Index getLength() const + { + return m_buffer ? m_buffer->getLength() : 0; + } + friend String operator+(const char*op1, const String & op2); friend String operator+(const String & op1, const char * op2); friend String operator+(const String & op1, const String & op2); - StringSlice TrimStart() const + StringSlice trimStart() const { - if (!buffer) + if (!m_buffer) return StringSlice(); - UInt startIndex = 0; + Index startIndex = 0; + const char*const data = getData(); while (startIndex < getLength() && - (getData()[startIndex] == ' ' || getData()[startIndex] == '\t' || getData()[startIndex] == '\r' || getData()[startIndex] == '\n')) + (data[startIndex] == ' ' || data[startIndex] == '\t' || data[startIndex] == '\r' || data[startIndex] == '\n')) startIndex++; - return StringSlice(buffer, startIndex, getLength()); + return StringSlice(m_buffer, startIndex, getLength()); } - StringSlice TrimEnd() const + StringSlice trimEnd() const { - if (!buffer) + if (!m_buffer) return StringSlice(); - UInt endIndex = getLength(); + Index endIndex = getLength(); + const char*const data = getData(); while (endIndex > 0 && - (getData()[endIndex-1] == ' ' || getData()[endIndex-1] == '\t' || getData()[endIndex-1] == '\r' || getData()[endIndex-1] == '\n')) + (data[endIndex-1] == ' ' || data[endIndex-1] == '\t' || data[endIndex-1] == '\r' || data[endIndex-1] == '\n')) endIndex--; - return StringSlice(buffer, 0, endIndex); + return StringSlice(m_buffer, 0, endIndex); } - StringSlice Trim() const + StringSlice trim() const { - if (!buffer) + if (!m_buffer) return StringSlice(); - UInt startIndex = 0; + Index startIndex = 0; + const char*const data = getData(); while (startIndex < getLength() && - (getData()[startIndex] == ' ' || getData()[startIndex] == '\t')) + (data[startIndex] == ' ' || data[startIndex] == '\t')) startIndex++; - UInt endIndex = getLength(); + Index endIndex = getLength(); while (endIndex > startIndex && - (getData()[endIndex-1] == ' ' || getData()[endIndex-1] == '\t')) + (data[endIndex-1] == ' ' || data[endIndex-1] == '\t')) endIndex--; - return StringSlice(buffer, startIndex, endIndex); + return StringSlice(m_buffer, startIndex, endIndex); } - StringSlice SubString(UInt id, UInt len) const + StringSlice subString(Index id, Index len) const { if (len == 0) return StringSlice(); @@ -541,17 +542,17 @@ namespace Slang if (len < 0) throw "SubString: length less than zero."; #endif - return StringSlice(buffer, id, id + len); + return StringSlice(m_buffer, id, id + len); } - char const* Buffer() const + char const* getBuffer() const { return getData(); } - OSString ToWString(UInt* len = 0) const; + OSString toWString(Index* len = 0) const; - bool Equals(const String & str, bool caseSensitive = true) + bool equals(const String & str, bool caseSensitive = true) { if (caseSensitive) return (strcmp(begin(), str.begin()) == 0); @@ -598,7 +599,7 @@ namespace Slang return (strcmp(begin(), str.begin()) <= 0); } - String ToUpper() const + String toUpper() const { String result; for (auto c : *this) @@ -609,7 +610,7 @@ namespace Slang return result; } - String ToLower() const + String toLower() const { String result; for (auto c : *this) @@ -620,108 +621,114 @@ namespace Slang return result; } - UInt Length() const - { - return getLength(); - } - - UInt IndexOf(const char * str, UInt id) const // String str + Index indexOf(const char * str, Index id) const // String str { if (id >= getLength()) - return UInt(-1); + return Index(-1); auto findRs = strstr(begin() + id, str); - UInt res = findRs ? findRs - begin() : -1; + Index res = findRs ? findRs - begin() : Index(-1); return res; } - UInt IndexOf(const String & str, UInt id) const + Index indexOf(const String & str, Index id) const { - return IndexOf(str.begin(), id); + return indexOf(str.begin(), id); } - UInt IndexOf(const char * str) const + Index indexOf(const char * str) const { - return IndexOf(str, 0); + return indexOf(str, 0); } - UInt IndexOf(const String & str) const + Index indexOf(const String & str) const { - return IndexOf(str.begin(), 0); + return indexOf(str.begin(), 0); } - UInt IndexOf(char ch, UInt id) const + Index indexOf(char ch, Index id) const { -#if _DEBUG - if (id < 0 || id >= getLength()) - throw "SubString: index out of range."; -#endif - if (!buffer) - return UInt(-1); - for (UInt i = id; i < getLength(); i++) - if (getData()[i] == ch) + const Index length = getLength(); + SLANG_ASSERT(id >= 0 && id <= length); + + if (!m_buffer) + return Index(-1); + + const char* data = getData(); + for (Index i = id; i < length; i++) + if (data[i] == ch) return i; - return UInt(-1); + return Index(-1); } - UInt IndexOf(char ch) const + Index indexOf(char ch) const { - return IndexOf(ch, 0); + return indexOf(ch, 0); } - UInt LastIndexOf(char ch) const - { - for (UInt i = getLength(); i > 0; i--) - if (getData()[i-1] == ch) - return i-1; - return UInt(-1); + Index lastIndexOf(char ch) const + { + const Index length = getLength(); + const char* data = getData(); + + // TODO(JS): If we know Index is signed we can do this a bit more simply + + for (Index i = length; i > 0; i--) + if (data[i - 1] == ch) + return i - 1; + return Index(-1); } - bool StartsWith(const char * str) const // String str + bool startsWith(const char * str) const // String str { - if (!buffer) + if (!m_buffer) return false; - UInt strLen = strlen(str); + Index strLen = Index(::strlen(str)); if (strLen > getLength()) return false; - for (UInt i = 0; i < strLen; i++) - if (str[i] != getData()[i]) + + const char*const data = getData(); + + for (Index i = 0; i < strLen; i++) + if (str[i] != data[i]) return false; return true; } - bool StartsWith(const String & str) const + bool startsWith(const String& str) const { - return StartsWith(str.begin()); + return startsWith(str.begin()); } - bool EndsWith(char const * str) const // String str + bool endsWith(char const * str) const // String str { - if (!buffer) + if (!m_buffer) return false; - UInt strLen = strlen(str); - if (strLen > getLength()) + + const Index strLen = Index(::strlen(str)); + const Index len = getLength(); + + if (strLen > len) return false; - for (UInt i = strLen; i > 0; i--) - if (str[i-1] != getData()[getLength() - strLen + i-1]) + const char* data = getData(); + for (Index i = strLen; i > 0; i--) + if (str[i-1] != data[len - strLen + i-1]) return false; return true; } - bool EndsWith(const String & str) const + bool endsWith(const String & str) const { - return EndsWith(str.begin()); + return endsWith(str.begin()); } - bool Contains(const char * str) const // String str + bool contains(const char * str) const // String str { - if (!buffer) - return false; - return (IndexOf(str) != UInt(-1)) ? true : false; + return m_buffer && indexOf(str) != Index(-1); } - bool Contains(const String & str) const + bool contains(const String & str) const { - return Contains(str.begin()); + return contains(str.begin()); } int GetHashCode() const @@ -731,7 +738,7 @@ namespace Slang UnownedStringSlice getUnownedSlice() const { - return StringRepresentation::asSlice(buffer); + return StringRepresentation::asSlice(m_buffer); } }; @@ -851,7 +858,7 @@ namespace Slang } void Append(const String & str) { - Append(str.Buffer(), str.Length()); + Append(str.getBuffer(), str.getLength()); } void Append(const char * str) { @@ -919,7 +926,7 @@ namespace Slang void Clear() { - buffer = 0; + m_buffer = 0; } }; diff --git a/source/core/slang-writer.cpp b/source/core/slang-writer.cpp index a3222b0d2..2c6f99bf9 100644 --- a/source/core/slang-writer.cpp +++ b/source/core/slang-writer.cpp @@ -66,17 +66,17 @@ ISlangUnknown* BaseWriter::getInterface(const Guid& guid) SLANG_NO_THROW char* SLANG_MCALL AppendBufferWriter::beginAppendBuffer(size_t maxNumChars) { - m_appendBuffer.SetSize(maxNumChars); - return m_appendBuffer.Buffer(); + m_appendBuffer.setCount(maxNumChars); + return m_appendBuffer.getBuffer(); } SLANG_NO_THROW SlangResult SLANG_MCALL AppendBufferWriter::endAppendBuffer(char* buffer, size_t numChars) { - SLANG_ASSERT(m_appendBuffer.Buffer() == buffer && buffer + numChars <= m_appendBuffer.end()); + SLANG_ASSERT(m_appendBuffer.getBuffer() == buffer && buffer + numChars <= m_appendBuffer.end()); // Do the actual write SlangResult res = write(buffer, numChars); // Clear so that buffer can't be written from again without assert - m_appendBuffer.Clear(); + m_appendBuffer.clear(); return res; } @@ -85,17 +85,17 @@ SLANG_NO_THROW SlangResult SLANG_MCALL AppendBufferWriter::endAppendBuffer(char* SLANG_NO_THROW char* SLANG_MCALL CallbackWriter::beginAppendBuffer(size_t maxNumChars) { // Add one so there is always space for end termination, we need for the callback. - m_appendBuffer.SetSize(maxNumChars + 1); - return m_appendBuffer.Buffer(); + m_appendBuffer.setCount(maxNumChars + 1); + return m_appendBuffer.getBuffer(); } SlangResult CallbackWriter::write(const char* chars, size_t numChars) { if (numChars > 0) { - char* appendBuffer = m_appendBuffer.Buffer(); + char* appendBuffer = m_appendBuffer.getBuffer(); // See if it's from an append buffer - if (chars >= appendBuffer && (chars + numChars) < (appendBuffer + m_appendBuffer.Count())) + if (chars >= appendBuffer && (chars + numChars) < (appendBuffer + m_appendBuffer.getCount())) { // Set terminating 0 appendBuffer[(chars + numChars) - appendBuffer] = 0; @@ -105,11 +105,11 @@ SlangResult CallbackWriter::write(const char* chars, size_t numChars) else { // Use the append buffer to add the terminating 0 - m_appendBuffer.SetSize(numChars + 1); - ::memcpy(m_appendBuffer.Buffer(), chars, numChars); + m_appendBuffer.setCount(numChars + 1); + ::memcpy(m_appendBuffer.getBuffer(), chars, numChars); m_appendBuffer[numChars] = 0; - m_callback(m_appendBuffer.Buffer(), (void*)m_data); + m_callback(m_appendBuffer.getBuffer(), (void*)m_data); } } diff --git a/source/core/smart-pointer.h b/source/core/smart-pointer.h index 8ce67e384..aa5c06e02 100644 --- a/source/core/smart-pointer.h +++ b/source/core/smart-pointer.h @@ -5,8 +5,6 @@ #include "hash.h" #include "type-traits.h" -#include <assert.h> - #include "../../slang.h" namespace Slang diff --git a/source/core/stream.cpp b/source/core/stream.cpp index 0fd266e0a..de0a8b8f3 100644 --- a/source/core/stream.cpp +++ b/source/core/stream.cpp @@ -113,11 +113,11 @@ namespace Slang } if (share == Slang::FileShare::None) #pragma warning(suppress:4996) - handle = _wfopen(fileName.ToWString(), mode); + handle = _wfopen(fileName.toWString(), mode); else - handle = _wfsopen(fileName.ToWString(), mode, shFlag); + handle = _wfsopen(fileName.toWString(), mode, shFlag); #else - handle = fopen(fileName.Buffer(), modeMBCS); + handle = fopen(fileName.getBuffer(), modeMBCS); #endif if (!handle) { @@ -228,7 +228,7 @@ namespace Slang pos = offset; break; case Slang::SeekOrigin::End: - pos = Int64(m_contents.Count()) + offset; + pos = Int64(m_contents.getCount()) + offset; break; case Slang::SeekOrigin::Current: pos = Int64(m_position) + offset; @@ -242,7 +242,7 @@ namespace Slang // Clamp to the valid range pos = (pos < 0) ? 0 : pos; - pos = (pos > Int64(m_contents.Count())) ? Int64(m_contents.Count()) : pos; + pos = (pos > Int64(m_contents.getCount())) ? Int64(m_contents.getCount()) : pos; m_position = UInt(pos); } @@ -254,7 +254,7 @@ namespace Slang throw IOException("Cannot read this stream."); } - const Int64 maxRead = Int64(m_contents.Count() - m_position); + const Int64 maxRead = Int64(m_contents.getCount() - m_position); if (maxRead == 0 && length > 0) { @@ -276,13 +276,13 @@ namespace Slang throw IOException("Cannot write this stream."); } - if (m_position == m_contents.Count()) + if (m_position == m_contents.getCount()) { - m_contents.AddRange((const uint8_t*)buffer, UInt(length)); + m_contents.addRange((const uint8_t*)buffer, UInt(length)); } else { - m_contents.InsertRange(m_position, (const uint8_t*)buffer, UInt(length)); + m_contents.insertRange(m_position, (const uint8_t*)buffer, UInt(length)); } m_atEnd = false; diff --git a/source/core/stream.h b/source/core/stream.h index 67a3549e9..618aadbd4 100644 --- a/source/core/stream.h +++ b/source/core/stream.h @@ -79,7 +79,7 @@ namespace Slang m_atEnd(false) {} - UInt m_position; + Index m_position; bool m_atEnd; ///< Happens when a read is done and nothing can be returned because already at end diff --git a/source/core/text-io.cpp b/source/core/text-io.cpp index d0d0a3cc6..1f6b44c92 100644 --- a/source/core/text-io.cpp +++ b/source/core/text-io.cpp @@ -15,7 +15,7 @@ namespace Slang public: virtual void GetBytes(List<char> & result, const String & str) override { - result.AddRange(str.Buffer(), str.Length()); + result.addRange(str.getBuffer(), str.getLength()); } virtual String ToString(const char * bytes, int /*length*/) override { @@ -28,17 +28,17 @@ namespace Slang public: virtual void GetBytes(List<char> & result, const String & str) override { - UInt ptr = 0; - while (ptr < str.Length()) + Index ptr = 0; + while (ptr < str.getLength()) { int codePoint = GetUnicodePointFromUTF8([&](int) { - if (ptr < str.Length()) + if (ptr < str.getLength()) return str[ptr++]; else return '\0'; }); - result.AddRange((char*)&codePoint, 4); + result.addRange((char*)&codePoint, 4); } } virtual String ToString(const char * bytes, int length) override @@ -66,12 +66,12 @@ namespace Slang {} virtual void GetBytes(List<char> & result, const String & str) override { - UInt ptr = 0; - while (ptr < str.Length()) + Index ptr = 0; + while (ptr < str.getLength()) { int codePoint = GetUnicodePointFromUTF8([&](int) { - if (ptr < str.Length()) + if (ptr < str.getLength()) return str[ptr++]; else return '\0'; @@ -82,7 +82,7 @@ namespace Slang count = EncodeUnicodePointToUTF16(buffer, codePoint); else count = EncodeUnicodePointToUTF16Reversed(buffer, codePoint); - result.AddRange((char*)buffer, count * 2); + result.addRange((char*)buffer, count * 2); } } virtual String ToString(const char * bytes, int length) override @@ -148,7 +148,7 @@ namespace Slang } void StreamWriter::Write(const String & str) { - encodingBuffer.Clear(); + encodingBuffer.clear(); StringBuilder sb; String newLine; #ifdef _WIN32 @@ -156,7 +156,7 @@ namespace Slang #else newLine = "\n"; #endif - for (UInt i = 0; i < str.Length(); i++) + for (Index i = 0; i < str.getLength(); i++) { if (str[i] == '\r') sb << newLine; @@ -169,7 +169,7 @@ namespace Slang sb << str[i]; } encoding->GetBytes(encodingBuffer, sb.ProduceString()); - stream->Write(encodingBuffer.Buffer(), encodingBuffer.Count()); + stream->Write(encodingBuffer.getBuffer(), encodingBuffer.getCount()); } void StreamWriter::Write(const char * str) { @@ -207,17 +207,17 @@ namespace Slang Encoding * StreamReader::DetermineEncoding() { - if (buffer.Count() >= 3 && (unsigned char)(buffer[0]) == 0xEF && (unsigned char)(buffer[1]) == 0xBB && (unsigned char)(buffer[2]) == 0xBF) + if (buffer.getCount() >= 3 && (unsigned char)(buffer[0]) == 0xEF && (unsigned char)(buffer[1]) == 0xBB && (unsigned char)(buffer[2]) == 0xBF) { ptr += 3; return Encoding::UTF8; } - else if (*((unsigned short*)(buffer.Buffer())) == 0xFEFF) + else if (*((unsigned short*)(buffer.getBuffer())) == 0xFEFF) { ptr += 2; return Encoding::UTF16; } - else if (*((unsigned short*)(buffer.Buffer())) == 0xFFFE) + else if (*((unsigned short*)(buffer.getBuffer())) == 0xFFFE) { ptr += 2; return Encoding::UTF16Reversed; @@ -225,7 +225,7 @@ namespace Slang else { // find null bytes - if (HasNullBytes(buffer.Buffer(), (int)buffer.Count())) + if (HasNullBytes(buffer.getBuffer(), (int)buffer.getCount())) { return Encoding::UTF16; } @@ -235,22 +235,22 @@ namespace Slang void StreamReader::ReadBuffer() { - buffer.SetSize(4096); - memset(buffer.Buffer(), 0, buffer.Count() * sizeof(buffer[0])); - auto len = stream->Read(buffer.Buffer(), buffer.Count()); - buffer.SetSize((int)len); + buffer.setCount(4096); + memset(buffer.getBuffer(), 0, buffer.getCount() * sizeof(buffer[0])); + auto len = stream->Read(buffer.getBuffer(), buffer.getCount()); + buffer.setCount((int)len); ptr = 0; } char StreamReader::ReadBufferChar() { - if (ptr<buffer.Count()) + if (ptr<buffer.getCount()) { return buffer[ptr++]; } if (!stream->IsEnd()) ReadBuffer(); - if (ptr<buffer.Count()) + if (ptr<buffer.getCount()) { return buffer[ptr++]; } diff --git a/source/core/text-io.h b/source/core/text-io.h index c914e340a..949150777 100644 --- a/source/core/text-io.h +++ b/source/core/text-io.h @@ -273,7 +273,7 @@ namespace Slang RefPtr<Stream> stream; List<char> buffer; Encoding * encoding; - UInt ptr; + Index ptr; char ReadBufferChar(); void ReadBuffer(); @@ -300,7 +300,7 @@ namespace Slang virtual String ReadToEnd(); virtual bool IsEnd() { - return ptr == buffer.Count() && stream->IsEnd(); + return ptr == buffer.getCount() && stream->IsEnd(); } virtual void Close() { diff --git a/source/core/token-reader.cpp b/source/core/token-reader.cpp index bf3294c8e..ea40c9ed9 100644 --- a/source/core/token-reader.cpp +++ b/source/core/token-reader.cpp @@ -44,15 +44,15 @@ namespace Slang void ParseOperators(const String & str, List<Token> & tokens, TokenFlags& tokenFlags, int line, int col, int startPos, String fileName) { - int pos = 0; - while (pos < (int)str.Length()) + Index pos = 0; + while (pos < str.getLength()) { wchar_t curChar = str[pos]; - wchar_t nextChar = (pos < (int)str.Length() - 1) ? str[pos + 1] : '\0'; - wchar_t nextNextChar = (pos < (int)str.Length() - 2) ? str[pos + 2] : '\0'; + wchar_t nextChar = (pos < str.getLength() - 1) ? str[pos + 1] : '\0'; + wchar_t nextNextChar = (pos < str.getLength() - 2) ? str[pos + 2] : '\0'; auto InsertToken = [&](TokenType type, const String & ct) { - tokens.Add(Token(type, ct, line, col + pos, pos + startPos, fileName, tokenFlags)); + tokens.add(Token(type, ct, line, int(col + pos), int(pos + startPos), fileName, tokenFlags)); tokenFlags = 0; }; switch (curChar) @@ -323,7 +323,7 @@ namespace Slang List<Token> TokenizeText(const String & fileName, const String & text) { - int lastPos = 0, pos = 0; + Index lastPos = 0, pos = 0; int line = 1, col = 0; String file = fileName; State state = State::Start; @@ -335,7 +335,7 @@ namespace Slang auto InsertToken = [&](TokenType type) { derivative = LexDerivative::None; - tokenList.Add(Token(type, tokenBuilder.ToString(), tokenLine, tokenCol, pos, file, tokenFlags)); + tokenList.add(Token(type, tokenBuilder.ToString(), tokenLine, tokenCol, int(pos), file, tokenFlags)); tokenFlags = 0; tokenBuilder.Clear(); }; @@ -365,10 +365,10 @@ namespace Slang break; } }; - while (pos <= (int)text.Length()) + while (pos <= text.getLength()) { - char curChar = (pos < (int)text.Length() ? text[pos] : ' '); - char nextChar = (pos < (int)text.Length() - 1) ? text[pos + 1] : '\0'; + char curChar = (pos < text.getLength() ? text[pos] : ' '); + char nextChar = (pos < text.getLength() - 1) ? text[pos + 1] : '\0'; if (lastPos != pos) { if (curChar == '\n') @@ -490,7 +490,7 @@ namespace Slang else { //do token analyze - ParseOperators(tokenBuilder.ToString(), tokenList, tokenFlags, tokenLine, tokenCol, (int)(pos - tokenBuilder.Length()), file); + ParseOperators(tokenBuilder.ToString(), tokenList, tokenFlags, tokenLine, tokenCol, (int)(pos - tokenBuilder.getLength()), file); tokenBuilder.Clear(); state = State::Start; } @@ -674,9 +674,11 @@ namespace Slang { StringBuilder sb; sb << "\""; - for (int i = 0; i < (int)str.Length(); i++) + const Index length = str.getLength(); + const char*const data = str.getBuffer(); + for (Index i = 0; i < length; i++) { - switch (str[i]) + switch (data[i]) { case ' ': sb << "\\s"; @@ -703,7 +705,7 @@ namespace Slang sb << "\\\\"; break; default: - sb << str[i]; + sb << data[i]; break; } } @@ -714,11 +716,13 @@ namespace Slang String UnescapeStringLiteral(String str) { StringBuilder sb; - for (int i = 0; i < (int)str.Length(); i++) + const Index length = str.getLength(); + const char*const data = str.getBuffer(); + for (Index i = 0; i < length; i++) { - if (str[i] == '\\' && i < (int)str.Length() - 1) + if (data[i] == '\\' && i < length - 1) { - switch (str[i + 1]) + switch (data[i + 1]) { case 's': sb << " "; @@ -746,12 +750,12 @@ namespace Slang break; default: i = i - 1; - sb << str[i]; + sb << data[i]; } i++; } else - sb << str[i]; + sb << data[i]; } return sb.ProduceString(); } diff --git a/source/core/token-reader.h b/source/core/token-reader.h index 48391738c..a5b9b3694 100644 --- a/source/core/token-reader.h +++ b/source/core/token-reader.h @@ -189,7 +189,7 @@ namespace Slang } Token ReadToken() { - if (tokenPtr < (int)tokens.Count()) + if (tokenPtr < (int)tokens.getCount()) { auto &rs = tokens[tokenPtr]; tokenPtr++; @@ -199,7 +199,7 @@ namespace Slang } Token NextToken(int offset = 0) { - if (tokenPtr + offset < (int)tokens.Count()) + if (tokenPtr + offset < (int)tokens.getCount()) return tokens[tokenPtr + offset]; else { @@ -210,7 +210,7 @@ namespace Slang } bool LookAhead(String token) { - if (tokenPtr < (int)tokens.Count()) + if (tokenPtr < (int)tokens.getCount()) { auto next = NextToken(); return next.Content == token; @@ -222,7 +222,7 @@ namespace Slang } bool IsEnd() { - return tokenPtr == (int)tokens.Count(); + return tokenPtr == (int)tokens.getCount(); } public: bool IsLegalText() @@ -235,24 +235,24 @@ namespace Slang { List<String> result; StringBuilder sb; - for (int i = 0; i < (int)text.Length(); i++) + for (Index i = 0; i < text.getLength(); i++) { if (text[i] == c) { auto str = sb.ToString(); - if (str.Length() != 0) - result.Add(str); + if (str.getLength() != 0) + result.add(str); sb.Clear(); } else sb << text[i]; } auto lastStr = sb.ToString(); - if (lastStr.Length()) - result.Add(lastStr); + if (lastStr.getLength()) + result.add(lastStr); return result; } } -#endif
\ No newline at end of file +#endif diff --git a/source/slang/check.cpp b/source/slang/check.cpp index e327834c0..6a40f436a 100644 --- a/source/slang/check.cpp +++ b/source/slang/check.cpp @@ -230,10 +230,10 @@ namespace Slang // that we can encode in our space of keys. args[0].aggVal = 0; args[1].aggVal = 0; - if (opExpr->Arguments.Count() > 2) + if (opExpr->Arguments.getCount() > 2) return false; - for (UInt i = 0; i < opExpr->Arguments.Count(); i++) + for (Index i = 0; i < opExpr->Arguments.getCount(); i++) { if (!args[i].fromType(opExpr->Arguments[i]->type.Ptr())) return false; @@ -1023,7 +1023,7 @@ namespace Slang for (auto argExpr : args) { - subst->args.Add(ExtractGenericArgVal(argExpr)); + subst->args.add(ExtractGenericArgVal(argExpr)); } DeclRef<Decl> innerDeclRef; @@ -1219,7 +1219,7 @@ namespace Slang // TODO: this is one place where syntax should get cloned! if (outProperType) - args.Add(typeParam->initType.exp); + args.add(typeParam->initType.exp); } else if (auto valParam = as<GenericValueParamDecl>(member)) { @@ -1235,7 +1235,7 @@ namespace Slang // TODO: this is one place where syntax should get cloned! if (outProperType) - args.Add(valParam->initExpr); + args.add(valParam->initExpr); } else { @@ -1487,7 +1487,7 @@ namespace Slang // First, we will check if we have run out of arguments // on the initializer list. // - UInt initArgCount = fromInitializerListExpr->args.Count(); + UInt initArgCount = fromInitializerListExpr->args.getCount(); if(ioInitArgIndex >= initArgCount) { // If we are at the end of the initializer list, @@ -1567,7 +1567,7 @@ namespace Slang UInt &ioArgIndex) { auto toType = inToType; - UInt argCount = fromInitializerListExpr->args.Count(); + UInt argCount = fromInitializerListExpr->args.getCount(); // In the case where we need to build a result expression, // we will collect the new arguments here @@ -1637,7 +1637,7 @@ namespace Slang if( coercedArg ) { - coercedArgs.Add(coercedArg); + coercedArgs.add(coercedArg); } } } @@ -1685,7 +1685,7 @@ namespace Slang if( coercedArg ) { - coercedArgs.Add(coercedArg); + coercedArgs.add(coercedArg); } } } @@ -1713,7 +1713,7 @@ namespace Slang if( coercedArg ) { - coercedArgs.Add(coercedArg); + coercedArgs.add(coercedArg); } } @@ -1775,7 +1775,7 @@ namespace Slang if( coercedArg ) { - coercedArgs.Add(coercedArg); + coercedArgs.add(coercedArg); } } } @@ -1803,7 +1803,7 @@ namespace Slang if( coercedArg ) { - coercedArgs.Add(coercedArg); + coercedArgs.add(coercedArg); } } } @@ -1862,7 +1862,7 @@ namespace Slang RefPtr<Expr>* outToExpr, RefPtr<InitializerListExpr> fromInitializerListExpr) { - UInt argCount = fromInitializerListExpr->args.Count(); + UInt argCount = fromInitializerListExpr->args.getCount(); UInt argIndex = 0; // TODO: we should handle the special case of `{0}` as an initializer @@ -2062,7 +2062,7 @@ namespace Slang // to the context and processed, we need to see whether // there was one best overload or not. // - if(overloadContext.bestCandidates.Count() != 0) + if(overloadContext.bestCandidates.getCount() != 0) { // In this case there were multiple equally-good candidates to call. // @@ -2159,7 +2159,7 @@ namespace Slang // auto castExpr = createImplicitCastExpr(); castExpr->loc = fromExpr->loc; - castExpr->Arguments.Add(fromExpr); + castExpr->Arguments.add(fromExpr); // // Next we need to set our cast expression as the "original" // expression and then complete the overload process. @@ -2181,8 +2181,8 @@ namespace Slang // because we don't allow nested implicit conversions, // but I'd rather play it safe. // - castExpr->Arguments.Clear(); - castExpr->Arguments.Add(fromExpr); + castExpr->Arguments.clear(); + castExpr->Arguments.add(fromExpr); } return true; @@ -2275,7 +2275,7 @@ namespace Slang castExpr->loc = fromExpr->loc; castExpr->FunctionExpr = typeExpr; castExpr->type = QualType(toType); - castExpr->Arguments.Add(fromExpr); + castExpr->Arguments.add(fromExpr); return castExpr; } @@ -2663,11 +2663,11 @@ namespace Slang param->nameAndLoc = member->nameAndLoc; param->type = varMember->type; param->loc = member->loc; - attribDecl->Members.Add(param); + attribDecl->Members.add(param); } } // add the attribute class definition to the syntax tree, so it can be found - structAttribDef->ParentDecl->Members.Add(attribDecl.Ptr()); + structAttribDef->ParentDecl->Members.add(attribDecl.Ptr()); structAttribDef->ParentDecl->memberDictionaryIsValid = false; // do necessary checks on this newly constructed node checkDecl(attribDecl.Ptr()); @@ -2676,7 +2676,7 @@ namespace Slang bool hasIntArgs(Attribute* attr, int numArgs) { - if (int(attr->args.Count()) != numArgs) + if (int(attr->args.getCount()) != numArgs) { return false; } @@ -2692,7 +2692,7 @@ namespace Slang bool hasStringArgs(Attribute* attr, int numArgs) { - if (int(attr->args.Count()) != numArgs) + if (int(attr->args.getCount()) != numArgs) { return false; } @@ -2730,7 +2730,7 @@ namespace Slang { if(auto numThreadsAttr = as<NumThreadsAttribute>(attr)) { - SLANG_ASSERT(attr->args.Count() == 3); + SLANG_ASSERT(attr->args.getCount() == 3); auto xVal = checkConstantIntVal(attr->args[0]); auto yVal = checkConstantIntVal(attr->args[1]); auto zVal = checkConstantIntVal(attr->args[2]); @@ -2748,7 +2748,7 @@ namespace Slang // This must be vk::binding or gl::binding (as specified in core.meta.slang under vk_binding/gl_binding) // Must have 2 int parameters. Ideally this would all be checked from the specification // in core.meta.slang, but that's not completely implemented. So for now we check here. - if (attr->args.Count() != 2) + if (attr->args.getCount() != 2) { return false; } @@ -2768,7 +2768,7 @@ namespace Slang } else if (auto maxVertexCountAttr = as<MaxVertexCountAttribute>(attr)) { - SLANG_ASSERT(attr->args.Count() == 1); + SLANG_ASSERT(attr->args.getCount() == 1); auto val = checkConstantIntVal(attr->args[0]); if(!val) return false; @@ -2777,7 +2777,7 @@ namespace Slang } else if(auto instanceAttr = as<InstanceAttribute>(attr)) { - SLANG_ASSERT(attr->args.Count() == 1); + SLANG_ASSERT(attr->args.getCount() == 1); auto val = checkConstantIntVal(attr->args[0]); if(!val) return false; @@ -2786,7 +2786,7 @@ namespace Slang } else if(auto entryPointAttr = as<EntryPointAttribute>(attr)) { - SLANG_ASSERT(attr->args.Count() == 1); + SLANG_ASSERT(attr->args.getCount() == 1); String stageName; if(!checkLiteralStringVal(attr->args[0], &stageName)) @@ -2825,22 +2825,22 @@ namespace Slang else if (as<PushConstantAttribute>(attr)) { // Has no args - SLANG_ASSERT(attr->args.Count() == 0); + SLANG_ASSERT(attr->args.getCount() == 0); } else if (as<ShaderRecordAttribute>(attr)) { // Has no args - SLANG_ASSERT(attr->args.Count() == 0); + SLANG_ASSERT(attr->args.getCount() == 0); } else if (as<EarlyDepthStencilAttribute>(attr)) { // Has no args - SLANG_ASSERT(attr->args.Count() == 0); + SLANG_ASSERT(attr->args.getCount() == 0); } else if (auto attrUsageAttr = as<AttributeUsageAttribute>(attr)) { uint32_t targetClassId = (uint32_t)UserDefinedAttributeTargets::None; - if (attr->args.Count() == 1) + if (attr->args.getCount() == 1) { RefPtr<IntVal> outIntVal; if (auto cInt = checkConstantEnumVal(attr->args[0])) @@ -2864,16 +2864,16 @@ namespace Slang // Check has an argument. We need this because default behavior is to give an error // if an attribute has arguments, but not handled explicitly (and the default param will come through // as 1 arg if nothing is specified) - SLANG_ASSERT(attr->args.Count() == 1); + SLANG_ASSERT(attr->args.getCount() == 1); } else if (auto userDefAttr = as<UserDefinedAttribute>(attr)) { // check arguments against attribute parameters defined in attribClassDecl - uint32_t paramIndex = 0; + Index paramIndex = 0; auto params = attribClassDecl->getMembersOfType<ParamDecl>(); for (auto paramDecl : params) { - if (paramIndex < attr->args.Count()) + if (paramIndex < attr->args.getCount()) { auto & arg = attr->args[paramIndex]; bool typeChecked = false; @@ -2896,18 +2896,18 @@ namespace Slang } paramIndex++; } - if (params.Count() < attr->args.Count()) + if (params.getCount() < attr->args.getCount()) { - getSink()->diagnose(attr, Diagnostics::tooManyArguments, attr->args.Count(), params.Count()); + getSink()->diagnose(attr, Diagnostics::tooManyArguments, attr->args.getCount(), params.getCount()); } - else if (params.Count() > attr->args.Count()) + else if (params.getCount() > attr->args.getCount()) { - getSink()->diagnose(attr, Diagnostics::notEnoughArguments, attr->args.Count(), params.Count()); + getSink()->diagnose(attr, Diagnostics::notEnoughArguments, attr->args.getCount(), params.getCount()); } } else if (auto formatAttr = as<FormatAttribute>(attr)) { - SLANG_ASSERT(attr->args.Count() == 1); + SLANG_ASSERT(attr->args.getCount() == 1); String formatName; if(!checkLiteralStringVal(attr->args[0], &formatName)) @@ -2916,7 +2916,7 @@ namespace Slang } ImageFormat format = ImageFormat::unknown; - if(!findImageFormatByName(formatName.Buffer(), &format)) + if(!findImageFormatByName(formatName.getBuffer(), &format)) { getSink()->diagnose(attr->args[0], Diagnostics::unknownImageFormatName, formatName); } @@ -2925,7 +2925,7 @@ namespace Slang } else { - if(attr->args.Count() == 0) + if(attr->args.getCount() == 0) { // If the attribute took no arguments, then we will // assume it is valid as written. @@ -2984,7 +2984,7 @@ namespace Slang // us to look at the attribute declaration itself. // // Start by doing argument/parameter matching - UInt argCount = attr->args.Count(); + UInt argCount = attr->args.getCount(); UInt paramCounter = 0; bool mismatch = false; for(auto paramDecl : attrDecl->getMembersOfType<ParamDecl>()) @@ -3008,7 +3008,7 @@ namespace Slang // default arguments as needed. // For now just copy the expression over. - attr->args.Add(paramDecl->initExpr); + attr->args.add(paramDecl->initExpr); } else { @@ -3317,9 +3317,9 @@ namespace Slang DeclRef<GenericDecl> requirementGenDecl, RefPtr<WitnessTable> witnessTable) { - if (genDecl.getDecl()->Members.Count() != requirementGenDecl.getDecl()->Members.Count()) + if (genDecl.getDecl()->Members.getCount() != requirementGenDecl.getDecl()->Members.getCount()) return false; - for (UInt i = 0; i < genDecl.getDecl()->Members.Count(); i++) + for (Index i = 0; i < genDecl.getDecl()->Members.getCount(); i++) { auto genMbr = genDecl.getDecl()->Members[i]; auto requiredGenMbr = genDecl.getDecl()->Members[i]; @@ -4049,7 +4049,7 @@ namespace Slang enumConformanceDecl->ParentDecl = decl; enumConformanceDecl->loc = decl->loc; enumConformanceDecl->base.type = getSession()->getEnumTypeType(); - decl->Members.Add(enumConformanceDecl); + decl->Members.add(enumConformanceDecl); // The `__EnumType` interface has one required member, the `__Tag` type. // We need to satisfy this requirement automatically, rather than require @@ -4329,11 +4329,11 @@ namespace Slang continue; if (auto typeParamDecl = as<GenericTypeParamDecl>(dd)) - outParams.Add(typeParamDecl); + outParams.add(typeParamDecl); else if (auto valueParamDecl = as<GenericValueParamDecl>(dd)) - outParams.Add(valueParamDecl); + outParams.add(valueParamDecl); else if (auto constraintDecl = as<GenericTypeConstraintDecl>(dd)) - outConstraints.Add(constraintDecl); + outConstraints.add(constraintDecl); } } @@ -4358,12 +4358,12 @@ namespace Slang // For there to be any hope of a match, the // two need to have the same number of parameters. - UInt paramCount = fstParams.Count(); - if (paramCount != sndParams.Count()) + Index paramCount = fstParams.getCount(); + if (paramCount != sndParams.getCount()) return false; // Now we'll walk through the parameters. - for (UInt pp = 0; pp < paramCount; ++pp) + for (Index pp = 0; pp < paramCount; ++pp) { Decl* fstParam = fstParams[pp]; Decl* sndParam = sndParams[pp]; @@ -4416,11 +4416,11 @@ namespace Slang // // For now I'm going to assume/require that all declarations must // declare the signature in a way that matches exactly. - UInt constraintCount = fstConstraints.Count(); - if(constraintCount != sndConstraints.Count()) + Index constraintCount = fstConstraints.getCount(); + if(constraintCount != sndConstraints.getCount()) return false; - for (UInt cc = 0; cc < constraintCount; ++cc) + for (Index cc = 0; cc < constraintCount; ++cc) { //auto fstConstraint = fstConstraints[cc]; //auto sndConstraint = sndConstraints[cc]; @@ -4448,12 +4448,12 @@ namespace Slang // If the functions have different numbers of parameters, then // their signatures trivially don't match. - auto fstParamCount = fstParams.Count(); - auto sndParamCount = sndParams.Count(); + auto fstParamCount = fstParams.getCount(); + auto sndParamCount = sndParams.getCount(); if (fstParamCount != sndParamCount) return false; - for (UInt ii = 0; ii < fstParamCount; ++ii) + for (Index ii = 0; ii < fstParamCount; ++ii) { auto fstParam = fstParams[ii]; auto sndParam = sndParams[ii]; @@ -4495,13 +4495,13 @@ namespace Slang { auto type = DeclRefType::Create(getSession(), makeDeclRef(typeParam)); - subst->args.Add(type); + subst->args.add(type); } else if (auto valueParam = as<GenericValueParamDecl>(dd)) { auto val = new GenericParamIntVal( makeDeclRef(valueParam)); - subst->args.Add(val); + subst->args.add(val); } // TODO: need to handle constraints here? } @@ -4845,8 +4845,8 @@ namespace Slang template<typename T> T* FindOuterStmt() { - UInt outerStmtCount = outerStmts.Count(); - for (UInt ii = outerStmtCount; ii > 0; --ii) + const Index outerStmtCount = outerStmts.getCount(); + for (Index ii = outerStmtCount; ii > 0; --ii) { auto outerStmt = outerStmts[ii-1]; auto found = as<T>(outerStmt); @@ -4877,12 +4877,12 @@ namespace Slang void PushOuterStmt(Stmt* stmt) { - outerStmts.Add(stmt); + outerStmts.add(stmt); } void PopOuterStmt(Stmt* /*stmt*/) { - outerStmts.RemoveAt(outerStmts.Count() - 1); + outerStmts.removeAt(outerStmts.getCount() - 1); } RefPtr<Expr> checkPredicateExpr(Expr* expr) @@ -5220,7 +5220,7 @@ namespace Slang // Let's not constant-fold operations with more than a certain number of arguments, for simplicity static const int kMaxArgs = 8; - if (invokeExpr->Arguments.Count() > kMaxArgs) + if (invokeExpr->Arguments.getCount() > kMaxArgs) return nullptr; // Before checking the operation name, let's look at the arguments @@ -5483,8 +5483,8 @@ namespace Slang auto substitutions = new GenericSubstitution(); substitutions->genericDecl = vectorGenericDecl.Ptr(); - substitutions->args.Add(elementType); - substitutions->args.Add(elementCount); + substitutions->args.add(elementType); + substitutions->args.add(elementCount); auto declRef = DeclRef<Decl>(vectorTypeDecl.Ptr(), substitutions); @@ -5588,7 +5588,7 @@ namespace Slang subscriptCallExpr->FunctionExpr = subscriptFuncExpr; // TODO(tfoley): This path can support multiple arguments easily - subscriptCallExpr->Arguments.Add(subscriptExpr->IndexExpression); + subscriptCallExpr->Arguments.add(subscriptExpr->IndexExpression); return CheckInvokeExprWithCheckedOperands(subscriptCallExpr.Ptr()); } @@ -5602,9 +5602,9 @@ namespace Slang bool MatchArguments(FuncDecl * functionNode, List <RefPtr<Expr>> &args) { - if (functionNode->GetParameters().Count() != args.Count()) + if (functionNode->GetParameters().getCount() != args.getCount()) return false; - int i = 0; + Index i = 0; for (auto param : functionNode->GetParameters()) { if (!param->type.Equals(args[i]->type.Ptr())) @@ -5832,7 +5832,7 @@ namespace Slang getterDecl->loc = decl->loc; getterDecl->ParentDecl = decl; - decl->Members.Add(getterDecl); + decl->Members.add(getterDecl); } for(auto mm : decl->Members) @@ -6221,7 +6221,7 @@ namespace Slang if(outWitness) { - caseWitnesses.Add(caseWitness); + caseWitnesses.add(caseWitness); } } @@ -6249,7 +6249,7 @@ namespace Slang RefPtr<TaggedUnionSubtypeWitness> taggedUnionWitness = new TaggedUnionSubtypeWitness(); taggedUnionWitness->sub = taggedUnionType; taggedUnionWitness->sup = DeclRefType::Create(getSession(), interfaceDeclRef); - taggedUnionWitness->caseWitnesses.SwapWith(caseWitnesses); + taggedUnionWitness->caseWitnesses.swapWith(caseWitnesses); *outWitness = taggedUnionWitness; } @@ -6556,7 +6556,7 @@ namespace Slang // failure! return SubstitutionSet(); } - args.Add(type); + args.add(type); } else if (auto valParam = m.as<GenericValueParamDecl>()) { @@ -6593,7 +6593,7 @@ namespace Slang // failure! return SubstitutionSet(); } - args.Add(val); + args.add(val); } else { @@ -6638,7 +6638,7 @@ namespace Slang if(subTypeWitness) { // We found a witness, so it will become an (implicit) argument. - solvedSubst->args.Add(subTypeWitness); + solvedSubst->args.add(subTypeWitness); } else { @@ -6690,13 +6690,13 @@ namespace Slang SourceLoc funcLoc; // The original arguments to the call - UInt argCount = 0; + Index argCount = 0; RefPtr<Expr>* args = nullptr; RefPtr<Type>* argTypes = nullptr; - UInt getArgCount() { return argCount; } - RefPtr<Expr>& getArg(UInt index) { return args[index]; } - RefPtr<Type>& getArgType(UInt index) + Index getArgCount() { return argCount; } + RefPtr<Expr>& getArg(Index index) { return args[index]; } + RefPtr<Type>& getArgType(Index index) { if(argTypes) return argTypes[index]; @@ -6875,7 +6875,7 @@ namespace Slang candidate.subst = genSubst; auto& checkedArgs = genSubst->args; - uint32_t aa = 0; + Index aa = 0; for (auto memberRef : getMembers(genericDeclRef)) { if (auto typeParamRef = memberRef.as<GenericTypeParamDecl>()) @@ -6899,7 +6899,7 @@ namespace Slang { typeExp = CoerceToProperType(TypeExp(arg)); } - checkedArgs.Add(typeExp.type); + checkedArgs.add(typeExp.type); } else if (auto valParamRef = memberRef.as<GenericValueParamDecl>()) { @@ -6917,7 +6917,7 @@ namespace Slang arg = coerce(GetType(valParamRef), arg); auto val = ExtractGenericArgInteger(arg); - checkedArgs.Add(val); + checkedArgs.add(val); } else { @@ -6933,7 +6933,7 @@ namespace Slang OverloadResolveContext& context, OverloadCandidate& candidate) { - UInt argCount = context.getArgCount(); + Index argCount = context.getArgCount(); List<DeclRef<ParamDecl>> params; switch (candidate.flavor) @@ -6952,9 +6952,9 @@ namespace Slang // Note(tfoley): We might have fewer arguments than parameters in the // case where one or more parameters had defaults. - SLANG_RELEASE_ASSERT(argCount <= params.Count()); + SLANG_RELEASE_ASSERT(argCount <= params.getCount()); - for (UInt ii = 0; ii < argCount; ++ii) + for (Index ii = 0; ii < argCount; ++ii) { auto& arg = context.getArg(ii); auto argType = context.getArgType(ii); @@ -7072,7 +7072,7 @@ namespace Slang auto subTypeWitness = tryGetSubtypeWitness(sub, sup); if(subTypeWitness) { - subst->args.Add(subTypeWitness); + subst->args.add(subTypeWitness); } else { @@ -7206,8 +7206,8 @@ namespace Slang callExpr = new InvokeExpr(); callExpr->loc = context.loc; - for(UInt aa = 0; aa < context.argCount; ++aa) - callExpr->Arguments.Add(context.getArg(aa)); + for(Index aa = 0; aa < context.argCount; ++aa) + callExpr->Arguments.add(context.getArg(aa)); } @@ -7290,13 +7290,13 @@ namespace Slang bool keepThisCandidate = true; // should this candidate be kept? - if (context.bestCandidates.Count() != 0) + if (context.bestCandidates.getCount() != 0) { // We have multiple candidates right now, so filter them. bool anyFiltered = false; // Note that we are querying the list length on every iteration, // because we might remove things. - for (UInt cc = 0; cc < context.bestCandidates.Count(); ++cc) + for (Index cc = 0; cc < context.bestCandidates.getCount(); ++cc) { int cmp = CompareOverloadCandidates(&candidate, &context.bestCandidates[cc]); if (cmp < 0) @@ -7304,7 +7304,7 @@ namespace Slang // our new candidate is better! // remove it from the list (by swapping in a later one) - context.bestCandidates.FastRemoveAt(cc); + context.bestCandidates.fastRemoveAt(cc); // and then reduce our index so that we re-visit the same index --cc; @@ -7344,16 +7344,16 @@ namespace Slang return; // Otherwise we want to keep the candidate - if (context.bestCandidates.Count() > 0) + if (context.bestCandidates.getCount() > 0) { // There were already multiple candidates, and we are adding one more - context.bestCandidates.Add(candidate); + context.bestCandidates.add(candidate); } else if (context.bestCandidate) { // There was a unique best candidate, but now we are ambiguous - context.bestCandidates.Add(*context.bestCandidate); - context.bestCandidates.Add(candidate); + context.bestCandidates.add(*context.bestCandidate); + context.bestCandidates.add(candidate); context.bestCandidate = nullptr; } else @@ -7581,10 +7581,10 @@ namespace Slang return false; // Their arguments must unify - SLANG_RELEASE_ASSERT(fstGen->args.Count() == sndGen->args.Count()); - UInt argCount = fstGen->args.Count(); + SLANG_RELEASE_ASSERT(fstGen->args.getCount() == sndGen->args.getCount()); + Index argCount = fstGen->args.getCount(); bool okay = true; - for (UInt aa = 0; aa < argCount; ++aa) + for (Index aa = 0; aa < argCount; ++aa) { if (!TryUnifyVals(constraints, fstGen->args[aa], sndGen->args[aa])) { @@ -7612,7 +7612,7 @@ namespace Slang constraint.decl = typeParamDecl.Ptr(); constraint.val = type; - constraints.constraints.Add(constraint); + constraints.constraints.add(constraint); return true; } @@ -7635,7 +7635,7 @@ namespace Slang constraint.decl = paramDecl.Ptr(); constraint.val = val; - constraints.constraints.Add(constraint); + constraints.constraints.add(constraint); return true; } @@ -7925,8 +7925,8 @@ namespace Slang { auto params = GetParameters(funcDeclRef).ToArray(); - UInt argCount = context.getArgCount(); - UInt paramCount = params.Count(); + Index argCount = context.getArgCount(); + Index paramCount = params.getCount(); // Bail out on mismatch. // TODO(tfoley): need more nuance here @@ -7935,7 +7935,7 @@ namespace Slang return DeclRef<Decl>(nullptr, nullptr); } - for (UInt aa = 0; aa < argCount; ++aa) + for (Index aa = 0; aa < argCount; ++aa) { #if 0 if (!TryUnifyArgAndParamTypes(constraints, args[aa], params[aa])) @@ -8418,8 +8418,8 @@ namespace Slang context.originalExpr = expr; context.funcLoc = funcExpr->loc; - context.argCount = expr->Arguments.Count(); - context.args = expr->Arguments.Buffer(); + context.argCount = expr->Arguments.getCount(); + context.args = expr->Arguments.getBuffer(); context.loc = expr->loc; if (auto funcMemberExpr = as<MemberExpr>(funcExpr)) @@ -8440,7 +8440,7 @@ namespace Slang AddOverloadCandidates(funcExpr, context); } - if (context.bestCandidates.Count() > 0) + if (context.bestCandidates.getCount() > 0) { // Things were ambiguous. @@ -8495,9 +8495,9 @@ namespace Slang } { - UInt candidateCount = context.bestCandidates.Count(); - UInt maxCandidatesToPrint = 10; // don't show too many candidates at once... - UInt candidateIndex = 0; + Index candidateCount = context.bestCandidates.getCount(); + Index maxCandidatesToPrint = 10; // don't show too many candidates at once... + Index candidateIndex = 0; for (auto candidate : context.bestCandidates) { String declString = getDeclSignatureString(candidate.item); @@ -8634,15 +8634,15 @@ namespace Slang OverloadResolveContext context; context.originalExpr = genericAppExpr; context.funcLoc = baseExpr->loc; - context.argCount = args.Count(); - context.args = args.Buffer(); + context.argCount = args.getCount(); + context.args = args.getBuffer(); context.loc = genericAppExpr->loc; context.baseExpr = GetBaseExpr(baseExpr); AddGenericOverloadCandidates(baseExpr, context); - if (context.bestCandidates.Count() > 0) + if (context.bestCandidates.getCount() > 0) { // Things were ambiguous. if (context.bestCandidates[0].status != OverloadCandidate::Status::Applicable) @@ -8666,7 +8666,7 @@ namespace Slang for (auto candidate : context.bestCandidates) { auto candidateExpr = CompleteOverloadCandidate(context, candidate); - overloadedExpr->candidiateExprs.Add(candidateExpr); + overloadedExpr->candidiateExprs.add(candidateExpr); } return overloadedExpr; } @@ -8708,7 +8708,7 @@ namespace Slang for( auto& caseTypeExpr : expr->caseTypes ) { caseTypeExpr = CheckProperType(caseTypeExpr); - type->caseTypes.Add(caseTypeExpr.type); + type->caseTypes.add(caseTypeExpr.type); } return expr; @@ -8735,8 +8735,8 @@ namespace Slang // if this is still an invoke expression, test arguments passed to inout/out parameter are LValues if(auto funcType = as<FuncType>(invoke->FunctionExpr->type)) { - UInt paramCount = funcType->getParamCount(); - for (UInt pp = 0; pp < paramCount; ++pp) + Index paramCount = funcType->getParamCount(); + for (Index pp = 0; pp < paramCount; ++pp) { auto paramType = funcType->getParamType(pp); if (as<OutTypeBase>(paramType) || as<RefType>(paramType)) @@ -8748,7 +8748,7 @@ namespace Slang // for an `inout` parameter to be converted in both // directions. // - if( pp < expr->Arguments.Count() ) + if( pp < expr->Arguments.getCount() ) { auto argExpr = expr->Arguments[pp]; if( !argExpr->type.IsLeftValue ) @@ -8945,7 +8945,7 @@ namespace Slang auto swizzleText = getText(memberRefExpr->name); - for (UInt i = 0; i < swizzleText.Length(); i++) + for (Index i = 0; i < swizzleText.getLength(); i++) { auto ch = swizzleText[i]; int elementIndex = -1; @@ -9121,7 +9121,7 @@ namespace Slang if (isUsableAsStaticMember(item)) { // If yes, then it will be part of the output. - staticItems.Add(item); + staticItems.add(item); } else { @@ -9135,7 +9135,7 @@ namespace Slang { // If we had some static items, then that's okay, // we just want to use our newly-filtered list. - if (staticItems.Count()) + if (staticItems.getCount()) { lookupResult.items = staticItems; } @@ -9585,7 +9585,7 @@ namespace Slang { // Each leaf parameter of interface type adds one slot. // - ioSlots.paramTypes.Add(type); + ioSlots.paramTypes.add(type); } else if( auto structDeclRef = typeDeclRef.as<StructDecl>() ) { @@ -9621,13 +9621,12 @@ namespace Slang ExistentialTypeSlots& ioSlots, DeclRef<VarDeclBase> paramDeclRef) { - UInt startSlot = ioSlots.paramTypes.Count(); + Index startSlot = ioSlots.paramTypes.getCount(); _collectExistentialTypeParamsRec(ioSlots, paramDeclRef); - UInt endSlot = ioSlots.paramTypes.Count(); - UInt slotCount = endSlot - startSlot; - - ioParamInfo.firstExistentialTypeSlot = startSlot; - ioParamInfo.existentialTypeSlotCount = slotCount; + Index endSlot = ioSlots.paramTypes.getCount(); + + ioParamInfo.firstExistentialTypeSlot = UInt(startSlot); + ioParamInfo.existentialTypeSlotCount = UInt(endSlot - startSlot);; } /// Enumerate the existential-type parameters of an `EntryPoint`. @@ -9652,7 +9651,7 @@ namespace Slang m_existentialSlots, paramDeclRef); - m_shaderParams.Add(shaderParamInfo); + m_shaderParams.add(shaderParamInfo); } } } @@ -9714,7 +9713,7 @@ namespace Slang if (attr) { - if (attr->args.Count() != 1) + if (attr->args.getCount() != 1) { sink->diagnose(attr, Diagnostics::badlyDefinedPatchConstantFunc, entryPointName); return; @@ -9764,7 +9763,7 @@ namespace Slang { const auto& semanticToken = semantic->name; - String lowerName = String(semanticToken.Content).ToLower(); + String lowerName = String(semanticToken.Content).toLower(); if(lowerName == "sv_dispatchthreadid") { @@ -10033,7 +10032,7 @@ static void collectFields( if(fieldDeclRef.getDecl()->HasModifier<HLSLStaticModifier>()) continue; - outFields.Add(fieldDeclRef); + outFields.add(fieldDeclRef); } } @@ -10112,14 +10111,14 @@ static bool validateGenericSubstitutionsMatch( - UInt argCount = left->args.Count(); - if( argCount != right->args.Count() ) + Index argCount = left->args.getCount(); + if( argCount != right->args.getCount() ) { diagnoseTypeMismatch(sink, stack); return false; } - for( UInt aa = 0; aa < argCount; ++aa ) + for( Index aa = 0; aa < argCount; ++aa ) { auto leftArg = left->args[aa]; auto rightArg = right->args[aa]; @@ -10256,8 +10255,8 @@ static bool validateTypesMatch( collectFields(leftStructDeclRef, leftFields); collectFields(rightStructDeclRef, rightFields); - UInt leftFieldCount = leftFields.Count(); - UInt rightFieldCount = rightFields.Count(); + Index leftFieldCount = leftFields.getCount(); + Index rightFieldCount = rightFields.getCount(); if( leftFieldCount != rightFieldCount ) { @@ -10265,7 +10264,7 @@ static bool validateTypesMatch( return false; } - for( UInt ii = 0; ii < leftFieldCount; ++ii ) + for( Index ii = 0; ii < leftFieldCount; ++ii ) { auto leftField = leftFields[ii]; auto rightField = rightFields[ii]; @@ -10399,13 +10398,13 @@ static bool doesParameterMatch( // consider the new variable to be a redclaration of // the existing one. - existingParam.additionalParamDeclRefs.Add( + existingParam.additionalParamDeclRefs.add( makeDeclRef(globalVar.Ptr())); continue; } } - Int newParamIndex = Int(m_shaderParams.Count()); + Int newParamIndex = Int(m_shaderParams.getCount()); mapNameToParamIndex.Add(paramName, newParamIndex); GlobalShaderParamInfo shaderParamInfo; @@ -10416,7 +10415,7 @@ static bool doesParameterMatch( m_globalExistentialSlots, makeDeclRef(globalVar.Ptr())); - m_shaderParams.Add(shaderParamInfo); + m_shaderParams.add(shaderParamInfo); } } } @@ -10476,7 +10475,7 @@ static bool doesParameterMatch( if( entryPoint ) { program->addEntryPoint(entryPoint); - entryPointReq->getTranslationUnit()->entryPoints.Add(entryPoint); + entryPointReq->getTranslationUnit()->entryPoints.add(entryPoint); } } @@ -10501,8 +10500,8 @@ static bool doesParameterMatch( // For now we'll start with an extremely basic approach that // should work for typical HLSL code. // - UInt translationUnitCount = compileRequest->translationUnits.Count(); - for(UInt tt = 0; tt < translationUnitCount; ++tt) + Index translationUnitCount = compileRequest->translationUnits.getCount(); + for(Index tt = 0; tt < translationUnitCount; ++tt) { auto translationUnit = compileRequest->translationUnits[tt]; for( auto globalDecl : translationUnit->getModuleDecl()->Members ) @@ -10542,7 +10541,7 @@ static bool doesParameterMatch( validateEntryPoint(entryPoint, sink); program->addEntryPoint(entryPoint); - translationUnit->entryPoints.Add(entryPoint); + translationUnit->entryPoints.add(entryPoint); } } } @@ -10558,8 +10557,8 @@ static bool doesParameterMatch( List<RefPtr<Expr>> const& args, DiagnosticSink* sink) { - UInt slotCount = ioSlots.paramTypes.Count(); - UInt argCount = args.Count(); + Index slotCount = ioSlots.paramTypes.getCount(); + Index argCount = args.getCount(); if( slotCount != argCount ) { @@ -10569,7 +10568,7 @@ static bool doesParameterMatch( SemanticsVisitor visitor(linkage, sink); - for( UInt ii = 0; ii < slotCount; ++ii ) + for( Index ii = 0; ii < slotCount; ++ii ) { auto slotType = ioSlots.paramTypes[ii]; auto argExpr = args[ii]; @@ -10597,7 +10596,7 @@ static bool doesParameterMatch( ExistentialTypeSlots::Arg arg; arg.type = argType; arg.witness = witness; - ioSlots.args.Add(arg); + ioSlots.args.add(arg); } } @@ -10722,7 +10721,7 @@ static bool doesParameterMatch( // List<RefPtr<Scope>> scopesToTry; for( auto module : unspecialiedProgram->getModuleDependencies() ) - scopesToTry.Add(module->getModuleDecl()->scope); + scopesToTry.add(module->getModuleDecl()->scope); // We are going to do some semantic checking, so we need to // set up a `SemanticsVistitor` that we can use. @@ -10753,7 +10752,7 @@ static bool doesParameterMatch( } } - outGenericArgs.Add(argExpr); + outGenericArgs.add(argExpr); } } @@ -10802,7 +10801,7 @@ static bool doesParameterMatch( for(auto module : unspecializedProgram->getModuleDependencies()) { for(auto param : module->getModuleDecl()->getMembersOfType<GlobalGenericParamDecl>()) - globalGenericParams.Add(param); + globalGenericParams.add(param); } // Next, we will check whether the supplied arguments can @@ -10811,11 +10810,11 @@ static bool doesParameterMatch( // An easy early-out case will be if the number of // arguments isn't correct. // - if (globalGenericParams.Count() != globalGenericArgs.Count()) + if (globalGenericParams.getCount() != globalGenericArgs.getCount()) { sink->diagnose(SourceLoc(), Diagnostics::mismatchGlobalGenericArguments, - globalGenericParams.Count(), - globalGenericArgs.Count()); + globalGenericParams.getCount(), + globalGenericArgs.getCount()); return nullptr; } @@ -10847,12 +10846,12 @@ static bool doesParameterMatch( // // We will punt on this for now, and just check each constraint in isolation. // - UInt argCounter = 0; + Index argCounter = 0; for(auto& globalGenericParam : globalGenericParams) { // Get the argument that matches this parameter. - UInt argIndex = argCounter++; - SLANG_ASSERT(argIndex < globalGenericArgs.Count()); + Index argIndex = argCounter++; + SLANG_ASSERT(argIndex < globalGenericArgs.getCount()); auto globalGenericArg = checkProperType(linkage, TypeExp(globalGenericArgs[argIndex]), sink); if (!globalGenericArg) { @@ -10919,7 +10918,7 @@ static bool doesParameterMatch( GlobalGenericParamSubstitution::ConstraintArg constraintArg; constraintArg.decl = constraint; constraintArg.val = witness; - subst->constraintArgs.Add(constraintArg); + subst->constraintArgs.add(constraintArg); } // Add the substitution for this parameter to the global substitution @@ -11049,14 +11048,14 @@ static bool doesParameterMatch( // ahead and consider all the entry points that were found // by the front-end. // - UInt entryPointCount = endToEndReq->entryPoints.Count(); + Index entryPointCount = endToEndReq->entryPoints.getCount(); if( entryPointCount == 0 ) { entryPointCount = unspecializedProgram->getEntryPointCount(); - endToEndReq->entryPoints.SetSize(entryPointCount); + endToEndReq->entryPoints.setCount(entryPointCount); } - for( UInt ii = 0; ii < entryPointCount; ++ii ) + for( Index ii = 0; ii < entryPointCount; ++ii ) { auto unspecializedEntryPoint = unspecializedProgram->getEntryPoint(ii); auto& entryPointInfo = endToEndReq->entryPoints[ii]; @@ -11228,11 +11227,11 @@ static bool doesParameterMatch( { if( auto genericTypeParamDecl = as<GenericTypeParamDecl>(mm) ) { - genericSubst->args.Add(DeclRefType::Create(session, DeclRef<Decl>(genericTypeParamDecl, outerSubst))); + genericSubst->args.add(DeclRefType::Create(session, DeclRef<Decl>(genericTypeParamDecl, outerSubst))); } else if( auto genericValueParamDecl = as<GenericValueParamDecl>(mm) ) { - genericSubst->args.Add(new GenericParamIntVal(DeclRef<GenericValueParamDecl>(genericValueParamDecl, outerSubst))); + genericSubst->args.add(new GenericParamIntVal(DeclRef<GenericValueParamDecl>(genericValueParamDecl, outerSubst))); } } @@ -11245,7 +11244,7 @@ static bool doesParameterMatch( witness->declRef = DeclRef<Decl>(genericTypeConstraintDecl, outerSubst); witness->sub = genericTypeConstraintDecl->sub.type; witness->sup = genericTypeConstraintDecl->sup.type; - genericSubst->args.Add(witness); + genericSubst->args.add(witness); } } diff --git a/source/slang/compiler.cpp b/source/slang/compiler.cpp index 1222d91d2..83a579345 100644 --- a/source/slang/compiler.cpp +++ b/source/slang/compiler.cpp @@ -90,11 +90,11 @@ namespace Slang if (appendTo == ResultFormat::Text) { - outputString.append(result.outputString.Buffer()); + outputString.append(result.outputString.getBuffer()); } else if (appendTo == ResultFormat::Binary) { - outputBinary.AddRange(result.outputBinary.Buffer(), result.outputBinary.Count()); + outputBinary.addRange(result.outputBinary.getBuffer(), result.outputBinary.getCount()); } } @@ -113,7 +113,7 @@ namespace Slang break; case ResultFormat::Binary: - blob = createRawBlob(outputBinary.Buffer(), outputBinary.Count()); + blob = createRawBlob(outputBinary.getBuffer(), outputBinary.getCount()); break; } } @@ -221,7 +221,7 @@ namespace Slang { if( auto taggedUnionType = as<TaggedUnionType>(arg) ) { - m_taggedUnionTypes.Add(taggedUnionType); + m_taggedUnionTypes.add(taggedUnionType); } } } @@ -634,7 +634,7 @@ namespace Slang const auto& sourceFiles = translationUnitRequest->getSourceFiles(); - const int numSourceFiles = int(sourceFiles.Count()); + const Index numSourceFiles = sourceFiles.getCount(); switch (numSourceFiles) { @@ -675,7 +675,7 @@ namespace Slang EndToEndCompileRequest* endToEndReq, List<uint8_t>& byteCodeOut) { - byteCodeOut.Clear(); + byteCodeOut.clear(); auto session = compileRequest->getSession(); auto sink = compileRequest->getSink(); @@ -687,7 +687,7 @@ namespace Slang } auto hlslCode = emitHLSLForEntryPoint(compileRequest, entryPoint, entryPointIndex, targetReq, endToEndReq); - maybeDumpIntermediate(compileRequest, hlslCode.Buffer(), CodeGenTarget::HLSL); + maybeDumpIntermediate(compileRequest, hlslCode.getBuffer(), CodeGenTarget::HLSL); auto profile = getEffectiveProfile(entryPoint, targetReq); @@ -704,21 +704,21 @@ namespace Slang for( auto& define : translationUnit->compileRequest->preprocessorDefinitions ) { D3D_SHADER_MACRO dxMacro; - dxMacro.Name = define.Key.Buffer(); - dxMacro.Definition = define.Value.Buffer(); - dxMacrosStorage.Add(dxMacro); + dxMacro.Name = define.Key.getBuffer(); + dxMacro.Definition = define.Value.getBuffer(); + dxMacrosStorage.add(dxMacro); } for( auto& define : translationUnit->preprocessorDefinitions ) { D3D_SHADER_MACRO dxMacro; - dxMacro.Name = define.Key.Buffer(); - dxMacro.Definition = define.Value.Buffer(); - dxMacrosStorage.Add(dxMacro); + dxMacro.Name = define.Key.getBuffer(); + dxMacro.Definition = define.Value.getBuffer(); + dxMacrosStorage.add(dxMacro); } D3D_SHADER_MACRO nullTerminator = { 0, 0 }; - dxMacrosStorage.Add(nullTerminator); + dxMacrosStorage.add(nullTerminator); - dxMacros = dxMacrosStorage.Buffer(); + dxMacros = dxMacrosStorage.getBuffer(); } DWORD flags = 0; @@ -774,12 +774,12 @@ namespace Slang ComPtr<ID3DBlob> diagnosticsBlob; HRESULT hr = compileFunc( hlslCode.begin(), - hlslCode.Length(), - sourcePath.Buffer(), + hlslCode.getLength(), + sourcePath.getBuffer(), dxMacros, nullptr, getText(entryPoint->getName()).begin(), - GetHLSLProfileName(profile).Buffer(), + GetHLSLProfileName(profile).getBuffer(), flags, 0, // unused: effect flags codeBlob.writeRef(), @@ -787,7 +787,7 @@ namespace Slang if (codeBlob && SLANG_SUCCEEDED(hr)) { - byteCodeOut.AddRange((uint8_t const*)codeBlob->GetBufferPointer(), (int)codeBlob->GetBufferSize()); + byteCodeOut.addRange((uint8_t const*)codeBlob->GetBufferPointer(), (int)codeBlob->GetBufferSize()); } if (FAILED(hr)) @@ -853,11 +853,11 @@ namespace Slang targetReq, endToEndReq, dxbc)); - if (!dxbc.Count()) + if (!dxbc.getCount()) { return SLANG_FAIL; } - return dissassembleDXBC(compileRequest, dxbc.Buffer(), dxbc.Count(), assemOut); + return dissassembleDXBC(compileRequest, dxbc.getBuffer(), dxbc.getCount(), assemOut); } #endif @@ -955,7 +955,7 @@ SlangResult dissassembleDXILUsingDXC( EndToEndCompileRequest* endToEndReq, List<uint8_t>& spirvOut) { - spirvOut.Clear(); + spirvOut.clear(); String rawGLSL = emitGLSLForEntryPoint( slangRequest, @@ -963,18 +963,18 @@ SlangResult dissassembleDXILUsingDXC( entryPointIndex, targetReq, endToEndReq); - maybeDumpIntermediate(slangRequest, rawGLSL.Buffer(), CodeGenTarget::GLSL); + maybeDumpIntermediate(slangRequest, rawGLSL.getBuffer(), CodeGenTarget::GLSL); auto outputFunc = [](void const* data, size_t size, void* userData) { - ((List<uint8_t>*)userData)->AddRange((uint8_t*)data, size); + ((List<uint8_t>*)userData)->addRange((uint8_t*)data, size); }; const String sourcePath = calcSourcePathForEntryPoint(endToEndReq, entryPointIndex); glslang_CompileRequest request; request.action = GLSLANG_ACTION_COMPILE_GLSL_TO_SPIRV; - request.sourcePath = sourcePath.Buffer(); + request.sourcePath = sourcePath.getBuffer(); request.slangStage = (SlangStage)entryPoint->getStage(); request.inputBegin = rawGLSL.begin(); @@ -1004,10 +1004,10 @@ SlangResult dissassembleDXILUsingDXC( endToEndReq, spirv)); - if (spirv.Count() == 0) + if (spirv.getCount() == 0) return SLANG_FAIL; - return dissassembleSPIRV(slangRequest, spirv.begin(), spirv.Count(), assemblyOut); + return dissassembleSPIRV(slangRequest, spirv.begin(), spirv.getCount(), assemblyOut); } #endif @@ -1033,7 +1033,7 @@ SlangResult dissassembleDXILUsingDXC( entryPointIndex, targetReq, endToEndReq); - maybeDumpIntermediate(compileRequest, code.Buffer(), target); + maybeDumpIntermediate(compileRequest, code.getBuffer(), target); result = CompileResult(code); } break; @@ -1046,7 +1046,7 @@ SlangResult dissassembleDXILUsingDXC( entryPointIndex, targetReq, endToEndReq); - maybeDumpIntermediate(compileRequest, code.Buffer(), target); + maybeDumpIntermediate(compileRequest, code.getBuffer(), target); result = CompileResult(code); } break; @@ -1063,7 +1063,7 @@ SlangResult dissassembleDXILUsingDXC( endToEndReq, code))) { - maybeDumpIntermediate(compileRequest, code.Buffer(), code.Count(), target); + maybeDumpIntermediate(compileRequest, code.getBuffer(), code.getCount(), target); result = CompileResult(code); } } @@ -1080,7 +1080,7 @@ SlangResult dissassembleDXILUsingDXC( endToEndReq, code))) { - maybeDumpIntermediate(compileRequest, code.Buffer(), target); + maybeDumpIntermediate(compileRequest, code.getBuffer(), target); result = CompileResult(code); } } @@ -1099,7 +1099,7 @@ SlangResult dissassembleDXILUsingDXC( endToEndReq, code))) { - maybeDumpIntermediate(compileRequest, code.Buffer(), code.Count(), target); + maybeDumpIntermediate(compileRequest, code.getBuffer(), code.getCount(), target); result = CompileResult(code); } } @@ -1119,11 +1119,11 @@ SlangResult dissassembleDXILUsingDXC( String assembly; dissassembleDXILUsingDXC( compileRequest, - code.Buffer(), - code.Count(), + code.getBuffer(), + code.getCount(), assembly); - maybeDumpIntermediate(compileRequest, assembly.Buffer(), target); + maybeDumpIntermediate(compileRequest, assembly.getBuffer(), target); result = CompileResult(assembly); } @@ -1142,7 +1142,7 @@ SlangResult dissassembleDXILUsingDXC( endToEndReq, code))) { - maybeDumpIntermediate(compileRequest, code.Buffer(), code.Count(), target); + maybeDumpIntermediate(compileRequest, code.getBuffer(), code.getCount(), target); result = CompileResult(code); } } @@ -1159,7 +1159,7 @@ SlangResult dissassembleDXILUsingDXC( endToEndReq, code))) { - maybeDumpIntermediate(compileRequest, code.Buffer(), target); + maybeDumpIntermediate(compileRequest, code.getBuffer(), target); result = CompileResult(code); } } @@ -1229,7 +1229,7 @@ SlangResult dissassembleDXILUsingDXC( OutputFileKind kind) { FILE* file = fopen( - path.Buffer(), + path.getBuffer(), kind == OutputFileKind::Binary ? "wb" : "w"); if (!file) { @@ -1287,7 +1287,7 @@ SlangResult dissassembleDXILUsingDXC( ISlangWriter* writer, String const& text) { - writer->write(text.Buffer(), text.Length()); + writer->write(text.getBuffer(), text.getLength()); } static void writeEntryPointResultToStandardOutput( @@ -1425,7 +1425,7 @@ SlangResult dissassembleDXILUsingDXC( // Generate target code any entry points that // have been requested for compilation. auto entryPointCount = program->getEntryPointCount(); - for(UInt ii = 0; ii < entryPointCount; ++ii) + for(Index ii = 0; ii < entryPointCount; ++ii) { auto entryPoint = program->getEntryPoint(ii); CompileResult entryPointResult = emitEntryPoint( @@ -1472,8 +1472,8 @@ SlangResult dissassembleDXILUsingDXC( auto program = compileRequest->getSpecializedProgram(); for (auto targetReq : linkage->targets) { - UInt entryPointCount = program->getEntryPointCount(); - for (UInt ee = 0; ee < entryPointCount; ++ee) + Index entryPointCount = program->getEntryPointCount(); + for (Index ee = 0; ee < entryPointCount; ++ee) { writeEntryPointResult( compileRequest, @@ -1516,7 +1516,7 @@ SlangResult dissassembleDXILUsingDXC( path.append(id); path.append(ext); - FILE* file = fopen(path.Buffer(), isBinary ? "wb" : "w"); + FILE* file = fopen(path.getBuffer(), isBinary ? "wb" : "w"); if (!file) return; fwrite(data, size, 1, file); @@ -1578,7 +1578,7 @@ SlangResult dissassembleDXILUsingDXC( { String spirvAssembly; dissassembleSPIRV(compileRequest, data, size, spirvAssembly); - dumpIntermediateText(compileRequest, spirvAssembly.begin(), spirvAssembly.Length(), ".spv.asm"); + dumpIntermediateText(compileRequest, spirvAssembly.begin(), spirvAssembly.getLength(), ".spv.asm"); } break; @@ -1592,7 +1592,7 @@ SlangResult dissassembleDXILUsingDXC( { String dxbcAssembly; dissassembleDXBC(compileRequest, data, size, dxbcAssembly); - dumpIntermediateText(compileRequest, dxbcAssembly.begin(), dxbcAssembly.Length(), ".dxbc.asm"); + dumpIntermediateText(compileRequest, dxbcAssembly.begin(), dxbcAssembly.getLength(), ".dxbc.asm"); } break; #endif @@ -1607,7 +1607,7 @@ SlangResult dissassembleDXILUsingDXC( { String dxilAssembly; dissassembleDXILUsingDXC(compileRequest, data, size, dxilAssembly); - dumpIntermediateText(compileRequest, dxilAssembly.begin(), dxilAssembly.Length(), ".dxil.asm"); + dumpIntermediateText(compileRequest, dxilAssembly.begin(), dxilAssembly.getLength(), ".dxil.asm"); } break; #endif diff --git a/source/slang/compiler.h b/source/slang/compiler.h index 5199d2540..233fa3d05 100644 --- a/source/slang/compiler.h +++ b/source/slang/compiler.h @@ -321,22 +321,22 @@ namespace Slang Profile profile); /// Get the number of existential type parameters for the entry point. - UInt getExistentialTypeParamCount() { return m_existentialSlots.paramTypes.Count(); } + Index getExistentialTypeParamCount() { return m_existentialSlots.paramTypes.getCount(); } /// Get the existential type parameter at `index`. - Type* getExistentialTypeParam(UInt index) { return m_existentialSlots.paramTypes[index]; } + Type* getExistentialTypeParam(Index index) { return m_existentialSlots.paramTypes[index]; } /// Get the number of arguments supplied for existential type parameters. /// /// Note that the number of arguments may not match the number of parameters. /// In particular, an unspecialized entry point may have many parameters, but zero arguments. - UInt getExistentialTypeArgCount() { return m_existentialSlots.args.Count(); } + Index getExistentialTypeArgCount() { return m_existentialSlots.args.getCount(); } /// Get the existential type argument (type and witness table) at `index`. - ExistentialTypeSlots::Arg getExistentialTypeArg(UInt index) { return m_existentialSlots.args[index]; } + ExistentialTypeSlots::Arg getExistentialTypeArg(Index index) { return m_existentialSlots.args[index]; } /// Get an array of all existential type arguments. - ExistentialTypeSlots::Arg const* getExistentialTypeArgs() { return m_existentialSlots.args.Buffer(); } + ExistentialTypeSlots::Arg const* getExistentialTypeArgs() { return m_existentialSlots.args.getBuffer(); } /// Get an array of all entry-point shader parameters. List<ShaderParamInfo> const& getShaderParams() { return m_shaderParams; } @@ -827,7 +827,7 @@ namespace Slang List<RefPtr<FrontEndEntryPointRequest>> m_entryPointReqs; List<RefPtr<FrontEndEntryPointRequest>> const& getEntryPointReqs() { return m_entryPointReqs; } - UInt getEntryPointReqCount() { return m_entryPointReqs.Count(); } + UInt getEntryPointReqCount() { return m_entryPointReqs.getCount(); } FrontEndEntryPointRequest* getEntryPointReq(UInt index) { return m_entryPointReqs[index]; } // Directories to search for `#include` files or `import`ed modules @@ -913,10 +913,10 @@ namespace Slang Linkage* getLinkage() { return m_linkage; } /// Get the number of entry points added to the program - UInt getEntryPointCount() { return m_entryPoints.Count(); } + Index getEntryPointCount() { return m_entryPoints.getCount(); } /// Get the entry point at the given `index`. - RefPtr<EntryPoint> getEntryPoint(UInt index) { return m_entryPoints[index]; } + RefPtr<EntryPoint> getEntryPoint(Index index) { return m_entryPoints[index]; } /// Get the full ist of entry points on the program. List<RefPtr<EntryPoint>> const& getEntryPoints() { return m_entryPoints; } @@ -980,22 +980,22 @@ namespace Slang RefPtr<IRModule> getOrCreateIRModule(DiagnosticSink* sink); /// Get the number of existential type parameters for the program. - UInt getExistentialTypeParamCount() { return m_globalExistentialSlots.paramTypes.Count(); } + Index getExistentialTypeParamCount() { return m_globalExistentialSlots.paramTypes.getCount(); } /// Get the existential type parameter at `index`. - Type* getExistentialTypeParam(UInt index) { return m_globalExistentialSlots.paramTypes[index]; } + Type* getExistentialTypeParam(Index index) { return m_globalExistentialSlots.paramTypes[index]; } /// Get the number of arguments supplied for existential type parameters. /// /// Note that the number of arguments may not match the number of parameters. /// In particular, an unspecialized program may have many parameters, but zero arguments. - UInt getExistentialTypeArgCount() { return m_globalExistentialSlots.args.Count(); } + Index getExistentialTypeArgCount() { return m_globalExistentialSlots.args.getCount(); } /// Get the existential type argument (type and witness table) at `index`. - ExistentialTypeSlots::Arg getExistentialTypeArg(UInt index) { return m_globalExistentialSlots.args[index]; } + ExistentialTypeSlots::Arg getExistentialTypeArg(Index index) { return m_globalExistentialSlots.args[index]; } /// Get an array of all existential type arguments. - ExistentialTypeSlots::Arg const* getExistentialTypeArgs() { return m_globalExistentialSlots.args.Buffer(); } + ExistentialTypeSlots::Arg const* getExistentialTypeArgs() { return m_globalExistentialSlots.args.getBuffer(); } /// Get an array of all global shader parameters. List<GlobalShaderParamInfo> const& getShaderParams() { return m_shaderParams; } diff --git a/source/slang/diagnostics.cpp b/source/slang/diagnostics.cpp index 4edea57a2..a947e7369 100644 --- a/source/slang/diagnostics.cpp +++ b/source/slang/diagnostics.cpp @@ -23,15 +23,24 @@ void printDiagnosticArg(StringBuilder& sb, char const* str) sb << str; } -void printDiagnosticArg(StringBuilder& sb, int str) +void printDiagnosticArg(StringBuilder& sb, int32_t val) { - sb << str; + sb << val; +} + +void printDiagnosticArg(StringBuilder& sb, uint32_t val) +{ + sb << val; +} + +void printDiagnosticArg(StringBuilder& sb, int64_t val) +{ + sb << val; } -void printDiagnosticArg(StringBuilder& sb, UInt val) +void printDiagnosticArg(StringBuilder& sb, uint64_t val) { - // TODO: make this robust - sb << (int) val; + sb << val; } void printDiagnosticArg(StringBuilder& sb, Slang::String const& str) @@ -278,7 +287,7 @@ void DiagnosticSink::diagnoseImpl(SourceLoc const& pos, DiagnosticInfo const& in StringBuilder messageBuilder; formatDiagnostic(this, diagnostic, messageBuilder); - writer->write(messageBuilder.Buffer(), messageBuilder.Length()); + writer->write(messageBuilder.getBuffer(), messageBuilder.getLength()); } else { diff --git a/source/slang/diagnostics.h b/source/slang/diagnostics.h index 72c272fa0..7d76ffa85 100644 --- a/source/slang/diagnostics.h +++ b/source/slang/diagnostics.h @@ -80,8 +80,13 @@ namespace Slang enum class ProfileVersion; void printDiagnosticArg(StringBuilder& sb, char const* str); - void printDiagnosticArg(StringBuilder& sb, int val); - void printDiagnosticArg(StringBuilder& sb, UInt val); + + void printDiagnosticArg(StringBuilder& sb, int32_t val); + void printDiagnosticArg(StringBuilder& sb, uint32_t val); + + void printDiagnosticArg(StringBuilder& sb, int64_t val); + void printDiagnosticArg(StringBuilder& sb, uint64_t val); + void printDiagnosticArg(StringBuilder& sb, Slang::String const& str); void printDiagnosticArg(StringBuilder& sb, Slang::UnownedStringSlice const& str); void printDiagnosticArg(StringBuilder& sb, Name* name); diff --git a/source/slang/dxc-support.cpp b/source/slang/dxc-support.cpp index cab94e74b..b6eaf8aa9 100644 --- a/source/slang/dxc-support.cpp +++ b/source/slang/dxc-support.cpp @@ -99,15 +99,15 @@ namespace Slang entryPointIndex, targetReq, endToEndReq); - maybeDumpIntermediate(compileRequest, hlslCode.Buffer(), CodeGenTarget::HLSL); + maybeDumpIntermediate(compileRequest, hlslCode.getBuffer(), CodeGenTarget::HLSL); // Wrap the // Create blob from the string ComPtr<IDxcBlobEncoding> dxcSourceBlob; SLANG_RETURN_ON_FAIL(dxcLibrary->CreateBlobWithEncodingFromPinned( - (LPBYTE)hlslCode.Buffer(), - (UINT32)hlslCode.Length(), + (LPBYTE)hlslCode.getBuffer(), + (UINT32)hlslCode.getLength(), 0, dxcSourceBlob.writeRef())); @@ -181,11 +181,11 @@ namespace Slang args[argCount++] = L"-no-warnings"; String entryPointName = getText(entryPoint->getName()); - OSString wideEntryPointName = entryPointName.ToWString(); + OSString wideEntryPointName = entryPointName.toWString(); auto profile = getEffectiveProfile(entryPoint, targetReq); String profileName = GetHLSLProfileName(profile); - OSString wideProfileName = profileName.ToWString(); + OSString wideProfileName = profileName.toWString(); // We will enable the flag to generate proper code for 16-bit types // by default, as long as the user is requesting a sufficiently @@ -207,7 +207,7 @@ namespace Slang ComPtr<IDxcOperationResult> dxcResult; SLANG_RETURN_ON_FAIL(dxcCompiler->Compile(dxcSourceBlob, - sourcePath.ToWString().begin(), + sourcePath.toWString().begin(), profile.GetStage() == Stage::Unknown ? L"" : wideEntryPointName.begin(), wideProfileName.begin(), args, @@ -248,7 +248,7 @@ namespace Slang ComPtr<IDxcBlob> dxcResultBlob; SLANG_RETURN_ON_FAIL(dxcResult->GetResult(dxcResultBlob.writeRef())); - outCode.AddRange( + outCode.addRange( (uint8_t const*)dxcResultBlob->GetBufferPointer(), (int) dxcResultBlob->GetBufferSize()); diff --git a/source/slang/emit.cpp b/source/slang/emit.cpp index 8bb2a244b..24d1ce56c 100644 --- a/source/slang/emit.cpp +++ b/source/slang/emit.cpp @@ -1490,7 +1490,7 @@ struct EmitVisitor // If no target name was specified, then the modifier implicitly // applies to all targets. - if(targetName.Length() == 0) + if(targetName.getLength() == 0) return true; return isTargetIntrinsicModifierApplicable(targetName); @@ -2105,7 +2105,7 @@ struct EmitVisitor char const* dummyChar = "U"; // Special case a name that is the empty string, just in case. - if(name.Length() == 0) + if(name.getLength() == 0) return dummyChar; // Otherwise, we are going to walk over the name byte by byte @@ -2117,7 +2117,7 @@ struct EmitVisitor // GLSL reserverse all names that start with `gl_`, // so if we are in danger of collision, then make // our name start with a dummy character instead. - if(name.StartsWith("gl_")) + if(name.startsWith("gl_")) { sb.append(dummyChar); } @@ -2126,7 +2126,7 @@ struct EmitVisitor // We will also detect user-defined names that // might overlap with our convention for mangled names, // to avoid an possible collision. - if(name.StartsWith("_S")) + if(name.startsWith("_S")) { sb.Append(dummyChar); } @@ -2259,7 +2259,7 @@ struct EmitVisitor sb.append(nameHint); // Avoid introducing a double underscore - if(!nameHint.EndsWith("_")) + if(!nameHint.endsWith("_")) { sb.append("_"); } @@ -3037,7 +3037,7 @@ struct EmitVisitor auto outerPrec = inOuterPrec; IRUse* args = inst->getOperands(); - UInt argCount = inst->getOperandCount(); + Index argCount = inst->getOperandCount(); // First operand was the function to be called args++; @@ -3053,7 +3053,7 @@ struct EmitVisitor emit(name); Emit("("); - for (UInt aa = 0; aa < argCount; ++aa) + for (Index aa = 0; aa < argCount; ++aa) { if (aa != 0) Emit(", "); emitIROperand(ctx, args[aa].get(), mode, kEOp_General); @@ -3100,7 +3100,7 @@ struct EmitVisitor case '5': case '6': case '7': case '8': case '9': { // Simple case: emit one of the direct arguments to the call - UInt argIndex = d - '0'; + Index argIndex = d - '0'; SLANG_RELEASE_ASSERT((0 <= argIndex) && (argIndex < argCount)); Emit("("); emitIROperand(ctx, args[argIndex].get(), mode, kEOp_General); @@ -3223,7 +3223,7 @@ struct EmitVisitor // we can use it in the constructed expression. SLANG_RELEASE_ASSERT(*cursor >= '0' && *cursor <= '9'); - UInt argIndex = (*cursor++) - '0'; + Index argIndex = (*cursor++) - '0'; SLANG_RELEASE_ASSERT(argCount > argIndex); auto vectorArg = args[argIndex].get(); @@ -3246,7 +3246,7 @@ struct EmitVisitor // (this is the inverse of `$z`). // SLANG_RELEASE_ASSERT(*cursor >= '0' && *cursor <= '9'); - UInt argIndex = (*cursor++) - '0'; + Index argIndex = (*cursor++) - '0'; SLANG_RELEASE_ASSERT(argCount > argIndex); auto arg = args[argIndex].get(); @@ -3303,7 +3303,7 @@ struct EmitVisitor // with the front-end picking the right overload // based on the "address space" of the argument. - UInt argIndex = 0; + Index argIndex = 0; SLANG_RELEASE_ASSERT(argCount > argIndex); auto arg = args[argIndex].get(); @@ -3328,7 +3328,7 @@ struct EmitVisitor // to the `imageAtomic*` function. // - UInt argIndex = 0; + Index argIndex = 0; SLANG_RELEASE_ASSERT(argCount > argIndex); auto arg = args[argIndex].get(); @@ -3411,7 +3411,7 @@ struct EmitVisitor // used as the argument ray payload at a // trace call site. - UInt argIndex = 0; + Index argIndex = 0; SLANG_RELEASE_ASSERT(argCount > argIndex); auto arg = args[argIndex].get(); auto argLoad = as<IRLoad>(arg); @@ -3428,7 +3428,7 @@ struct EmitVisitor // used as the argument callable payload at a // call site. - UInt argIndex = 0; + Index argIndex = 0; SLANG_RELEASE_ASSERT(argCount > argIndex); auto arg = args[argIndex].get(); auto argLoad = as<IRLoad>(arg); @@ -4105,8 +4105,8 @@ struct EmitVisitor auto ii = (IRSwizzle*)inst; emitIROperand(ctx, ii->getBase(), mode, leftSide(outerPrec, prec)); emit("."); - UInt elementCount = ii->getElementCount(); - for (UInt ee = 0; ee < elementCount; ++ee) + const Index elementCount = Index(ii->getElementCount()); + for (Index ee = 0; ee < elementCount; ++ee) { IRInst* irElementIndex = ii->getElementIndex(ee); SLANG_RELEASE_ASSERT(irElementIndex->op == kIROp_IntLit); @@ -4816,8 +4816,8 @@ struct EmitVisitor { assert(attrib); - attrib->args.Count(); - if (attrib->args.Count() != 1) + attrib->args.getCount(); + if (attrib->args.getCount() != 1) { SLANG_DIAGNOSE_UNEXPECTED(getSink(), entryPoint->loc, "Attribute expects single parameter"); return; @@ -4843,8 +4843,8 @@ struct EmitVisitor { assert(attrib); - attrib->args.Count(); - if (attrib->args.Count() != 1) + attrib->args.getCount(); + if (attrib->args.getCount() != 1) { SLANG_DIAGNOSE_UNEXPECTED(getSink(), entryPoint->loc, "Attribute expects single parameter"); return; @@ -6814,7 +6814,7 @@ struct EmitVisitor } ctx->mapInstToLevel[inst] = requiredLevel; - ctx->actions->Add(action); + ctx->actions->add(action); } void computeIREmitActions( diff --git a/source/slang/ir-bind-existentials.cpp b/source/slang/ir-bind-existentials.cpp index f87a7d233..f0c02dd67 100644 --- a/source/slang/ir-bind-existentials.cpp +++ b/source/slang/ir-bind-existentials.cpp @@ -285,7 +285,7 @@ struct BindExistentialSlots UInt slotOperandCount = slotCount*2; List<IRInst*> slotOperands; for(UInt ii = 0; ii < slotOperandCount; ++ii) - slotOperands.Add(slotArgs[ii].get()); + slotOperands.add(slotArgs[ii].get()); // We are going to create a proxy type that represents // the results of plugging all the information @@ -294,7 +294,7 @@ struct BindExistentialSlots auto newType = builder.getBindExistentialsType( fullType, slotOperandCount, - slotOperands.Buffer()); + slotOperands.getBuffer()); // We will replace the type of the original parameter // with the new proxy type. @@ -315,7 +315,7 @@ struct BindExistentialSlots // List<IRUse*> usesToReplace; for(auto use = inst->firstUse; use; use = use->nextUse ) - usesToReplace.Add(use); + usesToReplace.add(use); // Now we can loop over our list of uses and replace each. // @@ -329,7 +329,7 @@ struct BindExistentialSlots fullType, inst, slotOperandCount, - slotOperands.Buffer()); + slotOperands.getBuffer()); // Second we make the use site point at the new // value instead. diff --git a/source/slang/ir-clone.cpp b/source/slang/ir-clone.cpp index bd5f9bcaa..d26b470d6 100644 --- a/source/slang/ir-clone.cpp +++ b/source/slang/ir-clone.cpp @@ -176,7 +176,7 @@ static void _cloneInstDecorationsAndChildren( IRCloningOldNewPair pair; pair.oldInst = oldChild; pair.newInst = newChild; - pairs.Add(pair); + pairs.add(pair); } } @@ -271,9 +271,9 @@ void cloneDecoration( bool IRSimpleSpecializationKey::operator==(IRSimpleSpecializationKey const& other) const { - auto valCount = vals.Count(); - if(valCount != other.vals.Count()) return false; - for( UInt ii = 0; ii < valCount; ++ii ) + auto valCount = vals.getCount(); + if(valCount != other.vals.getCount()) return false; + for( Index ii = 0; ii < valCount; ++ii ) { if(vals[ii] != other.vals[ii]) return false; } @@ -282,9 +282,9 @@ bool IRSimpleSpecializationKey::operator==(IRSimpleSpecializationKey const& othe int IRSimpleSpecializationKey::GetHashCode() const { - auto valCount = vals.Count(); + auto valCount = vals.getCount(); int hash = Slang::GetHashCode(valCount); - for( UInt ii = 0; ii < valCount; ++ii ) + for( Index ii = 0; ii < valCount; ++ii ) { hash = combineHash(hash, Slang::GetHashCode(vals[ii])); } diff --git a/source/slang/ir-constexpr.cpp b/source/slang/ir-constexpr.cpp index 163f3d98a..c56a15663 100644 --- a/source/slang/ir-constexpr.cpp +++ b/source/slang/ir-constexpr.cpp @@ -162,7 +162,7 @@ void maybeAddToWorkList( { if( !context->onWorkList.Contains(gv) ) { - context->workList.Add(gv); + context->workList.add(gv); context->onWorkList.Add(gv); } } @@ -489,10 +489,10 @@ void propagateConstExpr( // We will iterate applying propagation to one global value at a time // until we run out. - while( context.workList.Count() ) + while( context.workList.getCount() ) { auto gv = context.workList[0]; - context.workList.FastRemoveAt(0); + context.workList.fastRemoveAt(0); context.onWorkList.Remove(gv); switch( gv->op ) diff --git a/source/slang/ir-dce.cpp b/source/slang/ir-dce.cpp index ba6d7adb9..f1a34bedf 100644 --- a/source/slang/ir-dce.cpp +++ b/source/slang/ir-dce.cpp @@ -74,7 +74,7 @@ struct DeadCodeEliminationContext if(liveInsts.Contains(inst)) return; liveInsts.Add(inst); - workList.Add(inst); + workList.add(inst); } // Given the basic infrastructrure above, let's @@ -95,10 +95,10 @@ struct DeadCodeEliminationContext // processing entries off of our work list // until it goes dry. // - while( workList.Count() ) + while( workList.getCount() ) { - auto inst = workList.Last(); - workList.RemoveLast(); + auto inst = workList.getLast(); + workList.removeLast(); // At this point we know that `inst` is live, // and we want to start considering which other diff --git a/source/slang/ir-dominators.cpp b/source/slang/ir-dominators.cpp index ad1639db5..488e67724 100644 --- a/source/slang/ir-dominators.cpp +++ b/source/slang/ir-dominators.cpp @@ -245,7 +245,7 @@ struct PostorderComputationContext : public DepthFirstSearchContext virtual void postVisit(IRBlock* block) SLANG_OVERRIDE { - order->Add(block); + order->add(block); } }; @@ -314,7 +314,7 @@ struct DominatorTreeComputationContext // We will initialize our map from the block objects to their "name" // (index in the traversal order), before moving on. - BlockName blockCount = BlockName(postorder.Count()); + BlockName blockCount = BlockName(postorder.getCount()); for(BlockName bb = 0; bb < blockCount; ++bb) { mapBlockToName[postorder[bb]] = bb; @@ -322,7 +322,7 @@ struct DominatorTreeComputationContext // Next we initialize the `doms` array that we will iteratively turn // into an encoding of the dominator tree. - doms.SetSize(blockCount); + doms.setCount(blockCount); for(BlockName bb = 0; bb < blockCount; ++bb) { doms[bb] = kUndefined; @@ -524,11 +524,11 @@ struct DominatorTreeComputationContext // We will build some intermediate information on each // block to help us fill out the tree. - BlockName blockCount = BlockName(doms.Count()); + BlockName blockCount = BlockName(doms.getCount()); List<BlockInfo> blockInfos; for(BlockName bb = 0; bb < blockCount; ++bb) { - blockInfos.Add(BlockInfo()); + blockInfos.add(BlockInfo()); } // We will propagate layout information in two passes over the tree. @@ -626,7 +626,7 @@ struct DominatorTreeComputationContext // RefPtr<IRDominatorTree> dominatorTree = new IRDominatorTree(); dominatorTree->code = code; - dominatorTree->nodes.SetSize(blockCount); + dominatorTree->nodes.setCount(blockCount); // We will iterate over all of the blocks, and fill in the corresponding // dominator tree node for each. diff --git a/source/slang/ir-entry-point-uniforms.cpp b/source/slang/ir-entry-point-uniforms.cpp index 501af56cf..6ee05611d 100644 --- a/source/slang/ir-entry-point-uniforms.cpp +++ b/source/slang/ir-entry-point-uniforms.cpp @@ -373,7 +373,7 @@ struct MoveEntryPointUniformParametersToGlobalScope // Note: an empty `struct` parameter would also show up the same way, but // we should eliminate any such parameters later on during type legalization. // - if(layout->resourceInfos.Count() == 0) + if(layout->resourceInfos.getCount() == 0) return true; // if none of the above tests determined that the diff --git a/source/slang/ir-glsl-legalize.cpp b/source/slang/ir-glsl-legalize.cpp index 3811346a5..aa6eb187f 100644 --- a/source/slang/ir-glsl-legalize.cpp +++ b/source/slang/ir-glsl-legalize.cpp @@ -224,10 +224,10 @@ GLSLSystemValueInfo* getGLSLSystemValueInfo( char const* outerArrayName = nullptr; auto semanticNameSpelling = varLayout->systemValueSemantic; - if(semanticNameSpelling.Length() == 0) + if(semanticNameSpelling.getLength() == 0) return nullptr; - auto semanticName = semanticNameSpelling.ToLower(); + auto semanticName = semanticNameSpelling.toLower(); IRType* requiredType = nullptr; @@ -698,7 +698,7 @@ ScalarizedVal createGLSLGlobalVaryingsImpl( element.val = fieldVal; element.key = field->getKey(); - tupleValImpl->elements.Add(element); + tupleValImpl->elements.add(element); } } @@ -835,9 +835,9 @@ void assign( // that is not a tuple. We will perform assignment // element-by-element. auto rightTupleVal = as<ScalarizedTupleValImpl>(right.impl); - UInt elementCount = rightTupleVal->elements.Count(); + Index elementCount = rightTupleVal->elements.getCount(); - for( UInt ee = 0; ee < elementCount; ++ee ) + for( Index ee = 0; ee < elementCount; ++ee ) { auto rightElement = rightTupleVal->elements[ee]; auto leftElementVal = extractField( @@ -861,9 +861,9 @@ void assign( // We have a tuple, so we are going to need to try and assign // to each of its constituent fields. auto leftTupleVal = as<ScalarizedTupleValImpl>(left.impl); - UInt elementCount = leftTupleVal->elements.Count(); + Index elementCount = leftTupleVal->elements.getCount(); - for( UInt ee = 0; ee < elementCount; ++ee ) + for( Index ee = 0; ee < elementCount; ++ee ) { auto rightElementVal = extractField( builder, @@ -923,15 +923,15 @@ ScalarizedVal getSubscriptVal( RefPtr<ScalarizedTupleValImpl> resultTuple = new ScalarizedTupleValImpl(); resultTuple->type = elementType; - UInt elementCount = inputTuple->elements.Count(); - UInt elementCounter = 0; + Index elementCount = inputTuple->elements.getCount(); + Index elementCounter = 0; auto structType = as<IRStructType>(elementType); for(auto field : structType->getFields()) { auto tupleElementType = field->getFieldType(); - UInt elementIndex = elementCounter++; + Index elementIndex = elementCounter++; SLANG_RELEASE_ASSERT(elementIndex < elementCount); auto inputElement = inputTuple->elements[elementIndex]; @@ -944,7 +944,7 @@ ScalarizedVal getSubscriptVal( inputElement.val, indexVal); - resultTuple->elements.Add(resultElement); + resultTuple->elements.add(resultElement); } SLANG_RELEASE_ASSERT(elementCounter == elementCount); @@ -983,7 +983,7 @@ IRInst* materializeTupleValue( auto tupleVal = val.impl.as<ScalarizedTupleValImpl>(); SLANG_ASSERT(tupleVal); - UInt elementCount = tupleVal->elements.Count(); + Index elementCount = tupleVal->elements.getCount(); auto type = tupleVal->type; if( auto arrayType = as<IRArrayType>(type)) @@ -1009,13 +1009,13 @@ IRInst* materializeTupleValue( builder, arrayElementPseudoVal); - arrayElementVals.Add(arrayElementVal); + arrayElementVals.add(arrayElementVal); } return builder->emitMakeArray( arrayType, - arrayElementVals.Count(), - arrayElementVals.Buffer()); + arrayElementVals.getCount(), + arrayElementVals.getBuffer()); } else { @@ -1026,16 +1026,16 @@ IRInst* materializeTupleValue( // TODO: this should be using a `makeStruct` instruction. List<IRInst*> elementVals; - for( UInt ee = 0; ee < elementCount; ++ee ) + for( Index ee = 0; ee < elementCount; ++ee ) { auto elementVal = materializeValue(builder, tupleVal->elements[ee].val); - elementVals.Add(elementVal); + elementVals.add(elementVal); } return builder->emitConstructorInst( tupleVal->type, - elementVals.Count(), - elementVals.Buffer()); + elementVals.getCount(), + elementVals.getBuffer()); } } diff --git a/source/slang/ir-insts.h b/source/slang/ir-insts.h index ab333f2be..5970e2b36 100644 --- a/source/slang/ir-insts.h +++ b/source/slang/ir-insts.h @@ -782,7 +782,7 @@ struct IRBuilder List<IRType*> const& paramTypes, IRType* resultType) { - return getFuncType(paramTypes.Count(), paramTypes.Buffer(), resultType); + return getFuncType(paramTypes.getCount(), paramTypes.getBuffer(), resultType); } IRConstantBufferType* getConstantBufferType( @@ -802,7 +802,7 @@ struct IRBuilder IRType* getTaggedUnionType( List<IRType*> const& caseTypes) { - return getTaggedUnionType(caseTypes.Count(), caseTypes.Buffer()); + return getTaggedUnionType(caseTypes.getCount(), caseTypes.getBuffer()); } IRType* getBindExistentialsType( @@ -854,7 +854,7 @@ struct IRBuilder IRInst* func, List<IRInst*> const& args) { - return emitCallInst(type, func, args.Count(), args.Buffer()); + return emitCallInst(type, func, args.getCount(), args.getBuffer()); } IRInst* createIntrinsicInst( @@ -883,7 +883,7 @@ struct IRBuilder IRType* type, List<IRInst*> const& args) { - return emitMakeVector(type, args.Count(), args.Buffer()); + return emitMakeVector(type, args.getCount(), args.getBuffer()); } IRInst* emitMakeMatrix( @@ -905,7 +905,7 @@ struct IRBuilder IRType* type, List<IRInst*> const& args) { - return emitMakeStruct(type, args.Count(), args.Buffer()); + return emitMakeStruct(type, args.getCount(), args.getBuffer()); } IRInst* emitMakeExistential( diff --git a/source/slang/ir-legalize-types.cpp b/source/slang/ir-legalize-types.cpp index 127593dd5..cfc495070 100644 --- a/source/slang/ir-legalize-types.cpp +++ b/source/slang/ir-legalize-types.cpp @@ -22,7 +22,7 @@ namespace Slang LegalVal LegalVal::tuple(RefPtr<TuplePseudoVal> tupleVal) { - SLANG_ASSERT(tupleVal->elements.Count()); + SLANG_ASSERT(tupleVal->elements.getCount()); LegalVal result; result.flavor = LegalVal::Flavor::tuple; @@ -202,7 +202,7 @@ static void getArgumentValues( break; case LegalVal::Flavor::simple: - instArgs.Add(val.getSimple()); + instArgs.add(val.getSimple()); break; case LegalVal::Flavor::implicitDeref: @@ -259,8 +259,8 @@ static LegalVal legalizeCall( return LegalVal::simple(context->builder->emitCallInst( retIRType, callInst->getCallee(), - instArgs.Count(), - instArgs.Buffer())); + instArgs.getCount(), + instArgs.getBuffer())); } static LegalVal legalizeRetVal(IRTypeLegalizationContext* context, @@ -322,7 +322,7 @@ static LegalVal legalizeLoad( element.key = ee.key; element.val = legalizeLoad(context, ee.val); - tupleVal->elements.Add(element); + tupleVal->elements.add(element); } return LegalVal::tuple(tupleVal); } @@ -382,9 +382,9 @@ static LegalVal legalizeStore( // the tuple. auto destTuple = legalPtrVal.getTuple(); auto valTuple = legalVal.getTuple(); - SLANG_ASSERT(destTuple->elements.Count() == valTuple->elements.Count()); + SLANG_ASSERT(destTuple->elements.getCount() == valTuple->elements.getCount()); - for (UInt i = 0; i < valTuple->elements.Count(); i++) + for (Index i = 0; i < valTuple->elements.getCount(); i++) { legalizeStore(context, destTuple->elements[i].val, valTuple->elements[i].val); } @@ -615,7 +615,7 @@ static LegalVal unwrapBufferValue( context, legalPtrOperand, ee.field); - obj->elements.Add(element); + obj->elements.add(element); } return LegalVal::tuple(obj); @@ -667,7 +667,7 @@ static LegalType getPointedToType( TuplePseudoType::Element resultElement; resultElement.key = ee.key; resultElement.type = getPointedToType(context, ee.type); - resultTuple->elements.Add(resultElement); + resultTuple->elements.add(resultElement); } return LegalType::tuple(resultTuple); } @@ -889,10 +889,10 @@ static LegalVal legalizeGetElement( auto tupleType = type.getTuple(); SLANG_ASSERT(tupleType); - auto elemCount = ptrTupleInfo->elements.Count(); - SLANG_ASSERT(elemCount == tupleType->elements.Count()); + auto elemCount = ptrTupleInfo->elements.getCount(); + SLANG_ASSERT(elemCount == tupleType->elements.getCount()); - for(UInt ee = 0; ee < elemCount; ++ee) + for(Index ee = 0; ee < elemCount; ++ee) { auto ptrElem = ptrTupleInfo->elements[ee]; auto elemType = tupleType->elements[ee].type; @@ -905,7 +905,7 @@ static LegalVal legalizeGetElement( ptrElem.val, indexOperand); - resTupleInfo->elements.Add(resElem); + resTupleInfo->elements.add(resElem); } return LegalVal::tuple(resTupleInfo); @@ -1000,10 +1000,10 @@ static LegalVal legalizeGetElementPtr( auto tupleType = type.getTuple(); SLANG_ASSERT(tupleType); - auto elemCount = ptrTupleInfo->elements.Count(); - SLANG_ASSERT(elemCount == tupleType->elements.Count()); + auto elemCount = ptrTupleInfo->elements.getCount(); + SLANG_ASSERT(elemCount == tupleType->elements.getCount()); - for(UInt ee = 0; ee < elemCount; ++ee) + for(Index ee = 0; ee < elemCount; ++ee) { auto ptrElem = ptrTupleInfo->elements[ee]; auto elemType = tupleType->elements[ee].type; @@ -1016,7 +1016,7 @@ static LegalVal legalizeGetElementPtr( ptrElem.val, indexOperand); - resTupleInfo->elements.Add(resElem); + resTupleInfo->elements.add(resElem); } return LegalVal::tuple(resTupleInfo); @@ -1090,13 +1090,13 @@ static LegalVal legalizeMakeStruct( // the `struct` type with them as fields // would not be simple... // - args.Add(legalArgs[aa].getSimple()); + args.add(legalArgs[aa].getSimple()); } return LegalVal::simple( builder->emitMakeStruct( legalType.getSimple(), argCount, - args.Buffer())); + args.getBuffer())); } case LegalType::Flavor::pair: @@ -1120,30 +1120,30 @@ static LegalVal legalizeMakeStruct( { // The argument is itself a pair auto argPair = arg.getPair(); - ordinaryArgs.Add(argPair->ordinaryVal); - specialArgs.Add(argPair->specialVal); + ordinaryArgs.add(argPair->ordinaryVal); + specialArgs.add(argPair->specialVal); } else if(ee.flags & Slang::PairInfo::kFlag_hasOrdinary) { - ordinaryArgs.Add(arg); + ordinaryArgs.add(arg); } else if(ee.flags & Slang::PairInfo::kFlag_hasSpecial) { - specialArgs.Add(arg); + specialArgs.add(arg); } } LegalVal ordinaryVal = legalizeMakeStruct( context, ordinaryType, - ordinaryArgs.Buffer(), - ordinaryArgs.Count()); + ordinaryArgs.getBuffer(), + ordinaryArgs.getCount()); LegalVal specialVal = legalizeMakeStruct( context, specialType, - specialArgs.Buffer(), - specialArgs.Count()); + specialArgs.getBuffer(), + specialArgs.getCount()); return LegalVal::pair(ordinaryVal, specialVal, pairInfo); } @@ -1172,7 +1172,7 @@ static LegalVal legalizeMakeStruct( resElem.key = elemKey; resElem.val = argVal; - resTupleInfo->elements.Add(resElem); + resTupleInfo->elements.add(resElem); } return LegalVal::tuple(resTupleInfo); } @@ -1316,7 +1316,7 @@ static LegalVal legalizeLocalVar( // Remove the old local var. irLocalVar->removeFromParent(); // add old local var to list - context->replacedInstructions.Add(irLocalVar); + context->replacedInstructions.add(irLocalVar); return newVal; } break; @@ -1348,7 +1348,7 @@ static LegalVal legalizeParam( auto newVal = declareVars(context, kIROp_Param, legalParamType, nullptr, LegalVarChain(), nameHint, originalParam, nullptr); originalParam->removeFromParent(); - context->replacedInstructions.Add(originalParam); + context->replacedInstructions.add(originalParam); return newVal; } } @@ -1422,7 +1422,7 @@ static LegalVal legalizeInst( { auto oldArg = inst->getOperand(aa); auto legalArg = legalizeOperand(context, oldArg); - legalArgs.Add(legalArg); + legalArgs.add(legalArg); if (legalArg.flavor != LegalVal::Flavor::simple) anyComplex = true; @@ -1466,14 +1466,14 @@ static LegalVal legalizeInst( context, inst, legalType, - legalArgs.Buffer()); + legalArgs.getBuffer()); // After we are done, we will eliminate the // original instruction by removing it from // the IR. // inst->removeFromParent(); - context->replacedInstructions.Add(inst); + context->replacedInstructions.add(inst); // The value to be used when referencing // the original instruction will now be @@ -1489,7 +1489,7 @@ static void addParamType(List<IRType*>& ioParamTypes, LegalType t) break; case LegalType::Flavor::simple: - ioParamTypes.Add(t.getSimple()); + ioParamTypes.add(t.getSimple()); break; case LegalType::Flavor::implicitDeref: @@ -1571,8 +1571,8 @@ static LegalVal legalizeFunc( } auto newFuncType = context->builder->getFuncType( - newParamTypes.Count(), - newParamTypes.Buffer(), + newParamTypes.getCount(), + newParamTypes.getBuffer(), newResultType); context->builder->setDataType(irFunc, newFuncType); @@ -1799,7 +1799,7 @@ static void _addFieldsToWrappedBufferElementTypeLayout( // information so that we can find the field layout // based on the IR key for the struct field. // - newTypeLayout->fields.Add(newFieldLayout); + newTypeLayout->fields.add(newFieldLayout); newTypeLayout->mapKeyToLayout.Add(simpleInfo->key, newFieldLayout); } break; @@ -2310,7 +2310,7 @@ static LegalVal declareVars( TuplePseudoVal::Element element; element.key = ee.key; element.val = fieldVal; - tupleVal->elements.Add(element); + tupleVal->elements.add(element); } return LegalVal::tuple(tupleVal); @@ -2380,7 +2380,7 @@ static LegalVal legalizeGlobalVar( // Remove the old global from the module. irGlobalVar->removeFromParent(); - context->replacedInstructions.Add(irGlobalVar); + context->replacedInstructions.add(irGlobalVar); return newVal; } @@ -2424,7 +2424,7 @@ static LegalVal legalizeGlobalConstant( // Remove the old global from the module. irGlobalConstant->removeFromParent(); - context->replacedInstructions.Add(irGlobalConstant); + context->replacedInstructions.add(irGlobalConstant); return newVal; } @@ -2473,7 +2473,7 @@ static LegalVal legalizeGlobalParam( // Remove the old global from the module. irGlobalParam->removeFromParent(); - context->replacedInstructions.Add(irGlobalParam); + context->replacedInstructions.add(irGlobalParam); return newVal; } diff --git a/source/slang/ir-link.cpp b/source/slang/ir-link.cpp index 60bafb9d1..d4f736a08 100644 --- a/source/slang/ir-link.cpp +++ b/source/slang/ir-link.cpp @@ -775,11 +775,11 @@ IRFunc* specializeIRForEntryPoint( if( auto firstBlock = clonedFunc->getFirstBlock() ) { auto paramsStructLayout = getScopeStructLayout(entryPointLayout); - UInt paramLayoutCount = paramsStructLayout->fields.Count(); - UInt paramCounter = 0; + Index paramLayoutCount = paramsStructLayout->fields.getCount(); + Index paramCounter = 0; for( auto pp = firstBlock->getFirstParam(); pp; pp = pp->getNextParam() ) { - UInt paramIndex = paramCounter++; + Index paramIndex = paramCounter++; if( paramIndex < paramLayoutCount ) { auto paramLayout = paramsStructLayout->fields[paramIndex]; diff --git a/source/slang/ir-restructure.cpp b/source/slang/ir-restructure.cpp index d8d3fe7c9..47a0d1fee 100644 --- a/source/slang/ir-restructure.cpp +++ b/source/slang/ir-restructure.cpp @@ -514,14 +514,14 @@ namespace Slang caseIndex++; RefPtr<SwitchRegion::Case> currentCase = new SwitchRegion::Case(); - switchRegion->cases.Add(currentCase); + switchRegion->cases.add(currentCase); // Add the case value for this case, and any // others that share the same label // for(;;) { - currentCase->values.Add(caseVal); + currentCase->values.add(caseVal); // Are there any more `case`s left? // @@ -586,7 +586,7 @@ namespace Slang if(!defaultLabelHandled) { RefPtr<SwitchRegion::Case> defaultCase = new SwitchRegion::Case(); - switchRegion->cases.Add(defaultCase); + switchRegion->cases.add(defaultCase); // Note: we use `null` instead of `breakLabel` as the end block // here, to ensure that the `default` region will end with an diff --git a/source/slang/ir-sccp.cpp b/source/slang/ir-sccp.cpp index 66b370848..242ef0a37 100644 --- a/source/slang/ir-sccp.cpp +++ b/source/slang/ir-sccp.cpp @@ -357,7 +357,7 @@ struct SCCPContext // executed. We do this by adding the target to our CFG work list. // auto target = unconditionalBranch->getTargetBlock(); - cfgWorkList.Add(target); + cfgWorkList.add(target); // Besides transferring control to another block, the other // thing our unconditional branch instructions do is provide @@ -408,7 +408,7 @@ struct SCCPContext setLatticeVal(param, newVal); for( auto use = param->firstUse; use; use = use->nextUse ) { - ssaWorkList.Add(use->getUser()); + ssaWorkList.add(use->getUser()); } } } @@ -448,7 +448,7 @@ struct SCCPContext // bail out now. // auto target = boolConst->getValue() ? conditionalBranch->getTrueBlock() : conditionalBranch->getFalseBlock(); - cfgWorkList.Add(target); + cfgWorkList.add(target); return; } } @@ -459,8 +459,8 @@ struct SCCPContext // taken, so that both of the target blocks are // potentially executed. // - cfgWorkList.Add(conditionalBranch->getTrueBlock()); - cfgWorkList.Add(conditionalBranch->getFalseBlock()); + cfgWorkList.add(conditionalBranch->getTrueBlock()); + cfgWorkList.add(conditionalBranch->getFalseBlock()); } else if( auto switchInst = as<IRSwitch>(inst) ) { @@ -497,7 +497,7 @@ struct SCCPContext // Whatever single block we decided will get executed, // we need to make sure it gets processed and then bail. // - cfgWorkList.Add(target); + cfgWorkList.add(target); return; } } @@ -507,9 +507,9 @@ struct SCCPContext // for( UInt cc = 0; cc < caseCount; ++cc ) { - cfgWorkList.Add(switchInst->getCaseLabel(cc)); + cfgWorkList.add(switchInst->getCaseLabel(cc)); } - cfgWorkList.Add(switchInst->getDefaultLabel()); + cfgWorkList.add(switchInst->getDefaultLabel()); } // There are other cases of terminator instructions not handled @@ -563,7 +563,7 @@ struct SCCPContext // for( auto use = inst->firstUse; use; use = use->nextUse ) { - ssaWorkList.Add(use->getUser()); + ssaWorkList.add(use->getUser()); } } @@ -584,7 +584,7 @@ struct SCCPContext // The entry block is always going to be executed when the // function gets called, so we will process it right away. // - cfgWorkList.Add(firstBlock); + cfgWorkList.add(firstBlock); // The parameters of the first block are our function parameters, // and we want to operate on the assumption that they could have @@ -597,7 +597,7 @@ struct SCCPContext // Now we will iterate until both of our work lists go dry. // - while(cfgWorkList.Count() || ssaWorkList.Count()) + while(cfgWorkList.getCount() || ssaWorkList.getCount()) { // Note: there is a design choice to be had here // around whether we do `if if` or `while while` @@ -607,12 +607,12 @@ struct SCCPContext // We will start by processing any blocks that we // have determined are potentially reachable. // - while( cfgWorkList.Count() ) + while( cfgWorkList.getCount() ) { // We pop one block off of the work list. // auto block = cfgWorkList[0]; - cfgWorkList.FastRemoveAt(0); + cfgWorkList.fastRemoveAt(0); // We only want to process blocks that haven't // already been marked as executed, so that we @@ -644,12 +644,12 @@ struct SCCPContext // will start looking at individual instructions that // need to be updated. // - while( ssaWorkList.Count() ) + while( ssaWorkList.getCount() ) { // We pop one instruction that needs an update. // auto inst = ssaWorkList[0]; - ssaWorkList.FastRemoveAt(0); + ssaWorkList.fastRemoveAt(0); // Before updating the instruction, we will check if // the parent block of the instructin is marked as @@ -728,7 +728,7 @@ struct SCCPContext inst->replaceUsesWith(constantVal); if( !inst->mightHaveSideEffects() ) { - instsToRemove.Add(inst); + instsToRemove.add(inst); } } } @@ -817,7 +817,7 @@ struct SCCPContext { if( !isMarkedAsExecuted(block) ) { - unreachableBlocks.Add(block); + unreachableBlocks.add(block); } } // diff --git a/source/slang/ir-serialize.cpp b/source/slang/ir-serialize.cpp index a50ed6bd5..33238a9a6 100644 --- a/source/slang/ir-serialize.cpp +++ b/source/slang/ir-serialize.cpp @@ -81,7 +81,7 @@ void StringRepresentationCache::init(const List<char>* stringTable, NamePool* na m_scopeManager = scopeManager; // Decode the table - m_entries.SetSize(StringSlicePool::kNumDefaultHandles); + m_entries.setCount(StringSlicePool::kNumDefaultHandles); SLANG_COMPILE_TIME_ASSERT(StringSlicePool::kNumDefaultHandles == 2); { @@ -112,13 +112,13 @@ void StringRepresentationCache::init(const List<char>* stringTable, NamePool* na entry.m_numChars = len; entry.m_object = nullptr; - m_entries.Add(entry); + m_entries.add(entry); cur = reader.m_pos + len; } } - m_entries.Compress(); + m_entries.compress(); } Name* StringRepresentationCache::getName(Handle handle) @@ -209,7 +209,7 @@ char* StringRepresentationCache::getCStr(Handle handle) /* static */void SerialStringTableUtil::encodeStringTable(const UnownedStringSlice* slices, size_t numSlices, List<char>& stringTable) { - stringTable.Clear(); + stringTable.clear(); for (size_t i = 0; i < numSlices; ++i) { const UnownedStringSlice slice = slices[i]; @@ -218,9 +218,9 @@ char* StringRepresentationCache::getCStr(Handle handle) // We need to write into the the string array char prefixBytes[6]; const int numPrefixBytes = EncodeUnicodePointToUTF8(prefixBytes, len); - const int baseIndex = int(stringTable.Count()); + const Index baseIndex = stringTable.getCount(); - stringTable.SetSize(baseIndex + numPrefixBytes + len); + stringTable.setCount(baseIndex + numPrefixBytes + len); char* dst = stringTable.begin() + baseIndex; @@ -239,14 +239,14 @@ char* StringRepresentationCache::getCStr(Handle handle) { CharReader reader(cur); const int len = GetUnicodePointFromUTF8(reader); - slicesOut.Add(UnownedStringSlice(reader.m_pos, len)); + slicesOut.add(UnownedStringSlice(reader.m_pos, len)); cur = reader.m_pos + len; } } /* static */void SerialStringTableUtil::decodeStringTable(const List<char>& stringTable, List<UnownedStringSlice>& slicesOut) { - slicesOut.SetSize(2); + slicesOut.setCount(2); slicesOut[0] = UnownedStringSlice(nullptr, size_t(0)); slicesOut[1] = UnownedStringSlice("", size_t(0)); @@ -255,19 +255,19 @@ char* StringRepresentationCache::getCStr(Handle handle) /* static */void SerialStringTableUtil::calcStringSlicePoolMap(const List<UnownedStringSlice>& slices, StringSlicePool& pool, List<StringSlicePool::Handle>& indexMapOut) { - SLANG_ASSERT(slices.Count() >= StringSlicePool::kNumDefaultHandles); + SLANG_ASSERT(slices.getCount() >= StringSlicePool::kNumDefaultHandles); SLANG_ASSERT(slices[int(StringSlicePool::kNullHandle)] == "" && slices[int(StringSlicePool::kNullHandle)].begin() == nullptr); SLANG_ASSERT(slices[int(StringSlicePool::kEmptyHandle)] == ""); - indexMapOut.SetSize(slices.Count()); + indexMapOut.setCount(slices.getCount()); // Set up all of the defaults for (int i = 0; i < StringSlicePool::kNumDefaultHandles; ++i) { indexMapOut[i] = StringSlicePool::Handle(i); } - const int numSlices = int(slices.Count()); - for (int i = StringSlicePool::kNumDefaultHandles; i < numSlices ; ++i) + const Index numSlices = slices.getCount(); + for (Index i = StringSlicePool::kNumDefaultHandles; i < numSlices ; ++i) { indexMapOut[i] = pool.add(slices[i]); } @@ -278,7 +278,7 @@ char* StringRepresentationCache::getCStr(Handle handle) template<typename T> static size_t _calcArraySize(const List<T>& list) { - return list.Count() * sizeof(T); + return list.getCount() * sizeof(T); } size_t IRSerialData::calcSizeInBytes() const @@ -306,32 +306,32 @@ IRSerialData::IRSerialData() void IRSerialData::clear() { // First Instruction is null - m_insts.SetSize(1); + m_insts.setCount(1); memset(&m_insts[0], 0, sizeof(Inst)); - m_childRuns.Clear(); - m_externalOperands.Clear(); - m_rawSourceLocs.Clear(); + m_childRuns.clear(); + m_externalOperands.clear(); + m_rawSourceLocs.clear(); - m_stringTable.Clear(); + m_stringTable.clear(); // Debug data - m_debugLineInfos.Clear(); - m_debugAdjustedLineInfos.Clear(); - m_debugSourceInfos.Clear(); - m_debugSourceLocRuns.Clear(); - m_debugStringTable.Clear(); + m_debugLineInfos.clear(); + m_debugAdjustedLineInfos.clear(); + m_debugSourceInfos.clear(); + m_debugSourceLocRuns.clear(); + m_debugStringTable.clear(); } template <typename T> static bool _isEqual(const List<T>& aIn, const List<T>& bIn) { - if (aIn.Count() != bIn.Count()) + if (aIn.getCount() != bIn.getCount()) { return false; } - size_t size = size_t(aIn.Count()); + size_t size = size_t(aIn.getCount()); const T* a = aIn.begin(); const T* b = bIn.begin(); @@ -376,8 +376,8 @@ void IRSerialWriter::_addInstruction(IRInst* inst) SLANG_ASSERT(!m_instMap.ContainsKey(inst)); // Add to the map - m_instMap.Add(inst, Ser::InstIndex(m_insts.Count())); - m_insts.Add(inst); + m_instMap.Add(inst, Ser::InstIndex(m_insts.getCount())); + m_insts.add(inst); } #if 0 @@ -444,7 +444,7 @@ void IRSerialWriter::_addDebugSourceLocRun(SourceLoc sourceLoc, uint32_t startIn int entryIndex = sourceView->findEntryIndex(sourceLoc); if (entryIndex < 0) { - debugSourceFile->m_lineInfos.Add(lineInfo); + debugSourceFile->m_lineInfos.add(lineInfo); } else { @@ -463,7 +463,7 @@ void IRSerialWriter::_addDebugSourceLocRun(SourceLoc sourceLoc, uint32_t startIn adjustedLineInfo.m_adjustedLineIndex = lineIndex + entry.m_lineAdjust; - debugSourceFile->m_adjustedLineInfos.Add(adjustedLineInfo); + debugSourceFile->m_adjustedLineInfos.add(adjustedLineInfo); } debugSourceFile->setHasLineIndex(lineIndex); @@ -475,7 +475,7 @@ void IRSerialWriter::_addDebugSourceLocRun(SourceLoc sourceLoc, uint32_t startIn sourceLocRun.m_startInstIndex = IRSerialData::InstIndex(startInstIndex); sourceLocRun.m_sourceLoc = uint32_t(debugSourceFile->m_baseSourceLoc + offset); - m_serialData->m_debugSourceLocRuns.Add(sourceLocRun); + m_serialData->m_debugSourceLocRuns.add(sourceLocRun); } Result IRSerialWriter::_calcDebugInfo() @@ -497,8 +497,8 @@ Result IRSerialWriter::_calcDebugInfo() // Find all of the source locations and their associated instructions List<InstLoc> instLocs; - const int numInsts = int(m_insts.Count()); - for (int i = 1; i < numInsts; i++) + const Index numInsts = m_insts.getCount(); + for (Index i = 1; i < numInsts; i++) { IRInst* srcInst = m_insts[i]; if (!srcInst->sourceLoc.isValid()) @@ -508,11 +508,11 @@ Result IRSerialWriter::_calcDebugInfo() InstLoc instLoc; instLoc.instIndex = uint32_t(i); instLoc.sourceLoc = uint32_t(srcInst->sourceLoc.getRaw()); - instLocs.Add(instLoc); + instLocs.add(instLoc); } // Sort them - instLocs.Sort(); + instLocs.sort(); m_debugFreeSourceLoc = 1; // Look for runs @@ -549,25 +549,25 @@ Result IRSerialWriter::_calcDebugInfo() IRSerialData::DebugSourceInfo sourceInfo; - sourceInfo.m_numLines = uint32_t(debugSourceFile->m_sourceFile->getLineBreakOffsets().Count()); + sourceInfo.m_numLines = uint32_t(debugSourceFile->m_sourceFile->getLineBreakOffsets().getCount()); sourceInfo.m_startSourceLoc = uint32_t(debugSourceFile->m_baseSourceLoc); sourceInfo.m_endSourceLoc = uint32_t(debugSourceFile->m_baseSourceLoc + sourceFile->getContentSize()); sourceInfo.m_pathIndex = Ser::StringIndex(m_debugStringSlicePool.add(sourceFile->getPathInfo().foundPath)); - sourceInfo.m_lineInfosStartIndex = uint32_t(m_serialData->m_debugLineInfos.Count()); - sourceInfo.m_adjustedLineInfosStartIndex = uint32_t(m_serialData->m_debugAdjustedLineInfos.Count()); + sourceInfo.m_lineInfosStartIndex = uint32_t(m_serialData->m_debugLineInfos.getCount()); + sourceInfo.m_adjustedLineInfosStartIndex = uint32_t(m_serialData->m_debugAdjustedLineInfos.getCount()); - sourceInfo.m_numLineInfos = uint32_t(debugSourceFile->m_lineInfos.Count()); - sourceInfo.m_numAdjustedLineInfos = uint32_t(debugSourceFile->m_adjustedLineInfos.Count()); + sourceInfo.m_numLineInfos = uint32_t(debugSourceFile->m_lineInfos.getCount()); + sourceInfo.m_numAdjustedLineInfos = uint32_t(debugSourceFile->m_adjustedLineInfos.getCount()); // Add the line infos - m_serialData->m_debugLineInfos.AddRange(debugSourceFile->m_lineInfos.begin(), debugSourceFile->m_lineInfos.Count()); - m_serialData->m_debugAdjustedLineInfos.AddRange(debugSourceFile->m_adjustedLineInfos.begin(), debugSourceFile->m_adjustedLineInfos.Count()); + m_serialData->m_debugLineInfos.addRange(debugSourceFile->m_lineInfos.begin(), debugSourceFile->m_lineInfos.getCount()); + m_serialData->m_debugAdjustedLineInfos.addRange(debugSourceFile->m_adjustedLineInfos.begin(), debugSourceFile->m_adjustedLineInfos.getCount()); // Add the source info - m_serialData->m_debugSourceInfos.Add(sourceInfo); + m_serialData->m_debugSourceInfos.add(sourceInfo); } // Convert the string pool @@ -586,33 +586,33 @@ Result IRSerialWriter::write(IRModule* module, SourceManager* sourceManager, Opt serialData->clear(); // We reserve 0 for null - m_insts.Clear(); - m_insts.Add(nullptr); + m_insts.clear(); + m_insts.add(nullptr); // Reset m_instMap.Clear(); - m_decorations.Clear(); + m_decorations.clear(); // Stack for parentInst List<IRInst*> parentInstStack; IRModuleInst* moduleInst = module->getModuleInst(); - parentInstStack.Add(moduleInst); + parentInstStack.add(moduleInst); // Add to the map _addInstruction(moduleInst); // Traverse all of the instructions - while (parentInstStack.Count()) + while (parentInstStack.getCount()) { // If it's in the stack it is assumed it is already in the inst map - IRInst* parentInst = parentInstStack.Last(); - parentInstStack.RemoveLast(); + IRInst* parentInst = parentInstStack.getLast(); + parentInstStack.removeLast(); SLANG_ASSERT(m_instMap.ContainsKey(parentInst)); // Okay we go through each of the children in order. If they are IRInstParent derived, we add to stack to process later // cos we want breadth first so the order of children is the same as their index order, meaning we don't need to store explicit indices - const Ser::InstIndex startChildInstIndex = Ser::InstIndex(m_insts.Count()); + const Ser::InstIndex startChildInstIndex = Ser::InstIndex(m_insts.getCount()); IRInstListBase childrenList = parentInst->getDecorationsAndChildren(); for (IRInst* child : childrenList) @@ -622,18 +622,18 @@ Result IRSerialWriter::write(IRModule* module, SourceManager* sourceManager, Opt _addInstruction(child); - parentInstStack.Add(child); + parentInstStack.add(child); } // If it had any children, then store the information about it - if (Ser::InstIndex(m_insts.Count()) != startChildInstIndex) + if (Ser::InstIndex(m_insts.getCount()) != startChildInstIndex) { Ser::InstRun run; run.m_parentIndex = m_instMap[parentInst]; run.m_startInstIndex = startChildInstIndex; - run.m_numChildren = Ser::SizeType(m_insts.Count() - int(startChildInstIndex)); + run.m_numChildren = Ser::SizeType(m_insts.getCount() - int(startChildInstIndex)); - m_serialData->m_childRuns.Add(run); + m_serialData->m_childRuns.add(run); } } @@ -650,15 +650,15 @@ Result IRSerialWriter::write(IRModule* module, SourceManager* sourceManager, Opt #endif // Set to the right size - m_serialData->m_insts.SetSize(m_insts.Count()); + m_serialData->m_insts.setCount(m_insts.getCount()); // Clear all instructions - memset(m_serialData->m_insts.begin(), 0, sizeof(Ser::Inst) * m_serialData->m_insts.Count()); + memset(m_serialData->m_insts.begin(), 0, sizeof(Ser::Inst) * m_serialData->m_insts.getCount()); // Need to set up the actual instructions { - const int numInsts = int(m_insts.Count()); + const Index numInsts = m_insts.getCount(); - for (int i = 1; i < numInsts; ++i) + for (Index i = 1; i < numInsts; ++i) { IRInst* srcInst = m_insts[i]; Ser::Inst& dstInst = m_serialData->m_insts[i]; @@ -744,8 +744,8 @@ Result IRSerialWriter::write(IRModule* module, SourceManager* sourceManager, Opt { dstInst.m_payloadType = PayloadType::OperandExternal; - int operandArrayBaseIndex = int(m_serialData->m_externalOperands.Count()); - m_serialData->m_externalOperands.SetSize(operandArrayBaseIndex + numOperands); + int operandArrayBaseIndex = int(m_serialData->m_externalOperands.getCount()); + m_serialData->m_externalOperands.setCount(operandArrayBaseIndex + numOperands); dstOperands = m_serialData->m_externalOperands.begin() + operandArrayBaseIndex; @@ -770,13 +770,13 @@ Result IRSerialWriter::write(IRModule* module, SourceManager* sourceManager, Opt // If the option to use RawSourceLocations is enabled, serialize out as is if (options & OptionFlag::RawSourceLocation) { - const int numInsts = int(m_insts.Count()); - serialData->m_rawSourceLocs.SetSize(numInsts); + const Index numInsts = m_insts.getCount(); + serialData->m_rawSourceLocs.setCount(numInsts); Ser::RawSourceLoc* dstLocs = serialData->m_rawSourceLocs.begin(); // 0 is null, just mark as no location dstLocs[0] = Ser::RawSourceLoc(0); - for (int i = 1; i < numInsts; ++i) + for (Index i = 1; i < numInsts; ++i) { IRInst* srcInst = m_insts[i]; dstLocs[i] = Ser::RawSourceLoc(srcInst->sourceLoc.getRaw()); @@ -797,18 +797,18 @@ static size_t _calcChunkSize(IRSerialBinary::CompressionType compressionType, co { typedef IRSerialBinary Bin; - if (array.Count()) + if (array.getCount()) { switch (compressionType) { case Bin::CompressionType::None: { - const size_t size = sizeof(Bin::ArrayHeader) + sizeof(T) * array.Count(); + const size_t size = sizeof(Bin::ArrayHeader) + sizeof(T) * array.getCount(); return (size + 3) & ~size_t(3); } case Bin::CompressionType::VariableByteLite: { - const size_t payloadSize = ByteEncodeUtil::calcEncodeLiteSizeUInt32((const uint32_t*)array.begin(), (array.Count() * sizeof(T)) / sizeof(uint32_t)); + const size_t payloadSize = ByteEncodeUtil::calcEncodeLiteSizeUInt32((const uint32_t*)array.begin(), (array.getCount() * sizeof(T)) / sizeof(uint32_t)); const size_t size = sizeof(Bin::CompressedArrayHeader) + payloadSize; return (size + 3) & ~size_t(3); } @@ -860,7 +860,7 @@ static Result _writeArrayChunk(IRSerialBinary::CompressionType compressionType, ByteEncodeUtil::encodeLiteUInt32((const uint32_t*)data, numCompressedEntries, compressedPayload); - payloadSize = sizeof(Bin::CompressedArrayHeader) - sizeof(Bin::Chunk) + compressedPayload.Count(); + payloadSize = sizeof(Bin::CompressedArrayHeader) - sizeof(Bin::Chunk) + compressedPayload.getCount(); Bin::CompressedArrayHeader header; header.m_chunk.m_type = SLANG_MAKE_COMPRESSED_FOUR_CC(chunkId); @@ -870,7 +870,7 @@ static Result _writeArrayChunk(IRSerialBinary::CompressionType compressionType, stream->Write(&header, sizeof(header)); - stream->Write(compressedPayload.begin(), compressedPayload.Count()); + stream->Write(compressedPayload.begin(), compressedPayload.getCount()); break; } default: @@ -893,7 +893,7 @@ static Result _writeArrayChunk(IRSerialBinary::CompressionType compressionType, template <typename T> Result _writeArrayChunk(IRSerialBinary::CompressionType compressionType, uint32_t chunkId, const List<T>& array, Stream* stream) { - return _writeArrayChunk(compressionType, chunkId, array.begin(), size_t(array.Count()), sizeof(T), stream); + return _writeArrayChunk(compressionType, chunkId, array.begin(), size_t(array.getCount()), sizeof(T), stream); } Result _encodeInsts(IRSerialBinary::CompressionType compressionType, const List<IRSerialData::Inst>& instsIn, List<uint8_t>& encodeArrayOut) @@ -905,9 +905,9 @@ Result _encodeInsts(IRSerialBinary::CompressionType compressionType, const List< { return SLANG_FAIL; } - encodeArrayOut.Clear(); + encodeArrayOut.clear(); - const size_t numInsts = size_t(instsIn.Count()); + const size_t numInsts = size_t(instsIn.getCount()); const IRSerialData::Inst* insts = instsIn.begin(); uint8_t* encodeOut = encodeArrayOut.begin(); @@ -927,11 +927,11 @@ Result _encodeInsts(IRSerialBinary::CompressionType compressionType, const List< { const size_t offset = size_t(encodeOut - encodeArrayOut.begin()); - const UInt oldCapacity = encodeArrayOut.Capacity(); + const UInt oldCapacity = encodeArrayOut.getCapacity(); - encodeArrayOut.Reserve(oldCapacity + (oldCapacity >> 1) + maxInstSize); - const UInt capacity = encodeArrayOut.Capacity(); - encodeArrayOut.SetSize(capacity); + encodeArrayOut.reserve(oldCapacity + (oldCapacity >> 1) + maxInstSize); + const UInt capacity = encodeArrayOut.getCapacity(); + encodeArrayOut.setCount(capacity); encodeOut = encodeArrayOut.begin() + offset; encodeEnd = encodeArrayOut.end(); @@ -982,14 +982,14 @@ Result _encodeInsts(IRSerialBinary::CompressionType compressionType, const List< } // Fix the size - encodeArrayOut.SetSize(UInt(encodeOut - encodeArrayOut.begin())); + encodeArrayOut.setCount(UInt(encodeOut - encodeArrayOut.begin())); return SLANG_OK; } Result _writeInstArrayChunk(IRSerialBinary::CompressionType compressionType, uint32_t chunkId, const List<IRSerialData::Inst>& array, Stream* stream) { typedef IRSerialBinary Bin; - if (array.Count() == 0) + if (array.getCount() == 0) { return SLANG_OK; } @@ -1005,16 +1005,16 @@ Result _writeInstArrayChunk(IRSerialBinary::CompressionType compressionType, uin List<uint8_t> compressedPayload; SLANG_RETURN_ON_FAIL(_encodeInsts(compressionType, array, compressedPayload)); - size_t payloadSize = sizeof(Bin::CompressedArrayHeader) - sizeof(Bin::Chunk) + compressedPayload.Count(); + size_t payloadSize = sizeof(Bin::CompressedArrayHeader) - sizeof(Bin::Chunk) + compressedPayload.getCount(); Bin::CompressedArrayHeader header; header.m_chunk.m_type = SLANG_MAKE_COMPRESSED_FOUR_CC(chunkId); header.m_chunk.m_size = uint32_t(payloadSize); - header.m_numEntries = uint32_t(array.Count()); + header.m_numEntries = uint32_t(array.getCount()); header.m_numCompressedEntries = 0; stream->Write(&header, sizeof(header)); - stream->Write(compressedPayload.begin(), compressedPayload.Count()); + stream->Write(compressedPayload.begin(), compressedPayload.getCount()); // All chunks have sizes rounded to dword size if (payloadSize & 3) @@ -1046,7 +1046,7 @@ static size_t _calcInstChunkSize(IRSerialBinary::CompressionType compressionType { size_t size = sizeof(Bin::CompressedArrayHeader); - size_t numInsts = size_t(instsIn.Count()); + size_t numInsts = size_t(instsIn.getCount()); size += numInsts * 2; // op and payload IRSerialData::Inst* insts = instsIn.begin(); @@ -1114,7 +1114,7 @@ static size_t _calcInstChunkSize(IRSerialBinary::CompressionType compressionType _calcChunkSize(Bin::CompressionType::None, data.m_stringTable) + _calcChunkSize(Bin::CompressionType::None, data.m_rawSourceLocs); - if (data.m_debugSourceInfos.Count()) + if (data.m_debugSourceInfos.getCount()) { totalSize += _calcChunkSize(Bin::CompressionType::None, data.m_debugStringTable) + _calcChunkSize(Bin::CompressionType::None, data.m_debugLineInfos) + @@ -1146,7 +1146,7 @@ static size_t _calcInstChunkSize(IRSerialBinary::CompressionType compressionType SLANG_RETURN_ON_FAIL(_writeArrayChunk(Bin::CompressionType::None, Bin::kUInt32SourceLocFourCc, data.m_rawSourceLocs, stream)); - if (data.m_debugSourceInfos.Count()) + if (data.m_debugSourceInfos.getCount()) { _writeArrayChunk(Bin::CompressionType::None, Bin::kDebugStringFourCc, data.m_debugStringTable, stream); _writeArrayChunk(Bin::CompressionType::None, Bin::kDebugLineInfoFourCc, data.m_debugLineInfos, stream); @@ -1184,7 +1184,7 @@ class ListResizerForType: public ListResizer virtual void* setSize(size_t newSize) SLANG_OVERRIDE { - m_list.SetSize(UInt(newSize)); + m_list.setCount(UInt(newSize)); return (void*)m_list.begin(); } @@ -1215,7 +1215,7 @@ static Result _readArrayChunk(IRSerialBinary::CompressionType compressionType, c size_t payloadSize = header.m_chunk.m_size - (sizeof(header) - sizeof(Bin::Chunk)); List<uint8_t> compressedPayload; - compressedPayload.SetSize(payloadSize); + compressedPayload.setCount(payloadSize); stream->Read(compressedPayload.begin(), payloadSize); *numReadInOut += payloadSize; @@ -1294,7 +1294,7 @@ static Result _decodeInsts(IRSerialBinary::CompressionType compressionType, cons return SLANG_FAIL; } - const size_t numInsts = size_t(instsOut.Count()); + const size_t numInsts = size_t(instsOut.getCount()); IRSerialData::Inst* insts = instsOut.begin(); const uint8_t* encodeCur = encodeIn.begin(); @@ -1381,12 +1381,12 @@ Result _readInstArrayChunk(const IRSerialBinary::SlangHeader& slangHeader, const size_t payloadSize = header.m_chunk.m_size - (sizeof(header) - sizeof(Bin::Chunk)); List<uint8_t> compressedPayload; - compressedPayload.SetSize(payloadSize); + compressedPayload.setCount(payloadSize); stream->Read(compressedPayload.begin(), payloadSize); *numReadInOut += payloadSize; - arrayOut.SetSize(header.m_numEntries); + arrayOut.setCount(header.m_numEntries); SLANG_RETURN_ON_FAIL(_decodeInsts(compressionType, compressedPayload, arrayOut)); break; @@ -1561,7 +1561,7 @@ static SourceRange _toSourceRange(const IRSerialData::DebugSourceInfo& info) static int _findIndex(const List<IRSerialData::DebugSourceInfo>& infos, SourceLoc sourceLoc) { - const int numInfos = int(infos.Count()); + const int numInfos = int(infos.getCount()); for (int i = 0; i < numInfos; ++i) { if (_toSourceRange(infos[i]).contains(sourceLoc)) @@ -1598,11 +1598,11 @@ static int _calcFixSourceLoc(const IRSerialData::DebugSourceInfo& info, SourceVi List<IRInst*> insts; - const int numInsts = int(data.m_insts.Count()); + const Index numInsts = data.m_insts.getCount(); SLANG_ASSERT(numInsts > 0); - insts.SetSize(numInsts); + insts.setCount(numInsts); insts[0] = nullptr; // 0 holds null @@ -1622,7 +1622,7 @@ static int _calcFixSourceLoc(const IRSerialData::DebugSourceInfo& info, SourceVi insts[1] = moduleInst; } - for (int i = 2; i < numInsts; ++i) + for (Index i = 2; i < numInsts; ++i) { const Ser::Inst& srcInst = data.m_insts[i]; @@ -1714,7 +1714,7 @@ static int _calcFixSourceLoc(const IRSerialData::DebugSourceInfo& info, SourceVi } // Patch up the operands - for (int i = 1; i < numInsts; ++i) + for (Index i = 1; i < numInsts; ++i) { const Ser::Inst& srcInst = data.m_insts[i]; const IROp op((IROp)srcInst.m_op); @@ -1746,8 +1746,8 @@ static int _calcFixSourceLoc(const IRSerialData::DebugSourceInfo& info, SourceVi // Patch up the children { - const int numChildRuns = int(data.m_childRuns.Count()); - for (int i = 0; i < numChildRuns; i++) + const Index numChildRuns = data.m_childRuns.getCount(); + for (Index i = 0; i < numChildRuns; i++) { const auto& run = data.m_childRuns[i]; @@ -1763,10 +1763,10 @@ static int _calcFixSourceLoc(const IRSerialData::DebugSourceInfo& info, SourceVi } // Re-add source locations, if they are defined - if (int(m_serialData->m_rawSourceLocs.Count()) == numInsts) + if (m_serialData->m_rawSourceLocs.getCount() == numInsts) { const Ser::RawSourceLoc* srcLocs = m_serialData->m_rawSourceLocs.begin(); - for (int i = 1; i < numInsts; ++i) + for (Index i = 1; i < numInsts; ++i) { IRInst* dstInst = insts[i]; @@ -1774,7 +1774,7 @@ static int _calcFixSourceLoc(const IRSerialData::DebugSourceInfo& info, SourceVi } } - if (sourceManager && m_serialData->m_debugSourceInfos.Count()) + if (sourceManager && m_serialData->m_debugSourceInfos.getCount()) { List<UnownedStringSlice> debugStringSlices; SerialStringTableUtil::decodeStringTable(m_serialData->m_debugStringTable, debugStringSlices); @@ -1786,13 +1786,13 @@ static int _calcFixSourceLoc(const IRSerialData::DebugSourceInfo& info, SourceVi const List<IRSerialData::DebugSourceInfo>& sourceInfos = m_serialData->m_debugSourceInfos; // Construct the source files - int numSourceFiles = int(sourceInfos.Count()); + Index numSourceFiles = sourceInfos.getCount(); // These hold the views (and SourceFile as there is only one SourceFile per view) in the same order as the sourceInfos List<SourceView*> sourceViews; - sourceViews.SetSize(numSourceFiles); + sourceViews.setCount(numSourceFiles); - for (int i = 0; i < numSourceFiles; ++i) + for (Index i = 0; i < numSourceFiles; ++i) { const IRSerialData::DebugSourceInfo& srcSourceInfo = sourceInfos[i]; @@ -1807,8 +1807,8 @@ static int _calcFixSourceLoc(const IRSerialData::DebugSourceInfo& info, SourceVi List<IRSerialData::DebugLineInfo> lineInfos; // Add the adjusted lines { - lineInfos.SetSize(srcSourceInfo.m_numAdjustedLineInfos); - IRSerialData::DebugAdjustedLineInfo* srcAdjustedLineInfos = m_serialData->m_debugAdjustedLineInfos.Buffer() + srcSourceInfo.m_adjustedLineInfosStartIndex; + lineInfos.setCount(srcSourceInfo.m_numAdjustedLineInfos); + const IRSerialData::DebugAdjustedLineInfo* srcAdjustedLineInfos = m_serialData->m_debugAdjustedLineInfos.getBuffer() + srcSourceInfo.m_adjustedLineInfosStartIndex; const int numAdjustedLines = int(srcSourceInfo.m_numAdjustedLineInfos); for (int j = 0; j < numAdjustedLines; ++j) { @@ -1816,22 +1816,22 @@ static int _calcFixSourceLoc(const IRSerialData::DebugSourceInfo& info, SourceVi } } // Add regular lines - lineInfos.AddRange(m_serialData->m_debugLineInfos.Buffer() + srcSourceInfo.m_lineInfosStartIndex, srcSourceInfo.m_numLineInfos); + lineInfos.addRange(m_serialData->m_debugLineInfos.getBuffer() + srcSourceInfo.m_lineInfosStartIndex, srcSourceInfo.m_numLineInfos); // Put in sourceloc order - lineInfos.Sort(); + lineInfos.sort(); List<uint32_t> lineBreakOffsets; // We can now set up the line breaks array const int numLines = int(srcSourceInfo.m_numLines); - lineBreakOffsets.SetSize(numLines); + lineBreakOffsets.setCount(numLines); { - const int numLineInfos = int(lineInfos.Count()); - int lineIndex = 0; + const Index numLineInfos = lineInfos.getCount(); + Index lineIndex = 0; // Every line up and including should hold the same offset - for (int lineInfoIndex = 0; lineInfoIndex < numLineInfos; ++lineInfoIndex) + for (Index lineInfoIndex = 0; lineInfoIndex < numLineInfos; ++lineInfoIndex) { const auto& lineInfo = lineInfos[lineInfoIndex]; @@ -1857,7 +1857,7 @@ static int _calcFixSourceLoc(const IRSerialData::DebugSourceInfo& info, SourceVi } } - sourceFile->setLineBreakOffsets(lineBreakOffsets.Buffer(), lineBreakOffsets.Count()); + sourceFile->setLineBreakOffsets(lineBreakOffsets.getBuffer(), lineBreakOffsets.getCount()); if (srcSourceInfo.m_numAdjustedLineInfos) { @@ -1865,12 +1865,12 @@ static int _calcFixSourceLoc(const IRSerialData::DebugSourceInfo& info, SourceVi int numEntries = int(srcSourceInfo.m_numAdjustedLineInfos); - adjustedLineInfos.AddRange(m_serialData->m_debugAdjustedLineInfos.Buffer() + srcSourceInfo.m_adjustedLineInfosStartIndex, numEntries); - adjustedLineInfos.Sort(); + adjustedLineInfos.addRange(m_serialData->m_debugAdjustedLineInfos.getBuffer() + srcSourceInfo.m_adjustedLineInfosStartIndex, numEntries); + adjustedLineInfos.sort(); // Work out the views adjustments, and place in dstEntries List<SourceView::Entry> dstEntries; - dstEntries.SetSize(numEntries); + dstEntries.setCount(numEntries); const uint32_t sourceLocOffset = uint32_t(sourceView->getRange().begin.getRaw()); @@ -1885,7 +1885,7 @@ static int _calcFixSourceLoc(const IRSerialData::DebugSourceInfo& info, SourceVi } // Set the adjustments on the view - sourceView->setEntries(dstEntries.Buffer(), dstEntries.Count()); + sourceView->setEntries(dstEntries.getBuffer(), dstEntries.getCount()); } sourceViews[i] = sourceView; @@ -1895,14 +1895,14 @@ static int _calcFixSourceLoc(const IRSerialData::DebugSourceInfo& info, SourceVi { List<IRSerialData::SourceLocRun> sourceRuns(m_serialData->m_debugSourceLocRuns); // They are now in source location order - sourceRuns.Sort(); + sourceRuns.sort(); // Just guess initially 0 for the source file that contains the initial run SourceRange range; int fixSourceLoc = _calcFixSourceLoc(sourceInfos[0], sourceViews[0], range); - const int numRuns = int(sourceRuns.Count()); - for (int i = 0; i < numRuns; ++i) + const Index numRuns = sourceRuns.getCount(); + for (Index i = 0; i < numRuns; ++i) { const auto& run = sourceRuns[i]; const SourceLoc srcSourceLoc = SourceLoc::fromRaw(run.m_sourceLoc); @@ -1922,8 +1922,8 @@ static int _calcFixSourceLoc(const IRSerialData::DebugSourceInfo& info, SourceVi // Work out the fixed source location SourceLoc sourceLoc = SourceLoc::fromRaw(int(run.m_sourceLoc) + fixSourceLoc); - SLANG_ASSERT(uint32_t(run.m_startInstIndex) + run.m_numInst <= insts.Count()); - IRInst** dstInsts = insts.Buffer() + int(run.m_startInstIndex); + SLANG_ASSERT(Index(uint32_t(run.m_startInstIndex) + run.m_numInst) <= insts.getCount()); + IRInst** dstInsts = insts.getBuffer() + int(run.m_startInstIndex); const int runSize = int(run.m_numInst); for (int j = 0; j < runSize; ++j) @@ -1942,30 +1942,30 @@ static int _calcFixSourceLoc(const IRSerialData::DebugSourceInfo& info, SourceVi /* static */void IRSerialUtil::calcInstructionList(IRModule* module, List<IRInst*>& instsOut) { // We reserve 0 for null - instsOut.SetSize(1); + instsOut.setCount(1); instsOut[0] = nullptr; // Stack for parentInst List<IRInst*> parentInstStack; IRModuleInst* moduleInst = module->getModuleInst(); - parentInstStack.Add(moduleInst); + parentInstStack.add(moduleInst); // Add to list - instsOut.Add(moduleInst); + instsOut.add(moduleInst); // Traverse all of the instructions - while (parentInstStack.Count()) + while (parentInstStack.getCount()) { // If it's in the stack it is assumed it is already in the inst map - IRInst* parentInst = parentInstStack.Last(); - parentInstStack.RemoveLast(); + IRInst* parentInst = parentInstStack.getLast(); + parentInstStack.removeLast(); IRInstListBase childrenList = parentInst->getDecorationsAndChildren(); for (IRInst* child : childrenList) { - instsOut.Add(child); - parentInstStack.Add(child); + instsOut.add(child); + parentInstStack.add(child); } } } @@ -2015,7 +2015,7 @@ static int _calcFixSourceLoc(const IRSerialData::DebugSourceInfo& info, SourceVi List<IRInst*> readInsts; calcInstructionList(irReadModule, readInsts); - if (readInsts.Count() != originalInsts.Count()) + if (readInsts.getCount() != originalInsts.getCount()) { SLANG_ASSERT(!"Instruction counts don't match"); return SLANG_FAIL; @@ -2025,7 +2025,7 @@ static int _calcFixSourceLoc(const IRSerialData::DebugSourceInfo& info, SourceVi { SLANG_ASSERT(readInsts[0] == originalInsts[0]); // All the source locs should be identical - for (UInt i = 1; i < readInsts.Count(); ++i) + for (Index i = 1; i < readInsts.getCount(); ++i) { IRInst* origInst = originalInsts[i]; IRInst* readInst = readInsts[i]; @@ -2040,7 +2040,7 @@ static int _calcFixSourceLoc(const IRSerialData::DebugSourceInfo& info, SourceVi else if (optionFlags & IRSerialWriter::OptionFlag::DebugInfo) { // They should be on the same line nos - for (UInt i = 1; i < readInsts.Count(); ++i) + for (Index i = 1; i < readInsts.getCount(); ++i) { IRInst* origInst = originalInsts[i]; IRInst* readInst = readInsts[i]; diff --git a/source/slang/ir-serialize.h b/source/slang/ir-serialize.h index c32013928..8be852e95 100644 --- a/source/slang/ir-serialize.h +++ b/source/slang/ir-serialize.h @@ -461,10 +461,10 @@ protected: // Need to know how many lines there are const List<uint32_t>& lineOffsets = sourceFile->getLineBreakOffsets(); - const auto numLineIndices = lineOffsets.Count(); + const auto numLineIndices = lineOffsets.getCount(); // Set none as being used initially - m_lineIndexUsed.SetSize(numLineIndices); + m_lineIndexUsed.setCount(numLineIndices); ::memset(m_lineIndexUsed.begin(), 0, numLineIndices * sizeof(uint8_t)); } /// True if we have information on that line index diff --git a/source/slang/ir-specialize-resources.cpp b/source/slang/ir-specialize-resources.cpp index d25284927..96f328672 100644 --- a/source/slang/ir-specialize-resources.cpp +++ b/source/slang/ir-specialize-resources.cpp @@ -57,10 +57,10 @@ struct ResourceParameterSpecializationContext // We will process the work list until it goes dry, // treating it like a stack of work items. // - while( workList.Count() ) + while( workList.getCount() ) { - auto call = workList.Last(); - workList.RemoveLast(); + auto call = workList.getLast(); + workList.removeLast(); // At each call site we first check whether it // is something we can (and should) specialize, @@ -84,7 +84,7 @@ struct ResourceParameterSpecializationContext // if( auto call = as<IRCall>(inst) ) { - workList.Add(call); + workList.add(call); } // Recursively walk through any children, to @@ -395,8 +395,8 @@ struct ResourceParameterSpecializationContext auto newCall = getBuilder()->emitCallInst( oldCall->getFullType(), newFunc, - callInfo.newArgs.Count(), - callInfo.newArgs.Buffer()); + callInfo.newArgs.getCount(), + callInfo.newArgs.getBuffer()); newCall->insertBefore(oldCall); oldCall->replaceUsesWith(newCall); @@ -477,7 +477,7 @@ struct ResourceParameterSpecializationContext // the original function, since different functions // will always yield different specializations. // - callInfo.key.vals.Add(oldFunc); + callInfo.key.vals.add(oldFunc); // The rest of the information is gathered by looking // at parameter and argument pairs. @@ -507,7 +507,7 @@ struct ResourceParameterSpecializationContext // to add any information to distinguish the // specialized callee based on this paramter. // - ioInfo.newArgs.Add(oldArg); + ioInfo.newArgs.add(oldArg); } else { @@ -537,7 +537,7 @@ struct ResourceParameterSpecializationContext // callee reflects that we are specializing // to the chosen parameter. // - ioInfo.key.vals.Add(oldGlobalParam); + ioInfo.key.vals.add(oldGlobalParam); } else if( oldArg->op == kIROp_getElement ) { @@ -563,7 +563,7 @@ struct ResourceParameterSpecializationContext // the arguments at the new call site, and // don't add anything to the specialization key. // - ioInfo.newArgs.Add(oldIndex); + ioInfo.newArgs.add(oldIndex); } else { @@ -601,7 +601,7 @@ struct ResourceParameterSpecializationContext // We will collect the replacement value to use // for each of the original parameters in an array. // - funcInfo.replacementsForOldParameters.Add(newVal); + funcInfo.replacementsForOldParameters.add(newVal); } } @@ -620,7 +620,7 @@ struct ResourceParameterSpecializationContext // create it here. // auto newParam = getBuilder()->createParam(oldParam->getFullType()); - ioInfo.newParams.Add(newParam); + ioInfo.newParams.add(newParam); // The new parameter will be used as the replacement // for the old one in the specialized function. @@ -683,7 +683,7 @@ struct ResourceParameterSpecializationContext // auto builder = getBuilder(); auto newIndex = builder->createParam(oldIndex->getFullType()); - ioInfo.newParams.Add(newIndex); + ioInfo.newParams.add(newIndex); // Finally, we need to compute a value that // can stand in for `oldArg` (which was @@ -714,7 +714,7 @@ struct ResourceParameterSpecializationContext // that should be inserted into the body of // the specialized callee. // - ioInfo.newBodyInsts.Add(newVal); + ioInfo.newBodyInsts.add(newVal); return newVal; } @@ -773,13 +773,13 @@ struct ResourceParameterSpecializationContext List<IRType*> paramTypes; for( auto param : funcInfo.newParams ) { - paramTypes.Add(param->getFullType()); + paramTypes.add(param->getFullType()); } auto builder = getBuilder(); IRType* funcType = builder->getFuncType( - paramTypes.Count(), - paramTypes.Buffer(), + paramTypes.getCount(), + paramTypes.getBuffer(), oldFunc->getResultType()); IRFunc* newFunc = builder->createFunc(); diff --git a/source/slang/ir-specialize.cpp b/source/slang/ir-specialize.cpp index e491eaa31..57d14c11a 100644 --- a/source/slang/ir-specialize.cpp +++ b/source/slang/ir-specialize.cpp @@ -112,7 +112,7 @@ struct SpecializationContext return; } - workList.Add(inst); + workList.add(inst); } // When a transformation makes a change to an instruction, @@ -192,11 +192,11 @@ struct SpecializationContext // the array `[g, a, b, c]`. // Key key; - key.vals.Add(specializeInst->getBase()); + key.vals.add(specializeInst->getBase()); UInt argCount = specializeInst->getArgCount(); for( UInt ii = 0; ii < argCount; ++ii ) { - key.vals.Add(specializeInst->getArg(ii)); + key.vals.add(specializeInst->getArg(ii)); } { @@ -568,10 +568,10 @@ struct SpecializationContext // We will then iterate until our work list goes dry. // - while(workList.Count() != 0) + while(workList.getCount() != 0) { - IRInst* inst = workList.Last(); - workList.RemoveLast(); + IRInst* inst = workList.getLast(); + workList.removeLast(); // For each instruction we process, we want to perform // a few steps. @@ -677,7 +677,7 @@ struct SpecializationContext // The specialized callee will always depend on the unspecialized // function from which it is generated, so we add that to our key. // - key.vals.Add(calleeFunc); + key.vals.add(calleeFunc); // Also, for any parameter that has an existential type, the // specialized function will depend on the concrete type of the @@ -700,7 +700,7 @@ struct SpecializationContext // auto val = makeExistential->getWrappedValue(); auto valType = val->getFullType(); - key.vals.Add(valType); + key.vals.add(valType); // We are also including the witness table in the key. // This isn't required with our current language model, @@ -717,7 +717,7 @@ struct SpecializationContext // table even if it is redundant. // auto witnessTable = makeExistential->getWitnessTable(); - key.vals.Add(witnessTable); + key.vals.add(witnessTable); } else { @@ -757,7 +757,7 @@ struct SpecializationContext // If the parameter doesn't have an existential type, then we // don't want to change up the argument we pass at all. // - newArgs.Add(arg); + newArgs.add(arg); } else { @@ -768,7 +768,7 @@ struct SpecializationContext if( auto makeExistential = as<IRMakeExistential>(arg) ) { auto val = makeExistential->getWrappedValue(); - newArgs.Add(val); + newArgs.add(val); } else { @@ -912,7 +912,7 @@ struct SpecializationContext // and we'll use that instead of the original parameter. // auto newParam = builder->createParam(oldParam->getFullType()); - newParams.Add(newParam); + newParams.add(newParam); replacementVal = newParam; } else @@ -936,7 +936,7 @@ struct SpecializationContext // auto valType = val->getFullType(); auto newParam = builder->createParam(valType); - newParams.Add(newParam); + newParams.add(newParam); // Within the body of the function we cannot just use `val` // directly, because the existing code expects an existential @@ -948,7 +948,7 @@ struct SpecializationContext // correct existential type, and stores the right witness table). // auto newMakeExistential = builder->emitMakeExistential(oldParam->getFullType(), newParam, witnessTable); - newBodyInsts.Add(newMakeExistential); + newBodyInsts.add(newMakeExistential); replacementVal = newMakeExistential; } else @@ -972,11 +972,11 @@ struct SpecializationContext List<IRType*> newParamTypes; for( auto newParam : newParams ) { - newParamTypes.Add(newParam->getFullType()); + newParamTypes.add(newParam->getFullType()); } IRType* newFuncType = builder->getFuncType( - newParamTypes.Count(), - newParamTypes.Buffer(), + newParamTypes.getCount(), + newParamTypes.getBuffer(), oldFunc->getResultType()); IRFunc* newFunc = builder->createFunc(); newFunc->setFullType(newFuncType); @@ -1190,7 +1190,7 @@ struct SpecializationContext UInt slotOperandCount = wrapInst->getSlotOperandCount(); for( UInt ii = 0; ii < slotOperandCount; ++ii ) { - slotOperands.Add(wrapInst->getSlotOperand(ii)); + slotOperands.add(wrapInst->getSlotOperand(ii)); } auto newLoadInst = builder.emitLoad(elementType, val); @@ -1198,7 +1198,7 @@ struct SpecializationContext resultType, newLoadInst, slotOperandCount, - slotOperands.Buffer()); + slotOperands.getBuffer()); addUsersToWorkList(inst); diff --git a/source/slang/ir-ssa.cpp b/source/slang/ir-ssa.cpp index 624454a43..64f9210e1 100644 --- a/source/slang/ir-ssa.cpp +++ b/source/slang/ir-ssa.cpp @@ -247,7 +247,7 @@ void identifyPromotableVars( if (isPromotableVar(context, var)) { - context->promotableVars.Add(var); + context->promotableVars.add(var); } } } @@ -262,7 +262,7 @@ IRVar* asPromotableVar( return nullptr; IRVar* var = (IRVar*)value; - if (!context->promotableVars.Contains(var)) + if (!context->promotableVars.contains(var)) return nullptr; return var; @@ -312,7 +312,7 @@ IRInst* applyAccessChain( case kIROp_FieldAddress: { - SLANG_ASSERT(context->instsToRemove.Contains(accessChain)); + SLANG_ASSERT(context->instsToRemove.contains(accessChain)); auto baseChain = accessChain->getOperand(0); auto fieldKey = accessChain->getOperand(1); @@ -326,7 +326,7 @@ IRInst* applyAccessChain( case kIROp_getElementPtr: { - SLANG_ASSERT(context->instsToRemove.Contains(accessChain)); + SLANG_ASSERT(context->instsToRemove.contains(accessChain)); auto baseChain = accessChain->getOperand(0); auto index = accessChain->getOperand(1); @@ -407,7 +407,7 @@ PhiInfo* addPhi( phiInfo->phi = phi; phiInfo->var = var; - blockInfo->phis.Add(phiInfo); + blockInfo->phis.add(phiInfo); return phiInfo; } @@ -474,7 +474,7 @@ IRInst* tryRemoveTrivialPhi( auto maybeOtherPhi = (IRParam*) user; if( auto otherPhiInfo = context->getPhiInfo(maybeOtherPhi) ) { - otherPhis.Add(otherPhiInfo); + otherPhis.add(otherPhiInfo); } } } @@ -525,7 +525,7 @@ IRInst* addPhiOperands( auto phiOperand = readVar(context, predInfo, var); - operandValues.Add(phiOperand); + operandValues.add(phiOperand); } // The `IRUse` type needs to stay at a stable location @@ -533,8 +533,8 @@ IRInst* addPhiOperands( // list with its final size so that we can preserve the // required invariant. - UInt operandCount = operandValues.Count(); - phiInfo->operands.SetSize(operandCount); + UInt operandCount = operandValues.getCount(); + phiInfo->operands.setCount(operandCount); for(UInt ii = 0; ii < operandCount; ++ii) { phiInfo->operands[ii].init(phiInfo->phi, operandValues[ii]); @@ -577,7 +577,7 @@ void maybeSealBlock( // Note that we are doing the "inefficient" loop where we compute // the count on each iteration to account for the possibility that // new incomplete phis will get added while we are working. - for (UInt ii = 0; ii < blockInfo->phis.Count(); ++ii) + for (Index ii = 0; ii < blockInfo->phis.getCount(); ++ii) { auto incompletePhi = blockInfo->phis[ii]; addPhiOperands(context, blockInfo, incompletePhi); @@ -845,7 +845,7 @@ void processBlock( auto ptrArg = ii->getOperand(0); if (auto var = asPromotableVarAccessChain(context, ptrArg)) { - context->instsToRemove.Add(ii); + context->instsToRemove.add(ii); } } break; @@ -929,7 +929,7 @@ static void breakCriticalEdges( // Furthermore, the `IRUse` embedded in `succIter` represents // that edge directly. auto edgeUse = succIter.use; - criticalEdges.Add(edgeUse); + criticalEdges.add(edgeUse); } } @@ -984,7 +984,7 @@ void constructSSA(ConstructSSAContext* context) // If none of the variables are promote-able, // then we can exit without making any changes - if (context->promotableVars.Count() == 0) + if (context->promotableVars.getCount() == 0) return; // We are going to walk the blocks in order, @@ -1036,7 +1036,7 @@ void constructSSA(ConstructSSAContext* context) phiInfo->operands[predIndex].clear(); - predInfo->successorArgs.Add(operandVal); + predInfo->successorArgs.add(operandVal); } } } @@ -1053,7 +1053,7 @@ void constructSSA(ConstructSSAContext* context) // Don't do any work for blocks that don't need to pass along // values to the sucessor block. - auto addedArgCount = blockInfo->successorArgs.Count(); + auto addedArgCount = blockInfo->successorArgs.getCount(); if (addedArgCount == 0) continue; @@ -1071,18 +1071,18 @@ void constructSSA(ConstructSSAContext* context) List<IRInst*> newArgs; for (UInt aa = 0; aa < oldArgCount; ++aa) { - newArgs.Add(oldTerminator->getOperand(aa)); + newArgs.add(oldTerminator->getOperand(aa)); } - for (UInt aa = 0; aa < addedArgCount; ++aa) + for (Index aa = 0; aa < addedArgCount; ++aa) { - newArgs.Add(blockInfo->successorArgs[aa]); + newArgs.add(blockInfo->successorArgs[aa]); } IRTerminatorInst* newTerminator = (IRTerminatorInst*)blockInfo->builder.emitIntrinsicInst( oldTerminator->getFullType(), oldTerminator->op, newArgCount, - newArgs.Buffer()); + newArgs.getBuffer()); // Transfer decorations (a terminator should have no children) over to the new instruction. // diff --git a/source/slang/ir-union.cpp b/source/slang/ir-union.cpp index 91e60c5bf..b4fbc4c96 100644 --- a/source/slang/ir-union.cpp +++ b/source/slang/ir-union.cpp @@ -230,7 +230,7 @@ struct DesugarUnionTypesContext // list for later removal. // inst->replaceUsesWith(replacement); - instsToRemove.Add(inst); + instsToRemove.add(inst); } break; @@ -269,7 +269,7 @@ struct DesugarUnionTypesContext // for fields, etc.). // auto taggedUnionTypeLayout = taggedUnionInfo->taggedUnionTypeLayout; - SLANG_ASSERT(caseTagIndex < taggedUnionTypeLayout->caseTypeLayouts.Count()); + SLANG_ASSERT(caseTagIndex < UInt(taggedUnionTypeLayout->caseTypeLayouts.getCount())); auto caseTypeLayout = taggedUnionTypeLayout->caseTypeLayouts[caseTagIndex]; // At this point we know the type we are trying to extract, as well @@ -321,7 +321,7 @@ struct DesugarUnionTypesContext // this instruction, and schedule the original instruction for removal. // inst->replaceUsesWith(payloadVal); - instsToRemove.Add(inst); + instsToRemove.add(inst); } break; } @@ -403,7 +403,7 @@ struct DesugarUnionTypesContext fieldType, fieldTypeLayout, fieldOffset); - fieldVals.Add(fieldVal); + fieldVals.add(fieldVal); } // The final value is then just a new struct constructed from @@ -447,7 +447,7 @@ struct DesugarUnionTypesContext elementType, elementTypeLayout, payloadOffset + ii*elementSize); - elementVals.Add(elementVal); + elementVals.add(elementVal); } return builder->emitMakeVector(vecType, elementVals); } @@ -625,7 +625,7 @@ struct DesugarUnionTypesContext // auto info = createTaggedUnionInfo(type); mapIRTypeToTaggedUnionInfo.Add(type, info.Ptr()); - taggedUnionInfos.Add(info); + taggedUnionInfos.add(info); return info; } diff --git a/source/slang/ir.cpp b/source/slang/ir.cpp index 43ec09abb..150a5d544 100644 --- a/source/slang/ir.cpp +++ b/source/slang/ir.cpp @@ -275,12 +275,12 @@ namespace Slang List<IRInst*> existentialArgs; for( UInt ii = 0; ii < existentialArgCount; ++ii ) { - existentialArgs.Add(bindExistentials->getExistentialArg(ii)); + existentialArgs.add(bindExistentials->getExistentialArg(ii)); } return builder->getBindExistentialsType( baseElementType, existentialArgCount, - existentialArgs.Buffer()); + existentialArgs.getBuffer()); } } @@ -1862,12 +1862,12 @@ namespace Slang List<IRInst*> slotArgs; for( UInt ii = 0; ii < slotArgCount; ++ii ) { - slotArgs.Add(slotArgUses[ii].get()); + slotArgs.add(slotArgUses[ii].get()); } return getBindExistentialsType( baseType, slotArgCount, - slotArgs.Buffer()); + slotArgs.getBuffer()); } @@ -3069,7 +3069,7 @@ namespace Slang // Allow an empty nam // Special case a name that is the empty string, just in case. - if(name.Length() == 0) + if(name.getLength() == 0) { sb.append('_'); } @@ -3766,7 +3766,7 @@ namespace Slang dumpInst(&context, globalVal); - writer->write(sb.Buffer(), sb.Length()); + writer->write(sb.getBuffer(), sb.getLength()); writer->flush(); } @@ -3780,7 +3780,7 @@ namespace Slang void dumpIR(IRModule* module, ISlangWriter* writer, IRDumpMode mode) { String ir = getSlangIRAssembly(module, mode); - writer->write(ir.Buffer(), ir.Length()); + writer->write(ir.getBuffer(), ir.getLength()); writer->flush(); } diff --git a/source/slang/legalize-types.cpp b/source/slang/legalize-types.cpp index 995b797e4..64dafb938 100644 --- a/source/slang/legalize-types.cpp +++ b/source/slang/legalize-types.cpp @@ -22,7 +22,7 @@ LegalType LegalType::implicitDeref( LegalType LegalType::tuple( RefPtr<TuplePseudoType> tupleType) { - SLANG_ASSERT(tupleType->elements.Count()); + SLANG_ASSERT(tupleType->elements.getCount()); LegalType result; result.flavor = Flavor::tuple; @@ -363,7 +363,7 @@ struct TupleTypeBuilder SLANG_UNEXPECTED("unexpected ordinary field type"); } } - ordinaryElements.Add(ordinaryElement); + ordinaryElements.add(ordinaryElement); if (specialType.flavor != LegalType::Flavor::none) { @@ -374,11 +374,11 @@ struct TupleTypeBuilder TuplePseudoType::Element specialElement; specialElement.key = fieldKey; specialElement.type = specialType; - specialElements.Add(specialElement); + specialElements.add(specialElement); } pairElement.type = LegalType::pair(ordinaryType, specialType, elementPairInfo); - pairElements.Add(pairElement); + pairElements.add(pairElement); } // Add a field to the (pseudo-)type we are building @@ -452,7 +452,7 @@ struct TupleTypeBuilder // collide. // // (Also, the original type wasn't legal - that was the whole point...) - context->replacedInstructions.Add(originalStructType); + context->replacedInstructions.add(originalStructType); for(auto ee : ordinaryElements) { @@ -681,7 +681,7 @@ LegalType createLegalUniformBufferTypeForResources( newElement.key = ee.key; newElement.type = LegalType::implicitDeref(ee.type); - bufferPseudoTupleType->elements.Add(newElement); + bufferPseudoTupleType->elements.add(newElement); } return LegalType::tuple(bufferPseudoTupleType); @@ -808,7 +808,7 @@ LegalElementWrapping declareStructFields( TupleLegalElementWrappingObj::Element element; element.key = ee.key; element.field = declareStructFields(context, structType, ee.type); - obj->elements.Add(element); + obj->elements.add(element); } return LegalElementWrapping::makeTuple(obj); } @@ -952,7 +952,7 @@ static LegalType createLegalPtrType( op, ee.type); - ptrPseudoTupleType->elements.Add(newElement); + ptrPseudoTupleType->elements.add(newElement); } return LegalType::tuple(ptrPseudoTupleType); @@ -1072,7 +1072,7 @@ static LegalType wrapLegalType( ordinaryWrapper, specialWrapper); - resultTupleType->elements.Add(element); + resultTupleType->elements.add(element); } return LegalType::tuple(resultTupleType); diff --git a/source/slang/lexer.cpp b/source/slang/lexer.cpp index b6745b15f..8cb9fa5ee 100644 --- a/source/slang/lexer.cpp +++ b/source/slang/lexer.cpp @@ -19,15 +19,15 @@ namespace Slang Token* TokenList::begin() const { - SLANG_ASSERT(mTokens.Count()); + SLANG_ASSERT(mTokens.getCount()); return &mTokens[0]; } Token* TokenList::end() const { - SLANG_ASSERT(mTokens.Count()); - SLANG_ASSERT(mTokens[mTokens.Count()-1].type == TokenType::EndOfFile); - return &mTokens[mTokens.Count() - 1]; + SLANG_ASSERT(mTokens.getCount()); + SLANG_ASSERT(mTokens[mTokens.getCount()-1].type == TokenType::EndOfFile); + return &mTokens[mTokens.getCount() - 1]; } TokenSpan::TokenSpan() @@ -1325,7 +1325,7 @@ namespace Slang for(;;) { Token token = lexToken(); - tokenList.mTokens.Add(token); + tokenList.mTokens.add(token); if(token.type == TokenType::EndOfFile) return tokenList; diff --git a/source/slang/lookup.cpp b/source/slang/lookup.cpp index 2c822eb15..fe535d6e7 100644 --- a/source/slang/lookup.cpp +++ b/source/slang/lookup.cpp @@ -42,7 +42,7 @@ void buildMemberDictionary(ContainerDecl* decl) return; decl->memberDictionary.Clear(); - decl->transparentMembers.Clear(); + decl->transparentMembers.clear(); // are we a generic? GenericDecl* genericDecl = as<GenericDecl>(decl); @@ -56,7 +56,7 @@ void buildMemberDictionary(ContainerDecl* decl) { TransparentMemberInfo info; info.decl = m.Ptr(); - decl->transparentMembers.Add(info); + decl->transparentMembers.add(info); } // Ignore members with no name @@ -121,13 +121,13 @@ void AddToLookupResult( else if (!result.isOverloaded()) { // We are about to make this overloaded - result.items.Add(result.item); - result.items.Add(item); + result.items.add(result.item); + result.items.add(item); } else { // The result was already overloaded, so we pile on - result.items.Add(item); + result.items.add(item); } } diff --git a/source/slang/lower-to-ir.cpp b/source/slang/lower-to-ir.cpp index 0864d4bfe..2e9915669 100644 --- a/source/slang/lower-to-ir.cpp +++ b/source/slang/lower-to-ir.cpp @@ -677,9 +677,9 @@ LoweredValInfo emitCallToDeclRef( RefPtr<BoundSubscriptInfo> boundSubscript = new BoundSubscriptInfo(); boundSubscript->declRef = subscriptDeclRef; boundSubscript->type = type; - boundSubscript->args.AddRange(args, argCount); + boundSubscript->args.addRange(args, argCount); - context->shared->extValues.Add(boundSubscript); + context->shared->extValues.add(boundSubscript); return LoweredValInfo::boundSubscript(boundSubscript); } @@ -769,9 +769,9 @@ LoweredValInfo emitCallToDeclRef( List<IRType*> argTypes; for(UInt ii = 0; ii < argCount; ++ii) { - argTypes.Add(args[ii]->getDataType()); + argTypes.add(args[ii]->getDataType()); } - funcType = builder->getFuncType(argCount, argTypes.Buffer(), type); + funcType = builder->getFuncType(argCount, argTypes.getBuffer(), type); } LoweredValInfo funcVal = emitDeclRef(context, funcDeclRef, funcType); return emitCallToVal(context, type, funcVal, argCount, args); @@ -784,7 +784,7 @@ LoweredValInfo emitCallToDeclRef( IRType* funcType, List<IRInst*> const& args) { - return emitCallToDeclRef(context, type, funcDeclRef, funcType, args.Count(), args.Buffer()); + return emitCallToDeclRef(context, type, funcDeclRef, funcType, args.getCount(), args.getBuffer()); } IRInst* getFieldKey( @@ -826,7 +826,7 @@ LoweredValInfo extractField( boundMemberInfo->base = base; boundMemberInfo->declRef = field; - context->shared->extValues.Add(boundMemberInfo); + context->shared->extValues.add(boundMemberInfo); return LoweredValInfo::boundMember(boundMemberInfo); } break; @@ -1156,12 +1156,12 @@ struct ValLoweringVisitor : ValVisitor<ValLoweringVisitor, LoweredValInfo, Lower // We can turn each of those per-case witnesses into a witness // table value: // - auto caseCount = val->caseWitnesses.Count(); + auto caseCount = val->caseWitnesses.getCount(); List<IRInst*> caseWitnessTables; for( auto caseWitness : val->caseWitnesses ) { auto caseWitnessTable = lowerSimpleVal(context, caseWitness); - caseWitnessTables.Add(caseWitnessTable); + caseWitnessTables.add(caseWitnessTable); } // Now we need to synthesize a witness table for the tagged union @@ -1244,7 +1244,7 @@ struct ValLoweringVisitor : ValVisitor<ValLoweringVisitor, LoweredValInfo, Lower auto irThisParam = subBuilder->emitParam(irThisType); List<IRType*> irParamTypes; - irParamTypes.Add(irThisType); + irParamTypes.add(irThisType); // Create the remaining parameters of the callable, // using a decl-ref specialized to the tagged union @@ -1262,8 +1262,8 @@ struct ValLoweringVisitor : ValVisitor<ValLoweringVisitor, LoweredValInfo, Lower auto irParamType = lowerType(context, GetType(paramDeclRef)); auto irParam = subBuilder->emitParam(irParamType); - irParams.Add(irParam); - irParamTypes.Add(irParamType); + irParams.add(irParam); + irParamTypes.add(irParamType); } auto irResultType = lowerType(context, GetResultType(callableDeclRef)); @@ -1286,7 +1286,7 @@ struct ValLoweringVisitor : ValVisitor<ValLoweringVisitor, LoweredValInfo, Lower IRBlock* defaultLabel = nullptr; - for( UInt ii = 0; ii < caseCount; ++ii ) + for( Index ii = 0; ii < caseCount; ++ii ) { auto caseTag = subBuilder->getIntValue(irTagVal->getDataType(), ii); @@ -1296,8 +1296,8 @@ struct ValLoweringVisitor : ValVisitor<ValLoweringVisitor, LoweredValInfo, Lower if(!defaultLabel) defaultLabel = caseLabel; - switchCaseOperands.Add(caseTag); - switchCaseOperands.Add(caseLabel); + switchCaseOperands.add(caseTag); + switchCaseOperands.add(caseLabel); subBuilder->setInsertInto(caseLabel); @@ -1332,7 +1332,7 @@ struct ValLoweringVisitor : ValVisitor<ValLoweringVisitor, LoweredValInfo, Lower auto caseThisArg = subBuilder->emitExtractTaggedUnionPayload( caseThisType, irThisParam, caseTag); - caseArgs.Add(caseThisArg); + caseArgs.add(caseThisArg); // The remaining arguments to the call will just be forwarded from // the parameters of the wrapper function. @@ -1343,7 +1343,7 @@ struct ValLoweringVisitor : ValVisitor<ValLoweringVisitor, LoweredValInfo, Lower // for( auto param : irParams ) { - caseArgs.Add(param); + caseArgs.add(param); } auto caseCall = subBuilder->emitCallInst(caseResultType, caseFunc, caseArgs); @@ -1375,8 +1375,8 @@ struct ValLoweringVisitor : ValVisitor<ValLoweringVisitor, LoweredValInfo, Lower irTagVal, // value to `switch` on invalidLabel, // `break` label (block after the `switch` statement ends) defaultLabel, // `default` label (where to go if no `case` matches) - switchCaseOperands.Count(), - switchCaseOperands.Buffer()); + switchCaseOperands.getCount(), + switchCaseOperands.getBuffer()); } else { @@ -1410,11 +1410,11 @@ struct ValLoweringVisitor : ValVisitor<ValLoweringVisitor, LoweredValInfo, Lower List<IRType*> paramTypes; for (UInt pp = 0; pp < paramCount; ++pp) { - paramTypes.Add(lowerType(context, type->getParamType(pp))); + paramTypes.add(lowerType(context, type->getParamType(pp))); } return getBuilder()->getFuncType( paramCount, - paramTypes.Buffer(), + paramTypes.getBuffer(), resultType); } @@ -1592,7 +1592,7 @@ struct ValLoweringVisitor : ValVisitor<ValLoweringVisitor, LoweredValInfo, Lower for(auto caseType : type->caseTypes) { auto irCaseType = lowerType(context, caseType); - irCaseTypes.Add(irCaseType); + irCaseTypes.add(irCaseType); } auto irType = getBuilder()->getTaggedUnionType(irCaseTypes); @@ -1728,7 +1728,7 @@ static String getNameForNameHint( // or with an empty name if(!leafName) return String(); - if(leafName->text.Length() == 0) + if(leafName->text.getLength() == 0) return String(); @@ -1773,7 +1773,7 @@ static String getNameForNameHint( } auto parentName = getNameForNameHint(context, parentDecl); - if(parentName.Length() == 0) + if(parentName.getLength() == 0) { return leafName->text; } @@ -1797,7 +1797,7 @@ static void addNameHint( Decl* decl) { String name = getNameForNameHint(context, decl); - if(name.Length() == 0) + if(name.getLength() == 0) return; context->irBuilder->addNameHintDecoration(inst, name.getUnownedSlice()); } @@ -1846,7 +1846,7 @@ void addArgs( case LoweredValInfo::Flavor::SwizzledLValue: case LoweredValInfo::Flavor::BoundSubscript: case LoweredValInfo::Flavor::BoundMember: - args.Add(getSimpleVal(context, argInfo)); + args.add(getSimpleVal(context, argInfo)); break; default: @@ -2070,10 +2070,10 @@ struct ExprLoweringVisitorBase : ExprVisitor<Derived, LoweredValInfo> List<IRInst*> args; for(UInt ee = 0; ee < elementCount; ++ee) { - args.Add(irDefaultValue); + args.add(irDefaultValue); } return LoweredValInfo::simple( - getBuilder()->emitMakeVector(irType, args.Count(), args.Buffer())); + getBuilder()->emitMakeVector(irType, args.getCount(), args.getBuffer())); } else if (auto matrixType = as<MatrixExpressionType>(type)) { @@ -2086,10 +2086,10 @@ struct ExprLoweringVisitorBase : ExprVisitor<Derived, LoweredValInfo> List<IRInst*> args; for(UInt rr = 0; rr < rowCount; ++rr) { - args.Add(irDefaultValue); + args.add(irDefaultValue); } return LoweredValInfo::simple( - getBuilder()->emitMakeMatrix(irType, args.Count(), args.Buffer())); + getBuilder()->emitMakeMatrix(irType, args.getCount(), args.getBuffer())); } else if (auto arrayType = as<ArrayExpressionType>(type)) { @@ -2100,11 +2100,11 @@ struct ExprLoweringVisitorBase : ExprVisitor<Derived, LoweredValInfo> List<IRInst*> args; for(UInt ee = 0; ee < elementCount; ++ee) { - args.Add(irDefaultElement); + args.add(irDefaultElement); } return LoweredValInfo::simple( - getBuilder()->emitMakeArray(irType, args.Count(), args.Buffer())); + getBuilder()->emitMakeArray(irType, args.getCount(), args.getBuffer())); } else if (auto declRefType = as<DeclRefType>(type)) { @@ -2118,11 +2118,11 @@ struct ExprLoweringVisitorBase : ExprVisitor<Derived, LoweredValInfo> continue; auto irFieldVal = getSimpleVal(context, getDefaultVal(ff)); - args.Add(irFieldVal); + args.add(irFieldVal); } return LoweredValInfo::simple( - getBuilder()->emitMakeStruct(irType, args.Count(), args.Buffer())); + getBuilder()->emitMakeStruct(irType, args.getCount(), args.getBuffer())); } } @@ -2149,7 +2149,7 @@ struct ExprLoweringVisitorBase : ExprVisitor<Derived, LoweredValInfo> IRType* irType = lowerType(context, type); List<IRInst*> args; - UInt argCount = expr->args.Count(); + UInt argCount = expr->args.getCount(); // If the initializer list was empty, then the user was // asking for default initialization, which should apply @@ -2170,19 +2170,19 @@ struct ExprLoweringVisitorBase : ExprVisitor<Derived, LoweredValInfo> { auto argExpr = expr->args[ee]; LoweredValInfo argVal = lowerRValueExpr(context, argExpr); - args.Add(getSimpleVal(context, argVal)); + args.add(getSimpleVal(context, argVal)); } if(elementCount > argCount) { auto irDefaultValue = getSimpleVal(context, getDefaultVal(arrayType->baseType)); for(UInt ee = argCount; ee < elementCount; ++ee) { - args.Add(irDefaultValue); + args.add(irDefaultValue); } } return LoweredValInfo::simple( - getBuilder()->emitMakeArray(irType, args.Count(), args.Buffer())); + getBuilder()->emitMakeArray(irType, args.getCount(), args.getBuffer())); } else if (auto vectorType = as<VectorExpressionType>(type)) { @@ -2192,19 +2192,19 @@ struct ExprLoweringVisitorBase : ExprVisitor<Derived, LoweredValInfo> { auto argExpr = expr->args[ee]; LoweredValInfo argVal = lowerRValueExpr(context, argExpr); - args.Add(getSimpleVal(context, argVal)); + args.add(getSimpleVal(context, argVal)); } if(elementCount > argCount) { auto irDefaultValue = getSimpleVal(context, getDefaultVal(vectorType->elementType)); for(UInt ee = argCount; ee < elementCount; ++ee) { - args.Add(irDefaultValue); + args.add(irDefaultValue); } } return LoweredValInfo::simple( - getBuilder()->emitMakeVector(irType, args.Count(), args.Buffer())); + getBuilder()->emitMakeVector(irType, args.getCount(), args.getBuffer())); } else if (auto matrixType = as<MatrixExpressionType>(type)) { @@ -2214,7 +2214,7 @@ struct ExprLoweringVisitorBase : ExprVisitor<Derived, LoweredValInfo> { auto argExpr = expr->args[rr]; LoweredValInfo argVal = lowerRValueExpr(context, argExpr); - args.Add(getSimpleVal(context, argVal)); + args.add(getSimpleVal(context, argVal)); } if(rowCount > argCount) { @@ -2223,12 +2223,12 @@ struct ExprLoweringVisitorBase : ExprVisitor<Derived, LoweredValInfo> for(UInt rr = argCount; rr < rowCount; ++rr) { - args.Add(irDefaultValue); + args.add(irDefaultValue); } } return LoweredValInfo::simple( - getBuilder()->emitMakeMatrix(irType, args.Count(), args.Buffer())); + getBuilder()->emitMakeMatrix(irType, args.getCount(), args.getBuffer())); } else if (auto declRefType = as<DeclRefType>(type)) { @@ -2246,17 +2246,17 @@ struct ExprLoweringVisitorBase : ExprVisitor<Derived, LoweredValInfo> { auto argExpr = expr->args[argIndex]; LoweredValInfo argVal = lowerRValueExpr(context, argExpr); - args.Add(getSimpleVal(context, argVal)); + args.add(getSimpleVal(context, argVal)); } else { auto irDefaultValue = getSimpleVal(context, getDefaultVal(ff)); - args.Add(irDefaultValue); + args.add(irDefaultValue); } } return LoweredValInfo::simple( - getBuilder()->emitMakeStruct(irType, args.Count(), args.Buffer())); + getBuilder()->emitMakeStruct(irType, args.getCount(), args.getBuffer())); } } @@ -2315,7 +2315,7 @@ struct ExprLoweringVisitorBase : ExprVisitor<Derived, LoweredValInfo> List<IRInst*>* ioArgs, List<OutArgumentFixup>* ioFixups) { - UInt argCount = expr->Arguments.Count(); + UInt argCount = expr->Arguments.getCount(); UInt argCounter = 0; for (auto paramDeclRef : getMembersOfType<ParamDecl>(funcDeclRef)) { @@ -2370,7 +2370,7 @@ struct ExprLoweringVisitorBase : ExprVisitor<Derived, LoweredValInfo> // pass in the actual pointer. // IRInst* argPtr = getAddress(context, loweredArg, argExpr->loc); - (*ioArgs).Add(argPtr); + (*ioArgs).add(argPtr); } else if (paramDecl->HasModifier<OutModifier>() || paramDecl->HasModifier<InOutModifier>()) @@ -2414,7 +2414,7 @@ struct ExprLoweringVisitorBase : ExprVisitor<Derived, LoweredValInfo> // Now we can pass the address of the temporary variable // to the callee as the actual argument for the `in out` SLANG_ASSERT(tempVar.flavor == LoweredValInfo::Flavor::Ptr); - (*ioArgs).Add(tempVar.val); + (*ioArgs).add(tempVar.val); // Finally, after the call we will need // to copy in the other direction: from our @@ -2423,7 +2423,7 @@ struct ExprLoweringVisitorBase : ExprVisitor<Derived, LoweredValInfo> fixup.src = tempVar; fixup.dst = loweredArg; - (*ioFixups).Add(fixup); + (*ioFixups).add(fixup); } else @@ -2823,7 +2823,7 @@ struct LValueExprLoweringVisitor : ExprLoweringVisitorBase<LValueExprLoweringVis } } - context->shared->extValues.Add(swizzledLValue); + context->shared->extValues.add(swizzledLValue); return LoweredValInfo::swizzledLValue(swizzledLValue); } }; @@ -3517,8 +3517,8 @@ struct StmtLoweringVisitor : StmtVisitor<StmtLoweringVisitor> auto label = getLabelForCase(info); // Add this `case` to the list for the enclosing `switch`. - info->cases.Add(caseVal); - info->cases.Add(label); + info->cases.add(caseVal); + info->cases.add(label); } else if(auto defaultStmt = as<DefaultStmt>(stmt)) { @@ -3655,8 +3655,8 @@ struct StmtLoweringVisitor : StmtVisitor<StmtLoweringVisitor> conditionVal, breakLabel, defaultLabel, - info.cases.Count(), - info.cases.Buffer()); + info.cases.getCount(), + info.cases.getBuffer()); // Finally we insert the label that a `break` will jump to // (and that control flow will fall through to otherwise). @@ -3795,7 +3795,7 @@ LoweredValInfo tryGetAddress( auto newBase = tryGetAddress(context, originalBase, TryGetAddressMode::Aggressive); RefPtr<SwizzledLValueInfo> newSwizzleInfo = new SwizzledLValueInfo(); - context->shared->extValues.Add(newSwizzleInfo); + context->shared->extValues.add(newSwizzleInfo); newSwizzleInfo->base = newBase; newSwizzleInfo->type = originalSwizzleInfo->type; @@ -4561,11 +4561,11 @@ struct DeclLoweringVisitor : DeclVisitor<DeclLoweringVisitor, LoweredValInfo> { if (auto typeParamDecl = as<GenericTypeParamDecl>(member)) { - genericArgs.Add(getSimpleVal(context, ensureDecl(context, typeParamDecl))); + genericArgs.add(getSimpleVal(context, ensureDecl(context, typeParamDecl))); } else if (auto valDecl = as<GenericValueParamDecl>(member)) { - genericArgs.Add(getSimpleVal(context, ensureDecl(context, valDecl))); + genericArgs.add(getSimpleVal(context, ensureDecl(context, valDecl))); } } // Then we emit constraint parameters, again in @@ -4574,11 +4574,11 @@ struct DeclLoweringVisitor : DeclVisitor<DeclLoweringVisitor, LoweredValInfo> { if (auto constraintDecl = as<GenericTypeConstraintDecl>(member)) { - genericArgs.Add(getSimpleVal(context, ensureDecl(context, constraintDecl))); + genericArgs.add(getSimpleVal(context, ensureDecl(context, constraintDecl))); } } - return builder->emitSpecializeInst(type, specialiedOuterVal, genericArgs.Count(), genericArgs.Buffer()); + return builder->emitSpecializeInst(type, specialiedOuterVal, genericArgs.getCount(), genericArgs.getBuffer()); } IRInst* defaultSpecializeOuterGenerics( @@ -5239,7 +5239,7 @@ struct DeclLoweringVisitor : DeclVisitor<DeclLoweringVisitor, LoweredValInfo> info.direction = direction; info.isThisParam = true; - ioParameterLists->params.Add(info); + ioParameterLists->params.add(info); } void addThisParameter( ParameterDirection direction, @@ -5321,7 +5321,7 @@ struct DeclLoweringVisitor : DeclVisitor<DeclLoweringVisitor, LoweredValInfo> { for( auto paramDecl : callableDecl->GetParameters() ) { - ioParameterLists->params.Add(getParameterInfo(paramDecl)); + ioParameterLists->params.add(getParameterInfo(paramDecl)); } } } @@ -5588,7 +5588,7 @@ struct DeclLoweringVisitor : DeclVisitor<DeclLoweringVisitor, LoweredValInfo> irParamType = maybeGetConstExprType(irParamType, paramInfo.decl); } - paramTypes.Add(irParamType); + paramTypes.add(irParamType); } auto irResultType = lowerType(subContext, declForReturnType->ReturnType); @@ -5601,7 +5601,7 @@ struct DeclLoweringVisitor : DeclVisitor<DeclLoweringVisitor, LoweredValInfo> // it as a parameter. // IRType* irParamType = irResultType; - paramTypes.Add(irParamType); + paramTypes.add(irParamType); // Instead, a setter always returns `void` // @@ -5616,8 +5616,8 @@ struct DeclLoweringVisitor : DeclVisitor<DeclLoweringVisitor, LoweredValInfo> } auto irFuncType = subBuilder->getFuncType( - paramTypes.Count(), - paramTypes.Buffer(), + paramTypes.getCount(), + paramTypes.getBuffer(), irResultType); irFunc->setFullType(irFuncType); @@ -6090,7 +6090,7 @@ LoweredValInfo emitDeclRef( { auto irArgVal = lowerSimpleVal(context, argVal); SLANG_ASSERT(irArgVal); - irArgs.Add(irArgVal); + irArgs.add(irArgVal); } // Once we have both the generic and its arguments, @@ -6099,8 +6099,8 @@ LoweredValInfo emitDeclRef( auto irSpecializedVal = context->irBuilder->emitSpecializeInst( type, irGenericVal, - irArgs.Count(), - irArgs.Buffer()); + irArgs.getCount(), + irArgs.getBuffer()); return LoweredValInfo::simple(irSpecializedVal); } @@ -6226,18 +6226,18 @@ static void lowerProgramEntryPointToIR( if( existentialTypeArgCount ) { List<IRInst*> existentialSlotArgs; - for( UInt ii = 0; ii < existentialTypeArgCount; ++ii ) + for( Index ii = 0; ii < existentialTypeArgCount; ++ii ) { auto arg = entryPoint->getExistentialTypeArg(ii); auto irArgType = lowerType(context, arg.type); auto irWitnessTable = lowerSimpleVal(context, arg.witness); - existentialSlotArgs.Add(irArgType); - existentialSlotArgs.Add(irWitnessTable); + existentialSlotArgs.add(irArgType); + existentialSlotArgs.add(irWitnessTable); } - builder->addBindExistentialSlotsDecoration(loweredEntryPointFunc, existentialSlotArgs.Count(), existentialSlotArgs.Buffer()); + builder->addBindExistentialSlotsDecoration(loweredEntryPointFunc, existentialSlotArgs.getCount(), existentialSlotArgs.getBuffer()); } @@ -6456,18 +6456,18 @@ RefPtr<IRModule> generateIRForProgram( if( existentialTypeArgCount ) { List<IRInst*> existentialSlotArgs; - for( UInt ii = 0; ii < existentialTypeArgCount; ++ii ) + for( Index ii = 0; ii < existentialTypeArgCount; ++ii ) { auto arg = program->getExistentialTypeArg(ii); auto irArgType = lowerType(context, arg.type); auto irWitnessTable = lowerSimpleVal(context, arg.witness); - existentialSlotArgs.Add(irArgType); - existentialSlotArgs.Add(irWitnessTable); + existentialSlotArgs.add(irArgType); + existentialSlotArgs.add(irWitnessTable); } - builder->emitBindGlobalExistentialSlots(existentialSlotArgs.Count(), existentialSlotArgs.Buffer()); + builder->emitBindGlobalExistentialSlots(existentialSlotArgs.getCount(), existentialSlotArgs.getBuffer()); } diff --git a/source/slang/mangle.cpp b/source/slang/mangle.cpp index 61fa709b1..2ed9cfea6 100644 --- a/source/slang/mangle.cpp +++ b/source/slang/mangle.cpp @@ -46,7 +46,7 @@ namespace Slang // We prefix the string with its byte length, so that // decoding doesn't have to worry about finding a terminator. - UInt length = str.Length(); + Index length = str.getLength(); emit(context, length); context->sb.append(str); } @@ -279,7 +279,7 @@ namespace Slang { // This is the case where we *do* have substitutions. emitRaw(context, "G"); - UInt genericArgCount = subst->args.Count(); + UInt genericArgCount = subst->args.getCount(); emit(context, genericArgCount); for( auto aa : subst->args ) { diff --git a/source/slang/options.cpp b/source/slang/options.cpp index 6474f2afe..a5cdfef44 100644 --- a/source/slang/options.cpp +++ b/source/slang/options.cpp @@ -173,7 +173,7 @@ struct OptionsParser SlangSourceLanguage language, Stage impliedStage) { - auto translationUnitIndex = rawTranslationUnits.Count(); + auto translationUnitIndex = rawTranslationUnits.getCount(); auto translationUnitID = spAddTranslationUnit(compileRequest, language, nullptr); // As a sanity check: the API should be returning the same translation @@ -181,14 +181,14 @@ struct OptionsParser // be broken if we decide to support a mix of translation units specified // via API, and ones specified via command-line arguments. // - SLANG_RELEASE_ASSERT(UInt(translationUnitID) == translationUnitIndex); + SLANG_RELEASE_ASSERT(Index(translationUnitID) == translationUnitIndex); RawTranslationUnit rawTranslationUnit; rawTranslationUnit.sourceLanguage = language; rawTranslationUnit.translationUnitID = translationUnitID; rawTranslationUnit.impliedStage = impliedStage; - rawTranslationUnits.Add(rawTranslationUnit); + rawTranslationUnits.add(rawTranslationUnit); return int(translationUnitIndex); } @@ -247,7 +247,7 @@ struct OptionsParser for (int i = 0; i < SLANG_COUNT_OF(entries); ++i) { const Entry& entry = entries[i]; - if (path.EndsWith(entry.ext)) + if (path.endsWith(entry.ext)) { return entry.profileId; } @@ -283,7 +283,7 @@ struct OptionsParser for (int i = 0; i < SLANG_COUNT_OF(entries); ++i) { const Entry& entry = entries[i]; - if (path.EndsWith(entry.ext)) + if (path.endsWith(entry.ext)) { outImpliedStage = Stage(entry.impliedStage); return entry.sourceLanguage; @@ -301,7 +301,7 @@ struct OptionsParser // how we should handle it. String path = String(inPath); - if( path.EndsWith(".slang") ) + if( path.endsWith(".slang") ) { // Plain old slang code addInputSlangPath(path); @@ -329,7 +329,7 @@ struct OptionsParser RawOutput rawOutput; rawOutput.path = path; rawOutput.impliedFormat = impliedFormat; - rawOutputs.Add(rawOutput); + rawOutputs.add(rawOutput); } void addOutputPath(char const* inPath) @@ -338,7 +338,7 @@ struct OptionsParser if (!inPath) {} #define CASE(EXT, TARGET) \ - else if(path.EndsWith(EXT)) do { addOutputPath(path, CodeGenTarget(SLANG_##TARGET)); } while(0) + else if(path.endsWith(EXT)) do { addOutputPath(path, CodeGenTarget(SLANG_##TARGET)); } while(0) CASE(".hlsl", HLSL); CASE(".fx", HLSL); @@ -362,7 +362,7 @@ struct OptionsParser #undef CASE - else if (path.EndsWith(".slang-module")) + else if (path.endsWith(".slang-module")) { spSetOutputContainerFormat(compileRequest, SLANG_CONTAINER_FORMAT_SLANG_MODULE); requestImpl->containerOutputPath = path; @@ -377,7 +377,7 @@ struct OptionsParser RawEntryPoint* getCurrentEntryPoint() { - auto rawEntryPointCount = rawEntryPoints.Count(); + auto rawEntryPointCount = rawEntryPoints.getCount(); return rawEntryPointCount ? &rawEntryPoints[rawEntryPointCount-1] : &defaultEntryPoint; } @@ -396,7 +396,7 @@ struct OptionsParser RawTarget* getCurrentTarget() { - auto rawTargetCount = rawTargets.Count(); + auto rawTargetCount = rawTargets.getCount(); return rawTargetCount ? &rawTargets[rawTargetCount-1] : &defaultTarget; } @@ -510,7 +510,7 @@ struct OptionsParser RawTarget rawTarget; rawTarget.format = CodeGenTarget(format); - rawTargets.Add(rawTarget); + rawTargets.add(rawTarget); } // A "profile" can specify both a general capability level for // a target, and also (as a legacy/compatibility feature) a @@ -566,7 +566,7 @@ struct OptionsParser rawEntryPoint.name = name; rawEntryPoint.translationUnitIndex = currentTranslationUnitIndex; - rawEntryPoints.Add(rawEntryPoint); + rawEntryPoints.add(rawEntryPoint); } else if (argStr == "-pass-through") { @@ -808,15 +808,15 @@ struct OptionsParser // of the translation unit, then we assume they wanted to compile a single // entry point named `main`. // - if(rawEntryPoints.Count() == 0 - && rawTranslationUnits.Count() == 1 + if(rawEntryPoints.getCount() == 0 + && rawTranslationUnits.getCount() == 1 && (defaultEntryPoint.stage != Stage::Unknown || rawTranslationUnits[0].impliedStage != Stage::Unknown)) { RawEntryPoint entry; entry.name = "main"; entry.translationUnitIndex = 0; - rawEntryPoints.Add(entry); + rawEntryPoints.add(entry); } // If the user (manually or implicitly) specified only a single entry point, @@ -825,7 +825,7 @@ struct OptionsParser // to the "default" entry point, we should copy it over to the // explicit one. // - if( rawEntryPoints.Count() == 1 ) + if( rawEntryPoints.getCount() == 1 ) { if(defaultEntryPoint.stage != Stage::Unknown) { @@ -848,7 +848,7 @@ struct OptionsParser // if( defaultEntryPoint.stage != Stage::Unknown ) { - if( rawEntryPoints.Count() == 0 ) + if( rawEntryPoints.getCount() == 0 ) { sink->diagnose(SourceLoc(), Diagnostics::stageSpecificationIgnoredBecauseNoEntryPoints); } @@ -988,7 +988,7 @@ struct OptionsParser // If there was no explicit `-target` specified, then we will look // at the `-o` options to see what we can infer. // - if(rawTargets.Count() == 0) + if(rawTargets.getCount() == 0) { for(auto& rawOutput : rawOutputs) { @@ -1000,11 +1000,11 @@ struct OptionsParser int targetIndex = 0; if( !mapFormatToTargetIndex.TryGetValue(impliedFormat, targetIndex) ) { - targetIndex = (int) rawTargets.Count(); + targetIndex = (int) rawTargets.getCount(); RawTarget rawTarget; rawTarget.format = impliedFormat; - rawTargets.Add(rawTarget); + rawTargets.add(rawTarget); mapFormatToTargetIndex[impliedFormat] = targetIndex; } @@ -1019,7 +1019,7 @@ struct OptionsParser // is specified more than once (just because of the ambiguities // it will create). // - int targetCount = (int) rawTargets.Count(); + int targetCount = (int) rawTargets.getCount(); for(int targetIndex = 0; targetIndex < targetCount; ++targetIndex) { auto format = rawTargets[targetIndex].format; @@ -1039,7 +1039,7 @@ struct OptionsParser // because there were no output paths), but there was a profile specified, // then we can try to infer a target from the profile. // - if( rawTargets.Count() == 0 + if( rawTargets.getCount() == 0 && defaultTarget.profileVersion != ProfileVersion::Unknown && !defaultTarget.conflictingProfilesSet) { @@ -1085,14 +1085,14 @@ struct OptionsParser { RawTarget rawTarget; rawTarget.format = inferredFormat; - rawTargets.Add(rawTarget); + rawTargets.add(rawTarget); } } // Similar to the case for entry points, if there is a single target, // then we allow some of its options to come from the "default" // target state. - if(rawTargets.Count() == 1) + if(rawTargets.getCount() == 1) { if(defaultTarget.profileVersion != ProfileVersion::Unknown) { @@ -1114,7 +1114,7 @@ struct OptionsParser // if( defaultTarget.profileVersion != ProfileVersion::Unknown ) { - if( rawTargets.Count() == 0 ) + if( rawTargets.getCount() == 0 ) { // This should only happen if there were multiple `-profile` options, // so we didn't try to infer a target, or if the `-profile` option @@ -1130,7 +1130,7 @@ struct OptionsParser if( defaultTarget.targetFlags ) { - if( rawTargets.Count() == 0 ) + if( rawTargets.getCount() == 0 ) { sink->diagnose(SourceLoc(), Diagnostics::targetFlagsIgnoredBecauseNoTargets); } @@ -1142,7 +1142,7 @@ struct OptionsParser if( defaultTarget.floatingPointMode != FloatingPointMode::Default ) { - if( rawTargets.Count() == 0 ) + if( rawTargets.getCount() == 0 ) { sink->diagnose(SourceLoc(), Diagnostics::targetFlagsIgnoredBecauseNoTargets); } @@ -1204,7 +1204,7 @@ struct OptionsParser // If there is only a single entry point, then that is automatically // the entry point that should be associated with all outputs. // - if( rawEntryPoints.Count() == 1 ) + if( rawEntryPoints.getCount() == 1 ) { for( auto& rawOutput : rawOutputs ) { @@ -1215,7 +1215,7 @@ struct OptionsParser // Similarly, if there is only one target, then all outputs must // implicitly appertain to that target. // - if( rawTargets.Count() == 1 ) + if( rawTargets.getCount() == 1 ) { for( auto& rawOutput : rawOutputs ) { diff --git a/source/slang/parameter-binding.cpp b/source/slang/parameter-binding.cpp index 293a24338..bdb76a005 100644 --- a/source/slang/parameter-binding.cpp +++ b/source/slang/parameter-binding.cpp @@ -99,7 +99,7 @@ struct UsedRanges // using indices, because we may actually modify // the array as we go. // - Int rangeCount = ranges.Count(); + Int rangeCount = ranges.getCount(); for(Int rr = 0; rr < rangeCount; ++rr) { auto existingRange = ranges[rr]; @@ -161,7 +161,7 @@ struct UsedRanges prefix.begin = range.begin; prefix.end = existingRange.begin; prefix.parameter = range.parameter; - ranges.Add(prefix); + ranges.add(prefix); } // // Now we know that the interval `[range.begin, existingRange.begin)` @@ -195,14 +195,14 @@ struct UsedRanges // if(range.begin < range.end) { - ranges.Add(range); + ranges.add(range); } // Any ranges that got added along the way might not // be in the proper sorted order, so we'll need to // sort the array to restore our global invariant. // - ranges.Sort(); + ranges.sort(); // We end by returning an overlapping parameter that // we found along the way, if any. @@ -250,7 +250,7 @@ struct UsedRanges { UInt begin = 0; - UInt rangeCount = ranges.Count(); + UInt rangeCount = ranges.getCount(); for (UInt rr = 0; rr < rangeCount; ++rr) { // try to fit in before this range... @@ -584,7 +584,7 @@ static bool findLayoutArg( { if( modifier ) { - *outVal = (UInt) strtoull(String(modifier->valToken.Content).Buffer(), nullptr, 10); + *outVal = (UInt) strtoull(String(modifier->valToken.Content).getBuffer(), nullptr, 10); return true; } } @@ -671,8 +671,8 @@ static void collectGlobalGenericParameter( { RefPtr<GenericParamLayout> layout = new GenericParamLayout(); layout->decl = paramDecl; - layout->index = (int)context->shared->programLayout->globalGenericParams.Count(); - context->shared->programLayout->globalGenericParams.Add(layout); + layout->index = (int)context->shared->programLayout->globalGenericParams.getCount(); + context->shared->programLayout->globalGenericParams.add(layout); context->shared->programLayout->globalGenericParamsMap[layout->decl->getName()->text] = layout.Ptr(); } @@ -716,10 +716,10 @@ static void collectGlobalScopeParameter( // TODO: `ParameterInfo` should probably become `LayoutParamInfo`. // ParameterInfo* parameterInfo = new ParameterInfo(); - context->shared->parameters.Add(parameterInfo); + context->shared->parameters.add(parameterInfo); // Add the first variable declaration to the list of declarations for the parameter - parameterInfo->varLayouts.Add(varLayout); + parameterInfo->varLayouts.add(varLayout); // Add any additional variables to the list of declarations for( auto additionalVarDeclRef : shaderParamInfo.additionalParamDeclRefs ) @@ -739,7 +739,7 @@ static void collectGlobalScopeParameter( additionalVarLayout->typeLayout = typeLayout; additionalVarLayout->varDecl = additionalVarDeclRef; - parameterInfo->varLayouts.Add(additionalVarLayout); + parameterInfo->varLayouts.add(additionalVarLayout); } } @@ -1002,7 +1002,7 @@ void generateParameterBindings( RefPtr<ParameterInfo> parameterInfo) { // There must be at least one declaration for the parameter. - SLANG_RELEASE_ASSERT(parameterInfo->varLayouts.Count() != 0); + SLANG_RELEASE_ASSERT(parameterInfo->varLayouts.getCount() != 0); // Iterate over all declarations looking for explicit binding information. for( auto& varLayout : parameterInfo->varLayouts ) @@ -1246,8 +1246,8 @@ static void completeBindingsForParameter( // that earlier code has validated that the declarations // "match". - SLANG_RELEASE_ASSERT(parameterInfo->varLayouts.Count() != 0); - auto firstVarLayout = parameterInfo->varLayouts.First(); + SLANG_RELEASE_ASSERT(parameterInfo->varLayouts.getCount() != 0); + auto firstVarLayout = parameterInfo->varLayouts.getFirst(); completeBindingsForParameterImpl( context, @@ -1342,7 +1342,7 @@ SimpleSemanticInfo decomposeSimpleSemantic( // The name is everything before the digits String stringComposedName(composedName); - info.name = stringComposedName.SubString(0, indexLoc); + info.name = stringComposedName.subString(0, indexLoc); info.index = strtol(stringComposedName.begin() + indexLoc, nullptr, 10); } return info; @@ -1362,11 +1362,11 @@ static RefPtr<TypeLayout> processSimpleEntryPointParameter( auto semanticIndex = *state.ioSemanticIndex; String semanticName = optSemanticName ? *optSemanticName : ""; - String sn = semanticName.ToLower(); + String sn = semanticName.toLower(); RefPtr<TypeLayout> typeLayout; - if (sn.StartsWith("sv_") - || sn.StartsWith("nv_")) + if (sn.startsWith("sv_") + || sn.startsWith("nv_")) { // System-value semantic. @@ -1626,7 +1626,7 @@ static RefPtr<TypeLayout> processEntryPointVaryingParameter( // supposed to be case-insensitive and // upper-case is the dominant convention. String semanticName = *optSemanticName; - String sn = semanticName.ToUpper(); + String sn = semanticName.toUpper(); auto semanticIndex = *state.ioSemanticIndex; @@ -1720,7 +1720,7 @@ static RefPtr<TypeLayout> processEntryPointVaryingParameter( } } - structLayout->fields.Add(fieldVarLayout); + structLayout->fields.add(fieldVarLayout); structLayout->mapVarToLayout.Add(field.getDecl(), fieldVarLayout); } @@ -1883,7 +1883,7 @@ struct ScopeLayoutBuilder } } - m_structLayout->fields.Add(firstVarLayout); + m_structLayout->fields.add(firstVarLayout); if( parameterInfo ) { @@ -1934,8 +1934,8 @@ struct ScopeLayoutBuilder void addParameter( ParameterInfo* parameterInfo) { - SLANG_RELEASE_ASSERT(parameterInfo->varLayouts.Count() != 0); - auto firstVarLayout = parameterInfo->varLayouts.First(); + SLANG_RELEASE_ASSERT(parameterInfo->varLayouts.getCount() != 0); + auto firstVarLayout = parameterInfo->varLayouts.getFirst(); _addParameter(firstVarLayout, parameterInfo); } @@ -2024,7 +2024,7 @@ static void collectEntryPointParameters( // The entry point layout must be added to the output // program layout so that it can be accessed by reflection. // - context->shared->programLayout->entryPoints.Add(entryPointLayout); + context->shared->programLayout->entryPoints.add(entryPointLayout); // For the duration of our parameter collection work we will // establish this entry point as the current one in the context. @@ -2041,7 +2041,7 @@ static void collectEntryPointParameters( SLANG_ASSERT(taggedUnionType); auto substType = taggedUnionType->Substitute(typeSubst).as<Type>(); auto typeLayout = createTypeLayout(context->layoutContext, substType); - entryPointLayout->taggedUnionTypeLayouts.Add(typeLayout); + entryPointLayout->taggedUnionTypeLayouts.add(typeLayout); } // We are going to iterate over the entry-point parameters, @@ -2337,8 +2337,8 @@ RefPtr<ProgramLayout> generateParameterBindings( bool needDefaultConstantBuffer = false; for( auto& parameterInfo : sharedContext.parameters ) { - SLANG_RELEASE_ASSERT(parameterInfo->varLayouts.Count() != 0); - auto firstVarLayout = parameterInfo->varLayouts.First(); + SLANG_RELEASE_ASSERT(parameterInfo->varLayouts.getCount() != 0); + auto firstVarLayout = parameterInfo->varLayouts.getFirst(); // Does the field have any uniform data? if( firstVarLayout->typeLayout->FindResourceInfo(LayoutResourceKind::Uniform) ) @@ -2366,8 +2366,8 @@ RefPtr<ProgramLayout> generateParameterBindings( // for (auto& parameterInfo : sharedContext.parameters) { - SLANG_RELEASE_ASSERT(parameterInfo->varLayouts.Count() != 0); - auto firstVarLayout = parameterInfo->varLayouts.First(); + SLANG_RELEASE_ASSERT(parameterInfo->varLayouts.getCount() != 0); + auto firstVarLayout = parameterInfo->varLayouts.getFirst(); // For each parameter, we will look at each resource it consumes. // diff --git a/source/slang/parser.cpp b/source/slang/parser.cpp index a6063a2a9..825aea324 100644 --- a/source/slang/parser.cpp +++ b/source/slang/parser.cpp @@ -735,7 +735,7 @@ namespace Slang auto arg = parser->ParseArgExpr(); if (arg) { - modifier->args.Add(arg); + modifier->args.add(arg); } if (AdvanceIfMatch(parser, TokenType::RParent)) @@ -1075,7 +1075,7 @@ namespace Slang if (container) { member->ParentDecl = container.Ptr(); - container->Members.Add(member); + container->Members.add(member); container->memberDictionaryIsValid = false; } @@ -1597,13 +1597,13 @@ namespace Slang { group = new DeclGroup(); group->loc = startPosition; - group->decls.Add(decl); + group->decls.add(decl); decl = nullptr; } if( group ) { - group->decls.Add(newDecl); + group->decls.add(newDecl); } else { @@ -1662,10 +1662,10 @@ namespace Slang parser->ReadToken(TokenType::OpLess); parser->genericDepth++; // For now assume all generics have at least one argument - genericApp->Arguments.Add(ParseGenericArg(parser)); + genericApp->Arguments.add(ParseGenericArg(parser)); while (AdvanceIf(parser, TokenType::Comma)) { - genericApp->Arguments.Add(ParseGenericArg(parser)); + genericApp->Arguments.add(ParseGenericArg(parser)); } parser->genericDepth--; @@ -1778,7 +1778,7 @@ namespace Slang while(!AdvanceIfMatch(parser, TokenType::RParent)) { auto caseType = parser->ParseTypeExp(); - taggedUnionType->caseTypes.Add(caseType); + taggedUnionType->caseTypes.add(caseType); if(AdvanceIf(parser, TokenType::RParent)) break; @@ -2258,7 +2258,7 @@ namespace Slang bufferDataTypeExpr->name = bufferDataTypeDecl->nameAndLoc.name; bufferDataTypeExpr->scope = parser->currentScope.Ptr(); - // Construct a type exrpession to reference the type constructor + // Construct a type expression to reference the type constructor auto bufferWrapperTypeExpr = new VarExpr(); bufferWrapperTypeExpr->loc = bufferWrapperTypeNamePos; bufferWrapperTypeExpr->name = getName(parser, bufferWrapperTypeName); @@ -2272,11 +2272,11 @@ namespace Slang auto bufferVarTypeExpr = new GenericAppExpr(); bufferVarTypeExpr->loc = bufferVarDecl->loc; bufferVarTypeExpr->FunctionExpr = bufferWrapperTypeExpr; - bufferVarTypeExpr->Arguments.Add(bufferDataTypeExpr); + bufferVarTypeExpr->Arguments.add(bufferDataTypeExpr); bufferVarDecl->type.exp = bufferVarTypeExpr; - // Any semantics applied to the bufer declaration are taken as applying + // Any semantics applied to the buffer declaration are taken as applying // to the variable instead. ParseOptSemantics(parser, bufferVarDecl.Ptr()); @@ -2943,7 +2943,7 @@ namespace Slang } else if( auto declGroup = as<DeclGroup>(declBase) ) { - if( declGroup->decls.Count() == 1 ) + if( declGroup->decls.getCount() == 1 ) { return declGroup->decls[0]; } @@ -3340,14 +3340,14 @@ namespace Slang } else if (auto seqStmt = as<SeqStmt>(body)) { - seqStmt->stmts.Add(stmt); + seqStmt->stmts.add(stmt); } else { RefPtr<SeqStmt> newBody = new SeqStmt(); newBody->loc = blockStatement->loc; - newBody->stmts.Add(body); - newBody->stmts.Add(stmt); + newBody->stmts.add(body); + newBody->stmts.add(stmt); body = newBody; } @@ -3668,8 +3668,8 @@ namespace Slang RefPtr<InfixExpr> expr = new InfixExpr(); expr->loc = op->loc; expr->FunctionExpr = op; - expr->Arguments.Add(left); - expr->Arguments.Add(right); + expr->Arguments.add(left); + expr->Arguments.add(right); return expr; } @@ -3696,11 +3696,11 @@ namespace Slang select->loc = op->loc; select->FunctionExpr = op; - select->Arguments.Add(expr); + select->Arguments.add(expr); - select->Arguments.Add(parser->ParseExpression(opPrec)); + select->Arguments.add(parser->ParseExpression(opPrec)); parser->ReadToken(TokenType::Colon); - select->Arguments.Add(parser->ParseExpression(opPrec)); + select->Arguments.add(parser->ParseExpression(opPrec)); expr = select; continue; @@ -3855,7 +3855,7 @@ namespace Slang // // Proper disambiguation requires mixing up parsing // and semantic checking (which we should do eventually) - // but for now we will follow some hueristics. + // but for now we will follow some heuristics. case TokenType::LParent: { Token openParen = parser->ReadToken(TokenType::LParent); @@ -3868,7 +3868,7 @@ namespace Slang parser->ReadToken(TokenType::RParent); auto arg = parsePrefixExpr(parser); - tcexpr->Arguments.Add(arg); + tcexpr->Arguments.add(arg); return tcexpr; } @@ -3903,7 +3903,7 @@ namespace Slang auto expr = parser->ParseArgExpr(); if( expr ) { - initExpr->args.Add(expr); + initExpr->args.add(expr); } if(AdvanceIfMatch(parser, TokenType::RBrace)) @@ -4150,7 +4150,7 @@ namespace Slang RefPtr<OperatorExpr> postfixExpr = new PostfixExpr(); parser->FillPosition(postfixExpr.Ptr()); postfixExpr->FunctionExpr = parseOperator(parser); - postfixExpr->Arguments.Add(expr); + postfixExpr->Arguments.add(expr); expr = postfixExpr; } @@ -4184,7 +4184,7 @@ namespace Slang while (!parser->tokenReader.IsAtEnd()) { if (!parser->LookAheadToken(TokenType::RParent)) - invokeExpr->Arguments.Add(parser->ParseArgExpr()); + invokeExpr->Arguments.add(parser->ParseArgExpr()); else { break; @@ -4259,7 +4259,7 @@ namespace Slang RefPtr<PrefixExpr> prefixExpr = new PrefixExpr(); parser->FillPosition(prefixExpr.Ptr()); prefixExpr->FunctionExpr = parseOperator(parser); - prefixExpr->Arguments.Add(parsePrefixExpr(parser)); + prefixExpr->Arguments.add(parsePrefixExpr(parser)); return prefixExpr; } break; @@ -4566,7 +4566,7 @@ namespace Slang while( AdvanceIf(parser, TokenType::Comma) ) { auto operand = uint32_t(StringToInt(parser->ReadToken(TokenType::IntegerLiteral).Content)); - modifier->irOperands.Add(operand); + modifier->irOperands.add(operand); } parser->ReadToken(TokenType::RParent); diff --git a/source/slang/preprocessor.cpp b/source/slang/preprocessor.cpp index 103db7dcb..bf6f7b7ca 100644 --- a/source/slang/preprocessor.cpp +++ b/source/slang/preprocessor.cpp @@ -564,7 +564,7 @@ static void AddEndOfStreamToken( { Token token = PeekRawToken(preprocessor); token.type = TokenType::EndOfFile; - macro->tokens.mTokens.Add(token); + macro->tokens.mTokens.add(token); } static SimpleTokenInputStream* createSimpleInputStream( @@ -574,13 +574,13 @@ static SimpleTokenInputStream* createSimpleInputStream( SimpleTokenInputStream* inputStream = new SimpleTokenInputStream(); initializeInputStream(preprocessor, inputStream); - inputStream->lexedTokens.mTokens.Add(token); + inputStream->lexedTokens.mTokens.add(token); Token eofToken; eofToken.type = TokenType::EndOfFile; eofToken.loc = token.loc; eofToken.flags = TokenFlag::AfterWhitespace | TokenFlag::AtStartOfLine; - inputStream->lexedTokens.mTokens.Add(eofToken); + inputStream->lexedTokens.mTokens.add(eofToken); inputStream->tokenReader = TokenReader(inputStream->lexedTokens); @@ -659,7 +659,7 @@ static void MaybeBeginMacroExpansion( expansion->environment = &expansion->argumentEnvironment; // Try to read any arguments present. - UInt paramCount = macro->params.Count(); + UInt paramCount = macro->params.getCount(); UInt argIndex = 0; switch (PeekRawTokenType(preprocessor)) @@ -740,7 +740,7 @@ static void MaybeBeginMacroExpansion( } // Add the token and continue parsing. - arg->tokens.mTokens.Add(AdvanceRawToken(preprocessor)); + arg->tokens.mTokens.add(AdvanceRawToken(preprocessor)); } doneWithArgument: {} // We've parsed an argument and should move onto @@ -1586,7 +1586,7 @@ static SlangResult readFile( // auto linkage = context->preprocessor->linkage; auto fileSystemExt = linkage->getFileSystemExt(); - SLANG_RETURN_ON_FAIL(fileSystemExt->loadFile(path.Buffer(), outBlob)); + SLANG_RETURN_ON_FAIL(fileSystemExt->loadFile(path.getBuffer(), outBlob)); // If we are running the preprocessor as part of compiling a // specific module, then we must keep track of the file we've @@ -1732,7 +1732,7 @@ static void HandleDefineDirective(PreprocessorDirectiveContext* context) // are not allowed to be used as macros or parameters). // Add the parameter to the macro being deifned - macro->params.Add(paramToken); + macro->params.add(paramToken); // If we see `)` then we are done with arguments if (PeekRawTokenType(context) == TokenType::RParent) @@ -1755,12 +1755,12 @@ static void HandleDefineDirective(PreprocessorDirectiveContext* context) // Last token on line will be turned into a conceptual end-of-file // token for the sub-stream that the macro expands into. token.type = TokenType::EndOfFile; - macro->tokens.mTokens.Add(token); + macro->tokens.mTokens.add(token); break; } // In the ordinary case, we just add the token to the definition - macro->tokens.mTokens.Add(token); + macro->tokens.mTokens.add(token); } } @@ -1939,7 +1939,7 @@ static const PragmaDirective kUnknownPragmaDirective = { // Look up the `#pragma` directive with the given name. static PragmaDirective const* findPragmaDirective(String const& name) { - char const* nameStr = name.Buffer(); + char const* nameStr = name.getBuffer(); for (int ii = 0; kPragmaDirectives[ii].name; ++ii) { if (strcmp(kPragmaDirectives[ii].name, nameStr) != 0) @@ -2037,7 +2037,7 @@ static const PreprocessorDirective kInvalidDirective = { // Look up the directive with the given name. static PreprocessorDirective const* FindDirective(String const& name) { - char const* nameStr = name.Buffer(); + char const* nameStr = name.getBuffer(); for (int ii = 0; kDirectives[ii].name; ++ii) { if (strcmp(kDirectives[ii].name, nameStr) != 0) @@ -2236,7 +2236,7 @@ static TokenList ReadAllTokens( { Token token = ReadToken(preprocessor); - tokens.mTokens.Add(token); + tokens.mTokens.add(token); // Note: we include the EOF token in the list, // since that is expected by the `TokenList` type. diff --git a/source/slang/reflection.cpp b/source/slang/reflection.cpp index 9c33ca9d3..326a27854 100644 --- a/source/slang/reflection.cpp +++ b/source/slang/reflection.cpp @@ -137,13 +137,13 @@ SLANG_API char const* spReflectionUserAttribute_GetName(SlangReflectionUserAttri { auto userAttr = convert(attrib); if (!userAttr) return nullptr; - return userAttr->getName()->text.Buffer(); + return userAttr->getName()->text.getBuffer(); } SLANG_API unsigned int spReflectionUserAttribute_GetArgumentCount(SlangReflectionUserAttribute* attrib) { auto userAttr = convert(attrib); if (!userAttr) return 0; - return (unsigned int)userAttr->args.Count(); + return (unsigned int)userAttr->args.getCount(); } SlangReflectionType* spReflectionUserAttribute_GetArgumentType(SlangReflectionUserAttribute* attrib, unsigned int index) { @@ -155,7 +155,7 @@ SLANG_API SlangResult spReflectionUserAttribute_GetArgumentValueInt(SlangReflect { auto userAttr = convert(attrib); if (!userAttr) return SLANG_ERROR_INVALID_PARAMETER; - if (index >= userAttr->args.Count()) return SLANG_ERROR_INVALID_PARAMETER; + if (index >= (unsigned int)userAttr->args.getCount()) return SLANG_ERROR_INVALID_PARAMETER; RefPtr<RefObject> val; if (userAttr->intArgVals.TryGetValue(index, val)) { @@ -168,7 +168,7 @@ SLANG_API SlangResult spReflectionUserAttribute_GetArgumentValueFloat(SlangRefle { auto userAttr = convert(attrib); if (!userAttr) return SLANG_ERROR_INVALID_PARAMETER; - if (index >= userAttr->args.Count()) return SLANG_ERROR_INVALID_PARAMETER; + if (index >= (unsigned int)userAttr->args.getCount()) return SLANG_ERROR_INVALID_PARAMETER; if (auto cexpr = as<FloatingPointLiteralExpr>(userAttr->args[index])) { *rs = (float)cexpr->value; @@ -180,7 +180,7 @@ SLANG_API const char* spReflectionUserAttribute_GetArgumentValueString(SlangRefl { auto userAttr = convert(attrib); if (!userAttr) return nullptr; - if (index >= userAttr->args.Count()) return nullptr; + if (index >= (unsigned int)userAttr->args.getCount()) return nullptr; if (auto cexpr = as<StringLiteralExpr>(userAttr->args[index])) { if (bufLen) @@ -772,7 +772,7 @@ static SlangParameterCategory getParameterCategory( static SlangParameterCategory getParameterCategory( TypeLayout* typeLayout) { - auto resourceInfoCount = typeLayout->resourceInfos.Count(); + auto resourceInfoCount = typeLayout->resourceInfos.getCount(); if(resourceInfoCount == 1) { return getParameterCategory(typeLayout->resourceInfos[0].kind); @@ -790,7 +790,7 @@ static TypeLayout* maybeGetContainerLayout(TypeLayout* typeLayout) if (auto parameterGroupTypeLayout = as<ParameterGroupTypeLayout>(typeLayout)) { auto containerTypeLayout = parameterGroupTypeLayout->containerVarLayout->typeLayout; - if (containerTypeLayout->resourceInfos.Count() != 0) + if (containerTypeLayout->resourceInfos.getCount() != 0) { return containerTypeLayout; } @@ -816,7 +816,7 @@ SLANG_API unsigned spReflectionTypeLayout_GetCategoryCount(SlangReflectionTypeLa typeLayout = maybeGetContainerLayout(typeLayout); - return (unsigned) typeLayout->resourceInfos.Count(); + return (unsigned) typeLayout->resourceInfos.getCount(); } SLANG_API SlangParameterCategory spReflectionTypeLayout_GetCategoryByIndex(SlangReflectionTypeLayout* inTypeLayout, unsigned index) @@ -871,9 +871,9 @@ SLANG_API char const* spReflectionVariable_GetName(SlangReflectionVariable* inVa // If the variable is one that has an "external" name that is supposed // to be exposed for reflection, then report it here if(auto reflectionNameMod = var->FindModifier<ParameterGroupReflectionName>()) - return getText(reflectionNameMod->nameAndLoc.name).Buffer(); + return getText(reflectionNameMod->nameAndLoc.name).getBuffer(); - return getText(var->getName()).Buffer(); + return getText(var->getName()).getBuffer(); } SLANG_API SlangReflectionType* spReflectionVariable_GetType(SlangReflectionVariable* inVar) @@ -1046,7 +1046,7 @@ SLANG_API char const* spReflectionVariableLayout_GetSemanticName(SlangReflection if (!(varLayout->flags & Slang::VarLayoutFlag::HasSemantic)) return 0; - return varLayout->semanticName.Buffer(); + return varLayout->semanticName.getBuffer(); } SLANG_API size_t spReflectionVariableLayout_GetSemanticIndex(SlangReflectionVariableLayout* inVarLayout) @@ -1124,7 +1124,7 @@ namespace Slang if(auto structLayout = as<StructTypeLayout>(typeLayout)) { - return (unsigned) structLayout->fields.Count(); + return (unsigned) structLayout->fields.getCount(); } return 0; @@ -1259,7 +1259,7 @@ SLANG_API int spReflectionEntryPoint_usesAnySampleRateInput( SLANG_API char const* spReflectionTypeParameter_GetName(SlangReflectionTypeParameter * inTypeParam) { auto typeParam = convert(inTypeParam); - return typeParam->decl->getName()->text.Buffer(); + return typeParam->decl->getName()->text.getBuffer(); } SLANG_API unsigned spReflectionTypeParameter_GetIndex(SlangReflectionTypeParameter * inTypeParam) @@ -1272,14 +1272,14 @@ SLANG_API unsigned int spReflectionTypeParameter_GetConstraintCount(SlangReflect { auto typeParam = convert(inTypeParam); auto constraints = typeParam->decl->getMembersOfType<GenericTypeConstraintDecl>(); - return (unsigned int)constraints.Count(); + return (unsigned int)constraints.getCount(); } SLANG_API SlangReflectionType* spReflectionTypeParameter_GetConstraintByIndex(SlangReflectionTypeParameter * inTypeParam, unsigned index) { auto typeParam = convert(inTypeParam); auto constraints = typeParam->decl->getMembersOfType<GenericTypeConstraintDecl>(); - return (SlangReflectionType*)constraints.ToArray()[index]->sup.Ptr(); + return (SlangReflectionType*)constraints.toArray()[index]->sup.Ptr(); } // Shader Reflection @@ -1293,7 +1293,7 @@ SLANG_API unsigned spReflection_GetParameterCount(SlangReflection* inProgram) if (!globalStructLayout) return 0; - return (unsigned) globalStructLayout->fields.Count(); + return (unsigned) globalStructLayout->fields.getCount(); } SLANG_API SlangReflectionParameter* spReflection_GetParameterByIndex(SlangReflection* inProgram, unsigned index) @@ -1311,7 +1311,7 @@ SLANG_API SlangReflectionParameter* spReflection_GetParameterByIndex(SlangReflec SLANG_API unsigned int spReflection_GetTypeParameterCount(SlangReflection * reflection) { auto program = convert(reflection); - return (unsigned int)program->globalGenericParams.Count(); + return (unsigned int)program->globalGenericParams.getCount(); } SLANG_API SlangReflectionTypeParameter* spReflection_GetTypeParameterByIndex(SlangReflection * reflection, unsigned int index) @@ -1334,7 +1334,7 @@ SLANG_API SlangUInt spReflection_getEntryPointCount(SlangReflection* inProgram) auto program = convert(inProgram); if(!program) return 0; - return SlangUInt(program->entryPoints.Count()); + return SlangUInt(program->entryPoints.getCount()); } SLANG_API SlangReflectionEntryPoint* spReflection_getEntryPointByIndex(SlangReflection* inProgram, SlangUInt index) diff --git a/source/slang/slang-file-system.cpp b/source/slang/slang-file-system.cpp index 58cda679d..9cd2ee035 100644 --- a/source/slang/slang-file-system.cpp +++ b/source/slang/slang-file-system.cpp @@ -235,7 +235,7 @@ SlangResult CacheFileSystem::_calcUniqueIdentity(const String& path, String& out { // Try getting the uniqueIdentity by asking underlying file system ComPtr<ISlangBlob> uniqueIdentity; - SLANG_RETURN_ON_FAIL(m_fileSystemExt->getFileUniqueIdentity(path.Buffer(), uniqueIdentity.writeRef())); + SLANG_RETURN_ON_FAIL(m_fileSystemExt->getFileUniqueIdentity(path.getBuffer(), uniqueIdentity.writeRef())); // Get the path as a string outUniqueIdentity = StringUtil::getString(uniqueIdentity); return SLANG_OK; @@ -255,7 +255,7 @@ SlangResult CacheFileSystem::_calcUniqueIdentity(const String& path, String& out case UniqueIdentityMode::Hash: { // I can only see if this is the same file as already loaded by loading the file and doing a hash - Result res = m_fileSystem->loadFile(path.Buffer(), outFileContents.writeRef()); + Result res = m_fileSystem->loadFile(path.getBuffer(), outFileContents.writeRef()); if (SLANG_FAILED(res) || outFileContents == nullptr) { return SLANG_FAIL; @@ -265,7 +265,7 @@ SlangResult CacheFileSystem::_calcUniqueIdentity(const String& path, String& out const uint64_t hash = GetHashCode64((const char*)outFileContents->getBufferPointer(), outFileContents->getBufferSize()); String hashString = Path::getFileName(path); - hashString = hashString.ToLower(); + hashString = hashString.toLower(); hashString.append(':'); @@ -362,7 +362,7 @@ SlangResult CacheFileSystem::loadFile(char const* pathIn, ISlangBlob** blobOut) if (info->m_loadFileResult == CompressedResult::Uninitialized) { - info->m_loadFileResult = toCompressedResult(m_fileSystem->loadFile(path.Buffer(), info->m_fileBlob.writeRef())); + info->m_loadFileResult = toCompressedResult(m_fileSystem->loadFile(path.getBuffer(), info->m_fileBlob.writeRef())); } *blobOut = info->m_fileBlob; @@ -419,7 +419,7 @@ SlangResult CacheFileSystem::getPathType(const char* pathIn, SlangPathType* path // Okay try to load the file if (info->m_loadFileResult == CompressedResult::Uninitialized) { - info->m_loadFileResult = toCompressedResult(m_fileSystem->loadFile(path.Buffer(), info->m_fileBlob.writeRef())); + info->m_loadFileResult = toCompressedResult(m_fileSystem->loadFile(path.getBuffer(), info->m_fileBlob.writeRef())); } // Make the getPathResult the same as the load result @@ -482,7 +482,7 @@ SlangResult CacheFileSystem::getCanonicalPath(const char* path, ISlangBlob** out { // Get the path as a string String canonicalPath = StringUtil::getString(canonicalPathBlob); - if (canonicalPath.Length() > 0) + if (canonicalPath.getLength() > 0) { info->m_canonicalPath = new StringBlob(canonicalPath); } diff --git a/source/slang/slang-stdlib.cpp b/source/slang/slang-stdlib.cpp index 183bed9ba..d2d29beae 100644 --- a/source/slang/slang-stdlib.cpp +++ b/source/slang/slang-stdlib.cpp @@ -12,7 +12,7 @@ namespace Slang { String Session::getStdlibPath() { - if(stdlibPath.Length() != 0) + if(stdlibPath.getLength() != 0) return stdlibPath; StringBuilder pathBuilder; @@ -244,7 +244,7 @@ namespace Slang String Session::getCoreLibraryCode() { - if (coreLibraryCode.Length() > 0) + if (coreLibraryCode.getLength() > 0) return coreLibraryCode; StringBuilder sb; @@ -264,7 +264,7 @@ namespace Slang String Session::getHLSLLibraryCode() { - if (hlslLibraryCode.Length() > 0) + if (hlslLibraryCode.getLength() > 0) return hlslLibraryCode; StringBuilder sb; diff --git a/source/slang/slang.cpp b/source/slang/slang.cpp index affce384b..7556ac9b2 100644 --- a/source/slang/slang.cpp +++ b/source/slang/slang.cpp @@ -75,7 +75,7 @@ Session::Session() auto baseModuleDecl = populateBaseLanguageModule( this, baseLanguageScope); - loadedModuleCode.Add(baseModuleDecl); + loadedModuleCode.add(baseModuleDecl); coreLanguageScope = new Scope(); coreLanguageScope->nextSibling = baseLanguageScope; @@ -108,7 +108,7 @@ struct IncludeHandlerImpl : IncludeHandler ComPtr<ISlangBlob> combinedPathBlob; SLANG_RETURN_ON_FAIL(fileSystemExt->calcCombinedPath(fromPathType, fromPath.begin(), path.begin(), combinedPathBlob.writeRef())); String combinedPath(StringUtil::getString(combinedPathBlob)); - if (combinedPath.Length() <= 0) + if (combinedPath.getLength() <= 0) { return SLANG_FAIL; } @@ -126,7 +126,7 @@ struct IncludeHandlerImpl : IncludeHandler // If the rel path exists -> a uniqueIdentity MUST exists too String uniqueIdentity(StringUtil::getString(uniqueIdentityBlob)); - if (uniqueIdentity.Length() <= 0) + if (uniqueIdentity.getLength() <= 0) { // Unique identity can't be empty return SLANG_FAIL; @@ -188,7 +188,7 @@ struct IncludeHandlerImpl : IncludeHandler { ISlangFileSystemExt* fileSystemExt = _getFileSystemExt(); ComPtr<ISlangBlob> simplifiedPath; - if (SLANG_FAILED(fileSystemExt->getSimplifiedPath(path.Buffer(), simplifiedPath.writeRef()))) + if (SLANG_FAILED(fileSystemExt->getSimplifiedPath(path.getBuffer(), simplifiedPath.writeRef()))) { return path; } @@ -422,7 +422,7 @@ SourceManager* TranslationUnitRequest::getSourceManager() void TranslationUnitRequest::addSourceFile(SourceFile* sourceFile) { - m_sourceFiles.Add(sourceFile); + m_sourceFiles.add(sourceFile); // We want to record that the compiled module has a dependency // on the path of the source file, but we also need to account @@ -472,7 +472,7 @@ void EndToEndCompileRequest::setWriter(WriterChannel chan, ISlangWriter* writer) SlangResult Linkage::loadFile(String const& path, ISlangBlob** outBlob) { - return fileSystemExt->loadFile(path.Buffer(), outBlob); + return fileSystemExt->loadFile(path.getBuffer(), outBlob); } RefPtr<Expr> Linkage::parseTypeString(String typeStr, RefPtr<Scope> scope) @@ -549,7 +549,7 @@ Type* Program::getTypeFromString(String typeStr, DiagnosticSink* sink) // List<RefPtr<Scope>> scopesToTry; for(auto module : getModuleDependencies()) - scopesToTry.Add(module->getModuleDecl()->scope); + scopesToTry.add(module->getModuleDecl()->scope); auto linkage = getLinkage(); for(auto& s : scopesToTry) @@ -839,7 +839,7 @@ SlangResult EndToEndCompileRequest::executeActionsInner() // TODO: This logic should be moved into `options.cpp` or somewhere else // specific to the command-line tool. // - if (getLinkage()->targets.Count() == 0) + if (getLinkage()->targets.getCount() == 0) { auto language = inferSourceLanguage(getFrontEndReq()); switch (language) @@ -938,7 +938,7 @@ SlangResult EndToEndCompileRequest::executeActions() int FrontEndCompileRequest::addTranslationUnit(SourceLanguage language, Name* moduleName) { - UInt result = translationUnits.Count(); + Index result = translationUnits.getCount(); RefPtr<TranslationUnitRequest> translationUnit = new TranslationUnitRequest(this); translationUnit->compileRequest = this; @@ -946,7 +946,7 @@ int FrontEndCompileRequest::addTranslationUnit(SourceLanguage language, Name* mo translationUnit->moduleName = moduleName; - translationUnits.Add(translationUnit); + translationUnits.add(translationUnit); return (int) result; } @@ -959,7 +959,7 @@ int FrontEndCompileRequest::addTranslationUnit(SourceLanguage language) // even when they are being compiled together. // String generatedName = "tu"; - generatedName.append(translationUnits.Count()); + generatedName.append(translationUnits.getCount()); return addTranslationUnit(language, getNamePool()->getName(generatedName)); } @@ -1029,7 +1029,7 @@ int FrontEndCompileRequest::addEntryPoint( { auto translationUnitReq = translationUnits[translationUnitIndex]; - UInt result = m_entryPointReqs.Count(); + Index result = m_entryPointReqs.getCount(); RefPtr<FrontEndEntryPointRequest> entryPointReq = new FrontEndEntryPointRequest( this, @@ -1037,7 +1037,7 @@ int FrontEndCompileRequest::addEntryPoint( getNamePool()->getName(name), entryPointProfile); - m_entryPointReqs.Add(entryPointReq); + m_entryPointReqs.add(entryPointReq); // translationUnitReq->entryPoints.Add(entryPointReq); return int(result); @@ -1053,10 +1053,10 @@ int EndToEndCompileRequest::addEntryPoint( EntryPointInfo entryPointInfo; for (auto typeName : genericTypeNames) - entryPointInfo.genericArgStrings.Add(typeName); + entryPointInfo.genericArgStrings.add(typeName); - UInt result = entryPoints.Count(); - entryPoints.Add(_Move(entryPointInfo)); + Index result = entryPoints.getCount(); + entryPoints.add(_Move(entryPointInfo)); return (int) result; } @@ -1067,8 +1067,8 @@ UInt Linkage::addTarget( targetReq->linkage = this; targetReq->target = target; - UInt result = targets.Count(); - targets.Add(targetReq); + Index result = targets.getCount(); + targets.add(targetReq); return (int) result; } @@ -1085,7 +1085,7 @@ void Linkage::loadParsedModule( // Get a path String mostUniqueIdentity = pathInfo.getMostUniqueIdentity(); - SLANG_ASSERT(mostUniqueIdentity.Length() > 0); + SLANG_ASSERT(mostUniqueIdentity.getLength() > 0); mapPathToLoadedModule.Add(mostUniqueIdentity, loadedModule); mapNameToLoadedModules.Add(name, loadedModule); @@ -1107,7 +1107,7 @@ void Linkage::loadParsedModule( SLANG_ASSERT(errorCountAfter == 0); loadedModule->setIRModule(generateIRForTranslationUnit(translationUnit)); } - loadedModulesList.Add(loadedModule); + loadedModulesList.add(loadedModule); } Module* Linkage::loadModule(String const& name) @@ -1263,7 +1263,7 @@ RefPtr<Module> Linkage::findOrImportModule( // Try to load it ComPtr<ISlangBlob> fileContents; - if(SLANG_FAILED(getFileSystemExt()->loadFile(filePathInfo.foundPath.Buffer(), fileContents.writeRef()))) + if(SLANG_FAILED(getFileSystemExt()->loadFile(filePathInfo.foundPath.getBuffer(), fileContents.writeRef()))) { sink->diagnose(loc, Diagnostics::cannotOpenFile, fileName); mapNameToLoadedModules[name] = nullptr; @@ -1314,7 +1314,7 @@ void ModuleDependencyList::_addDependency(Module* module) if(m_moduleSet.Contains(module)) return; - m_moduleList.Add(module); + m_moduleList.add(module); m_moduleSet.Add(module); } @@ -1327,7 +1327,7 @@ void FilePathDependencyList::addDependency(String const& path) if(m_filePathSet.Contains(path)) return; - m_filePathList.Add(path); + m_filePathList.add(path); m_filePathSet.Add(path); } @@ -1381,7 +1381,7 @@ void Program::addReferencedLeafModule(Module* module) void Program::addEntryPoint(EntryPoint* entryPoint) { - m_entryPoints.Add(entryPoint); + m_entryPoints.add(entryPoint); for(auto module : entryPoint->getModuleDependencies()) { @@ -1423,7 +1423,7 @@ TargetProgram::TargetProgram( : m_program(program) , m_targetReq(targetReq) { - m_entryPointResults.SetSize(program->getEntryPoints().Count()); + m_entryPointResults.setCount(program->getEntryPoints().getCount()); } // @@ -1516,7 +1516,7 @@ void Session::addBuiltinSource( SlangResult res = compileRequest->executeActionsInner(); if (SLANG_FAILED(res)) { - char const* diagnostics = sink.outputBuffer.Buffer(); + char const* diagnostics = sink.outputBuffer.getBuffer(); fprintf(stderr, "%s", diagnostics); #ifdef _WIN32 @@ -1556,7 +1556,7 @@ void Session::addBuiltinSource( // We need to retain this AST so that we can use it in other code // (Note that the `Scope` type does not retain the AST it points to) - loadedModuleCode.Add(syntax); + loadedModuleCode.add(syntax); } Session::~Session() @@ -1770,7 +1770,7 @@ SLANG_API void spSetCodeGenTarget( { auto req = convert(request); auto linkage = req->getLinkage(); - linkage->targets.Clear(); + linkage->targets.clear(); linkage->addTarget(Slang::CodeGenTarget(target)); } @@ -1912,7 +1912,7 @@ SLANG_API void spAddSearchPath( { auto req = convert(request); auto linkage = req->getLinkage(); - linkage->searchDirectories.searchDirectories.Add(Slang::SearchDirectory(path)); + linkage->searchDirectories.searchDirectories.add(Slang::SearchDirectory(path)); } SLANG_API void spAddPreprocessorDefine( @@ -1990,7 +1990,7 @@ SLANG_API void spAddTranslationUnitSourceFile( auto frontEndReq = req->getFrontEndReq(); if(!path) return; if(translationUnitIndex < 0) return; - if(Slang::UInt(translationUnitIndex) >= frontEndReq->translationUnits.Count()) return; + if(Slang::Index(translationUnitIndex) >= frontEndReq->translationUnits.getCount()) return; frontEndReq->addTranslationUnitSourceFile( translationUnitIndex, @@ -2019,19 +2019,20 @@ SLANG_API void spAddTranslationUnitSourceStringSpan( char const* sourceBegin, char const* sourceEnd) { + using namespace Slang; if(!request) return; auto req = convert(request); auto frontEndReq = req->getFrontEndReq(); if(!sourceBegin) return; if(translationUnitIndex < 0) return; - if(Slang::UInt(translationUnitIndex) >= frontEndReq->translationUnits.Count()) return; + if(Index(translationUnitIndex) >= frontEndReq->translationUnits.getCount()) return; if(!path) path = ""; frontEndReq->addTranslationUnitSourceString( translationUnitIndex, path, - Slang::UnownedStringSlice(sourceBegin, sourceEnd)); + UnownedStringSlice(sourceBegin, sourceEnd)); } SLANG_API void spAddTranslationUnitSourceBlob( @@ -2045,7 +2046,7 @@ SLANG_API void spAddTranslationUnitSourceBlob( auto frontEndReq = req->getFrontEndReq(); if(!sourceBlob) return; if(translationUnitIndex < 0) return; - if(Slang::UInt(translationUnitIndex) >= frontEndReq->translationUnits.Count()) return; + if(Slang::Index(translationUnitIndex) >= frontEndReq->translationUnits.getCount()) return; if(!path) path = ""; @@ -2090,19 +2091,20 @@ SLANG_API int spAddEntryPointEx( int genericParamTypeNameCount, char const ** genericParamTypeNames) { + using namespace Slang; if (!request) return -1; auto req = convert(request); auto frontEndReq = req->getFrontEndReq(); if (!name) return -1; if (translationUnitIndex < 0) return -1; - if (Slang::UInt(translationUnitIndex) >= frontEndReq->translationUnits.Count()) return -1; - Slang::List<Slang::String> typeNames; + if (Index(translationUnitIndex) >= frontEndReq->translationUnits.getCount()) return -1; + List<String> typeNames; for (int i = 0; i < genericParamTypeNameCount; i++) - typeNames.Add(genericParamTypeNames[i]); + typeNames.add(genericParamTypeNames[i]); return req->addEntryPoint( translationUnitIndex, name, - Slang::Profile(Slang::Stage(stage)), + Profile(Stage(stage)), typeNames); } @@ -2115,9 +2117,9 @@ SLANG_API SlangResult spSetGlobalGenericArgs( auto req = convert(request); auto& genericArgStrings = req->globalGenericArgStrings; - genericArgStrings.Clear(); + genericArgStrings.clear(); for (int i = 0; i < genericArgCount; i++) - genericArgStrings.Add(genericArgs[i]); + genericArgStrings.add(genericArgs[i]); return SLANG_OK; } @@ -2127,15 +2129,16 @@ SLANG_API SlangResult spSetTypeNameForGlobalExistentialTypeParam( int slotIndex, char const* typeName) { + using namespace Slang; if(!request) return SLANG_FAIL; if(slotIndex < 0) return SLANG_FAIL; if(!typeName) return SLANG_FAIL; auto req = convert(request); auto& typeArgStrings = req->globalExistentialSlotArgStrings; - if(Slang::UInt(slotIndex) >= typeArgStrings.Count()) - typeArgStrings.SetSize(slotIndex+1); - typeArgStrings[slotIndex] = Slang::String(typeName); + if(Index(slotIndex) >= typeArgStrings.getCount()) + typeArgStrings.setCount(slotIndex+1); + typeArgStrings[slotIndex] = String(typeName); return SLANG_OK; } @@ -2145,20 +2148,21 @@ SLANG_API SlangResult spSetTypeNameForEntryPointExistentialTypeParam( int slotIndex, char const* typeName) { + using namespace Slang; if(!request) return SLANG_FAIL; if(entryPointIndex < 0) return SLANG_FAIL; if(slotIndex < 0) return SLANG_FAIL; if(!typeName) return SLANG_FAIL; auto req = convert(request); - if(Slang::UInt(entryPointIndex) >= req->entryPoints.Count()) + if(Index(entryPointIndex) >= req->entryPoints.getCount()) return SLANG_FAIL; auto& entryPointInfo = req->entryPoints[entryPointIndex]; auto& typeArgStrings = entryPointInfo.existentialArgStrings; - if(Slang::UInt(slotIndex) >= typeArgStrings.Count()) - typeArgStrings.SetSize(slotIndex+1); - typeArgStrings[slotIndex] = Slang::String(typeName); + if(Index(slotIndex) >= typeArgStrings.getCount()) + typeArgStrings.setCount(slotIndex+1); + typeArgStrings[slotIndex] = String(typeName); return SLANG_OK; } @@ -2224,7 +2228,7 @@ spGetDependencyFileCount( auto req = convert(request); auto frontEndReq = req->getFrontEndReq(); auto program = frontEndReq->getProgram(); - return (int) program->getFilePathDependencies().Count(); + return (int) program->getFilePathDependencies().getCount(); } /** Get the path to a file this compilation dependend on. @@ -2247,7 +2251,7 @@ spGetTranslationUnitCount( { auto req = convert(request); auto frontEndReq = req->getFrontEndReq(); - return (int) frontEndReq->translationUnits.Count(); + return (int) frontEndReq->translationUnits.getCount(); } // Get the output code associated with a specific translation unit @@ -2264,44 +2268,45 @@ SLANG_API void const* spGetEntryPointCode( int entryPointIndex, size_t* outSize) { + using namespace Slang; auto req = convert(request); auto linkage = req->getLinkage(); auto program = req->getSpecializedProgram(); // TODO: We should really accept a target index in this API - Slang::UInt targetIndex = 0; - auto targetCount = linkage->targets.Count(); + Index targetIndex = 0; + auto targetCount = linkage->targets.getCount(); if (targetIndex >= targetCount) return nullptr; auto targetReq = linkage->targets[targetIndex]; if(entryPointIndex < 0) return nullptr; - if(Slang::UInt(entryPointIndex) >= req->entryPoints.Count()) return nullptr; + if(Index(entryPointIndex) >= req->entryPoints.getCount()) return nullptr; auto entryPoint = program->getEntryPoint(entryPointIndex); auto targetProgram = program->getTargetProgram(targetReq); if(!targetProgram) return nullptr; - Slang::CompileResult& result = targetProgram->getExistingEntryPointResult(entryPointIndex); + CompileResult& result = targetProgram->getExistingEntryPointResult(entryPointIndex); void const* data = nullptr; size_t size = 0; switch (result.format) { - case Slang::ResultFormat::None: + case ResultFormat::None: default: break; - case Slang::ResultFormat::Binary: - data = result.outputBinary.Buffer(); - size = result.outputBinary.Count(); + case ResultFormat::Binary: + data = result.outputBinary.getBuffer(); + size = result.outputBinary.getCount(); break; - case Slang::ResultFormat::Text: - data = result.outputString.Buffer(); - size = result.outputString.Length(); + case ResultFormat::Text: + data = result.outputString.getBuffer(); + size = result.outputString.getLength(); break; } @@ -2315,6 +2320,7 @@ SLANG_API SlangResult spGetEntryPointCodeBlob( int targetIndex, ISlangBlob** outBlob) { + using namespace Slang; if(!request) return SLANG_ERROR_INVALID_PARAMETER; if(!outBlob) return SLANG_ERROR_INVALID_PARAMETER; @@ -2322,14 +2328,14 @@ SLANG_API SlangResult spGetEntryPointCodeBlob( auto linkage = req->getLinkage(); auto program = req->getSpecializedProgram(); - int targetCount = (int) linkage->targets.Count(); + Index targetCount = linkage->targets.getCount(); if((targetIndex < 0) || (targetIndex >= targetCount)) { return SLANG_ERROR_INVALID_PARAMETER; } auto targetReq = linkage->targets[targetIndex]; - int entryPointCount = (int) req->entryPoints.Count(); + Index entryPointCount = req->entryPoints.getCount(); if((entryPointIndex < 0) || (entryPointIndex >= entryPointCount)) { return SLANG_ERROR_INVALID_PARAMETER; @@ -2381,8 +2387,8 @@ SLANG_API SlangReflection* spGetReflection( // so that we can do this better, and make it clear that // `spGetReflection()` is shorthand for `targetIndex == 0`. // - Slang::UInt targetIndex = 0; - auto targetCount = linkage->targets.Count(); + Slang::Index targetIndex = 0; + auto targetCount = linkage->targets.getCount(); if (targetIndex >= targetCount) return nullptr; diff --git a/source/slang/source-loc.cpp b/source/slang/source-loc.cpp index 886b4fefb..b67426053 100644 --- a/source/slang/source-loc.cpp +++ b/source/slang/source-loc.cpp @@ -34,7 +34,7 @@ int SourceView::findEntryIndex(SourceLoc sourceLoc) const const auto rawValue = sourceLoc.getRaw(); - int hi = int(m_entries.Count()); + Index hi = m_entries.getCount(); // If there are no entries, or it is in front of the first entry, then there is no associated entry if (hi == 0 || m_entries[0].m_startLoc.getRaw() > sourceLoc.getRaw()) @@ -42,10 +42,10 @@ int SourceView::findEntryIndex(SourceLoc sourceLoc) const return -1; } - int lo = 0; + Index lo = 0; while (lo + 1 < hi) { - const int mid = (hi + lo) >> 1; + const Index mid = (hi + lo) >> 1; const Entry& midEntry = m_entries[mid]; SourceLoc::RawValue midValue = midEntry.m_startLoc.getRaw(); if (midValue <= rawValue) @@ -60,7 +60,7 @@ int SourceView::findEntryIndex(SourceLoc sourceLoc) const } } - return lo; + return int(lo); } void SourceView::addLineDirective(SourceLoc directiveLoc, StringSlicePool::Handle pathHandle, int line) @@ -69,7 +69,7 @@ void SourceView::addLineDirective(SourceLoc directiveLoc, StringSlicePool::Handl SLANG_ASSERT(m_range.contains(directiveLoc)); // Check that the directiveLoc values are always increasing - SLANG_ASSERT(m_entries.Count() == 0 || (m_entries.Last().m_startLoc.getRaw() < directiveLoc.getRaw())); + SLANG_ASSERT(m_entries.getCount() == 0 || (m_entries.getLast().m_startLoc.getRaw() < directiveLoc.getRaw())); // Calculate the offset const int offset = m_range.getOffset(directiveLoc); @@ -88,7 +88,7 @@ void SourceView::addLineDirective(SourceLoc directiveLoc, StringSlicePool::Handl // Taking both into account means +2 is correct 'fix' entry.m_lineAdjust = line - (lineIndex + 2); - m_entries.Add(entry); + m_entries.add(entry); } void SourceView::addLineDirective(SourceLoc directiveLoc, const String& path, int line) @@ -101,10 +101,10 @@ void SourceView::addDefaultLineDirective(SourceLoc directiveLoc) { SLANG_ASSERT(m_range.contains(directiveLoc)); // Check that the directiveLoc values are always increasing - SLANG_ASSERT(m_entries.Count() == 0 || (m_entries.Last().m_startLoc.getRaw() < directiveLoc.getRaw())); + SLANG_ASSERT(m_entries.getCount() == 0 || (m_entries.getLast().m_startLoc.getRaw() < directiveLoc.getRaw())); // Well if there are no entries, or the last one puts it in default case, then we don't need to add anything - if (m_entries.Count() == 0 || (m_entries.Count() && m_entries.Last().isDefault())) + if (m_entries.getCount() == 0 || (m_entries.getCount() && m_entries.getLast().isDefault())) { return; } @@ -116,7 +116,7 @@ void SourceView::addDefaultLineDirective(SourceLoc directiveLoc) SLANG_ASSERT(entry.isDefault()); - m_entries.Add(entry); + m_entries.add(entry); } HumaneSourceLoc SourceView::getHumaneLoc(SourceLoc loc, SourceLocType type) @@ -160,7 +160,7 @@ HumaneSourceLoc SourceView::getHumaneLoc(SourceLoc loc, SourceLocType type) PathInfo SourceView::_getPathInfo() const { - if (m_viewPath.Length()) + if (m_viewPath.getLength()) { PathInfo pathInfo(m_sourceFile->getPathInfo()); pathInfo.foundPath = m_viewPath; @@ -200,8 +200,8 @@ PathInfo SourceView::getPathInfo(SourceLoc loc, SourceLocType type) void SourceFile::setLineBreakOffsets(const uint32_t* offsets, UInt numOffsets) { - m_lineBreakOffsets.Clear(); - m_lineBreakOffsets.AddRange(offsets, numOffsets); + m_lineBreakOffsets.clear(); + m_lineBreakOffsets.addRange(offsets, numOffsets); } const List<uint32_t>& SourceFile::getLineBreakOffsets() @@ -209,7 +209,7 @@ const List<uint32_t>& SourceFile::getLineBreakOffsets() // We now have a raw input file that we can search for line breaks. // We obviously don't want to do a linear scan over and over, so we will // cache an array of line break locations in the file. - if (m_lineBreakOffsets.Count() == 0) + if (m_lineBreakOffsets.getCount() == 0) { UnownedStringSlice content = getContent(); @@ -219,7 +219,7 @@ const List<uint32_t>& SourceFile::getLineBreakOffsets() char const* cursor = begin; // Treat the beginning of the file as a line break - m_lineBreakOffsets.Add(0); + m_lineBreakOffsets.add(0); while (cursor != end) { @@ -238,7 +238,7 @@ const List<uint32_t>& SourceFile::getLineBreakOffsets() if ((c^d) == ('\r' ^ '\n')) cursor++; - m_lineBreakOffsets.Add(uint32_t(cursor - begin)); + m_lineBreakOffsets.add(uint32_t(cursor - begin)); break; } default: @@ -265,12 +265,12 @@ int SourceFile::calcLineIndexFromOffset(int offset) // At this point we can assume the `lineBreakOffsets` array has been filled in. // We will use a binary search to find the line index that contains our // chosen offset. - int lo = 0; - int hi = int(lineBreakOffsets.Count()); + Index lo = 0; + Index hi = lineBreakOffsets.getCount(); while (lo + 1 < hi) { - const int mid = (hi + lo) >> 1; + const Index mid = (hi + lo) >> 1; const uint32_t midOffset = lineBreakOffsets[mid]; if (midOffset <= uint32_t(offset)) { @@ -282,7 +282,7 @@ int SourceFile::calcLineIndexFromOffset(int offset) } } - return lo; + return int(lo); } int SourceFile::calcColumnIndex(int lineIndex, int offset) @@ -331,11 +331,11 @@ String SourceFile::calcVerbosePath() const { String canonicalPath; ComPtr<ISlangBlob> canonicalPathBlob; - if (SLANG_SUCCEEDED(fileSystemExt->getCanonicalPath(m_pathInfo.foundPath.Buffer(), canonicalPathBlob.writeRef()))) + if (SLANG_SUCCEEDED(fileSystemExt->getCanonicalPath(m_pathInfo.foundPath.getBuffer(), canonicalPathBlob.writeRef()))) { canonicalPath = StringUtil::getString(canonicalPathBlob); } - if (canonicalPath.Length() > 0) + if (canonicalPath.getLength() > 0) { return canonicalPath; } @@ -416,14 +416,14 @@ SourceRange SourceManager::allocateSourceRange(UInt size) SourceFile* SourceManager::createSourceFileWithSize(const PathInfo& pathInfo, size_t contentSize) { SourceFile* sourceFile = new SourceFile(this, pathInfo, contentSize); - m_sourceFiles.Add(sourceFile); + m_sourceFiles.add(sourceFile); return sourceFile; } SourceFile* SourceManager::createSourceFileWithString(const PathInfo& pathInfo, const String& contents) { - SourceFile* sourceFile = new SourceFile(this, pathInfo, contents.Length()); - m_sourceFiles.Add(sourceFile); + SourceFile* sourceFile = new SourceFile(this, pathInfo, contents.getLength()); + m_sourceFiles.add(sourceFile); sourceFile->setContents(contents); return sourceFile; } @@ -431,7 +431,7 @@ SourceFile* SourceManager::createSourceFileWithString(const PathInfo& pathInfo, SourceFile* SourceManager::createSourceFileWithBlob(const PathInfo& pathInfo, ISlangBlob* blob) { SourceFile* sourceFile = new SourceFile(this, pathInfo, blob->getBufferSize()); - m_sourceFiles.Add(sourceFile); + m_sourceFiles.add(sourceFile); sourceFile->setContents(blob); return sourceFile; } @@ -442,7 +442,7 @@ SourceView* SourceManager::createSourceView(SourceFile* sourceFile, const PathIn SourceView* sourceView = nullptr; if (pathInfo && - (pathInfo->foundPath.Length() && sourceFile->getPathInfo().foundPath != pathInfo->foundPath)) + (pathInfo->foundPath.getLength() && sourceFile->getPathInfo().foundPath != pathInfo->foundPath)) { sourceView = new SourceView(sourceFile, range, &pathInfo->foundPath); } @@ -451,14 +451,14 @@ SourceView* SourceManager::createSourceView(SourceFile* sourceFile, const PathIn sourceView = new SourceView(sourceFile, range, nullptr); } - m_sourceViews.Add(sourceView); + m_sourceViews.add(sourceView); return sourceView; } SourceView* SourceManager::findSourceView(SourceLoc loc) const { - int hi = int(m_sourceViews.Count()); + Index hi = m_sourceViews.getCount(); // It must be in the range of this manager and have associated views for it to possibly be a hit if (!getSourceRange().contains(loc) || hi == 0) { @@ -482,10 +482,10 @@ SourceView* SourceManager::findSourceView(SourceLoc loc) const const SourceLoc::RawValue rawLoc = loc.getRaw(); // Binary chop to see if we can find the associated SourceUnit - int lo = 0; + Index lo = 0; while (lo + 1 < hi) { - int mid = (hi + lo) >> 1; + Index mid = (hi + lo) >> 1; SourceView* midView = m_sourceViews[mid]; if (midView->getRange().contains(loc)) diff --git a/source/slang/source-loc.h b/source/slang/source-loc.h index e12ec640e..95db7a50e 100644 --- a/source/slang/source-loc.h +++ b/source/slang/source-loc.h @@ -53,11 +53,11 @@ struct PathInfo }; /// True if has a canonical path - SLANG_FORCE_INLINE bool hasUniqueIdentity() const { return type == Type::Normal && uniqueIdentity.Length() > 0; } + SLANG_FORCE_INLINE bool hasUniqueIdentity() const { return type == Type::Normal && uniqueIdentity.getLength() > 0; } /// True if has a regular found path - SLANG_FORCE_INLINE bool hasFoundPath() const { return type == Type::Normal || type == Type::FoundPath || (type == Type::FromString && foundPath.Length() > 0); } + SLANG_FORCE_INLINE bool hasFoundPath() const { return type == Type::Normal || type == Type::FoundPath || (type == Type::FromString && foundPath.getLength() > 0); } /// True if has a found path that has originated from a file (as opposed to string or some other origin) - SLANG_FORCE_INLINE bool hasFileFoundPath() const { return (type == Type::Normal || type == Type::FoundPath) && foundPath.Length() > 0; } + SLANG_FORCE_INLINE bool hasFileFoundPath() const { return (type == Type::Normal || type == Type::FoundPath) && foundPath.getLength() > 0; } /// Returns the 'most unique' identity for the path. If has a 'uniqueIdentity' returns that, else the foundPath, else "". const String getMostUniqueIdentity() const; @@ -65,8 +65,8 @@ struct PathInfo // So simplify construction. In normal usage it's safer to use make methods over constructing directly. static PathInfo makeUnknown() { return PathInfo { Type::Unknown, "unknown", String() }; } static PathInfo makeTokenPaste() { return PathInfo{ Type::TokenPaste, "token paste", String()}; } - static PathInfo makeNormal(const String& foundPathIn, const String& uniqueIdentity) { SLANG_ASSERT(uniqueIdentity.Length() > 0 && foundPathIn.Length() > 0); return PathInfo { Type::Normal, foundPathIn, uniqueIdentity }; } - static PathInfo makePath(const String& pathIn) { SLANG_ASSERT(pathIn.Length() > 0); return PathInfo { Type::FoundPath, pathIn, String()}; } + static PathInfo makeNormal(const String& foundPathIn, const String& uniqueIdentity) { SLANG_ASSERT(uniqueIdentity.getLength() > 0 && foundPathIn.getLength() > 0); return PathInfo { Type::Normal, foundPathIn, uniqueIdentity }; } + static PathInfo makePath(const String& pathIn) { SLANG_ASSERT(pathIn.getLength() > 0); return PathInfo { Type::FoundPath, pathIn, String()}; } static PathInfo makeTypeParse() { return PathInfo { Type::TypeParse, "type string", String() }; } static PathInfo makeCommandLine() { return PathInfo { Type::CommandLine, "command line", String() }; } static PathInfo makeFromString(const String& userPath) { return PathInfo{ Type::FromString, userPath, String() }; } @@ -264,7 +264,7 @@ class SourceView /// Get the entries const List<Entry>& getEntries() const { return m_entries; } /// Set the entries list - void setEntries(const Entry* entries, UInt numEntries) { m_entries.Clear(); m_entries.AddRange(entries, numEntries); } + void setEntries(const Entry* entries, UInt numEntries) { m_entries.clear(); m_entries.addRange(entries, numEntries); } /// Get the source file holds the contents this view SourceFile* getSourceFile() const { return m_sourceFile; } diff --git a/source/slang/syntax.cpp b/source/slang/syntax.cpp index c48eb7755..c069c69d7 100644 --- a/source/slang/syntax.cpp +++ b/source/slang/syntax.cpp @@ -299,7 +299,7 @@ void Type::accept(IValVisitor* visitor, void* extra) auto substitutions = new GenericSubstitution(); substitutions->genericDecl = genericDecl; - substitutions->args.Add(valueType); + substitutions->args.add(valueType); auto declRef = DeclRef<Decl>(typeDecl.Ptr(), substitutions); auto rsType = DeclRefType::Create( @@ -766,7 +766,7 @@ void Type::accept(IValVisitor* visitor, void* extra) } else if (magicMod->name == "Vector") { - SLANG_ASSERT(subst && subst->args.Count() == 2); + SLANG_ASSERT(subst && subst->args.getCount() == 2); auto vecType = new VectorExpressionType(); vecType->setSession(session); vecType->declRef = declRef; @@ -776,7 +776,7 @@ void Type::accept(IValVisitor* visitor, void* extra) } else if (magicMod->name == "Matrix") { - SLANG_ASSERT(subst && subst->args.Count() == 3); + SLANG_ASSERT(subst && subst->args.getCount() == 3); auto matType = new MatrixExpressionType(); matType->setSession(session); matType->declRef = declRef; @@ -784,7 +784,7 @@ void Type::accept(IValVisitor* visitor, void* extra) } else if (magicMod->name == "Texture") { - SLANG_ASSERT(subst && subst->args.Count() >= 1); + SLANG_ASSERT(subst && subst->args.getCount() >= 1); auto textureType = new TextureType( TextureFlavor(magicMod->tag), ExtractGenericArgType(subst->args[0])); @@ -794,7 +794,7 @@ void Type::accept(IValVisitor* visitor, void* extra) } else if (magicMod->name == "TextureSampler") { - SLANG_ASSERT(subst && subst->args.Count() >= 1); + SLANG_ASSERT(subst && subst->args.getCount() >= 1); auto textureType = new TextureSamplerType( TextureFlavor(magicMod->tag), ExtractGenericArgType(subst->args[0])); @@ -804,7 +804,7 @@ void Type::accept(IValVisitor* visitor, void* extra) } else if (magicMod->name == "GLSLImageType") { - SLANG_ASSERT(subst && subst->args.Count() >= 1); + SLANG_ASSERT(subst && subst->args.getCount() >= 1); auto textureType = new GLSLImageType( TextureFlavor(magicMod->tag), ExtractGenericArgType(subst->args[0])); @@ -832,7 +832,7 @@ void Type::accept(IValVisitor* visitor, void* extra) #define CASE(n,T) \ else if(magicMod->name == #n) { \ - SLANG_ASSERT(subst && subst->args.Count() == 1); \ + SLANG_ASSERT(subst && subst->args.getCount() == 1); \ auto type = new T(); \ type->setSession(session); \ type->elementType = ExtractGenericArgType(subst->args[0]); \ @@ -1074,7 +1074,7 @@ void Type::accept(IValVisitor* visitor, void* extra) List<RefPtr<Type>> substParamTypes; for( auto pp : paramTypes ) { - substParamTypes.Add(pp->SubstituteImpl(subst, &diff).as<Type>()); + substParamTypes.add(pp->SubstituteImpl(subst, &diff).as<Type>()); } // early exit for no change... @@ -1098,7 +1098,7 @@ void Type::accept(IValVisitor* visitor, void* extra) List<RefPtr<Type>> canParamTypes; for( auto pp : paramTypes ) { - canParamTypes.Add(pp->GetCanonicalType()); + canParamTypes.add(pp->GetCanonicalType()); } RefPtr<FuncType> canType = new FuncType(); @@ -1256,8 +1256,8 @@ void Type::accept(IValVisitor* visitor, void* extra) auto substitutions = new GenericSubstitution(); substitutions->genericDecl = vectorGenericDecl.Ptr(); - substitutions->args.Add(elementType); - substitutions->args.Add(elementCount); + substitutions->args.add(elementType); + substitutions->args.add(elementCount); auto declRef = DeclRef<Decl>(vectorTypeDecl.Ptr(), substitutions); @@ -1348,7 +1348,7 @@ void Type::accept(IValVisitor* visitor, void* extra) List<RefPtr<Val>> substArgs; for (auto a : args) { - substArgs.Add(a->SubstituteImpl(substSet, &diff)); + substArgs.add(a->SubstituteImpl(substSet, &diff)); } if (!diff) return this; @@ -1375,9 +1375,9 @@ void Type::accept(IValVisitor* visitor, void* extra) if (genericDecl != genericSubst->genericDecl) return false; - UInt argCount = args.Count(); - SLANG_RELEASE_ASSERT(args.Count() == genericSubst->args.Count()); - for (UInt aa = 0; aa < argCount; ++aa) + Index argCount = args.getCount(); + SLANG_RELEASE_ASSERT(args.getCount() == genericSubst->args.getCount()); + for (Index aa = 0; aa < argCount; ++aa) { if (!args[aa]->EqualsVal(genericSubst->args[aa].Ptr())) return false; @@ -1447,7 +1447,7 @@ void Type::accept(IValVisitor* visitor, void* extra) substConstraintArg.decl = constraintArg.decl; substConstraintArg.val = constraintArg.val->SubstituteImpl(substSet, &diff); - substConstraintArgs.Add(substConstraintArg); + substConstraintArgs.add(substConstraintArg); } if(!diff) @@ -1476,9 +1476,9 @@ void Type::accept(IValVisitor* visitor, void* extra) return false; if (!actualType->EqualsVal(genSubst->actualType)) return false; - if (constraintArgs.Count() != genSubst->constraintArgs.Count()) + if (constraintArgs.getCount() != genSubst->constraintArgs.getCount()) return false; - for (UInt i = 0; i < constraintArgs.Count(); i++) + for (Index i = 0; i < constraintArgs.getCount(); i++) { if (!constraintArgs[i].val->EqualsVal(genSubst->constraintArgs[i].val)) return false; @@ -2139,7 +2139,7 @@ void Type::accept(IValVisitor* visitor, void* extra) paramType = session->getOutType(paramType); } } - funcType->paramTypes.Add(paramType); + funcType->paramTypes.add(paramType); } return funcType; @@ -2238,7 +2238,7 @@ void Type::accept(IValVisitor* visitor, void* extra) continue; bool found = false; - UInt index = 0; + Index index = 0; for (auto m : genericDecl->Members) { if (auto constraintParam = as<GenericTypeConstraintDecl>(m)) @@ -2254,9 +2254,9 @@ void Type::accept(IValVisitor* visitor, void* extra) if (found) { (*ioDiff)++; - auto ordinaryParamCount = genericDecl->getMembersOfType<GenericTypeParamDecl>().Count() + - genericDecl->getMembersOfType<GenericValueParamDecl>().Count(); - SLANG_ASSERT(index + ordinaryParamCount < genericSubst->args.Count()); + auto ordinaryParamCount = genericDecl->getMembersOfType<GenericTypeParamDecl>().getCount() + + genericDecl->getMembersOfType<GenericValueParamDecl>().getCount(); + SLANG_ASSERT(index + ordinaryParamCount < genericSubst->args.getCount()); return genericSubst->args[index + ordinaryParamCount]; } } @@ -2583,11 +2583,11 @@ void Type::accept(IValVisitor* visitor, void* extra) if(!taggedUnion) return false; - auto caseCount = caseTypes.Count(); - if(caseCount != taggedUnion->caseTypes.Count()) + auto caseCount = caseTypes.getCount(); + if(caseCount != taggedUnion->caseTypes.getCount()) return false; - for( UInt ii = 0; ii < caseCount; ++ii ) + for( Index ii = 0; ii < caseCount; ++ii ) { if(!caseTypes[ii]->Equals(taggedUnion->caseTypes[ii])) return false; @@ -2613,7 +2613,7 @@ void Type::accept(IValVisitor* visitor, void* extra) for( auto caseType : caseTypes ) { auto canCaseType = caseType->GetCanonicalType(); - canType->caseTypes.Add(canCaseType); + canType->caseTypes.add(canCaseType); } return canType; @@ -2626,7 +2626,7 @@ void Type::accept(IValVisitor* visitor, void* extra) List<RefPtr<Type>> substCaseTypes; for( auto caseType : caseTypes ) { - substCaseTypes.Add(caseType->SubstituteImpl(subst, &diff).as<Type>()); + substCaseTypes.add(caseType->SubstituteImpl(subst, &diff).as<Type>()); } if(!diff) return this; @@ -2635,7 +2635,7 @@ void Type::accept(IValVisitor* visitor, void* extra) RefPtr<TaggedUnionType> substType = new TaggedUnionType(); substType->setSession(getSession()); - substType->caseTypes.SwapWith(substCaseTypes); + substType->caseTypes.swapWith(substCaseTypes); return substType; } @@ -2650,11 +2650,11 @@ bool TaggedUnionSubtypeWitness::EqualsVal(Val* val) if(!taggedUnionWitness) return false; - auto caseCount = caseWitnesses.Count(); - if(caseCount != taggedUnionWitness->caseWitnesses.Count()) + auto caseCount = caseWitnesses.getCount(); + if(caseCount != taggedUnionWitness->caseWitnesses.getCount()) return false; - for(UInt ii = 0; ii < caseCount; ++ii) + for(Index ii = 0; ii < caseCount; ++ii) { if(!caseWitnesses[ii]->EqualsVal(taggedUnionWitness->caseWitnesses[ii])) return false; @@ -2698,7 +2698,7 @@ RefPtr<Val> TaggedUnionSubtypeWitness::SubstituteImpl(SubstitutionSet subst, int List<RefPtr<Val>> substCaseWitnesses; for( auto caseWitness : caseWitnesses ) { - substCaseWitnesses.Add(caseWitness->SubstituteImpl(subst, &diff)); + substCaseWitnesses.add(caseWitness->SubstituteImpl(subst, &diff)); } if(!diff) @@ -2709,7 +2709,7 @@ RefPtr<Val> TaggedUnionSubtypeWitness::SubstituteImpl(SubstitutionSet subst, int RefPtr<TaggedUnionSubtypeWitness> substWitness = new TaggedUnionSubtypeWitness(); substWitness->sub = substSub; substWitness->sup = substSup; - substWitness->caseWitnesses.SwapWith(substCaseWitnesses); + substWitness->caseWitnesses.swapWith(substCaseWitnesses); return substWitness; } diff --git a/source/slang/syntax.h b/source/slang/syntax.h index 41d8b2cec..eb7cee40a 100644 --- a/source/slang/syntax.h +++ b/source/slang/syntax.h @@ -589,50 +589,50 @@ namespace Slang typedef RefPtr<Decl> Element; FilteredMemberList() - : mBegin(NULL) - , mEnd(NULL) + : m_begin(nullptr) + , m_end(nullptr) {} explicit FilteredMemberList( List<Element> const& list) - : mBegin(Adjust(list.begin(), list.end())) - , mEnd(list.end()) + : m_begin(adjust(list.begin(), list.end())) + , m_end(list.end()) {} struct Iterator { - Element* mCursor; - Element* mEnd; + Element* m_cursor; + Element* m_end; bool operator!=(Iterator const& other) { - return mCursor != other.mCursor; + return m_cursor != other.m_cursor; } void operator++() { - mCursor = Adjust(mCursor + 1, mEnd); + m_cursor = adjust(m_cursor + 1, m_end); } RefPtr<T>& operator*() { - return *(RefPtr<T>*)mCursor; + return *(RefPtr<T>*)m_cursor; } }; Iterator begin() { - Iterator iter = { mBegin, mEnd }; + Iterator iter = { m_begin, m_end }; return iter; } Iterator end() { - Iterator iter = { mEnd, mEnd }; + Iterator iter = { m_end, m_end }; return iter; } - static Element* Adjust(Element* cursor, Element* end) + static Element* adjust(Element* cursor, Element* end) { while (cursor != end) { @@ -645,10 +645,10 @@ namespace Slang // TODO(tfoley): It is ugly to have these. // We should probably fix the call sites instead. - RefPtr<T>& First() { return *begin(); } - UInt Count() + RefPtr<T>& getFirst() { return *begin(); } + Index getCount() { - UInt count = 0; + Index count = 0; for (auto iter : (*this)) { (void)iter; @@ -657,18 +657,18 @@ namespace Slang return count; } - List<RefPtr<T>> ToArray() + List<RefPtr<T>> toArray() { List<RefPtr<T>> result; for (auto element : (*this)) { - result.Add(element); + result.add(element); } return result; } - Element* mBegin; - Element* mEnd; + Element* m_begin; + Element* m_end; }; struct TransparentMemberInfo @@ -702,7 +702,7 @@ namespace Slang { List<DeclRef<T>> result; for (auto d : *this) - result.Add(d); + result.add(d); return result; } @@ -998,11 +998,11 @@ namespace Slang // Was at least one result found? bool isValid() const { return item.declRef.getDecl() != nullptr; } - bool isOverloaded() const { return items.Count() > 1; } + bool isOverloaded() const { return items.getCount() > 1; } Name* getName() const { - return items.Count() > 1 ? items[0].declRef.GetName() : item.declRef.GetName(); + return items.getCount() > 1 ? items[0].declRef.GetName() : item.declRef.GetName(); } LookupResultItem* begin() { @@ -1217,14 +1217,14 @@ namespace Slang { List<DeclRef<T>> rs; for (auto d : getMembersOfType<T>(declRef)) - rs.Add(d); + rs.add(d); if (auto aggDeclRef = declRef.as<AggTypeDecl>()) { for (auto ext = GetCandidateExtensions(aggDeclRef); ext; ext = ext->nextCandidateExtension) { auto extMembers = getMembersOfType<T>(DeclRef<ContainerDecl>(ext, declRef.substitutions)); for (auto mbr : extMembers) - rs.Add(mbr); + rs.add(mbr); } } return rs; diff --git a/source/slang/type-defs.h b/source/slang/type-defs.h index b7af1d975..2d376d754 100644 --- a/source/slang/type-defs.h +++ b/source/slang/type-defs.h @@ -406,7 +406,7 @@ RAW( FuncType() {} - UInt getParamCount() { return paramTypes.Count(); } + UInt getParamCount() { return paramTypes.getCount(); } Type* getParamType(UInt index) { return paramTypes[index]; } Type* getResultType() { return resultType; } diff --git a/source/slang/type-layout.cpp b/source/slang/type-layout.cpp index 90acf0d3c..e315c2fb6 100644 --- a/source/slang/type-layout.cpp +++ b/source/slang/type-layout.cpp @@ -1119,7 +1119,7 @@ RefPtr<TypeLayout> applyOffsetToTypeLayout( } } - newStructTypeLayout->fields.Add(newField); + newStructTypeLayout->fields.add(newField); mapOldFieldToNew.Add(oldField.Ptr(), newField.Ptr()); } @@ -1843,7 +1843,7 @@ static TypeLayoutResult _createTypeLayout( int findGenericParam(List<RefPtr<GenericParamLayout>> & genericParameters, GlobalGenericParamDecl * decl) { - return (int)genericParameters.FindFirst([=](RefPtr<GenericParamLayout> & x) {return x->decl.Ptr() == decl; }); + return (int)genericParameters.findFirstIndex([=](RefPtr<GenericParamLayout> & x) {return x->decl.Ptr() == decl; }); } // When constructing a new var layout from an existing one, @@ -1999,7 +1999,7 @@ static RefPtr<TypeLayout> maybeAdjustLayoutForArrayElementType( } else if(auto originalStructTypeLayout = originalTypeLayout.as<StructTypeLayout>() ) { - UInt fieldCount = originalStructTypeLayout->fields.Count(); + Index fieldCount = originalStructTypeLayout->fields.getCount(); // Empty struct? Bail out. if(fieldCount == 0) @@ -2072,7 +2072,7 @@ static RefPtr<TypeLayout> maybeAdjustLayoutForArrayElementType( } } - adjustedStructTypeLayout->fields.Add(adjustedField); + adjustedStructTypeLayout->fields.add(adjustedField); mapOriginalFieldToAdjusted.Add(originalField, adjustedField); } @@ -2119,7 +2119,7 @@ TypeLayoutResult makeTypeLayoutResult(RefPtr<TypeLayout> typeLayout) // If the type only consumes a single kind of non-uniform resource, // we can fill in the `info` field directly. // - if( typeLayout->resourceInfos.Count() == 1 ) + if( typeLayout->resourceInfos.getCount() == 1 ) { auto resInfo = typeLayout->resourceInfos[0]; if( resInfo.kind != LayoutResourceKind::Uniform ) @@ -2209,7 +2209,7 @@ RefPtr<VarLayout> StructTypeLayoutBuilder::addField( RefPtr<VarLayout> fieldLayout = new VarLayout(); fieldLayout->varDecl = field; fieldLayout->typeLayout = fieldTypeLayout; - m_typeLayout->fields.Add(fieldLayout); + m_typeLayout->fields.add(fieldLayout); m_typeLayout->mapVarToLayout.Add(field.getDecl(), fieldLayout); // Set up uniform offset information, if there is any uniform data in the field @@ -2906,7 +2906,7 @@ static TypeLayoutResult _createTypeLayout( // We need to remember the layout of the case type // on the final `TaggedUnionTypeLayout`. // - taggedUnionLayout->caseTypeLayouts.Add(caseTypeLayout); + taggedUnionLayout->caseTypeLayouts.add(caseTypeLayout); // We also need to consider contributions for other // resource kinds beyond uniform data. diff --git a/source/slang/type-layout.h b/source/slang/type-layout.h index f0c09f371..fcb2c3419 100644 --- a/source/slang/type-layout.h +++ b/source/slang/type-layout.h @@ -358,8 +358,8 @@ public: ResourceInfo info; info.kind = kind; info.count = 0; - resourceInfos.Add(info); - return &resourceInfos.Last(); + resourceInfos.add(info); + return &resourceInfos.getLast(); } void addResourceUsage(ResourceInfo info) @@ -460,8 +460,8 @@ public: info.space = 0; info.index = 0; - resourceInfos.Add(info); - return &resourceInfos.Last(); + resourceInfos.add(info); + return &resourceInfos.getLast(); } ResourceInfo* findOrAddResourceInfo(LayoutResourceKind kind) diff --git a/source/slangc/main.cpp b/source/slangc/main.cpp index 80b9cddbd..ddeb315e1 100644 --- a/source/slangc/main.cpp +++ b/source/slangc/main.cpp @@ -66,7 +66,7 @@ SLANG_TEST_TOOL_API SlangResult innerMain(StdWriters* stdWriters, SlangSession* #ifndef _DEBUG catch (Exception & e) { - StdWriters::getOut().print("internal compiler error: %S\n", e.Message.ToWString().begin()); + StdWriters::getOut().print("internal compiler error: %S\n", e.Message.toWString().begin()); res = SLANG_FAIL; } #endif @@ -102,12 +102,12 @@ int wmain(int argc, wchar_t** argv) List<String> args; for(int ii = 0; ii < argc; ++ii) { - args.Add(String::FromWString(argv[ii])); + args.add(String::fromWString(argv[ii])); } List<char const*> argBuffers; for(int ii = 0; ii < argc; ++ii) { - argBuffers.Add(args[ii].Buffer()); + argBuffers.add(args[ii].getBuffer()); } result = MAIN(argc, (char**) &argBuffers[0]); |
