diff --git a/.bazelrc b/.bazelrc index 0175683..405e5e1 100644 --- a/.bazelrc +++ b/.bazelrc @@ -24,6 +24,14 @@ build:windows --nolegacy_external_runfiles # hermetic x86_64-pc-windows-gnu toolchain instead of the C++ toolchain wrapper. build:windows --@rules_rust//rust/settings:toolchain_linker_preference=rust +# Linux-specific settings +# Zig CC statically links libc++/libc++abi/libunwind into every shared library, +# duplicating C++ runtime state and breaking exception propagation across +# dynamically linked cc_library (.so) boundaries. Link cc_library targets +# statically while still linking explicit shared libraries (e.g. Rust cdylibs) +# dynamically. +build:linux --dynamic_mode=off + # Linting settings # To run linting: bazel build --config=lint //... build:lint --aspects=//tools:lint.bzl%ruff,@rules_rust//rust:defs.bzl%rust_clippy_aspect,@rules_rust//rust:defs.bzl%rustfmt_aspect diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3a97104..ae7d908 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -5,8 +5,12 @@ on: jobs: ci: - name: Continuous Testing - runs-on: ubuntu-latest + name: Continuous Testing (${{ matrix.os }}) + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest] steps: - name: Checkout repository diff --git a/MODULE.bazel b/MODULE.bazel index e722e80..50896ef 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -13,6 +13,7 @@ bazel_dep(name = "rules_python_gazelle_plugin", version = "0.37.0") bazel_dep(name = "hermetic_cc_toolchain", version = "4.1.0") bazel_dep(name = "platforms", version = "1.1.0") bazel_dep(name = "rules_rust", version = "0.75.0") +bazel_dep(name = "rules_cc", version = "0.2.17") python = use_extension("@rules_python//python/extensions:python.bzl", "python") python.toolchain( @@ -75,8 +76,19 @@ use_repo(rust, "rust_toolchains") register_toolchains("@rust_toolchains//:all") +single_version_override( + module_name = "hermetic_cc_toolchain", + patch_strip = 1, + patches = [ + "//patches:hermetic_cc_toolchain.patch", + ], +) + single_version_override( module_name = "rules_rust", patch_strip = 1, - patches = ["//patches:rules_rust_windows_gnu.patch"], + patches = [ + "//patches:rules_rust_windows_gnu.patch", + "//patches:rules_rust_cdylib_windows.patch", + ], ) diff --git a/README.md b/README.md index 7eed27a..46cdaf8 100644 --- a/README.md +++ b/README.md @@ -79,6 +79,21 @@ To run the Rust calculator example: bazel run //rs:main -- calc "2 + 3 * 4" ``` +To run the C++ calculator example: +```shell +bazel run //cc:main -- calc "2 + 3 * 4" +``` + +To run the Rust calling C++ FFI interop example: +```shell +bazel run //rs:main -- calc-cpp "2 * (3 + 4) ^ 2" +``` + +To run the C++ calling Rust FFI interop example: +```shell +bazel run //cc:main -- calc-rs "2 * (3 + 4) ^ 2" +``` + To format Bazel files: ```shell buildifier BUILD.bazel diff --git a/cc/BUILD.bazel b/cc/BUILD.bazel new file mode 100644 index 0000000..32e9ac0 --- /dev/null +++ b/cc/BUILD.bazel @@ -0,0 +1,56 @@ +load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library", "cc_test") + +cc_library( + name = "calculator", + srcs = ["calculator.cc"], + hdrs = ["calculator.hh"], + copts = [ + "-fno-exceptions", + "-fno-rtti", + ], + visibility = ["//visibility:public"], +) + +cc_library( + name = "rust_calculator", + srcs = ["rust_calculator.cc"], + hdrs = ["rust_calculator.hh"], + visibility = ["//visibility:public"], + deps = ["//rs:rust_calculator"], +) + +cc_binary( + name = "main", + srcs = ["main.cc"], + env = select({ + "@platforms//os:windows": { + "PATH": "rs;.", + }, + "//conditions:default": {}, + }), + visibility = ["//visibility:public"], + deps = [ + ":calculator", + ":rust_calculator", + ], +) + +cc_test( + name = "calculator_test", + srcs = ["calculator_test.cc"], + deps = [":calculator"], +) + +cc_test( + name = "rust_calculator_test", + srcs = ["rust_calculator_test.cc"], + env = select({ + "@platforms//os:windows": { + "PATH": "rs;.", + }, + "//conditions:default": {}, + }), + deps = [ + ":rust_calculator", + ], +) diff --git a/cc/calculator.cc b/cc/calculator.cc new file mode 100644 index 0000000..bd8956a --- /dev/null +++ b/cc/calculator.cc @@ -0,0 +1,269 @@ +#include "cc/calculator.hh" + +#include +#include +#include +#include +#include +#include +#include + +namespace calculator { +namespace { + +enum class TokenType { + Number, + Plus, + Minus, + Star, + Slash, + Power, + LParen, + RParen, + Invalid, + End +}; + +struct Token { + TokenType type; + double value{0.0}; +}; + +class Lexer { +public: + explicit Lexer(std::string_view input) : input_(input), pos_(0) {} + + Token next_token() { + skip_whitespace(); + if (pos_ >= input_.size()) { + return {TokenType::End, 0.0}; + } + + char c = input_[pos_]; + if (std::isdigit(static_cast(c)) || c == '.') { + const char* start_ptr = input_.data() + pos_; + char* end_ptr = nullptr; + double val = std::strtod(start_ptr, &end_ptr); + if (end_ptr == start_ptr) { + pos_++; + return {TokenType::Invalid, 0.0}; + } + pos_ += static_cast(end_ptr - start_ptr); + return {TokenType::Number, val}; + } + + pos_++; + switch (c) { + case '+': return {TokenType::Plus, 0.0}; + case '-': return {TokenType::Minus, 0.0}; + case '*': + if (pos_ < input_.size() && input_[pos_] == '*') { + pos_++; + return {TokenType::Power, 0.0}; + } + return {TokenType::Star, 0.0}; + case '/': return {TokenType::Slash, 0.0}; + case '^': return {TokenType::Power, 0.0}; + case '(': return {TokenType::LParen, 0.0}; + case ')': return {TokenType::RParen, 0.0}; + default: return {TokenType::Invalid, 0.0}; + } + } + +private: + void skip_whitespace() { + while (pos_ < input_.size() && std::isspace(static_cast(input_[pos_]))) { + pos_++; + } + } + + std::string_view input_; + size_t pos_; +}; + +class Parser { +public: + explicit Parser(std::string_view input) : lexer_(input), error_code_(0), error_msg_(nullptr) { + advance(); + } + + bool parse(double* out_result) { + if (current_token_.type == TokenType::End) { + set_error(3, "empty expression"); + return false; + } + double res = expression(); + if (error_code_ != 0) { + return false; + } + if (current_token_.type != TokenType::End) { + set_error(4, "trailing unparsed tokens"); + return false; + } + if (out_result) { + *out_result = res; + } + return true; + } + + int32_t error_code() const { return error_code_; } + const char* error_msg() const { return error_msg_ ? error_msg_ : ""; } + +private: + void set_error(int32_t code, const char* msg) { + if (error_code_ == 0) { + error_code_ = code; + error_msg_ = msg; + } + } + + void advance() { + current_token_ = lexer_.next_token(); + } + + double expression() { + double result = term(); + if (error_code_ != 0) return 0.0; + while (current_token_.type == TokenType::Plus || current_token_.type == TokenType::Minus) { + bool is_plus = (current_token_.type == TokenType::Plus); + advance(); + double rhs = term(); + if (error_code_ != 0) return 0.0; + if (is_plus) { + result += rhs; + } else { + result -= rhs; + } + } + return result; + } + + double term() { + double result = unary(); + if (error_code_ != 0) return 0.0; + while (current_token_.type == TokenType::Star || current_token_.type == TokenType::Slash) { + bool is_mul = (current_token_.type == TokenType::Star); + advance(); + double rhs = unary(); + if (error_code_ != 0) return 0.0; + if (is_mul) { + result *= rhs; + } else { + if (rhs == 0.0) { + set_error(1, "division by zero"); + return 0.0; + } + result /= rhs; + } + } + return result; + } + + double unary() { + if (current_token_.type == TokenType::Plus) { + advance(); + return unary(); + } + if (current_token_.type == TokenType::Minus) { + advance(); + return -unary(); + } + return power(); + } + + double power() { + double base = primary(); + if (error_code_ != 0) return 0.0; + if (current_token_.type == TokenType::Power) { + advance(); + double exponent = unary(); + if (error_code_ != 0) return 0.0; + return std::pow(base, exponent); + } + return base; + } + + double primary() { + if (current_token_.type == TokenType::Number) { + double val = current_token_.value; + advance(); + return val; + } + if (current_token_.type == TokenType::LParen) { + advance(); + double result = expression(); + if (error_code_ != 0) return 0.0; + if (current_token_.type != TokenType::RParen) { + set_error(2, "invalid syntax"); + return 0.0; + } + advance(); + return result; + } + set_error(2, "invalid syntax"); + return 0.0; + } + + Lexer lexer_; + Token current_token_; + int32_t error_code_; + const char* error_msg_; +}; + +} // namespace + +double evaluate_expression(std::string_view expr) { + Parser parser(expr); + double result = 0.0; + if (!parser.parse(&result)) { + return 0.0; + } + return result; +} + +} // namespace calculator + +extern "C" { + +int32_t cc_calculator_eval( + const char* expr, + double* out_result, + char* err_buf, + size_t err_buf_len +) { + if (!expr || !out_result) { + if (err_buf && err_buf_len > 0) { + std::strncpy(err_buf, "null pointer argument", err_buf_len - 1); + err_buf[err_buf_len - 1] = '\0'; + } + return -1; + } + + calculator::Parser parser(expr); + if (!parser.parse(out_result)) { + if (err_buf && err_buf_len > 0) { + std::strncpy(err_buf, parser.error_msg(), err_buf_len - 1); + err_buf[err_buf_len - 1] = '\0'; + } + return parser.error_code(); + } + + if (err_buf && err_buf_len > 0) { + err_buf[0] = '\0'; + } + return 0; +} + +int32_t cc_calculator_add(int32_t a, int32_t b) { + return a + b; +} + +double cc_calculator_pow(double base, double exp) { + return std::pow(base, exp); +} + +const char* cc_calculator_version(void) { + return "1.0.0-cpp"; +} + +} // extern "C" diff --git a/cc/calculator.hh b/cc/calculator.hh new file mode 100644 index 0000000..38ba8dc --- /dev/null +++ b/cc/calculator.hh @@ -0,0 +1,53 @@ +#pragma once + +#include +#include + +#ifdef __cplusplus +#include +#include + +namespace calculator { + +/// Evaluates a mathematical string expression in C++. +/// Supported operators: +, -, *, /, ^ and ** (power), and parentheses. +/// Throws std::runtime_error on invalid syntax, empty expression, or division by zero. +double evaluate_expression(std::string_view expr); + +} // namespace calculator +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/// C-compatible FFI interface for evaluating expressions. +/// +/// Returns 0 on success, or a non-zero error code: +/// 1: Division by zero +/// 2: Invalid syntax +/// 3: Empty expression +/// 4: Trailing tokens +/// -1: Unexpected internal error or null pointer +/// +/// On success, *out_result contains the evaluated double. +/// If err_buf is non-null and err_buf_len > 0, an error description is written. +int32_t cc_calculator_eval( + const char* expr, + double* out_result, + char* err_buf, + size_t err_buf_len +); + +/// Adds two 32-bit integers via C++ implementation. +int32_t cc_calculator_add(int32_t a, int32_t b); + +/// Computes base raised to exp via C++ implementation. +double cc_calculator_pow(double base, double exp); + +/// Returns the C++ calculator engine version string. +const char* cc_calculator_version(void); + +#ifdef __cplusplus +} +#endif diff --git a/cc/calculator_test.cc b/cc/calculator_test.cc new file mode 100644 index 0000000..1ffc3ac --- /dev/null +++ b/cc/calculator_test.cc @@ -0,0 +1,75 @@ +#include "cc/calculator.hh" + +#include +#include +#include +#include + +void test_basic_operations() { + assert(calculator::evaluate_expression("2 + 2") == 4.0); + assert(calculator::evaluate_expression("5 - 3") == 2.0); + assert(calculator::evaluate_expression("4 * 3") == 12.0); + assert(calculator::evaluate_expression("10 / 2") == 5.0); +} + +void test_operator_precedence() { + assert(calculator::evaluate_expression("2 + 3 * 4") == 14.0); + assert(calculator::evaluate_expression("(2 + 3) * 4") == 20.0); +} + +void test_power_operations() { + assert(calculator::evaluate_expression("2 ** 3") == 8.0); + assert(calculator::evaluate_expression("2 ^ 3") == 8.0); +} + +void test_unary_operations() { + assert(calculator::evaluate_expression("-5 + 3") == -2.0); + assert(calculator::evaluate_expression("-(3 * 2)") == -6.0); +} + +void test_float_parsing() { + assert(calculator::evaluate_expression("2.5 * 4") == 10.0); +} + +void test_ffi_functions() { + double result = 0.0; + char err[64] = {0}; + + // Successful evaluation + int32_t status = cc_calculator_eval("3 * (4 + 5)", &result, err, sizeof(err)); + assert(status == 0); + assert(result == 27.0); + assert(err[0] == '\0'); + + // Division by zero + status = cc_calculator_eval("8 / 0", &result, err, sizeof(err)); + assert(status == 1); + assert(std::strcmp(err, "division by zero") == 0); + + // Invalid syntax + status = cc_calculator_eval("1 ++ 2 *", &result, err, sizeof(err)); + assert(status == 2); + assert(std::strcmp(err, "invalid syntax") == 0); + + // Empty expression + status = cc_calculator_eval(" ", &result, err, sizeof(err)); + assert(status == 3); + assert(std::strcmp(err, "empty expression") == 0); + + // Direct helper functions + assert(cc_calculator_add(10, 32) == 42); + assert(cc_calculator_pow(3.0, 3.0) == 27.0); + assert(std::strcmp(cc_calculator_version(), "1.0.0-cpp") == 0); +} + +int main() { + test_basic_operations(); + test_operator_precedence(); + test_power_operations(); + test_unary_operations(); + test_float_parsing(); + test_ffi_functions(); + + std::cout << "All C++ calculator tests passed successfully!" << std::endl; + return 0; +} diff --git a/cc/main.cc b/cc/main.cc new file mode 100644 index 0000000..f440ca3 --- /dev/null +++ b/cc/main.cc @@ -0,0 +1,68 @@ +#include "cc/calculator.hh" +#include "cc/rust_calculator.hh" + +#include +#include +#include + +void print_usage() { + std::cout << "Usage: main [arguments]\n" + << "Commands:\n" + << " info Display information about the C++ environment.\n" + << " calc Evaluate a mathematical expression using C++ engine.\n" + << " calc-rs Evaluate a mathematical expression using Rust FFI engine.\n"; +} + +int main(int argc, char* argv[]) { + if (argc < 2) { + print_usage(); + return 1; + } + + std::string_view command = argv[1]; + if (command == "info") { + std::cout << "C++ Standard: " << __cplusplus << "\n" + << "Engine Version: " << cc_calculator_version() << "\n" + << "Rust Interop Engine Version: " << rust_interop::version() << "\n" + << "Bazel hermetic C++ toolchain is working!\n"; + return 0; + } + + if (command == "calc") { + if (argc < 3) { + std::cerr << "Error: calc command requires a mathematical expression.\n"; + return 1; + } + std::string expression = argv[2]; + double result = 0.0; + char err_buf[256] = {0}; + int32_t status = cc_calculator_eval(expression.c_str(), &result, err_buf, sizeof(err_buf)); + if (status == 0) { + std::cout << expression << " = " << result << "\n"; + return 0; + } else { + std::cerr << "Error: " << (err_buf[0] != '\0' ? err_buf : "evaluation failed") << "\n"; + return 1; + } + } + + if (command == "calc-rs") { + if (argc < 3) { + std::cerr << "Error: calc-rs command requires a mathematical expression.\n"; + return 1; + } + std::string expression = argv[2]; + try { + double result = rust_interop::evaluate_expression(expression); + std::cout << expression << " = " << result << " (via Rust engine)\n"; + return 0; + } catch (const std::exception& e) { + std::cerr << "Error: " << e.what() << "\n"; + return 1; + } + } + + std::cerr << "Error: Unknown command '" << command << "'\n"; + print_usage(); + return 1; +} diff --git a/cc/rust_calculator.cc b/cc/rust_calculator.cc new file mode 100644 index 0000000..57214ac --- /dev/null +++ b/cc/rust_calculator.cc @@ -0,0 +1,52 @@ +#include "cc/rust_calculator.hh" + +#include +#include + +extern "C" { +int32_t rs_calculator_eval( + const char* expr, + double* out_result, + char* err_buf, + size_t err_buf_len +); +int32_t rs_calculator_add(int32_t a, int32_t b); +double rs_calculator_pow(double base, double exp); +const char* rs_calculator_version(void); +} + +namespace rust_interop { + +double evaluate_expression(std::string_view expr) { + std::string null_term_expr(expr); + double result = 0.0; + char err_buf[256] = {0}; + + int32_t status = rs_calculator_eval( + null_term_expr.c_str(), + &result, + err_buf, + sizeof(err_buf) + ); + + if (status != 0) { + throw std::runtime_error(err_buf[0] != '\0' ? err_buf : "Rust evaluation failed"); + } + + return result; +} + +int32_t add(int32_t a, int32_t b) { + return rs_calculator_add(a, b); +} + +double pow(double base, double exp) { + return rs_calculator_pow(base, exp); +} + +std::string_view version() { + const char* v = rs_calculator_version(); + return v ? std::string_view(v) : "unknown"; +} + +} // namespace rust_interop diff --git a/cc/rust_calculator.hh b/cc/rust_calculator.hh new file mode 100644 index 0000000..589fb56 --- /dev/null +++ b/cc/rust_calculator.hh @@ -0,0 +1,24 @@ +#pragma once + +#include +#include +#include +#include + +namespace rust_interop { + +/// Evaluates a mathematical string expression using the hermetic Rust engine. +/// Supported operators: +, -, *, /, ^, ** and parentheses. +/// Throws std::runtime_error on failure (syntax error, division by zero, etc.). +double evaluate_expression(std::string_view expr); + +/// Adds two 32-bit integers via the Rust implementation. +int32_t add(int32_t a, int32_t b); + +/// Computes base raised to exponent via the Rust implementation. +double pow(double base, double exp); + +/// Returns the version string of the Rust calculator engine. +std::string_view version(); + +} // namespace rust_interop diff --git a/cc/rust_calculator_test.cc b/cc/rust_calculator_test.cc new file mode 100644 index 0000000..edb12fa --- /dev/null +++ b/cc/rust_calculator_test.cc @@ -0,0 +1,67 @@ +#include "cc/rust_calculator.hh" + +#include +#include +#include + +void test_basic_operations() { + assert(rust_interop::evaluate_expression("2 + 2") == 4.0); + assert(rust_interop::evaluate_expression("5 - 3") == 2.0); + assert(rust_interop::evaluate_expression("4 * 3") == 12.0); + assert(rust_interop::evaluate_expression("10 / 2") == 5.0); +} + +void test_operator_precedence() { + assert(rust_interop::evaluate_expression("2 + 3 * 4") == 14.0); + assert(rust_interop::evaluate_expression("(2 + 3) * 4") == 20.0); +} + +void test_power_operations() { + assert(rust_interop::evaluate_expression("2 ** 3") == 8.0); + assert(rust_interop::evaluate_expression("2 ^ 3") == 8.0); +} + +void test_unary_operations() { + assert(rust_interop::evaluate_expression("-5 + 3") == -2.0); + assert(rust_interop::evaluate_expression("-(3 * 2)") == -6.0); +} + +void test_division_by_zero() { + bool caught = false; + try { + rust_interop::evaluate_expression("10 / 0"); + } catch (const std::runtime_error& e) { + caught = true; + assert(std::string_view(e.what()) == "division by zero"); + } + assert(caught); +} + +void test_invalid_syntax() { + bool caught = false; + try { + rust_interop::evaluate_expression("2 + * 3"); + } catch (const std::runtime_error&) { + caught = true; + } + assert(caught); +} + +void test_direct_helpers() { + assert(rust_interop::add(15, 27) == 42); + assert(rust_interop::pow(2.0, 10.0) == 1024.0); + assert(rust_interop::version() == "1.0.0-rust"); +} + +int main() { + test_basic_operations(); + test_operator_precedence(); + test_power_operations(); + test_unary_operations(); + test_division_by_zero(); + test_invalid_syntax(); + test_direct_helpers(); + + std::cout << "All C++ calling Rust interop tests passed successfully!" << std::endl; + return 0; +} diff --git a/patches/BUILD.bazel b/patches/BUILD.bazel index 6a4b63c..6cc0f8c 100644 --- a/patches/BUILD.bazel +++ b/patches/BUILD.bazel @@ -1 +1,5 @@ -exports_files(["rules_rust_windows_gnu.patch"]) +exports_files([ + "hermetic_cc_toolchain.patch", + "rules_rust_cdylib_windows.patch", + "rules_rust_windows_gnu.patch", +]) diff --git a/patches/hermetic_cc_toolchain.patch b/patches/hermetic_cc_toolchain.patch new file mode 100644 index 0000000..d134b56 --- /dev/null +++ b/patches/hermetic_cc_toolchain.patch @@ -0,0 +1,277 @@ +diff --git a/toolchain/toolchain/defs.bzl b/toolchain/toolchain/defs.bzl +index 73cf613..9fee7da 100644 +--- a/toolchain/toolchain/defs.bzl ++++ b/toolchain/toolchain/defs.bzl +@@ -2,6 +2,10 @@ load("@hermetic_cc_toolchain//toolchain/private:defs.bzl", "target_structs") + + def declare_toolchains(configs = "", extra_target_settings = []): + for target_config in target_structs(): ++ # On macOS, bypass Zig CC toolchains and use Apple's native toolchain ++ # to support Apple-specific linker flags (-x, -oso_prefix) from Go and Rust. ++ if target_config.libc == "darwin": ++ continue + gotarget = target_config.gotarget + zigtarget = target_config.zigtarget + +@@ -18,6 +22,10 @@ def declare_toolchains(configs = "", extra_target_settings = []): + + def declare_libc_aware_toolchains(configs = "", extra_target_settings = []): + for target_config in target_structs(): ++ # On macOS, bypass Zig CC toolchains and use Apple's native toolchain ++ # to support Apple-specific linker flags (-x, -oso_prefix) from Go and Rust. ++ if target_config.libc == "darwin": ++ continue + gotarget = target_config.gotarget + zigtarget = target_config.zigtarget + +diff --git a/toolchain/zig_cc_toolchain.bzl b/toolchain/zig_cc_toolchain.bzl +index 72fa0c2..a1b2c3d 100644 +--- a/toolchain/zig_cc_toolchain.bzl ++++ b/toolchain/zig_cc_toolchain.bzl +@@ -8,6 +8,7 @@ load( + "flag_set", + "tool", + "tool_path", ++ "variable_with_value", + ) + load("@rules_cc//cc/common:cc_common.bzl", "cc_common") + load("@rules_cc//cc/toolchains:cc_toolchain_config_info.bzl", "CcToolchainConfigInfo") +@@ -161,12 +162,237 @@ def _zig_cc_toolchain_config_impl(ctx): + ], + ) + ++ dynamic_linking_features = [] ++ if ctx.attr.supports_dynamic_linker: ++ is_macos = "macos" in ctx.attr.target ++ rpath_prefix = "@loader_path" if is_macos else "$ORIGIN" ++ dynamic_linking_features.append( ++ feature( ++ name = "runtime_library_search_directories", ++ flag_sets = [ ++ flag_set( ++ actions = all_link_actions, ++ flag_groups = [ ++ flag_group( ++ iterate_over = "runtime_library_search_directories", ++ flag_groups = [ ++ flag_group( ++ flags = [ ++ "-Xlinker", ++ "-rpath", ++ "-Xlinker", ++ rpath_prefix + "/%{runtime_library_search_directories}", ++ ], ++ ), ++ ], ++ expand_if_available = "runtime_library_search_directories", ++ ), ++ ], ++ ), ++ ], ++ ), ++ ) ++ if is_macos: ++ dynamic_linking_features.append( ++ feature( ++ name = "set_install_name", ++ enabled = True, ++ flag_sets = [ ++ flag_set( ++ actions = dynamic_library_link_actions, ++ flag_groups = [ ++ flag_group( ++ expand_if_available = "runtime_solib_name", ++ flags = ["-Wl,-install_name,@rpath/%{runtime_solib_name}"], ++ ), ++ ], ++ ), ++ ], ++ ), ++ ) ++ else: ++ link_and_lto_actions = all_link_actions + [ ++ ACTION_NAMES.lto_index_for_dynamic_library, ++ ACTION_NAMES.lto_index_for_executable, ++ ACTION_NAMES.lto_index_for_nodeps_dynamic_library, ++ ] ++ dynamic_linking_features.append( ++ feature( ++ name = "soname", ++ enabled = True, ++ flag_sets = [ ++ flag_set( ++ actions = dynamic_library_link_actions, ++ flag_groups = [ ++ flag_group( ++ expand_if_available = "runtime_solib_name", ++ flags = ["-Wl,-soname,%{runtime_solib_name}"], ++ ), ++ ], ++ ), ++ ], ++ ), ++ ) ++ # Zig CC passes --as-needed by default on Linux, which drops shared ++ # libraries that are only referenced transitively by another shared ++ # library (standard in Bazel's dynamic cc_library linking model). ++ # Define libraries_to_link, user_link_flags, and legacy_link_flags ++ # immediately after no_as_needed so -Wl,--no-as-needed precedes all ++ # -l inputs (rules_cc otherwise prepends legacy features first). ++ dynamic_linking_features.append( ++ feature( ++ name = "no_as_needed", ++ enabled = True, ++ flag_sets = [ ++ flag_set( ++ actions = link_and_lto_actions, ++ flag_groups = [ ++ flag_group( ++ flags = ["-Wl,--no-as-needed"], ++ ), ++ ], ++ ), ++ ], ++ ), ++ ) ++ dynamic_linking_features.append( ++ feature( ++ name = "libraries_to_link", ++ flag_sets = [ ++ flag_set( ++ actions = link_and_lto_actions, ++ flag_groups = [ ++ flag_group( ++ expand_if_true = "thinlto_param_file", ++ flags = ["-Wl,@%{thinlto_param_file}"], ++ ), ++ flag_group( ++ expand_if_available = "libraries_to_link", ++ iterate_over = "libraries_to_link", ++ flag_groups = [ ++ flag_group( ++ expand_if_equal = variable_with_value( ++ "libraries_to_link.type", ++ "object_file_group", ++ ), ++ expand_if_false = "libraries_to_link.is_whole_archive", ++ flags = ["-Wl,--start-lib"], ++ ), ++ flag_group( ++ expand_if_true = "libraries_to_link.is_whole_archive", ++ expand_if_equal = variable_with_value( ++ "libraries_to_link.type", ++ "static_library", ++ ), ++ flags = ["-Wl,-whole-archive"], ++ ), ++ flag_group( ++ expand_if_equal = variable_with_value( ++ "libraries_to_link.type", ++ "object_file_group", ++ ), ++ iterate_over = "libraries_to_link.object_files", ++ flags = ["%{libraries_to_link.object_files}"], ++ ), ++ flag_group( ++ expand_if_equal = variable_with_value( ++ "libraries_to_link.type", ++ "object_file", ++ ), ++ flags = ["%{libraries_to_link.name}"], ++ ), ++ flag_group( ++ expand_if_equal = variable_with_value( ++ "libraries_to_link.type", ++ "interface_library", ++ ), ++ flags = ["%{libraries_to_link.name}"], ++ ), ++ flag_group( ++ expand_if_equal = variable_with_value( ++ "libraries_to_link.type", ++ "static_library", ++ ), ++ flags = ["%{libraries_to_link.name}"], ++ ), ++ flag_group( ++ expand_if_equal = variable_with_value( ++ "libraries_to_link.type", ++ "dynamic_library", ++ ), ++ flags = ["-l%{libraries_to_link.name}"], ++ ), ++ flag_group( ++ expand_if_equal = variable_with_value( ++ "libraries_to_link.type", ++ "versioned_dynamic_library", ++ ), ++ flags = ["-l:%{libraries_to_link.name}"], ++ ), ++ flag_group( ++ expand_if_true = "libraries_to_link.is_whole_archive", ++ expand_if_equal = variable_with_value( ++ "libraries_to_link.type", ++ "static_library", ++ ), ++ flags = ["-Wl,-no-whole-archive"], ++ ), ++ flag_group( ++ expand_if_equal = variable_with_value( ++ "libraries_to_link.type", ++ "object_file_group", ++ ), ++ expand_if_false = "libraries_to_link.is_whole_archive", ++ flags = ["-Wl,--end-lib"], ++ ), ++ ], ++ ), ++ ], ++ ), ++ ], ++ ), ++ ) ++ dynamic_linking_features.append( ++ feature( ++ name = "user_link_flags", ++ flag_sets = [ ++ flag_set( ++ actions = link_and_lto_actions, ++ flag_groups = [ ++ flag_group( ++ expand_if_available = "user_link_flags", ++ iterate_over = "user_link_flags", ++ flags = ["%{user_link_flags}"], ++ ), ++ ], ++ ), ++ ], ++ ), ++ ) ++ dynamic_linking_features.append( ++ feature( ++ name = "legacy_link_flags", ++ flag_sets = [ ++ flag_set( ++ actions = link_and_lto_actions, ++ flag_groups = [ ++ flag_group( ++ expand_if_available = "legacy_link_flags", ++ iterate_over = "legacy_link_flags", ++ flags = ["%{legacy_link_flags}"], ++ ), ++ ], ++ ), ++ ], ++ ), ++ ) ++ + features = [ + compile_and_link_flags, + default_linker_flags, + supports_dynamic_linker, + strip_debug_symbols_feature, +- ] + _compilation_mode_features(ctx) ++ ] + dynamic_linking_features + _compilation_mode_features(ctx) + + artifact_name_patterns = [ + artifact_name_pattern(**json.decode(p)) diff --git a/patches/rules_rust_cdylib_windows.patch b/patches/rules_rust_cdylib_windows.patch new file mode 100644 index 0000000..a88ced8 --- /dev/null +++ b/patches/rules_rust_cdylib_windows.patch @@ -0,0 +1,175 @@ +diff --git a/rust/private/rustc.bzl b/rust/private/rustc.bzl +index 72d776f..0dc0323 100644 +--- a/rust/private/rustc.bzl ++++ b/rust/private/rustc.bzl +@@ -1473,10 +1473,41 @@ def construct_arguments( + include_link_flags = include_link_flags, + ) + +- # On macOS, set the dylib install name to @rpath/ so that ++ # On macOS, set the dylib/cdylib install name to @rpath/ so that + # consumers find it via RPATH rather than the exec-root build path. +- if crate_info.type == "dylib" and toolchain.target_os in ["macos", "darwin"]: +- rustc_flags.add("--codegen=link-arg=-Wl,-install_name,@rpath/" + crate_info.output.basename) ++ if crate_info.type in ("cdylib", "dylib") and toolchain.target_os in ["macos", "darwin"]: ++ if ld_is_direct_driver: ++ rustc_flags.add("--codegen=link-arg=-install_name") ++ rustc_flags.add("--codegen=link-arg=@rpath/" + crate_info.output.basename) ++ else: ++ rustc_flags.add("--codegen=link-arg=-Wl,-install_name,@rpath/" + crate_info.output.basename) ++ ++ # On ELF platforms, set the DT_SONAME so that downstream linkers ++ # record the soname rather than the exec-root solib path. ++ if ( ++ crate_info.type in ("cdylib", "dylib") and ++ toolchain.target_os in ["linux", "android", "freebsd", "openbsd", "netbsd"] ++ ): ++ prefix = "" if ld_is_direct_driver else "-Wl," ++ rustc_flags.add("--codegen=link-arg=%s-soname=%s" % (prefix, crate_info.output.basename)) ++ ++ # On Windows GNU targets, the C runtime startup object (dllcrt2.o) provides ++ # the DLL entry point (DllMainCRTStartup on 64-bit x86_64/aarch64, or ++ # _DllMainCRTStartup@12 with stdcall name decoration on 32-bit x86), which ++ # gcc/clang drivers pass via `-e`. When invoking a direct linker driver such ++ # as `rust-lld` without gcc/clang, `ld.lld -flavor gnu` defaults to looking ++ # for `_DllMainCRTStartup` (without @12 or without matching 64-bit symbols), ++ # causing an undefined symbol error. Pass the entry point explicitly. ++ if ( ++ crate_info.type in ("cdylib", "dylib", "proc-macro") and ++ toolchain.target_os == "windows" and ++ toolchain.target_abi != "msvc" and ++ ld_is_direct_driver ++ ): ++ if toolchain.target_arch in ("i686", "i586", "i386"): ++ rustc_flags.add("--codegen=link-arg=--entry=_DllMainCRTStartup@12") ++ else: ++ rustc_flags.add("--codegen=link-arg=--entry=DllMainCRTStartup") + + use_metadata = _depend_on_metadata(crate_info, force_depend_on_objects) + +@@ -2010,9 +2041,14 @@ def rustc_compile_action( + # interface library that rustc generates in the output files. + interface_library = None + if toolchain.target_os == "windows" and crate_info.type == "cdylib": +- # Rustc generates the import library with a `.dll.lib` extension rather than the usual `.lib` one that msvc +- # expects (see https://github.com/rust-lang/rust/pull/29520 for more context). +- interface_library = ctx.actions.declare_file(crate_info.output.basename + ".lib", sibling = crate_info.output) ++ if toolchain.target_abi == "msvc": ++ # Rustc generates the import library with a `.dll.lib` extension rather than the usual `.lib` one that msvc ++ # expects (see https://github.com/rust-lang/rust/pull/29520 for more context). ++ interface_library_name = crate_info.output.basename + ".lib" ++ else: ++ # On non-MSVC Windows targets (e.g. gnu, gnullvm), rustc generates `lib.dll.a`. ++ interface_library_name = "lib" + crate_info.output.basename + ".a" ++ interface_library = ctx.actions.declare_file(interface_library_name, sibling = crate_info.output) + outputs.append(interface_library) + + # The action might generate extra output that we don't want to include in the `DefaultInfo` files. +@@ -2206,7 +2242,7 @@ def rustc_compile_action( + files = getattr(ctx.files, "data", []) + + ([] if experimental_use_coverage_metadata_files else coverage_runfiles) + + # Include any generated Rust ABI dylibs as required runfiles. +- ([crate_info.output] if crate_info.type == "dylib" else []) + ++ ([crate_info.output] if crate_info.type in ("dylib", "cdylib") else []) + + # Include the stdlib dylib when dynamically linking the standard library. + ([toolchain.rust_std_dylib] if link_std_dylib and toolchain.rust_std_dylib else []), + ) +@@ -2544,6 +2580,7 @@ def establish_cc_info(ctx, attr, crate_info, toolchain, cc_toolchain, feature_co + feature_configuration = feature_configuration, + cc_toolchain = cc_toolchain, + dynamic_library = crate_info.output, ++ dynamic_library_symlink_path = crate_info.output.basename, + interface_library = interface_library, + ) + elif crate_info.type == "dylib": +@@ -2572,9 +2609,13 @@ def establish_cc_info(ctx, attr, crate_info, toolchain, cc_toolchain, feature_co + linking_context = linking_context, + debug_context = debug_context, + ), +- toolchain.stdlib_linkflags, + ] + ++ # A cdylib is already linked against the Rust standard library, so its ++ # stdlib link flags do not need to propagate to downstream link actions. ++ if crate_info.type != "cdylib": ++ cc_infos.append(toolchain.stdlib_linkflags) ++ + # Flattening is okay since crate_info.deps only records direct deps. + for dep in crate_info.deps.to_list(): + if dep.cc_info: +@@ -2972,6 +3013,7 @@ def _make_link_flags_windows(make_link_flags_args, flavor_msvc, use_direct_drive + linker_input, use_pic, ambiguous_libs, include_link_flags = make_link_flags_args + ret = [] + prefix = "" if use_direct_driver else "-Wl," ++ has_static_trailing_libs = False + for lib in linker_input.libraries: + if lib.alwayslink: + if flavor_msvc: +@@ -3004,6 +3046,7 @@ def _make_link_flags_darwin(make_link_flags_args, use_direct_driver): + linker_input, use_pic, ambiguous_libs, include_link_flags = make_link_flags_args + ret = [] + prefix = "" if use_direct_driver else "-Wl," ++ has_static_trailing_libs = False + for lib in linker_input.libraries: + if lib.alwayslink: + ret.extend([ +@@ -3019,6 +3062,7 @@ def _make_link_flags_default(make_link_flags_args, use_direct_driver): + linker_input, use_pic, ambiguous_libs, include_link_flags = make_link_flags_args + ret = [] + prefix = "" if use_direct_driver else "-Wl," ++ has_static_trailing_libs = False + for lib in linker_input.libraries: + if lib.alwayslink: + ret.extend([ +@@ -3027,7 +3071,19 @@ def _make_link_flags_default(make_link_flags_args, use_direct_driver): + ("-Clink-arg=%s--no-whole-archive" % prefix), + ]) + elif include_link_flags: +- ret.extend(portable_link_flags(lib, use_pic, ambiguous_libs, get_lib_name_default)) ++ flags = portable_link_flags(lib, use_pic, ambiguous_libs, get_lib_name_default) ++ if (lib.static_library or lib.pic_static_library) and not _is_dylib(lib): ++ # On Linux/ELF platforms, rustc emits `-Wl,-Bdynamic` before trailing link-args. ++ # When linking against static libraries in Section C, switch the linker to static ++ # mode so that `-l` searches for `lib.a` rather than requiring `lib.so`. ++ ret.extend([f for f in flags if not f.startswith("-Clink-arg=")]) ++ ret.append("-Clink-arg=%s-Bstatic" % prefix) ++ ret.extend([f for f in flags if f.startswith("-Clink-arg=")]) ++ has_static_trailing_libs = True ++ else: ++ ret.extend(flags) ++ if has_static_trailing_libs: ++ ret.append("-Clink-arg=%s-Bdynamic" % prefix) + _add_user_link_flags(ret, linker_input) + return ret + +diff --git a/test/unit/cc_info/cc_info_test.bzl b/test/unit/cc_info/cc_info_test.bzl +index 3530a48..aebedbf 100644 +--- a/test/unit/cc_info/cc_info_test.bzl ++++ b/test/unit/cc_info/cc_info_test.bzl +@@ -98,7 +98,7 @@ def _proc_macro_does_not_provide_cc_info_test_impl(ctx): + def _cdylib_provides_cc_info_test_impl(ctx): + env = analysistest.begin(ctx) + tut = analysistest.target_under_test(env) +- _assert_cc_info_has_library_to_link(env, tut, "cdylib", 2) ++ _assert_cc_info_has_library_to_link(env, tut, "cdylib", 1) + return analysistest.end(env) + + def _staticlib_provides_cc_info_test_impl(ctx): +diff --git a/test/unit/win_interface_library/win_interface_library_analysis_test.bzl b/test/unit/win_interface_library/win_interface_library_analysis_test.bzl +index 016d4d2..aaff9df 100644 +--- a/test/unit/win_interface_library/win_interface_library_analysis_test.bzl ++++ b/test/unit/win_interface_library/win_interface_library_analysis_test.bzl +@@ -12,10 +12,11 @@ def _win_interface_library_test_impl(ctx): + files = target[DefaultInfo].files.to_list() + cc_library = target[CcInfo].linking_context.linker_inputs.to_list()[0].libraries[0] + +- # Make sure that we have both the `.dll` and the `.dll.lib` file in the default info's files ++ # Make sure that we have both the `.dll` and the import library (`.dll.lib` on MSVC, ++ # `.dll.a` on GNU/LLVM-GNU) in the default info's files. + asserts.equals(env, len(files), 2) + asserts.true(env, files[0].basename.endswith(".dll")) +- asserts.true(env, files[1].basename.endswith(".dll.lib")) ++ asserts.true(env, files[1].basename.endswith((".dll.lib", ".dll.a"))) + + # Make sure that the cc_library has both a dynamic and interface library + asserts.true(env, cc_library.dynamic_library != None) diff --git a/patches/rules_rust_windows_gnu.patch b/patches/rules_rust_windows_gnu.patch index bf78bfe..adbe7aa 100644 --- a/patches/rules_rust_windows_gnu.patch +++ b/patches/rules_rust_windows_gnu.patch @@ -1,3 +1,4 @@ +diff --git a/rust/private/repository_utils.bzl b/rust/private/repository_utils.bzl --- a/rust/private/repository_utils.bzl +++ b/rust/private/repository_utils.bzl @@ -56,6 +56,7 @@ filegroup( diff --git a/rs/BUILD.bazel b/rs/BUILD.bazel index 57ecf70..e8070e2 100644 --- a/rs/BUILD.bazel +++ b/rs/BUILD.bazel @@ -1,4 +1,4 @@ -load("@rules_rust//rust:defs.bzl", "rust_binary", "rust_library", "rust_test") +load("@rules_rust//rust:defs.bzl", "rust_binary", "rust_library", "rust_shared_library", "rust_test") rust_library( name = "calculator", @@ -7,12 +7,31 @@ rust_library( visibility = ["//:__subpackages__"], ) +rust_shared_library( + name = "rust_calculator", + srcs = ["rust_calculator.rs"], + edition = "2021", + visibility = ["//visibility:public"], + deps = [":calculator"], +) + +rust_library( + name = "cpp_calculator", + srcs = ["cpp_calculator.rs"], + edition = "2021", + link_deps = ["//cc:calculator"], + visibility = ["//:__subpackages__"], +) + rust_binary( name = "main", srcs = ["main.rs"], edition = "2021", visibility = ["//:__subpackages__"], - deps = [":calculator"], + deps = [ + ":calculator", + ":cpp_calculator", + ], ) rust_test( @@ -21,3 +40,10 @@ rust_test( edition = "2021", deps = [":calculator"], ) + +rust_test( + name = "cpp_calculator_test", + srcs = ["cpp_calculator_test.rs"], + edition = "2021", + deps = [":cpp_calculator"], +) diff --git a/rs/cpp_calculator.rs b/rs/cpp_calculator.rs new file mode 100644 index 0000000..825e097 --- /dev/null +++ b/rs/cpp_calculator.rs @@ -0,0 +1,65 @@ +use std::ffi::{CStr, CString}; +use std::os::raw::{c_char, c_int}; + +extern "C" { + fn cc_calculator_eval( + expr: *const c_char, + out_result: *mut f64, + err_buf: *mut c_char, + err_buf_len: usize, + ) -> c_int; + + fn cc_calculator_add(a: i32, b: i32) -> i32; + fn cc_calculator_pow(base: f64, exp: f64) -> f64; + fn cc_calculator_version() -> *const c_char; +} + +/// Safely evaluates a mathematical string expression using the hermetic C++ engine. +/// +/// Supported operators: +, -, *, /, ^, ** and parentheses. +/// Returns Ok(f64) on success, or Err(String) describing the parsing or runtime error. +pub fn evaluate_expression_cpp(expr: &str) -> Result { + let c_expr = CString::new(expr).map_err(|e| format!("invalid C string: {e}"))?; + let mut result = 0.0f64; + let mut err_buf = [0u8; 256]; + + let status = unsafe { + cc_calculator_eval( + c_expr.as_ptr(), + &mut result, + err_buf.as_mut_ptr() as *mut c_char, + err_buf.len(), + ) + }; + + if status == 0 { + Ok(result) + } else { + let err_msg = unsafe { CStr::from_ptr(err_buf.as_ptr() as *const c_char) } + .to_str() + .unwrap_or("unknown error"); + Err(err_msg.to_string()) + } +} + +/// Invokes the C++ integer addition function via FFI. +pub fn add_cpp(a: i32, b: i32) -> i32 { + unsafe { cc_calculator_add(a, b) } +} + +/// Invokes the C++ power function via FFI. +pub fn pow_cpp(base: f64, exp: f64) -> f64 { + unsafe { cc_calculator_pow(base, exp) } +} + +/// Returns the C++ calculator engine version string via FFI. +pub fn version_cpp() -> &'static str { + unsafe { + let ptr = cc_calculator_version(); + if ptr.is_null() { + "unknown" + } else { + CStr::from_ptr(ptr).to_str().unwrap_or("unknown") + } + } +} diff --git a/rs/cpp_calculator_test.rs b/rs/cpp_calculator_test.rs new file mode 100644 index 0000000..dc91566 --- /dev/null +++ b/rs/cpp_calculator_test.rs @@ -0,0 +1,56 @@ +use cpp_calculator::{add_cpp, evaluate_expression_cpp, pow_cpp, version_cpp}; + +#[test] +fn test_cpp_basic_operations() { + assert_eq!(evaluate_expression_cpp("2 + 2"), Ok(4.0)); + assert_eq!(evaluate_expression_cpp("5 - 3"), Ok(2.0)); + assert_eq!(evaluate_expression_cpp("4 * 3"), Ok(12.0)); + assert_eq!(evaluate_expression_cpp("10 / 2"), Ok(5.0)); +} + +#[test] +fn test_cpp_operator_precedence() { + assert_eq!(evaluate_expression_cpp("2 + 3 * 4"), Ok(14.0)); + assert_eq!(evaluate_expression_cpp("(2 + 3) * 4"), Ok(20.0)); +} + +#[test] +fn test_cpp_power_operations() { + assert_eq!(evaluate_expression_cpp("2 ** 3"), Ok(8.0)); + assert_eq!(evaluate_expression_cpp("2 ^ 3"), Ok(8.0)); +} + +#[test] +fn test_cpp_unary_operations() { + assert_eq!(evaluate_expression_cpp("-5 + 3"), Ok(-2.0)); + assert_eq!(evaluate_expression_cpp("-(3 * 2)"), Ok(-6.0)); +} + +#[test] +fn test_cpp_division_by_zero() { + let result = evaluate_expression_cpp("10 / 0"); + assert!(result.is_err()); + assert_eq!(result.unwrap_err(), "division by zero"); +} + +#[test] +fn test_cpp_invalid_syntax() { + assert!(evaluate_expression_cpp("2 + * 3").is_err()); +} + +#[test] +fn test_cpp_unsupported_operations() { + assert!(evaluate_expression_cpp("import os").is_err()); +} + +#[test] +fn test_cpp_float_parsing() { + assert_eq!(evaluate_expression_cpp("2.5 * 4"), Ok(10.0)); +} + +#[test] +fn test_cpp_direct_helpers() { + assert_eq!(add_cpp(15, 27), 42); + assert_eq!(pow_cpp(2.0, 10.0), 1024.0); + assert_eq!(version_cpp(), "1.0.0-cpp"); +} diff --git a/rs/main.rs b/rs/main.rs index c6b004d..9d04bae 100644 --- a/rs/main.rs +++ b/rs/main.rs @@ -4,8 +4,9 @@ use std::process; fn print_usage() { println!("Usage: main [arguments]"); println!("Commands:"); - println!(" info Display information about the Rust environment."); - println!(" calc Evaluate a mathematical expression securely."); + println!(" info Display information about the Rust environment."); + println!(" calc Evaluate a mathematical expression using Rust engine."); + println!(" calc-cpp Evaluate a mathematical expression using C++ FFI engine."); } fn main() { @@ -19,6 +20,10 @@ fn main() { "info" => { println!("OS: {}, Arch: {}", env::consts::OS, env::consts::ARCH); println!("Bazel hermetic Rust template is working!"); + println!( + "C++ Interop Engine Version: {}", + cpp_calculator::version_cpp() + ); } "calc" => { if args.len() < 3 { @@ -34,6 +39,20 @@ fn main() { } } } + "calc-cpp" => { + if args.len() < 3 { + eprintln!("Error: calc-cpp command requires a mathematical expression."); + process::exit(1); + } + let expression = &args[2]; + match cpp_calculator::evaluate_expression_cpp(expression) { + Ok(result) => println!("{expression} = {result} (via C++ engine)"), + Err(err) => { + eprintln!("Error: {err}"); + process::exit(1); + } + } + } unknown => { eprintln!("Error: Unknown command '{unknown}'"); print_usage(); diff --git a/rs/rust_calculator.rs b/rs/rust_calculator.rs new file mode 100644 index 0000000..1fab149 --- /dev/null +++ b/rs/rust_calculator.rs @@ -0,0 +1,91 @@ +use std::ffi::{CStr, CString}; +use std::os::raw::{c_char, c_int}; + +/// Evaluates a mathematical string expression using the Rust calculator engine. +/// +/// Returns 0 on success, or a non-zero error code: +/// 1: Division by zero +/// 2: Invalid syntax +/// 3: Empty expression +/// 4: Trailing unparsed tokens +/// -1: Null pointer or unexpected error +/// +/// # Safety +/// Caller must ensure that `expr` is a valid null-terminated C string and +/// that `out_result` and `err_buf` point to valid memory if non-null. +#[no_mangle] +pub unsafe extern "C" fn rs_calculator_eval( + expr: *const c_char, + out_result: *mut f64, + err_buf: *mut c_char, + err_buf_len: usize, +) -> c_int { + if expr.is_null() || out_result.is_null() { + if !err_buf.is_null() && err_buf_len > 0 { + let msg = b"null pointer argument\0"; + let copy_len = msg.len().min(err_buf_len); + std::ptr::copy_nonoverlapping(msg.as_ptr() as *const c_char, err_buf, copy_len); + *err_buf.add(copy_len - 1) = 0; + } + return -1; + } + + let c_str = CStr::from_ptr(expr); + let expr_str = match c_str.to_str() { + Ok(s) => s, + Err(_) => { + if !err_buf.is_null() && err_buf_len > 0 { + let msg = b"invalid utf-8 string\0"; + let copy_len = msg.len().min(err_buf_len); + std::ptr::copy_nonoverlapping(msg.as_ptr() as *const c_char, err_buf, copy_len); + *err_buf.add(copy_len - 1) = 0; + } + return 2; + } + }; + + match calculator::evaluate_expression(expr_str) { + Ok(val) => { + *out_result = val; + if !err_buf.is_null() && err_buf_len > 0 { + *err_buf = 0; + } + 0 + } + Err(err) => { + let code = match err.as_str() { + "division by zero" => 1, + "empty expression" => 3, + "trailing unparsed tokens" => 4, + _ => 2, + }; + if !err_buf.is_null() && err_buf_len > 0 { + let c_err = CString::new(err).unwrap_or_default(); + let bytes = c_err.as_bytes_with_nul(); + let copy_len = bytes.len().min(err_buf_len); + std::ptr::copy_nonoverlapping(bytes.as_ptr() as *const c_char, err_buf, copy_len); + *err_buf.add(copy_len - 1) = 0; + } + code + } + } +} + +/// Evaluates integer addition in Rust. +#[no_mangle] +pub extern "C" fn rs_calculator_add(a: i32, b: i32) -> i32 { + a + b +} + +/// Evaluates floating point exponentiation in Rust. +#[no_mangle] +pub extern "C" fn rs_calculator_pow(base: f64, exp: f64) -> f64 { + base.powf(exp) +} + +/// Returns the Rust calculator engine version string. +#[no_mangle] +pub extern "C" fn rs_calculator_version() -> *const c_char { + static VERSION: &[u8] = b"1.0.0-rust\0"; + VERSION.as_ptr() as *const c_char +} diff --git a/tools/BUILD.bazel b/tools/BUILD.bazel index cedb81a..a6f43b6 100644 --- a/tools/BUILD.bazel +++ b/tools/BUILD.bazel @@ -53,10 +53,12 @@ py_binary( py_binary( name = "staticcheck", - srcs = ["run_in_cwd.py"], - args = ["$(rlocationpath @co_honnef_go_tools//cmd/staticcheck:staticcheck)"], - data = ["@co_honnef_go_tools//cmd/staticcheck"], - main = "run_in_cwd.py", + srcs = ["staticcheck.py"], + data = [ + "@co_honnef_go_tools//cmd/staticcheck", + "@rules_go//go", + ], + main = "staticcheck.py", visibility = ["//visibility:public"], ) diff --git a/tools/staticcheck.py b/tools/staticcheck.py new file mode 100644 index 0000000..be0d7a4 --- /dev/null +++ b/tools/staticcheck.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python3 +"""Launcher for staticcheck that restores the workspace working directory and provisions hermetic Go.""" + +from __future__ import annotations + +import os +import subprocess +import sys +from collections.abc import Callable +from pathlib import Path + +SCRIPT_PATH = Path(__file__).resolve() + + +def _find_file_from_manifest(predicate: Callable[[str], bool]) -> Path | None: + manifest_file = os.environ.get("RUNFILES_MANIFEST_FILE") + if manifest_file: + manifest_path = Path(manifest_file) + if manifest_path.is_file(): + with manifest_path.open(encoding="utf-8") as f: + for line in f: + match line.strip().split(" ", 1): + case [rpath, target] if predicate(rpath): + candidate = Path(target) + if candidate.is_file(): + return candidate + case _: + continue + return None + + +def _find_runfiles_dir() -> Path | None: + runfiles_env = os.environ.get("PYTHON_RUNFILES") or os.environ.get("RUNFILES_DIR") + if runfiles_env and Path(runfiles_env).is_dir(): + return Path(runfiles_env) + + for parent in [SCRIPT_PATH, *SCRIPT_PATH.parents]: + if parent.name.endswith(".runfiles") and parent.is_dir(): + return parent + return None + + +def _find_binary(rel_suffix: str, exe_name: str) -> Path | None: + from_manifest = _find_file_from_manifest(lambda rpath: rpath.endswith(f"{rel_suffix}/{exe_name}")) + if from_manifest: + return from_manifest + + runfiles_dir = _find_runfiles_dir() + if runfiles_dir: + for repo_dir in runfiles_dir.iterdir(): + if not repo_dir.is_dir(): + continue + candidate = repo_dir / rel_suffix / exe_name + if candidate.is_file(): + return candidate + + return None + + +def main() -> None: + exe_name = "staticcheck.exe" if sys.platform == "win32" else "staticcheck" + go_exe = "go.exe" if sys.platform == "win32" else "go" + + found_bin = _find_binary("cmd/staticcheck/staticcheck_", exe_name) + if not found_bin: + found_bin = _find_binary("cmd/staticcheck", exe_name) + + if not found_bin: + sys.stderr.write("Error: Could not locate staticcheck binary in runfiles.\n") + sys.exit(1) + + hermetic_go = _find_binary("go/tools/go_bin_runner/bin", go_exe) + if not hermetic_go: + hermetic_go = _find_binary("bin", go_exe) + + if hermetic_go: + os.environ["PATH"] = str(hermetic_go.parent.resolve()) + os.pathsep + os.environ.get("PATH", "") + + workspace_dir = os.environ.get("BUILD_WORKING_DIRECTORY") or os.environ.get("BUILD_WORKSPACE_DIRECTORY") + if workspace_dir: + os.chdir(workspace_dir) + + res = subprocess.run([str(found_bin.resolve()), *sys.argv[1:]], check=False) + sys.exit(res.returncode) + + +if __name__ == "__main__": + main()