diff options
| author | Ellie Hermaszewska <ellieh@nvidia.com> | 2024-10-29 14:49:26 +0800 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2024-10-29 14:49:26 +0800 |
| commit | f65d756bff8d4c5cbc15bd0322a2ae8e6b896a21 (patch) | |
| tree | ea1d61342cd29368e19135000ec2948813096205 /tools/slang-unit-test | |
| parent | a729c15e9dce9f5116a38afc66329ab2ca4cea54 (diff) | |
format
* format
* Minor test fixes
* enable checking cpp format in ci
Diffstat (limited to 'tools/slang-unit-test')
35 files changed, 1405 insertions, 1097 deletions
diff --git a/tools/slang-unit-test/unit-test-byte-encode.cpp b/tools/slang-unit-test/unit-test-byte-encode.cpp index 38bd5561d..36b9f91d8 100644 --- a/tools/slang-unit-test/unit-test-byte-encode.cpp +++ b/tools/slang-unit-test/unit-test-byte-encode.cpp @@ -1,15 +1,13 @@ // unit-test-byte-encode.cpp #include "../../source/core/slang-byte-encode-util.h" +#include "../../source/core/slang-list.h" +#include "../../source/core/slang-random-generator.h" +#include "tools/unit-test/slang-unit-test.h" #include <stdio.h> #include <stdlib.h> -#include "tools/unit-test/slang-unit-test.h" - -#include "../../source/core/slang-random-generator.h" -#include "../../source/core/slang-list.h" - using namespace Slang; static void checkUInt32(uint32_t value) @@ -91,28 +89,38 @@ SLANG_UNIT_TEST(byteEncode) { const int v = ByteEncodeUtil::calcMsb8(uint32_t((randGen.nextInt32() & 0xf) | 1)); - // Make the commonality of different numbers that bytes are most common, then shorts etc.. + // Make the commonality of different numbers that bytes are most common, then shorts + // etc.. uint32_t mask; switch (v) { - case 0: mask = 0xffffffff; break; - case 1: mask = 0x00ffffff; break; - case 2: mask = 0x0000ffff; break; - case 3: mask = 0x000000ff; break; + case 0: mask = 0xffffffff; break; + case 1: mask = 0x00ffffff; break; + case 2: mask = 0x0000ffff; break; + case 3: mask = 0x000000ff; break; } initialBuffer[i] = randGen.nextInt32() & mask; } - - size_t numEncodeBytes = ByteEncodeUtil::encodeLiteUInt32(initialBuffer.begin(), blockSize, encodedBuffer.begin()); - SLANG_CHECK(ByteEncodeUtil::calcEncodeLiteSizeUInt32(initialBuffer.begin(), blockSize) == numEncodeBytes); + size_t numEncodeBytes = ByteEncodeUtil::encodeLiteUInt32( + initialBuffer.begin(), + blockSize, + encodedBuffer.begin()); + + SLANG_CHECK( + ByteEncodeUtil::calcEncodeLiteSizeUInt32(initialBuffer.begin(), blockSize) == + numEncodeBytes); + + size_t numEncodeBytes2 = ByteEncodeUtil::decodeLiteUInt32( + encodedBuffer.begin(), + blockSize, + decodeBuffer.begin()); - size_t numEncodeBytes2 = ByteEncodeUtil::decodeLiteUInt32(encodedBuffer.begin(), blockSize, decodeBuffer.begin()); - SLANG_CHECK(numEncodeBytes2 == numEncodeBytes); - - SLANG_CHECK(memcmp(decodeBuffer.begin(), initialBuffer.begin(), sizeof(uint32_t) * blockSize) == 0); + + SLANG_CHECK( + memcmp(decodeBuffer.begin(), initialBuffer.begin(), sizeof(uint32_t) * blockSize) == 0); } { @@ -134,6 +142,5 @@ SLANG_UNIT_TEST(byteEncode) checkUInt32(uint32_t(i)); } #endif - } - + } } diff --git a/tools/slang-unit-test/unit-test-com-host-callable.cpp b/tools/slang-unit-test/unit-test-com-host-callable.cpp index 29bc91739..7fcc033b4 100644 --- a/tools/slang-unit-test/unit-test-com-host-callable.cpp +++ b/tools/slang-unit-test/unit-test-com-host-callable.cpp @@ -1,27 +1,25 @@ // unit-test-com-host-callable.cpp #include "../../source/core/slang-byte-encode-util.h" - -#include <stdio.h> -#include <stdlib.h> - -#include "tools/unit-test/slang-unit-test.h" - -#include "slang.h" +#include "../../source/core/slang-list.h" #include "slang-com-helper.h" #include "slang-com-ptr.h" +#include "slang.h" +#include "tools/unit-test/slang-unit-test.h" -#include "../../source/core/slang-list.h" +#include <stdio.h> +#include <stdlib.h> -namespace { // anonymous +namespace +{ // anonymous // Slang namespace is used for elements support code (like core) which we use here // for ComPtr<> and TestToolUtil using namespace Slang; -// For the moment we have to explicitly write the Slang COM interface in C++ code. It *MUST* match +// For the moment we have to explicitly write the Slang COM interface in C++ code. It *MUST* match // the interface in the slang source -// As it stands all interfaces need to derive from ISlangUnknown (or IUnknown). +// As it stands all interfaces need to derive from ISlangUnknown (or IUnknown). class IDoThings : public ISlangUnknown { public: @@ -50,20 +48,34 @@ class DoThings : public IDoThings { public: // We don't need queryInterface for this impl, or ref counting - virtual SLANG_NO_THROW SlangResult SLANG_MCALL queryInterface(SlangUUID const& uuid, void** outObject) SLANG_OVERRIDE { return SLANG_E_NOT_IMPLEMENTED; } + virtual SLANG_NO_THROW SlangResult SLANG_MCALL + queryInterface(SlangUUID const& uuid, void** outObject) SLANG_OVERRIDE + { + return SLANG_E_NOT_IMPLEMENTED; + } virtual SLANG_NO_THROW uint32_t SLANG_MCALL addRef() SLANG_OVERRIDE { return 1; } virtual SLANG_NO_THROW uint32_t SLANG_MCALL release() SLANG_OVERRIDE { return 1; } // IDoThings - virtual SLANG_NO_THROW int SLANG_MCALL doThing(int a, int b) SLANG_OVERRIDE { return a + b + 1; } - virtual SLANG_NO_THROW int SLANG_MCALL calcHash(const char* in) SLANG_OVERRIDE { return (int)_calcHash(in); } + virtual SLANG_NO_THROW int SLANG_MCALL doThing(int a, int b) SLANG_OVERRIDE + { + return a + b + 1; + } + virtual SLANG_NO_THROW int SLANG_MCALL calcHash(const char* in) SLANG_OVERRIDE + { + return (int)_calcHash(in); + } }; class CountGood : public ICountGood { public: // We don't need queryInterface for this impl, or ref counting - virtual SLANG_NO_THROW SlangResult SLANG_MCALL queryInterface(SlangUUID const& uuid, void** outObject) SLANG_OVERRIDE { return SLANG_E_NOT_IMPLEMENTED; } + virtual SLANG_NO_THROW SlangResult SLANG_MCALL + queryInterface(SlangUUID const& uuid, void** outObject) SLANG_OVERRIDE + { + return SLANG_E_NOT_IMPLEMENTED; + } virtual SLANG_NO_THROW uint32_t SLANG_MCALL addRef() SLANG_OVERRIDE { return 1; } virtual SLANG_NO_THROW uint32_t SLANG_MCALL release() SLANG_OVERRIDE { return 1; } @@ -75,44 +87,50 @@ public: struct ComTestContext { - ComTestContext(UnitTestContext* context): - m_unitTestContext(context) + ComTestContext(UnitTestContext* context) + : m_unitTestContext(context) { slang::IGlobalSession* slangSession = m_unitTestContext->slangGlobalSession; - m_defaultCppCompiler = slangSession->getDefaultDownstreamCompiler(SLANG_SOURCE_LANGUAGE_CPP); - - m_hostHostCallableCompiler = slangSession->getDownstreamCompilerForTransition(SLANG_CPP_SOURCE, SLANG_HOST_HOST_CALLABLE); - m_shaderHostCallableCompiler = slangSession->getDownstreamCompilerForTransition(SLANG_CPP_SOURCE, SLANG_SHADER_HOST_CALLABLE); + m_defaultCppCompiler = + slangSession->getDefaultDownstreamCompiler(SLANG_SOURCE_LANGUAGE_CPP); + m_hostHostCallableCompiler = slangSession->getDownstreamCompilerForTransition( + SLANG_CPP_SOURCE, + SLANG_HOST_HOST_CALLABLE); + m_shaderHostCallableCompiler = slangSession->getDownstreamCompilerForTransition( + SLANG_CPP_SOURCE, + SLANG_SHADER_HOST_CALLABLE); } SlangResult runTests() { slang::IGlobalSession* slangSession = m_unitTestContext->slangGlobalSession; - // TODO(JS): - // Care is needed around this in normal testing. `slang-llvm` is whatever was asked for for when premake was built - // when the target is specified. Otherwise it is the `default` which is typically 64 bit during development. + // TODO(JS): + // Care is needed around this in normal testing. `slang-llvm` is whatever was asked for for + // when premake was built when the target is specified. Otherwise it is the `default` which + // is typically 64 bit during development. // - // On CI we should be okay, because it should download the correct `slang-llvm` for the build (as it packages up with it). - // But for normal development, that can easily not be the case (for example changing to 32 bit build in VS is a problem). + // On CI we should be okay, because it should download the correct `slang-llvm` for the + // build (as it packages up with it). But for normal development, that can easily not be the + // case (for example changing to 32 bit build in VS is a problem). // - // Make sure to run + // Make sure to run // // ``` // premake --arch=x86 --deps=true // ``` // // for the actual target/arch(!) - - const bool hasLlvm = SLANG_SUCCEEDED(slangSession->checkPassThroughSupport(SLANG_PASS_THROUGH_LLVM)); + + const bool hasLlvm = + SLANG_SUCCEEDED(slangSession->checkPassThroughSupport(SLANG_PASS_THROUGH_LLVM)); SlangPassThrough cppCompiler = SLANG_PASS_THROUGH_NONE; { - const SlangPassThrough cppCompilers[] = - { + const SlangPassThrough cppCompilers[] = { SLANG_PASS_THROUGH_VISUAL_STUDIO, SLANG_PASS_THROUGH_GCC, SLANG_PASS_THROUGH_CLANG, @@ -132,9 +150,15 @@ struct ComTestContext if (cppCompiler != SLANG_PASS_THROUGH_NONE) { slangSession->setDefaultDownstreamCompiler(SLANG_SOURCE_LANGUAGE_CPP, cppCompiler); - - slangSession->setDownstreamCompilerForTransition(SLANG_CPP_SOURCE, SLANG_SHADER_HOST_CALLABLE, cppCompiler); - slangSession->setDownstreamCompilerForTransition(SLANG_CPP_SOURCE, SLANG_HOST_HOST_CALLABLE, cppCompiler); + + slangSession->setDownstreamCompilerForTransition( + SLANG_CPP_SOURCE, + SLANG_SHADER_HOST_CALLABLE, + cppCompiler); + slangSession->setDownstreamCompilerForTransition( + SLANG_CPP_SOURCE, + SLANG_HOST_HOST_CALLABLE, + cppCompiler); SLANG_RETURN_ON_FAIL(_runTest()); } @@ -157,14 +181,17 @@ struct ComTestContext slang::IGlobalSession* slangSession = m_unitTestContext->slangGlobalSession; slangSession->setDefaultDownstreamCompiler(SLANG_SOURCE_LANGUAGE_CPP, m_defaultCppCompiler); - slangSession->setDownstreamCompilerForTransition(SLANG_CPP_SOURCE, SLANG_SHADER_HOST_CALLABLE, m_shaderHostCallableCompiler); - slangSession->setDownstreamCompilerForTransition(SLANG_CPP_SOURCE, SLANG_HOST_HOST_CALLABLE, m_hostHostCallableCompiler); + slangSession->setDownstreamCompilerForTransition( + SLANG_CPP_SOURCE, + SLANG_SHADER_HOST_CALLABLE, + m_shaderHostCallableCompiler); + slangSession->setDownstreamCompilerForTransition( + SLANG_CPP_SOURCE, + SLANG_HOST_HOST_CALLABLE, + m_hostHostCallableCompiler); } - ~ComTestContext() - { - _reset(); - } + ~ComTestContext() { _reset(); } SlangResult _runTest(); @@ -186,9 +213,9 @@ SlangResult ComTestContext::_runTest() SLANG_ALLOW_DEPRECATED_END // We want to compile to 'HOST_CALLABLE' here such that we can execute the Slang code. - // - // Note that it is possible to use HOST_HOST_CALLABLE, but this currently only works with 'regular' C++ compilers - // not with `slang-llvm`. + // + // Note that it is possible to use HOST_HOST_CALLABLE, but this currently only works with + // 'regular' C++ compilers not with `slang-llvm`. const int targetIndex = request->addCodeGenTarget(SLANG_SHADER_HOST_CALLABLE); // Set the target flag to indicate that we want to compile all into a library. @@ -198,10 +225,13 @@ SlangResult ComTestContext::_runTest() request->setDebugInfoLevel(SLANG_DEBUG_INFO_LEVEL_STANDARD); // Add the translation unit - const int translationUnitIndex = request->addTranslationUnit(SLANG_SOURCE_LANGUAGE_SLANG, nullptr); + const int translationUnitIndex = + request->addTranslationUnit(SLANG_SOURCE_LANGUAGE_SLANG, nullptr); // Set the source file for the translation unit - request->addTranslationUnitSourceFile(translationUnitIndex, "tools/slang-unit-test/unit-test-com-host-callable.slang"); + request->addTranslationUnitSourceFile( + translationUnitIndex, + "tools/slang-unit-test/unit-test-com-host-callable.slang"); const SlangResult compileRes = request->compile(); @@ -214,8 +244,8 @@ SlangResult ComTestContext::_runTest() printf("%s", diagnostics); } - // Get the 'shared library' (note that this doesn't necessarily have to be implemented as a shared library - // it's just an interface to executable code). + // Get the 'shared library' (note that this doesn't necessarily have to be implemented as a + // shared library it's just an interface to executable code). ComPtr<ISlangSharedLibrary> sharedLibrary; SLANG_RETURN_ON_FAIL(request->getTargetHostCallable(0, sharedLibrary.writeRef())); @@ -305,7 +335,7 @@ SlangResult ComTestContext::_runTest() for (Index i = 0; i < 10; ++i) { SLANG_CHECK(*counterPtr == &counter); - + const auto v = nextCount(); SLANG_CHECK(v == i); } @@ -314,7 +344,7 @@ SlangResult ComTestContext::_runTest() return SLANG_OK; } -} // anonymous +} // namespace SLANG_UNIT_TEST(comHostCallable) { @@ -322,9 +352,9 @@ SLANG_UNIT_TEST(comHostCallable) // TODO(JS): // We can't currently run this test reliably on targets other than windows // Visual Studio DownstreamCompiler has support for 32 bit builds - // Other targets generally build for the native environment which is almost always 64 bit, + // Other targets generally build for the native environment which is almost always 64 bit, // and it requires other features to build/test 32 bit binaries on such systems. - // + // // So we disable for any 32 bit non MS target for now return; #endif @@ -332,6 +362,6 @@ SLANG_UNIT_TEST(comHostCallable) ComTestContext context(unitTestContext); const auto result = context.runTests(); - + SLANG_CHECK(SLANG_SUCCEEDED(result)); } diff --git a/tools/slang-unit-test/unit-test-command-line-args.cpp b/tools/slang-unit-test/unit-test-command-line-args.cpp index a4dc8a16c..febbeaddb 100644 --- a/tools/slang-unit-test/unit-test-command-line-args.cpp +++ b/tools/slang-unit-test/unit-test-command-line-args.cpp @@ -1,7 +1,6 @@ // unit-test-command-line-args.cpp #include "../../source/compiler-core/slang-command-line-args.h" - #include "tools/unit-test/slang-unit-test.h" using namespace Slang; @@ -17,9 +16,8 @@ SLANG_UNIT_TEST(commandLineArgs) DownstreamArgs downstreamArgs(context); DiagnosticSink sink(context->getSourceManager(), nullptr); - - const char* inArgs[] = - { + + const char* inArgs[] = { "-Xa...", "-blah", "10", @@ -28,13 +26,10 @@ SLANG_UNIT_TEST(commandLineArgs) args.setArgs(inArgs, SLANG_COUNT_OF(inArgs)); - SLANG_CHECK(SLANG_SUCCEEDED(downstreamArgs.stripDownstreamArgs(args, DownstreamArgs::Flag::AllowNewNames, &sink))); + SLANG_CHECK(SLANG_SUCCEEDED( + downstreamArgs.stripDownstreamArgs(args, DownstreamArgs::Flag::AllowNewNames, &sink))); - const char* aArgs[] = - { - "-blah", - "10" - }; + const char* aArgs[] = {"-blah", "10"}; SLANG_CHECK(downstreamArgs.getArgsByName("a").hasArgs(aArgs, SLANG_COUNT_OF(aArgs))); SLANG_CHECK(args.getArgCount() == 0 && sink.getErrorCount() == 0); @@ -47,8 +42,7 @@ SLANG_UNIT_TEST(commandLineArgs) DiagnosticSink sink(context->getSourceManager(), nullptr); - const char* inArgs[] = - { + const char* inArgs[] = { "-Xa...", "-blah", "10", @@ -56,13 +50,10 @@ SLANG_UNIT_TEST(commandLineArgs) args.setArgs(inArgs, SLANG_COUNT_OF(inArgs)); - SLANG_CHECK(SLANG_SUCCEEDED(downstreamArgs.stripDownstreamArgs(args, DownstreamArgs::Flag::AllowNewNames, &sink))); + SLANG_CHECK(SLANG_SUCCEEDED( + downstreamArgs.stripDownstreamArgs(args, DownstreamArgs::Flag::AllowNewNames, &sink))); - const char* aArgs[] = - { - "-blah", - "10" - }; + const char* aArgs[] = {"-blah", "10"}; SLANG_CHECK(downstreamArgs.getArgsByName("a").hasArgs(aArgs, SLANG_COUNT_OF(aArgs))); SLANG_CHECK(args.getArgCount() == 0 && sink.getErrorCount() == 0); @@ -76,8 +67,7 @@ SLANG_UNIT_TEST(commandLineArgs) DiagnosticSink sink(context->getSourceManager(), nullptr); - const char* inArgs[] = - { + const char* inArgs[] = { "-something", "andAnother", "-Xa...", @@ -93,24 +83,16 @@ SLANG_UNIT_TEST(commandLineArgs) args.setArgs(inArgs, SLANG_COUNT_OF(inArgs)); - SLANG_CHECK(SLANG_SUCCEEDED(downstreamArgs.stripDownstreamArgs(args, DownstreamArgs::Flag::AllowNewNames, &sink))); + SLANG_CHECK(SLANG_SUCCEEDED( + downstreamArgs.stripDownstreamArgs(args, DownstreamArgs::Flag::AllowNewNames, &sink))); - const char* aArgs[] = - { - "-blah", - "-Xb...", - "-hey", - "-X.", - "10" - }; + const char* aArgs[] = {"-blah", "-Xb...", "-hey", "-X.", "10"}; - const char* cArgs[] = - { + const char* cArgs[] = { "somethingForC", }; - const char* mainArgs[] = - { + const char* mainArgs[] = { "-something", "andAnother", }; @@ -120,6 +102,4 @@ SLANG_UNIT_TEST(commandLineArgs) SLANG_CHECK(args.hasArgs(mainArgs, SLANG_COUNT_OF(mainArgs)) && sink.getErrorCount() == 0); } - } - diff --git a/tools/slang-unit-test/unit-test-compression.cpp b/tools/slang-unit-test/unit-test-compression.cpp index 486a252b2..28f18997f 100644 --- a/tools/slang-unit-test/unit-test-compression.cpp +++ b/tools/slang-unit-test/unit-test-compression.cpp @@ -1,8 +1,7 @@ // unit-compression.cpp -#include "tools/unit-test/slang-unit-test.h" - -#include "../../source/core/slang-lz4-compression-system.h" #include "../../source/core/slang-deflate-compression-system.h" +#include "../../source/core/slang-lz4-compression-system.h" +#include "tools/unit-test/slang-unit-test.h" using namespace Slang; @@ -10,9 +9,9 @@ static ICompressionSystem* _getCompressionSystem(CompressionSystemType type) { switch (type) { - case CompressionSystemType::Deflate: return DeflateCompressionSystem::getSingleton(); break; - case CompressionSystemType::LZ4: return LZ4CompressionSystem::getSingleton(); break; - default: break; + case CompressionSystemType::Deflate: return DeflateCompressionSystem::getSingleton(); break; + case CompressionSystemType::LZ4: return LZ4CompressionSystem::getSingleton(); break; + default: break; } return nullptr; } @@ -23,7 +22,7 @@ SLANG_UNIT_TEST(compression) for (Index i = 0; i < Count(CompressionSystemType::CountOf); ++i) { ICompressionSystem* system = _getCompressionSystem(CompressionSystemType(i)); - + if (!system) { continue; @@ -37,13 +36,18 @@ SLANG_UNIT_TEST(compression) // Use the default style CompressionStyle style; - SLANG_CHECK(SLANG_SUCCEEDED(system->compress(&style, src, srcSize, compressedBlob.writeRef()))); - + SLANG_CHECK( + SLANG_SUCCEEDED(system->compress(&style, src, srcSize, compressedBlob.writeRef()))); + // Now lets decompress List<char> decompressedData; decompressedData.setCount(srcSize); - SLANG_CHECK(SLANG_SUCCEEDED(system->decompress(compressedBlob->getBufferPointer(), compressedBlob->getBufferSize(), srcSize, decompressedData.getBuffer()))); + SLANG_CHECK(SLANG_SUCCEEDED(system->decompress( + compressedBlob->getBufferPointer(), + compressedBlob->getBufferSize(), + srcSize, + decompressedData.getBuffer()))); SLANG_CHECK(::memcmp(src, decompressedData.getBuffer(), srcSize) == 0); } } diff --git a/tools/slang-unit-test/unit-test-crypto.cpp b/tools/slang-unit-test/unit-test-crypto.cpp index adb7b2218..244f7135b 100644 --- a/tools/slang-unit-test/unit-test-crypto.cpp +++ b/tools/slang-unit-test/unit-test-crypto.cpp @@ -1,7 +1,6 @@ // unit-test-sha1.cpp -#include "tools/unit-test/slang-unit-test.h" - #include "../../source/core/slang-crypto.h" +#include "tools/unit-test/slang-unit-test.h" using namespace Slang; @@ -29,7 +28,7 @@ SLANG_UNIT_TEST(crypto) SLANG_CHECK(Digest("0123456789abcdef").toString() == "0123456789abcdef"); Slang::ComPtr<ISlangBlob> blob = Digest("0123456789abcdef").toBlob(); - const uint8_t check[] = { 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef }; + const uint8_t check[] = {0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef}; SLANG_CHECK(blob->getBufferSize() == 8); SLANG_CHECK(::memcmp(blob->getBufferPointer(), check, 8) == 0); @@ -48,7 +47,8 @@ SLANG_UNIT_TEST(crypto) // One call to update() { MD5 sha1; - const String str("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."); + const String str("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod " + "tempor incididunt ut labore et dolore magna aliqua."); sha1.update(str.getBuffer(), str.getLength()); auto digest = sha1.finalize(); SLANG_CHECK(digest.toString() == "818c6e601a24f72750da0f6c9b8ebe28"); @@ -57,8 +57,10 @@ SLANG_UNIT_TEST(crypto) // Two calls to update() { MD5 sha1; - const String str1("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."); - const String str2("Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."); + const String str1("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod " + "tempor incididunt ut labore et dolore magna aliqua."); + const String str2("Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi " + "ut aliquip ex ea commodo consequat."); sha1.update(str1.getBuffer(), str1.getLength()); sha1.update(str2.getBuffer(), str2.getLength()); auto digest = sha1.finalize(); @@ -68,9 +70,12 @@ SLANG_UNIT_TEST(crypto) // compute() { SLANG_CHECK(MD5::compute(nullptr, 0).toString() == "d41d8cd98f00b204e9800998ecf8427e"); - const String str("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."); - SLANG_CHECK(MD5::compute(str.getBuffer(), str.getLength()).toString() == "818c6e601a24f72750da0f6c9b8ebe28"); - } + const String str("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod " + "tempor incididunt ut labore et dolore magna aliqua."); + SLANG_CHECK( + MD5::compute(str.getBuffer(), str.getLength()).toString() == + "818c6e601a24f72750da0f6c9b8ebe28"); + } // SHA1 @@ -84,7 +89,8 @@ SLANG_UNIT_TEST(crypto) // One call to update() { SHA1 sha1; - const String str("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."); + const String str("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod " + "tempor incididunt ut labore et dolore magna aliqua."); sha1.update(str.getBuffer(), str.getLength()); auto digest = sha1.finalize(); SLANG_CHECK(digest.toString() == "cca0871ecbe200379f0a1e4b46de177e2d62e655"); @@ -93,8 +99,10 @@ SLANG_UNIT_TEST(crypto) // Two calls to update() { SHA1 sha1; - const String str1("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."); - const String str2("Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."); + const String str1("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod " + "tempor incididunt ut labore et dolore magna aliqua."); + const String str2("Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi " + "ut aliquip ex ea commodo consequat."); sha1.update(str1.getBuffer(), str1.getLength()); sha1.update(str2.getBuffer(), str2.getLength()); auto digest = sha1.finalize(); @@ -103,9 +111,13 @@ SLANG_UNIT_TEST(crypto) // compute() { - SLANG_CHECK(SHA1::compute(nullptr, 0).toString() == "da39a3ee5e6b4b0d3255bfef95601890afd80709"); - const String str("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."); - SLANG_CHECK(SHA1::compute(str.getBuffer(), str.getLength()).toString() == "cca0871ecbe200379f0a1e4b46de177e2d62e655"); + SLANG_CHECK( + SHA1::compute(nullptr, 0).toString() == "da39a3ee5e6b4b0d3255bfef95601890afd80709"); + const String str("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod " + "tempor incididunt ut labore et dolore magna aliqua."); + SLANG_CHECK( + SHA1::compute(str.getBuffer(), str.getLength()).toString() == + "cca0871ecbe200379f0a1e4b46de177e2d62e655"); } // DigestBuider @@ -169,5 +181,5 @@ SLANG_UNIT_TEST(crypto) auto digest = builder.finalize(); SLANG_CHECK(digest.toString() == "4ae71336e44bf9bf79d2752e234818a5"); - } + } } diff --git a/tools/slang-unit-test/unit-test-decl-tree-reflection.cpp b/tools/slang-unit-test/unit-test-decl-tree-reflection.cpp index 89579c585..cbe0eb80b 100644 --- a/tools/slang-unit-test/unit-test-decl-tree-reflection.cpp +++ b/tools/slang-unit-test/unit-test-decl-tree-reflection.cpp @@ -1,15 +1,14 @@ // unit-test-translation-unit-import.cpp +#include "../../source/core/slang-io.h" +#include "../../source/core/slang-process.h" +#include "slang-com-ptr.h" #include "slang.h" +#include "tools/unit-test/slang-unit-test.h" #include <stdio.h> #include <stdlib.h> -#include "tools/unit-test/slang-unit-test.h" -#include "slang-com-ptr.h" -#include "../../source/core/slang-io.h" -#include "../../source/core/slang-process.h" - using namespace Slang; static String getTypeFullName(slang::TypeReflection* type) @@ -27,7 +26,8 @@ static void printRefl(slang::DeclReflection* refl, unsigned int level = 0) { std::cout << " "; } - std::cout<< "[" << names[(unsigned int)refl->getKind()] << "] (" << refl->getChildrenCount() << ")" << std::endl; + std::cout << "[" << names[(unsigned int)refl->getKind()] << "] (" << refl->getChildrenCount() + << ")" << std::endl; for (auto* child : refl->getChildren()) { @@ -101,16 +101,28 @@ SLANG_UNIT_TEST(declTreeReflection) SLANG_CHECK(globalSession->createSession(sessionDesc, session.writeRef()) == SLANG_OK); ComPtr<slang::IBlob> diagnosticBlob; - auto module = session->loadModuleFromSourceString("m", "m.slang", userSourceBody, diagnosticBlob.writeRef()); + auto module = session->loadModuleFromSourceString( + "m", + "m.slang", + userSourceBody, + diagnosticBlob.writeRef()); SLANG_CHECK(module != nullptr); ComPtr<slang::IEntryPoint> entryPoint; - module->findAndCheckEntryPoint("fragMain", SLANG_STAGE_FRAGMENT, entryPoint.writeRef(), diagnosticBlob.writeRef()); + module->findAndCheckEntryPoint( + "fragMain", + SLANG_STAGE_FRAGMENT, + entryPoint.writeRef(), + diagnosticBlob.writeRef()); SLANG_CHECK(entryPoint != nullptr); ComPtr<slang::IComponentType> compositeProgram; - slang::IComponentType* components[] = { module, entryPoint.get() }; - session->createCompositeComponentType(components, 2, compositeProgram.writeRef(), diagnosticBlob.writeRef()); + slang::IComponentType* components[] = {module, entryPoint.get()}; + session->createCompositeComponentType( + components, + 2, + compositeProgram.writeRef(), + diagnosticBlob.writeRef()); SLANG_CHECK(compositeProgram != nullptr); auto moduleDeclReflection = module->getModuleReflection(); @@ -137,7 +149,9 @@ SLANG_UNIT_TEST(declTreeReflection) // Second declaration should be a function auto secondDecl = moduleDeclReflection->getChild(1); SLANG_CHECK(secondDecl->getKind() == slang::DeclReflection::Kind::Func); - SLANG_CHECK(secondDecl->getChildrenCount() == 2); // Parameter declarations are children (return type is not) + SLANG_CHECK( + secondDecl->getChildrenCount() == + 2); // Parameter declarations are children (return type is not) { auto funcReflection = secondDecl->asFunction(); @@ -147,7 +161,9 @@ SLANG_UNIT_TEST(declTreeReflection) SLANG_CHECK(funcReflection->getParameterCount() == 2); SLANG_CHECK(UnownedStringSlice(funcReflection->getParameterByIndex(0)->getName()) == "x"); SLANG_CHECK(getTypeFullName(funcReflection->getParameterByIndex(0)->getType()) == "float"); - SLANG_CHECK(funcReflection->getParameterByIndex(0)->findModifier(slang::Modifier::NoDiff) != nullptr); + SLANG_CHECK( + funcReflection->getParameterByIndex(0)->findModifier(slang::Modifier::NoDiff) != + nullptr); SLANG_CHECK(UnownedStringSlice(funcReflection->getParameterByIndex(1)->getName()) == "y"); SLANG_CHECK(getTypeFullName(funcReflection->getParameterByIndex(1)->getType()) == "int"); @@ -161,13 +177,15 @@ SLANG_UNIT_TEST(declTreeReflection) auto result = userAttribute->getArgumentValueInt(0, &val); SLANG_CHECK(result == SLANG_OK); SLANG_CHECK(val == 1024); - SLANG_CHECK(funcReflection->findUserAttributeByName(globalSession.get(), "MyFuncProperty") == userAttribute); + SLANG_CHECK( + funcReflection->findUserAttributeByName(globalSession.get(), "MyFuncProperty") == + userAttribute); } // Third declaration should also be a function auto thirdDecl = moduleDeclReflection->getChild(2); SLANG_CHECK(thirdDecl->getKind() == slang::DeclReflection::Kind::Func); - SLANG_CHECK(thirdDecl->getChildrenCount() == 1); + SLANG_CHECK(thirdDecl->getChildrenCount() == 1); { auto funcReflection = thirdDecl->asFunction(); @@ -175,7 +193,9 @@ SLANG_UNIT_TEST(declTreeReflection) SLANG_CHECK(UnownedStringSlice(funcReflection->getName()) == "fragMain"); SLANG_CHECK(funcReflection->getParameterCount() == 1); SLANG_CHECK(UnownedStringSlice(funcReflection->getParameterByIndex(0)->getName()) == "pos"); - SLANG_CHECK(getTypeFullName(funcReflection->getParameterByIndex(0)->getType()) == "vector<float,4>"); + SLANG_CHECK( + getTypeFullName(funcReflection->getParameterByIndex(0)->getType()) == + "vector<float,4>"); } // Sixth declaration should be a generic struct @@ -187,9 +207,11 @@ SLANG_UNIT_TEST(declTreeReflection) SLANG_CHECK(UnownedStringSlice(typeParamT->getName()) == "T"); auto typeParamTConstraintCount = genericReflection->getTypeParameterConstraintCount(typeParamT); SLANG_CHECK(typeParamTConstraintCount == 2); - auto typeParamTConstraintType1 = genericReflection->getTypeParameterConstraintType(typeParamT, 0); + auto typeParamTConstraintType1 = + genericReflection->getTypeParameterConstraintType(typeParamT, 0); SLANG_CHECK(getTypeFullName(typeParamTConstraintType1) == "IArithmetic"); - auto typeParamTConstraintType2 = genericReflection->getTypeParameterConstraintType(typeParamT, 1); + auto typeParamTConstraintType2 = + genericReflection->getTypeParameterConstraintType(typeParamT, 1); SLANG_CHECK(getTypeFullName(typeParamTConstraintType2) == "IFloat"); auto innerStruct = genericReflection->getInnerDecl(); @@ -205,7 +227,7 @@ SLANG_UNIT_TEST(declTreeReflection) { auto type = compositeProgram->getLayout()->findTypeByName("MyType"); SLANG_CHECK(type != nullptr); - //SLANG_CHECK(type->getKind() == slang::DeclReflection::Kind::Struct); + // SLANG_CHECK(type->getKind() == slang::DeclReflection::Kind::Struct); SLANG_CHECK(UnownedStringSlice(type->getName()) == "MyType"); auto funcReflection = compositeProgram->getLayout()->findFunctionByNameInType(type, "f"); SLANG_CHECK(funcReflection != nullptr); @@ -220,7 +242,7 @@ SLANG_UNIT_TEST(declTreeReflection) { auto type = compositeProgram->getLayout()->findTypeByName("MyGenericType<half>"); SLANG_CHECK(type != nullptr); - //SLANG_CHECK(type->getKind() == slang::DeclReflection::Kind::Struct); + // SLANG_CHECK(type->getKind() == slang::DeclReflection::Kind::Struct); SLANG_CHECK(getTypeFullName(type) == "MyGenericType<half>"); auto funcReflection = compositeProgram->getLayout()->findFunctionByNameInType(type, "g"); SLANG_CHECK(funcReflection != nullptr); @@ -242,85 +264,98 @@ SLANG_UNIT_TEST(declTreeReflection) SLANG_CHECK(getTypeFullName(funcReflection->getParameterByIndex(0)->getType()) == "float"); SLANG_CHECK(UnownedStringSlice(funcReflection->getParameterByIndex(1)->getName()) == "y"); SLANG_CHECK(getTypeFullName(funcReflection->getParameterByIndex(1)->getType()) == "half"); - + // Access parent generic container from a specialized method. auto specializationInfo = funcReflection->getGenericContainer(); SLANG_CHECK(specializationInfo != nullptr); SLANG_CHECK(UnownedStringSlice(specializationInfo->getName()) == "h"); - SLANG_CHECK(specializationInfo->asDecl()->getKind() == slang::DeclReflection::Kind::Generic); + SLANG_CHECK( + specializationInfo->asDecl()->getKind() == slang::DeclReflection::Kind::Generic); // Check type parameters SLANG_CHECK(specializationInfo->getTypeParameterCount() == 1); auto typeParam = specializationInfo->getTypeParameter(0); SLANG_CHECK(UnownedStringSlice(typeParam->getName()) == "U"); // generic name - SLANG_CHECK(getTypeFullName(specializationInfo->getConcreteType(typeParam)) == "float"); // specialized type name under the context in which the generic is obtained + SLANG_CHECK( + getTypeFullName(specializationInfo->getConcreteType(typeParam)) == + "float"); // specialized type name under the context in which the generic is obtained SLANG_CHECK(specializationInfo->getTypeParameterConstraintCount(typeParam) == 0); // Go up another level to the generic struct specializationInfo = specializationInfo->getOuterGenericContainer(); SLANG_CHECK(specializationInfo != nullptr); SLANG_CHECK(UnownedStringSlice(specializationInfo->getName()) == "MyGenericType"); - SLANG_CHECK(specializationInfo->asDecl()->getKind() == slang::DeclReflection::Kind::Generic); + SLANG_CHECK( + specializationInfo->asDecl()->getKind() == slang::DeclReflection::Kind::Generic); // Check type parameters SLANG_CHECK(specializationInfo->getTypeParameterCount() == 1); typeParam = specializationInfo->getTypeParameter(0); SLANG_CHECK(UnownedStringSlice(typeParam->getName()) == "T"); // generic name - SLANG_CHECK(getTypeFullName(specializationInfo->getConcreteType(typeParam)) == "half"); // specialized type name under the context in which the generic is obtained + SLANG_CHECK( + getTypeFullName(specializationInfo->getConcreteType(typeParam)) == + "half"); // specialized type name under the context in which the generic is obtained SLANG_CHECK(specializationInfo->getTypeParameterConstraintCount(typeParam) == 2); // Query 'j' on the type 'half' funcReflection = compositeProgram->getLayout()->findFunctionByNameInType(type, "j<10>"); SLANG_CHECK(funcReflection != nullptr); SLANG_CHECK(UnownedStringSlice(funcReflection->getName()) == "j"); - + // Check the generic parameters specializationInfo = funcReflection->getGenericContainer(); SLANG_CHECK(specializationInfo != nullptr); SLANG_CHECK(UnownedStringSlice(specializationInfo->getName()) == "j"); - SLANG_CHECK(specializationInfo->asDecl()->getKind() == slang::DeclReflection::Kind::Generic); + SLANG_CHECK( + specializationInfo->asDecl()->getKind() == slang::DeclReflection::Kind::Generic); SLANG_CHECK(specializationInfo->getValueParameterCount() == 1); auto valueParam = specializationInfo->getValueParameter(0); SLANG_CHECK(UnownedStringSlice(valueParam->getName()) == "N"); // generic name SLANG_CHECK(specializationInfo->getConcreteIntVal(valueParam) == 10); } - + // Check specializeGeneric() and applySpecializations() { auto unspecializedType = compositeProgram->getLayout()->findTypeByName("MyGenericType"); SLANG_CHECK(unspecializedType != nullptr); auto halfType = compositeProgram->getLayout()->findTypeByName("half"); SLANG_CHECK(halfType != nullptr); - + slang::GenericReflection* genericContainer = unspecializedType->getGenericContainer(); SLANG_CHECK(genericContainer != nullptr); - //auto typeParamT = genericContainer->getTypeParameter(0); - + // auto typeParamT = genericContainer->getTypeParameter(0); + List<slang::GenericArgType> argTypes; List<slang::GenericArgReflection> args; argTypes.add(slang::GenericArgType::SLANG_GENERIC_ARG_TYPE); args.add({halfType}); auto specializedContainer = compositeProgram->getLayout()->specializeGeneric( - genericContainer, argTypes.getCount(), argTypes.getBuffer(), args.getBuffer(), nullptr); - + genericContainer, + argTypes.getCount(), + argTypes.getBuffer(), + args.getBuffer(), + nullptr); + SLANG_CHECK(specializedContainer != nullptr); auto specializedType = unspecializedType->applySpecializations(specializedContainer); SLANG_CHECK(specializedType != nullptr); SLANG_CHECK(getTypeFullName(specializedType) == "MyGenericType<half>"); - } - // Check specializeGeneric() and applySpecializations() on multiple levels (generic function nested in a generic struct) + // Check specializeGeneric() and applySpecializations() on multiple levels (generic function + // nested in a generic struct) { auto unspecializedType = compositeProgram->getLayout()->findTypeByName("MyGenericType"); - auto unspecializedFunc = compositeProgram->getLayout()->findFunctionByNameInType(unspecializedType, "j"); + auto unspecializedFunc = + compositeProgram->getLayout()->findFunctionByNameInType(unspecializedType, "j"); SLANG_CHECK(unspecializedFunc != nullptr); auto halfType = compositeProgram->getLayout()->findTypeByName("half"); SLANG_CHECK(halfType != nullptr); - + slang::GenericReflection* genericFuncContainer = unspecializedFunc->getGenericContainer(); SLANG_CHECK(genericFuncContainer != nullptr); - slang::GenericReflection* genericStructContainer = genericFuncContainer->getOuterGenericContainer(); + slang::GenericReflection* genericStructContainer = + genericFuncContainer->getOuterGenericContainer(); SLANG_CHECK(genericStructContainer != nullptr); // Specialize the outer container with half @@ -329,11 +364,16 @@ SLANG_UNIT_TEST(declTreeReflection) argTypes.add(slang::GenericArgType::SLANG_GENERIC_ARG_TYPE); args.add({halfType}); auto specializedStructContainer = compositeProgram->getLayout()->specializeGeneric( - genericStructContainer, argTypes.getCount(), argTypes.getBuffer(), args.getBuffer(), nullptr); + genericStructContainer, + argTypes.getCount(), + argTypes.getBuffer(), + args.getBuffer(), + nullptr); SLANG_CHECK(specializedStructContainer != nullptr); // apply T=half. N is still left unspecialized. - genericFuncContainer = genericFuncContainer->applySpecializations(specializedStructContainer); + genericFuncContainer = + genericFuncContainer->applySpecializations(specializedStructContainer); // Specialize the inner container with 10 separately.. argTypes.clear(); @@ -345,16 +385,21 @@ SLANG_UNIT_TEST(declTreeReflection) args.add(argN); auto specializedFuncContainer = compositeProgram->getLayout()->specializeGeneric( - genericFuncContainer, argTypes.getCount(), argTypes.getBuffer(), args.getBuffer(), nullptr); + genericFuncContainer, + argTypes.getCount(), + argTypes.getBuffer(), + args.getBuffer(), + nullptr); auto specializedFunc = unspecializedFunc->applySpecializations(specializedFuncContainer); SLANG_CHECK(specializedFunc != nullptr); - + // ------ check the specialized function auto specializationInfo = specializedFunc->getGenericContainer(); SLANG_CHECK(specializationInfo != nullptr); SLANG_CHECK(UnownedStringSlice(specializationInfo->getName()) == "j"); - SLANG_CHECK(specializationInfo->asDecl()->getKind() == slang::DeclReflection::Kind::Generic); + SLANG_CHECK( + specializationInfo->asDecl()->getKind() == slang::DeclReflection::Kind::Generic); SLANG_CHECK(specializationInfo->getValueParameterCount() == 1); auto valueParam = specializationInfo->getValueParameter(0); SLANG_CHECK(UnownedStringSlice(valueParam->getName()) == "N"); // generic name @@ -364,7 +409,8 @@ SLANG_UNIT_TEST(declTreeReflection) specializationInfo = specializationInfo->getOuterGenericContainer(); SLANG_CHECK(specializationInfo != nullptr); SLANG_CHECK(UnownedStringSlice(specializationInfo->getName()) == "MyGenericType"); - SLANG_CHECK(specializationInfo->asDecl()->getKind() == slang::DeclReflection::Kind::Generic); + SLANG_CHECK( + specializationInfo->asDecl()->getKind() == slang::DeclReflection::Kind::Generic); // Check type parameters SLANG_CHECK(specializationInfo->getTypeParameterCount() == 1); auto typeParam = specializationInfo->getTypeParameter(0); @@ -399,15 +445,16 @@ SLANG_UNIT_TEST(declTreeReflection) argTypes.add(floatType); argTypes.add(uintType); - slang::FunctionReflection* specializedFoo = unspecializedFoo->specializeWithArgTypes(argTypes.getCount(), argTypes.getBuffer()); + slang::FunctionReflection* specializedFoo = + unspecializedFoo->specializeWithArgTypes(argTypes.getCount(), argTypes.getBuffer()); SLANG_CHECK(specializedFoo != nullptr); - + SLANG_CHECK(getTypeFullName(specializedFoo->getReturnType()) == "float"); SLANG_CHECK(specializedFoo->getParameterCount() == 2); SLANG_CHECK(UnownedStringSlice(specializedFoo->getParameterByIndex(0)->getName()) == "t"); SLANG_CHECK(getTypeFullName(specializedFoo->getParameterByIndex(0)->getType()) == "float"); - + SLANG_CHECK(UnownedStringSlice(specializedFoo->getParameterByIndex(1)->getName()) == "u"); SLANG_CHECK(getTypeFullName(specializedFoo->getParameterByIndex(1)->getType()) == "uint"); } @@ -417,7 +464,8 @@ SLANG_UNIT_TEST(declTreeReflection) auto specializedType = compositeProgram->getLayout()->findTypeByName("MyGenericType<half>"); SLANG_CHECK(specializedType != nullptr); - auto unspecializedMethod = compositeProgram->getLayout()->findFunctionByNameInType(specializedType, "h"); + auto unspecializedMethod = + compositeProgram->getLayout()->findFunctionByNameInType(specializedType, "h"); SLANG_CHECK(unspecializedMethod != nullptr); // Specialize the method with float @@ -431,13 +479,12 @@ SLANG_UNIT_TEST(declTreeReflection) argTypes.add(floatType); argTypes.add(halfType); - auto specializedMethodWithFloat = unspecializedMethod->specializeWithArgTypes( - argTypes.getCount(), - argTypes.getBuffer()); + auto specializedMethodWithFloat = + unspecializedMethod->specializeWithArgTypes(argTypes.getCount(), argTypes.getBuffer()); SLANG_CHECK(specializedMethodWithFloat != nullptr); SLANG_CHECK(getTypeFullName(specializedMethodWithFloat->getReturnType()) == "float"); } - + // Check iterators { unsigned int count = 0; @@ -448,32 +495,35 @@ SLANG_UNIT_TEST(declTreeReflection) SLANG_CHECK(count == 9); count = 0; - for (auto* child : moduleDeclReflection->getChildrenOfKind<slang::DeclReflection::Kind::Func>()) + for (auto* child : + moduleDeclReflection->getChildrenOfKind<slang::DeclReflection::Kind::Func>()) { count++; } SLANG_CHECK(count == 3); count = 0; - for (auto* child : moduleDeclReflection->getChildrenOfKind<slang::DeclReflection::Kind::Struct>()) + for (auto* child : + moduleDeclReflection->getChildrenOfKind<slang::DeclReflection::Kind::Struct>()) { count++; } SLANG_CHECK(count == 2); count = 0; - for (auto* child : moduleDeclReflection->getChildrenOfKind<slang::DeclReflection::Kind::Generic>()) + for (auto* child : + moduleDeclReflection->getChildrenOfKind<slang::DeclReflection::Kind::Generic>()) { count++; } SLANG_CHECK(count == 2); count = 0; - for (auto* child : moduleDeclReflection->getChildrenOfKind<slang::DeclReflection::Kind::Namespace>()) + for (auto* child : + moduleDeclReflection->getChildrenOfKind<slang::DeclReflection::Kind::Namespace>()) { count++; } SLANG_CHECK(count == 1); } } - diff --git a/tools/slang-unit-test/unit-test-default-matrix-layout.cpp b/tools/slang-unit-test/unit-test-default-matrix-layout.cpp index 540036650..406432321 100644 --- a/tools/slang-unit-test/unit-test-default-matrix-layout.cpp +++ b/tools/slang-unit-test/unit-test-default-matrix-layout.cpp @@ -1,24 +1,23 @@ // unit-test-default-matrix-layout.cpp -#include <stdio.h> -#include <stdlib.h> - -#include "tools/unit-test/slang-unit-test.h" - -#include "slang.h" +#include "../../source/core/slang-list.h" #include "slang-com-helper.h" #include "slang-com-ptr.h" +#include "slang.h" +#include "tools/unit-test/slang-unit-test.h" -#include "../../source/core/slang-list.h" +#include <stdio.h> +#include <stdlib.h> -namespace { +namespace +{ using namespace Slang; struct DefaultMatrixLayoutTestContext { - DefaultMatrixLayoutTestContext(UnitTestContext* context): - m_unitTestContext(context) + DefaultMatrixLayoutTestContext(UnitTestContext* context) + : m_unitTestContext(context) { slang::IGlobalSession* slangSession = m_unitTestContext->slangGlobalSession; } @@ -36,7 +35,9 @@ struct DefaultMatrixLayoutTestContext sessionDesc.defaultMatrixLayoutMode = SLANG_MATRIX_LAYOUT_COLUMN_MAJOR; SLANG_RETURN_ON_FAIL(slangSession->createSession(sessionDesc, session.writeRef())); - auto module = session->loadModuleFromSourceString("mymodule", "mymodule.slang", + auto module = session->loadModuleFromSourceString( + "mymodule", + "mymodule.slang", R"( RWStructuredBuffer<float> output; [numthreads(1,1,1)] [shader("compute")] @@ -53,9 +54,10 @@ struct DefaultMatrixLayoutTestContext if (!entryPoint) return SLANG_FAIL; - slang::IComponentType* components[] = { module, entryPoint.get() }; + slang::IComponentType* components[] = {module, entryPoint.get()}; ComPtr<slang::IComponentType> composedProgram; - SLANG_RETURN_ON_FAIL(session->createCompositeComponentType(components, 2, composedProgram.writeRef())); + SLANG_RETURN_ON_FAIL( + session->createCompositeComponentType(components, 2, composedProgram.writeRef())); ComPtr<slang::IComponentType> linkedProgram; SLANG_RETURN_ON_FAIL(composedProgram->link(linkedProgram.writeRef())); @@ -72,13 +74,13 @@ struct DefaultMatrixLayoutTestContext UnitTestContext* m_unitTestContext; }; -} // anonymous +} // namespace SLANG_UNIT_TEST(defaultMatrixLayout) { DefaultMatrixLayoutTestContext context(unitTestContext); const auto result = context.runTests(); - + SLANG_CHECK(SLANG_SUCCEEDED(result)); } diff --git a/tools/slang-unit-test/unit-test-fcpw-compile.cpp b/tools/slang-unit-test/unit-test-fcpw-compile.cpp index 5e57ea55c..e36052b65 100644 --- a/tools/slang-unit-test/unit-test-fcpw-compile.cpp +++ b/tools/slang-unit-test/unit-test-fcpw-compile.cpp @@ -1,15 +1,14 @@ // unit-test-fcpw-compile.cpp +#include "../../source/core/slang-io.h" +#include "../../source/core/slang-process.h" +#include "slang-com-ptr.h" #include "slang.h" +#include "tools/unit-test/slang-unit-test.h" #include <stdio.h> #include <stdlib.h> -#include "tools/unit-test/slang-unit-test.h" -#include "slang-com-ptr.h" -#include "../../source/core/slang-io.h" -#include "../../source/core/slang-process.h" - using namespace Slang; // A test that uses the COM API to load and compile the FCPW library written by @@ -35,7 +34,8 @@ SLANG_UNIT_TEST(fcpwCompile) SLANG_CHECK(globalSession->createSession(sessionDesc, session.writeRef()) == SLANG_OK); ComPtr<slang::IBlob> diagnosticBlob; - auto module = session->loadModule("tests/fcpw/bvh-traversal.cs.slang", diagnosticBlob.writeRef()); + auto module = + session->loadModule("tests/fcpw/bvh-traversal.cs.slang", diagnosticBlob.writeRef()); SLANG_CHECK(module != nullptr); ComPtr<slang::IEntryPoint> entryPoint; @@ -43,8 +43,12 @@ SLANG_UNIT_TEST(fcpwCompile) SLANG_CHECK(entryPoint != nullptr); ComPtr<slang::IComponentType> compositeProgram; - slang::IComponentType* components[] = { module, entryPoint.get() }; - session->createCompositeComponentType(components, 2, compositeProgram.writeRef(), diagnosticBlob.writeRef()); + slang::IComponentType* components[] = {module, entryPoint.get()}; + session->createCompositeComponentType( + components, + 2, + compositeProgram.writeRef(), + diagnosticBlob.writeRef()); SLANG_CHECK(compositeProgram != nullptr); ComPtr<slang::IComponentType> linkedProgram; @@ -56,4 +60,3 @@ SLANG_UNIT_TEST(fcpwCompile) SLANG_CHECK(code != nullptr); SLANG_CHECK(code->getBufferSize() != 0); } - diff --git a/tools/slang-unit-test/unit-test-file-system.cpp b/tools/slang-unit-test/unit-test-file-system.cpp index 05892b10b..46061e2d8 100644 --- a/tools/slang-unit-test/unit-test-file-system.cpp +++ b/tools/slang-unit-test/unit-test-file-system.cpp @@ -1,530 +1,572 @@ // unit-test-file-system.cpp +#include "../../source/core/slang-castable.h" +#include "../../source/core/slang-deflate-compression-system.h" #include "../../source/core/slang-file-system.h" - +#include "../../source/core/slang-io.h" +#include "../../source/core/slang-lz4-compression-system.h" +#include "../../source/core/slang-memory-file-system.h" #include "../../source/core/slang-riff-file-system.h" #include "../../source/core/slang-zip-file-system.h" - -#include "../../source/core/slang-memory-file-system.h" - -#include "../../source/core/slang-deflate-compression-system.h" -#include "../../source/core/slang-lz4-compression-system.h" -#include "../../source/core/slang-castable.h" - -#include "../../source/core/slang-io.h" - #include "tools/unit-test/slang-unit-test.h" using namespace Slang; -namespace { // anonymous +namespace +{ // anonymous enum class FileSystemType { - Zip, - RiffUncompressed, - RiffDeflate, - RiffLZ4, - Memory, - Relative, - CountOf, + Zip, + RiffUncompressed, + RiffDeflate, + RiffLZ4, + Memory, + Relative, + CountOf, }; -struct Entry +struct Entry { - typedef Entry ThisType; + typedef Entry ThisType; - bool operator<(const ThisType& rhs) const { return path < rhs.path; } - bool operator==(const ThisType& rhs) const { return path == rhs.path && type == rhs.type; } - bool operator!=(const ThisType& rhs) const { return !(*this == rhs); } + bool operator<(const ThisType& rhs) const { return path < rhs.path; } + bool operator==(const ThisType& rhs) const { return path == rhs.path && type == rhs.type; } + bool operator!=(const ThisType& rhs) const { return !(*this == rhs); } - SlangPathType type; - String path; + SlangPathType type; + String path; }; -} // anonymous +} // namespace -static SlangResult _checkFile(ISlangFileSystemExt* fileSystem, const char* path, const UnownedStringSlice& contentsSlice) +static SlangResult _checkFile( + ISlangFileSystemExt* fileSystem, + const char* path, + const UnownedStringSlice& contentsSlice) { - SlangPathType pathType; - SLANG_RETURN_ON_FAIL(fileSystem->getPathType(path, &pathType)); - - if (pathType != SLANG_PATH_TYPE_FILE) - { - return SLANG_FAIL; - } - - ComPtr<ISlangBlob> blob; - SLANG_RETURN_ON_FAIL(fileSystem->loadFile(path, blob.writeRef())); - - if (blob->getBufferSize() != contentsSlice.getLength()) - { - return SLANG_FAIL; - } - if (contentsSlice != UnownedStringSlice((const char*)blob->getBufferPointer(), blob->getBufferSize())) - { - return SLANG_FAIL; - } - return SLANG_OK; + SlangPathType pathType; + SLANG_RETURN_ON_FAIL(fileSystem->getPathType(path, &pathType)); + + if (pathType != SLANG_PATH_TYPE_FILE) + { + return SLANG_FAIL; + } + + ComPtr<ISlangBlob> blob; + SLANG_RETURN_ON_FAIL(fileSystem->loadFile(path, blob.writeRef())); + + if (blob->getBufferSize() != contentsSlice.getLength()) + { + return SLANG_FAIL; + } + if (contentsSlice != + UnownedStringSlice((const char*)blob->getBufferPointer(), blob->getBufferSize())) + { + return SLANG_FAIL; + } + return SLANG_OK; } -static SlangResult _checkFile(ISlangMutableFileSystem* fileSystem, const char* path, const char* contents) +static SlangResult _checkFile( + ISlangMutableFileSystem* fileSystem, + const char* path, + const char* contents) { - return _checkFile(fileSystem, path, UnownedStringSlice(contents)); + return _checkFile(fileSystem, path, UnownedStringSlice(contents)); } static SlangResult _checkDirectoryExists(ISlangFileSystemExt* fileSystem, const char* path) { - SlangPathType pathType; - SLANG_RETURN_ON_FAIL(fileSystem->getPathType(path, &pathType)); - - if (pathType != SLANG_PATH_TYPE_DIRECTORY) - { - return SLANG_FAIL; - } - return SLANG_OK; + SlangPathType pathType; + SLANG_RETURN_ON_FAIL(fileSystem->getPathType(path, &pathType)); + + if (pathType != SLANG_PATH_TYPE_DIRECTORY) + { + return SLANG_FAIL; + } + return SLANG_OK; } -static SlangResult _createAndCheckFile(ISlangMutableFileSystem* fileSystem, const char* path, const char* contents) +static SlangResult _createAndCheckFile( + ISlangMutableFileSystem* fileSystem, + const char* path, + const char* contents) { - UnownedStringSlice contentsSlice(contents); + UnownedStringSlice contentsSlice(contents); - SLANG_RETURN_ON_FAIL(fileSystem->saveFile(path, contentsSlice.begin(), contentsSlice.getLength())); - SLANG_RETURN_ON_FAIL(_checkFile(fileSystem, path, contentsSlice)); + SLANG_RETURN_ON_FAIL( + fileSystem->saveFile(path, contentsSlice.begin(), contentsSlice.getLength())); + SLANG_RETURN_ON_FAIL(_checkFile(fileSystem, path, contentsSlice)); - // Delete it - SLANG_RETURN_ON_FAIL(fileSystem->remove(path)); + // Delete it + SLANG_RETURN_ON_FAIL(fileSystem->remove(path)); - // Check it's gone - SlangPathType pathType; - if (SLANG_SUCCEEDED(fileSystem->getPathType(path, &pathType))) - { - return SLANG_FAIL; - } + // Check it's gone + SlangPathType pathType; + if (SLANG_SUCCEEDED(fileSystem->getPathType(path, &pathType))) + { + return SLANG_FAIL; + } - // Save as a blob - ComPtr<ISlangBlob> blob = RawBlob::create(contentsSlice.begin(), contentsSlice.getLength()); + // Save as a blob + ComPtr<ISlangBlob> blob = RawBlob::create(contentsSlice.begin(), contentsSlice.getLength()); - SLANG_RETURN_ON_FAIL(fileSystem->saveFileBlob(path, blob)); - SLANG_RETURN_ON_FAIL(_checkFile(fileSystem, path, contentsSlice)); + SLANG_RETURN_ON_FAIL(fileSystem->saveFileBlob(path, blob)); + SLANG_RETURN_ON_FAIL(_checkFile(fileSystem, path, contentsSlice)); - return SLANG_OK; + return SLANG_OK; } static bool _areEqual(ISlangBlob* a, ISlangBlob* b) { - if (a == b) - { - return true; - } - if ((!a || !b) || (a->getBufferSize() != b->getBufferSize())) - { - return false; - } - - return ::memcmp(a->getBufferPointer(), b->getBufferPointer(), a->getBufferSize()) == 0; + if (a == b) + { + return true; + } + if ((!a || !b) || (a->getBufferSize() != b->getBufferSize())) + { + return false; + } + + return ::memcmp(a->getBufferPointer(), b->getBufferPointer(), a->getBufferSize()) == 0; } -static SlangResult _checkCanonical(ISlangMutableFileSystem* fileSystem, const char*const* paths, Count count) +static SlangResult _checkCanonical( + ISlangMutableFileSystem* fileSystem, + const char* const* paths, + Count count) { - if (count <= 0) - { - return SLANG_FAIL; - } - - // The path has to exist to something for canonicalization to be relied upon - SlangPathType pathType; - SLANG_RETURN_ON_FAIL(fileSystem->getPathType(paths[0], &pathType)); - - String canonicalPath; - { - ComPtr<ISlangBlob> blob; - SLANG_RETURN_ON_FAIL(fileSystem->getPath(PathKind::Canonical, paths[0], blob.writeRef())); - canonicalPath = StringUtil::getString(blob); - } - - // The canonicalized path must point to the same thing - SlangPathType canonicalPathType; - SLANG_RETURN_ON_FAIL(fileSystem->getPathType(canonicalPath.getBuffer(), &canonicalPathType)); - - if (canonicalPathType != pathType) - { - return SLANG_FAIL; - } - - // If they are the file, being hte same file, they must hold the same data... - if (pathType == SLANG_PATH_TYPE_FILE) - { - ComPtr<ISlangBlob> blob; - ComPtr<ISlangBlob> canonicalPathBlob; - SLANG_RETURN_ON_FAIL(fileSystem->loadFile(paths[0], blob.writeRef())); - SLANG_RETURN_ON_FAIL(fileSystem->loadFile(canonicalPath.getBuffer(), canonicalPathBlob.writeRef())); - - if (!_areEqual(blob, canonicalPathBlob)) - { - return SLANG_FAIL; - } - } - - for (Index i = 1; i < count; ++i) - { - ComPtr<ISlangBlob> blob; - SLANG_RETURN_ON_FAIL(fileSystem->getPath(PathKind::Canonical, paths[i], blob.writeRef())); - const auto checkPath = StringUtil::getString(blob); - - if (checkPath != canonicalPath) - { - return SLANG_FAIL; - } - } - - return SLANG_OK; + if (count <= 0) + { + return SLANG_FAIL; + } + + // The path has to exist to something for canonicalization to be relied upon + SlangPathType pathType; + SLANG_RETURN_ON_FAIL(fileSystem->getPathType(paths[0], &pathType)); + + String canonicalPath; + { + ComPtr<ISlangBlob> blob; + SLANG_RETURN_ON_FAIL(fileSystem->getPath(PathKind::Canonical, paths[0], blob.writeRef())); + canonicalPath = StringUtil::getString(blob); + } + + // The canonicalized path must point to the same thing + SlangPathType canonicalPathType; + SLANG_RETURN_ON_FAIL(fileSystem->getPathType(canonicalPath.getBuffer(), &canonicalPathType)); + + if (canonicalPathType != pathType) + { + return SLANG_FAIL; + } + + // If they are the file, being hte same file, they must hold the same data... + if (pathType == SLANG_PATH_TYPE_FILE) + { + ComPtr<ISlangBlob> blob; + ComPtr<ISlangBlob> canonicalPathBlob; + SLANG_RETURN_ON_FAIL(fileSystem->loadFile(paths[0], blob.writeRef())); + SLANG_RETURN_ON_FAIL( + fileSystem->loadFile(canonicalPath.getBuffer(), canonicalPathBlob.writeRef())); + + if (!_areEqual(blob, canonicalPathBlob)) + { + return SLANG_FAIL; + } + } + + for (Index i = 1; i < count; ++i) + { + ComPtr<ISlangBlob> blob; + SLANG_RETURN_ON_FAIL(fileSystem->getPath(PathKind::Canonical, paths[i], blob.writeRef())); + const auto checkPath = StringUtil::getString(blob); + + if (checkPath != canonicalPath) + { + return SLANG_FAIL; + } + } + + return SLANG_OK; } static SlangResult _createAndCheckDirectory(ISlangMutableFileSystem* fileSystem, const char* path) { - SLANG_RETURN_ON_FAIL(fileSystem->createDirectory(path)); + SLANG_RETURN_ON_FAIL(fileSystem->createDirectory(path)); - SlangPathType pathType; - SLANG_RETURN_ON_FAIL(fileSystem->getPathType(path, &pathType)); + SlangPathType pathType; + SLANG_RETURN_ON_FAIL(fileSystem->getPathType(path, &pathType)); - if (pathType != SLANG_PATH_TYPE_DIRECTORY) - { - return SLANG_FAIL; - } + if (pathType != SLANG_PATH_TYPE_DIRECTORY) + { + return SLANG_FAIL; + } - return SLANG_OK; + return SLANG_OK; } static void _entryCallback(SlangPathType pathType, const char* name, void* userData) { - List<Entry>& out = *(List<Entry>*)userData; - out.add(Entry{pathType, name}); + List<Entry>& out = *(List<Entry>*)userData; + out.add(Entry{pathType, name}); } -static SlangResult _enumeratePath(ISlangFileSystemExt* fileSystem, const char* path, const ConstArrayView<Entry>& entries) +static SlangResult _enumeratePath( + ISlangFileSystemExt* fileSystem, + const char* path, + const ConstArrayView<Entry>& entries) { - List<Entry> contents; - - SLANG_RETURN_ON_FAIL(fileSystem->enumeratePathContents(path, _entryCallback, (void*)&contents)); - - contents.sort(); - - if (contents.getArrayView() != entries) - { - return SLANG_FAIL; - } - - return SLANG_OK; + List<Entry> contents; + + SLANG_RETURN_ON_FAIL(fileSystem->enumeratePathContents(path, _entryCallback, (void*)&contents)); + + contents.sort(); + + if (contents.getArrayView() != entries) + { + return SLANG_FAIL; + } + + return SLANG_OK; } -static SlangResult _checkSimplifiedPath(ISlangFileSystemExt* fileSystem, const char* path, const char* normalPath) +static SlangResult _checkSimplifiedPath( + ISlangFileSystemExt* fileSystem, + const char* path, + const char* normalPath) { - ComPtr<ISlangBlob> simplifiedPathBlob; - SLANG_RETURN_ON_FAIL(fileSystem->getPath(PathKind::Simplified, path, simplifiedPathBlob.writeRef())); + ComPtr<ISlangBlob> simplifiedPathBlob; + SLANG_RETURN_ON_FAIL( + fileSystem->getPath(PathKind::Simplified, path, simplifiedPathBlob.writeRef())); - auto simplifiedPath = StringUtil::getString(simplifiedPathBlob); + auto simplifiedPath = StringUtil::getString(simplifiedPathBlob); - if (simplifiedPath != normalPath) - { - return SLANG_FAIL; - } + if (simplifiedPath != normalPath) + { + return SLANG_FAIL; + } - return SLANG_OK; + return SLANG_OK; } -SlangResult _appendPathEntries(ISlangFileSystemExt* fileSystem, const char* inBasePath, List<Entry>& outEntries) +SlangResult _appendPathEntries( + ISlangFileSystemExt* fileSystem, + const char* inBasePath, + List<Entry>& outEntries) { - const UnownedStringSlice basePath(inBasePath); - if (basePath == toSlice(".") || basePath.getLength() == 0) - { - // We don't need to append path prefixes if we are at the root. - SLANG_RETURN_ON_FAIL(fileSystem->enumeratePathContents(inBasePath, _entryCallback, (void*)&outEntries)); - } - else - { - const Index startIndex = outEntries.getCount(); - SLANG_RETURN_ON_FAIL(fileSystem->enumeratePathContents(inBasePath, _entryCallback, (void*)&outEntries)); - - const String basePathString(basePath); - - // we need to fix all of the added paths to make absolute - const Count count = outEntries.getCount(); - for (Index i = startIndex; i < count; ++i) - { - auto& entry = outEntries[i]; - entry.path = Path::combine(basePathString, entry.path); - } - } - - return SLANG_OK; + const UnownedStringSlice basePath(inBasePath); + if (basePath == toSlice(".") || basePath.getLength() == 0) + { + // We don't need to append path prefixes if we are at the root. + SLANG_RETURN_ON_FAIL( + fileSystem->enumeratePathContents(inBasePath, _entryCallback, (void*)&outEntries)); + } + else + { + const Index startIndex = outEntries.getCount(); + SLANG_RETURN_ON_FAIL( + fileSystem->enumeratePathContents(inBasePath, _entryCallback, (void*)&outEntries)); + + const String basePathString(basePath); + + // we need to fix all of the added paths to make absolute + const Count count = outEntries.getCount(); + for (Index i = startIndex; i < count; ++i) + { + auto& entry = outEntries[i]; + entry.path = Path::combine(basePathString, entry.path); + } + } + + return SLANG_OK; } -static SlangResult _getAllEntries(ISlangFileSystemExt* fileSystem, const char* inBasePath, List<Entry>& outEntries) +static SlangResult _getAllEntries( + ISlangFileSystemExt* fileSystem, + const char* inBasePath, + List<Entry>& outEntries) { - outEntries.clear(); - - // Simplify the base - auto basePath = Path::simplify(inBasePath); - - _appendPathEntries(fileSystem, basePath.getBuffer(), outEntries); - - for (Index i = 0; i < outEntries.getCount(); ++i) - { - // We need to make a copy as outEntries is mutated - const Entry entry = outEntries[i]; - if (entry.type == SLANG_PATH_TYPE_DIRECTORY) - { - _appendPathEntries(fileSystem, entry.path.getBuffer(), outEntries); - } - } - - // Sort to remove issues with traversal ordering - outEntries.sort(); - return SLANG_OK; + outEntries.clear(); + + // Simplify the base + auto basePath = Path::simplify(inBasePath); + + _appendPathEntries(fileSystem, basePath.getBuffer(), outEntries); + + for (Index i = 0; i < outEntries.getCount(); ++i) + { + // We need to make a copy as outEntries is mutated + const Entry entry = outEntries[i]; + if (entry.type == SLANG_PATH_TYPE_DIRECTORY) + { + _appendPathEntries(fileSystem, entry.path.getBuffer(), outEntries); + } + } + + // Sort to remove issues with traversal ordering + outEntries.sort(); + return SLANG_OK; } static SlangResult _checkEqual(ISlangFileSystemExt* a, ISlangFileSystemExt* b) { - List<Entry> aEntries, bEntries; + List<Entry> aEntries, bEntries; - SLANG_RETURN_ON_FAIL(_getAllEntries(a, ".", aEntries)); - SLANG_RETURN_ON_FAIL(_getAllEntries(b, ".", bEntries)); + SLANG_RETURN_ON_FAIL(_getAllEntries(a, ".", aEntries)); + SLANG_RETURN_ON_FAIL(_getAllEntries(b, ".", bEntries)); - if (aEntries != bEntries) - { - return SLANG_FAIL; - } + if (aEntries != bEntries) + { + return SLANG_FAIL; + } - // For all the files check the contents is the same + // For all the files check the contents is the same - for (const auto& entry : aEntries) - { - if (entry.type != SLANG_PATH_TYPE_FILE) - { - continue; - } + for (const auto& entry : aEntries) + { + if (entry.type != SLANG_PATH_TYPE_FILE) + { + continue; + } - ComPtr<ISlangBlob> blobA, blobB; + ComPtr<ISlangBlob> blobA, blobB; - SLANG_RETURN_ON_FAIL(a->loadFile(entry.path.getBuffer(), blobA.writeRef())); - SLANG_RETURN_ON_FAIL(b->loadFile(entry.path.getBuffer(), blobB.writeRef())); + SLANG_RETURN_ON_FAIL(a->loadFile(entry.path.getBuffer(), blobA.writeRef())); + SLANG_RETURN_ON_FAIL(b->loadFile(entry.path.getBuffer(), blobB.writeRef())); - if (blobA->getBufferSize() != blobB->getBufferSize()) - { - return SLANG_FAIL; - } + if (blobA->getBufferSize() != blobB->getBufferSize()) + { + return SLANG_FAIL; + } - if (::memcmp(blobA->getBufferPointer(), blobB->getBufferPointer(), blobA->getBufferSize()) != 0) - { - return SLANG_FAIL; - } - } + if (::memcmp( + blobA->getBufferPointer(), + blobB->getBufferPointer(), + blobA->getBufferSize()) != 0) + { + return SLANG_FAIL; + } + } - return SLANG_OK; + return SLANG_OK; } -static SlangResult _createFileSystem(FileSystemType type, ComPtr<ISlangMutableFileSystem>& outFileSystem) +static SlangResult _createFileSystem( + FileSystemType type, + ComPtr<ISlangMutableFileSystem>& outFileSystem) { - outFileSystem.setNull(); - switch (type) - { - case FileSystemType::Zip: return ZipFileSystem::create(outFileSystem); - case FileSystemType::RiffUncompressed: outFileSystem = new RiffFileSystem(nullptr); break; - case FileSystemType::RiffDeflate: outFileSystem = new RiffFileSystem(DeflateCompressionSystem::getSingleton()); break; - case FileSystemType::RiffLZ4: outFileSystem = new RiffFileSystem(LZ4CompressionSystem::getSingleton()); break; - case FileSystemType::Memory: outFileSystem = new MemoryFileSystem; break; - case FileSystemType::Relative: - { - ComPtr<ISlangMutableFileSystem> memoryFileSystem(new MemoryFileSystem); - memoryFileSystem->createDirectory("base"); - - outFileSystem = new RelativeFileSystem(memoryFileSystem, "base"); - break; - } - } - - return outFileSystem ? SLANG_OK : SLANG_FAIL; + outFileSystem.setNull(); + switch (type) + { + case FileSystemType::Zip: return ZipFileSystem::create(outFileSystem); + case FileSystemType::RiffUncompressed: outFileSystem = new RiffFileSystem(nullptr); break; + case FileSystemType::RiffDeflate: + outFileSystem = new RiffFileSystem(DeflateCompressionSystem::getSingleton()); + break; + case FileSystemType::RiffLZ4: + outFileSystem = new RiffFileSystem(LZ4CompressionSystem::getSingleton()); + break; + case FileSystemType::Memory: outFileSystem = new MemoryFileSystem; break; + case FileSystemType::Relative: + { + ComPtr<ISlangMutableFileSystem> memoryFileSystem(new MemoryFileSystem); + memoryFileSystem->createDirectory("base"); + + outFileSystem = new RelativeFileSystem(memoryFileSystem, "base"); + break; + } + } + + return outFileSystem ? SLANG_OK : SLANG_FAIL; } static SlangResult _testImplicitDirectory(FileSystemType type) { - ComPtr<ISlangMutableFileSystem> fileSystem; - SLANG_RETURN_ON_FAIL(_createFileSystem(type, fileSystem)); + ComPtr<ISlangMutableFileSystem> fileSystem; + SLANG_RETURN_ON_FAIL(_createFileSystem(type, fileSystem)); - const char contents3[] = "Some text...."; + const char contents3[] = "Some text...."; - SLANG_RETURN_ON_FAIL(fileSystem->saveFile("implicit-path/file2.txt", contents3, SLANG_COUNT_OF(contents3))); + SLANG_RETURN_ON_FAIL( + fileSystem->saveFile("implicit-path/file2.txt", contents3, SLANG_COUNT_OF(contents3))); - { - SlangPathType pathType; - SLANG_RETURN_ON_FAIL(fileSystem->getPathType("implicit-path", &pathType)); + { + SlangPathType pathType; + SLANG_RETURN_ON_FAIL(fileSystem->getPathType("implicit-path", &pathType)); - SLANG_CHECK(pathType == SLANG_PATH_TYPE_DIRECTORY); + SLANG_CHECK(pathType == SLANG_PATH_TYPE_DIRECTORY); - auto checkEntries = [&]() -> SlangResult - { - List<Entry> entries; - SLANG_RETURN_ON_FAIL(_getAllEntries(fileSystem, "implicit-path", entries)); + auto checkEntries = [&]() -> SlangResult + { + List<Entry> entries; + SLANG_RETURN_ON_FAIL(_getAllEntries(fileSystem, "implicit-path", entries)); - // It contains a file - SLANG_CHECK(entries.getCount() == 1); + // It contains a file + SLANG_CHECK(entries.getCount() == 1); - for (const auto& entry : entries) - { - // All of these should exist - SlangPathType pathType; - SLANG_RETURN_ON_FAIL(fileSystem->getPathType(entry.path.getBuffer(), &pathType)); - } - return SLANG_OK; - }; + for (const auto& entry : entries) + { + // All of these should exist + SlangPathType pathType; + SLANG_RETURN_ON_FAIL(fileSystem->getPathType(entry.path.getBuffer(), &pathType)); + } + return SLANG_OK; + }; - SLANG_RETURN_ON_FAIL(checkEntries()); + SLANG_RETURN_ON_FAIL(checkEntries()); - // Make an explicit path, and see whe have the same results - fileSystem->createDirectory("implicit-path"); + // Make an explicit path, and see whe have the same results + fileSystem->createDirectory("implicit-path"); - SLANG_RETURN_ON_FAIL(checkEntries()); - } + SLANG_RETURN_ON_FAIL(checkEntries()); + } - return SLANG_OK; + return SLANG_OK; } static SlangResult _test(FileSystemType type) { - ComPtr<ISlangMutableFileSystem> fileSystem; - SLANG_RETURN_ON_FAIL(_createFileSystem(type, fileSystem)); - - const auto aText = "someText"; - const auto bText = "A longer bit of text...."; - const auto d_aText = "Some more silly stuff"; - const auto d_bText = "Lets go!"; - - SLANG_RETURN_ON_FAIL(_createAndCheckFile(fileSystem, "a", aText)); - SLANG_RETURN_ON_FAIL(_createAndCheckFile(fileSystem, "b", bText)); - - SLANG_RETURN_ON_FAIL(_createAndCheckDirectory(fileSystem, "d")); - SLANG_RETURN_ON_FAIL(_createAndCheckFile(fileSystem, "d/a", d_aText)); - SLANG_RETURN_ON_FAIL(_createAndCheckFile(fileSystem, "d\\b", d_bText)); - - // Try and absolute path - SLANG_RETURN_ON_FAIL(_checkFile(fileSystem, "/a", aText)); - SLANG_RETURN_ON_FAIL(_checkFile(fileSystem, "/b", bText)); - SLANG_RETURN_ON_FAIL(_checkFile(fileSystem, "/d/a", d_aText)); - SLANG_RETURN_ON_FAIL(_checkFile(fileSystem, "/d\\b", d_bText)); - - - // Check canonical on files - { - const char* paths[] = { "a", "/a", "./a", "d/../a", ".\\d/.\\..\\a" }; - SLANG_RETURN_ON_FAIL(_checkCanonical(fileSystem, paths, SLANG_COUNT_OF(paths))); - } - - { - const char* paths[] = { "/d/b", "d/./b" }; - SLANG_RETURN_ON_FAIL(_checkCanonical(fileSystem, paths, SLANG_COUNT_OF(paths))); - } - - // Check canonical on directories - { - const char* paths[] = { ".", "/", "/d/..", "d/.." }; - SLANG_RETURN_ON_FAIL(_checkCanonical(fileSystem, paths, SLANG_COUNT_OF(paths))); - } - - { - const char* paths[] = { "d", "./d", "/d", "/d/./../d" }; - SLANG_RETURN_ON_FAIL(_checkCanonical(fileSystem, paths, SLANG_COUNT_OF(paths))); - } - - // Lets find all the files in the directory - - { - const Entry entries[] = { {SLANG_PATH_TYPE_FILE, "a" }, {SLANG_PATH_TYPE_FILE, "b" } }; - SLANG_RETURN_ON_FAIL(_enumeratePath(fileSystem, "d", makeConstArrayView(entries))); - } - - { - const Entry entries[] = { {SLANG_PATH_TYPE_FILE, "a" }, {SLANG_PATH_TYPE_FILE, "b" }, {SLANG_PATH_TYPE_DIRECTORY, "d" } }; - SLANG_RETURN_ON_FAIL(_enumeratePath(fileSystem, ".", makeConstArrayView(entries))); - - // Let's check that / and \ works for the root directory - SLANG_RETURN_ON_FAIL(_enumeratePath(fileSystem, "/", makeConstArrayView(entries))); - SLANG_RETURN_ON_FAIL(_enumeratePath(fileSystem, "\\", makeConstArrayView(entries))); - } - - // Check the root directory exists - { - SLANG_RETURN_ON_FAIL(_checkDirectoryExists(fileSystem, ".")); - SLANG_RETURN_ON_FAIL(_checkDirectoryExists(fileSystem, "/")); - SLANG_RETURN_ON_FAIL(_checkDirectoryExists(fileSystem, "\\")); - } - - { - SLANG_RETURN_ON_FAIL(_checkSimplifiedPath(fileSystem, "d/../a", "a")); - } - - - // If we have an archive file system check out it's behavior - if (IArchiveFileSystem* archiveFileSystem = as<IArchiveFileSystem>(fileSystem)) - { - // Load and check its okay - - ComPtr<ISlangBlob> archiveBlob; - SLANG_RETURN_ON_FAIL(archiveFileSystem->storeArchive(false, archiveBlob.writeRef())); - - ComPtr<ISlangFileSystemExt> loadedFileSystem; - SLANG_RETURN_ON_FAIL(loadArchiveFileSystem(archiveBlob->getBufferPointer(), archiveBlob->getBufferSize(), loadedFileSystem)); - - // Check the file systems contents are the same - SLANG_RETURN_ON_FAIL(_checkEqual(loadedFileSystem, fileSystem)); - } - - SLANG_RETURN_ON_FAIL(fileSystem->remove("d/a")); - { - const Entry entries[] = { {SLANG_PATH_TYPE_FILE, "b" } }; - SLANG_RETURN_ON_FAIL(_enumeratePath(fileSystem, "d", makeConstArrayView(entries))); - } - SLANG_RETURN_ON_FAIL(fileSystem->remove("d\\b")); - { - SLANG_RETURN_ON_FAIL(_enumeratePath(fileSystem, "d", makeConstArrayView((const Entry*)nullptr, 0))); - } - - // If it's removed it can't be removed again - SLANG_CHECK(SLANG_FAILED(fileSystem->remove("d\\b"))); - - // Remove the directory - SLANG_RETURN_ON_FAIL(fileSystem->remove("d")); - - { - const Entry entries[] = { {SLANG_PATH_TYPE_FILE, "a" }, {SLANG_PATH_TYPE_FILE, "b" } }; - SLANG_RETURN_ON_FAIL(_enumeratePath(fileSystem, ".", makeConstArrayView(entries))); - } - - return SLANG_OK; + ComPtr<ISlangMutableFileSystem> fileSystem; + SLANG_RETURN_ON_FAIL(_createFileSystem(type, fileSystem)); + + const auto aText = "someText"; + const auto bText = "A longer bit of text...."; + const auto d_aText = "Some more silly stuff"; + const auto d_bText = "Lets go!"; + + SLANG_RETURN_ON_FAIL(_createAndCheckFile(fileSystem, "a", aText)); + SLANG_RETURN_ON_FAIL(_createAndCheckFile(fileSystem, "b", bText)); + + SLANG_RETURN_ON_FAIL(_createAndCheckDirectory(fileSystem, "d")); + SLANG_RETURN_ON_FAIL(_createAndCheckFile(fileSystem, "d/a", d_aText)); + SLANG_RETURN_ON_FAIL(_createAndCheckFile(fileSystem, "d\\b", d_bText)); + + // Try and absolute path + SLANG_RETURN_ON_FAIL(_checkFile(fileSystem, "/a", aText)); + SLANG_RETURN_ON_FAIL(_checkFile(fileSystem, "/b", bText)); + SLANG_RETURN_ON_FAIL(_checkFile(fileSystem, "/d/a", d_aText)); + SLANG_RETURN_ON_FAIL(_checkFile(fileSystem, "/d\\b", d_bText)); + + + // Check canonical on files + { + const char* paths[] = {"a", "/a", "./a", "d/../a", ".\\d/.\\..\\a"}; + SLANG_RETURN_ON_FAIL(_checkCanonical(fileSystem, paths, SLANG_COUNT_OF(paths))); + } + + { + const char* paths[] = {"/d/b", "d/./b"}; + SLANG_RETURN_ON_FAIL(_checkCanonical(fileSystem, paths, SLANG_COUNT_OF(paths))); + } + + // Check canonical on directories + { + const char* paths[] = {".", "/", "/d/..", "d/.."}; + SLANG_RETURN_ON_FAIL(_checkCanonical(fileSystem, paths, SLANG_COUNT_OF(paths))); + } + + { + const char* paths[] = {"d", "./d", "/d", "/d/./../d"}; + SLANG_RETURN_ON_FAIL(_checkCanonical(fileSystem, paths, SLANG_COUNT_OF(paths))); + } + + // Lets find all the files in the directory + + { + const Entry entries[] = {{SLANG_PATH_TYPE_FILE, "a"}, {SLANG_PATH_TYPE_FILE, "b"}}; + SLANG_RETURN_ON_FAIL(_enumeratePath(fileSystem, "d", makeConstArrayView(entries))); + } + + { + const Entry entries[] = { + {SLANG_PATH_TYPE_FILE, "a"}, + {SLANG_PATH_TYPE_FILE, "b"}, + {SLANG_PATH_TYPE_DIRECTORY, "d"}}; + SLANG_RETURN_ON_FAIL(_enumeratePath(fileSystem, ".", makeConstArrayView(entries))); + + // Let's check that / and \ works for the root directory + SLANG_RETURN_ON_FAIL(_enumeratePath(fileSystem, "/", makeConstArrayView(entries))); + SLANG_RETURN_ON_FAIL(_enumeratePath(fileSystem, "\\", makeConstArrayView(entries))); + } + + // Check the root directory exists + { + SLANG_RETURN_ON_FAIL(_checkDirectoryExists(fileSystem, ".")); + SLANG_RETURN_ON_FAIL(_checkDirectoryExists(fileSystem, "/")); + SLANG_RETURN_ON_FAIL(_checkDirectoryExists(fileSystem, "\\")); + } + + { + SLANG_RETURN_ON_FAIL(_checkSimplifiedPath(fileSystem, "d/../a", "a")); + } + + + // If we have an archive file system check out it's behavior + if (IArchiveFileSystem* archiveFileSystem = as<IArchiveFileSystem>(fileSystem)) + { + // Load and check its okay + + ComPtr<ISlangBlob> archiveBlob; + SLANG_RETURN_ON_FAIL(archiveFileSystem->storeArchive(false, archiveBlob.writeRef())); + + ComPtr<ISlangFileSystemExt> loadedFileSystem; + SLANG_RETURN_ON_FAIL(loadArchiveFileSystem( + archiveBlob->getBufferPointer(), + archiveBlob->getBufferSize(), + loadedFileSystem)); + + // Check the file systems contents are the same + SLANG_RETURN_ON_FAIL(_checkEqual(loadedFileSystem, fileSystem)); + } + + SLANG_RETURN_ON_FAIL(fileSystem->remove("d/a")); + { + const Entry entries[] = {{SLANG_PATH_TYPE_FILE, "b"}}; + SLANG_RETURN_ON_FAIL(_enumeratePath(fileSystem, "d", makeConstArrayView(entries))); + } + SLANG_RETURN_ON_FAIL(fileSystem->remove("d\\b")); + { + SLANG_RETURN_ON_FAIL( + _enumeratePath(fileSystem, "d", makeConstArrayView((const Entry*)nullptr, 0))); + } + + // If it's removed it can't be removed again + SLANG_CHECK(SLANG_FAILED(fileSystem->remove("d\\b"))); + + // Remove the directory + SLANG_RETURN_ON_FAIL(fileSystem->remove("d")); + + { + const Entry entries[] = {{SLANG_PATH_TYPE_FILE, "a"}, {SLANG_PATH_TYPE_FILE, "b"}}; + SLANG_RETURN_ON_FAIL(_enumeratePath(fileSystem, ".", makeConstArrayView(entries))); + } + + return SLANG_OK; } SLANG_UNIT_TEST(fileSystem) { - for (Index i = 0; i < Count(FileSystemType::CountOf); ++i) - { - const auto type = FileSystemType(i); - - SLANG_CHECK(SLANG_SUCCEEDED(_test(type))); - - // Some file system types support 'implicit directories'. - // This means that if a file is created with a path, the directories - // required to make that path valid are 'implicitly' created. - // - // Currently this behavior is supported by zip, and this test checks - // that it is working correctly, as we require the file system to - // behave correctly in other ways irrespectively of if the directory is - // implicit or not. - const bool hasImplicitDirectory = (type == FileSystemType::Zip); - if (hasImplicitDirectory) - { - SLANG_CHECK(SLANG_SUCCEEDED(_testImplicitDirectory(type))); - } - } + for (Index i = 0; i < Count(FileSystemType::CountOf); ++i) + { + const auto type = FileSystemType(i); + + SLANG_CHECK(SLANG_SUCCEEDED(_test(type))); + + // Some file system types support 'implicit directories'. + // This means that if a file is created with a path, the directories + // required to make that path valid are 'implicitly' created. + // + // Currently this behavior is supported by zip, and this test checks + // that it is working correctly, as we require the file system to + // behave correctly in other ways irrespectively of if the directory is + // implicit or not. + const bool hasImplicitDirectory = (type == FileSystemType::Zip); + if (hasImplicitDirectory) + { + SLANG_CHECK(SLANG_SUCCEEDED(_testImplicitDirectory(type))); + } + } } - diff --git a/tools/slang-unit-test/unit-test-find-check-entrypoint.cpp b/tools/slang-unit-test/unit-test-find-check-entrypoint.cpp index 122f26ddd..717b937d1 100644 --- a/tools/slang-unit-test/unit-test-find-check-entrypoint.cpp +++ b/tools/slang-unit-test/unit-test-find-check-entrypoint.cpp @@ -1,18 +1,17 @@ // unit-test-translation-unit-import.cpp +#include "../../source/core/slang-io.h" +#include "../../source/core/slang-process.h" +#include "slang-com-ptr.h" #include "slang.h" +#include "tools/unit-test/slang-unit-test.h" #include <stdio.h> #include <stdlib.h> -#include "tools/unit-test/slang-unit-test.h" -#include "slang-com-ptr.h" -#include "../../source/core/slang-io.h" -#include "../../source/core/slang-process.h" - using namespace Slang; -// Test that the IModule::findAndCheckEntryPoint API supports discovering +// Test that the IModule::findAndCheckEntryPoint API supports discovering // entrypoints without a [shader] attribute. SLANG_UNIT_TEST(findAndCheckEntryPoint) @@ -39,16 +38,28 @@ SLANG_UNIT_TEST(findAndCheckEntryPoint) SLANG_CHECK(globalSession->createSession(sessionDesc, session.writeRef()) == SLANG_OK); ComPtr<slang::IBlob> diagnosticBlob; - auto module = session->loadModuleFromSourceString("m", "m.slang", userSourceBody, diagnosticBlob.writeRef()); + auto module = session->loadModuleFromSourceString( + "m", + "m.slang", + userSourceBody, + diagnosticBlob.writeRef()); SLANG_CHECK(module != nullptr); ComPtr<slang::IEntryPoint> entryPoint; - module->findAndCheckEntryPoint("fragMain", SLANG_STAGE_FRAGMENT, entryPoint.writeRef(), diagnosticBlob.writeRef()); + module->findAndCheckEntryPoint( + "fragMain", + SLANG_STAGE_FRAGMENT, + entryPoint.writeRef(), + diagnosticBlob.writeRef()); SLANG_CHECK(entryPoint != nullptr); ComPtr<slang::IComponentType> compositeProgram; - slang::IComponentType* components[] = { module, entryPoint.get() }; - session->createCompositeComponentType(components, 2, compositeProgram.writeRef(), diagnosticBlob.writeRef()); + slang::IComponentType* components[] = {module, entryPoint.get()}; + session->createCompositeComponentType( + components, + 2, + compositeProgram.writeRef(), + diagnosticBlob.writeRef()); SLANG_CHECK(compositeProgram != nullptr); ComPtr<slang::IComponentType> linkedProgram; @@ -60,4 +71,3 @@ SLANG_UNIT_TEST(findAndCheckEntryPoint) SLANG_CHECK(code != nullptr); SLANG_CHECK(code->getBufferSize() != 0); } - diff --git a/tools/slang-unit-test/unit-test-find-entrypoint-nested.cpp b/tools/slang-unit-test/unit-test-find-entrypoint-nested.cpp index addada5b6..6cf2ffd17 100644 --- a/tools/slang-unit-test/unit-test-find-entrypoint-nested.cpp +++ b/tools/slang-unit-test/unit-test-find-entrypoint-nested.cpp @@ -1,15 +1,14 @@ // unit-test-find-entrypoint-nested.cpp +#include "../../source/core/slang-io.h" +#include "../../source/core/slang-process.h" +#include "slang-com-ptr.h" #include "slang.h" +#include "tools/unit-test/slang-unit-test.h" #include <stdio.h> #include <stdlib.h> -#include "tools/unit-test/slang-unit-test.h" -#include "slang-com-ptr.h" -#include "../../source/core/slang-io.h" -#include "../../source/core/slang-process.h" - using namespace Slang; // Test that the IModule::findAndCheckEntryPoint API works with modules that @@ -52,16 +51,28 @@ SLANG_UNIT_TEST(findEntryPointNested) SLANG_CHECK(globalSession->createSession(sessionDesc, session.writeRef()) == SLANG_OK); ComPtr<slang::IBlob> diagnosticBlob; - auto module = session->loadModuleFromSourceString("m", "m.slang", userSourceBody, diagnosticBlob.writeRef()); + auto module = session->loadModuleFromSourceString( + "m", + "m.slang", + userSourceBody, + diagnosticBlob.writeRef()); SLANG_CHECK(module != nullptr); ComPtr<slang::IEntryPoint> entryPoint; - module->findAndCheckEntryPoint("outer", SLANG_STAGE_RAY_GENERATION, entryPoint.writeRef(), diagnosticBlob.writeRef()); + module->findAndCheckEntryPoint( + "outer", + SLANG_STAGE_RAY_GENERATION, + entryPoint.writeRef(), + diagnosticBlob.writeRef()); SLANG_CHECK(entryPoint != nullptr); ComPtr<slang::IComponentType> compositeProgram; - slang::IComponentType* components[] = { module, entryPoint.get() }; - session->createCompositeComponentType(components, 2, compositeProgram.writeRef(), diagnosticBlob.writeRef()); + slang::IComponentType* components[] = {module, entryPoint.get()}; + session->createCompositeComponentType( + components, + 2, + compositeProgram.writeRef(), + diagnosticBlob.writeRef()); SLANG_CHECK(compositeProgram != nullptr); ComPtr<slang::IComponentType> linkedProgram; @@ -73,4 +84,3 @@ SLANG_UNIT_TEST(findEntryPointNested) SLANG_CHECK(code != nullptr); SLANG_CHECK(code->getBufferSize() != 0); } - diff --git a/tools/slang-unit-test/unit-test-find-type-by-name.cpp b/tools/slang-unit-test/unit-test-find-type-by-name.cpp index ee6ba3516..a42b08ade 100644 --- a/tools/slang-unit-test/unit-test-find-type-by-name.cpp +++ b/tools/slang-unit-test/unit-test-find-type-by-name.cpp @@ -1,21 +1,19 @@ // unit-test-find-type-by-name.cpp #include "slang.h" +#include "tools/unit-test/slang-unit-test.h" #include <stdio.h> #include <stdlib.h> -#include "tools/unit-test/slang-unit-test.h" - using namespace Slang; SLANG_UNIT_TEST(findTypeByName) { - const char* testSource = - "struct TestStruct {" - " int member0;" - " Texture2D texture1;" - "};"; + const char* testSource = "struct TestStruct {" + " int member0;" + " Texture2D texture1;" + "};"; auto session = spCreateSession(); auto request = spCreateCompileRequest(session); spAddCodeGenTarget(request, SLANG_DXBC); @@ -44,7 +42,8 @@ SLANG_UNIT_TEST(findTypeByName) auto paramBlockElementType = paramBlockType->getElementType(); SLANG_CHECK_ABORT(paramBlockElementType != nullptr); auto paramBlockElementTypeName = paramBlockElementType->getName(); - SLANG_CHECK_ABORT(paramBlockElementTypeName && strcmp(paramBlockElementTypeName, "TestStruct") == 0); + SLANG_CHECK_ABORT( + paramBlockElementTypeName && strcmp(paramBlockElementTypeName, "TestStruct") == 0); }; testBody(); @@ -52,4 +51,3 @@ SLANG_UNIT_TEST(findTypeByName) spDestroyCompileRequest(request); spDestroySession(session); } - diff --git a/tools/slang-unit-test/unit-test-free-list.cpp b/tools/slang-unit-test/unit-test-free-list.cpp index d6c8b47a7..80cd01dc1 100644 --- a/tools/slang-unit-test/unit-test-free-list.cpp +++ b/tools/slang-unit-test/unit-test-free-list.cpp @@ -1,15 +1,13 @@ // unit-test-free-list.cpp #include "../../source/core/slang-free-list.h" +#include "../../source/core/slang-list.h" +#include "../../source/core/slang-random-generator.h" +#include "tools/unit-test/slang-unit-test.h" #include <stdio.h> #include <stdlib.h> -#include "tools/unit-test/slang-unit-test.h" - -#include "../../source/core/slang-random-generator.h" -#include "../../source/core/slang-list.h" - using namespace Slang; SLANG_UNIT_TEST(freeList) @@ -24,7 +22,7 @@ SLANG_UNIT_TEST(freeList) for (int i = 0; i < 1000; i++) { const int numAlloc = randGen.nextInt32UpTo(20); - + for (int j = 0; j < numAlloc; j++) { int* ptr = (int*)freeList.allocate(); @@ -50,4 +48,3 @@ SLANG_UNIT_TEST(freeList) } } } - diff --git a/tools/slang-unit-test/unit-test-function-reflection.cpp b/tools/slang-unit-test/unit-test-function-reflection.cpp index f893da69d..2d62bd761 100644 --- a/tools/slang-unit-test/unit-test-function-reflection.cpp +++ b/tools/slang-unit-test/unit-test-function-reflection.cpp @@ -1,15 +1,14 @@ // unit-test-translation-unit-import.cpp +#include "../../source/core/slang-io.h" +#include "../../source/core/slang-process.h" +#include "slang-com-ptr.h" #include "slang.h" +#include "tools/unit-test/slang-unit-test.h" #include <stdio.h> #include <stdlib.h> -#include "tools/unit-test/slang-unit-test.h" -#include "slang-com-ptr.h" -#include "../../source/core/slang-io.h" -#include "../../source/core/slang-process.h" - using namespace Slang; static String getTypeFullName(slang::TypeReflection* type) @@ -59,19 +58,30 @@ SLANG_UNIT_TEST(functionReflection) SLANG_CHECK(globalSession->createSession(sessionDesc, session.writeRef()) == SLANG_OK); ComPtr<slang::IBlob> diagnosticBlob; - auto module = session->loadModuleFromSourceString("m", "m.slang", userSourceBody, diagnosticBlob.writeRef()); + auto module = session->loadModuleFromSourceString( + "m", + "m.slang", + userSourceBody, + diagnosticBlob.writeRef()); SLANG_CHECK(module != nullptr); ComPtr<slang::IEntryPoint> entryPoint; - module->findAndCheckEntryPoint("fragMain", SLANG_STAGE_FRAGMENT, entryPoint.writeRef(), diagnosticBlob.writeRef()); + module->findAndCheckEntryPoint( + "fragMain", + SLANG_STAGE_FRAGMENT, + entryPoint.writeRef(), + diagnosticBlob.writeRef()); SLANG_CHECK(entryPoint != nullptr); auto entryPointFuncReflection = entryPoint->getFunctionReflection(); SLANG_CHECK(entryPointFuncReflection != nullptr); SLANG_CHECK(UnownedStringSlice(entryPointFuncReflection->getName()) == "fragMain"); SLANG_CHECK(entryPointFuncReflection->getParameterCount() == 1); - SLANG_CHECK(UnownedStringSlice(entryPointFuncReflection->getParameterByIndex(0)->getName()) == "pos"); - SLANG_CHECK(getTypeFullName(entryPointFuncReflection->getParameterByIndex(0)->getType()) == "vector<float,4>"); + SLANG_CHECK( + UnownedStringSlice(entryPointFuncReflection->getParameterByIndex(0)->getName()) == "pos"); + SLANG_CHECK( + getTypeFullName(entryPointFuncReflection->getParameterByIndex(0)->getType()) == + "vector<float,4>"); auto funcReflection = module->getLayout()->findFunctionByName("ordinaryFunc"); SLANG_CHECK(funcReflection != nullptr); @@ -82,7 +92,8 @@ SLANG_UNIT_TEST(functionReflection) SLANG_CHECK(funcReflection->getParameterCount() == 2); SLANG_CHECK(UnownedStringSlice(funcReflection->getParameterByIndex(0)->getName()) == "x"); SLANG_CHECK(getTypeFullName(funcReflection->getParameterByIndex(0)->getType()) == "float"); - SLANG_CHECK(funcReflection->getParameterByIndex(0)->findModifier(slang::Modifier::NoDiff) != nullptr); + SLANG_CHECK( + funcReflection->getParameterByIndex(0)->findModifier(slang::Modifier::NoDiff) != nullptr); SLANG_CHECK(UnownedStringSlice(funcReflection->getParameterByIndex(1)->getName()) == "y"); SLANG_CHECK(getTypeFullName(funcReflection->getParameterByIndex(1)->getType()) == "int"); @@ -96,7 +107,9 @@ SLANG_UNIT_TEST(functionReflection) auto result = userAttribute->getArgumentValueInt(0, &val); SLANG_CHECK(result == SLANG_OK); SLANG_CHECK(val == 1024); - SLANG_CHECK(funcReflection->findUserAttributeByName(globalSession.get(), "MyFuncProperty") == userAttribute); + SLANG_CHECK( + funcReflection->findUserAttributeByName(globalSession.get(), "MyFuncProperty") == + userAttribute); // Check overloaded method resolution auto overloadReflection = module->getLayout()->findFunctionByName("foo"); @@ -129,7 +142,7 @@ SLANG_UNIT_TEST(functionReflection) // // More testing for specializeWithArgTypes - // + // // bar1 (IFloat, IFloat) -> int // @@ -144,11 +157,13 @@ SLANG_UNIT_TEST(functionReflection) argTypes[1] = float3Type; resolvedFunctionReflection = bar1Reflection->specializeWithArgTypes(2, argTypes); - + SLANG_CHECK(resolvedFunctionReflection != nullptr); SLANG_CHECK(resolvedFunctionReflection->getParameterCount() == 2); - SLANG_CHECK(getTypeFullName(resolvedFunctionReflection->getParameterByIndex(0)->getType()) == "IFloat"); - SLANG_CHECK(getTypeFullName(resolvedFunctionReflection->getParameterByIndex(1)->getType()) == "IFloat"); + SLANG_CHECK( + getTypeFullName(resolvedFunctionReflection->getParameterByIndex(0)->getType()) == "IFloat"); + SLANG_CHECK( + getTypeFullName(resolvedFunctionReflection->getParameterByIndex(1)->getType()) == "IFloat"); // bar2 (T : IFloat, float3) -> int // @@ -166,8 +181,11 @@ SLANG_UNIT_TEST(functionReflection) SLANG_CHECK(resolvedFunctionReflection != nullptr); SLANG_CHECK(resolvedFunctionReflection->getParameterCount() == 2); - SLANG_CHECK(getTypeFullName(resolvedFunctionReflection->getParameterByIndex(0)->getType()) == "float"); - SLANG_CHECK(getTypeFullName(resolvedFunctionReflection->getParameterByIndex(1)->getType()) == "vector<float,3>"); + SLANG_CHECK( + getTypeFullName(resolvedFunctionReflection->getParameterByIndex(0)->getType()) == "float"); + SLANG_CHECK( + getTypeFullName(resolvedFunctionReflection->getParameterByIndex(1)->getType()) == + "vector<float,3>"); // failure case @@ -188,4 +206,3 @@ SLANG_UNIT_TEST(functionReflection) SLANG_CHECK(resolvedFunctionReflection != nullptr); SLANG_CHECK(resolvedFunctionReflection == bar3Reflection); } - diff --git a/tools/slang-unit-test/unit-test-generic-interface-conformance.cpp b/tools/slang-unit-test/unit-test-generic-interface-conformance.cpp index 740d13bef..df5e6e63a 100644 --- a/tools/slang-unit-test/unit-test-generic-interface-conformance.cpp +++ b/tools/slang-unit-test/unit-test-generic-interface-conformance.cpp @@ -1,18 +1,17 @@ // unit-test-translation-unit-import.cpp +#include "../../source/core/slang-io.h" +#include "../../source/core/slang-process.h" +#include "slang-com-ptr.h" #include "slang.h" +#include "tools/unit-test/slang-unit-test.h" #include <stdio.h> #include <stdlib.h> -#include "tools/unit-test/slang-unit-test.h" -#include "slang-com-ptr.h" -#include "../../source/core/slang-io.h" -#include "../../source/core/slang-process.h" - using namespace Slang; -// Test that the IModule::findAndCheckEntryPoint API supports discovering +// Test that the IModule::findAndCheckEntryPoint API supports discovering // entrypoints without a [shader] attribute. SLANG_UNIT_TEST(genericInterfaceConformance) @@ -56,26 +55,38 @@ SLANG_UNIT_TEST(genericInterfaceConformance) sessionDesc.targetCount = 1; sessionDesc.targets = &targetDesc; sessionDesc.allowGLSLSyntax = true; - + ComPtr<slang::ISession> session; SLANG_CHECK(globalSession->createSession(sessionDesc, session.writeRef()) == SLANG_OK); ComPtr<slang::IBlob> diagnosticBlob; - auto module = session->loadModuleFromSourceString("m", "m.slang", userSourceBody, diagnosticBlob.writeRef()); + auto module = session->loadModuleFromSourceString( + "m", + "m.slang", + userSourceBody, + diagnosticBlob.writeRef()); SLANG_CHECK(module != nullptr); ComPtr<slang::IEntryPoint> entryPoint; - module->findAndCheckEntryPoint("computeMain", SLANG_STAGE_COMPUTE, entryPoint.writeRef(), diagnosticBlob.writeRef()); + module->findAndCheckEntryPoint( + "computeMain", + SLANG_STAGE_COMPUTE, + entryPoint.writeRef(), + diagnosticBlob.writeRef()); SLANG_CHECK(entryPoint != nullptr); ComPtr<slang::IComponentType> compositeProgram; - slang::IComponentType* components[] = { module, entryPoint.get() }; - session->createCompositeComponentType(components, 2, compositeProgram.writeRef(), diagnosticBlob.writeRef()); + slang::IComponentType* components[] = {module, entryPoint.get()}; + session->createCompositeComponentType( + components, + 2, + compositeProgram.writeRef(), + diagnosticBlob.writeRef()); SLANG_CHECK(compositeProgram != nullptr); ComPtr<slang::ITypeConformance> typeConformance; - auto result = session->createTypeConformanceComponentType( - compositeProgram->getLayout()->findTypeByName("TestInterfaceImpl<float>"), + auto result = session->createTypeConformanceComponentType( + compositeProgram->getLayout()->findTypeByName("TestInterfaceImpl<float>"), compositeProgram->getLayout()->findTypeByName("ITestInterface<float>"), typeConformance.writeRef(), 3, @@ -84,9 +95,12 @@ SLANG_UNIT_TEST(genericInterfaceConformance) SLANG_CHECK(typeConformance != nullptr); ComPtr<slang::IComponentType> compositeProgram2; - slang::IComponentType* components2[] = { compositeProgram.get(), typeConformance.get() }; + slang::IComponentType* components2[] = {compositeProgram.get(), typeConformance.get()}; session->createCompositeComponentType( - components2, 2, compositeProgram2.writeRef(), diagnosticBlob.writeRef()); + components2, + 2, + compositeProgram2.writeRef(), + diagnosticBlob.writeRef()); ComPtr<slang::IComponentType> linkedProgram; compositeProgram2->link(linkedProgram.writeRef(), diagnosticBlob.writeRef()); @@ -99,4 +113,3 @@ SLANG_UNIT_TEST(genericInterfaceConformance) auto codeSrc = UnownedStringSlice((const char*)code->getBufferPointer()); SLANG_CHECK(codeSrc.indexOf(toSlice("computeMain")) != -1); } - diff --git a/tools/slang-unit-test/unit-test-get-target-code.cpp b/tools/slang-unit-test/unit-test-get-target-code.cpp index 7cb51c91b..f3df15b64 100644 --- a/tools/slang-unit-test/unit-test-get-target-code.cpp +++ b/tools/slang-unit-test/unit-test-get-target-code.cpp @@ -1,15 +1,14 @@ // unit-test-translation-unit-import.cpp +#include "../../source/core/slang-io.h" +#include "../../source/core/slang-process.h" +#include "slang-com-ptr.h" #include "slang.h" +#include "tools/unit-test/slang-unit-test.h" #include <stdio.h> #include <stdlib.h> -#include "tools/unit-test/slang-unit-test.h" -#include "slang-com-ptr.h" -#include "../../source/core/slang-io.h" -#include "../../source/core/slang-process.h" - using namespace Slang; // Test that the IComponentType::getTargetCode API supports @@ -47,7 +46,11 @@ SLANG_UNIT_TEST(getTargetCode) SLANG_CHECK(globalSession->createSession(sessionDesc, session.writeRef()) == SLANG_OK); ComPtr<slang::IBlob> diagnosticBlob; - auto module = session->loadModuleFromSourceString("m", "m.slang", userSourceBody, diagnosticBlob.writeRef()); + auto module = session->loadModuleFromSourceString( + "m", + "m.slang", + userSourceBody, + diagnosticBlob.writeRef()); SLANG_CHECK(module != nullptr); ComPtr<slang::IComponentType> linkedProgram; @@ -66,4 +69,3 @@ SLANG_UNIT_TEST(getTargetCode) SLANG_CHECK(resultStr.indexOf(toSlice("fragMain")) != -1); SLANG_CHECK(resultStr.indexOf(toSlice("vertMain")) != -1); } - diff --git a/tools/slang-unit-test/unit-test-image-format-reflection.cpp b/tools/slang-unit-test/unit-test-image-format-reflection.cpp index 34678472c..66d18b3e0 100644 --- a/tools/slang-unit-test/unit-test-image-format-reflection.cpp +++ b/tools/slang-unit-test/unit-test-image-format-reflection.cpp @@ -1,15 +1,14 @@ // unit-test-image-format-reflection.cpp +#include "../../source/core/slang-io.h" +#include "../../source/core/slang-process.h" +#include "slang-com-ptr.h" #include "slang.h" +#include "tools/unit-test/slang-unit-test.h" #include <stdio.h> #include <stdlib.h> -#include "tools/unit-test/slang-unit-test.h" -#include "slang-com-ptr.h" -#include "../../source/core/slang-io.h" -#include "../../source/core/slang-process.h" - using namespace Slang; // Test that the getBindingRangeImageFormat API works. @@ -39,20 +38,31 @@ SLANG_UNIT_TEST(imageFormatReflection) SLANG_CHECK(globalSession->createSession(sessionDesc, session.writeRef()) == SLANG_OK); ComPtr<slang::IBlob> diagnosticBlob; - auto module = session->loadModuleFromSourceString("m", "m.slang", userSourceBody, diagnosticBlob.writeRef()); + auto module = session->loadModuleFromSourceString( + "m", + "m.slang", + userSourceBody, + diagnosticBlob.writeRef()); SLANG_CHECK(module != nullptr); ComPtr<slang::IEntryPoint> entryPoint; - module->findAndCheckEntryPoint("fragMain", SLANG_STAGE_FRAGMENT, entryPoint.writeRef(), diagnosticBlob.writeRef()); + module->findAndCheckEntryPoint( + "fragMain", + SLANG_STAGE_FRAGMENT, + entryPoint.writeRef(), + diagnosticBlob.writeRef()); SLANG_CHECK(entryPoint != nullptr); ComPtr<slang::IComponentType> compositeProgram; - slang::IComponentType* components[] = { module, entryPoint.get() }; - session->createCompositeComponentType(components, 2, compositeProgram.writeRef(), diagnosticBlob.writeRef()); + slang::IComponentType* components[] = {module, entryPoint.get()}; + session->createCompositeComponentType( + components, + 2, + compositeProgram.writeRef(), + diagnosticBlob.writeRef()); SLANG_CHECK(compositeProgram != nullptr); auto layout = compositeProgram->getLayout(0); auto format = layout->getGlobalParamsTypeLayout()->getBindingRangeImageFormat(0); SLANG_CHECK(format == SLANG_IMAGE_FORMAT_rgba32ui); } - diff --git a/tools/slang-unit-test/unit-test-io.cpp b/tools/slang-unit-test/unit-test-io.cpp index fbac5af17..0e6cab94d 100644 --- a/tools/slang-unit-test/unit-test-io.cpp +++ b/tools/slang-unit-test/unit-test-io.cpp @@ -1,7 +1,6 @@ // unit-test-io.cpp #include "../../source/core/slang-io.h" - #include "tools/unit-test/slang-unit-test.h" using namespace Slang; @@ -9,7 +8,7 @@ using namespace Slang; static SlangResult _checkGenerateTemporary() { /// Test temporary file functionality - + List<String> paths; for (Index i = 0; i < 10; ++i) @@ -47,7 +46,7 @@ static SlangResult _checkGenerateTemporary() for (auto& path : paths) { SLANG_CHECK(File::exists(path)); - + const auto removeResult = File::remove(path); SLANG_CHECK(SLANG_SUCCEEDED(removeResult)); diff --git a/tools/slang-unit-test/unit-test-json-native.cpp b/tools/slang-unit-test/unit-test-json-native.cpp index 546131e4b..de5b7cfa4 100644 --- a/tools/slang-unit-test/unit-test-json-native.cpp +++ b/tools/slang-unit-test/unit-test-json-native.cpp @@ -1,21 +1,20 @@ // unit-test-json-native.cpp -#include "../../source/core/slang-rtti-info.h" - #include "../../source/compiler-core/slang-json-native.h" #include "../../source/compiler-core/slang-json-parser.h" - +#include "../../source/core/slang-rtti-info.h" #include "tools/unit-test/slang-unit-test.h" using namespace Slang; -namespace { // anonymous +namespace +{ // anonymous struct OtherStruct { typedef OtherStruct ThisType; - bool operator==(const ThisType& rhs) const { return f == rhs.f && value == rhs.value; } + bool operator==(const ThisType& rhs) const { return f == rhs.f && value == rhs.value; } bool operator!=(const ThisType& rhs) const { return !(*this == rhs); } float f = 1.0f; @@ -32,7 +31,7 @@ static const StructRttiInfo _makeOtherStructRtti() builder.addField("value", &obj.value); return builder.make(); } -/* static */const StructRttiInfo OtherStruct::g_rttiInfo = _makeOtherStructRtti(); +/* static */ const StructRttiInfo OtherStruct::g_rttiInfo = _makeOtherStructRtti(); struct SomeStruct { @@ -40,13 +39,9 @@ struct SomeStruct bool operator==(const ThisType& rhs) const { - return a == rhs.a && - b == rhs.b && - s == rhs.s && - list == rhs.list && - boolValue == rhs.boolValue && - structList == rhs.structList && - makeConstArrayView(fixedArray) == makeConstArrayView(rhs.fixedArray); + return a == rhs.a && b == rhs.b && s == rhs.s && list == rhs.list && + boolValue == rhs.boolValue && structList == rhs.structList && + makeConstArrayView(fixedArray) == makeConstArrayView(rhs.fixedArray); } bool operator!=(const ThisType& rhs) const { return !(*this == rhs); } @@ -58,7 +53,7 @@ struct SomeStruct List<OtherStruct> structList; - int fixedArray[2] = { 0, 0 }; + int fixedArray[2] = {0, 0}; static const StructRttiInfo g_rttiInfo; }; @@ -78,9 +73,9 @@ static const StructRttiInfo _makeSomeStructRtti() return builder.make(); } -/* static */const StructRttiInfo SomeStruct::g_rttiInfo = _makeSomeStructRtti(); +/* static */ const StructRttiInfo SomeStruct::g_rttiInfo = _makeSomeStructRtti(); -} // anonymous +} // namespace static SlangResult _check() @@ -107,7 +102,7 @@ static SlangResult _check() DiagnosticSink sink(&sourceManager, &JSONLexer::calcLexemeLocation); - auto typeMap = JSONNativeUtil::getTypeFuncsMap(); + auto typeMap = JSONNativeUtil::getTypeFuncsMap(); RefPtr<JSONContainer> container(new JSONContainer(&sourceManager)); @@ -129,7 +124,8 @@ static SlangResult _check() { // Now need to parse as JSON String contents(json); - SourceFile* sourceFile = sourceManager.createSourceFileWithString(PathInfo::makeUnknown(), contents); + SourceFile* sourceFile = + sourceManager.createSourceFileWithString(PathInfo::makeUnknown(), contents); SourceView* sourceView = sourceManager.createSourceView(sourceFile, nullptr, SourceLoc()); JSONLexer lexer; @@ -149,7 +145,8 @@ static SlangResult _check() { SomeStruct readS; - SLANG_RETURN_ON_FAIL(converter.convert(readValue, GetRttiInfo<SomeStruct>::get(), &readS)); + SLANG_RETURN_ON_FAIL( + converter.convert(readValue, GetRttiInfo<SomeStruct>::get(), &readS)); // Should be equal SLANG_CHECK(readS == s); @@ -162,5 +159,4 @@ static SlangResult _check() SLANG_UNIT_TEST(JSONNative) { SLANG_CHECK(SLANG_SUCCEEDED(_check())); - } diff --git a/tools/slang-unit-test/unit-test-json.cpp b/tools/slang-unit-test/unit-test-json.cpp index b861465c8..532777030 100644 --- a/tools/slang-unit-test/unit-test-json.cpp +++ b/tools/slang-unit-test/unit-test-json.cpp @@ -1,14 +1,14 @@ #include "../../source/compiler-core/slang-json-lexer.h" -#include "../../source/core/slang-string-escape-util.h" #include "../../source/compiler-core/slang-json-parser.h" #include "../../source/compiler-core/slang-json-value.h" - +#include "../../source/core/slang-string-escape-util.h" #include "tools/unit-test/slang-unit-test.h" using namespace Slang; -namespace { // anonymous +namespace +{ // anonymous struct Element { @@ -16,14 +16,15 @@ struct Element const char* value; }; -} // anonymous +} // namespace static SlangResult _lex(const char* in, DiagnosticSink* sink, List<JSONToken>& toks) { SourceManager* sourceManager = sink->getSourceManager(); String contents(in); - SourceFile* sourceFile = sourceManager->createSourceFileWithString(PathInfo::makeUnknown(), contents); + SourceFile* sourceFile = + sourceManager->createSourceFileWithString(PathInfo::makeUnknown(), contents); SourceView* sourceView = sourceManager->createSourceView(sourceFile, nullptr, SourceLoc()); JSONLexer lexer; @@ -55,7 +56,8 @@ static SlangResult _parse(const char* in, DiagnosticSink* sink, JSONListener* li SourceManager* sourceManager = sink->getSourceManager(); String contents(in); - SourceFile* sourceFile = sourceManager->createSourceFileWithString(PathInfo::makeUnknown(), contents); + SourceFile* sourceFile = + sourceManager->createSourceFileWithString(PathInfo::makeUnknown(), contents); SourceView* sourceView = sourceManager->createSourceView(sourceFile, nullptr, SourceLoc()); JSONLexer lexer; @@ -66,7 +68,11 @@ static SlangResult _parse(const char* in, DiagnosticSink* sink, JSONListener* li return SLANG_OK; } -static bool _areEqual(SourceManager* sourceManager, const List<JSONToken>& toks, const Element* eles, Index elesCount) +static bool _areEqual( + SourceManager* sourceManager, + const List<JSONToken>& toks, + const Element* eles, + Index elesCount) { if (toks.getCount() != elesCount) { @@ -74,7 +80,7 @@ static bool _areEqual(SourceManager* sourceManager, const List<JSONToken>& toks, } SourceView* sourceView = toks.getCount() ? sourceManager->findSourceView(toks[0].loc) : nullptr; - const char*const content = sourceView ? sourceView->getContent().begin() : nullptr; + const char* const content = sourceView ? sourceView->getContent().begin() : nullptr; for (Index i = 0; i < toks.getCount(); ++i) { @@ -108,32 +114,32 @@ SLANG_UNIT_TEST(json) DiagnosticSink sink(&sourceManager, nullptr); { - const char text[] = " { \"Hello\" : [ \"World\", 1, 2.0, -3.0, -435.5345435, 45e-10, 421.00e+20, 17e1] }"; + const char text[] = + " { \"Hello\" : [ \"World\", 1, 2.0, -3.0, -435.5345435, 45e-10, 421.00e+20, 17e1] }"; - const Element eles[] = - { - {JSONTokenType::LBrace, "{" }, + const Element eles[] = { + {JSONTokenType::LBrace, "{"}, {JSONTokenType::StringLiteral, "\"Hello\""}, - {JSONTokenType::Colon, ":" }, - {JSONTokenType::LBracket, "[" }, - {JSONTokenType::StringLiteral, "\"World\"" }, - {JSONTokenType::Comma, "," }, - {JSONTokenType::IntegerLiteral, "1" }, - {JSONTokenType::Comma, "," }, - {JSONTokenType::FloatLiteral, "2.0" }, - {JSONTokenType::Comma, "," }, - {JSONTokenType::FloatLiteral, "-3.0" }, - {JSONTokenType::Comma, "," }, - {JSONTokenType::FloatLiteral, "-435.5345435" }, - {JSONTokenType::Comma, "," }, - {JSONTokenType::FloatLiteral, "45e-10" }, - {JSONTokenType::Comma, "," }, - {JSONTokenType::FloatLiteral, "421.00e+20" }, - {JSONTokenType::Comma, "," }, - {JSONTokenType::FloatLiteral, "17e1" }, - {JSONTokenType::RBracket, "]" }, - {JSONTokenType::RBrace, "}" }, - {JSONTokenType::EndOfFile, "" }, + {JSONTokenType::Colon, ":"}, + {JSONTokenType::LBracket, "["}, + {JSONTokenType::StringLiteral, "\"World\""}, + {JSONTokenType::Comma, ","}, + {JSONTokenType::IntegerLiteral, "1"}, + {JSONTokenType::Comma, ","}, + {JSONTokenType::FloatLiteral, "2.0"}, + {JSONTokenType::Comma, ","}, + {JSONTokenType::FloatLiteral, "-3.0"}, + {JSONTokenType::Comma, ","}, + {JSONTokenType::FloatLiteral, "-435.5345435"}, + {JSONTokenType::Comma, ","}, + {JSONTokenType::FloatLiteral, "45e-10"}, + {JSONTokenType::Comma, ","}, + {JSONTokenType::FloatLiteral, "421.00e+20"}, + {JSONTokenType::Comma, ","}, + {JSONTokenType::FloatLiteral, "17e1"}, + {JSONTokenType::RBracket, "]"}, + {JSONTokenType::RBrace, "}"}, + {JSONTokenType::EndOfFile, ""}, }; List<JSONToken> toks; @@ -145,7 +151,7 @@ SLANG_UNIT_TEST(json) { StringEscapeHandler* handler = StringEscapeUtil::getHandler(StringEscapeUtil::Style::JSON); - + { const auto slice = UnownedStringSlice::fromLiteral("\n\r\b\f\t \"\\/ Some text..."); @@ -173,8 +179,9 @@ SLANG_UNIT_TEST(json) { const uint32_t digitValue = (v >> ((3 - i) * 4)) & 0xf; - char digitC = (digitValue > 9) ? char(digitValue - 10 + 'a') : char(digitValue + '0'); - work[i + 2] = digitC; + char digitC = + (digitValue > 9) ? char(digitValue - 10 + 'a') : char(digitValue + '0'); + work[i + 2] = digitC; } buf << UnownedStringSlice(work, 6); @@ -241,7 +248,6 @@ SLANG_UNIT_TEST(json) } SLANG_CHECK(container->areEqual(value, copy)); - } } @@ -254,7 +260,7 @@ SLANG_UNIT_TEST(json) for (Int i = 0; i < 100; ++i) { - + values.add(JSONValue::makeInt(i)); values.add(JSONValue::makeFloat(-double(i))); } @@ -266,11 +272,14 @@ SLANG_UNIT_TEST(json) SLANG_CHECK(arrayView.getCount() == values.getCount()); // Check the values are the same - SLANG_CHECK(container->areEqual(arrayView.getBuffer(), values.getBuffer(), arrayView.getCount())); + SLANG_CHECK(container->areEqual( + arrayView.getBuffer(), + values.getBuffer(), + arrayView.getCount())); { JSONWriter writer(JSONWriter::IndentationStyle::KNR, 80); - + container->traverseRecursively(array, &writer); } } @@ -296,7 +305,7 @@ SLANG_UNIT_TEST(json) RefPtr<JSONContainer> container = new JSONContainer(&sourceManager); const char aText[] = "{ \"a\" : 10, \"b\" : 20.0, \"a\" : \"Hello\" }"; - + JSONBuilder builder(container); SLANG_CHECK(SLANG_SUCCEEDED(_parse(aText, &sink, &builder))); const JSONValue a = builder.getRootValue(); @@ -319,7 +328,8 @@ SLANG_UNIT_TEST(json) { RefPtr<JSONContainer> container = new JSONContainer(&sourceManager); - const char aText[] = "{ \"a\" : \"Hi!\", \"b\" : 20.0, \"c\" : \"Hello\", \"d\" : 30, \"e\": null, \"f\": true }"; + const char aText[] = "{ \"a\" : \"Hi!\", \"b\" : 20.0, \"c\" : \"Hello\", \"d\" : 30, " + "\"e\": null, \"f\": true }"; JSONBuilder builder(container); SLANG_CHECK(SLANG_SUCCEEDED(_parse(aText, &sink, &builder))); @@ -329,7 +339,7 @@ SLANG_UNIT_TEST(json) for (char c = 'a'; c <= 'f'; c++) { - const char name[] = { c, 0 }; + const char name[] = {c, 0}; JSONKey key = container->getKey(UnownedStringSlice(name, 1)); auto value = container->findObjectValue(rootValue, key); @@ -357,4 +367,3 @@ SLANG_UNIT_TEST(json) SLANG_CHECK(values[5].asBool() == true); } } - diff --git a/tools/slang-unit-test/unit-test-lock-file.cpp b/tools/slang-unit-test/unit-test-lock-file.cpp index 4915770fe..5ef9fa036 100644 --- a/tools/slang-unit-test/unit-test-lock-file.cpp +++ b/tools/slang-unit-test/unit-test-lock-file.cpp @@ -1,8 +1,7 @@ // unit-test-lock-file.cpp -#include "tools/unit-test/slang-unit-test.h" - #include "../../source/core/slang-io.h" #include "../../source/core/slang-process.h" +#include "tools/unit-test/slang-unit-test.h" #include <atomic> #include <future> @@ -11,7 +10,9 @@ using namespace Slang; -static const String fileName = Path::simplify(Path::getParentDirectory(Path::getExecutablePath()) + "/test_lock_file" + String(Process::getId())); +static const String fileName = Path::simplify( + Path::getParentDirectory(Path::getExecutablePath()) + "/test_lock_file" + + String(Process::getId())); SLANG_UNIT_TEST(lockFileOpenClose) { @@ -86,8 +87,8 @@ SLANG_UNIT_TEST(lockFileSync) SLANG_CHECK(lockFile2.tryLock(LockFile::LockType::Exclusive) == SLANG_E_TIME_OUT); // Start a number of threads and wait for them to start up. - // Each thread immediately tries to acquire the lock in non-blocking mode (expected to fail). - // Next each thread acquires the lock in blocking mode. + // Each thread immediately tries to acquire the lock in non-blocking mode (expected to + // fail). Next each thread acquires the lock in blocking mode. std::vector<LockTask> tasks(32); for (auto& task : tasks) { diff --git a/tools/slang-unit-test/unit-test-memory-arena.cpp b/tools/slang-unit-test/unit-test-memory-arena.cpp index b2671160a..beb19b28b 100644 --- a/tools/slang-unit-test/unit-test-memory-arena.cpp +++ b/tools/slang-unit-test/unit-test-memory-arena.cpp @@ -1,15 +1,13 @@ // unit-test-free-list.cpp +#include "../../source/core/slang-list.h" #include "../../source/core/slang-memory-arena.h" +#include "../../source/core/slang-random-generator.h" +#include "tools/unit-test/slang-unit-test.h" #include <stdio.h> #include <stdlib.h> -#include "tools/unit-test/slang-unit-test.h" - -#include "../../source/core/slang-random-generator.h" -#include "../../source/core/slang-list.h" - using namespace Slang; @@ -32,21 +30,17 @@ enum class TestMode eCount, }; -} // anonymous +} // namespace static size_t getAlignment(TestMode mode) { switch (mode) { - default: - case TestMode::eUnaligned: - return 1; - case TestMode::eExplicitAligned: - return 16; - case TestMode::eImplicitAligned: - return 32; - case TestMode::eDefaultAligned: - return MemoryArena::kMinAlignment; + default: + case TestMode::eUnaligned: return 1; + case TestMode::eExplicitAligned: return 16; + case TestMode::eImplicitAligned: return 32; + case TestMode::eDefaultAligned: return MemoryArena::kMinAlignment; } } @@ -129,7 +123,7 @@ SLANG_UNIT_TEST(memoryArena) arena.reset(); { - uint32_t data[] = { 1, 2, 3 }; + uint32_t data[] = {1, 2, 3}; const uint32_t* copy = arena.allocateAndCopyArray(data, SLANG_COUNT_OF(data)); @@ -141,7 +135,8 @@ SLANG_UNIT_TEST(memoryArena) int count = 0; const size_t blockSize = 1024; - for (TestMode mode = TestMode(0); int(mode) < int(TestMode::eCount); mode = TestMode(int(mode) + 1)) + for (TestMode mode = TestMode(0); int(mode) < int(TestMode::eCount); + mode = TestMode(int(mode) + 1)) { const size_t alignment = getAlignment(mode); @@ -162,7 +157,7 @@ SLANG_UNIT_TEST(memoryArena) // Deallocate everything arena.deallocateAll(); blocks.clear(); - } + } else if (var == 2) { arena.reset(); @@ -181,7 +176,6 @@ SLANG_UNIT_TEST(memoryArena) arena.rewindToCursor(blocks[rewindIndex].m_data); // All the blocks (includign this one) and now deallocated blocks.setCount(rewindIndex); - } else { @@ -202,7 +196,7 @@ SLANG_UNIT_TEST(memoryArena) } else if ((randGen.nextInt32() & 0xff) < 2) { - // Let's try for a block that's awkwardly sized + // Let's try for a block that's awkwardly sized sizeInBytes = blockSize / 3 + 10; } @@ -211,25 +205,25 @@ SLANG_UNIT_TEST(memoryArena) void* mem = nullptr; switch (mode) { - default: - case TestMode::eUnaligned: + default: + case TestMode::eUnaligned: { mem = arena.allocateUnaligned(sizeInBytes); break; } - case TestMode::eImplicitAligned: + case TestMode::eImplicitAligned: { // Fix the size to get implicit alignment sizeInBytes = (sizeInBytes & ~(alignment - 1)) + alignment; mem = arena.allocateUnaligned(sizeInBytes); break; } - case TestMode::eExplicitAligned: + case TestMode::eExplicitAligned: { mem = arena.allocateAligned(sizeInBytes, alignment); break; } - case TestMode::eDefaultAligned: + case TestMode::eDefaultAligned: { mem = arena.allocate(sizeInBytes); break; @@ -264,8 +258,5 @@ SLANG_UNIT_TEST(memoryArena) } { // Do lots of allocations and test out rewind - - - } } diff --git a/tools/slang-unit-test/unit-test-offset-container.cpp b/tools/slang-unit-test/unit-test-offset-container.cpp index 9d8e3a9ff..90f187282 100644 --- a/tools/slang-unit-test/unit-test-offset-container.cpp +++ b/tools/slang-unit-test/unit-test-offset-container.cpp @@ -1,7 +1,6 @@ // unit-test-offset-container.cpp #include "../../source/core/slang-offset-container.h" - #include "tools/unit-test/slang-unit-test.h" using namespace Slang; @@ -19,16 +18,17 @@ static void _checkEncodeDecode(uint32_t size) SLANG_CHECK(chars - (const char*)encode == encodeSize); } -namespace { // anonymous +namespace +{ // anonymous struct Root { - Offset32Array<Offset32Ptr<OffsetString> > dirs; + Offset32Array<Offset32Ptr<OffsetString>> dirs; Offset32Ptr<OffsetString> name; float value; }; -} // anonymous +} // namespace SLANG_UNIT_TEST(offsetContainer) { @@ -41,9 +41,8 @@ SLANG_UNIT_TEST(offsetContainer) { OffsetContainer container; - - const char* strings[] = - { + + const char* strings[] = { "Hello", "World", nullptr, @@ -65,7 +64,7 @@ SLANG_UNIT_TEST(offsetContainer) { List<uint8_t> copy; copy.addRange(container.getData(), container.getDataCount()); - + MemoryOffsetBase base; base.set(copy.getBuffer(), copy.getCount()); @@ -109,7 +108,7 @@ SLANG_UNIT_TEST(offsetContainer) SLANG_CHECK(str == nullptr); } - index ++; + index++; } } } diff --git a/tools/slang-unit-test/unit-test-parameter-usage-reflection.cpp b/tools/slang-unit-test/unit-test-parameter-usage-reflection.cpp index 911bdc5a4..c437ae2a2 100644 --- a/tools/slang-unit-test/unit-test-parameter-usage-reflection.cpp +++ b/tools/slang-unit-test/unit-test-parameter-usage-reflection.cpp @@ -1,15 +1,14 @@ // unit-test-parameter-usage-reflection.cpp +#include "../../source/core/slang-io.h" +#include "../../source/core/slang-process.h" +#include "slang-com-ptr.h" #include "slang.h" +#include "tools/unit-test/slang-unit-test.h" #include <stdio.h> #include <stdlib.h> -#include "tools/unit-test/slang-unit-test.h" -#include "slang-com-ptr.h" -#include "../../source/core/slang-io.h" -#include "../../source/core/slang-process.h" - using namespace Slang; // Test that the isParameterLocationUsed API works. @@ -40,16 +39,28 @@ SLANG_UNIT_TEST(isParameterLocationUsedReflection) SLANG_CHECK(globalSession->createSession(sessionDesc, session.writeRef()) == SLANG_OK); ComPtr<slang::IBlob> diagnosticBlob; - auto module = session->loadModuleFromSourceString("m", "m.slang", userSourceBody, diagnosticBlob.writeRef()); + auto module = session->loadModuleFromSourceString( + "m", + "m.slang", + userSourceBody, + diagnosticBlob.writeRef()); SLANG_CHECK(module != nullptr); ComPtr<slang::IEntryPoint> entryPoint; - module->findAndCheckEntryPoint("fragMain", SLANG_STAGE_FRAGMENT, entryPoint.writeRef(), diagnosticBlob.writeRef()); + module->findAndCheckEntryPoint( + "fragMain", + SLANG_STAGE_FRAGMENT, + entryPoint.writeRef(), + diagnosticBlob.writeRef()); SLANG_CHECK(entryPoint != nullptr); ComPtr<slang::IComponentType> compositeProgram; - slang::IComponentType* components[] = { module, entryPoint.get() }; - session->createCompositeComponentType(components, 2, compositeProgram.writeRef(), diagnosticBlob.writeRef()); + slang::IComponentType* components[] = {module, entryPoint.get()}; + session->createCompositeComponentType( + components, + 2, + compositeProgram.writeRef(), + diagnosticBlob.writeRef()); SLANG_CHECK(compositeProgram != nullptr); ComPtr<slang::IComponentType> linkedProgram; @@ -65,4 +76,3 @@ SLANG_UNIT_TEST(isParameterLocationUsedReflection) metadata->isParameterLocationUsed(SLANG_PARAMETER_CATEGORY_DESCRIPTOR_TABLE_SLOT, 0, 1, isUsed); SLANG_CHECK(!isUsed); } - diff --git a/tools/slang-unit-test/unit-test-path.cpp b/tools/slang-unit-test/unit-test-path.cpp index c27feee9c..d96acd4f7 100644 --- a/tools/slang-unit-test/unit-test-path.cpp +++ b/tools/slang-unit-test/unit-test-path.cpp @@ -1,7 +1,6 @@ // unit-test-path.cpp #include "../../source/core/slang-io.h" - #include "tools/unit-test/slang-unit-test.h" using namespace Slang; @@ -37,7 +36,9 @@ SLANG_UNIT_TEST(path) SLANG_CHECK(Path::simplify("a:\\what\\..\\.\\..\\is\\.\\..\\this\\.\\") == "a:/../this"); - SLANG_CHECK(Path::simplify("tests/preprocessor/.\\pragma-once-a.h") == "tests/preprocessor/pragma-once-a.h"); + SLANG_CHECK( + Path::simplify("tests/preprocessor/.\\pragma-once-a.h") == + "tests/preprocessor/pragma-once-a.h"); SLANG_CHECK(Path::hasRelativeElement(".")); @@ -55,8 +56,5 @@ SLANG_UNIT_TEST(path) SLANG_CHECK(Path::hasRelativeElement("a:/what/.././../is/./../this/./")); SLANG_CHECK(Path::hasRelativeElement("a:\\what\\..\\.\\..\\is\\.\\..\\this\\.\\")); - - } } - diff --git a/tools/slang-unit-test/unit-test-persistent-cache.cpp b/tools/slang-unit-test/unit-test-persistent-cache.cpp index cb7ebcab2..fa5d286f2 100644 --- a/tools/slang-unit-test/unit-test-persistent-cache.cpp +++ b/tools/slang-unit-test/unit-test-persistent-cache.cpp @@ -1,18 +1,17 @@ // unit-test-persistent-cache.cpp -#include "tools/unit-test/slang-unit-test.h" - -#include "../../source/core/slang-persistent-cache.h" -#include "../../source/core/slang-io.h" #include "../../source/core/slang-file-system.h" -#include "../../source/core/slang-random-generator.h" +#include "../../source/core/slang-io.h" +#include "../../source/core/slang-persistent-cache.h" #include "../../source/core/slang-process.h" +#include "../../source/core/slang-random-generator.h" +#include "tools/unit-test/slang-unit-test.h" -#include <chrono> -#include <thread> #include <atomic> -#include <mutex> +#include <chrono> #include <condition_variable> #include <functional> +#include <mutex> +#include <thread> using namespace Slang; @@ -28,19 +27,17 @@ inline ComPtr<ISlangBlob> createRandomBlob(size_t size) inline bool isBlobEqual(ISlangBlob* a, ISlangBlob* b) { - return - a->getBufferSize() == b->getBufferSize() && - ::memcmp(a->getBufferPointer(), b->getBufferPointer(), a->getBufferSize()) == 0; + return a->getBufferSize() == b->getBufferSize() && + ::memcmp(a->getBufferPointer(), b->getBufferPointer(), a->getBufferSize()) == 0; } class Barrier { public: Barrier(size_t threadCount, std::function<void()> completionFunc = nullptr) - : m_threadCount(threadCount) - , m_waitCount(threadCount) - , m_completionFunc(completionFunc) - {} + : m_threadCount(threadCount), m_waitCount(threadCount), m_completionFunc(completionFunc) + { + } Barrier(const Barrier& barrier) = delete; Barrier& operator=(const Barrier& barrier) = delete; @@ -53,14 +50,15 @@ public: if (--m_waitCount == 0) { - if (m_completionFunc) m_completionFunc(); + if (m_completionFunc) + m_completionFunc(); ++m_generation; m_waitCount = m_threadCount; m_condition.notify_all(); } else { - m_condition.wait(lock, [this, generation] () { return generation != m_generation; }); + m_condition.wait(lock, [this, generation]() { return generation != m_generation; }); } } @@ -87,7 +85,9 @@ struct PersistentCacheTest PersistentCacheTest(Count maxEntryCount = 0) { osFileSystem = OSFileSystem::getMutableSingleton(); - cacheDirectory = Path::simplify(Path::getParentDirectory(Path::getExecutablePath()) + "/persistent-cache-test" + String(Process::getId())); + cacheDirectory = Path::simplify( + Path::getParentDirectory(Path::getExecutablePath()) + "/persistent-cache-test" + + String(Process::getId())); removeCacheFiles(); @@ -153,16 +153,10 @@ struct PersistentCacheTest } // Get the absolute filename for a cache entry file. - String getEntryFileName(const Entry& entry) - { - return cache->getEntryFileName(entry.key); - } + String getEntryFileName(const Entry& entry) { return cache->getEntryFileName(entry.key); } // Get the absolute filename of the cache index file. - String getIndexFilename() - { - return cache->m_indexFileName; - } + String getIndexFilename() { return cache->m_indexFileName; } }; } // namespace Slang @@ -174,7 +168,10 @@ struct PersistentCacheTest // - resetting stats struct BasicTest : public PersistentCacheTest { - BasicTest() : PersistentCacheTest() {} + BasicTest() + : PersistentCacheTest() + { + } void run() { @@ -189,7 +186,7 @@ struct BasicTest : public PersistentCacheTest { auto data = createRandomBlob(i * 1024); auto key = SHA1::compute(data->getBufferPointer(), data->getBufferSize()); - entries.add(Entry{ key, data }); + entries.add(Entry{key, data}); } for (size_t i = 0; i < 10; ++i) @@ -251,7 +248,10 @@ struct BasicTest : public PersistentCacheTest // Tests the least-recently-used cache eviction policy. struct EvictionTest : public PersistentCacheTest { - EvictionTest() : PersistentCacheTest(3) {} + EvictionTest() + : PersistentCacheTest(3) + { + } void run() { @@ -261,7 +261,7 @@ struct EvictionTest : public PersistentCacheTest { auto data = createRandomBlob(4096); auto key = SHA1::compute(data->getBufferPointer(), data->getBufferSize()); - entries.add(Entry{ key, data }); + entries.add(Entry{key, data}); } writeEntry(entries[0]); @@ -335,8 +335,8 @@ struct CorruptionTest : public PersistentCacheTest { auto data = createRandomBlob(4096); auto key = SHA1::compute(data->getBufferPointer(), data->getBufferSize()); - entries.add(Entry{ key, data }); - } + entries.add(Entry{key, data}); + } // Test behavior when a cached entry file is removed externally before reading. writeEntry(entries[0]); @@ -372,17 +372,18 @@ struct CorruptionTest : public PersistentCacheTest // Test different corruptions of the index file. testIndexCorruption( - [this]() - { - osFileSystem->remove(getIndexFilename().getBuffer()); - }, + [this]() { osFileSystem->remove(getIndexFilename().getBuffer()); }, SLANG_E_NOT_FOUND); testIndexCorruption( [this]() { FileStream fs; - fs.init(getIndexFilename(), FileMode::Open, FileAccess::ReadWrite, FileShare::ReadWrite); + fs.init( + getIndexFilename(), + FileMode::Open, + FileAccess::ReadWrite, + FileShare::ReadWrite); fs.write("x", 1); }, SLANG_E_INTERNAL_FAIL); @@ -391,7 +392,11 @@ struct CorruptionTest : public PersistentCacheTest [this]() { FileStream fs; - fs.init(getIndexFilename(), FileMode::Open, FileAccess::ReadWrite, FileShare::ReadWrite); + fs.init( + getIndexFilename(), + FileMode::Open, + FileAccess::ReadWrite, + FileShare::ReadWrite); fs.seek(SeekOrigin::Start, 4); uint32_t version = 0xffffffff; fs.write(&version, sizeof(version)); @@ -402,7 +407,11 @@ struct CorruptionTest : public PersistentCacheTest [this]() { FileStream fs; - fs.init(getIndexFilename(), FileMode::Open, FileAccess::ReadWrite, FileShare::ReadWrite); + fs.init( + getIndexFilename(), + FileMode::Open, + FileAccess::ReadWrite, + FileShare::ReadWrite); fs.seek(SeekOrigin::Start, 8); uint32_t count = 0x7fffffff; fs.write(&count, sizeof(count)); @@ -413,7 +422,11 @@ struct CorruptionTest : public PersistentCacheTest [this]() { FileStream fs; - fs.init(getIndexFilename(), FileMode::Open, FileAccess::ReadWrite, FileShare::ReadWrite); + fs.init( + getIndexFilename(), + FileMode::Open, + FileAccess::ReadWrite, + FileShare::ReadWrite); fs.seek(SeekOrigin::Start, 8); uint32_t count = 0; fs.write(&count, sizeof(count)); @@ -424,7 +437,11 @@ struct CorruptionTest : public PersistentCacheTest [this]() { FileStream fs; - fs.init(getIndexFilename(), FileMode::Open, FileAccess::ReadWrite, FileShare::ReadWrite); + fs.init( + getIndexFilename(), + FileMode::Open, + FileAccess::ReadWrite, + FileShare::ReadWrite); fs.seek(SeekOrigin::End, 0); fs.write("x", 1); }, @@ -432,11 +449,13 @@ struct CorruptionTest : public PersistentCacheTest } }; -#undef ENABLE_LOGGING +#undef ENABLE_LOGGING #undef ENABLE_WRITE_TEST #ifdef ENABLE_LOGGING -#define LOG(fmt, ...) printf(fmt, ##__VA_ARGS__); fflush(stdout); +#define LOG(fmt, ...) \ + printf(fmt, ##__VA_ARGS__); \ + fflush(stdout); #else #define LOG(fmt, ...) #endif @@ -475,10 +494,13 @@ struct StressTest : public PersistentCacheTest std::atomic<uint32_t> readSuccess{0}; std::thread threads[kThreadCount]; - Barrier *read_barrier; - Barrier *write_barrier; + Barrier* read_barrier; + Barrier* write_barrier; - StressTest() : PersistentCacheTest(kEntryCount - kEntryShortageCount) {} + StressTest() + : PersistentCacheTest(kEntryCount - kEntryShortageCount) + { + } void run() { @@ -488,20 +510,16 @@ struct StressTest : public PersistentCacheTest size_t size = rng.nextInt32InRange(256, 64 * 1024); auto data = createRandomBlob(size); auto key = SHA1::compute(data->getBufferPointer(), data->getBufferSize()); - entries.add(Entry{ key, data }); + entries.add(Entry{key, data}); } auto startTime = std::chrono::high_resolution_clock::now(); - Barrier read_barrier_( - kThreadCount, - []() - { - LOG("Read synchronized\n"); - }); + Barrier read_barrier_(kThreadCount, []() { LOG("Read synchronized\n"); }); Barrier write_barrier_( kThreadCount, - [this](){ + [this]() + { LOG("Write synchronized\n"); #ifndef ENABLE_WRITE_TEST SLANG_CHECK(readSuccess == kEntryCount - kEntryShortageCount); @@ -523,12 +541,16 @@ struct StressTest : public PersistentCacheTest while (true) { // Write to cache. - size_t startIndex = (iteration * kEntryCount + (threadIndex * kBatchCount)) % (kEntryCount * 2); + size_t startIndex = + (iteration * kEntryCount + (threadIndex * kBatchCount)) % + (kEntryCount * 2); for (size_t i = 0; i < kBatchCount; ++i) { const Entry& entry = entries[startIndex + i]; #ifdef ENABLE_WRITE_TEST - osFileSystem->saveFileBlob(getEntryFileName(entry).getBuffer(), entry.data); + osFileSystem->saveFileBlob( + getEntryFileName(entry).getBuffer(), + entry.data); #else writeEntry(entry); #endif @@ -536,7 +558,9 @@ struct StressTest : public PersistentCacheTest bytesWritten.fetch_add((uint32_t)entry.data->getBufferSize()); } - LOG("Thread %u: ended writing (iteration=%u)\n", threadIndex, iteration.load()); + LOG("Thread %u: ended writing (iteration=%u)\n", + threadIndex, + iteration.load()); // Synchronize. read_barrier->wait(); @@ -555,7 +579,9 @@ struct StressTest : public PersistentCacheTest entriesRead.fetch_add(1); } - LOG("Thread %u: ended reading (iteration=%u)\n", threadIndex, iteration.load()); + LOG("Thread %u: ended reading (iteration=%u)\n", + threadIndex, + iteration.load()); // Synchronize. write_barrier->wait(); @@ -577,7 +603,8 @@ struct StressTest : public PersistentCacheTest auto endTime = std::chrono::high_resolution_clock::now(); auto duration = endTime - startTime; - auto seconds = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count() / 1000.0; + auto seconds = + std::chrono::duration_cast<std::chrono::milliseconds>(duration).count() / 1000.0; LOG("Total time: %.3fs\n", seconds); LOG("Total bytes written: %d\n", bytesWritten.load()); diff --git a/tools/slang-unit-test/unit-test-process.cpp b/tools/slang-unit-test/unit-test-process.cpp index d24120716..8866f4a9e 100644 --- a/tools/slang-unit-test/unit-test-process.cpp +++ b/tools/slang-unit-test/unit-test-process.cpp @@ -1,17 +1,19 @@ // unit-test-process.cpp -#include "../../source/core/slang-string-util.h" -#include "../../source/core/slang-process-util.h" - -#include "../../source/core/slang-io.h" #include "../../source/core/slang-http.h" +#include "../../source/core/slang-io.h" +#include "../../source/core/slang-process-util.h" #include "../../source/core/slang-random-generator.h" - +#include "../../source/core/slang-string-util.h" #include "tools/unit-test/slang-unit-test.h" using namespace Slang; -static SlangResult _createProcess(UnitTestContext* context, const char* toolName, const List<String>* optArgs, RefPtr<Process>& outProcess) +static SlangResult _createProcess( + UnitTestContext* context, + const char* toolName, + const List<String>* optArgs, + RefPtr<Process>& outProcess) { CommandLine cmdLine; cmdLine.setExecutableLocation(ExecutableLocation(context->executableDirectory, "test-process")); @@ -34,7 +36,8 @@ static SlangResult _httpReflectTest(UnitTestContext* context) SLANG_RETURN_ON_FAIL(_createProcess(context, "http-reflect", nullptr, process)); Stream* writeStream = process->getStream(StdStreamType::In); - RefPtr<BufferedReadStream> readStream( new BufferedReadStream(process->getStream(StdStreamType::Out))); + RefPtr<BufferedReadStream> readStream( + new BufferedReadStream(process->getStream(StdStreamType::Out))); RefPtr<HTTPPacketConnection> connection = new HTTPPacketConnection(readStream, writeStream); RefPtr<RandomGenerator> rand = RandomGenerator::create(10000); @@ -91,7 +94,8 @@ static SlangResult _httpReflectTest(UnitTestContext* context) static SlangResult _countTest(UnitTestContext* context, Index size, Index crashIndex = -1) { /* Here we are trying to test what happens if the server produces a large amount of data, and - we just wait for termination. Do we receive all of the data irrespective of how much there is? */ + we just wait for termination. Do we receive all of the data irrespective of how much there is? + */ List<String> args; { @@ -147,7 +151,7 @@ static SlangResult _countTest(UnitTestContext* context, Index size, Index crashI static SlangResult _countTests(UnitTestContext* context) { - const Index sizes[] = { 1, 10, 1000, 1000, 10000, 100000 }; + const Index sizes[] = {1, 10, 1000, 1000, 10000, 100000}; for (auto size : sizes) { SLANG_RETURN_ON_FAIL(_countTest(context, size)); diff --git a/tools/slang-unit-test/unit-test-record-replay.cpp b/tools/slang-unit-test/unit-test-record-replay.cpp index 33bbab0c3..b81304937 100644 --- a/tools/slang-unit-test/unit-test-record-replay.cpp +++ b/tools/slang-unit-test/unit-test-record-replay.cpp @@ -1,12 +1,10 @@ // unit-test-record-replay.cpp -#include "../../source/core/slang-string-util.h" -#include "../../source/core/slang-process-util.h" - -#include "../../source/core/slang-io.h" #include "../../source/core/slang-http.h" +#include "../../source/core/slang-io.h" +#include "../../source/core/slang-process-util.h" #include "../../source/core/slang-random-generator.h" - +#include "../../source/core/slang-string-util.h" #include "tools/unit-test/slang-unit-test.h" #include <chrono> @@ -14,7 +12,11 @@ using namespace Slang; -static SlangResult createProcess(UnitTestContext* context, const char* processName, const List<String>* optArgs, RefPtr<Process>& outProcess) +static SlangResult createProcess( + UnitTestContext* context, + const char* processName, + const List<String>* optArgs, + RefPtr<Process>& outProcess) { CommandLine cmdLine; cmdLine.setExecutableLocation(ExecutableLocation(context->executableDirectory, processName)); @@ -60,7 +62,9 @@ static SlangResult parseHashes(List<String> const& lines, List<entryHashInfo>& o } entryHashInfo hashInfo; - auto extractToken = [](const UnownedStringSlice& token, const char splitChar, UnownedStringSlice& outToken) -> SlangResult + auto extractToken = [](const UnownedStringSlice& token, + const char splitChar, + UnownedStringSlice& outToken) -> SlangResult { List<UnownedStringSlice> subTokens; StringUtil::split(token, splitChar, subTokens); @@ -153,7 +157,10 @@ static void findRecordFileName(List<String>* fileNames) m_fileNames->add(filename); } } - Visitor(List<String>* fileNames) : m_fileNames(fileNames) {} + Visitor(List<String>* fileNames) + : m_fileNames(fileNames) + { + } List<String>* m_fileNames; }; @@ -161,14 +168,18 @@ static void findRecordFileName(List<String>* fileNames) Path::find("slang-record", "*.cap", &visitor); } -static SlangResult launchProcessAndReadStdout(UnitTestContext* context, const List<String>& optArgs, - const char* exampleName, RefPtr<Process>& process, ExecuteResult& exeRes) +static SlangResult launchProcessAndReadStdout( + UnitTestContext* context, + const List<String>& optArgs, + const char* exampleName, + RefPtr<Process>& process, + ExecuteResult& exeRes) { StringBuilder msgBuilder; SlangResult res = createProcess(context, exampleName, &optArgs, process); if (SLANG_FAILED(res)) { - msgBuilder << "Failed to launch process of '"<< exampleName << "'\n"; + msgBuilder << "Failed to launch process of '" << exampleName << "'\n"; getTestReporter()->message(TestMessageType::TestFailure, msgBuilder.toString().getBuffer()); return res; } @@ -202,7 +213,10 @@ static SlangResult launchProcessAndReadStdout(UnitTestContext* context, const Li return SLANG_OK; } -static SlangResult runExample(UnitTestContext* context, const char* exampleName, List<entryHashInfo>& outHashes) +static SlangResult runExample( + UnitTestContext* context, + const char* exampleName, + List<entryHashInfo>& outHashes) { SlangResult finalRes = SLANG_OK; @@ -301,7 +315,9 @@ static SlangResult replayExample(UnitTestContext* context, List<entryHashInfo>& return SLANG_OK; } -static SlangResult resultCompare(List<entryHashInfo> const& expectHashes, List<entryHashInfo> const& resultHashes) +static SlangResult resultCompare( + List<entryHashInfo> const& expectHashes, + List<entryHashInfo> const& resultHashes) { if (expectHashes.getCount() == 0) { @@ -312,7 +328,8 @@ static SlangResult resultCompare(List<entryHashInfo> const& expectHashes, List<e StringBuilder msgBuilder; if (expectHashes.getCount() != resultHashes.getCount()) { - msgBuilder << "The number of hashes doesn't match, expect: " << expectHashes.getCount() << ", actual: " << resultHashes.getCount() << "\n"; + msgBuilder << "The number of hashes doesn't match, expect: " << expectHashes.getCount() + << ", actual: " << resultHashes.getCount() << "\n"; getTestReporter()->message(TestMessageType::TestFailure, msgBuilder.toString().getBuffer()); return SLANG_FAIL; } @@ -322,23 +339,32 @@ static SlangResult resultCompare(List<entryHashInfo> const& expectHashes, List<e if (expectHashes[i].targetIndex != resultHashes[i].targetIndex) { msgBuilder << "Failed to match 'targetIndex' at index " << i << "\n"; - msgBuilder << "Expect: " << expectHashes[i].targetIndex << ", actual: " << resultHashes[i].targetIndex << "\n"; - getTestReporter()->message(TestMessageType::TestFailure, msgBuilder.toString().getBuffer()); + msgBuilder << "Expect: " << expectHashes[i].targetIndex + << ", actual: " << resultHashes[i].targetIndex << "\n"; + getTestReporter()->message( + TestMessageType::TestFailure, + msgBuilder.toString().getBuffer()); return SLANG_FAIL; } if (expectHashes[i].entryPointIndex != resultHashes[i].entryPointIndex) { msgBuilder << "Failed to match 'entryPointIndex' at index " << i << "\n"; - msgBuilder << "Expect: " << expectHashes[i].entryPointIndex << ", actual: " << resultHashes[i].entryPointIndex << "\n"; - getTestReporter()->message(TestMessageType::TestFailure, msgBuilder.toString().getBuffer()); + msgBuilder << "Expect: " << expectHashes[i].entryPointIndex + << ", actual: " << resultHashes[i].entryPointIndex << "\n"; + getTestReporter()->message( + TestMessageType::TestFailure, + msgBuilder.toString().getBuffer()); return SLANG_FAIL; } if (expectHashes[i].hash != resultHashes[i].hash) { msgBuilder << "Failed to match 'hash' at index " << i << "\n"; - msgBuilder << "Expect: " << expectHashes[i].hash << ", actual: " << resultHashes[i].hash << "\n"; - getTestReporter()->message(TestMessageType::TestFailure, msgBuilder.toString().getBuffer()); + msgBuilder << "Expect: " << expectHashes[i].hash << ", actual: " << resultHashes[i].hash + << "\n"; + getTestReporter()->message( + TestMessageType::TestFailure, + msgBuilder.toString().getBuffer()); return SLANG_FAIL; } } @@ -351,7 +377,9 @@ static SlangResult cleanupRecordFiles() SlangResult res = Path::removeNonEmpty("slang-record"); if (SLANG_FAILED(res)) { - getTestReporter()->message(TestMessageType::TestFailure, "Failed to remove 'slang-record' directory\n"); + getTestReporter()->message( + TestMessageType::TestFailure, + "Failed to remove 'slang-record' directory\n"); } return res; @@ -362,17 +390,17 @@ static SlangResult runTest(UnitTestContext* context, const char* testName) List<entryHashInfo> expectHashes; List<entryHashInfo> resultHashes; SlangResult res = SLANG_OK; - if((res = runExample(context, testName, expectHashes)) != SLANG_OK) + if ((res = runExample(context, testName, expectHashes)) != SLANG_OK) { goto error; } - if((res = replayExample(context, resultHashes)) != SLANG_OK) + if ((res = replayExample(context, resultHashes)) != SLANG_OK) { goto error; } - if((res = resultCompare(expectHashes, resultHashes)) != SLANG_OK) + if ((res = resultCompare(expectHashes, resultHashes)) != SLANG_OK) { goto error; } @@ -384,15 +412,15 @@ error: static SlangResult runTests(UnitTestContext* context) { - const char* testBinaryNames[] = { + const char* testBinaryNames[] = { "cpu-hello-world", "triangle", "ray-tracing", "ray-tracing-pipeline", "autodiff-texture", "gpu-printing" - // "shader-object", // these examples requires reflection API to replay, we have to disable it for now. - // "model-viewer", + // "shader-object", // these examples requires reflection API to replay, we have to disable + // it for now. "model-viewer", }; SlangResult finalRes = SLANG_OK; @@ -403,7 +431,9 @@ static SlangResult runTests(UnitTestContext* context) { StringBuilder msgBuilder; msgBuilder << "Failed subtest: '" << testBinaryName << "'\n\n\n"; - getTestReporter()->message(TestMessageType::TestFailure, msgBuilder.toString().getBuffer()); + getTestReporter()->message( + TestMessageType::TestFailure, + msgBuilder.toString().getBuffer()); finalRes = res; } } diff --git a/tools/slang-unit-test/unit-test-riff.cpp b/tools/slang-unit-test/unit-test-riff.cpp index 2902a9af5..a0eb91a47 100644 --- a/tools/slang-unit-test/unit-test-riff.cpp +++ b/tools/slang-unit-test/unit-test-riff.cpp @@ -1,14 +1,16 @@ // unit-test-riff.cpp -#include "../../source/core/slang-riff.h" - #include "../../source/core/slang-random-generator.h" - +#include "../../source/core/slang-riff.h" #include "tools/unit-test/slang-unit-test.h" using namespace Slang; -static void _writeRandom(RandomGenerator* rand, size_t maxSize, RiffContainer& ioContainer, List<uint8_t>& ioData) +static void _writeRandom( + RandomGenerator* rand, + size_t maxSize, + RiffContainer& ioContainer, + List<uint8_t>& ioData) { while (true) { @@ -29,7 +31,8 @@ static void _writeRandom(RandomGenerator* rand, size_t maxSize, RiffContainer& i } // Should be a single block with same data as the List - RiffContainer::DataChunk* dataChunk = as<RiffContainer::DataChunk>(ioContainer.getCurrentChunk()); + RiffContainer::DataChunk* dataChunk = + as<RiffContainer::DataChunk>(ioContainer.getCurrentChunk()); SLANG_ASSERT(dataChunk); } @@ -45,7 +48,7 @@ SLANG_UNIT_TEST(riff) RiffContainer container; { - ScopeChunk scopeContainer(&container, Kind::List, markThings); + ScopeChunk scopeContainer(&container, Kind::List, markThings); { ScopeChunk scopeChunk(&container, Kind::Data, markData); @@ -89,7 +92,7 @@ SLANG_UNIT_TEST(riff) } { - OwnedMemoryStream stream(FileAccess::ReadWrite); + OwnedMemoryStream stream(FileAccess::ReadWrite); SLANG_CHECK(SLANG_SUCCEEDED(RiffUtil::write(container.getRoot(), true, &stream))); stream.seek(SeekOrigin::Start, 0); @@ -108,10 +111,10 @@ SLANG_UNIT_TEST(riff) SLANG_CHECK(readBuilder == builder); } } - } - // Test writing as a stream only allocates a single data block (as long as there is enough space). + // Test writing as a stream only allocates a single data block (as long as there is enough + // space). { RiffContainer container; @@ -121,39 +124,46 @@ SLANG_UNIT_TEST(riff) RefPtr<RandomGenerator> rand = RandomGenerator::create(0x345234); List<uint8_t> data; - _writeRandom(rand, container.getMemoryArena().getBlockPayloadSize() / 2, container, data); + _writeRandom( + rand, + container.getMemoryArena().getBlockPayloadSize() / 2, + container, + data); // Should be a single block with same data as the List - RiffContainer::DataChunk* dataChunk = as<RiffContainer::DataChunk>(container.getCurrentChunk()); + RiffContainer::DataChunk* dataChunk = + as<RiffContainer::DataChunk>(container.getCurrentChunk()); SLANG_ASSERT(dataChunk); // It should be a single block SLANG_CHECK(dataChunk->getSingleData() != nullptr); SLANG_CHECK(dataChunk->isEqual(data.getBuffer(), data.getCount())); - } - } + } // Test writing across multiple data blocks { RefPtr<RandomGenerator> rand = RandomGenerator::create(0x345234); - for (Int i = 0 ; i < 100; ++i) + for (Int i = 0; i < 100; ++i) { RiffContainer container; - const size_t maxSize = rand->nextInt32InRange(1, int32_t(container.getMemoryArena().getBlockPayloadSize() * 3)); - + const size_t maxSize = rand->nextInt32InRange( + 1, + int32_t(container.getMemoryArena().getBlockPayloadSize() * 3)); + ScopeChunk scopeChunk(&container, Kind::List, markData); { ScopeChunk scopeChunk(&container, Kind::Data, markData); - + List<uint8_t> data; _writeRandom(rand, maxSize, container, data); // Should be a single block with same data as the List - RiffContainer::DataChunk* dataChunk = as<RiffContainer::DataChunk>(container.getCurrentChunk()); + RiffContainer::DataChunk* dataChunk = + as<RiffContainer::DataChunk>(container.getCurrentChunk()); SLANG_CHECK(dataChunk && dataChunk->isEqual(data.getBuffer(), data.getCount())); } } @@ -176,4 +186,3 @@ SLANG_UNIT_TEST(riff) } #endif } - diff --git a/tools/slang-unit-test/unit-test-rtti.cpp b/tools/slang-unit-test/unit-test-rtti.cpp index f72cfbde2..485d58aea 100644 --- a/tools/slang-unit-test/unit-test-rtti.cpp +++ b/tools/slang-unit-test/unit-test-rtti.cpp @@ -1,12 +1,12 @@ // unit-test-rtti.cpp #include "../../source/core/slang-rtti-info.h" - #include "tools/unit-test/slang-unit-test.h" using namespace Slang; -namespace { // anonymous +namespace +{ // anonymous struct SomeStruct { @@ -18,7 +18,7 @@ struct SomeStruct static const StructRttiInfo g_rttiInfo; }; -} // anonymous +} // namespace static const StructRttiInfo _makeSomeStructRtti() { @@ -32,14 +32,13 @@ static const StructRttiInfo _makeSomeStructRtti() return builder.make(); } -/* static */const StructRttiInfo SomeStruct::g_rttiInfo = _makeSomeStructRtti(); +/* static */ const StructRttiInfo SomeStruct::g_rttiInfo = _makeSomeStructRtti(); SLANG_UNIT_TEST(Rtti) { using namespace Slang; - const RttiInfo* types[] = - { + const RttiInfo* types[] = { GetRttiInfo<int32_t>::get(), GetRttiInfo<int32_t[10]>::get(), GetRttiInfo<String>::get(), @@ -48,7 +47,7 @@ SLANG_UNIT_TEST(Rtti) GetRttiInfo<int32_t[2][3]>::get(), GetRttiInfo<SomeStruct>::get(), GetRttiInfo<SomeStruct*>::get(), - GetRttiInfo<const float*const>::get(), + GetRttiInfo<const float* const>::get(), }; StringBuilder buf; @@ -59,16 +58,15 @@ SLANG_UNIT_TEST(Rtti) buf << "\n"; } - const char expected[] = - "int32_t\n" - "int32_t[10]\n" - "String\n" - "List<String>\n" - "List<List<String>>\n" - "int32_t[2][3]\n" - "SomeStruct\n" - "SomeStruct*\n" - "float*\n"; + const char expected[] = "int32_t\n" + "int32_t[10]\n" + "String\n" + "List<String>\n" + "List<List<String>>\n" + "int32_t[2][3]\n" + "SomeStruct\n" + "SomeStruct*\n" + "float*\n"; SLANG_CHECK(buf == expected) } diff --git a/tools/slang-unit-test/unit-test-short-list.cpp b/tools/slang-unit-test/unit-test-short-list.cpp index 2760d633e..9d5de9328 100644 --- a/tools/slang-unit-test/unit-test-short-list.cpp +++ b/tools/slang-unit-test/unit-test-short-list.cpp @@ -19,36 +19,36 @@ static bool _checkArrayView(ArrayView<T> v0, ArrayView<T> v1) SLANG_UNIT_TEST(shortList) { { - ShortList<String, 4> shortList = { "a", "b", "c" }; + ShortList<String, 4> shortList = {"a", "b", "c"}; shortList.add("d"); auto arrayView = shortList.getArrayView(); SLANG_CHECK(arrayView.ownsStorage == false); - SLANG_CHECK(_checkArrayView(arrayView.arrayView, - List<String>{"a", "b", "c", "d"}.getArrayView())); + SLANG_CHECK( + _checkArrayView(arrayView.arrayView, List<String>{"a", "b", "c", "d"}.getArrayView())); shortList.add("e"); auto arrayView2 = shortList.getArrayView(); SLANG_CHECK(arrayView2.ownsStorage == true); - SLANG_CHECK(_checkArrayView(arrayView2.arrayView, + SLANG_CHECK(_checkArrayView( + arrayView2.arrayView, List<String>{"a", "b", "c", "d", "e"}.getArrayView())); auto arrayView3 = shortList.getArrayView(0, 2); SLANG_CHECK(arrayView3.ownsStorage == false); - SLANG_CHECK(_checkArrayView(arrayView3.arrayView, - List<String>{"a", "b"}.getArrayView())); + SLANG_CHECK(_checkArrayView(arrayView3.arrayView, List<String>{"a", "b"}.getArrayView())); auto arrayView4 = shortList.getArrayView(4, 1); SLANG_CHECK(arrayView4.ownsStorage == false); - SLANG_CHECK(_checkArrayView(arrayView4.arrayView, - List<String>{"e"}.getArrayView())); + SLANG_CHECK(_checkArrayView(arrayView4.arrayView, List<String>{"e"}.getArrayView())); auto arrayView5 = shortList.getArrayView(2, 3); SLANG_CHECK(arrayView5.ownsStorage == true); - SLANG_CHECK(_checkArrayView(arrayView5.arrayView, - List<String>{"c", "d", "e"}.getArrayView())); + SLANG_CHECK( + _checkArrayView(arrayView5.arrayView, List<String>{"c", "d", "e"}.getArrayView())); ShortList<String, 1> copy2; ShortList<String, 2> copy1; copy1 = shortList; for (auto item : copy1) copy2.add(item); - SLANG_CHECK(_checkArrayView(copy2.getArrayView().arrayView, + SLANG_CHECK(_checkArrayView( + copy2.getArrayView().arrayView, List<String>{"a", "b", "c", "d", "e"}.getArrayView())); SLANG_CHECK(copy2.indexOf("a") == 0); @@ -61,17 +61,20 @@ SLANG_UNIT_TEST(shortList) copy2.add("f"); copy2.fastRemove("c"); copy2.compress(); - SLANG_CHECK(_checkArrayView(copy2.getArrayView().arrayView, + SLANG_CHECK(_checkArrayView( + copy2.getArrayView().arrayView, List<String>{"a", "b", "f", "d", "e"}.getArrayView())); shortList.removeLast(); shortList.removeLast(); shortList.compress(); - SLANG_CHECK(_checkArrayView(shortList.getArrayView().arrayView, + SLANG_CHECK(_checkArrayView( + shortList.getArrayView().arrayView, List<String>{"a", "b", "c"}.getArrayView())); shortList.add("d"); shortList.add("e"); - SLANG_CHECK(_checkArrayView(shortList.getArrayView().arrayView, + SLANG_CHECK(_checkArrayView( + shortList.getArrayView().arrayView, List<String>{"a", "b", "c", "d", "e"}.getArrayView())); } } diff --git a/tools/slang-unit-test/unit-test-source-map.cpp b/tools/slang-unit-test/unit-test-source-map.cpp index d4363e02c..797229afe 100644 --- a/tools/slang-unit-test/unit-test-source-map.cpp +++ b/tools/slang-unit-test/unit-test-source-map.cpp @@ -1,28 +1,29 @@ #include "../../source/compiler-core/slang-json-lexer.h" -#include "../../source/core/slang-string-escape-util.h" +#include "../../source/compiler-core/slang-json-native.h" #include "../../source/compiler-core/slang-json-parser.h" +#include "../../source/compiler-core/slang-json-source-map-util.h" #include "../../source/compiler-core/slang-json-value.h" - -#include "../../source/compiler-core/slang-json-native.h" - #include "../../source/compiler-core/slang-source-map.h" -#include "../../source/compiler-core/slang-json-source-map-util.h" - #include "../../source/core/slang-rtti-info.h" - +#include "../../source/core/slang-string-escape-util.h" #include "tools/unit-test/slang-unit-test.h" using namespace Slang; -static SlangResult _read(JSONContainer* container, const String& json, DiagnosticSink* sink, SourceMap& outSourceMap) +static SlangResult _read( + JSONContainer* container, + const String& json, + DiagnosticSink* sink, + SourceMap& outSourceMap) { auto sourceManager = sink->getSourceManager(); JSONValue rootValue; { // Now need to parse as JSON - SourceFile* sourceFile = sourceManager->createSourceFileWithString(PathInfo::makeUnknown(), json); + SourceFile* sourceFile = + sourceManager->createSourceFileWithString(PathInfo::makeUnknown(), json); SourceView* sourceView = sourceManager->createSourceView(sourceFile, nullptr, SourceLoc()); JSONLexer lexer; @@ -41,7 +42,11 @@ static SlangResult _read(JSONContainer* container, const String& json, Diagnosti return SLANG_OK; } -static SlangResult _write(JSONContainer* container, const SourceMap& sourceMap, DiagnosticSink* sink, String& out) +static SlangResult _write( + JSONContainer* container, + const SourceMap& sourceMap, + DiagnosticSink* sink, + String& out) { // Write it out JSONValue jsonValue; @@ -78,10 +83,10 @@ static SlangResult _check() SourceMap sourceMap; SLANG_RETURN_ON_FAIL(_read(container, jsonSource, &sink, sourceMap)); - + String json; SLANG_RETURN_ON_FAIL(_write(container, sourceMap, &sink, json)); - + SourceMap readSourceMap; SLANG_RETURN_ON_FAIL(_read(container, json, &sink, readSourceMap)); @@ -89,7 +94,7 @@ static SlangResult _check() { return SLANG_FAIL; } - + // Lets try copy construction { SourceMap copy(sourceMap); @@ -117,4 +122,3 @@ SLANG_UNIT_TEST(sourceMap) { SLANG_CHECK(SLANG_SUCCEEDED(_check())); } - diff --git a/tools/slang-unit-test/unit-test-string-escape.cpp b/tools/slang-unit-test/unit-test-string-escape.cpp index 337573081..3a1cb7f06 100644 --- a/tools/slang-unit-test/unit-test-string-escape.cpp +++ b/tools/slang-unit-test/unit-test-string-escape.cpp @@ -1,79 +1,80 @@ // unit-test-string-escape.cpp #include "../../source/core/slang-string-escape-util.h" - #include "tools/unit-test/slang-unit-test.h" using namespace Slang; static bool _checkConversion(StringEscapeHandler* handler, const UnownedStringSlice& check) { - StringBuilder buf; - handler->appendEscaped(check, buf); + StringBuilder buf; + handler->appendEscaped(check, buf); - StringBuilder decode; - handler->appendUnescaped(buf.getUnownedSlice(), decode); + StringBuilder decode; + handler->appendUnescaped(buf.getUnownedSlice(), decode); - return decode == check; + return decode == check; } static bool _checkDecode(const UnownedStringSlice& encoded, const UnownedStringSlice& decoded) { - auto handler = StringEscapeUtil::getHandler(StringEscapeUtil::Style::Cpp); + auto handler = StringEscapeUtil::getHandler(StringEscapeUtil::Style::Cpp); - StringBuilder buf; - StringEscapeUtil::appendUnquoted(handler, encoded, buf); - return buf == decoded; + StringBuilder buf; + StringEscapeUtil::appendUnquoted(handler, encoded, buf); + return buf == decoded; } -#define SLANG_ENCODED_DECODED(x) \ - const auto encoded = toSlice(#x); \ - const auto decoded = toSlice(x); +#define SLANG_ENCODED_DECODED(x) \ + const auto encoded = toSlice(#x); \ + const auto decoded = toSlice(x); SLANG_UNIT_TEST(StringEscape) { - // Check greedy hex digits - { - // \x can have any number of hex digits - const char text[] = "\x000001"; - SLANG_ASSERT(SLANG_COUNT_OF(text) == 2 && text[0] == 1); - } - - // Check octal greedy - { - //\ + up to 3 octal digits - const char text[] = "\0011"; - SLANG_ASSERT(SLANG_COUNT_OF(text) == 3 && text[0] == 1 && text[1] == '1'); - - const char text2[] = "\78"; - SLANG_ASSERT(SLANG_COUNT_OF(text2) == 3 && text2[0] == 7 && text2[1] == '8'); - } - - { - auto handler = StringEscapeUtil::getHandler(StringEscapeUtil::Style::Cpp); - - SLANG_CHECK(_checkConversion(handler, toSlice("\0\1\2""2"))); - } - - { - auto handler = StringEscapeUtil::getHandler(StringEscapeUtil::Style::Cpp); - - // We can't just use '\uxxxx', because it has to be translatable into an output character in MSVC (not into utf8) - // Can make work perhaps with something like - // #pragma execution_character_set("utf-8") - // But for now we don't worry - // - // Visual Studio does not appear to support '\U' by default, presumably because wchar_t is 16 bits - - { - SLANG_ENCODED_DECODED("\a\b\0hey~\u0023\n\0"); - SLANG_CHECK(_checkDecode(encoded, decoded)); - } - - { - SLANG_ENCODED_DECODED("\n\v\b\t\1\02\003\x5z\x00007f\0"); - SLANG_CHECK(_checkDecode(encoded, decoded)); - } - } + // Check greedy hex digits + { + // \x can have any number of hex digits + const char text[] = "\x000001"; + SLANG_ASSERT(SLANG_COUNT_OF(text) == 2 && text[0] == 1); + } + + // Check octal greedy + { + //\ + up to 3 octal digits + const char text[] = "\0011"; + SLANG_ASSERT(SLANG_COUNT_OF(text) == 3 && text[0] == 1 && text[1] == '1'); + + const char text2[] = "\78"; + SLANG_ASSERT(SLANG_COUNT_OF(text2) == 3 && text2[0] == 7 && text2[1] == '8'); + } + + { + auto handler = StringEscapeUtil::getHandler(StringEscapeUtil::Style::Cpp); + + SLANG_CHECK(_checkConversion( + handler, + toSlice("\0\1\2" + "2"))); + } + + { + auto handler = StringEscapeUtil::getHandler(StringEscapeUtil::Style::Cpp); + + // We can't just use '\uxxxx', because it has to be translatable into an output character in + // MSVC (not into utf8) Can make work perhaps with something like #pragma + // execution_character_set("utf-8") But for now we don't worry + // + // Visual Studio does not appear to support '\U' by default, presumably because wchar_t is + // 16 bits + + { + SLANG_ENCODED_DECODED("\a\b\0hey~\u0023\n\0"); + SLANG_CHECK(_checkDecode(encoded, decoded)); + } + + { + SLANG_ENCODED_DECODED("\n\v\b\t\1\02\003\x5z\x00007f\0"); + SLANG_CHECK(_checkDecode(encoded, decoded)); + } + } } - diff --git a/tools/slang-unit-test/unit-test-string.cpp b/tools/slang-unit-test/unit-test-string.cpp index 230cb72f8..4a71bca4b 100644 --- a/tools/slang-unit-test/unit-test-string.cpp +++ b/tools/slang-unit-test/unit-test-string.cpp @@ -1,16 +1,18 @@ // unit-test-path.cpp #include "../../source/core/slang-string-util.h" - #include "tools/unit-test/slang-unit-test.h" -//#include <math.h> +// #include <math.h> #include <sstream> using namespace Slang; -static bool _areEqual(const List<UnownedStringSlice>& lines, const UnownedStringSlice* checkLines, Int checkLinesCount) +static bool _areEqual( + const List<UnownedStringSlice>& lines, + const UnownedStringSlice* checkLines, + Int checkLinesCount) { if (checkLinesCount != lines.getCount()) { @@ -27,7 +29,10 @@ static bool _areEqual(const List<UnownedStringSlice>& lines, const UnownedString return true; } -static bool _checkLines(const UnownedStringSlice& input, const UnownedStringSlice* checkLines, Int checkLinesCount) +static bool _checkLines( + const UnownedStringSlice& input, + const UnownedStringSlice* checkLines, + Int checkLinesCount) { List<UnownedStringSlice> lines; StringUtil::calcLines(input, lines); @@ -100,7 +105,11 @@ static int64_t _calcULPDistance(double a, double b) return distance < 0 ? -distance : distance; } -static bool _areApproximatelyEqual(double a, double b, double fixedEpsilon = 1e-10, int ulpsEpsilon = 100) +static bool _areApproximatelyEqual( + double a, + double b, + double fixedEpsilon = 1e-10, + int ulpsEpsilon = 100) { // Handle the near-zero case. const double difference = abs(a - b); @@ -115,8 +124,11 @@ static bool _areApproximatelyEqual(double a, double b, double fixedEpsilon = 1e- SLANG_UNIT_TEST(string) { { - UnownedStringSlice checkLines[] = { UnownedStringSlice::fromLiteral("") }; - SLANG_CHECK(_checkLines(UnownedStringSlice::fromLiteral(""), checkLines, SLANG_COUNT_OF(checkLines))); + UnownedStringSlice checkLines[] = {UnownedStringSlice::fromLiteral("")}; + SLANG_CHECK(_checkLines( + UnownedStringSlice::fromLiteral(""), + checkLines, + SLANG_COUNT_OF(checkLines))); } { // Will emit no lines @@ -124,16 +136,30 @@ SLANG_UNIT_TEST(string) } { // Two lines - both empty - UnownedStringSlice checkLines[] = { UnownedStringSlice(), UnownedStringSlice()}; - SLANG_CHECK(_checkLines(UnownedStringSlice::fromLiteral("\n"), checkLines, SLANG_COUNT_OF(checkLines))); + UnownedStringSlice checkLines[] = {UnownedStringSlice(), UnownedStringSlice()}; + SLANG_CHECK(_checkLines( + UnownedStringSlice::fromLiteral("\n"), + checkLines, + SLANG_COUNT_OF(checkLines))); } { - UnownedStringSlice checkLines[] = { UnownedStringSlice::fromLiteral("Hello"), UnownedStringSlice::fromLiteral("World!") }; - SLANG_CHECK(_checkLines(UnownedStringSlice::fromLiteral("Hello\nWorld!"), checkLines, SLANG_COUNT_OF(checkLines))); + UnownedStringSlice checkLines[] = { + UnownedStringSlice::fromLiteral("Hello"), + UnownedStringSlice::fromLiteral("World!")}; + SLANG_CHECK(_checkLines( + UnownedStringSlice::fromLiteral("Hello\nWorld!"), + checkLines, + SLANG_COUNT_OF(checkLines))); } { - UnownedStringSlice checkLines[] = { UnownedStringSlice::fromLiteral("Hello"), UnownedStringSlice::fromLiteral("World!"), UnownedStringSlice() }; - SLANG_CHECK(_checkLines(UnownedStringSlice::fromLiteral("Hello\n\rWorld!\n"), checkLines, SLANG_COUNT_OF(checkLines))); + UnownedStringSlice checkLines[] = { + UnownedStringSlice::fromLiteral("Hello"), + UnownedStringSlice::fromLiteral("World!"), + UnownedStringSlice()}; + SLANG_CHECK(_checkLines( + UnownedStringSlice::fromLiteral("Hello\n\rWorld!\n"), + checkLines, + SLANG_COUNT_OF(checkLines))); } { @@ -143,16 +169,27 @@ SLANG_UNIT_TEST(string) } { Int value; - SLANG_CHECK(SLANG_SUCCEEDED(StringUtil::parseInt(UnownedStringSlice("-10"), value)) && value == -10); - SLANG_CHECK(SLANG_SUCCEEDED(StringUtil::parseInt(UnownedStringSlice("0"), value)) && value == 0); - SLANG_CHECK(SLANG_SUCCEEDED(StringUtil::parseInt(UnownedStringSlice("-0"), value)) && value == 0); - - SLANG_CHECK(SLANG_SUCCEEDED(StringUtil::parseInt(UnownedStringSlice("13824"), value)) && value == 13824); - SLANG_CHECK(SLANG_SUCCEEDED(StringUtil::parseInt(UnownedStringSlice("-13824"), value)) && value == -13824); + SLANG_CHECK( + SLANG_SUCCEEDED(StringUtil::parseInt(UnownedStringSlice("-10"), value)) && + value == -10); + SLANG_CHECK( + SLANG_SUCCEEDED(StringUtil::parseInt(UnownedStringSlice("0"), value)) && value == 0); + SLANG_CHECK( + SLANG_SUCCEEDED(StringUtil::parseInt(UnownedStringSlice("-0"), value)) && value == 0); + + SLANG_CHECK( + SLANG_SUCCEEDED(StringUtil::parseInt(UnownedStringSlice("13824"), value)) && + value == 13824); + SLANG_CHECK( + SLANG_SUCCEEDED(StringUtil::parseInt(UnownedStringSlice("-13824"), value)) && + value == -13824); } { - UnownedStringSlice values[] = { UnownedStringSlice("hello"), UnownedStringSlice("world"), UnownedStringSlice("!") }; + UnownedStringSlice values[] = { + UnownedStringSlice("hello"), + UnownedStringSlice("world"), + UnownedStringSlice("!")}; ArrayView<UnownedStringSlice> valuesView(values, SLANG_COUNT_OF(values)); List<UnownedStringSlice> checkValues; @@ -192,7 +229,7 @@ SLANG_UNIT_TEST(string) } } { - + List<double> values; values.add(0.0); values.add(-0.0); @@ -221,7 +258,7 @@ SLANG_UNIT_TEST(string) SlangResult res = StringUtil::parseDouble(slice, parsedValue); auto ulpsParsed = _calcULPDistance(value, parsedValue); - + SLANG_CHECK(SLANG_SUCCEEDED(res)); // Check that they are equal @@ -254,7 +291,7 @@ SLANG_UNIT_TEST(string) SlangResult res = StringUtil::parseInt64(slice, parsedValue); SLANG_CHECK(SLANG_SUCCEEDED(res)); - + // Check that they are equal SLANG_CHECK(value == parsedValue); } diff --git a/tools/slang-unit-test/unit-test-translation-unit-import.cpp b/tools/slang-unit-test/unit-test-translation-unit-import.cpp index 3b7f90c00..9870cf1e6 100644 --- a/tools/slang-unit-test/unit-test-translation-unit-import.cpp +++ b/tools/slang-unit-test/unit-test-translation-unit-import.cpp @@ -1,15 +1,14 @@ // unit-test-translation-unit-import.cpp +#include "../../source/core/slang-io.h" +#include "../../source/core/slang-process.h" +#include "slang-com-ptr.h" #include "slang.h" +#include "tools/unit-test/slang-unit-test.h" #include <stdio.h> #include <stdlib.h> -#include "tools/unit-test/slang-unit-test.h" -#include "slang-com-ptr.h" -#include "../../source/core/slang-io.h" -#include "../../source/core/slang-process.h" - using namespace Slang; // Test that the API supports discovering previously checked translation unit in the same @@ -17,10 +16,9 @@ using namespace Slang; SLANG_UNIT_TEST(translationUnitImport) { // Source for the first translation unit. - const char* generatedSource = - "public int f() {" - " return 5;" - "};"; + const char* generatedSource = "public int f() {" + " return 5;" + "};"; // Source for the a file that imports the first translation unit. // The import should succeed and `f` should be visible to this module. @@ -50,13 +48,21 @@ SLANG_UNIT_TEST(translationUnitImport) File::writeAllText(moduleName + ".slang", fileSource); spAddCodeGenTarget(request, SLANG_HLSL); - int generatedTranslationUnitIndex = spAddTranslationUnit(request, SLANG_SOURCE_LANGUAGE_SLANG, "generatedUnit"); + int generatedTranslationUnitIndex = + spAddTranslationUnit(request, SLANG_SOURCE_LANGUAGE_SLANG, "generatedUnit"); spAddTranslationUnitSourceString( - request, generatedTranslationUnitIndex, "generatedFile", generatedSource); + request, + generatedTranslationUnitIndex, + "generatedFile", + generatedSource); - int entryPointTranslationUnitIndex = spAddTranslationUnit(request, SLANG_SOURCE_LANGUAGE_SLANG, "userUnit"); + int entryPointTranslationUnitIndex = + spAddTranslationUnit(request, SLANG_SOURCE_LANGUAGE_SLANG, "userUnit"); spAddTranslationUnitSourceString( - request, entryPointTranslationUnitIndex, "userFile", userSource.getUnownedSlice().begin()); + request, + entryPointTranslationUnitIndex, + "userFile", + userSource.getUnownedSlice().begin()); spAddEntryPoint(request, entryPointTranslationUnitIndex, "computeMain", SLANG_STAGE_COMPUTE); auto compileResult = spCompile(request); @@ -65,9 +71,8 @@ SLANG_UNIT_TEST(translationUnitImport) Slang::ComPtr<ISlangBlob> outBlob; spGetEntryPointCodeBlob(request, 0, 0, outBlob.writeRef()); SLANG_CHECK(outBlob && outBlob->getBufferSize() != 0); - + spDestroyCompileRequest(request); spDestroySession(session); File::remove(moduleName + ".slang"); } - |
