diff --git a/demo_external_lsp.cpp b/demo_external_lsp.cpp index 01da7386..1c9d750a 100644 --- a/demo_external_lsp.cpp +++ b/demo_external_lsp.cpp @@ -1,7 +1,7 @@ /** * @file demo_external_lsp.cpp * @brief Demo application for testing external language server integration. - * + * * This demo tests the integration with real language servers like clangd and pyright. * It demonstrates: * - Auto-configuration of available language servers @@ -11,17 +11,19 @@ * - Requesting hover information */ -#include "bolt/editor/lsp_client.hpp" -#include "bolt/editor/lsp_server_configs.hpp" -#include -#include #include -#include #include +#include +#include +#include -using namespace bolt::lsp; +#include "bolt/editor/lsp_client.hpp" +#include "bolt/editor/lsp_server_configs.hpp" + +using namespace bolt::lsp; // NOLINT(build/namespaces) // Test file content +// clang-format off const char* CPP_TEST_CODE = R"( #include #include @@ -40,6 +42,7 @@ int main() { return 0; } )"; +// clang-format on const char* PYTHON_TEST_CODE = R"( import os @@ -74,105 +77,56 @@ void printSubsection(const std::string& title) { std::cout << "\n--- " << title << " ---\n\n"; } -bool testClangd(const std::string& testDir) { - printSeparator("Testing clangd (C/C++ Language Server)"); - - if (!LspServerConfigs::isServerAvailable("cpp")) { - std::cout << "❌ clangd is not available on this system.\n"; - std::cout << " Install with: sudo apt-get install clangd\n"; - return false; - } - - std::cout << "✅ clangd is available\n"; - - // Get configuration - auto config = LspServerConfigs::clangd(testDir); +// Describes one external language server exercised by the demo. +struct ServerDemoSpec { + std::string title; // Heading printed before the test + std::string languageKey; // Key used for the availability check + std::string name; // Server name used in messages + std::string installHint; // Command that installs the server + std::string fileName; // Name of the test file inside the test directory + const char* code; // Content of the test file + LspClientConfig (*makeConfig)(const std::string&); + Position completionPosition; + std::optional hoverPosition; // No hover request when empty +}; + +// Prints the command line the server is started with. +void printServerCommand(const LspClientConfig& config) { std::cout << " Command: " << config.serverCommand << "\n"; std::cout << " Args: "; for (const auto& arg : config.serverArgs) { std::cout << arg << " "; } std::cout << "\n"; - - // Create test file - std::string testFile = testDir + "/test.cpp"; - { - std::ofstream file(testFile); - file << CPP_TEST_CODE; - } - std::cout << " Created test file: " << testFile << "\n\n"; - - // Create client - printSubsection("Connecting to clangd"); - - auto connection = std::make_unique(); - LspClient client(std::move(connection)); - - if (!client.connect(config)) { - std::cout << "❌ Failed to connect to clangd\n"; - return false; - } - std::cout << "✅ Connected to clangd\n"; - - // Initialize - printSubsection("Initializing LSP session"); - - bool initSuccess = false; - client.initialize([&initSuccess](bool success) { - initSuccess = success; - }); - - // Wait for initialization (with timeout) +} + +// Polls until the flag is set by a response callback or the timeout expires. +void waitForFlag(const bool& flag, std::chrono::seconds timeout) { auto startTime = std::chrono::steady_clock::now(); - while (!initSuccess && - std::chrono::steady_clock::now() - startTime < std::chrono::seconds(10)) { + while (!flag && std::chrono::steady_clock::now() - startTime < timeout) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } - - if (!initSuccess) { - std::cout << "❌ Failed to initialize LSP session (timeout)\n"; - client.disconnect(); - return false; - } - std::cout << "✅ LSP session initialized\n"; - - // Open document - printSubsection("Opening document"); - - TextDocumentItem doc; - doc.uri = "file://" + testFile; - doc.languageId = "cpp"; - doc.version = 1; - doc.text = CPP_TEST_CODE; - - client.didOpenTextDocument(doc); - std::cout << "✅ Sent didOpen notification\n"; - - // Wait for clangd to process the file - std::this_thread::sleep_for(std::chrono::seconds(2)); - - // Request completion +} + +// Requests completion at the given position and prints the first few items. +void requestCompletion(LspClient& client, const std::string& uri, const Position& position) { printSubsection("Requesting code completion"); - + TextDocumentPositionParams completionParams; - completionParams.textDocument.uri = doc.uri; - completionParams.position = Position(8, 9); // After "std::" on line 8 - + completionParams.textDocument.uri = uri; + completionParams.position = position; + CompletionList completions; bool completionReceived = false; - + client.completion(completionParams, [&completions, &completionReceived](const CompletionList& result) { completions = result; completionReceived = true; }); - + // Wait for completion response - startTime = std::chrono::steady_clock::now(); - while (!completionReceived && - std::chrono::steady_clock::now() - startTime < std::chrono::seconds(5)) { - std::this_thread::sleep_for(std::chrono::milliseconds(100)); - } - + waitForFlag(completionReceived, std::chrono::seconds(5)); + if (completionReceived) { std::cout << "✅ Received " << completions.items.size() << " completion items\n"; int shown = 0; @@ -187,29 +141,27 @@ bool testClangd(const std::string& testDir) { } else { std::cout << "⚠️ Completion request timed out\n"; } - - // Request hover +} + +// Requests hover information at the given position and prints it. +void requestHover(LspClient& client, const std::string& uri, const Position& position) { printSubsection("Requesting hover information"); - + TextDocumentPositionParams hoverParams; - hoverParams.textDocument.uri = doc.uri; - hoverParams.position = Position(6, 10); // On "vector" - + hoverParams.textDocument.uri = uri; + hoverParams.position = position; + std::optional hoverResult; bool hoverReceived = false; - + client.hover(hoverParams, [&hoverResult, &hoverReceived](const std::optional& result) { hoverResult = result; hoverReceived = true; }); - + // Wait for hover response - startTime = std::chrono::steady_clock::now(); - while (!hoverReceived && - std::chrono::steady_clock::now() - startTime < std::chrono::seconds(5)) { - std::this_thread::sleep_for(std::chrono::milliseconds(100)); - } - + waitForFlag(hoverReceived, std::chrono::seconds(5)); + if (hoverReceived && hoverResult.has_value()) { std::cout << "✅ Received hover information:\n"; std::string content = hoverResult->contents; @@ -221,185 +173,150 @@ bool testClangd(const std::string& testDir) { } else { std::cout << "⚠️ Hover request timed out or returned empty\n"; } - - // Close document - printSubsection("Closing document"); - - TextDocumentIdentifier closeDoc; - closeDoc.uri = doc.uri; - client.didCloseTextDocument(closeDoc); - std::cout << "✅ Sent didClose notification\n"; - - // Shutdown - printSubsection("Shutting down"); - - client.shutdown([](bool success) { - std::cout << (success ? "✅" : "❌") << " Shutdown " << (success ? "successful" : "failed") << "\n"; - }); - - std::this_thread::sleep_for(std::chrono::milliseconds(500)); - client.disconnect(); - std::cout << "✅ Disconnected from clangd\n"; - - return true; } -bool testPyright(const std::string& testDir) { - printSeparator("Testing pyright (Python Language Server)"); - - if (!LspServerConfigs::isServerAvailable("python")) { - std::cout << "❌ pyright is not available on this system.\n"; - std::cout << " Install with: npm install -g pyright\n"; +// Runs the whole demo session (connect, open, query, shut down) against one server. +bool testLanguageServer(const ServerDemoSpec& spec, const std::string& testDir) { + printSeparator(spec.title); + + if (!LspServerConfigs::isServerAvailable(spec.languageKey)) { + std::cout << "❌ " << spec.name << " is not available on this system.\n"; + std::cout << " Install with: " << spec.installHint << "\n"; return false; } - - std::cout << "✅ pyright is available\n"; - + + std::cout << "✅ " << spec.name << " is available\n"; + // Get configuration - auto config = LspServerConfigs::pyright(testDir); - std::cout << " Command: " << config.serverCommand << "\n"; - std::cout << " Args: "; - for (const auto& arg : config.serverArgs) { - std::cout << arg << " "; - } - std::cout << "\n"; - + auto config = spec.makeConfig(testDir); + printServerCommand(config); + // Create test file - std::string testFile = testDir + "/test.py"; + std::string testFile = testDir + "/" + spec.fileName; { std::ofstream file(testFile); - file << PYTHON_TEST_CODE; + file << spec.code; } std::cout << " Created test file: " << testFile << "\n\n"; - + // Create client - printSubsection("Connecting to pyright"); - + printSubsection("Connecting to " + spec.name); + auto connection = std::make_unique(); LspClient client(std::move(connection)); - + if (!client.connect(config)) { - std::cout << "❌ Failed to connect to pyright\n"; + std::cout << "❌ Failed to connect to " << spec.name << "\n"; return false; } - std::cout << "✅ Connected to pyright\n"; - + std::cout << "✅ Connected to " << spec.name << "\n"; + // Initialize printSubsection("Initializing LSP session"); - + bool initSuccess = false; - client.initialize([&initSuccess](bool success) { - initSuccess = success; - }); - - // Wait for initialization - auto startTime = std::chrono::steady_clock::now(); - while (!initSuccess && - std::chrono::steady_clock::now() - startTime < std::chrono::seconds(10)) { - std::this_thread::sleep_for(std::chrono::milliseconds(100)); - } - + client.initialize([&initSuccess](bool success) { initSuccess = success; }); + + // Wait for initialization (with timeout) + waitForFlag(initSuccess, std::chrono::seconds(10)); + if (!initSuccess) { std::cout << "❌ Failed to initialize LSP session (timeout)\n"; client.disconnect(); return false; } std::cout << "✅ LSP session initialized\n"; - + // Open document printSubsection("Opening document"); - + TextDocumentItem doc; doc.uri = "file://" + testFile; - doc.languageId = "python"; + doc.languageId = spec.languageKey; doc.version = 1; - doc.text = PYTHON_TEST_CODE; - + doc.text = spec.code; + client.didOpenTextDocument(doc); std::cout << "✅ Sent didOpen notification\n"; - - // Wait for pyright to process + + // Wait for the server to process the file std::this_thread::sleep_for(std::chrono::seconds(2)); - - // Request completion - printSubsection("Requesting code completion"); - - TextDocumentPositionParams completionParams; - completionParams.textDocument.uri = doc.uri; - completionParams.position = Position(1, 7); // After "import " - - CompletionList completions; - bool completionReceived = false; - - client.completion(completionParams, [&completions, &completionReceived](const CompletionList& result) { - completions = result; - completionReceived = true; - }); - - // Wait for completion response - startTime = std::chrono::steady_clock::now(); - while (!completionReceived && - std::chrono::steady_clock::now() - startTime < std::chrono::seconds(5)) { - std::this_thread::sleep_for(std::chrono::milliseconds(100)); - } - - if (completionReceived) { - std::cout << "✅ Received " << completions.items.size() << " completion items\n"; - int shown = 0; - for (const auto& item : completions.items) { - if (shown++ < 5) { - std::cout << " - " << item.label << "\n"; - } - } - if (completions.items.size() > 5) { - std::cout << " ... and " << (completions.items.size() - 5) << " more\n"; - } - } else { - std::cout << "⚠️ Completion request timed out\n"; + + requestCompletion(client, doc.uri, spec.completionPosition); + + if (spec.hoverPosition.has_value()) { + requestHover(client, doc.uri, *spec.hoverPosition); } - + // Close document printSubsection("Closing document"); - + TextDocumentIdentifier closeDoc; closeDoc.uri = doc.uri; client.didCloseTextDocument(closeDoc); std::cout << "✅ Sent didClose notification\n"; - + // Shutdown printSubsection("Shutting down"); - + client.shutdown([](bool success) { std::cout << (success ? "✅" : "❌") << " Shutdown " << (success ? "successful" : "failed") << "\n"; }); - + std::this_thread::sleep_for(std::chrono::milliseconds(500)); client.disconnect(); - std::cout << "✅ Disconnected from pyright\n"; - + std::cout << "✅ Disconnected from " << spec.name << "\n"; + return true; } +bool testClangd(const std::string& testDir) { + ServerDemoSpec spec; + spec.title = "Testing clangd (C/C++ Language Server)"; + spec.languageKey = "cpp"; + spec.name = "clangd"; + spec.installHint = "sudo apt-get install clangd"; + spec.fileName = "test.cpp"; + spec.code = CPP_TEST_CODE; + spec.makeConfig = [](const std::string& rootPath) { return LspServerConfigs::clangd(rootPath); }; + spec.completionPosition = Position(8, 9); // After "std::" on line 8 + spec.hoverPosition = Position(6, 10); // On "vector" + return testLanguageServer(spec, testDir); +} + +bool testPyright(const std::string& testDir) { + ServerDemoSpec spec; + spec.title = "Testing pyright (Python Language Server)"; + spec.languageKey = "python"; + spec.name = "pyright"; + spec.installHint = "npm install -g pyright"; + spec.fileName = "test.py"; + spec.code = PYTHON_TEST_CODE; + spec.makeConfig = [](const std::string& rootPath) { return LspServerConfigs::pyright(rootPath); }; + spec.completionPosition = Position(1, 7); // After "import " + return testLanguageServer(spec, testDir); +} + void testAutoConfiguration(const std::string& testDir) { printSeparator("Testing Auto-Configuration"); - + // Print availability report std::cout << LspAutoConfigurator::getAvailabilityReport(); - + // Create a client manager LspClientManager manager; - + // Auto-configure int configured = LspAutoConfigurator::autoConfigureAll(manager, testDir); std::cout << "Auto-configured " << configured << " language server(s)\n"; - + // List registered languages auto languages = manager.getRegisteredLanguages(); std::cout << "Registered languages:\n"; for (const auto& lang : languages) { std::cout << " - " << lang << "\n"; } - + manager.shutdown(); } @@ -409,34 +326,34 @@ int main() { std::cout << "║ Bolt C++ External LSP Integration Demo ║\n"; std::cout << "║ Testing Real Language Server Connections ║\n"; std::cout << "╚══════════════════════════════════════════════════════════╝\n"; - + // Create test directory std::string testDir = "/tmp/bolt_lsp_test"; std::filesystem::create_directories(testDir); std::cout << "\nTest directory: " << testDir << "\n"; - + // Test auto-configuration testAutoConfiguration(testDir); - + // Test clangd bool clangdSuccess = testClangd(testDir); - + // Test pyright bool pyrightSuccess = testPyright(testDir); - + // Summary printSeparator("Test Summary"); - + std::cout << "clangd (C/C++): " << (clangdSuccess ? "✅ PASSED" : "❌ FAILED") << "\n"; std::cout << "pyright (Python): " << (pyrightSuccess ? "✅ PASSED" : "❌ FAILED") << "\n"; - + // Cleanup std::filesystem::remove_all(testDir); std::cout << "\nCleaned up test directory.\n"; - + std::cout << "\n" << std::string(60, '=') << "\n"; std::cout << " External LSP Integration Demo Complete\n"; std::cout << std::string(60, '=') << "\n\n"; - + return (clangdSuccess && pyrightSuccess) ? 0 : 1; } diff --git a/demo_gpu_acceleration.cpp b/demo_gpu_acceleration.cpp index 7cad7f39..5bf76e18 100644 --- a/demo_gpu_acceleration.cpp +++ b/demo_gpu_acceleration.cpp @@ -1,60 +1,65 @@ +#include #include #include -#include + #include "bolt/ai/gpu_acceleration.hpp" #include "bolt/core/logging.hpp" -using namespace bolt::ai; +using namespace bolt::ai; // NOLINT(build/namespaces) + +// Returns the display name of a GPU backend type. +static const char* backendTypeName(GPUBackendType type) { + switch (type) { + case GPUBackendType::CUDA: + return "CUDA"; + case GPUBackendType::OpenCL: + return "OpenCL"; + case GPUBackendType::Vulkan: + return "Vulkan"; + case GPUBackendType::CPU: + return "CPU"; + default: + return "Unknown"; + } +} int main() { std::cout << "=== GPU Acceleration Demo for Bolt C++ ===" << std::endl; - + // Initialize logging bolt::LogManager::configureConsoleLogging(); - + // Check if GPU acceleration is available std::cout << "\n1. Checking GPU availability..." << std::endl; bool gpuAvailable = gpu_utils::isGPUAccelerationAvailable(); std::cout << "GPU acceleration available: " << (gpuAvailable ? "Yes" : "No") << std::endl; - + // Get recommended GPU configuration std::cout << "\n2. Getting recommended GPU configuration..." << std::endl; GPUConfig recommendedConfig = gpu_utils::getRecommendedGPUConfig(); std::cout << "Recommended backend: "; - switch (recommendedConfig.preferredBackend) { - case GPUBackendType::CUDA: std::cout << "CUDA"; break; - case GPUBackendType::OpenCL: std::cout << "OpenCL"; break; - case GPUBackendType::Vulkan: std::cout << "Vulkan"; break; - case GPUBackendType::CPU: std::cout << "CPU"; break; - default: std::cout << "Unknown"; break; - } + std::cout << backendTypeName(recommendedConfig.preferredBackend); std::cout << std::endl; - + // Initialize GPU acceleration manager std::cout << "\n3. Initializing GPU acceleration manager..." << std::endl; auto& gpuManager = GPUAccelerationManager::getInstance(); - + if (!gpuManager.initialize(recommendedConfig)) { std::cerr << "Failed to initialize GPU acceleration manager" << std::endl; return 1; } - + // Detect available devices std::cout << "\n4. Detecting available GPU devices..." << std::endl; auto devices = gpuManager.detectAvailableDevices(); std::cout << "Found " << devices.size() << " device(s):" << std::endl; - + for (size_t i = 0; i < devices.size(); i++) { const auto& device = devices[i]; std::cout << " Device " << i << ": " << device.name << std::endl; std::cout << " Type: "; - switch (device.backendType) { - case GPUBackendType::CUDA: std::cout << "CUDA"; break; - case GPUBackendType::OpenCL: std::cout << "OpenCL"; break; - case GPUBackendType::Vulkan: std::cout << "Vulkan"; break; - case GPUBackendType::CPU: std::cout << "CPU"; break; - default: std::cout << "Unknown"; break; - } + std::cout << backendTypeName(device.backendType); std::cout << std::endl; std::cout << " Available: " << (device.isAvailable ? "Yes" : "No") << std::endl; if (device.totalMemory > 0) { @@ -63,43 +68,43 @@ int main() { } std::cout << " Description: " << device.description << std::endl; } - + // Get current device information std::cout << "\n5. Current device information..." << std::endl; auto currentDevice = gpuManager.getCurrentDevice(); std::cout << "Currently using: " << currentDevice.name << " (" << currentDevice.description << ")" << std::endl; - + // Test GPU-accelerated model std::cout << "\n6. Testing GPU-accelerated model..." << std::endl; - + // Configure GPU settings GPUConfig gpuConfig; gpuConfig.enableAutomaticFallback = true; gpuConfig.enableMemoryOptimization = true; - + // Create a mock model path (in real use, this would be a path to an actual model file) std::string mockModelPath = "/tmp/mock_model.gguf"; - + try { GPUAcceleratedModel model(mockModelPath, gpuConfig); - + std::cout << "Model created successfully" << std::endl; std::cout << "GPU accelerated: " << (model.isGPUAccelerated() ? "Yes" : "No") << std::endl; - + // Test text generation (simplified) std::cout << "\n7. Testing text generation..." << std::endl; std::string prompt = "Hello, this is a test prompt"; - + auto startTime = std::chrono::high_resolution_clock::now(); std::string response = model.generate(prompt, 50); auto endTime = std::chrono::high_resolution_clock::now(); - + auto duration = std::chrono::duration_cast(endTime - startTime); - + std::cout << "Prompt: " << prompt << std::endl; std::cout << "Generated response: " << response << std::endl; std::cout << "Generation time: " << duration.count() << " ms" << std::endl; - + // Test embedding generation std::cout << "\n8. Testing embedding generation..." << std::endl; auto embedding = model.generateEmbedding("Test text for embedding"); @@ -111,7 +116,7 @@ int main() { } std::cout << "..." << std::endl; } - + // Display performance statistics std::cout << "\n9. Performance statistics..." << std::endl; auto stats = model.getPerformanceStats(); @@ -122,52 +127,40 @@ int main() { if (stats.totalComputeTime > 0) { std::cout << "Average ops per second: " << stats.averageOpsPerSecond << std::endl; } - } catch (const GPUAccelerationException& e) { std::cerr << "GPU acceleration error: " << e.what() << std::endl; std::cout << "Failed backend: "; - switch (e.getFailedBackend()) { - case GPUBackendType::CUDA: std::cout << "CUDA"; break; - case GPUBackendType::OpenCL: std::cout << "OpenCL"; break; - case GPUBackendType::Vulkan: std::cout << "Vulkan"; break; - case GPUBackendType::CPU: std::cout << "CPU"; break; - default: std::cout << "Unknown"; break; - } + std::cout << backendTypeName(e.getFailedBackend()); std::cout << std::endl; } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; } - + // Test memory management std::cout << "\n10. Memory management test..." << std::endl; if (gpuManager.isInitialized()) { auto& memManager = gpuManager.getMemoryManager(); std::cout << "Used GPU memory: " << (memManager.getUsedMemory() / (1024 * 1024)) << " MB" << std::endl; - std::cout << "Available GPU memory: " << (memManager.getAvailableMemory() / (1024 * 1024)) << " MB" << std::endl; - + std::cout << "Available GPU memory: " << (memManager.getAvailableMemory() / (1024 * 1024)) << " MB" + << std::endl; + // Test memory optimization memManager.optimizeMemoryUsage(); memManager.defragmentMemory(); } - + // Benchmark different backends (if available) std::cout << "\n11. Benchmarking GPU backends..." << std::endl; GPUBackendType bestBackend = gpu_utils::benchmarkGPUBackends(); std::cout << "Best performing backend: "; - switch (bestBackend) { - case GPUBackendType::CUDA: std::cout << "CUDA"; break; - case GPUBackendType::OpenCL: std::cout << "OpenCL"; break; - case GPUBackendType::Vulkan: std::cout << "Vulkan"; break; - case GPUBackendType::CPU: std::cout << "CPU"; break; - default: std::cout << "Unknown"; break; - } + std::cout << backendTypeName(bestBackend); std::cout << std::endl; - + // Cleanup std::cout << "\n12. Shutting down..." << std::endl; gpuManager.shutdown(); - + std::cout << "\n=== GPU Acceleration Demo Complete ===" << std::endl; - + return 0; -} \ No newline at end of file +} diff --git a/demo_lsp_editor_integration.cpp b/demo_lsp_editor_integration.cpp index 85690e73..72e9349a 100644 --- a/demo_lsp_editor_integration.cpp +++ b/demo_lsp_editor_integration.cpp @@ -1,8 +1,8 @@ -//#include "bolt/editor/integrated_editor.hpp" +// #include "bolt/editor/integrated_editor.hpp" #include #include -#include #include +#include // This is a simplified integration example showing how LSP would work with IntegratedEditor // Note: This uses a simplified approach due to compilation issues with the full implementation @@ -14,18 +14,18 @@ namespace lsp { struct Position { size_t line; size_t character; - Position(size_t l = 0, size_t c = 0) : line(l), character(c) {} + explicit Position(size_t l = 0, size_t c = 0) : line(l), character(c) {} }; struct CompletionItem { std::string label; std::string detail; - CompletionItem(const std::string& l, const std::string& d = "") : label(l), detail(d) {} + explicit CompletionItem(const std::string& l, const std::string& d = "") : label(l), detail(d) {} }; // Simplified language plugin interface class ISimpleLangPlugin { -public: + public: virtual ~ISimpleLangPlugin() = default; virtual std::vector getCompletions(const std::string& filePath, size_t line, size_t column) = 0; virtual std::string getHover(const std::string& filePath, size_t line, size_t column) = 0; @@ -34,32 +34,34 @@ class ISimpleLangPlugin { // C++ language plugin for the demo class CppLangPlugin : public ISimpleLangPlugin { -public: + public: std::vector getCompletions(const std::string& filePath, size_t line, size_t column) override { - return { - "std::vector", - "std::unique_ptr", - "std::shared_ptr", - "std::string", - "std::cout", - "std::endl", - "namespace", - "class", - "virtual", - "override", - "template", - "auto" - }; + return {"std::vector", + "std::unique_ptr", + "std::shared_ptr", + "std::string", + "std::cout", + "std::endl", + "namespace", + "class", + "virtual", + "override", + "template", + "auto"}; } - + std::string getHover(const std::string& filePath, size_t line, size_t column) override { return "C++ Symbol Information\n" - "File: " + filePath + "\n" - "Position: " + std::to_string(line) + ":" + std::to_string(column) + "\n" + "File: " + + filePath + + "\n" + "Position: " + + std::to_string(line) + ":" + std::to_string(column) + + "\n" "Type: Modern C++ feature\n" "Documentation: Standard library or language feature"; } - + std::vector getSupportedExtensions() const override { return {".cpp", ".hpp", ".c", ".h", ".cc", ".cxx", ".hxx"}; } @@ -67,103 +69,94 @@ class CppLangPlugin : public ISimpleLangPlugin { // LSP service that integrates with the editor class EditorLspService { -private: + private: std::vector> plugins_; - -public: - void registerPlugin(std::shared_ptr plugin) { - plugins_.push_back(plugin); - } - + + public: + void registerPlugin(std::shared_ptr plugin) { plugins_.push_back(plugin); } + std::vector getCompletionsForEditor(const std::string& filePath, size_t line, size_t column) { - for (auto& plugin : plugins_) { - auto extensions = plugin->getSupportedExtensions(); - for (const auto& ext : extensions) { - if (filePath.length() >= ext.length() && - filePath.substr(filePath.length() - ext.length()) == ext) { - return plugin->getCompletions(filePath, line, column); - } - } + auto plugin = findPluginForFile(filePath); + if (plugin) { + return plugin->getCompletions(filePath, line, column); } return {}; } - + std::string getHoverForEditor(const std::string& filePath, size_t line, size_t column) { - for (auto& plugin : plugins_) { - auto extensions = plugin->getSupportedExtensions(); - for (const auto& ext : extensions) { - if (filePath.length() >= ext.length() && - filePath.substr(filePath.length() - ext.length()) == ext) { - return plugin->getHover(filePath, line, column); - } - } + auto plugin = findPluginForFile(filePath); + if (plugin) { + return plugin->getHover(filePath, line, column); } return ""; } - - bool supportsFile(const std::string& filePath) { + + bool supportsFile(const std::string& filePath) { return findPluginForFile(filePath) != nullptr; } + + private: + // Returns the first registered plugin that handles the file's extension, or nullptr. + std::shared_ptr findPluginForFile(const std::string& filePath) { for (auto& plugin : plugins_) { auto extensions = plugin->getSupportedExtensions(); for (const auto& ext : extensions) { - if (filePath.length() >= ext.length() && - filePath.substr(filePath.length() - ext.length()) == ext) { - return true; + if (filePath.length() >= ext.length() && filePath.substr(filePath.length() - ext.length()) == ext) { + return plugin; } } } - return false; + return nullptr; } }; // Enhanced editor with LSP integration class LspIntegratedEditor { -private: + private: EditorLspService lspService_; std::string currentFile_; size_t currentLine_ = 0; size_t currentColumn_ = 0; - -public: + + public: void initializeLsp() { // Register C++ language plugin auto cppPlugin = std::make_shared(); lspService_.registerPlugin(cppPlugin); - + std::cout << "LSP Integration initialized with C++ support" << std::endl; } - + void openFile(const std::string& filePath) { currentFile_ = filePath; currentLine_ = 0; currentColumn_ = 0; - + std::cout << "Opened file: " << filePath << std::endl; - + if (lspService_.supportsFile(filePath)) { std::cout << " LSP support: Available" << std::endl; } else { std::cout << " LSP support: Not available for this file type" << std::endl; } } - + void setCursor(size_t line, size_t column) { currentLine_ = line; currentColumn_ = column; std::cout << "Cursor moved to " << line << ":" << column << std::endl; } - + void triggerCompletion() { if (currentFile_.empty()) { std::cout << "No file open for completion" << std::endl; return; } - + std::cout << "\n=== Code Completion Request ===" << std::endl; std::cout << "File: " << currentFile_ << std::endl; std::cout << "Position: " << currentLine_ << ":" << currentColumn_ << std::endl; - + auto completions = lspService_.getCompletionsForEditor(currentFile_, currentLine_, currentColumn_); - + if (completions.empty()) { std::cout << "No completions available" << std::endl; } else { @@ -176,16 +169,16 @@ class LspIntegratedEditor { } } } - + void triggerHover() { if (currentFile_.empty()) { std::cout << "No file open for hover" << std::endl; return; } - + std::cout << "\n=== Hover Information Request ===" << std::endl; std::string hoverInfo = lspService_.getHoverForEditor(currentFile_, currentLine_, currentColumn_); - + if (hoverInfo.empty()) { std::cout << "No hover information available" << std::endl; } else { @@ -193,27 +186,27 @@ class LspIntegratedEditor { std::cout << hoverInfo << std::endl; } } - + void simulateEditing() { std::cout << "\n=== Simulating Editing Session ===" << std::endl; - + // Simulate opening a C++ file openFile("example.cpp"); - + // Simulate cursor movements and requests setCursor(1, 0); std::cout << "\nTyping 'std::' ..." << std::endl; setCursor(1, 5); triggerCompletion(); - + setCursor(5, 10); std::cout << "\nHovering over a symbol..." << std::endl; triggerHover(); - + setCursor(10, 15); std::cout << "\nTriggering completion in different context..." << std::endl; triggerCompletion(); - + // Try unsupported file type std::cout << "\n" << std::endl; openFile("example.py"); @@ -221,21 +214,21 @@ class LspIntegratedEditor { } }; -} // namespace lsp -} // namespace bolt +} // namespace lsp +} // namespace bolt int main() { std::cout << "=== Bolt C++ Editor LSP Integration Demo ===" << std::endl; std::cout << "\nThis demo shows how LSP integrates with the Integrated Editor" << std::endl; - + bolt::lsp::LspIntegratedEditor editor; - + // Initialize LSP support editor.initializeLsp(); - + // Simulate an editing session editor.simulateEditing(); - + std::cout << "\n=== Integration Demo Complete ===" << std::endl; std::cout << "\nKey Integration Points Demonstrated:" << std::endl; std::cout << "1. LSP service registration with language plugins" << std::endl; @@ -243,13 +236,13 @@ int main() { std::cout << "3. Context-aware code completion" << std::endl; std::cout << "4. Position-based hover information" << std::endl; std::cout << "5. Seamless integration with editor operations" << std::endl; - + std::cout << "\nNext Steps for Full Integration:" << std::endl; std::cout << "- Connect with actual IntegratedEditor instance" << std::endl; std::cout << "- Implement real-time diagnostic updates" << std::endl; std::cout << "- Add external language server support" << std::endl; std::cout << "- Integrate with multi-cursor and split-view features" << std::endl; std::cout << "- Support for advanced LSP features (go-to-definition, references)" << std::endl; - + return 0; -} \ No newline at end of file +} diff --git a/demo_lsp_integration.cpp b/demo_lsp_integration.cpp index c5f50a3c..c526782a 100644 --- a/demo_lsp_integration.cpp +++ b/demo_lsp_integration.cpp @@ -1,7 +1,7 @@ #include +#include #include #include -#include // Minimal LSP demonstration without the compilation issues namespace bolt { @@ -11,15 +11,15 @@ namespace lsp { struct Position { size_t line; size_t character; - - Position(size_t l = 0, size_t c = 0) : line(l), character(c) {} + + explicit Position(size_t l = 0, size_t c = 0) : line(l), character(c) {} }; struct CompletionItem { std::string label; std::string detail; - - CompletionItem(const std::string& l, const std::string& d = "") : label(l), detail(d) {} + + explicit CompletionItem(const std::string& l, const std::string& d = "") : label(l), detail(d) {} }; struct CompletionList { @@ -29,7 +29,7 @@ struct CompletionList { // Minimal language plugin interface for demo class ILanguagePlugin { -public: + public: virtual ~ILanguagePlugin() = default; virtual std::vector getCodeCompletions(const std::string& filePath, size_t line, size_t column) = 0; virtual std::string getHoverInfo(const std::string& filePath, size_t line, size_t column) = 0; @@ -40,41 +40,31 @@ class ILanguagePlugin { // Demo C++ language plugin class CppLanguagePlugin : public ILanguagePlugin { -public: + public: std::vector getCodeCompletions(const std::string& filePath, size_t line, size_t column) override { - return { - "std::vector", - "std::string", - "std::cout", - "std::endl", - "class", - "namespace", - "virtual", - "override", - "template", - "typename" - }; + return {"std::vector", "std::string", "std::cout", "std::endl", "class", + "namespace", "virtual", "override", "template", "typename"}; } - + std::string getHoverInfo(const std::string& filePath, size_t line, size_t column) override { return "C++ language hover information for position " + std::to_string(line) + ":" + std::to_string(column); } - + std::vector getDiagnostics(const std::string& filePath, const std::string& content) override { std::vector diagnostics; - + // Simple diagnostic checks if (content.find("nullptr") != std::string::npos && content.find("#include") == std::string::npos) { diagnostics.push_back("Warning: Using nullptr without proper includes"); } - + if (content.find("using namespace std") != std::string::npos) { diagnostics.push_back("Warning: Avoid 'using namespace std' in headers"); } - + return diagnostics; } - + std::string formatCode(const std::string& code) override { // Simple formatting - ensure code ends with newline std::string formatted = code; @@ -83,7 +73,7 @@ class CppLanguagePlugin : public ILanguagePlugin { } return formatted; } - + std::vector getSupportedExtensions() const override { return {".cpp", ".hpp", ".c", ".h", ".cc", ".cxx"}; } @@ -91,100 +81,86 @@ class CppLanguagePlugin : public ILanguagePlugin { // LSP Server demonstration class LspServer { -private: + private: std::vector> plugins_; - -public: - void registerPlugin(std::shared_ptr plugin) { - plugins_.push_back(plugin); - } - + + public: + void registerPlugin(std::shared_ptr plugin) { plugins_.push_back(plugin); } + CompletionList getCompletions(const std::string& filePath, const Position& position) { CompletionList result; - + for (auto& plugin : plugins_) { - auto extensions = plugin->getSupportedExtensions(); - bool supportsFile = false; - - for (const auto& ext : extensions) { - if (filePath.length() >= ext.length() && - filePath.substr(filePath.length() - ext.length()) == ext) { - supportsFile = true; - break; - } - } - - if (supportsFile) { + if (pluginSupportsFile(*plugin, filePath)) { auto completions = plugin->getCodeCompletions(filePath, position.line, position.character); for (const auto& completion : completions) { result.items.emplace_back(completion, "Completion from " + std::string(typeid(*plugin).name())); } } } - + return result; } - + std::string getHover(const std::string& filePath, const Position& position) { for (auto& plugin : plugins_) { - auto extensions = plugin->getSupportedExtensions(); - for (const auto& ext : extensions) { - if (filePath.length() >= ext.length() && - filePath.substr(filePath.length() - ext.length()) == ext) { - return plugin->getHoverInfo(filePath, position.line, position.character); - } + if (pluginSupportsFile(*plugin, filePath)) { + return plugin->getHoverInfo(filePath, position.line, position.character); } } return ""; } - + std::vector getDiagnostics(const std::string& filePath, const std::string& content) { std::vector allDiagnostics; - + for (auto& plugin : plugins_) { - auto extensions = plugin->getSupportedExtensions(); - for (const auto& ext : extensions) { - if (filePath.length() >= ext.length() && - filePath.substr(filePath.length() - ext.length()) == ext) { - auto diagnostics = plugin->getDiagnostics(filePath, content); - allDiagnostics.insert(allDiagnostics.end(), diagnostics.begin(), diagnostics.end()); - break; - } + if (pluginSupportsFile(*plugin, filePath)) { + auto diagnostics = plugin->getDiagnostics(filePath, content); + allDiagnostics.insert(allDiagnostics.end(), diagnostics.begin(), diagnostics.end()); } } - + return allDiagnostics; } - + std::string formatDocument(const std::string& filePath, const std::string& content) { for (auto& plugin : plugins_) { - auto extensions = plugin->getSupportedExtensions(); - for (const auto& ext : extensions) { - if (filePath.length() >= ext.length() && - filePath.substr(filePath.length() - ext.length()) == ext) { - return plugin->formatCode(content); - } + if (pluginSupportsFile(*plugin, filePath)) { + return plugin->formatCode(content); } } return content; } + + private: + // Returns true when the file path ends with one of the plugin's supported extensions. + static bool pluginSupportsFile(const ILanguagePlugin& plugin, const std::string& filePath) { + auto extensions = plugin.getSupportedExtensions(); + for (const auto& ext : extensions) { + if (filePath.length() >= ext.length() && filePath.substr(filePath.length() - ext.length()) == ext) { + return true; + } + } + return false; + } }; -} // namespace lsp -} // namespace bolt +} // namespace lsp +} // namespace bolt int main() { - using namespace bolt::lsp; - + using namespace bolt::lsp; // NOLINT(build/namespaces) + std::cout << "=== Bolt C++ LSP Integration Demo ===" << std::endl; - + // Create LSP server LspServer lspServer; - + // Register C++ language plugin auto cppPlugin = std::make_shared(); lspServer.registerPlugin(cppPlugin); - + std::cout << "\n1. Testing C++ Language Plugin Registration:" << std::endl; auto extensions = cppPlugin->getSupportedExtensions(); std::cout << " Supported extensions: "; @@ -192,12 +168,12 @@ int main() { std::cout << ext << " "; } std::cout << std::endl; - + // Test completion std::cout << "\n2. Testing Code Completion:" << std::endl; std::string filePath = "test.cpp"; Position position(10, 5); - + auto completions = lspServer.getCompletions(filePath, position); std::cout << " Found " << completions.items.size() << " completions for " << filePath << ":" << std::endl; for (size_t i = 0; i < std::min(size_t(5), completions.items.size()); ++i) { @@ -206,12 +182,12 @@ int main() { if (completions.items.size() > 5) { std::cout << " ... and " << (completions.items.size() - 5) << " more" << std::endl; } - + // Test hover std::cout << "\n3. Testing Hover Information:" << std::endl; std::string hoverInfo = lspServer.getHover(filePath, position); std::cout << " Hover: " << hoverInfo << std::endl; - + // Test diagnostics std::cout << "\n4. Testing Diagnostics:" << std::endl; std::string testCode = R"( @@ -224,26 +200,26 @@ int main() { return 0; } )"; - + auto diagnostics = lspServer.getDiagnostics(filePath, testCode); std::cout << " Found " << diagnostics.size() << " diagnostic issues:" << std::endl; for (const auto& diag : diagnostics) { std::cout << " - " << diag << std::endl; } - + // Test formatting std::cout << "\n5. Testing Code Formatting:" << std::endl; std::string unformattedCode = "int main(){return 0;}"; std::string formattedCode = lspServer.formatDocument(filePath, unformattedCode); std::cout << " Original: \"" << unformattedCode << "\"" << std::endl; std::cout << " Formatted: \"" << formattedCode << "\"" << std::endl; - + // Test with unsupported file std::cout << "\n6. Testing Unsupported File Type:" << std::endl; std::string pythonFile = "test.py"; auto pythonCompletions = lspServer.getCompletions(pythonFile, position); std::cout << " Completions for " << pythonFile << ": " << pythonCompletions.items.size() << std::endl; - + std::cout << "\n=== LSP Integration Demo Complete ===" << std::endl; std::cout << "\nThis demonstrates basic LSP functionality including:" << std::endl; std::cout << "- Language plugin registration and management" << std::endl; @@ -254,6 +230,6 @@ int main() { std::cout << "- File type support detection" << std::endl; std::cout << "\nThe LSP server can be extended with additional language plugins" << std::endl; std::cout << "and integrated with external language servers via JSON-RPC." << std::endl; - + return 0; -} \ No newline at end of file +} diff --git a/demo_multi_cursor.cpp b/demo_multi_cursor.cpp index 910a4f04..85abbcfe 100644 --- a/demo_multi_cursor.cpp +++ b/demo_multi_cursor.cpp @@ -1,130 +1,125 @@ #include #include +#include + #include "bolt/editor/cursor_manager.hpp" #include "bolt/editor/integrated_editor.hpp" -using namespace bolt; +using namespace bolt; // NOLINT(build/namespaces) + +// Prints the position of every cursor in the list. +static void printCursorPositions(const std::vector& cursors) { + for (size_t i = 0; i < cursors.size(); ++i) { + std::cout << " Cursor " << i << ": (" << cursors[i].line << ", " << cursors[i].column << ")" << std::endl; + } +} void demonstrateBasicMultiCursor() { std::cout << "\n=== Basic Multi-Cursor Operations ===" << std::endl; - + CursorManager& manager = CursorManager::getInstance(); manager.clearCursors(); - + // Add multiple cursors std::cout << "Adding cursors at positions (1,5), (3,10), (5,15)..." << std::endl; manager.addCursor(1, 5); manager.addCursor(3, 10); manager.addCursor(5, 15); - + std::cout << "Total cursors: " << manager.getCursorCount() << std::endl; - + auto cursors = manager.getCursors(); for (size_t i = 0; i < cursors.size(); ++i) { - std::cout << "Cursor " << i << ": line " << cursors[i].line - << ", column " << cursors[i].column << std::endl; + std::cout << "Cursor " << i << ": line " << cursors[i].line << ", column " << cursors[i].column << std::endl; } } void demonstrateTextOperations() { std::cout << "\n=== Multi-Cursor Text Operations ===" << std::endl; - + CursorManager& manager = CursorManager::getInstance(); manager.clearCursors(); - + // Add cursors for demonstration manager.addCursor(0, 0); manager.addCursor(1, 5); - + std::cout << "Initial cursor positions:" << std::endl; auto cursors = manager.getCursors(); - for (size_t i = 0; i < cursors.size(); ++i) { - std::cout << " Cursor " << i << ": (" << cursors[i].line - << ", " << cursors[i].column << ")" << std::endl; - } - + printCursorPositions(cursors); + // Simulate text insertion std::cout << "\nInserting text 'Hello' at all cursor positions..." << std::endl; manager.insertTextAtCursors("Hello"); - + cursors = manager.getCursors(); std::cout << "Cursors after insertion:" << std::endl; - for (size_t i = 0; i < cursors.size(); ++i) { - std::cout << " Cursor " << i << ": (" << cursors[i].line - << ", " << cursors[i].column << ")" << std::endl; - } + printCursorPositions(cursors); } void demonstrateSelectionOperations() { std::cout << "\n=== Multi-Cursor Selection Operations ===" << std::endl; - + CursorManager& manager = CursorManager::getInstance(); manager.clearCursors(); - + // Add cursor with selection Selection selection{2, 5, 2, 10}; manager.addCursorWithSelection(2, 5, selection); - + auto cursors = manager.getCursors(); std::cout << "Cursor with selection:" << std::endl; std::cout << " Position: (" << cursors[0].line << ", " << cursors[0].column << ")" << std::endl; - std::cout << " Selection: (" << cursors[0].selection.startLine << ", " - << cursors[0].selection.startColumn << ") to (" - << cursors[0].selection.endLine << ", " << cursors[0].selection.endColumn << ")" << std::endl; + std::cout << " Selection: (" << cursors[0].selection.startLine << ", " << cursors[0].selection.startColumn + << ") to (" << cursors[0].selection.endLine << ", " << cursors[0].selection.endColumn << ")" << std::endl; std::cout << " Has selection: " << (cursors[0].selection.hasSelection() ? "Yes" : "No") << std::endl; } void demonstrateMovementOperations() { std::cout << "\n=== Multi-Cursor Movement Operations ===" << std::endl; - + CursorManager& manager = CursorManager::getInstance(); manager.clearCursors(); - + // Add multiple cursors manager.addCursor(5, 10); manager.addCursor(8, 15); - + std::cout << "Initial cursor positions:" << std::endl; auto cursors = manager.getCursors(); - for (size_t i = 0; i < cursors.size(); ++i) { - std::cout << " Cursor " << i << ": (" << cursors[i].line - << ", " << cursors[i].column << ")" << std::endl; - } - + printCursorPositions(cursors); + // Move all cursors std::cout << "\nMoving all cursors by (+2 lines, +3 columns)..." << std::endl; manager.moveCursors(2, 3); - + cursors = manager.getCursors(); std::cout << "Cursors after movement:" << std::endl; - for (size_t i = 0; i < cursors.size(); ++i) { - std::cout << " Cursor " << i << ": (" << cursors[i].line - << ", " << cursors[i].column << ")" << std::endl; - } + printCursorPositions(cursors); } void demonstrateIntegratedEditorOperations() { std::cout << "\n=== Integrated Editor Multi-Cursor Operations ===" << std::endl; - + IntegratedEditor& editor = IntegratedEditor::getInstance(); - + // Clear any existing cursors editor.clearExtraCursors(); - + // Add cursors through the editor std::cout << "Adding cursors through IntegratedEditor..." << std::endl; editor.addCursorAtPosition(0, 0); editor.addCursorAtPosition(2, 5); editor.addCursorAtPosition(4, 10); - + std::cout << "Total cursors in editor: " << editor.getCursorCount() << std::endl; - + auto cursors = editor.getAllCursors(); for (size_t i = 0; i < cursors.size(); ++i) { - std::cout << " Editor cursor " << i << ": (" << cursors[i].line - << ", " << cursors[i].column << ")" << std::endl; + std::cout << " Editor cursor " << i << ": (" << cursors[i].line << ", " << cursors[i].column << ")" + << std::endl; } - + // Test keyboard shortcut simulation std::cout << "\nSimulating 'Ctrl+D' (add cursor at next occurrence)..." << std::endl; bool shortcutHandled = editor.handleKeyboardShortcut("Ctrl+D", "addCursorAtNextOccurrence"); @@ -134,19 +129,19 @@ void demonstrateIntegratedEditorOperations() { void demonstrateFindOperations() { std::cout << "\n=== Find and Multi-Cursor Operations ===" << std::endl; - + CursorManager& manager = CursorManager::getInstance(); manager.clearCursors(); - + // Start with one cursor manager.addCursor(0, 0); std::cout << "Starting with " << manager.getCursorCount() << " cursor" << std::endl; - + // Find next occurrence (simplified demonstration) std::cout << "Finding next occurrence of 'example'..." << std::endl; manager.findNextOccurrence("example", "This is example content with multiple example words"); std::cout << "Cursors after find next: " << manager.getCursorCount() << std::endl; - + // Select all occurrences std::cout << "Selecting all occurrences..." << std::endl; manager.selectAllOccurrences("example", "This is example content with multiple example words"); @@ -156,7 +151,7 @@ void demonstrateFindOperations() { int main() { std::cout << "Bolt C++ Multi-Cursor Editing Demo" << std::endl; std::cout << "===================================" << std::endl; - + try { demonstrateBasicMultiCursor(); demonstrateTextOperations(); @@ -164,14 +159,13 @@ int main() { demonstrateMovementOperations(); demonstrateIntegratedEditorOperations(); demonstrateFindOperations(); - + std::cout << "\n=== Demo completed successfully! ===" << std::endl; std::cout << "Multi-cursor editing support has been successfully implemented." << std::endl; - } catch (const std::exception& e) { std::cerr << "Demo failed with exception: " << e.what() << std::endl; return 1; } - + return 0; -} \ No newline at end of file +} diff --git a/test/test_bpe_tokenizer.cpp b/test/test_bpe_tokenizer.cpp index db3b5e74..e3a74eac 100644 --- a/test/test_bpe_tokenizer.cpp +++ b/test/test_bpe_tokenizer.cpp @@ -1,9 +1,17 @@ +#include +#include +#include + #include "bolt/ai/bpe_tokenizer.hpp" #include "bolt/test/test_framework.hpp" -#include using namespace bolt; +// Vocabulary with single characters plus the longer "hello" and " world" tokens. +static std::vector characterVocabulary() { + return {"", "", "", "h", "e", "l", "o", " ", "w", "r", "d", "hello", " world"}; +} + // Test tokenizer creation BOLT_TEST(BPETokenizer, BasicCreation) { BPETokenizer tokenizer; @@ -14,11 +22,9 @@ BOLT_TEST(BPETokenizer, BasicCreation) { // Test vocabulary loading BOLT_TEST(BPETokenizer, VocabularyLoading) { BPETokenizer tokenizer; - - std::vector tokens = { - "", "", "", "hello", " world", "test" - }; - + + std::vector tokens = {"", "", "", "hello", " world", "test"}; + bool result = tokenizer.loadVocabulary(tokens); BOLT_ASSERT_TRUE(result); BOLT_ASSERT_TRUE(tokenizer.isLoaded()); @@ -28,7 +34,7 @@ BOLT_TEST(BPETokenizer, VocabularyLoading) { // Test empty vocabulary BOLT_TEST(BPETokenizer, EmptyVocabulary) { BPETokenizer tokenizer; - + std::vector tokens; bool result = tokenizer.loadVocabulary(tokens); BOLT_ASSERT_FALSE(result); @@ -38,35 +44,28 @@ BOLT_TEST(BPETokenizer, EmptyVocabulary) { // Test basic encoding BOLT_TEST(BPETokenizer, BasicEncoding) { BPETokenizer tokenizer; - - std::vector tokens = { - "", "", "", "h", "e", "l", "o", " ", "w", "r", "d", - "hello", " world" - }; - - tokenizer.loadVocabulary(tokens); - + + tokenizer.loadVocabulary(characterVocabulary()); + // Test encoding auto encoded = tokenizer.encode("hello"); BOLT_ASSERT_FALSE(encoded.empty()); - + // Should prefer longer token "hello" over individual characters BOLT_ASSERT_EQUAL(encoded.size(), 1); - BOLT_ASSERT_EQUAL(encoded[0], 11); // Index of "hello" + BOLT_ASSERT_EQUAL(encoded[0], 11); // Index of "hello" } // Test basic decoding BOLT_TEST(BPETokenizer, BasicDecoding) { BPETokenizer tokenizer; - - std::vector tokens = { - "", "", "", "hello", " world" - }; - + + std::vector tokens = {"", "", "", "hello", " world"}; + tokenizer.loadVocabulary(tokens); - + // Test decoding - std::vector token_ids = {3, 4}; // "hello" + " world" + std::vector token_ids = {3, 4}; // "hello" + " world" std::string decoded = tokenizer.decode(token_ids); BOLT_ASSERT_EQUAL(decoded, std::string("hello world")); } @@ -74,36 +73,29 @@ BOLT_TEST(BPETokenizer, BasicDecoding) { // Test round-trip encoding/decoding BOLT_TEST(BPETokenizer, RoundTrip) { BPETokenizer tokenizer; - - std::vector tokens = { - "", "", "", "h", "e", "l", "o", " ", "w", "r", "d", - "hello", " world" - }; - - tokenizer.loadVocabulary(tokens); - + + tokenizer.loadVocabulary(characterVocabulary()); + std::string original = "hello world"; auto encoded = tokenizer.encode(original); std::string decoded = tokenizer.decode(encoded); - + BOLT_ASSERT_EQUAL(decoded, original); } // Test special tokens BOLT_TEST(BPETokenizer, SpecialTokens) { BPETokenizer tokenizer; - - std::vector tokens = { - "", "", "", "test" - }; - + + std::vector tokens = {"", "", "", "test"}; + tokenizer.loadVocabulary(tokens); - + // Check special token IDs are identified int pad = tokenizer.getPADToken(); int bos = tokenizer.getBOSToken(); int eos = tokenizer.getEOSToken(); - + // At least PAD should be identified BOLT_ASSERT_EQUAL(pad, 0); } @@ -111,17 +103,15 @@ BOLT_TEST(BPETokenizer, SpecialTokens) { // Test token lookup BOLT_TEST(BPETokenizer, TokenLookup) { BPETokenizer tokenizer; - - std::vector tokens = { - "", "", "", "hello", "world" - }; - + + std::vector tokens = {"", "", "", "hello", "world"}; + tokenizer.loadVocabulary(tokens); - + // Test getting token string by ID BOLT_ASSERT_EQUAL(tokenizer.getTokenString(3), std::string("hello")); BOLT_ASSERT_EQUAL(tokenizer.getTokenString(4), std::string("world")); - + // Test getting token ID by string BOLT_ASSERT_EQUAL(tokenizer.getTokenId("hello"), 3); BOLT_ASSERT_EQUAL(tokenizer.getTokenId("world"), 4); @@ -130,10 +120,10 @@ BOLT_TEST(BPETokenizer, TokenLookup) { // Test empty string encoding BOLT_TEST(BPETokenizer, EmptyString) { BPETokenizer tokenizer; - + std::vector tokens = {"", "test"}; tokenizer.loadVocabulary(tokens); - + auto encoded = tokenizer.encode(""); BOLT_ASSERT_TRUE(encoded.empty()); } diff --git a/test/test_model_loader.cpp b/test/test_model_loader.cpp index 2a16755d..cc1c04be 100644 --- a/test/test_model_loader.cpp +++ b/test/test_model_loader.cpp @@ -1,9 +1,11 @@ -#include "bolt/ai/model_loader.hpp" -#include "bolt/ai/ggml_loader.hpp" -#include "bolt/ai/gguf_loader.hpp" -#include #include #include +#include +#include + +#include "bolt/ai/ggml_loader.hpp" +#include "bolt/ai/gguf_loader.hpp" +#include "bolt/ai/model_loader.hpp" namespace fs = std::filesystem; @@ -20,7 +22,9 @@ void assert_false(bool condition, const std::string& message) { assert_true(!condition, message); } -void assert_equals(uint32_t actual, uint32_t expected, const std::string& message) { +// Shared implementation of the assert_equals overloads below. +template +void assert_equals_impl(const T& actual, const T& expected, const std::string& message) { if (actual != expected) { std::cerr << "ASSERTION FAILED: " << message << std::endl; std::cerr << " Expected: " << expected << std::endl; @@ -30,71 +34,104 @@ void assert_equals(uint32_t actual, uint32_t expected, const std::string& messag std::cout << "✓ " << message << " (value: " << actual << ")" << std::endl; } +void assert_equals(uint32_t actual, uint32_t expected, const std::string& message) { + assert_equals_impl(actual, expected, message); +} + void assert_equals(const std::string& actual, const std::string& expected, const std::string& message) { - if (actual != expected) { - std::cerr << "ASSERTION FAILED: " << message << std::endl; - std::cerr << " Expected: " << expected << std::endl; - std::cerr << " Actual: " << actual << std::endl; - exit(1); + assert_equals_impl(actual, expected, message); +} + +// Returns true for a ".bin" directory entry that is not an expected-logits file. +bool is_ggml_model_file(const fs::directory_entry& entry) { + if (entry.path().extension() != ".bin") { + return false; + } + // Skip expected-logits files + return entry.path().filename().string().find("expected-logits") == std::string::npos; +} + +// Checks tensor access on a loaded GGUF or GGML loader and prints its first tensor. +template +void check_first_tensor(Loader& loader) { + // Test tensor access + auto tensor_names = loader.getTensorNames(); + std::cout << " Number of tensors: " << tensor_names.size() << std::endl; + assert_true(tensor_names.size() > 0, "Should have at least one tensor"); + + if (!tensor_names.empty()) { + std::string first_tensor = tensor_names[0]; + assert_true(loader.hasTensor(first_tensor), "Should find first tensor"); + + const auto* info = loader.getTensorInfo(first_tensor); + assert_true(info != nullptr, "Should get tensor info"); + + if (info) { + std::cout << " First tensor: " << info->name << std::endl; + std::cout << " Dimensions: " << info->n_dims << "D ["; + for (size_t i = 0; i < info->dims.size(); i++) { + std::cout << info->dims[i]; + if (i < info->dims.size() - 1) { + std::cout << "x"; + } + } + std::cout << "]" << std::endl; + std::cout << " Type: " << info->type << std::endl; + std::cout << " Size: " << info->size << " bytes" << std::endl; + } } - std::cout << "✓ " << message << " (value: " << actual << ")" << std::endl; } // Test format detection void test_format_detection() { std::cout << "\n=== Testing Format Detection ===" << std::endl; - + // Test with GGUF models in the repository std::string gguf_test_path = "/home/ubuntu/bolt-cppml/ggml/llama.cpp/models"; - + if (fs::exists(gguf_test_path)) { for (const auto& entry : fs::directory_iterator(gguf_test_path)) { if (entry.path().extension() == ".gguf") { std::cout << "\nTesting GGUF file: " << entry.path().filename() << std::endl; - + bolt::ModelLoader loader(entry.path().string()); assert_true(loader.load(), "Should load GGUF file successfully"); assert_true(loader.isLoaded(), "Loader should report as loaded"); - assert_equals(static_cast(loader.getFormatType()), - static_cast(bolt::ModelLoader::FormatType::GGUF), - "Should detect GGUF format"); - + assert_equals(static_cast(loader.getFormatType()), + static_cast(bolt::ModelLoader::FormatType::GGUF), "Should detect GGUF format"); + loader.printModelInfo(); - break; // Test only first GGUF file found + break; // Test only first GGUF file found } } } - + // Test with GGML models in the repository std::string ggml_test_path = "/home/ubuntu/bolt-cppml/ggml/rwkv.cpp/tests"; - + if (fs::exists(ggml_test_path)) { for (const auto& entry : fs::directory_iterator(ggml_test_path)) { - if (entry.path().extension() == ".bin") { + if (is_ggml_model_file(entry)) { std::string filename = entry.path().filename().string(); - // Skip expected-logits files - if (filename.find("expected-logits") != std::string::npos) { - continue; - } - + std::cout << "\nTesting GGML file: " << filename << std::endl; - + bolt::ModelLoader loader(entry.path().string()); bool loaded = loader.load(); - + if (loaded) { assert_true(loader.isLoaded(), "Loader should report as loaded"); - assert_equals(static_cast(loader.getFormatType()), - static_cast(bolt::ModelLoader::FormatType::GGML_LEGACY), - "Should detect GGML legacy format"); - + assert_equals(static_cast(loader.getFormatType()), + static_cast(bolt::ModelLoader::FormatType::GGML_LEGACY), + "Should detect GGML legacy format"); + loader.printModelInfo(); } else { - std::cout << " Note: Failed to load (may not be a valid GGML file): " - << loader.getError() << std::endl; + std::cout << " Note: Failed to load (may not be a valid GGML file): " << loader.getError() + << std::endl; } - - break; // Test only first .bin file found + + break; // Test only first .bin file found } } } @@ -103,65 +140,42 @@ void test_format_detection() { // Test GGUF loader directly void test_gguf_loader() { std::cout << "\n=== Testing GGUF Loader ===" << std::endl; - + std::string gguf_test_path = "/home/ubuntu/bolt-cppml/ggml/llama.cpp/models"; - + if (!fs::exists(gguf_test_path)) { std::cout << "GGUF test path not found, skipping GGUF loader tests" << std::endl; return; } - + for (const auto& entry : fs::directory_iterator(gguf_test_path)) { if (entry.path().extension() == ".gguf") { std::cout << "\nTesting GGUF loader with: " << entry.path().filename() << std::endl; - + bolt::GGUFLoader loader(entry.path().string()); assert_true(loader.load(), "GGUF loader should load successfully"); assert_true(loader.isLoaded(), "GGUF loader should report as loaded"); - + // Test metadata access std::cout << " Version: " << loader.getVersion() << std::endl; std::cout << " Tensor count: " << loader.getTensorCount() << std::endl; std::cout << " Metadata count: " << loader.getMetadataCount() << std::endl; - + // Test common metadata keys if (loader.hasMetadata("general.architecture")) { std::string arch = loader.getMetadataString("general.architecture"); std::cout << " Architecture: " << arch << std::endl; assert_false(arch.empty(), "Architecture should not be empty"); } - + if (loader.hasMetadata("general.name")) { std::string name = loader.getMetadataString("general.name"); std::cout << " Model name: " << name << std::endl; } - - // Test tensor access - auto tensor_names = loader.getTensorNames(); - std::cout << " Number of tensors: " << tensor_names.size() << std::endl; - assert_true(tensor_names.size() > 0, "Should have at least one tensor"); - - if (!tensor_names.empty()) { - std::string first_tensor = tensor_names[0]; - assert_true(loader.hasTensor(first_tensor), "Should find first tensor"); - - const bolt::TensorInfo* info = loader.getTensorInfo(first_tensor); - assert_true(info != nullptr, "Should get tensor info"); - - if (info) { - std::cout << " First tensor: " << info->name << std::endl; - std::cout << " Dimensions: " << info->n_dims << "D ["; - for (size_t i = 0; i < info->dims.size(); i++) { - std::cout << info->dims[i]; - if (i < info->dims.size() - 1) std::cout << "x"; - } - std::cout << "]" << std::endl; - std::cout << " Type: " << info->type << std::endl; - std::cout << " Size: " << info->size << " bytes" << std::endl; - } - } - - break; // Test only first GGUF file + + check_first_tensor(loader); + + break; // Test only first GGUF file } } } @@ -169,36 +183,31 @@ void test_gguf_loader() { // Test GGML loader directly void test_ggml_loader() { std::cout << "\n=== Testing GGML Loader ===" << std::endl; - + std::string ggml_test_path = "/home/ubuntu/bolt-cppml/ggml/rwkv.cpp/tests"; - + if (!fs::exists(ggml_test_path)) { std::cout << "GGML test path not found, skipping GGML loader tests" << std::endl; return; } - + for (const auto& entry : fs::directory_iterator(ggml_test_path)) { - if (entry.path().extension() == ".bin") { + if (is_ggml_model_file(entry)) { std::string filename = entry.path().filename().string(); - - // Skip expected-logits files - if (filename.find("expected-logits") != std::string::npos) { - continue; - } - + // Only test RWKV model files if (filename.find("tiny-rwkv") == std::string::npos) { continue; } - + std::cout << "\nTesting GGML loader with: " << filename << std::endl; - + bolt::GGMLLoader loader(entry.path().string()); bool loaded = loader.load(); - + if (loaded) { assert_true(loader.isLoaded(), "GGML loader should report as loaded"); - + // Test hyperparameters const auto& hparams = loader.getHyperparameters(); std::cout << " Hyperparameters:" << std::endl; @@ -207,47 +216,24 @@ void test_ggml_loader() { std::cout << " n_layer: " << hparams.n_layer << std::endl; std::cout << " n_head: " << hparams.n_head << std::endl; std::cout << " ftype: " << hparams.ftype << std::endl; - + assert_true(hparams.n_vocab > 0, "Vocabulary size should be positive"); assert_true(hparams.n_embd > 0, "Embedding dimension should be positive"); assert_true(hparams.n_layer > 0, "Number of layers should be positive"); - + // Test vocabulary const auto& vocab = loader.getVocabulary(); std::cout << " Vocabulary size: " << vocab.size() << std::endl; - assert_equals(static_cast(vocab.size()), hparams.n_vocab, - "Vocabulary size should match hyperparameter"); - - // Test tensor access - auto tensor_names = loader.getTensorNames(); - std::cout << " Number of tensors: " << tensor_names.size() << std::endl; - assert_true(tensor_names.size() > 0, "Should have at least one tensor"); - - if (!tensor_names.empty()) { - std::string first_tensor = tensor_names[0]; - assert_true(loader.hasTensor(first_tensor), "Should find first tensor"); - - const bolt::GGMLTensorInfo* info = loader.getTensorInfo(first_tensor); - assert_true(info != nullptr, "Should get tensor info"); - - if (info) { - std::cout << " First tensor: " << info->name << std::endl; - std::cout << " Dimensions: " << info->n_dims << "D ["; - for (size_t i = 0; i < info->dims.size(); i++) { - std::cout << info->dims[i]; - if (i < info->dims.size() - 1) std::cout << "x"; - } - std::cout << "]" << std::endl; - std::cout << " Type: " << info->type << std::endl; - std::cout << " Size: " << info->size << " bytes" << std::endl; - } - } + assert_equals(static_cast(vocab.size()), hparams.n_vocab, + "Vocabulary size should match hyperparameter"); + + check_first_tensor(loader); } else { std::cout << " Note: Failed to load: " << loader.getError() << std::endl; std::cout << " This may be expected for some test files" << std::endl; } - - break; // Test only first valid RWKV file + + break; // Test only first valid RWKV file } } } @@ -255,62 +241,59 @@ void test_ggml_loader() { // Test unified model loader void test_unified_loader() { std::cout << "\n=== Testing Unified Model Loader ===" << std::endl; - + // Test with both GGUF and GGML files - std::vector test_paths = { - "/home/ubuntu/bolt-cppml/ggml/llama.cpp/models", - "/home/ubuntu/bolt-cppml/ggml/rwkv.cpp/tests" - }; - + std::vector test_paths = {"/home/ubuntu/bolt-cppml/ggml/llama.cpp/models", + "/home/ubuntu/bolt-cppml/ggml/rwkv.cpp/tests"}; + for (const auto& test_path : test_paths) { if (!fs::exists(test_path)) { continue; } - + for (const auto& entry : fs::directory_iterator(test_path)) { std::string ext = entry.path().extension().string(); std::string filename = entry.path().filename().string(); - + // Skip non-model files if (ext != ".gguf" && ext != ".bin") { continue; } - + // Skip expected-logits files if (filename.find("expected-logits") != std::string::npos) { continue; } - + std::cout << "\nTesting unified loader with: " << filename << std::endl; - + bolt::ModelLoader loader(entry.path().string()); bool loaded = loader.load(); - + if (loaded) { assert_true(loader.isLoaded(), "Unified loader should report as loaded"); - + std::cout << " Format: " << loader.getFormatName() << std::endl; std::cout << " Architecture: " << loader.getArchitecture() << std::endl; std::cout << " Vocab size: " << loader.getVocabSize() << std::endl; std::cout << " Embedding dim: " << loader.getEmbeddingDim() << std::endl; std::cout << " Num layers: " << loader.getNumLayers() << std::endl; - + // Test tensor access through unified interface auto tensor_names = loader.getTensorNames(); std::cout << " Tensor count: " << tensor_names.size() << std::endl; - + if (!tensor_names.empty()) { std::string first_tensor = tensor_names[0]; - assert_true(loader.hasTensor(first_tensor), - "Unified loader should find tensors"); + assert_true(loader.hasTensor(first_tensor), "Unified loader should find tensors"); } - + // Print full model info loader.printModelInfo(); } else { std::cout << " Note: Failed to load: " << loader.getError() << std::endl; } - + // Test one file per directory break; } @@ -320,23 +303,22 @@ void test_unified_loader() { int main() { std::cout << "=== GGML/GGUF Model Loader Test Suite ===" << std::endl; std::cout << "Testing model loading capabilities for both legacy GGML and GGUF formats\n" << std::endl; - + try { // Run all tests test_format_detection(); test_gguf_loader(); test_ggml_loader(); test_unified_loader(); - + std::cout << "\n=== All Tests Passed! ===" << std::endl; std::cout << "✓ Format detection working correctly" << std::endl; std::cout << "✓ GGUF loader functional" << std::endl; std::cout << "✓ GGML loader functional" << std::endl; std::cout << "✓ Unified loader working for both formats" << std::endl; - + return 0; - } - catch (const std::exception& e) { + } catch (const std::exception& e) { std::cerr << "Test failed with exception: " << e.what() << std::endl; return 1; } diff --git a/test/test_plugin_system.cpp b/test/test_plugin_system.cpp index cad7ec68..cabe201c 100644 --- a/test/test_plugin_system.cpp +++ b/test/test_plugin_system.cpp @@ -1,33 +1,34 @@ -#include "bolt/test_framework.hpp" -#include "bolt/core/plugin_system.hpp" -#include "bolt/core/plugin_interface.hpp" -#include "bolt/core/editor_store.hpp" -#include "bolt/editor/integrated_editor.hpp" +#include #include #include -#include + +#include "bolt/core/editor_store.hpp" +#include "bolt/core/plugin_interface.hpp" +#include "bolt/core/plugin_system.hpp" +#include "bolt/editor/integrated_editor.hpp" +#include "bolt/test_framework.hpp" using namespace bolt::test; namespace bolt { // Test plugin implementations -class TestEditorPlugin : public IEditorPlugin { -private: +// Metadata storage and lifecycle state handling shared by the test plugins. +template +class TestPluginBase : public PluginInterface { + protected: PluginMetadata metadata_; - int documentOpenedCount_ = 0; - int documentClosedCount_ = 0; -public: - TestEditorPlugin(const std::string& name = "TestEditorPlugin") { + TestPluginBase(const std::string& name, const std::string& description) { metadata_.name = name; metadata_.version = "1.0.0"; - metadata_.description = "Test editor plugin"; + metadata_.description = description; metadata_.author = "Test Author"; metadata_.license = "MIT"; metadata_.apiVersion = {1, 0, 0}; } + public: PluginMetadata getMetadata() const override { return metadata_; } bool initialize(PluginContext* context) override { @@ -35,124 +36,93 @@ class TestEditorPlugin : public IEditorPlugin { return true; } - void activate() override { - IPlugin::state_ = PluginState::Active; - } - - void deactivate() override { - IPlugin::state_ = PluginState::Loaded; - } - - void cleanup() override { - IPlugin::state_ = PluginState::Unloaded; - } - - void onDocumentOpened(const std::string& filePath, const std::string& content) override { - documentOpenedCount_++; - } + void activate() override { IPlugin::state_ = PluginState::Active; } - void onDocumentClosed(const std::string& filePath) override { - documentClosedCount_++; - } + void deactivate() override { IPlugin::state_ = PluginState::Loaded; } - int getDocumentOpenedCount() const { return documentOpenedCount_; } - int getDocumentClosedCount() const { return documentClosedCount_; } + void cleanup() override { IPlugin::state_ = PluginState::Unloaded; } }; -class TestLanguagePlugin : public ILanguagePlugin { -private: - PluginMetadata metadata_; +class TestEditorPlugin : public TestPluginBase { + private: + int documentOpenedCount_ = 0; + int documentClosedCount_ = 0; -public: - TestLanguagePlugin() { - metadata_.name = "TestLanguagePlugin"; - metadata_.version = "1.0.0"; - metadata_.description = "Test language plugin"; - metadata_.author = "Test Author"; - metadata_.license = "MIT"; - metadata_.apiVersion = {1, 0, 0}; - } + public: + explicit TestEditorPlugin(const std::string& name = "TestEditorPlugin") + : TestPluginBase(name, "Test editor plugin") {} - PluginMetadata getMetadata() const override { return metadata_; } + void onDocumentOpened(const std::string& filePath, const std::string& content) override { documentOpenedCount_++; } - bool initialize(PluginContext* context) override { - IPlugin::state_ = PluginState::Initialized; - return true; - } - - void activate() override { - IPlugin::state_ = PluginState::Active; - } + void onDocumentClosed(const std::string& filePath) override { documentClosedCount_++; } - void deactivate() override { - IPlugin::state_ = PluginState::Loaded; - } + int getDocumentOpenedCount() const { return documentOpenedCount_; } + int getDocumentClosedCount() const { return documentClosedCount_; } +}; - void cleanup() override { - IPlugin::state_ = PluginState::Unloaded; - } +class TestLanguagePlugin : public TestPluginBase { + public: + TestLanguagePlugin() : TestPluginBase("TestLanguagePlugin", "Test language plugin") {} - std::vector getSupportedExtensions() const override { - return {"cpp", "hpp", "c", "h"}; - } + std::vector getSupportedExtensions() const override { return {"cpp", "hpp", "c", "h"}; } std::vector getCodeCompletions(const std::string& filePath, size_t line, size_t column) override { return {"std::", "boost::", "auto"}; } }; -} // namespace bolt +} // namespace bolt // Test cases using the project's test framework BOLT_TEST(PluginSystem, BasicRegistration) { bolt::PluginSystem& pluginSystem = bolt::PluginSystem::getInstance(); - + // Clean state pluginSystem.shutdown(); pluginSystem.initialize(nullptr, nullptr); - + auto plugin = std::make_shared("TestPlugin1"); - + BOLT_ASSERT_TRUE(pluginSystem.loadPlugin(plugin)); BOLT_ASSERT_TRUE(pluginSystem.isPluginLoaded("TestPlugin1")); BOLT_ASSERT(plugin->getState() == bolt::PluginState::Initialized); - + BOLT_ASSERT_TRUE(pluginSystem.activatePlugin("TestPlugin1")); BOLT_ASSERT_TRUE(pluginSystem.isPluginActive("TestPlugin1")); BOLT_ASSERT(plugin->getState() == bolt::PluginState::Active); - + BOLT_ASSERT_TRUE(pluginSystem.deactivatePlugin("TestPlugin1")); BOLT_ASSERT_FALSE(pluginSystem.isPluginActive("TestPlugin1")); - + BOLT_ASSERT_TRUE(pluginSystem.unloadPlugin("TestPlugin1")); BOLT_ASSERT_FALSE(pluginSystem.isPluginLoaded("TestPlugin1")); - + pluginSystem.shutdown(); } BOLT_TEST(PluginSystem, PluginQueries) { bolt::PluginSystem& pluginSystem = bolt::PluginSystem::getInstance(); - + pluginSystem.shutdown(); pluginSystem.initialize(nullptr, nullptr); - + auto plugin1 = std::make_shared("Plugin1"); auto plugin2 = std::make_shared("Plugin2"); - + pluginSystem.loadPlugin(plugin1); pluginSystem.loadPlugin(plugin2); - + auto loadedNames = pluginSystem.getLoadedPluginNames(); BOLT_ASSERT_EQ(2, loadedNames.size()); - + auto retrievedPlugin = pluginSystem.getPlugin("Plugin1"); BOLT_ASSERT_NOT_NULL(retrievedPlugin.get()); BOLT_ASSERT_EQ("Plugin1", retrievedPlugin->getMetadata().name); - + auto allPlugins = pluginSystem.getPlugins(); BOLT_ASSERT_EQ(2, allPlugins.size()); - + pluginSystem.unloadPlugin("Plugin1"); pluginSystem.unloadPlugin("Plugin2"); pluginSystem.shutdown(); @@ -160,91 +130,91 @@ BOLT_TEST(PluginSystem, PluginQueries) { BOLT_TEST(PluginSystem, PluginMetadata) { bolt::PluginSystem& pluginSystem = bolt::PluginSystem::getInstance(); - + pluginSystem.shutdown(); pluginSystem.initialize(nullptr, nullptr); - + auto plugin = std::make_shared("MetadataTest"); pluginSystem.loadPlugin(plugin); - + auto metadata = pluginSystem.getPluginMetadata(); BOLT_ASSERT_EQ(1, metadata.size()); BOLT_ASSERT_EQ("MetadataTest", metadata[0].name); BOLT_ASSERT_EQ("1.0.0", metadata[0].version); BOLT_ASSERT_EQ("Test Author", metadata[0].author); - + pluginSystem.unloadPlugin("MetadataTest"); pluginSystem.shutdown(); } BOLT_TEST(PluginSystem, LanguagePlugins) { bolt::PluginSystem& pluginSystem = bolt::PluginSystem::getInstance(); - + pluginSystem.shutdown(); pluginSystem.initialize(nullptr, nullptr); - + auto langPlugin = std::make_shared(); pluginSystem.loadPlugin(langPlugin); - + auto cppPlugins = pluginSystem.getLanguagePluginsForFile("test.cpp"); BOLT_ASSERT_EQ(1, cppPlugins.size()); BOLT_ASSERT_EQ("TestLanguagePlugin", cppPlugins[0]->getMetadata().name); - + auto hppPlugins = pluginSystem.getLanguagePluginsForFile("test.hpp"); BOLT_ASSERT_EQ(1, hppPlugins.size()); - + auto jsPlugins = pluginSystem.getLanguagePluginsForFile("test.js"); BOLT_ASSERT_EQ(0, jsPlugins.size()); - + pluginSystem.unloadPlugin("TestLanguagePlugin"); pluginSystem.shutdown(); } BOLT_TEST(PluginSystem, ErrorHandling) { bolt::PluginSystem& pluginSystem = bolt::PluginSystem::getInstance(); - + pluginSystem.shutdown(); pluginSystem.initialize(nullptr, nullptr); - + // Clear any existing errors pluginSystem.clearPluginErrors(); - + // Try to load a non-existent plugin BOLT_ASSERT_FALSE(pluginSystem.loadPlugin("/nonexistent/plugin.so")); - + auto errors = pluginSystem.getPluginErrors(); BOLT_ASSERT_TRUE(errors.size() > 0); - + pluginSystem.clearPluginErrors(); errors = pluginSystem.getPluginErrors(); BOLT_ASSERT_EQ(0, errors.size()); - + pluginSystem.shutdown(); } BOLT_TEST(PluginSystem, LegacyPluginSupport) { bolt::PluginSystem& pluginSystem = bolt::PluginSystem::getInstance(); - + pluginSystem.shutdown(); pluginSystem.initialize(nullptr, nullptr); - + bool initialized = false; bool cleaned = false; - + bolt::Plugin legacyPlugin; legacyPlugin.name = "LegacyTest"; legacyPlugin.version = "1.0.0"; legacyPlugin.initialize = [&]() { initialized = true; }; legacyPlugin.cleanup = [&]() { cleaned = true; }; - + pluginSystem.registerPlugin(legacyPlugin); pluginSystem.initializeAll(); - + BOLT_ASSERT_TRUE(initialized); - + pluginSystem.cleanupAll(); BOLT_ASSERT_TRUE(cleaned); - + pluginSystem.shutdown(); } @@ -253,15 +223,15 @@ BOLT_TEST(PluginAPI, VersionCompatibility) { bolt::PluginAPIVersion v1_1_0{1, 1, 0}; bolt::PluginAPIVersion v1_2_0{1, 2, 0}; bolt::PluginAPIVersion v2_0_0{2, 0, 0}; - + // Same major version, newer minor should be compatible BOLT_ASSERT_TRUE(v1_0_0.isCompatible(v1_0_0)); BOLT_ASSERT_TRUE(v1_1_0.isCompatible(v1_0_0)); BOLT_ASSERT_TRUE(v1_2_0.isCompatible(v1_1_0)); - + // Older minor version should not be compatible BOLT_ASSERT_FALSE(v1_0_0.isCompatible(v1_1_0)); - + // Different major version should not be compatible BOLT_ASSERT_FALSE(v1_0_0.isCompatible(v2_0_0)); BOLT_ASSERT_FALSE(v2_0_0.isCompatible(v1_0_0)); @@ -277,7 +247,7 @@ BOLT_TEST(PluginMetadata, ValidMetadata) { metadata.name = "TestPlugin"; metadata.version = "1.0.0"; metadata.description = "Test plugin"; - + BOLT_ASSERT_TRUE(metadata.isValid()); } @@ -285,7 +255,7 @@ BOLT_TEST(PluginMetadata, InvalidMetadataEmptyName) { bolt::PluginMetadata metadata; metadata.name = ""; metadata.version = "1.0.0"; - + BOLT_ASSERT_FALSE(metadata.isValid()); } @@ -293,26 +263,26 @@ BOLT_TEST(PluginMetadata, InvalidMetadataEmptyVersion) { bolt::PluginMetadata metadata; metadata.name = "TestPlugin"; metadata.version = ""; - + BOLT_ASSERT_FALSE(metadata.isValid()); } int main() { bolt::test::TestSuite& suite = bolt::test::TestSuite::getInstance(); - + try { std::cout << "Running Plugin System Tests..." << std::endl; int result = suite.runAllTests(); - + if (result == 0) { std::cout << "\n✅ All Plugin System tests passed!" << std::endl; } else { std::cout << "\n❌ Some Plugin System tests failed!" << std::endl; } - + return result; } catch (...) { std::cout << "\n❌ Plugin System tests crashed!" << std::endl; return 1; } -} \ No newline at end of file +} diff --git a/test_benchmark_suite.cpp b/test_benchmark_suite.cpp index 2eee630a..af3bac7a 100644 --- a/test_benchmark_suite.cpp +++ b/test_benchmark_suite.cpp @@ -1,45 +1,42 @@ +#include +#include +#include +#include +#include + #include "include/bolt/core/benchmark_suite.hpp" -#include "include/bolt/core/performance_profiler.hpp" #include "include/bolt/core/logging.hpp" +#include "include/bolt/core/performance_profiler.hpp" #include "include/bolt/test_framework.hpp" -#include -#include -#include -using namespace bolt; +using namespace bolt; // NOLINT(build/namespaces) // Test benchmark functions -BOLT_BENCHMARK_CONFIG(test_simple_benchmark, "TEST", - "Simple test benchmark for validation", 5) { - +BOLT_BENCHMARK_CONFIG(test_simple_benchmark, "TEST", "Simple test benchmark for validation", 5) { // Simulate some work std::this_thread::sleep_for(std::chrono::milliseconds(10)); } -BOLT_BENCHMARK_CONFIG(test_failing_benchmark, "TEST", - "Benchmark that should fail to test error handling", 3) { - +BOLT_BENCHMARK_CONFIG(test_failing_benchmark, "TEST", "Benchmark that should fail to test error handling", 3) { // Throw an exception to test error handling throw std::runtime_error("Test benchmark failure"); } -BOLT_BENCHMARK_CONFIG(test_variable_duration, "TEST", - "Benchmark with variable duration for statistics testing", 10) { - +BOLT_BENCHMARK_CONFIG(test_variable_duration, "TEST", "Benchmark with variable duration for statistics testing", 10) { // Variable duration based on static counter static int counter = 0; - int duration = 5 + (counter++ % 10); // 5-15ms range + int duration = 5 + (counter++ % 10); // 5-15ms range std::this_thread::sleep_for(std::chrono::milliseconds(duration)); } // Test framework integration BOLT_TEST(BenchmarkSuite, BasicFunctionality) { auto& suite = BenchmarkSuite::getInstance(); - + // Test that we have some benchmarks registered auto benchmarks = suite.getAvailableBenchmarks(); BOLT_ASSERT_TRUE(benchmarks.size() > 0); - + // Test that we have test category auto categories = suite.getAvailableCategories(); bool hasTestCategory = std::find(categories.begin(), categories.end(), "TEST") != categories.end(); @@ -49,15 +46,15 @@ BOLT_TEST(BenchmarkSuite, BasicFunctionality) { BOLT_TEST(BenchmarkSuite, RunSingleBenchmark) { auto& suite = BenchmarkSuite::getInstance(); suite.enableVerboseOutput(false); - + // Run a simple test benchmark auto result = suite.runBenchmark("test_simple_benchmark"); - + BOLT_ASSERT_TRUE(result.isValid()); BOLT_ASSERT_EQ(result.name, "test_simple_benchmark"); BOLT_ASSERT_EQ(result.category, "TEST"); BOLT_ASSERT_TRUE(result.averageDurationMs >= 10.0); // Should take at least 10ms - BOLT_ASSERT_TRUE(result.averageDurationMs < 100.0); // But not too long + BOLT_ASSERT_TRUE(result.averageDurationMs < 100.0); // But not too long BOLT_ASSERT_TRUE(result.successfulRuns > 0); BOLT_ASSERT_EQ(result.failedRuns, 0); } @@ -65,10 +62,10 @@ BOLT_TEST(BenchmarkSuite, RunSingleBenchmark) { BOLT_TEST(BenchmarkSuite, FailingBenchmark) { auto& suite = BenchmarkSuite::getInstance(); suite.enableVerboseOutput(false); - + // Run a benchmark that should fail auto result = suite.runBenchmark("test_failing_benchmark"); - + BOLT_ASSERT_FALSE(result.isValid()); BOLT_ASSERT_EQ(result.name, "test_failing_benchmark"); BOLT_ASSERT_TRUE(result.failedRuns > 0); @@ -78,12 +75,12 @@ BOLT_TEST(BenchmarkSuite, FailingBenchmark) { BOLT_TEST(BenchmarkSuite, RunByCategory) { auto& suite = BenchmarkSuite::getInstance(); suite.enableVerboseOutput(false); - + // Run all TEST category benchmarks auto results = suite.runBenchmarksByCategory("TEST"); - - BOLT_ASSERT_TRUE(results.size() >= 3); // We have at least 3 test benchmarks - + + BOLT_ASSERT_TRUE(results.size() >= 3); // We have at least 3 test benchmarks + // Check that all results are from TEST category for (const auto& result : results) { BOLT_ASSERT_EQ(result.category, "TEST"); @@ -93,97 +90,91 @@ BOLT_TEST(BenchmarkSuite, RunByCategory) { BOLT_TEST(BenchmarkSuite, StatisticsCalculation) { auto& suite = BenchmarkSuite::getInstance(); suite.enableVerboseOutput(false); - + // Run benchmark with variable duration auto result = suite.runBenchmark("test_variable_duration"); - + BOLT_ASSERT_TRUE(result.isValid()); - BOLT_ASSERT_TRUE(result.standardDeviationMs > 0.0); // Should have some variation + BOLT_ASSERT_TRUE(result.standardDeviationMs > 0.0); // Should have some variation BOLT_ASSERT_TRUE(result.minDurationMs < result.maxDurationMs); BOLT_ASSERT_TRUE(result.averageDurationMs >= result.minDurationMs); BOLT_ASSERT_TRUE(result.averageDurationMs <= result.maxDurationMs); } +// Asserts that a generated report file can be opened and returns its content. +static std::string readReportFile(const std::string& filename) { + std::ifstream file(filename); + BOLT_ASSERT_TRUE(file.is_open()); + + std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); + return content; +} + BOLT_TEST(BenchmarkSuite, JsonReportGeneration) { auto& suite = BenchmarkSuite::getInstance(); suite.enableVerboseOutput(false); - + // Run a simple benchmark auto result = suite.runBenchmark("test_simple_benchmark"); std::vector results = {result}; - + // Generate JSON report std::string filename = "/tmp/test_benchmark_report.json"; suite.generateJsonReport(results, filename); - + // Verify file was created and has content - std::ifstream file(filename); - BOLT_ASSERT_TRUE(file.is_open()); - - std::string content((std::istreambuf_iterator(file)), - std::istreambuf_iterator()); + std::string content = readReportFile(filename); BOLT_ASSERT_TRUE(content.find("test_simple_benchmark") != std::string::npos); BOLT_ASSERT_TRUE(content.find("benchmark_suite_version") != std::string::npos); - - file.close(); + std::remove(filename.c_str()); } BOLT_TEST(BenchmarkSuite, CsvReportGeneration) { auto& suite = BenchmarkSuite::getInstance(); suite.enableVerboseOutput(false); - + // Run a simple benchmark auto result = suite.runBenchmark("test_simple_benchmark"); std::vector results = {result}; - + // Generate CSV report std::string filename = "/tmp/test_benchmark_report.csv"; suite.generateCsvReport(results, filename); - + // Verify file was created and has content - std::ifstream file(filename); - BOLT_ASSERT_TRUE(file.is_open()); - - std::string content((std::istreambuf_iterator(file)), - std::istreambuf_iterator()); + std::string content = readReportFile(filename); BOLT_ASSERT_TRUE(content.find("test_simple_benchmark") != std::string::npos); BOLT_ASSERT_TRUE(content.find("Name,Category") != std::string::npos); - - file.close(); + std::remove(filename.c_str()); } BOLT_TEST(BenchmarkSuite, HtmlReportGeneration) { auto& suite = BenchmarkSuite::getInstance(); suite.enableVerboseOutput(false); - + // Run a simple benchmark auto result = suite.runBenchmark("test_simple_benchmark"); std::vector results = {result}; - + // Generate HTML report std::string filename = "/tmp/test_benchmark_report.html"; suite.generateHtmlReport(results, filename); - + // Verify file was created and has content - std::ifstream file(filename); - BOLT_ASSERT_TRUE(file.is_open()); - - std::string content((std::istreambuf_iterator(file)), - std::istreambuf_iterator()); + std::string content = readReportFile(filename); BOLT_ASSERT_TRUE(content.find("test_simple_benchmark") != std::string::npos); BOLT_ASSERT_TRUE(content.find("") != std::string::npos); BOLT_ASSERT_TRUE(content.find("Bolt Performance Benchmark Report") != std::string::npos); - - file.close(); + std::remove(filename.c_str()); } BOLT_TEST(BenchmarkSuite, BaselineComparison) { auto& suite = BenchmarkSuite::getInstance(); suite.enableVerboseOutput(false); - + // Create baseline results BenchmarkResult baseline; baseline.name = "test_benchmark"; @@ -191,57 +182,56 @@ BOLT_TEST(BenchmarkSuite, BaselineComparison) { baseline.averageDurationMs = 100.0; baseline.successfulRuns = 10; baseline.totalIterations = 10; - + // Create current results (faster) BenchmarkResult current; current.name = "test_benchmark"; current.category = "TEST"; - current.averageDurationMs = 80.0; // 20% improvement + current.averageDurationMs = 80.0; // 20% improvement current.successfulRuns = 10; current.totalIterations = 10; - + std::vector baselineVec = {baseline}; std::vector currentVec = {current}; - + auto comparisons = suite.compareWithBaseline(currentVec, baselineVec); - + BOLT_ASSERT_EQ(comparisons.size(), 1); BOLT_ASSERT_EQ(comparisons[0].benchmarkName, "test_benchmark"); - BOLT_ASSERT_TRUE(comparisons[0].durationChangePercent < 0); // Negative = improvement + BOLT_ASSERT_TRUE(comparisons[0].durationChangePercent < 0); // Negative = improvement BOLT_ASSERT_TRUE(comparisons[0].hasImprovement()); } int main() { std::cout << "Benchmark Suite Test" << std::endl; std::cout << "===================" << std::endl; - + try { // Initialize logging for test output LogManager::configureConsoleLogging(LogLevel::WARN, false); - + std::cout << "Testing basic functionality..." << std::endl; runTest("BasicFunctionality", test_BenchmarkSuite_BasicFunctionality); runTest("RunSingleBenchmark", test_BenchmarkSuite_RunSingleBenchmark); runTest("FailingBenchmark", test_BenchmarkSuite_FailingBenchmark); runTest("RunByCategory", test_BenchmarkSuite_RunByCategory); - + std::cout << "\nTesting statistics..." << std::endl; runTest("StatisticsCalculation", test_BenchmarkSuite_StatisticsCalculation); - + std::cout << "\nTesting report generation..." << std::endl; runTest("JsonReportGeneration", test_BenchmarkSuite_JsonReportGeneration); runTest("CsvReportGeneration", test_BenchmarkSuite_CsvReportGeneration); runTest("HtmlReportGeneration", test_BenchmarkSuite_HtmlReportGeneration); - + std::cout << "\nTesting comparison features..." << std::endl; runTest("BaselineComparison", test_BenchmarkSuite_BaselineComparison); - + std::cout << "\n=== All Tests Passed ===\n" << std::endl; - } catch (const std::exception& e) { std::cerr << "Test failed with exception: " << e.what() << std::endl; return 1; } - + return 0; -} \ No newline at end of file +} diff --git a/test_gpu_simple.cpp b/test_gpu_simple.cpp index c1e2a2d0..c0ba886e 100644 --- a/test_gpu_simple.cpp +++ b/test_gpu_simple.cpp @@ -1,14 +1,15 @@ -#include -#include +#include +#include +#include + #include +#include #include -#include -#include #include +#include +#include #include -#include -#include -#include +#include // Simple logging for testing #define BOLT_INFO(msg) std::cout << "[INFO] " << msg << std::endl @@ -19,12 +20,7 @@ namespace bolt { namespace ai { -enum class GPUBackendType { - CPU, - CUDA, - OpenCL, - Vulkan -}; +enum class GPUBackendType { CPU, CUDA, OpenCL, Vulkan }; struct GPUDeviceInfo { int deviceId; @@ -43,30 +39,30 @@ struct GPUConfig { // Simple GPU manager for testing class SimpleGPUManager { -public: + public: static SimpleGPUManager& getInstance() { static SimpleGPUManager instance; return instance; } - + bool initialize(const GPUConfig& config = GPUConfig{}) { BOLT_INFO("Initializing Simple GPU Manager"); - + // Try to initialize CPU backend backend_ = ggml_backend_cpu_init(); if (!backend_) { BOLT_ERROR("Failed to initialize CPU backend"); return false; } - + bufferType_ = ggml_backend_cpu_buffer_type(); currentBackendType_ = GPUBackendType::CPU; initialized_ = true; - + BOLT_INFO("CPU backend initialized successfully"); return true; } - + void shutdown() { if (backend_) { ggml_backend_free(backend_); @@ -75,12 +71,12 @@ class SimpleGPUManager { initialized_ = false; BOLT_INFO("GPU manager shut down"); } - + bool isInitialized() const { return initialized_; } - + std::vector detectAvailableDevices() { std::vector devices; - + // Always add CPU device GPUDeviceInfo cpuDevice; cpuDevice.deviceId = -1; @@ -91,10 +87,10 @@ class SimpleGPUManager { cpuDevice.backendType = GPUBackendType::CPU; cpuDevice.isAvailable = true; devices.push_back(cpuDevice); - + return devices; } - + GPUDeviceInfo getCurrentDevice() const { GPUDeviceInfo device; device.name = "CPU"; @@ -103,14 +99,12 @@ class SimpleGPUManager { device.isAvailable = true; return device; } - - GPUBackendType getCurrentBackendType() const { - return currentBackendType_; - } - + + GPUBackendType getCurrentBackendType() const { return currentBackendType_; } + ggml_backend_t getBackend() const { return backend_; } -private: + private: bool initialized_ = false; ggml_backend_t backend_ = nullptr; ggml_backend_buffer_type_t bufferType_ = nullptr; @@ -119,138 +113,141 @@ class SimpleGPUManager { // Simple model wrapper for testing class SimpleGPUModel { -public: - SimpleGPUModel(const std::string& modelPath, const GPUConfig& config = GPUConfig{}) + public: + explicit SimpleGPUModel(const std::string& modelPath, const GPUConfig& config = GPUConfig{}) : modelPath_(modelPath), config_(config) { BOLT_INFO("Creating GPU model: " + modelPath); } - - ~SimpleGPUModel() { - BOLT_INFO("Destroying GPU model"); - } - - bool isLoaded() const { return false; } // Always false for test - bool isGPUAccelerated() const { + + ~SimpleGPUModel() { BOLT_INFO("Destroying GPU model"); } + + bool isLoaded() const { return false; } // Always false for test + bool isGPUAccelerated() const { auto& manager = SimpleGPUManager::getInstance(); return manager.isInitialized() && manager.getCurrentBackendType() != GPUBackendType::CPU; } - + std::string generate(const std::string& prompt, size_t maxTokens = 100) { BOLT_INFO("Generating response for prompt: " + prompt); return "Test generated response"; } - + std::vector generateEmbedding(const std::string& input) { BOLT_INFO("Generating embedding for input: " + input); - return std::vector(768, 0.1f); // Mock embedding + return std::vector(768, 0.1f); // Mock embedding } -private: + private: std::string modelPath_; GPUConfig config_; }; // Utility functions namespace gpu_utils { - bool isGPUAccelerationAvailable() { - // For this simple test, always return true (CPU is always available) - return true; - } - - GPUConfig getRecommendedGPUConfig() { - GPUConfig config; - config.preferredBackend = GPUBackendType::CPU; // Always recommend CPU for testing - return config; - } - - GPUBackendType benchmarkGPUBackends() { - return GPUBackendType::CPU; - } +bool isGPUAccelerationAvailable() { + // For this simple test, always return true (CPU is always available) + return true; } -} // namespace ai -} // namespace bolt +GPUConfig getRecommendedGPUConfig() { + GPUConfig config; + config.preferredBackend = GPUBackendType::CPU; // Always recommend CPU for testing + return config; +} -using namespace bolt::ai; +GPUBackendType benchmarkGPUBackends() { + return GPUBackendType::CPU; +} +} // namespace gpu_utils + +} // namespace ai +} // namespace bolt + +using namespace bolt::ai; // NOLINT(build/namespaces) + +// Returns the display name of a GPU backend type (empty for an unknown value). +static const char* backendTypeName(GPUBackendType type) { + switch (type) { + case GPUBackendType::CPU: + return "CPU"; + case GPUBackendType::CUDA: + return "CUDA"; + case GPUBackendType::OpenCL: + return "OpenCL"; + case GPUBackendType::Vulkan: + return "Vulkan"; + } + return ""; +} int main() { std::cout << "=== Simple GPU Acceleration Test ===" << std::endl; - + try { // Test 1: GPU availability std::cout << "\n1. Testing GPU availability..." << std::endl; bool available = gpu_utils::isGPUAccelerationAvailable(); std::cout << "GPU acceleration available: " << (available ? "Yes" : "No") << std::endl; - + // Test 2: Get recommended config std::cout << "\n2. Getting recommended configuration..." << std::endl; GPUConfig config = gpu_utils::getRecommendedGPUConfig(); std::cout << "Recommended backend: "; - switch (config.preferredBackend) { - case GPUBackendType::CPU: std::cout << "CPU"; break; - case GPUBackendType::CUDA: std::cout << "CUDA"; break; - case GPUBackendType::OpenCL: std::cout << "OpenCL"; break; - case GPUBackendType::Vulkan: std::cout << "Vulkan"; break; - } + std::cout << backendTypeName(config.preferredBackend); std::cout << std::endl; - + // Test 3: Initialize GPU manager std::cout << "\n3. Initializing GPU manager..." << std::endl; auto& gpuManager = SimpleGPUManager::getInstance(); - + if (!gpuManager.initialize(config)) { std::cerr << "Failed to initialize GPU manager" << std::endl; return 1; } - + std::cout << "GPU manager initialized successfully!" << std::endl; - + // Test 4: Device detection std::cout << "\n4. Detecting available devices..." << std::endl; auto devices = gpuManager.detectAvailableDevices(); std::cout << "Found " << devices.size() << " device(s):" << std::endl; - + for (size_t i = 0; i < devices.size(); i++) { const auto& device = devices[i]; std::cout << " Device " << i << ": " << device.name << std::endl; std::cout << " Description: " << device.description << std::endl; std::cout << " Available: " << (device.isAvailable ? "Yes" : "No") << std::endl; } - + // Test 5: Current device info std::cout << "\n5. Current device information..." << std::endl; auto currentDevice = gpuManager.getCurrentDevice(); std::cout << "Current device: " << currentDevice.name << std::endl; std::cout << "Backend type: "; - switch (gpuManager.getCurrentBackendType()) { - case GPUBackendType::CPU: std::cout << "CPU"; break; - case GPUBackendType::CUDA: std::cout << "CUDA"; break; - case GPUBackendType::OpenCL: std::cout << "OpenCL"; break; - case GPUBackendType::Vulkan: std::cout << "Vulkan"; break; - } + std::cout << backendTypeName(gpuManager.getCurrentBackendType()); std::cout << std::endl; - + // Test 6: GPU-accelerated model std::cout << "\n6. Testing GPU-accelerated model..." << std::endl; std::string mockModelPath = "/tmp/test_model.gguf"; SimpleGPUModel model(mockModelPath, config); - + std::cout << "Model created successfully!" << std::endl; std::cout << "GPU accelerated: " << (model.isGPUAccelerated() ? "Yes" : "No") << std::endl; std::cout << "Model loaded: " << (model.isLoaded() ? "Yes" : "No") << std::endl; - + // Test 7: Text generation std::cout << "\n7. Testing text generation..." << std::endl; std::string prompt = "Hello, this is a test"; auto startTime = std::chrono::high_resolution_clock::now(); std::string response = model.generate(prompt, 50); auto endTime = std::chrono::high_resolution_clock::now(); - + auto duration = std::chrono::duration_cast(endTime - startTime); std::cout << "Prompt: " << prompt << std::endl; std::cout << "Response: " << response << std::endl; std::cout << "Generation time: " << duration.count() << " ms" << std::endl; - + // Test 8: Embedding generation std::cout << "\n8. Testing embedding generation..." << std::endl; auto embedding = model.generateEmbedding("Test input text"); @@ -262,49 +259,43 @@ int main() { } std::cout << "..." << std::endl; } - + // Test 9: Backend benchmarking std::cout << "\n9. Benchmarking backends..." << std::endl; GPUBackendType bestBackend = gpu_utils::benchmarkGPUBackends(); std::cout << "Best backend: "; - switch (bestBackend) { - case GPUBackendType::CPU: std::cout << "CPU"; break; - case GPUBackendType::CUDA: std::cout << "CUDA"; break; - case GPUBackendType::OpenCL: std::cout << "OpenCL"; break; - case GPUBackendType::Vulkan: std::cout << "Vulkan"; break; - } + std::cout << backendTypeName(bestBackend); std::cout << std::endl; - + // Test 10: Cleanup std::cout << "\n10. Cleaning up..." << std::endl; gpuManager.shutdown(); - + std::cout << "\n=== Simple GPU Acceleration Test Complete ===" << std::endl; std::cout << "✅ All tests passed! GPU acceleration framework is working correctly." << std::endl; - + // Test GGML backend directly std::cout << "\n=== GGML Backend Test ===" << std::endl; - + // Test CPU backend directly auto cpu_backend = ggml_backend_cpu_init(); if (cpu_backend) { std::cout << "✅ GGML CPU backend initialized successfully" << std::endl; - + auto buffer_type = ggml_backend_cpu_buffer_type(); if (buffer_type) { std::cout << "✅ GGML CPU buffer type obtained successfully" << std::endl; } - + ggml_backend_free(cpu_backend); std::cout << "✅ GGML CPU backend freed successfully" << std::endl; } else { std::cout << "❌ Failed to initialize GGML CPU backend" << std::endl; } - } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; return 1; } - + return 0; -} \ No newline at end of file +} diff --git a/test_gpu_standalone.cpp b/test_gpu_standalone.cpp index 99e77d77..2f35f5db 100644 --- a/test_gpu_standalone.cpp +++ b/test_gpu_standalone.cpp @@ -1,6 +1,6 @@ +#include #include #include -#include // Simple test that directly includes our GPU acceleration without dependencies #define BOLT_HAVE_LOGGING_SIMPLE 1 @@ -12,91 +12,90 @@ #include "include/bolt/ai/gpu_acceleration.hpp" -using namespace bolt::ai; +using namespace bolt::ai; // NOLINT(build/namespaces) + +// Returns the display name of a GPU backend type. +static const char* backendTypeName(GPUBackendType type) { + switch (type) { + case GPUBackendType::CUDA: + return "CUDA"; + case GPUBackendType::OpenCL: + return "OpenCL"; + case GPUBackendType::Vulkan: + return "Vulkan"; + case GPUBackendType::CPU: + return "CPU"; + default: + return "Unknown"; + } +} int main() { std::cout << "=== Standalone GPU Acceleration Test ===" << std::endl; - + // Test GPU utility functions std::cout << "\n1. Testing GPU utility functions..." << std::endl; - + bool gpuAvailable = gpu_utils::isGPUAccelerationAvailable(); std::cout << "GPU acceleration available: " << (gpuAvailable ? "Yes" : "No") << std::endl; - + GPUConfig recommendedConfig = gpu_utils::getRecommendedGPUConfig(); std::cout << "Recommended backend: "; - switch (recommendedConfig.preferredBackend) { - case GPUBackendType::CUDA: std::cout << "CUDA"; break; - case GPUBackendType::OpenCL: std::cout << "OpenCL"; break; - case GPUBackendType::Vulkan: std::cout << "Vulkan"; break; - case GPUBackendType::CPU: std::cout << "CPU"; break; - default: std::cout << "Unknown"; break; - } + std::cout << backendTypeName(recommendedConfig.preferredBackend); std::cout << std::endl; - + // Test GPU manager initialization std::cout << "\n2. Testing GPU manager initialization..." << std::endl; - + auto& gpuManager = GPUAccelerationManager::getInstance(); - + if (!gpuManager.initialize(recommendedConfig)) { std::cerr << "Failed to initialize GPU manager" << std::endl; return 1; } - + std::cout << "GPU manager initialized successfully!" << std::endl; - + // Test device detection std::cout << "\n3. Testing device detection..." << std::endl; - + auto devices = gpuManager.detectAvailableDevices(); std::cout << "Found " << devices.size() << " device(s):" << std::endl; - + for (size_t i = 0; i < devices.size(); i++) { const auto& device = devices[i]; std::cout << " Device " << i << ": " << device.name << std::endl; std::cout << " Type: "; - switch (device.backendType) { - case GPUBackendType::CUDA: std::cout << "CUDA"; break; - case GPUBackendType::OpenCL: std::cout << "OpenCL"; break; - case GPUBackendType::Vulkan: std::cout << "Vulkan"; break; - case GPUBackendType::CPU: std::cout << "CPU"; break; - default: std::cout << "Unknown"; break; - } + std::cout << backendTypeName(device.backendType); std::cout << std::endl; std::cout << " Available: " << (device.isAvailable ? "Yes" : "No") << std::endl; if (device.totalMemory > 0) { std::cout << " Total Memory: " << (device.totalMemory / (1024 * 1024)) << " MB" << std::endl; } } - + // Test current device std::cout << "\n4. Testing current device info..." << std::endl; auto currentDevice = gpuManager.getCurrentDevice(); std::cout << "Current device: " << currentDevice.name << std::endl; std::cout << "Backend type: "; - switch (gpuManager.getCurrentBackendType()) { - case GPUBackendType::CUDA: std::cout << "CUDA"; break; - case GPUBackendType::OpenCL: std::cout << "OpenCL"; break; - case GPUBackendType::Vulkan: std::cout << "Vulkan"; break; - case GPUBackendType::CPU: std::cout << "CPU"; break; - default: std::cout << "Unknown"; break; - } + std::cout << backendTypeName(gpuManager.getCurrentBackendType()); std::cout << std::endl; - + // Test memory management std::cout << "\n5. Testing memory management..." << std::endl; if (gpuManager.isInitialized()) { auto& memManager = gpuManager.getMemoryManager(); std::cout << "Used GPU memory: " << (memManager.getUsedMemory() / (1024 * 1024)) << " MB" << std::endl; - std::cout << "Available GPU memory: " << (memManager.getAvailableMemory() / (1024 * 1024)) << " MB" << std::endl; - + std::cout << "Available GPU memory: " << (memManager.getAvailableMemory() / (1024 * 1024)) << " MB" + << std::endl; + // Test memory operations memManager.optimizeMemoryUsage(); memManager.defragmentMemory(); std::cout << "Memory management operations completed successfully!" << std::endl; } - + // Test performance stats std::cout << "\n6. Testing performance monitoring..." << std::endl; auto stats = gpuManager.getPerformanceStats(); @@ -104,72 +103,66 @@ int main() { std::cout << " Total compute operations: " << stats.totalComputeOps << std::endl; std::cout << " Total compute time: " << stats.totalComputeTime << " seconds" << std::endl; std::cout << " Total memory transfers: " << stats.totalMemoryTransfers << std::endl; - + gpuManager.resetPerformanceStats(); auto resetStats = gpuManager.getPerformanceStats(); std::cout << "After reset - Total compute operations: " << resetStats.totalComputeOps << std::endl; - + // Test GPU-accelerated model (basic test) std::cout << "\n7. Testing GPU-accelerated model..." << std::endl; try { GPUConfig modelConfig; - modelConfig.preferredBackend = GPUBackendType::CPU; // Force CPU for testing + modelConfig.preferredBackend = GPUBackendType::CPU; // Force CPU for testing modelConfig.enableAutomaticFallback = true; - + std::string mockModelPath = "/tmp/test_model.gguf"; GPUAcceleratedModel model(mockModelPath, modelConfig); - + std::cout << "Model created successfully!" << std::endl; std::cout << "GPU accelerated: " << (model.isGPUAccelerated() ? "Yes" : "No") << std::endl; std::cout << "Model loaded: " << (model.isLoaded() ? "Yes" : "No") << std::endl; - + // Test configuration model.setMaxContextSize(1024); model.setThreadCount(2); model.enableGPUOffloading(true); std::cout << "Model configuration updated successfully!" << std::endl; - + // Test generation (will return empty since model is not loaded) std::string result = model.generate("test prompt", 10); std::cout << "Generation test completed (result length: " << result.length() << ")" << std::endl; - + // Test embedding (will return empty since model is not loaded) auto embedding = model.generateEmbedding("test input"); std::cout << "Embedding test completed (dimension: " << embedding.size() << ")" << std::endl; - } catch (const std::exception& e) { std::cout << "Model test completed with expected behavior: " << e.what() << std::endl; } - + // Test configuration management std::cout << "\n8. Testing configuration management..." << std::endl; GPUConfig newConfig = recommendedConfig; newConfig.enableMemoryOptimization = false; gpuManager.updateConfig(newConfig); - + auto retrievedConfig = gpuManager.getConfig(); - std::cout << "Memory optimization: " << (retrievedConfig.enableMemoryOptimization ? "Enabled" : "Disabled") << std::endl; - + std::cout << "Memory optimization: " << (retrievedConfig.enableMemoryOptimization ? "Enabled" : "Disabled") + << std::endl; + // Test backend benchmarking std::cout << "\n9. Testing backend benchmarking..." << std::endl; GPUBackendType bestBackend = gpu_utils::benchmarkGPUBackends(); std::cout << "Best backend: "; - switch (bestBackend) { - case GPUBackendType::CUDA: std::cout << "CUDA"; break; - case GPUBackendType::OpenCL: std::cout << "OpenCL"; break; - case GPUBackendType::Vulkan: std::cout << "Vulkan"; break; - case GPUBackendType::CPU: std::cout << "CPU"; break; - default: std::cout << "Unknown"; break; - } + std::cout << backendTypeName(bestBackend); std::cout << std::endl; - + // Cleanup std::cout << "\n10. Cleaning up..." << std::endl; gpuManager.shutdown(); std::cout << "GPU manager shut down successfully!" << std::endl; - + std::cout << "\n=== Standalone GPU Acceleration Test Complete ===" << std::endl; std::cout << "✅ All tests passed! GPU acceleration is working correctly." << std::endl; - + return 0; -} \ No newline at end of file +} diff --git a/test_performance_profiler.cpp b/test_performance_profiler.cpp index 00da7eef..3e73b791 100644 --- a/test_performance_profiler.cpp +++ b/test_performance_profiler.cpp @@ -1,22 +1,24 @@ -#include "bolt/core/performance_profiler.hpp" -#include "bolt/core/error_handling.hpp" -#include -#include -#include #include +#include #include #include +#include +#include +#include + +#include "bolt/core/error_handling.hpp" +#include "bolt/core/performance_profiler.hpp" // Simple test framework (using existing pattern from other tests) #define BOLT_TEST(category, name) void test_##category##_##name() -#define BOLT_ASSERT_TRUE(condition) \ - do { \ - if (!(condition)) { \ +#define BOLT_ASSERT_TRUE(condition) \ + do { \ + if (!(condition)) { \ std::cerr << "Assertion failed: " #condition << " at " << __FILE__ << ":" << __LINE__ << std::endl; \ - throw std::runtime_error("Test assertion failed"); \ - } \ - } while(0) + throw std::runtime_error("Test assertion failed"); \ + } \ + } while (0) #define BOLT_ASSERT_FALSE(condition) BOLT_ASSERT_TRUE(!(condition)) #define BOLT_ASSERT_EQ(a, b) BOLT_ASSERT_TRUE((a) == (b)) @@ -39,20 +41,20 @@ BOLT_TEST(Profiler, BasicMetricTiming) { auto& profiler = bolt::PerformanceProfiler::getInstance(); profiler.reset(); profiler.enable(); - + auto metric = profiler.startMetric("test_metric", "TEST"); BOLT_ASSERT_NOT_NULL(metric); - - const int workDuration = 50; // 50ms + + const int workDuration = 50; // 50ms simulateWork(workDuration); - + profiler.endMetric(metric); - + // Check that the timing is approximately correct (within 20ms tolerance) double actualDuration = metric->getDurationMs(); BOLT_ASSERT_TRUE(actualDuration >= workDuration); - BOLT_ASSERT_TRUE(actualDuration < workDuration + 20); // Allow some overhead - + BOLT_ASSERT_TRUE(actualDuration < workDuration + 20); // Allow some overhead + BOLT_ASSERT_EQ(metric->name, "test_metric"); BOLT_ASSERT_EQ(metric->category, "TEST"); } @@ -61,21 +63,21 @@ BOLT_TEST(Profiler, ScopedProfiling) { auto& profiler = bolt::PerformanceProfiler::getInstance(); profiler.reset(); profiler.enable(); - + const int workDuration = 30; auto startCount = profiler.getTotalMetricsCount(); - + { bolt::ScopedProfiler scoped("scoped_test", "SCOPE"); simulateWork(workDuration); - + // Test current duration while still active double currentDuration = scoped.getCurrentDurationMs(); BOLT_ASSERT_TRUE(currentDuration >= workDuration - 5); - + scoped.addMetadata("test_key", "test_value"); - } // ScopedProfiler destructor should record the metric - + } // ScopedProfiler destructor should record the metric + auto endCount = profiler.getTotalMetricsCount(); BOLT_ASSERT_EQ(endCount, startCount + 1); } @@ -84,11 +86,11 @@ BOLT_TEST(Profiler, InstantMetrics) { auto& profiler = bolt::PerformanceProfiler::getInstance(); profiler.reset(); profiler.enable(); - + auto startCount = profiler.getTotalMetricsCount(); - + profiler.recordInstantMetric("instant_test", 42.5, "INSTANT"); - + auto endCount = profiler.getTotalMetricsCount(); BOLT_ASSERT_EQ(endCount, startCount + 1); } @@ -99,26 +101,26 @@ BOLT_TEST(Profiler, SessionCreationAndManagement) { auto& profiler = bolt::PerformanceProfiler::getInstance(); profiler.reset(); profiler.enable(); - + // Create a session auto session = profiler.createSession("test_session"); BOLT_ASSERT_NOT_NULL(session); BOLT_ASSERT_TRUE(session->isActive()); BOLT_ASSERT_EQ(session->getName(), "test_session"); - + // Set as current session profiler.setCurrentSession("test_session"); auto currentSession = profiler.getCurrentSession(); BOLT_ASSERT_EQ(currentSession, session); - + // Add metrics to session { bolt::ScopedProfiler scoped("session_metric", "SESSION"); simulateWork(10); } - + BOLT_ASSERT_EQ(session->getMetricsCount(), 1); - + // End session profiler.endSession("test_session"); BOLT_ASSERT_FALSE(session->isActive()); @@ -128,27 +130,27 @@ BOLT_TEST(Profiler, SessionStatistics) { auto& profiler = bolt::PerformanceProfiler::getInstance(); profiler.reset(); profiler.enable(); - + auto session = profiler.createSession("stats_session"); profiler.setCurrentSession("stats_session"); - + // Add multiple metrics with different durations const std::vector durations = {10, 20, 30, 40, 50}; for (size_t i = 0; i < durations.size(); ++i) { bolt::ScopedProfiler scoped("metric_" + std::to_string(i), "STATS"); simulateWork(durations[i]); } - + BOLT_ASSERT_EQ(session->getMetricsCount(), durations.size()); - + // Check statistics double avgDuration = session->getAverageDurationMs(); double minDuration = session->getMinDurationMs(); double maxDuration = session->getMaxDurationMs(); - - BOLT_ASSERT_TRUE(avgDuration >= 25 && avgDuration <= 35); // Should be around 30ms - BOLT_ASSERT_TRUE(minDuration >= 8); // Should be around 10ms - BOLT_ASSERT_TRUE(maxDuration >= 45); // Should be around 50ms + + BOLT_ASSERT_TRUE(avgDuration >= 25 && avgDuration <= 35); // Should be around 30ms + BOLT_ASSERT_TRUE(minDuration >= 8); // Should be around 10ms + BOLT_ASSERT_TRUE(maxDuration >= 45); // Should be around 50ms BOLT_ASSERT_TRUE(minDuration < maxDuration); } @@ -158,33 +160,33 @@ BOLT_TEST(Profiler, ConvenienceMacros) { auto& profiler = bolt::PerformanceProfiler::getInstance(); profiler.reset(); profiler.enable(); - + auto startCount = profiler.getTotalMetricsCount(); - + // Test function profiling macro auto testFunction = []() { BOLT_PROFILE_FUNCTION(); simulateWork(10); }; testFunction(); - + // Test scope profiling macro { BOLT_PROFILE_SCOPE("test_scope"); simulateWork(10); } - + // Test category-specific macros { BOLT_PROFILE_CORE("core_operation"); simulateWork(5); } - + { BOLT_PROFILE_AI("ai_inference"); simulateWork(5); } - + auto endCount = profiler.getTotalMetricsCount(); BOLT_ASSERT_EQ(endCount, startCount + 4); } @@ -193,15 +195,15 @@ BOLT_TEST(Profiler, SessionMacro) { auto& profiler = bolt::PerformanceProfiler::getInstance(); profiler.reset(); profiler.enable(); - + { BOLT_PROFILE_SESSION("macro_session"); - + { BOLT_PROFILE_SCOPE("session_work"); simulateWork(15); } - + auto currentSession = profiler.getCurrentSession(); BOLT_ASSERT_NOT_NULL(currentSession); BOLT_ASSERT_EQ(currentSession->getName(), "macro_session"); @@ -215,12 +217,12 @@ BOLT_TEST(Profiler, ThreadSafety) { auto& profiler = bolt::PerformanceProfiler::getInstance(); profiler.reset(); profiler.enable(); - + const int numThreads = 4; const int metricsPerThread = 10; - + std::vector threads; - + for (int t = 0; t < numThreads; ++t) { threads.emplace_back([&profiler, t, metricsPerThread]() { for (int i = 0; i < metricsPerThread; ++i) { @@ -229,11 +231,11 @@ BOLT_TEST(Profiler, ThreadSafety) { } }); } - + for (auto& thread : threads) { thread.join(); } - + size_t totalMetrics = profiler.getTotalMetricsCount(); BOLT_ASSERT_EQ(totalMetrics, numThreads * metricsPerThread); } @@ -242,35 +244,35 @@ BOLT_TEST(Profiler, ConcurrentSessions) { auto& profiler = bolt::PerformanceProfiler::getInstance(); profiler.reset(); profiler.enable(); - + const int numThreads = 3; std::vector threads; - + for (int t = 0; t < numThreads; ++t) { threads.emplace_back([&profiler, t]() { std::string sessionName = "concurrent_session_" + std::to_string(t); auto session = profiler.createSession(sessionName); profiler.setCurrentSession(sessionName); - + for (int i = 0; i < 5; ++i) { bolt::ScopedProfiler scoped("concurrent_metric_" + std::to_string(i), "CONCURRENT"); simulateWork(10); } - + profiler.endSession(sessionName); }); } - + for (auto& thread : threads) { thread.join(); } - + // Each thread should have created a session with 5 metrics for (int t = 0; t < numThreads; ++t) { std::string sessionName = "concurrent_session_" + std::to_string(t); auto session = profiler.getSession(sessionName); BOLT_ASSERT_NOT_NULL(session); - + // Debug output in case of failure size_t actualCount = session->getMetricsCount(); if (actualCount != 5) { @@ -282,37 +284,42 @@ BOLT_TEST(Profiler, ConcurrentSessions) { // ===== Data Export Tests ===== +// Asserts that an exported file can be opened and returns its content. +static std::string readExportedFile(const std::string& filename) { + std::ifstream file(filename); + BOLT_ASSERT_TRUE(file.is_open()); + + std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); + file.close(); + return content; +} + BOLT_TEST(Profiler, JsonExport) { auto& profiler = bolt::PerformanceProfiler::getInstance(); profiler.reset(); profiler.enable(); - + // Create some test data auto session = profiler.createSession("export_session"); profiler.setCurrentSession("export_session"); - + { BOLT_PROFILE_SCOPE("export_test"); simulateWork(10); } - + profiler.endSession("export_session"); - + // Add a global metric profiler.recordInstantMetric("global_metric", 25.5, "GLOBAL"); - + // Export to JSON const std::string filename = "/tmp/profiler_test_export.json"; profiler.exportToJson(filename); - + // Verify file was created and has content - std::ifstream file(filename); - BOLT_ASSERT_TRUE(file.is_open()); - - std::string content((std::istreambuf_iterator(file)), - std::istreambuf_iterator()); - file.close(); - + std::string content = readExportedFile(filename); + BOLT_ASSERT_TRUE(content.find("export_session") != std::string::npos); BOLT_ASSERT_TRUE(content.find("export_test") != std::string::npos); BOLT_ASSERT_TRUE(content.find("global_metric") != std::string::npos); @@ -323,30 +330,25 @@ BOLT_TEST(Profiler, CsvExport) { auto& profiler = bolt::PerformanceProfiler::getInstance(); profiler.reset(); profiler.enable(); - + // Create test data auto session = profiler.createSession("csv_session"); profiler.setCurrentSession("csv_session"); - + { BOLT_PROFILE_SCOPE("csv_test"); simulateWork(5); } - + profiler.endSession("csv_session"); - + // Export to CSV const std::string filename = "/tmp/profiler_test_export.csv"; profiler.exportToCsv(filename); - + // Verify file was created and has content - std::ifstream file(filename); - BOLT_ASSERT_TRUE(file.is_open()); - - std::string content((std::istreambuf_iterator(file)), - std::istreambuf_iterator()); - file.close(); - + std::string content = readExportedFile(filename); + BOLT_ASSERT_TRUE(content.find("Session,Name,Category,Duration(ms),MemoryUsage(bytes)") != std::string::npos); BOLT_ASSERT_TRUE(content.find("csv_session") != std::string::npos); BOLT_ASSERT_TRUE(content.find("csv_test") != std::string::npos); @@ -358,30 +360,30 @@ BOLT_TEST(Profiler, CategoryFiltering) { auto& profiler = bolt::PerformanceProfiler::getInstance(); profiler.reset(); profiler.enable(); - + // Create metrics in different categories { BOLT_PROFILE_CORE("core_task"); simulateWork(5); } - + { BOLT_PROFILE_AI("ai_task"); simulateWork(5); } - + { BOLT_PROFILE_MEMORY("memory_task"); simulateWork(5); } - + auto categories = profiler.getCategories(); BOLT_ASSERT_TRUE(categories.size() >= 3); - + auto coreMetrics = profiler.getMetricsByCategory("CORE"); auto aiMetrics = profiler.getMetricsByCategory("AI"); auto memoryMetrics = profiler.getMetricsByCategory("MEMORY"); - + BOLT_ASSERT_EQ(coreMetrics.size(), 1); BOLT_ASSERT_EQ(aiMetrics.size(), 1); BOLT_ASSERT_EQ(memoryMetrics.size(), 1); @@ -390,32 +392,32 @@ BOLT_TEST(Profiler, CategoryFiltering) { BOLT_TEST(Profiler, EnableDisable) { auto& profiler = bolt::PerformanceProfiler::getInstance(); profiler.reset(); - + // Test disabled state profiler.disable(); BOLT_ASSERT_FALSE(profiler.isEnabled()); - + auto startCount = profiler.getTotalMetricsCount(); - + { BOLT_PROFILE_SCOPE("disabled_test"); simulateWork(10); } - + auto endCount = profiler.getTotalMetricsCount(); - BOLT_ASSERT_EQ(endCount, startCount); // No metrics should be recorded - + BOLT_ASSERT_EQ(endCount, startCount); // No metrics should be recorded + // Test enabled state profiler.enable(); BOLT_ASSERT_TRUE(profiler.isEnabled()); - + { BOLT_PROFILE_SCOPE("enabled_test"); simulateWork(10); } - + auto finalCount = profiler.getTotalMetricsCount(); - BOLT_ASSERT_EQ(finalCount, endCount + 1); // One metric should be recorded + BOLT_ASSERT_EQ(finalCount, endCount + 1); // One metric should be recorded } // ===== Performance Tests ===== @@ -424,9 +426,9 @@ BOLT_TEST(Profiler, ProfilerOverhead) { auto& profiler = bolt::PerformanceProfiler::getInstance(); profiler.reset(); profiler.enable(); - + const int numIterations = 1000; - + // Measure time without profiling auto start = std::chrono::high_resolution_clock::now(); for (int i = 0; i < numIterations; ++i) { @@ -435,7 +437,7 @@ BOLT_TEST(Profiler, ProfilerOverhead) { } auto end = std::chrono::high_resolution_clock::now(); auto baselineDuration = std::chrono::duration_cast(end - start); - + // Measure time with profiling start = std::chrono::high_resolution_clock::now(); for (int i = 0; i < numIterations; ++i) { @@ -445,17 +447,18 @@ BOLT_TEST(Profiler, ProfilerOverhead) { } end = std::chrono::high_resolution_clock::now(); auto profiledDuration = std::chrono::duration_cast(end - start); - + // Calculate overhead - double overhead = (double)(profiledDuration.count() - baselineDuration.count()) / baselineDuration.count() * 100.0; - - std::cout << "Profiler overhead: " << overhead << "% (" - << (profiledDuration.count() - baselineDuration.count()) / (double)numIterations + double overhead = + static_cast(profiledDuration.count() - baselineDuration.count()) / baselineDuration.count() * 100.0; + + std::cout << "Profiler overhead: " << overhead << "% (" + << (profiledDuration.count() - baselineDuration.count()) / static_cast(numIterations) << " μs per profiled operation)" << std::endl; - + // With more realistic work, overhead should be much more reasonable - BOLT_ASSERT_TRUE(overhead < 100.0); // Allow up to 100% overhead for this test - + BOLT_ASSERT_TRUE(overhead < 100.0); // Allow up to 100% overhead for this test + // Verify all metrics were recorded BOLT_ASSERT_EQ(profiler.getTotalMetricsCount(), numIterations); } @@ -475,49 +478,48 @@ void runTest(const std::string& name, void (*testFunc)()) { int main() { std::cout << "Bolt Performance Profiler Test Suite" << std::endl; std::cout << "====================================" << std::endl; - + try { // Initialize logging for test output bolt::LogManager::configureConsoleLogging(bolt::LogLevel::WARN, false); - + std::cout << "Testing basic functionality..." << std::endl; runTest("BasicMetricTiming", test_Profiler_BasicMetricTiming); runTest("ScopedProfiling", test_Profiler_ScopedProfiling); runTest("InstantMetrics", test_Profiler_InstantMetrics); - + std::cout << "\nTesting session management..." << std::endl; runTest("SessionCreationAndManagement", test_Profiler_SessionCreationAndManagement); runTest("SessionStatistics", test_Profiler_SessionStatistics); - + std::cout << "\nTesting convenience macros..." << std::endl; runTest("ConvenienceMacros", test_Profiler_ConvenienceMacros); runTest("SessionMacro", test_Profiler_SessionMacro); - + std::cout << "\nTesting thread safety..." << std::endl; runTest("ThreadSafety", test_Profiler_ThreadSafety); runTest("ConcurrentSessions", test_Profiler_ConcurrentSessions); - + std::cout << "\nTesting data export..." << std::endl; runTest("JsonExport", test_Profiler_JsonExport); runTest("CsvExport", test_Profiler_CsvExport); - + std::cout << "\nTesting integration features..." << std::endl; runTest("CategoryFiltering", test_Profiler_CategoryFiltering); runTest("EnableDisable", test_Profiler_EnableDisable); - + std::cout << "\nTesting performance..." << std::endl; runTest("ProfilerOverhead", test_Profiler_ProfilerOverhead); - + std::cout << "\n🎉 All performance profiler tests passed successfully!" << std::endl; - + // Demonstrate profiler summary std::cout << "\n=== Profiler Summary After Tests ===" << std::endl; bolt::PerformanceProfiler::getInstance().printSummary(); - } catch (const std::exception& e) { std::cerr << "\nTest suite failed with exception: " << e.what() << std::endl; return 1; } - + return 0; -} \ No newline at end of file +}