From 25210d5b0e304711b24ad6a1caab237cc7985d3b Mon Sep 17 00:00:00 2001 From: Wenyi Tang Date: Thu, 30 Apr 2026 23:41:12 +0800 Subject: [PATCH] [refactor](bazel): move workspace files and bazel rules to root - Move vila/workspace0/1/2.bzl to root folder - Move vila/bazel/ to bazel/ for cleaner structure - Update all path references from @vila//vila/bazel to @vila//bazel - Update WORKSPACE and MODULE.bazel load paths - Update documentation (README.md, CLAUDE.md) Breaking change: downstream WORKSPACE users must update load paths from @vila//vila:workspace*.bzl to @vila//:workspace*.bzl Also add Claude skills for clim and vila library components: - clim-guide: comprehensive clim sub-targets documentation - vila-config, vila-graph, vila-hook, vila-logging, vila-profiling, vila-status, vila-widget: individual component usage guidance --- .claude/CLAUDE.md | 97 +-- .claude/MITIGATION.md | 85 +++ .claude/skills/clim-guide/SKILL.md | 601 ++++++++++++++++++ .claude/skills/vila-config/SKILL.md | 111 ++++ .claude/skills/vila-graph/SKILL.md | 214 +++++++ .claude/skills/vila-hook/SKILL.md | 117 ++++ .claude/skills/vila-logging/SKILL.md | 147 +++++ .claude/skills/vila-profiling/SKILL.md | 184 ++++++ .claude/skills/vila-status/SKILL.md | 237 +++++++ .claude/skills/vila-widget/SKILL.md | 197 ++++++ .pre-commit-config.yaml | 4 +- MODULE.bazel | 17 +- README.md | 6 +- WORKSPACE | 12 +- {vila/bazel => bazel}/BUILD.bazel | 0 {vila/bazel => bazel}/bzlmod/BUILD.bazel | 0 {vila/bazel => bazel}/bzlmod/extensions.bzl | 12 +- {vila/bazel => bazel}/device/BUILD.bazel | 0 {vila/bazel => bazel}/fmt.BUILD | 2 +- {vila/bazel => bazel}/hlsl/BUILD.bazel | 0 {vila/bazel => bazel}/hlsl/BUILD.tpl | 0 {vila/bazel => bazel}/hlsl/compiler.bzl.tpl | 0 {vila/bazel => bazel}/hlsl/hlsl_configure.bzl | 0 {vila/bazel => bazel}/ittapi.BUILD | 0 {vila/bazel => bazel}/local_archive.bzl | 0 {vila/bazel => bazel}/pre_compile.bzl | 2 +- {vila/bazel => bazel}/spdlog.BUILD | 0 {vila/bazel => bazel}/symlink.bzl | 0 {vila/bazel => bazel}/toolchains/BUILD.bazel | 0 .../toolchains/BUILD_bullseye.tpl | 0 .../bazel => bazel}/toolchains/BUILD_sycl.tpl | 2 +- .../toolchains/BUILD_sycl_unix.tpl | 0 .../toolchains/bullseye_cc_configure.bzl | 10 +- {vila/bazel => bazel}/toolchains/os.bzl | 0 .../toolchains/sycl_cc_configure.bzl | 14 +- .../toolchains/sycl_cc_toolchain_config.bzl | 0 .../toolchains/unix_toolchain_configure.bzl | 2 +- .../windows_toolchain_configure.bzl | 0 {vila/bazel => bazel}/tvm_ffi_configure.bzl | 4 +- {vila/bazel => bazel}/vila/BUILD.bazel | 0 .../bazel => bazel}/vila/compile_options.bzl | 0 {vila/bazel => bazel}/vila/vila.bzl | 2 +- {vila/bazel => bazel}/wdk/BUILD.bazel | 0 {vila/bazel => bazel}/wdk/BUILD.tpl | 0 {vila/bazel => bazel}/wdk/rc.bzl.tpl | 0 {vila/bazel => bazel}/wdk/wdk_configure.bzl | 6 +- {vila/bazel => bazel}/wdk/wpp.bzl.tpl | 0 tests/vila/BUILD.bazel | 2 +- tests/vila/bazel/sycl/BUILD.bazel | 4 +- tests/vila/pch/BUILD.bazel | 2 +- vila/BUILD.bazel | 2 +- vila/config/BUILD.bazel | 2 +- vila/graph/BUILD.bazel | 2 +- vila/logging/BUILD.bazel | 2 +- vila/profiling/BUILD.bazel | 2 +- vila/status/BUILD.bazel | 2 +- vila/widget/BUILD.bazel | 2 +- vila/workspace0.bzl => workspace0.bzl | 75 +-- vila/workspace1.bzl => workspace1.bzl | 84 ++- vila/workspace2.bzl => workspace2.bzl | 12 +- 60 files changed, 2107 insertions(+), 171 deletions(-) create mode 100644 .claude/MITIGATION.md create mode 100644 .claude/skills/clim-guide/SKILL.md create mode 100644 .claude/skills/vila-config/SKILL.md create mode 100644 .claude/skills/vila-graph/SKILL.md create mode 100644 .claude/skills/vila-hook/SKILL.md create mode 100644 .claude/skills/vila-logging/SKILL.md create mode 100644 .claude/skills/vila-profiling/SKILL.md create mode 100644 .claude/skills/vila-status/SKILL.md create mode 100644 .claude/skills/vila-widget/SKILL.md rename {vila/bazel => bazel}/BUILD.bazel (100%) rename {vila/bazel => bazel}/bzlmod/BUILD.bazel (100%) rename {vila/bazel => bazel}/bzlmod/extensions.bzl (88%) rename {vila/bazel => bazel}/device/BUILD.bazel (100%) rename {vila/bazel => bazel}/fmt.BUILD (92%) rename {vila/bazel => bazel}/hlsl/BUILD.bazel (100%) rename {vila/bazel => bazel}/hlsl/BUILD.tpl (100%) rename {vila/bazel => bazel}/hlsl/compiler.bzl.tpl (100%) rename {vila/bazel => bazel}/hlsl/hlsl_configure.bzl (100%) rename {vila/bazel => bazel}/ittapi.BUILD (100%) rename {vila/bazel => bazel}/local_archive.bzl (100%) rename {vila/bazel => bazel}/pre_compile.bzl (98%) rename {vila/bazel => bazel}/spdlog.BUILD (100%) rename {vila/bazel => bazel}/symlink.bzl (100%) rename {vila/bazel => bazel}/toolchains/BUILD.bazel (100%) rename {vila/bazel => bazel}/toolchains/BUILD_bullseye.tpl (100%) rename {vila/bazel => bazel}/toolchains/BUILD_sycl.tpl (97%) rename {vila/bazel => bazel}/toolchains/BUILD_sycl_unix.tpl (100%) rename {vila/bazel => bazel}/toolchains/bullseye_cc_configure.bzl (93%) rename {vila/bazel => bazel}/toolchains/os.bzl (100%) rename {vila/bazel => bazel}/toolchains/sycl_cc_configure.bzl (93%) rename {vila/bazel => bazel}/toolchains/sycl_cc_toolchain_config.bzl (100%) rename {vila/bazel => bazel}/toolchains/unix_toolchain_configure.bzl (99%) rename {vila/bazel => bazel}/toolchains/windows_toolchain_configure.bzl (100%) rename {vila/bazel => bazel}/tvm_ffi_configure.bzl (97%) rename {vila/bazel => bazel}/vila/BUILD.bazel (100%) rename {vila/bazel => bazel}/vila/compile_options.bzl (100%) rename {vila/bazel => bazel}/vila/vila.bzl (98%) rename {vila/bazel => bazel}/wdk/BUILD.bazel (100%) rename {vila/bazel => bazel}/wdk/BUILD.tpl (100%) rename {vila/bazel => bazel}/wdk/rc.bzl.tpl (100%) rename {vila/bazel => bazel}/wdk/wdk_configure.bzl (90%) rename {vila/bazel => bazel}/wdk/wpp.bzl.tpl (100%) rename vila/workspace0.bzl => workspace0.bzl (54%) rename vila/workspace1.bzl => workspace1.bzl (53%) rename vila/workspace2.bzl => workspace2.bzl (82%) diff --git a/.claude/CLAUDE.md b/.claude/CLAUDE.md index 80f0f55..9b56327 100644 --- a/.claude/CLAUDE.md +++ b/.claude/CLAUDE.md @@ -24,13 +24,14 @@ bazelisk build --config=sycl //... bazelisk --output_base="C:/temp/_vila_workspace" build --noenable_bzlmod //... ``` -**Legacy WORKSPACE setup (Windows)** requires loading three workspace files in sequence: +**Legacy WORKSPACE setup** requires loading three workspace files in sequence: ```bazel -load("@vila//vila:workspace0.bzl", vila_workspace0 = "workspace") +load("//:workspace0.bzl", vila_workspace0 = "workspace") vila_workspace0() -load("@vila//vila:workspace1.bzl", vila_workspace1 = "workspace") +load("//:workspace1.bzl", vila_workspace1 = "workspace") vila_workspace1() -load("@vila//vila:workspace2.bzl", vila_workspace2 = "workspace") +load("//:workspace2.bzl", vila_workspace2 = "workspace") +vila_workspace2() ``` ### CMake @@ -45,48 +46,60 @@ cmake -Bbuild -S. -GNinja -DVILA_ENABLE_TESTING=ON ## Code Style -- **Style**: Based on Google C++ Style (see `.clang-format`) -- **Clang-tidy**: Configured in `.clang-tidy`, targets `clim/` and `vila/` headers only (excludes generated files) -- **Pre-commit hooks**: Run via `pre-commit run -s HEAD^ -o HEAD` (see `.pre-commit-config.yaml`) -- **Spell checking**: Codespell configured with words bag at `.github/WORDS_BAG.txt` +- **Style**: Google C++ Style with 80-column limit (see `.clang-format`) +- **Clang-tidy**: Targets `clim/*.h` and `vila/*.h` headers only (excludes generated files). Warnings treated as errors for readability, bugprone, and concurrency checks. +- **Pre-commit hooks**: `pre-commit run -s HEAD^ -o HEAD` (see `.pre-commit-config.yaml`) +- **Spell checking**: Codespell with custom words bag at `.github/WORDS_BAG.txt` ## Architecture ``` -clim/ # Header-only utility library (math, strings, containers, etc.) - ├── argparse/ # Command-line argument parsing - ├── container/ # Bounding boxes, ring buffers, etc. - ├── filter/ # Kalman and alpha-beta filters - ├── hash/ # CityHash, MurmurHash - ├── math/ # Quaternion, numerical utilities - ├── os/ # OS utilities (aligned malloc, barriers) - ├── path/ # Cross-platform path handling - ├── reflection/ # Reflection registry - ├── string/ # String splitting, stripping, const_string - ├── vt/ # Vector math (GEMM, neural network ops) - └── zip/ # Zip utility functions +clim/ # Header-only utility library + ├── argparse # Command-line argument parsing (depends on //clim:string) + ├── container # Bounding boxes, ring buffers, array arithmetic + ├── filter # Kalman and alpha-beta filters (depends on //clim:container) + ├── hash # CityHash, MurmurHash implementations + ├── math # Quaternion, numerical utilities + ├── os # Aligned malloc, barriers, OS utilities + ├── path # Cross-platform path handling (defines HAS_STD_FS on non-Windows) + ├── reflection # Reflection registry (depends on //clim:string) + ├── string # String splitting, stripping, const_string + ├── vt # Vector math (GEMM, neural network ops; depends on //clim:traits) + └── zip # Zip utility functions vila/ # Core library components - ├── config/ # JSON-based configuration system - ├── graph/ # Template header-only DAG (dag.h, graph.h, route.h, traversal.h) - ├── hook/ # Windows DLL hooking (detours) - ├── logging/ # Logger with WPP support (code_location, logger) - ├── profiling/ # ITT, timer, trace utilities - ├── status/ # Status and StatusOr error handling - ├── widget/ # (UI components) - └── bazel/ # Bazel-specific build rules and toolchains - -python/ # Python bindings via nanobind/pybind11 -tests/ # GoogleTest-based C++ tests + ├── config # JSON-based configuration system + ├── graph # Template header-only DAG library (dag.h, digraph.h, graph.h, node.h, route.h, traversal.h) + ├── hook # Windows DLL hooking via Detours library + ├── logging # Logger with WPP support (code_location, logger) + ├── profiling # ITT instrumentation, timer, trace utilities + ├── status # Status and StatusOr error handling + └── widget # Registration tokens + +bazel/ # Bazel-specific build rules and toolchains +python/ # Python utilities (vila.core, vila.arith.random) +tests/ # GoogleTest-based C++ tests ``` ## Key Dependencies (via Bazel) - `fmt` (12.1.0) - Formatting library -- `spdlog` - Logging library -- `googletest` - Testing framework -- `google_benchmark` - Benchmarking -- `rules_foreign_cc` - CMake/ ninja build support +- `spdlog` - Logging library (loaded via extension) +- `googletest` (1.17.0) - Testing framework +- `google_benchmark` (1.9.2) - Benchmarking +- `rangev3` - Range library (for C++20 `range_test`) +- `ittapi` - Intel ITT instrumentation +- `tvm_ffi` - TVM FFI support (optional, requires `pip install apache-tvm-ffi`) + +## Custom Bazel Rules + +The project provides custom build rules in `bazel/vila/vila.bzl`: + +- `vila_cc_library` - Adds default copts +- `vila_cc_binary` - Adds default copts/linkopts, defaults to `linkstatic=True` +- `vila_cc_test` - Adds C++17 + Unicode copts, defaults to `linkstatic=True` +- `vila_dll_library` - Imports Windows DLL dependencies +- `vila_so_library` - Imports Linux shared library dependencies ## Testing @@ -101,11 +114,9 @@ pytest --cov=python/vila python/tests ## Windows-Specific Notes -- Default C++ standard: C++17 -- Windows WPP logging disabled by default (see commit ed44f79) -- Windows-specific configs use `select()` with `//conditions:default` since some build configs are Windows-only -- The `range_test` is Windows-only and requires C++20 - -## Editor Setup - -The project includes `.vscode/` settings for convenience with bazelized projects. +- Default C++ standard: C++17 (`/std:c++17` in `.bazelrc`) +- Windows WPP logging disabled by default (controlled by `--enable_wpp` flag) +- Windows-specific configs use `select()` with `//conditions:default` +- `range_test` is Windows-only and requires C++20 +- Use `/FC` flag for `__FILE__` to expand to full Windows path (see `const_string_test`) +- `.bazelrc` uses `--spawn_strategy=local` to work around sandbox issues diff --git a/.claude/MITIGATION.md b/.claude/MITIGATION.md new file mode 100644 index 0000000..c1f59c0 --- /dev/null +++ b/.claude/MITIGATION.md @@ -0,0 +1,85 @@ +# Bazel Structure Refactoring Mitigation Plan + +## Summary + +Refactor Bazel workspace structure by moving workspace files and bazel rules to more conventional locations: +- Move `vila/workspace0.bzl`, `vila/workspace1.bzl`, `vila/workspace2.bzl` to root folder +- Move `vila/bazel/` to `bazel/` + +## Status: COMPLETED ✓ + +## Changes + +### File Movements + +| Source | Destination | +|--------|-------------| +| `vila/workspace0.bzl` | `workspace0.bzl` | +| `vila/workspace1.bzl` | `workspace1.bzl` | +| `vila/workspace2.bzl` | `workspace2.bzl` | +| `vila/bazel/` (entire directory) | `bazel/` | + +### Path Updates + +Replace `@vila//vila/bazel` with `@vila//bazel` in all files. +Replace `@vila//vila:workspace*.bzl` with `//:workspace*.bzl` in WORKSPACE and documentation. + +### Files Affected + +#### Root Level +- `WORKSPACE` - workspace load paths +- `MODULE.bazel` - bzlmod extension paths +- `README.md` - documentation examples +- `.claude/CLAUDE.md` - build instructions + +#### Moved Files (internal references) +- `workspace1.bzl` - references `@vila//vila/bazel/` +- `workspace2.bzl` - references `@vila//vila/bazel/` +- `bazel/bzlmod/extensions.bzl` - references `@vila//vila/bazel/` +- `bazel/tvm_ffi_configure.bzl` - references `@vila//vila/bazel/` +- `bazel/vila/vila.bzl` - references `@vila//vila/bazel/vila/` +- `bazel/vila/compile_options.bzl` - references `@vila//vila:` (keeps same, vila constraints) +- `bazel/toolchains/*.bzl` - various references +- `bazel/wdk/wdk_configure.bzl` - template paths +- `bazel/pre_compile.bzl` - self-reference +- `bazel/toolchains/BUILD_sycl.tpl` - load statement +- `bazel/fmt.BUILD` - load statement + +#### vila Library BUILD Files +- `vila/BUILD.bazel` - sycl constraint reference +- `vila/config/BUILD.bazel` - vila_cc_library load +- `vila/graph/BUILD.bazel` - vila_cc_library load +- `vila/logging/BUILD.bazel` - vila_cc_library load +- `vila/profiling/BUILD.bazel` - vila_cc_library load +- `vila/status/BUILD.bazel` - vila_cc_library load +- `vila/widget/BUILD.bazel` - vila_cc_library load + +## Execution Steps + +1. ✓ Move workspace files to root +2. ✓ Move bazel directory to root +3. ✓ Update WORKSPACE load paths +4. ✓ Update MODULE.bazel extension paths +5. ✓ Update all .bzl file references +6. ✓ Update all BUILD file load statements +7. ✓ Update documentation (README.md, CLAUDE.md) +8. ✓ Remove empty `vila/bazel/` directory structure + +## Post-Refactoring Validation + +```bash +# Test legacy WORKSPACE build (PASSED) +bazelisk build --noenable_bzlmod //vila/status +# Result: Build completed successfully, 22 total actions + +# Test bzlmod build (PASSED) +bazelisk build //vila/status +# Result: Build completed successfully, 22 total actions +``` + +## Backward Compatibility + +This is a breaking change for downstream consumers using legacy WORKSPACE. They must update their load paths: +- `@vila//vila:workspace*.bzl` → `//:workspace*.bzl` + +Bzlmod users are unaffected since they use `bazel_dep()` only. diff --git a/.claude/skills/clim-guide/SKILL.md b/.claude/skills/clim-guide/SKILL.md new file mode 100644 index 0000000..440abd5 --- /dev/null +++ b/.claude/skills/clim-guide/SKILL.md @@ -0,0 +1,601 @@ +--- +name: clim-guide +description: Guidance for using the clim (C++ Library for Infrastructure and Math) header-only utility library. Use this skill when working with any clim component: argparse for command-line parsing, string utilities (str_split, strip, const_string, str_replace), container utilities (bounding_box, ringbuffer, array_arithmetic), path handling, filters (Kalman, alpha-beta), hash functions (CityHash, MurmurHash), math utilities (quaternion, numerical), OS utilities, reflection, vt (vector tensor operations), base64 encoding, or zip utilities. +type: skill +--- + +# CLIM Library Usage Guide + +CLIM is a header-only C++ utility library for computer vision and general infrastructure. All components are under `clim/` and can be included directly. Dependencies are minimal; most headers are standalone. + +## Bazel Dependencies + +```bazel +deps = ["//clim:"] +``` + +Available targets: `argparse`, `base64`, `container`, `filter`, `hash`, `math`, `os`, `path`, `reflection`, `string`, `vt`, `zip`, `clim` ( umbrella target for all). + +--- + +## argparse - Command-Line Argument Parsing + +**Header:** `clim/argparse.h` +**Depends on:** `//clim:string` + +Python-style argument parser supporting position args, keyword args, and flags. + +```cpp +#include "clim/argparse.h" + +auto parser = ArgumentParser("myprog"); +parser.AddArgument("--foo").WithDefault(100).Required().WithHelp("Foo value"); +parser.AddArgument("--bar").StoreTrue().WithHelp("Enable bar"); +parser.AddArgument("input").WithHelp("Input file"); // position arg + +auto args = parser.Parse(argc, argv); +int64_t foo = args["foo"].AsLong(); // or: args["foo"] +bool bar = args["bar"]; // implicit bool conversion +std::string input = args["input"].AsStr(); + +// Parse only known args, return unknown as map +auto [known, unknown] = parser.ParseKnown(argc, argv); + +// Parse from dict (for configuration) +std::map dict = {"foo", "200"}; +auto args = parser.ParseDict(dict); +``` + +**Argument modifiers:** +- `WithDefault(int64_t|int32_t|float|double|std::string)` - set default value +- `Required()` - mark as required +- `StoreTrue()` / `StoreFalse()` - boolean flags +- `Nargs(uint64_t)` - number of values (use '*' or '+' for variable) +- `WithHelp(std::string_view)` - help message + +--- + +## string - String Utilities + +**Headers:** `clim/str_split.h`, `clim/strip.h`, `clim/str_replace.h`, `clim/const_string.h` +**Target:** `//clim:string` + +### StrSplit / StrSplitStringView + +```cpp +#include "clim/str_split.h" + +// Split by character (returns std::vector) +auto parts = StrSplit("a,b,c", ','); // ["a", "b", "c"] + +// Split by string (returns string_view for efficiency) +auto parts = StrSplitStringView("a::b::c", "::"); // string_view vector +auto parts = StrSplitStringView("a,b,c", ','); // char version, faster +``` + +### Strip + +```cpp +#include "clim/strip.h" + +auto s = Strip(" hello "); // "hello" (strips spaces by default) +auto s = Strip("__hello__", '_'); // "hello" (custom char) +``` + +### StrReplace + +```cpp +#include "clim/str_replace.h" + +auto s = StrReplace("hello world", "world", "there"); // "hello there" +std::string mutable_str = "abcabc"; +StrReplaceInplace(mutable_str, "abc", "x"); // modifies in-place: "xx" +``` + +### ConstString (Compile-Time String) + +```cpp +#include "clim/const_string.h" + +constexpr auto s = ConstString("abc"); +s.Size(); // 4 (includes null terminator) +s.Data(); // "abc" +s[1]; // 'b' +s.Substr<1, 2>(); // ConstString("bc") +s.Find('c'); // 2 +s.ReverseFind('c'); // 2 + +// Useful with macros +ConstString(__FUNCTION__).Find(':'); // parse function name at compile-time +``` + +--- + +## container - Bounding Boxes & Ring Buffer + +**Headers:** `clim/bounding_box.h`, `clim/ringbuffer.h`, `clim/array_arithmetic.h`, `clim/rect.h` +**Target:** `//clim:container` + +### BoundingBox + +Templated bounding box with multiple representations: + +```cpp +#include "clim/bounding_box.h" + +// BoxType::xyxy - [left, top, right, bottom] +// BoxType::xywh - [left, top, width, height] +// BoxType::cxywh - [center_x, center_y, width, height] + +BoundingBox box(10, 20, 100, 200); +auto xywh = box.ToXYWH(); // convert representation +auto cxywh = box.ToCXYWH(); // convert to center format + +box.Area(); // area of box +box.Width(); // width +box.Height(); // height +box.Intersect(other); // intersection area (other must be xyxy) +box.Union(other); // union area + +// Relative/absolute coordinate conversion +auto rel = box.ToRelative(img_width, img_height); +auto abs = rel.ToAbsolute(img_width, img_height); +``` + +### RingBuffer + +Simple FIFO ring buffer (not thread-safe): + +```cpp +#include "clim/ringbuffer.h" + +RingBuffer buffer(10); // capacity 10 +buffer.Push(1); +buffer.Push(2); +buffer.Peak(); // 1 (oldest element, doesn't remove) +buffer.Pop(); // 1 (removes oldest) +buffer.Empty(); // check if empty +buffer.Capacity(); // 10 +``` + +### array_arithmetic + +Operator overloads for `std::array`: + +```cpp +#include "clim/array_arithmetic.h" + +std::array a = {1, 2, 3, 4}; +std::array b = {5, 6, 7, 8}; + +auto c = a + b; // element-wise add +auto d = a * 2.0; // scalar multiply +auto e = a / b; // element-wise divide +a += b; // in-place +abs(a); // element-wise abs +clip(a, 0.0, 10.0); // element-wise clip +l1(a); // L1 norm +l2(a); // L2 norm +``` + +--- + +## filter - Kalman & Alpha-Beta Filters + +**Headers:** `clim/kalman_filter.h`, `clim/alpha_beta_filter.h` +**Target:** `//clim:filter` (depends on `//clim:container`) + +### AlphaBetaFilter + +Simple state estimator for smoothing: + +```cpp +#include "clim/alpha_beta_filter.h" + +AlphaBetaFilter<4, double> filter; // 4-element array filter +std::array measurement = {1.0, 2.0, 3.0, 4.0}; + +// Filter with alpha=0.5, beta=0.1, dt=0.1 +auto smoothed = filter(measurement, 0.5, 0.1, 0.1); +auto predicted = filter.Predict(0.1); // predict next state +auto velocity = filter.Velocity(); // current velocity estimate +filter.Reset(); // reset state and velocity +``` + +### KalmanFilter + +Full Kalman filter with state and covariance: + +```cpp +#include "clim/kalman_filter.h" + +std::array initial = {0, 0, 0, 0}; +std::array variance = {1, 1, 1, 1}; +KalmanFilter<4, double> kf(initial, variance); + +auto priori = kf.Priori(); // predicted state + +// Posteriori update with measurement, dt, measurement noise R, process noise Q +std::array measure = {1.1, 2.2, 3.3, 4.4}; +std::array, 4> Q = {...}; // process noise per element +std::array R = {0.1, 0.1, 0.1, 0.1}; // measurement noise +auto posteriori = kf.Posteriori(measure, 0.1, R, Q); +``` + +--- + +## hash - CityHash & MurmurHash + +**Headers:** `clim/hasher/hash.h`, `clim/hasher/city.h`, `clim/hasher/murmur3.h` +**Target:** `//clim:hash` + +```cpp +#include "clim/hasher/hash.h" + +MixStringHash hasher; +uint64_t h = hasher("some_string"); // CityHash64 for len>=16, std::hash otherwise + +// Direct usage +#include "clim/hasher/city.h" +uint64_t h = CityHash64(data, len); +uint64_t h = CityHash64WithSeed(data, len, seed); + +#include "clim/hasher/murmur3.h" +uint32_t h = Murmur3_32(data, len, seed); +``` + +--- + +## math - Quaternion & Numerical Utilities + +**Headers:** `clim/quat.h`, `clim/numerical.h` +**Target:** `//clim:math` (depends on `//clim:traits`) + +### Quaternion + +3D rotation representation: + +```cpp +#include "clim/quat.h" + +Quaternion q; // identity quaternion +Quaternion q(0.1, 0.2, 0.3, 1.0); // from x,y,z,w +Quaternion q(pitch, yaw, roll, EulerType::xyz); // from Euler angles +Degree pitch(45), yaw(30), roll(0); +Quaternion q(pitch, yaw, roll); // from degrees + +q.W(), q.X(), q.Y(), q.Z(); // components +q.Normalize(); // normalized quaternion +q.Norm(); // L2 norm +q.Magnitude(); // rotation angle +q.Conj(); // conjugate + +auto [p, y, r] = q.AsEuler(EulerType::zyx); // to Euler angles + +// Apply rotation to 3D vector +auto [x', y', z'] = q.Apply(1.0, 0.0, 0.0); // rotate x-axis + +Quaternion_d q1, q2; +auto result = q1 * q2; // quaternion multiplication (compose rotations) +``` + +### numerical + +Math constants and utilities: + +```cpp +#include "clim/numerical.h" + +numbers::pi; // 3.14159... +numbers::e; // 2.71828... +numbers::pi_v; // templated pi + +round_div(7, 4); // 2 (rounded up integer division) +align_floor(7, 4); // 4 +align_ceil(7, 4); // 8 +align(7, 4); // 8 + +clip(x, -10.0, 10.0); // clamp to range +deg2rad(90.0); // π/2 +rad2deg(numbers::pi); // 180.0 + +numeric_div(7, 3); // safe division (avoids div-by-zero) +``` + +--- + +## os - Operating System Utilities + +**Headers:** `clim/os.h`, `clim/aligned_malloc.h`, `clim/barrier.h` +**Target:** `//clim:os` + +### Environ + +```cpp +#include "clim/os.h" + +auto envs = Environ(); // std::map of all env vars +``` + +### aligned_malloc + +```cpp +#include "clim/aligned_malloc.h" + +float* ptr = aligned_malloc(1024, 4096); // 4KB aligned +aligned_free(ptr); + +// Default template returns uint8_t* +auto ptr = aligned_malloc(1024); // default 4KB alignment +``` + +### Barrier + +Thread synchronization (from Eigen): + +```cpp +#include "clim/barrier.h" + +Barrier barrier(3); // wait for 3 notifications +// thread 1 +barrier.Notify(); +// thread 2 +barrier.Notify(); +// thread 3 +barrier.Notify(); +barrier.Wait(); // blocks until all 3 Notify() called +barrier.WaitFor(std::chrono::seconds(5)); // timed wait +barrier.Notified(); // check if notified +``` + +--- + +## path - Cross-Platform Path Handling + +**Headers:** `clim/path.h`, `clim/os_path.h` +**Target:** `//clim:path` + +Python pathlib-style path class: + +```cpp +#include "clim/path.h" + +Path p("/home/user/file.txt"); +p.Exists(); // bool +p.IsFile(); // bool +p.IsDir(); // bool +p.IsAbsolute(); // bool +p.Name(); // "file.txt" +p.Stem(); // "file" +p.Suffix(); // ".txt" +p.Parent(); // Path("/home/user") +p.Str(); // native string +p.AsPosix(); // forward slashes +p.AsUri(); // "file:///home/user/file.txt" + +p.Absolute(); // absolute path +p.Resolve(); // canonical path (resolves symlinks) +Path::CWD(); // current working directory + +p / "subdir"; // path concatenation +p.WithName("new.txt"); // change filename +p.WithSuffix(".csv"); // change extension +p.WithStem("data"); // change stem + +p.Glob("*.txt"); // std::vector matching pattern +p.RGlob("*.txt"); // recursive glob +p.RelativeTo(Path("/home")); // relative path + +Path("/home/user").IsRelativeTo(Path("/home")); // true +``` + +--- + +## reflection - File Path Macros + +**Header:** `clim/reflect.h` +**Target:** `//clim:reflection` (depends on `//clim:string`) + +```cpp +#include "clim/reflect.h" + +FILESTEM("/path/to/file.cpp"); // "file" (basename without extension) +BASENAME("/path/to/file.cpp"); // "file.cpp" (basename) +``` + +--- + +## vt - Vector Tensor Operations + +**Headers:** `clim/vt/vt.h`, `clim/vt/vt_gemm.h`, `clim/vt/vt_nn.h` +**Target:** `//clim:vt` (depends on `//clim:traits`) + +Header-only tensor library for STL containers. Works with `std::vector`, `std::list`, etc. + +### Basic Operations + +```cpp +#include "clim/vt/vt.h" +using namespace vt; + +std::vector a = {1, 2, 3, 4}; +std::vector b = {5, 6, 7, 8}; + +Add(a, b); // element-wise add +Sub(a, b); // element-wise subtract +Mul(a, b); // element-wise multiply +Div(a, b); // element-wise divide +Mul(a, 2.0); // scalar multiply + +Abs(a); // absolute values +ReduceSum(a); // sum +ReduceMean(a); // average +ReduceMax(a); // max +ReduceMin(a); // min +Median(a); // median +Dot(a, b); // dot product +PSNR(a, b); // peak signal-to-noise ratio + +PI(a); // product of all elements (Π) +PI(shape.begin(), shape.end()); // product of shape elements + +Cast>(a); // type conversion + +Arange>(0, 10, 2); // [0, 2, 4, 6, 8] (like numpy.arange) +Ones>(shape); // tensor of ones +Zeros>(shape); // tensor of zeros +RandomN>(100); // random uniform +``` + +### Tensor Index Operations + +```cpp +std::vector shape = {2, 3, 4}; // 3D tensor +std::vector index = {1, 2, 3}; + +// Convert N-D index to flat index +int flat = Index(index, shape); // 1*3*4 + 2*4 + 3 = 23 + +// Convert flat index to N-D index +auto nd = RevIndex(23, shape); // {1, 2, 3} + +// Slice tensor (use -1 to keep all along axis) +auto sliced = SliceAny(data, shape, {-1, 1, 2}); + +// Crop tensor +auto cropped = Crop(data, shape, {0, 1, 0}, {2, 2, 4}); + +// Transpose +auto perm = {2, 1, 0}; // reverse dimensions +auto transposed = Transpose(data, shape, perm); + +// Concatenate +auto combined = Concat(a, shape_a, b, shape_b, axis); + +// Pad +auto padded = Pad(data, shape, {1, 1, 2, 2}); // pad before/after each dim +``` + +### GEMM (Matrix Multiplication) + +```cpp +#include "clim/vt/vt_gemm.h" + +std::vector a = {...}; // shape [B, M, K] +std::vector b = {...}; // shape [B, K, N] +std::vector as = {1, 4, 3}; +std::vector bs = {1, 3, 5}; + +auto result = Gemm(a, as, b, bs); // shape [B, M, N] + +// With accumulation +auto c = Zeros>({1, 4, 5}); +Gemm(a, as, b, bs, c, cs); // c = a @ b + c + +// Scaled Dot-Product Attention (SDPA) +auto attn = SDPA(query, qs, key, ks, value, vs, mask, ms, scale); + +// Flash Attention (blocked algorithm) +auto attn = FlashAttention<64>(query, qs, key, ks, value, vs, mask, ms, scale); +``` + +### Neural Network Operations + +```cpp +#include "clim/vt/vt_nn.h" + +// 2D Convolution +auto conv = Conv(input, {IC, H, W}, weights, {OC, IC, K, K}, pad, groups, dilation, stride); + +// 2D Transposed Convolution +auto deconv = Deconv(input, {IC, H, W}, weights, {IC, OC, K, K}, stride, pad, opad, groups, dilation); + +// Pooling +auto pooled = MaxPool(data, shape, block_size); +auto pooled = AvgPool(data, shape, block_size); + +// Broadcasting +auto result = BroadcastAdd(a, as, b, bs); // NumPy-style broadcasting +auto result = BroadcastMul(a, as, b, bs); + +// Activations +auto activated = Relu(data); +auto activated = Sigmoid(data); +auto activated = Tanh(data); +auto activated = Softmax(data, shape, dim); +``` + +--- + +## base64 - Base64 Encoding/Decoding + +**Header:** `clim/base64.h` +**Target:** `//clim:base64` + +```cpp +#include "clim/base64.h" + +// Encode +std::string encoded = base64::encode(data_ptr, length); + +// Decode +std::vector decoded = base64::decode(encoded_str, encoded_len); +``` + +--- + +## zip - Container Zip Utility + +**Header:** `clim/zip.h` +**Target:** `//clim:zip` + +Zip two containers or tuples: + +```cpp +#include "clim/zip.h" + +std::vector a = {1, 2, 3}; +std::vector b = {'a', 'b', 'c'}; +auto pairs = zip(a, b); // std::vector>: [(1,'a'), (2,'b'), (3,'c')] +// Stops at shorter container + +// Tuple zip +std::tuple t1 = {1, 2.0}; +std::tuple t2 = {'a', 3.0f}; +auto zipped = tuple_zip(t1, t2); // tuple of pairs +``` + +--- + +## Common Patterns + +### Bazel Build + +```bazel +cc_library( + name = "my_lib", + srcs = ["my_lib.cpp"], + hdrs = ["my_lib.h"], + deps = [ + "//clim:argparse", + "//clim:path", + "//clim:vt", + ], +) +``` + +### Include Style + +All headers use `clim/` prefix: + +```cpp +#include "clim/argparse.h" +#include "clim/vt/vt.h" +#include "clim/hasher/hash.h" +``` + +### Namespace + +- Most utilities are in global namespace or `clim::` +- `vt::` namespace for vector tensor operations +- `base64::` namespace for base64 functions diff --git a/.claude/skills/vila-config/SKILL.md b/.claude/skills/vila-config/SKILL.md new file mode 100644 index 0000000..dcfe680 --- /dev/null +++ b/.claude/skills/vila-config/SKILL.md @@ -0,0 +1,111 @@ +--- +name: vila-config +description: Guidance for using the vila/config component - JSON configuration system using nlohmann/json. Use this skill when working with JSON configuration in C++, parsing JSON files, reading configuration from streams, or using vila's Json type alias and configuration utilities. +--- + +# VILA Config - JSON Configuration + +JSON-based configuration system built on nlohmann/json. + +## Headers + +```cpp +#include "vila/config/configuration.h" +``` + +## Bazel Target + +```bazel +deps = ["//vila/config"] +``` + +## Usage + +Vila provides a type alias and convenience functions for nlohmann::json: + +```cpp +#include "vila/config/configuration.h" + +namespace vila { +using Json = nlohmann::json; +} + +// Read JSON from file +vila::Json config = vila::JsonFromFile("config.json"); + +// Read JSON from stream +std::ifstream file("config.json"); +vila::Json config = vila::JsonFromStream(file); + +// Read JSON from string document +std::string json_str = "{\"key\": \"value\"}"; +vila::Json config = vila::JsonFromDoc(json_str); +``` + +## Nlohmann/Json Operations + +The `vila::Json` type alias provides full nlohmann::json functionality: + +```cpp +vila::Json j; +j["name"] = "example"; +j["value"] = 42; +j["array"] = {1, 2, 3}; +j["nested"]["key"] = "nested_value"; + +// Access values +std::string name = j["name"]; +int value = j["value"]; + +// Check if key exists +if (j.contains("optional_key")) { ... } + +// Get value with default +int val = j.value("key", 0); // returns 0 if key missing + +// Parse string +vila::Json j = vila::Json::parse("{\"key\": 123}"); + +// Serialize +std::string str = j.dump(); // compact +std::string str = j.dump(2); // pretty-print with 2-space indent + +// Type checking +j.is_string(); +j.is_number(); +j.is_array(); +j.is_object(); +j.is_null(); + +// Array operations +for (auto& element : j["array"]) { ... } +j["array"].push_back(4); +j["array"].size(); + +// Object operations +for (auto& [key, value] : j.items()) { ... } +j.erase("key"); +``` + +## Configuration Pattern + +Common pattern for application configuration: + +```cpp +struct AppConfig { + std::string name; + int port; + std::vector hosts; + + static AppConfig FromJson(const vila::Json& j) { + AppConfig cfg; + cfg.name = j.value("name", "default"); + cfg.port = j.value("port", 8080); + cfg.hosts = j.value("hosts", std::vector{}); + return cfg; + } +}; + +vila::Json config_json = vila::JsonFromFile("app.json"); +AppConfig config = AppConfig::FromJson(config_json); +``` diff --git a/.claude/skills/vila-graph/SKILL.md b/.claude/skills/vila-graph/SKILL.md new file mode 100644 index 0000000..ece8c01 --- /dev/null +++ b/.claude/skills/vila-graph/SKILL.md @@ -0,0 +1,214 @@ +--- +name: vila-graph +description: Guidance for using the vila/graph component - template header-only DAG (Directed Acyclic Graph) library. Use this skill when working with graph data structures, directed graphs, topological sorting, DFS/BFS traversal, cycle detection, path finding, or graph algorithms in C++. +--- + +# VILA Graph - Template DAG Library + +Header-only graph library with directed/undirected graphs and algorithms. + +## Headers + +```cpp +#include "vila/graph/graph.h" // Undirected graph +#include "vila/graph/digraph.h" // Directed graph +#include "vila/graph/dag.h" // DAG algorithms +#include "vila/graph/node.h" // Node container +#include "vila/graph/traversal.h" // DFS/BFS traversal +#include "vila/graph/route.h" // Path finding +``` + +## Bazel Target + +```bazel +deps = [ + "//vila/graph", + "//vila/graph:dag", + "//vila/graph:route", + "//vila/graph:traversal", +] +``` + +## Graph Types + +### Node Container + +```cpp +#include "vila/graph/node.h" + +// Node holds unique_ptr to instance T +vila::Node node(new int(42)); +vila::Node node(std::make_unique(42)); + +node.get(); // returns int* (raw pointer) +node.operator->(); // STL-style access +``` + +### Graph (Undirected) + +```cpp +#include "vila/graph/graph.h" + +vila::Graph g("main"); // named graph + +// Add nodes (must move ownership) +g.AddNode(vila::Node(new int(1))); +g.AddNode(vila::Node(new int(2))); + +// Add nodes from container +std::vector> nodes = {...}; +g.AddNodes(std::move(nodes)); + +// Add edges (between node pointers) +int* n1 = g.GetNodes().begin(); // get index +int* n2 = ...; +g.AddEdge(n1, n2); + +// Query +g.NumNodes(); +g.NumEdges(); +g.contains(node_ptr); // check if node exists +g.contains(u, v); // check if edge exists +g.Adjacent(node_ptr); // get neighbors + +// Properties (optional) +g.SetProperty(node_ptr, MyProp{}); +g.GetProperty(node_ptr); + +// Subgraphs (hierarchical) +g.AddGraph(vila::Graph("subgraph")); // nested graph +g.RemoveGraph("subgraph"); +g.PrintHierarchy(); // show structure + +// Create shallow copy (for algorithms) +auto copy = g.ShallowCopy(); +auto subg = g.Subgraph(node_set); +``` + +### DiGraph (Directed) + +```cpp +#include "vila/graph/digraph.h" + +vila::DiGraph dg("main"); + +dg.AddEdge(u, v); // directed: u -> v + +dg.Successor(u); // nodes u points to +dg.Predecessor(u); // nodes pointing to u +dg.InDegree(u); // number of incoming edges +dg.OutDegree(u); // number of outgoing edges + +dg.Reverse(); // reverse all edge directions + +// Shallow copy and subgraph +auto copy = dg.ShallowCopy(); +auto subg = dg.Subgraph(nodes); +``` + +## DAG Algorithms (dag.h) + +```cpp +#include "vila/graph/dag.h" + +// Topological sort +bool error = false; +auto order = vila::TopologicalSort(dg, &error); +// order is deque of node indices; error=true if cyclic + +// All topological sorts (Knuth algorithm) +auto all_orders = vila::AllTopologicalSorts(dg, &error); + +// Weighted topological sort (cluster by property) +auto order = vila::WeightedTopologicalSort(dg, &error); + +// Strongly connected components (Kosaraju) +auto sccs = vila::KosarajuStronglyConnectedComponents(dg); +// returns deque of unordered_set of node indices + +// Longest path in DAG +auto path = vila::DagLongestPath(dg); +auto path = vila::DagLongestPath(dg, [](auto u, auto v) { return weight; }); + +// Simple cycles (Johnson's algorithm) +auto cycles = vila::SimpleCycles(dg); +``` + +## Traversal (traversal.h) + +```cpp +#include "vila/graph/traversal.h" + +// DFS edges +auto edges = vila::DfsEdges(dg); // all nodes +auto edges = vila::DfsEdges(dg, {start_node}, depth); // from sources + +// DFS with labels +auto labeled = vila::DfsLabeledEdges(dg); +// returns deque of (u, v, edge_label) tuples +// edge_label: forward, nontree, reverse + +// DFS preorder/postorder +auto preorder = vila::DfsPreorder(dg); +auto preorder = vila::DfsPreorder(dg, {start_node}); +auto postorder = vila::DfsPostorder(dg); + +// BFS edges (works on undirected graphs too) +auto edges = vila::BfsEdges(g); +auto edges = vila::BfsEdges(g, {start_node}, depth_limit); +``` + +## Path Finding (route.h) + +```cpp +#include "vila/graph/route.h" + +// Check if nodes form simple path +bool is_path = vila::IsSimplePath(g, node_sequence); + +// All simple paths from source to target +auto paths = vila::AllSimplePaths(g, source, target); +auto paths = vila::AllSimplePaths(g, source, target, depth_limit); + +// All paths from source to any leaf +auto paths = vila::AllSimplePaths(dg, source); + +// All root-to-leaf paths +auto paths = vila::RootToLeafPaths(dg); +``` + +## Indexing + +Default `AddressIndex` uses raw pointers as indices: + +```cpp +vila::AddressIndex::index_type = int*; + +// Custom indexer +struct MyIndex { + using index_type = int; // or any hashable type + index_type operator()(const Node& node) const; +}; +``` + +## Common Patterns + +### Pipeline/DAG Pattern + +```cpp +vila::DiGraph pipeline("pipeline"); +for (auto& task : tasks) { + pipeline.AddNode(vila::Node(new Task(std::move(task)))); +} +for (auto& [from, to] : dependencies) { + pipeline.AddEdge(from, to); +} + +bool cyclic = false; +auto order = vila::TopologicalSort(pipeline, &cyclic); +if (cyclic) { /* handle cycle */ } + +for (auto* task_ptr : order) { + task_ptr->execute(); +} +``` diff --git a/.claude/skills/vila-hook/SKILL.md b/.claude/skills/vila-hook/SKILL.md new file mode 100644 index 0000000..a7b3a2d --- /dev/null +++ b/.claude/skills/vila-hook/SKILL.md @@ -0,0 +1,117 @@ +--- +name: vila-hook +description: Guidance for using the vila/hook component - Windows DLL hooking via Microsoft Detours library. Use this skill when hooking Windows API functions, intercepting DLL calls, or using Detours for function interception on Windows only. +--- + +# VILA Hook - Windows DLL Hooking + +Windows-only component for function hooking using Microsoft Detours. + +## Headers + +```cpp +#include "vila/hook/detours/detours.h" // Detours library wrapper +``` + +## Bazel Target + +```bazel +deps = ["//vila/hook"] +# Note: Only builds on Windows (@platforms//os:windows) +``` + +## Dependencies + +- `vila/hook/detours/` contains Microsoft Detours library (MIT license) +- Windows-only: uses `target_compatible_with = ["@platforms//os:windows"]` + +## Usage + +Detours is Microsoft's library for binary function interception: + +```cpp +#include "vila/hook/detours/detours.h" + +// Target function to hook +int OriginalFunction(int arg); + +// Hook function (replacement) +int HookedFunction(int arg) { + // Do something before original + int result = OriginalFunction(arg); // call original + // Do something after + return result; +} + +// Install hook +DetourTransactionBegin(); +DetourUpdateThread(GetCurrentThread()); +DetourAttach(&(PVOID&)OriginalFunction, HookedFunction); +DetourTransactionCommit(); + +// Remove hook +DetourTransactionBegin(); +DetourUpdateThread(GetCurrentThread()); +DetourDetach(&(PVOID&)OriginalFunction, HookedFunction); +DetourTransactionCommit(); +``` + +## Hooking Windows API + +```cpp +#include +#include "vila/hook/detours/detours.h" + +// Original function pointer +static BOOL (WINAPI* OriginalCreateFileW)( + LPCWSTR, DWORD, DWORD, LPSECURITY_ATTRIBUTES, DWORD, DWORD, HANDLE +) = CreateFileW; + +// Hook function +BOOL WINAPI HookedCreateFileW( + LPCWSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, + LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, + DWORD dwFlagsAndAttributes, HANDLE hTemplateFile +) { + LOGI("CreateFileW called: {}", lpFileName); + return OriginalCreateFileW( + lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, + dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile + ); +} + +// Install +void InstallHooks() { + DetourTransactionBegin(); + DetourUpdateThread(GetCurrentThread()); + DetourAttach(&(PVOID&)OriginalCreateFileW, HookedCreateFileW); + DetourTransactionCommit(); +} +``` + +## Transaction Pattern + +Detours uses transaction-based hook installation for safety: + +```cpp +// Multiple hooks in single transaction +DetourTransactionBegin(); +DetourUpdateThread(GetCurrentThread()); + +DetourAttach(&(PVOID&)Func1, HookFunc1); +DetourAttach(&(PVOID&)Func2, HookFunc2); +DetourAttach(&(PVOID&)Func3, HookFunc3); + +LONG error = DetourTransactionCommit(); +if (error != NO_ERROR) { + // Handle error - hooks not installed +} +``` + +## Notes + +- Detours can hook any function with known signature +- Works on both x86 and x64 Windows +- Original function pointer must be preserved for calling through +- Hook transactions are atomic - either all succeed or none +- Thread-safe: `DetourUpdateThread` ensures correct thread state diff --git a/.claude/skills/vila-logging/SKILL.md b/.claude/skills/vila-logging/SKILL.md new file mode 100644 index 0000000..fc602c9 --- /dev/null +++ b/.claude/skills/vila-logging/SKILL.md @@ -0,0 +1,147 @@ +--- +name: vila-logging +description: Guidance for using the vila/logging component - unified logging system with WPP (Windows Trace Preprocessing) support and fmt formatting. Use this skill when implementing logging in C++, using LOGT/LOGD/LOGI/LOGW/LOGE macros, or capturing source code locations and backtraces. +--- + +# VILA Logging - Unified Log System + +Singleton logging system with trace/debug/info/warning/error levels, fmt formatting, and optional WPP support. + +## Headers + +```cpp +#include "vila/logging/logger.h" +#include "vila/logging/code_location.h" // Source location capture +``` + +## Bazel Target + +```bazel +deps = ["//vila/logging:logger"] +# For code_location: +deps = ["//vila/logging:code_location"] +``` + +## Build Flags + +- `--enable_wpp`: Enable Windows WPP logging (default: false) +- `define VILA_USE_LOG`: Enable logging macros (auto-defined when `--with_log=true`) + +## Logger Class + +```cpp +#include "vila/logging/logger.h" + +namespace vila { +class Logger { + enum { + LOG_LEVEL_TRACE = 0, + LOG_LEVEL_DEBUG, + LOG_LEVEL_INFO, + LOG_LEVEL_WARN, + LOG_LEVEL_ERROR, + }; +}; +} + +// Get singleton +vila::Logger* logger = vila::Logger::Get(); + +// Set log level (positive=console, negative=file) +vila::Logger::SetLoggerLevel(2); // LOG_LEVEL_INFO and above to console +vila::Logger::SetLoggerLevel(-2); // LOG_LEVEL_INFO and above to file + +// Check if should log +if (vila::Logger::ShouldLog(vila::Logger::LOG_LEVEL_DEBUG)) { ... } + +// Nested logger (with scoped name) +vila::Logger* nested = logger->Nest("module_name"); + +// Log methods (use fmt formatting) +logger->Trace("value = {}", value); +logger->Debug("processing item {}", id); +logger->Info("operation completed"); +logger->Warning("unexpected value: {}", val); +logger->Error("failed to open file: {}", filename); + +// Flush buffered logs +vila::Logger::Flush(); + +// Drop logger (cleanup) +vila::Logger::Drop(); +``` + +## Logging Macros + +When `VILA_USE_LOG` is defined: + +```cpp +// Global logger macros +LOGT("trace message {}", arg); // Trace +LOGD("debug message {}", arg); // Debug +LOGI("info message {}", arg); // Info +LOGW("warning {}", arg); // Warning +LOGE("error {}", arg); // Error + +// Nested logger macros (scoped with file stem) +VLOGT("trace {}", arg); // Uses FILESTEM(__FILE__) as nested name +VLOGD("debug {}", arg); +VLOGI("info {}", arg); +VLOGW("warning {}", arg); +VLOGE("error {}", arg); +``` + +## Code Location + +Captures source location for error reporting: + +```cpp +#include "vila/logging/code_location.h" + +vila::CodeLocation loc(__FILE__, __LINE__, __FUNCTION__); +std::string str = loc.ToString(); // "file.cpp (42) void func()" + +// Capture backtrace +std::vector bt = vila::CaptureBackTrace(); + +// Format with fmt +fmt::format("Error at {}", loc); +``` + +## Log Level Guidance + +| Level | Use Case | +|---------|---------------------------------------| +| Trace | Detailed execution flow, enter/exit | +| Debug | Development info, variable values | +| Info | Normal operation milestones | +| Warning | Unexpected but recoverable situations | +| Error | Failures, exceptions | + +## Pattern: Scoped Logging + +```cpp +void ProcessData(Data* data) { + VLOGI("ProcessData start, size={}", data->size()); + // ... processing ... + VLOGD("intermediate result={}", result); + // ... more processing ... + VLOGI("ProcessData complete"); +} +``` + +## Pattern: Error with Location + +```cpp +#include "vila/logging/code_location.h" +#include "vila/logging/logger.h" + +void HandleError(const std::string& msg) { + vila::CodeLocation loc(__FILE__, __LINE__, __FUNCTION__); + auto bt = vila::CaptureBackTrace(); + LOGE("Error at {}: {}", loc.ToString(), msg); + for (const auto& frame : bt) { + LOGT(" {}", frame); + } +} +``` diff --git a/.claude/skills/vila-profiling/SKILL.md b/.claude/skills/vila-profiling/SKILL.md new file mode 100644 index 0000000..2e4f393 --- /dev/null +++ b/.claude/skills/vila-profiling/SKILL.md @@ -0,0 +1,184 @@ +--- +name: vila-profiling +description: Guidance for using the vila/profiling component - profiling tools including timer, ITT instrumentation, and tracing utilities. Use this skill when profiling C++ code performance, measuring execution time, using Intel ITT API, or adding trace markers for performance analysis. +--- + +# VILA Profiling - Performance Tools + +Profiling utilities for measuring execution time, ITT instrumentation, and tracing. + +## Headers + +```cpp +#include "vila/profiling/timer.h" // CPU profiler +#include "vila/profiling/itt.h" // Intel ITT instrumentation +#include "vila/profiling/trace.h" // Binary tracing +``` + +## Bazel Targets + +```bazel +deps = [ + "//vila/profiling:timer", + "//vila/profiling:itt", + "//vila/profiling:tracer", +] +``` + +## Profiler (timer.h) + +Singleton profiler for recording CPU execution time: + +```cpp +#include "vila/profiling/timer.h" + +namespace vila { +enum class ProfileFormat { text, json }; +} + +// Get singleton +vila::Profiler* profiler = vila::Profiler::Instance(); + +// Manual profiling +profiler->StartProfile("operation_name"); +// ... do work ... +profiler->EndProfile("operation_name"); + +// Get recorded times +std::vector times = profiler->GetProfile("operation_name"); +// times are in nanoseconds + +// Add custom timing +profiler->AddProfile("custom", std::chrono::nanoseconds(123456)); + +// Print analysis +profiler->PrintAnalyze(); // text format +profiler->PrintAnalyze(vila::ProfileFormat::json); // JSON format +``` + +## AutoProfiler (RAII) + +```cpp +#include "vila/profiling/timer.h" + +// Automatic scope profiling +void MyFunction() { + vila::AutoProfiler prof("MyFunction"); + // ... work ... + // Profiler.EndProfile called on destruction +} +``` + +## Windows Timer Period + +More accurate timing on Windows: + +```cpp +#ifdef _WIN32 +#include "vila/profiling/timer.h" + +// RAII timer period adjustment +vila::AutoSetTimerPeriod timer_period; +// Higher accuracy timing active for scope + +// Manual control +vila::SetTimerPeriod::Instance()->Start(); +vila::SetTimerPeriod::Instance()->End(); +#endif +``` + +## ITT Instrumentation (itt.h) + +Intel ITT API for VTune/Intel Profiler integration: + +```cpp +#include "vila/profiling/itt.h" + +// Create domain +vila::itt::domain_t* domain = vila::itt::DomainManager::CreateDomain("my_domain"); + +// Frame scope marking +void ProcessFrame() { + vila::itt::FrameScope frame(domain); // marks frame boundary + // ... frame processing ... + // Frame end on destruction +} + +// Or use string name +vila::itt::FrameScope frame("my_domain"); +``` + +## Binary Tracer (trace.h) + +Trace binary data for debugging: + +```cpp +#include "vila/profiling/trace.h" + +// Environment variables: +// VILA_TRACE_DEBUG=N - start frame N +// VILA_TRACE_DEBUG=N,M - frames N through M + +vila::BinTracer& tracer = vila::BinTracer::Instance(); + +// Step frame counter +tracer.StepFrameId(); + +// Check if should trace current frame +if (tracer.ShouldTrace()) { + // Trace binary data with shape + tracer.Trace("tensor_output", data_ptr, height, width, channels); +} + +// Type-specific overloads +tracer.Trace("char_data", char_ptr, shape); +tracer.Trace("int_data", int_ptr, shape); +tracer.Trace("float_data", float_ptr, shape); +tracer.Trace("double_data", double_ptr, shape); +``` + +## Debug Trace Macro + +```cpp +#include "vila/profiling/trace.h" + +#ifdef _DEBUG +// Logs function entry and exit at trace level +void MyFunction() { + DEBUGTRACE(); // Logs "MyFunction +" on entry, "MyFunction -" on exit + // ... work ... +} +#else +#define DEBUGTRACE(...) // No-op in release +#endif +``` + +## Common Patterns + +### Benchmark a Function + +```cpp +void BenchmarkOperation() { + vila::Profiler::Instance()->StartProfile("benchmark"); + for (int i = 0; i < 1000; i++) { + vila::AutoProfiler prof("inner_op"); + OperationToMeasure(); + } + vila::Profiler::Instance()->EndProfile("benchmark"); + vila::Profiler::Instance()->PrintAnalyze(); +} +``` + +### Mark Pipeline Frames + +```cpp +void ProcessPipeline() { + static auto* domain = vila::itt::DomainManager::CreateDomain("pipeline"); + + while (running) { + vila::itt::FrameScope frame(domain); + ProcessFrame(); + vila::BinTracer::Instance()->StepFrameId(); + } +} +``` diff --git a/.claude/skills/vila-status/SKILL.md b/.claude/skills/vila-status/SKILL.md new file mode 100644 index 0000000..ba5d352 --- /dev/null +++ b/.claude/skills/vila-status/SKILL.md @@ -0,0 +1,237 @@ +--- +name: vila-status +description: Guidance for using the vila/status component - Status and StatusOr error handling pattern similar to absl::Status. Use this skill when implementing error handling in C++, using StatusOr for return values, creating error Status objects, or handling ErrorCode enum values. +--- + +# VILA Status - Error Handling + +Status and StatusOr pattern for error handling, similar to absl::Status/absl::StatusOr. + +## Headers + +```cpp +#include "vila/status/status.h" // Status class and ErrorCode +#include "vila/status/statusor.h" // StatusOr template +``` + +## Bazel Target + +```bazel +deps = ["//vila/status"] +``` + +## ErrorCode Enum + +```cpp +#include "vila/status/status.h" + +namespace vila { +enum class ErrorCode : int { + warning = 1, // Not an error + success = 0, // No error + unknown = -1, + invalid_configuration = -2, + invalid_arguments = -3, + object_not_found = -4, + type_error = -5, + unsupported = -6, + bad_alloc = -7, + calculator_init_failed = -8, + calculator_aborted = -9, + wait_time_out = -10, + invalid_call = -11, + calculator_skip = -12, + null_pointer = -13, + not_implemented = -14, + // Hardware-specific errors + d3d_internal_error = -15, + ocl_internal_error = -16, + ze_internal_error = -17, + vpe_internal_error = -18, + // Memory errors + invalid_memory_shape = -19, + invalid_memory_layout = -20, + invalid_memory_format = -21, + context_changed = -30, + internal_error = -99, +}; +} + +// Convert to string +std::string str = vila::StatusCodeToString(code); + +// Format with fmt +fmt::format("Error: {}", code); +``` + +## Status Class + +```cpp +#include "vila/status/status.h" + +// Success status +vila::Status ok = vila::Success(); +vila::Status ok; // default constructor = success + +ok.Ok(); // true for success +ok.Fatal(); // true for error (not warning) + +// Error status +vila::Status err(vila::ErrorCode::invalid_arguments, "argument must be positive"); +err.Code(); // ErrorCode::invalid_arguments +err.RawCode(); // -3 +err.ToString(); // "invalid_arguments: argument must be positive" + +// Comparison +if (status == vila::ErrorCode::success) { ... } + +// Convert error to warning +vila::Status warning = vila::ToWarning(err); +warning.Ok(); // false +warning.Fatal(); // false (it's a warning, not error) +``` + +## Error Constructor Functions + +```cpp +// Each returns Status with formatted message +vila::Status Unknown("unknown error: {}", detail); +vila::Status InvalidConfiguration("config missing key: {}", key); +vila::Status InvalidArguments("arg {} out of range", arg); +vila::Status ObjectNotFound("object '{}' not found", name); +vila::Status TypeError("expected int, got {}", type); +vila::Status Unsupported("operation '{}' not supported", op); +vila::Status BadAlloc("failed to allocate {} bytes", size); +vila::Status NullPointer("pointer is null at {}", location); +vila::Status NotImplemented("feature '{}' not implemented", feature); +vila::Status InternalError("internal error: {}", msg); + +// Hardware-specific +vila::Status D3dInternalError("D3D error: {}", msg); +vila::Status OclInternalError("OpenCL error: {}", msg); +vila::Status ZeInternalError("Level-Zero error: {}", msg); + +// Memory-specific +vila::Status InvalidShape("shape {} invalid", shape); +vila::Status InvalidLayout("layout mismatch"); +vila::Status InvalidFormat("format {} unsupported", fmt); + +// Other +vila::Status CalculatorInitFailed("init failed for {}", name); +vila::Status CalculatorAborted("calculator {} aborted", name); +vila::Status CalculatorSkip("skipping {}", name); +vila::Status WaitTimeout("timeout after {} ms", ms); +vila::Status ContextChanged("context changed"); +``` + +## StatusOr + +```cpp +#include "vila/status/statusor.h" + +// StatusOr is either a value or an error +vila::StatusOr result = ComputeValue(); + +// Check success +if (result.Ok()) { + int value = result.ValueOrDie(); + int value = std::move(result).ValueOrDie(); // move value +} else { + vila::Status status = result.status(); + HandleError(status); +} + +// Ignore error (suppress unused warnings) +result.IgnoreError(); + +// Return from function +vila::StatusOr> CreateObject(int arg) { + if (arg < 0) { + return vila::InvalidArguments("arg must be non-negative"); + } + return std::make_unique(arg); // implicit conversion +} + +// Consume value (moves out) +int value = result.ConsumeValueOrDie(); + +// Conversion between StatusOr types +vila::StatusOr d = ComputeDouble(); +vila::StatusOr f = d; // implicit conversion if T convertible +``` + +## VilaFatalException + +```cpp +#include "vila/status/status.h" + +// Exception for fatal errors (throw sparingly) +throw vila::VilaFatalException( + vila::CodeLocation(__FILE__, __LINE__, __FUNCTION__), + "fatal error message", + vila::CaptureBackTrace() +); +``` + +## Common Patterns + +### Function Return Pattern + +```cpp +vila::StatusOr LoadData(const std::string& path) { + if (path.empty()) { + return vila::InvalidArguments("path cannot be empty"); + } + + Data* data = TryLoad(path); + if (!data) { + return vila::ObjectNotFound("data not found at {}", path); + } + + return data; // success +} + +// Caller +vila::StatusOr result = LoadData("data.bin"); +if (!result.Ok()) { + LOGE("Failed: {}", result.status()); + return result.status(); +} +Data* data = result.ValueOrDie(); +``` + +### Chained Operations + +```cpp +vila::Status ProcessPipeline() { + vila::StatusOr input = ReadInput(); + if (!input.Ok()) return input.status(); + + vila::StatusOr transformed = Transform(input.ValueOrDie()); + if (!transformed.Ok()) return transformed.status(); + + vila::StatusOr output = WriteOutput(transformed.ValueOrDie()); + if (!output.Ok()) return output.status(); + + return vila::Success(); +} +``` + +### Factory Pattern + +```cpp +class WidgetFactory { +public: + static vila::StatusOr> Create(const Config& cfg) { + if (!cfg.Validate()) { + return vila::InvalidConfiguration("invalid config"); + } + auto widget = std::make_unique(); + vila::Status init_status = widget->Initialize(cfg); + if (!init_status.Ok()) { + return init_status; + } + return widget; + } +}; +``` diff --git a/.claude/skills/vila-widget/SKILL.md b/.claude/skills/vila-widget/SKILL.md new file mode 100644 index 0000000..46f9020 --- /dev/null +++ b/.claude/skills/vila-widget/SKILL.md @@ -0,0 +1,197 @@ +--- +name: vila-widget +description: Guidance for using the vila/widget component - registration system for factory pattern and plugin architecture. Use this skill when implementing factory registries, registering plugin implementations, using GlobalFactoryRegistry, or managing RegistrationToken for lifecycle control. +--- + +# VILA Widget - Registration System + +Factory registry pattern for plugin architectures and runtime registration. + +## Headers + +```cpp +#include "vila/widget/registration.h" // FunctionRegistry, GlobalFactoryRegistry +#include "vila/widget/registration_token.h" // RegistrationToken, RAII Unregister +``` + +## Bazel Target + +```bazel +deps = ["//vila/widget:registration"] +``` + +## GlobalFactoryRegistry + +Singleton registry for factory functions: + +```cpp +#include "vila/widget/registration.h" + +// Define registry type +using WidgetRegistry = vila::GlobalFactoryRegistry< + std::unique_ptr, // return type + std::unique_ptr, // arg1 + const Config* // arg2 +>; + +// Register factory function +static auto registration = vila::RegistrationToken( + WidgetRegistry::Register("MyWidget", + [](std::unique_ptr g, const Config* c) { + return std::make_unique(std::move(g), c); + }, + __FILE__ // optional: source location + ) +); + +// Create by name +vila::StatusOr> widget = + WidgetRegistry::CreateByName("MyWidget", gadget, config); + +// Check if registered +bool exists = WidgetRegistry::IsRegistered("MyWidget"); + +// Get all registered names +auto names = WidgetRegistry::GetRegisteredNames(); + +// Get source location +std::string loc = WidgetRegistry::GetLocationByName("MyWidget"); +``` + +## Registration Macros + +```cpp +#include "vila/widget/registration.h" + +// Register with unqualified name +REGISTER_FACTORY_FUNCTION(WidgetRegistry, MyWidget, + [](Args... args) { return std::make_unique(args...); }); + +// Register with qualified name and custom variable +REGISTER_FACTORY_FUNCTION_QUALIFIED(WidgetRegistry, my_widget_reg, ::my_ns::MyWidget, + [](Args... args) { return std::make_unique(args...); }); +``` + +## RegistrationToken + +Token for managing registration lifetime: + +```cpp +#include "vila/widget/registration_token.h" + +// Create token with unregister function +vila::RegistrationToken token([]() { Cleanup(); }); + +// Unregister manually +token.Unregister(); // safe to call multiple times + +// Combine multiple tokens +auto combined = vila::RegistrationToken::Combine({token1, token2}); +combined.Unregister(); // unregisters all +``` + +## RAII Unregister + +Automatic cleanup on scope exit: + +```cpp +#include "vila/widget/registration_token.h" + +// RAII wrapper +vila::Unregister guard(WidgetRegistry::Register("TempWidget", factory)); +// ... use widget ... +// guard destructor calls Unregister() + +// Reset with new token (unregisters old first) +guard.Reset(new_token); + +// Move ownership +vila::Unregister other = std::move(guard); +``` + +## FunctionRegistry + +Non-singleton registry for local use: + +```cpp +#include "vila/widget/registration.h" + +vila::FunctionRegistry registry; + +// Register function +auto token = registry.Register("calc", [](std::string s) { return s.size(); }); + +// Invoke +int result = registry.Invoke("calc", "hello"); + +// Check and list +bool exists = registry.IsRegistered("calc"); +auto names = registry.GetRegisteredNames(); + +// Get location +std::string loc = registry.GetLocation("calc"); +``` + +## Plugin Pattern + +```cpp +// Define interface +class Plugin { +public: + virtual ~Plugin() = default; + virtual void Execute() = 0; +}; + +// Registry for plugins +using PluginRegistry = vila::GlobalFactoryRegistry>; + +// Plugin implementation +class MyPlugin : public Plugin { +public: + static std::unique_ptr Create() { + return std::make_unique(); + } + + void Execute() override { /* ... */ } +}; + +// Register +REGISTER_FACTORY_FUNCTION_QUALIFIED(PluginRegistry, my_plugin, ::MyPlugin, MyPlugin::Create); + +// Load and use +void LoadPlugin(const std::string& name) { + auto plugin = PluginRegistry::CreateByName(name); + if (plugin.Ok()) { + plugin.ValueOrDie()->Execute(); + } +} + +// List available plugins +for (const auto& name : PluginRegistry::GetRegisteredNames()) { + std::cout << "Available: " << name << "\n"; +} +``` + +## Testing Pattern + +```cpp +// Inject mock for testing +class MockWidget : public Widget { /* ... */ }; + +vila::Unregister mock_reg(WidgetRegistry::Register( + "MockWidget", + [](auto args) { return std::make_unique(); } +)); + +// Test with mock +auto widget = WidgetRegistry::CreateByName("MockWidget", args); +// mock_reg unregisters automatically at scope end +``` + +## Notes + +- `GlobalFactoryRegistry` is a singleton - one registry per `R, Args...` signature +- Registration names should be qualified C++ names (e.g., `::my_ns::MyClass`) +- Macro registrations are static - persist until program exit +- Manual `Register()` returns token for temporary/test registrations +- Thread-safe: internal mutex protects all operations diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 35e398c..d80ed46 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -14,7 +14,7 @@ repos: - id: requirements-txt-fixer - repo: https://github.com/astral-sh/ruff-pre-commit # Ruff version. - rev: v0.15.8 + rev: v0.15.12 hooks: # Run the linter. - id: ruff-check @@ -26,7 +26,7 @@ repos: hooks: - id: codespell args: [-I=.github/WORDS_BAG.txt, -w] - exclude: (\.(diff|patch)$|graphfile_generated.py|(.*\.bzl\.tpl)|(.*json.hpp|.*json_fwd.hpp)|(vila/hook/detours/.*)) + exclude: ((\.claude/.*)|(.*\.bzl\.tpl)|(.*json.hpp|.*json_fwd.hpp)|(vila/hook/detours/.*)) - repo: https://github.com/cmake-lint/cmake-lint rev: 1.4.3 hooks: diff --git a/MODULE.bazel b/MODULE.bazel index 4c1f1cf..f03b01d 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -20,6 +20,7 @@ bazel_dep(name = "bazel_skylib", version = "1.9.0") bazel_dep(name = "bazel_features", version = "1.43.0") bazel_dep(name = "rules_cc", version = "0.2.17") bazel_dep(name = "rules_python", version = "1.9.0") +bazel_dep(name = "rules_shell", version = "0.8.0") bazel_dep(name = "rules_foreign_cc", version = "0.15.1") bazel_dep(name = "googletest", version = "1.17.0", repo_name = "com_google_googletest") bazel_dep(name = "google_benchmark", version = "1.9.2", repo_name = "com_google_benchmark") @@ -40,29 +41,29 @@ pip.parse( ) use_repo(pip, "vila_pip_deps") -wdk_config_ext = use_extension("@vila//vila/bazel/bzlmod:extensions.bzl", "wdk_configure_extension") +wdk_config_ext = use_extension("@vila//bazel/bzlmod:extensions.bzl", "wdk_configure_extension") use_repo(wdk_config_ext, "local_config_wdk") -bullseye_config_ext = use_extension("@vila//vila/bazel/bzlmod:extensions.bzl", "bullseye_configure_extension") +bullseye_config_ext = use_extension("@vila//bazel/bzlmod:extensions.bzl", "bullseye_configure_extension") use_repo(bullseye_config_ext, "local_config_bullseye") -spdlog_ext = use_extension("@vila//vila/bazel/bzlmod:extensions.bzl", "spdlog_extension") +spdlog_ext = use_extension("@vila//bazel/bzlmod:extensions.bzl", "spdlog_extension") use_repo(spdlog_ext, "spdlog") -rangev3_ext = use_extension("@vila//vila/bazel/bzlmod:extensions.bzl", "rangev3_extension") +rangev3_ext = use_extension("@vila//bazel/bzlmod:extensions.bzl", "rangev3_extension") use_repo(rangev3_ext, "rangev3") -ittapi_ext = use_extension("@vila//vila/bazel/bzlmod:extensions.bzl", "ittapi_extension") +ittapi_ext = use_extension("@vila//bazel/bzlmod:extensions.bzl", "ittapi_extension") use_repo(ittapi_ext, "ittapi") -hedron_ext = use_extension("@vila//vila/bazel/bzlmod:extensions.bzl", "hedron_extension") +hedron_ext = use_extension("@vila//bazel/bzlmod:extensions.bzl", "hedron_extension") use_repo(hedron_ext, "hedron_compile_commands") -sycl_config_ext = use_extension("@vila//vila/bazel/bzlmod:extensions.bzl", "sycl_configure_extension") +sycl_config_ext = use_extension("@vila//bazel/bzlmod:extensions.bzl", "sycl_configure_extension") use_repo(sycl_config_ext, "local_config_sycl") # TVM FFI support (optional - requires: pip install apache-tvm-ffi) -tvm_ffi_ext = use_extension("@vila//vila/bazel/bzlmod:extensions.bzl", "tvm_ffi_extension") +tvm_ffi_ext = use_extension("@vila//bazel/bzlmod:extensions.bzl", "tvm_ffi_extension") use_repo(tvm_ffi_ext, "tvm_ffi") register_toolchains( diff --git a/README.md b/README.md index fad4191..ca9f611 100644 --- a/README.md +++ b/README.md @@ -43,15 +43,15 @@ http_archive( url = "https://github.com/llteco/vila/archive/{commit}.zip", ) -load("@vila//vila:workspace0.bzl", vila_workspace0 = "workspace") +load("@vila//:workspace0.bzl", vila_workspace0 = "workspace") vila_workspace0() -load("@vila//vila:workspace1.bzl", vila_workspace1 = "workspace") +load("@vila//:workspace1.bzl", vila_workspace1 = "workspace") vila_workspace1() -load("@vila//vila:workspace2.bzl", vila_workspace2 = "workspace") +load("@vila//:workspace2.bzl", vila_workspace2 = "workspace") vila_workspace2() diff --git a/WORKSPACE b/WORKSPACE index 361fa02..181d36d 100644 --- a/WORKSPACE +++ b/WORKSPACE @@ -16,15 +16,15 @@ limitations under the License. workspace(name = "vila") -load("@vila//vila:workspace0.bzl", vila_workspace0 = "workspace") +load("@vila//:workspace0.bzl", vila_workspace0 = "workspace") vila_workspace0() -load("@vila//vila:workspace1.bzl", vila_workspace1 = "workspace") +load("@vila//:workspace1.bzl", vila_workspace1 = "workspace") vila_workspace1() -load("@vila//vila:workspace2.bzl", vila_workspace2 = "workspace") +load("@vila//:workspace2.bzl", vila_workspace2 = "workspace") vila_workspace2( sycl = False, @@ -62,3 +62,9 @@ pip_parse( load("@vila_pip_deps//:requirements.bzl", "install_deps") install_deps() + +# load("@rules_shell//shell:repositories.bzl", "rules_shell_dependencies", "rules_shell_toolchains") + +# rules_shell_dependencies() + +# rules_shell_toolchains() diff --git a/vila/bazel/BUILD.bazel b/bazel/BUILD.bazel similarity index 100% rename from vila/bazel/BUILD.bazel rename to bazel/BUILD.bazel diff --git a/vila/bazel/bzlmod/BUILD.bazel b/bazel/bzlmod/BUILD.bazel similarity index 100% rename from vila/bazel/bzlmod/BUILD.bazel rename to bazel/bzlmod/BUILD.bazel diff --git a/vila/bazel/bzlmod/extensions.bzl b/bazel/bzlmod/extensions.bzl similarity index 88% rename from vila/bazel/bzlmod/extensions.bzl rename to bazel/bzlmod/extensions.bzl index e8a7a95..cc962bc 100644 --- a/vila/bazel/bzlmod/extensions.bzl +++ b/bazel/bzlmod/extensions.bzl @@ -15,17 +15,17 @@ limitations under the License. """ load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") -load("@vila//vila/bazel:tvm_ffi_configure.bzl", "tvm_ffi_configure") -load("@vila//vila/bazel/toolchains:bullseye_cc_configure.bzl", "bullseye_configure") -load("@vila//vila/bazel/toolchains:sycl_cc_configure.bzl", "sycl_configure") -load("@vila//vila/bazel/wdk:wdk_configure.bzl", "wdk_configure") +load("@vila//bazel:tvm_ffi_configure.bzl", "tvm_ffi_configure") +load("@vila//bazel/toolchains:bullseye_cc_configure.bzl", "bullseye_configure") +load("@vila//bazel/toolchains:sycl_cc_configure.bzl", "sycl_configure") +load("@vila//bazel/wdk:wdk_configure.bzl", "wdk_configure") def load_spdlog(ctx): # https://github.com/gabime/spdlog/releases spdlog_version = "1.17.0" http_archive( name = "spdlog", - build_file = "@vila//vila/bazel:spdlog.BUILD", + build_file = "@vila//bazel:spdlog.BUILD", integrity = "sha256-2IYpVcbXTlhGs/WAsWBdJCixHZekENhuL7E+hXzTp0Q=", strip_prefix = "spdlog-%s" % spdlog_version, url = "https://github.com/gabime/spdlog/archive/refs/tags/v%s.tar.gz" % spdlog_version, @@ -58,7 +58,7 @@ def load_ittapi(ctx): itt_version = "3.26.7" http_archive( name = "ittapi", - build_file = "@vila//vila/bazel:ittapi.BUILD", + build_file = "@vila//bazel:ittapi.BUILD", integrity = "sha256-KaoN1QzfDwoKIVY+r8W3znkFLBlZSmQBelHwkwSko58=", strip_prefix = "ittapi-%s" % itt_version, url = "https://github.com/intel/ittapi/archive/refs/tags/v%s.tar.gz" % itt_version, diff --git a/vila/bazel/device/BUILD.bazel b/bazel/device/BUILD.bazel similarity index 100% rename from vila/bazel/device/BUILD.bazel rename to bazel/device/BUILD.bazel diff --git a/vila/bazel/fmt.BUILD b/bazel/fmt.BUILD similarity index 92% rename from vila/bazel/fmt.BUILD rename to bazel/fmt.BUILD index 52dbabd..8a5e898 100644 --- a/vila/bazel/fmt.BUILD +++ b/bazel/fmt.BUILD @@ -6,7 +6,7 @@ E-mail: wenyitang@outlook.com Follow fmt/support/bazel/BUILD.bazel """ -load("@vila//vila/bazel/vila:vila.bzl", "vila_cc_library") +load("@vila//bazel/vila:vila.bzl", "vila_cc_library") package(default_visibility = ["//visibility:public"]) diff --git a/vila/bazel/hlsl/BUILD.bazel b/bazel/hlsl/BUILD.bazel similarity index 100% rename from vila/bazel/hlsl/BUILD.bazel rename to bazel/hlsl/BUILD.bazel diff --git a/vila/bazel/hlsl/BUILD.tpl b/bazel/hlsl/BUILD.tpl similarity index 100% rename from vila/bazel/hlsl/BUILD.tpl rename to bazel/hlsl/BUILD.tpl diff --git a/vila/bazel/hlsl/compiler.bzl.tpl b/bazel/hlsl/compiler.bzl.tpl similarity index 100% rename from vila/bazel/hlsl/compiler.bzl.tpl rename to bazel/hlsl/compiler.bzl.tpl diff --git a/vila/bazel/hlsl/hlsl_configure.bzl b/bazel/hlsl/hlsl_configure.bzl similarity index 100% rename from vila/bazel/hlsl/hlsl_configure.bzl rename to bazel/hlsl/hlsl_configure.bzl diff --git a/vila/bazel/ittapi.BUILD b/bazel/ittapi.BUILD similarity index 100% rename from vila/bazel/ittapi.BUILD rename to bazel/ittapi.BUILD diff --git a/vila/bazel/local_archive.bzl b/bazel/local_archive.bzl similarity index 100% rename from vila/bazel/local_archive.bzl rename to bazel/local_archive.bzl diff --git a/vila/bazel/pre_compile.bzl b/bazel/pre_compile.bzl similarity index 98% rename from vila/bazel/pre_compile.bzl rename to bazel/pre_compile.bzl index a7c8a1a..e06cd49 100644 --- a/vila/bazel/pre_compile.bzl +++ b/bazel/pre_compile.bzl @@ -7,7 +7,7 @@ Use precompiled headers (PCH) on Windows MSVC to speed up build time. Usage: - load("@vila//vila/bazel:pre_compile.bzl", "pch_library") + load("@vila//bazel:pre_compile.bzl", "pch_library") flags = pch_library( name = "mypch", diff --git a/vila/bazel/spdlog.BUILD b/bazel/spdlog.BUILD similarity index 100% rename from vila/bazel/spdlog.BUILD rename to bazel/spdlog.BUILD diff --git a/vila/bazel/symlink.bzl b/bazel/symlink.bzl similarity index 100% rename from vila/bazel/symlink.bzl rename to bazel/symlink.bzl diff --git a/vila/bazel/toolchains/BUILD.bazel b/bazel/toolchains/BUILD.bazel similarity index 100% rename from vila/bazel/toolchains/BUILD.bazel rename to bazel/toolchains/BUILD.bazel diff --git a/vila/bazel/toolchains/BUILD_bullseye.tpl b/bazel/toolchains/BUILD_bullseye.tpl similarity index 100% rename from vila/bazel/toolchains/BUILD_bullseye.tpl rename to bazel/toolchains/BUILD_bullseye.tpl diff --git a/vila/bazel/toolchains/BUILD_sycl.tpl b/bazel/toolchains/BUILD_sycl.tpl similarity index 97% rename from vila/bazel/toolchains/BUILD_sycl.tpl rename to bazel/toolchains/BUILD_sycl.tpl index b1f9a39..f784862 100644 --- a/vila/bazel/toolchains/BUILD_sycl.tpl +++ b/bazel/toolchains/BUILD_sycl.tpl @@ -6,7 +6,7 @@ E-mail: wenyitang@outlook.com custom cc toolchains for Windows """ -load("@vila//vila/bazel/toolchains:sycl_cc_toolchain_config.bzl", "cc_toolchain_config") +load("@vila//bazel/toolchains:sycl_cc_toolchain_config.bzl", "cc_toolchain_config") package(default_visibility = ["//visibility:public"]) diff --git a/vila/bazel/toolchains/BUILD_sycl_unix.tpl b/bazel/toolchains/BUILD_sycl_unix.tpl similarity index 100% rename from vila/bazel/toolchains/BUILD_sycl_unix.tpl rename to bazel/toolchains/BUILD_sycl_unix.tpl diff --git a/vila/bazel/toolchains/bullseye_cc_configure.bzl b/bazel/toolchains/bullseye_cc_configure.bzl similarity index 93% rename from vila/bazel/toolchains/bullseye_cc_configure.bzl rename to bazel/toolchains/bullseye_cc_configure.bzl index 187fb95..5bf1945 100644 --- a/vila/bazel/toolchains/bullseye_cc_configure.bzl +++ b/bazel/toolchains/bullseye_cc_configure.bzl @@ -6,9 +6,9 @@ E-mail: wenyitang@outlook.com config cc toolchain to use bullseye instruments """ -load("@vila//vila/bazel/toolchains:os.bzl", "is_windows") +load("@vila//bazel/toolchains:os.bzl", "is_windows") load( - "@vila//vila/bazel/toolchains:windows_toolchain_configure.bzl", + "@vila//bazel/toolchains:windows_toolchain_configure.bzl", "get_clang_cl_vars", "get_msvc_vars", "get_path_env_var", @@ -86,7 +86,7 @@ def _resolve_labels(repository_ctx, labels): def _bullseye_configure(repository_ctx): paths = _resolve_labels(repository_ctx, [ - "@vila//vila/bazel/toolchains:BUILD_bullseye.tpl", + "@vila//bazel/toolchains:BUILD_bullseye.tpl", "@bazel_tools//tools/cpp:windows_cc_toolchain_config.bzl", "@bazel_tools//tools/cpp:vc_installation_error.bat.tpl", "@bazel_tools//tools/cpp:clang_installation_error.bat.tpl", @@ -95,7 +95,7 @@ def _bullseye_configure(repository_ctx): if is_windows(repository_ctx): repo_name = repository_ctx.name.split("~")[-1] template_vars = dict({ - "%{constraint_values}": "\"@vila//vila/bazel/toolchains:bullseye\"", + "%{constraint_values}": "\"@vila//bazel/toolchains:bullseye\"", "%{platform_name}": repo_name, }) msvc_vars_x64 = get_msvc_vars(repository_ctx, paths, "x64") @@ -110,7 +110,7 @@ def _bullseye_configure(repository_ctx): repository_ctx.template( "BUILD", - paths["@vila//vila/bazel/toolchains:BUILD_bullseye.tpl"], + paths["@vila//bazel/toolchains:BUILD_bullseye.tpl"], template_vars, ) diff --git a/vila/bazel/toolchains/os.bzl b/bazel/toolchains/os.bzl similarity index 100% rename from vila/bazel/toolchains/os.bzl rename to bazel/toolchains/os.bzl diff --git a/vila/bazel/toolchains/sycl_cc_configure.bzl b/bazel/toolchains/sycl_cc_configure.bzl similarity index 93% rename from vila/bazel/toolchains/sycl_cc_configure.bzl rename to bazel/toolchains/sycl_cc_configure.bzl index 5cedce1..2d25999 100644 --- a/vila/bazel/toolchains/sycl_cc_configure.bzl +++ b/bazel/toolchains/sycl_cc_configure.bzl @@ -6,10 +6,10 @@ E-mail: wenyitang@outlook.com config cc toolchain to use oneAPI SYCL compiler (icp a.k.a dpc++) """ -load("@vila//vila/bazel/toolchains:os.bzl", "is_windows") -load("@vila//vila/bazel/toolchains:unix_toolchain_configure.bzl", "configure_unix_toolchain") +load("@vila//bazel/toolchains:os.bzl", "is_windows") +load("@vila//bazel/toolchains:unix_toolchain_configure.bzl", "configure_unix_toolchain") load( - "@vila//vila/bazel/toolchains:windows_toolchain_configure.bzl", + "@vila//bazel/toolchains:windows_toolchain_configure.bzl", "get_msvc_vars", "get_path_env_var", ) @@ -148,8 +148,8 @@ def _resolve_labels(repository_ctx, labels): def _sycl_configure(repository_ctx): paths = _resolve_labels(repository_ctx, [ - "@vila//vila/bazel/toolchains:BUILD_sycl.tpl", - "@vila//vila/bazel/toolchains:BUILD_sycl_unix.tpl", + "@vila//bazel/toolchains:BUILD_sycl.tpl", + "@vila//bazel/toolchains:BUILD_sycl_unix.tpl", # required by msvc "@bazel_tools//tools/cpp:windows_cc_toolchain_config.bzl", "@bazel_tools//tools/cpp:vc_installation_error.bat.tpl", @@ -164,7 +164,7 @@ def _sycl_configure(repository_ctx): repo_name = repository_ctx.name.split("~")[-1] template_vars = dict({ - "%{constraint_values}": "\"@vila//vila/bazel/toolchains:sycl\"", + "%{constraint_values}": "\"@vila//bazel/toolchains:sycl\"", "%{platform_name}": repo_name, }) if is_windows(repository_ctx): @@ -174,7 +174,7 @@ def _sycl_configure(repository_ctx): repository_ctx.template( "BUILD", - paths["@vila//vila/bazel/toolchains:BUILD_sycl.tpl"], + paths["@vila//bazel/toolchains:BUILD_sycl.tpl"], template_vars, ) else: diff --git a/vila/bazel/toolchains/sycl_cc_toolchain_config.bzl b/bazel/toolchains/sycl_cc_toolchain_config.bzl similarity index 100% rename from vila/bazel/toolchains/sycl_cc_toolchain_config.bzl rename to bazel/toolchains/sycl_cc_toolchain_config.bzl diff --git a/vila/bazel/toolchains/unix_toolchain_configure.bzl b/bazel/toolchains/unix_toolchain_configure.bzl similarity index 99% rename from vila/bazel/toolchains/unix_toolchain_configure.bzl rename to bazel/toolchains/unix_toolchain_configure.bzl index ad4bfcd..1b97477 100644 --- a/vila/bazel/toolchains/unix_toolchain_configure.bzl +++ b/bazel/toolchains/unix_toolchain_configure.bzl @@ -546,7 +546,7 @@ def configure_unix_toolchain(repository_ctx, paths, cpu_value, overriden_tools): write_builtin_include_directory_paths(repository_ctx, cc, builtin_include_directories) repository_ctx.template( "BUILD", - paths["@vila//vila/bazel/toolchains:BUILD_sycl_unix.tpl"], + paths["@vila//bazel/toolchains:BUILD_sycl_unix.tpl"], { "%{cc_toolchain_identifier}": cc_toolchain_identifier, "%{name}": cpu_value, diff --git a/vila/bazel/toolchains/windows_toolchain_configure.bzl b/bazel/toolchains/windows_toolchain_configure.bzl similarity index 100% rename from vila/bazel/toolchains/windows_toolchain_configure.bzl rename to bazel/toolchains/windows_toolchain_configure.bzl diff --git a/vila/bazel/tvm_ffi_configure.bzl b/bazel/tvm_ffi_configure.bzl similarity index 97% rename from vila/bazel/tvm_ffi_configure.bzl rename to bazel/tvm_ffi_configure.bzl index 41f1d8d..b224dd1 100644 --- a/vila/bazel/tvm_ffi_configure.bzl +++ b/bazel/tvm_ffi_configure.bzl @@ -20,11 +20,11 @@ Usage: 3. Depend on @tvm_ffi//:tvm_ffi in your targets Example in MODULE.bazel: - tvm_ffi_ext = use_extension("@vila//vila/bazel/bzlmod:extensions.bzl", "tvm_ffi_extension") + tvm_ffi_ext = use_extension("@vila//bazel/bzlmod:extensions.bzl", "tvm_ffi_extension") use_repo(tvm_ffi_ext, "tvm_ffi") Example in WORKSPACE: - load("@vila//vila/bazel:tvm_ffi_configure.bzl", "tvm_ffi_configure") + load("@vila//bazel:tvm_ffi_configure.bzl", "tvm_ffi_configure") tvm_ffi_configure(name = "tvm_ffi") """ diff --git a/vila/bazel/vila/BUILD.bazel b/bazel/vila/BUILD.bazel similarity index 100% rename from vila/bazel/vila/BUILD.bazel rename to bazel/vila/BUILD.bazel diff --git a/vila/bazel/vila/compile_options.bzl b/bazel/vila/compile_options.bzl similarity index 100% rename from vila/bazel/vila/compile_options.bzl rename to bazel/vila/compile_options.bzl diff --git a/vila/bazel/vila/vila.bzl b/bazel/vila/vila.bzl similarity index 98% rename from vila/bazel/vila/vila.bzl rename to bazel/vila/vila.bzl index 4477eb7..590b148 100644 --- a/vila/bazel/vila/vila.bzl +++ b/bazel/vila/vila.bzl @@ -8,7 +8,7 @@ Convenient object library for vila source code load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_import", "cc_library", "cc_test") load( - "@vila//vila/bazel/vila:compile_options.bzl", + "@vila//bazel/vila:compile_options.bzl", "CXX_STD_17", "DEFAULT_COPTS", "DEFAULT_LINKOPTS", diff --git a/vila/bazel/wdk/BUILD.bazel b/bazel/wdk/BUILD.bazel similarity index 100% rename from vila/bazel/wdk/BUILD.bazel rename to bazel/wdk/BUILD.bazel diff --git a/vila/bazel/wdk/BUILD.tpl b/bazel/wdk/BUILD.tpl similarity index 100% rename from vila/bazel/wdk/BUILD.tpl rename to bazel/wdk/BUILD.tpl diff --git a/vila/bazel/wdk/rc.bzl.tpl b/bazel/wdk/rc.bzl.tpl similarity index 100% rename from vila/bazel/wdk/rc.bzl.tpl rename to bazel/wdk/rc.bzl.tpl diff --git a/vila/bazel/wdk/wdk_configure.bzl b/bazel/wdk/wdk_configure.bzl similarity index 90% rename from vila/bazel/wdk/wdk_configure.bzl rename to bazel/wdk/wdk_configure.bzl index 0ce1c7d..1c36398 100644 --- a/vila/bazel/wdk/wdk_configure.bzl +++ b/bazel/wdk/wdk_configure.bzl @@ -41,12 +41,12 @@ def _wdk_configure(ctx): rc_compiler = ctx.path("{}\\x64\\rc.exe".format(wdk_bin_path)) - ctx.template("BUILD.bazel", Label("@vila//vila/bazel/wdk:BUILD.tpl")) - ctx.template("wpp.bzl", Label("@vila//vila/bazel/wdk:wpp.bzl.tpl"), { + ctx.template("BUILD.bazel", Label("@vila//bazel/wdk:BUILD.tpl")) + ctx.template("wpp.bzl", Label("@vila//bazel/wdk:wpp.bzl.tpl"), { "%{tracewpp}": str(tracewpp), "%{wppconfig}": str(wppconfig), }) - ctx.template("rc.bzl", Label("@vila//vila/bazel/wdk:rc.bzl.tpl"), { + ctx.template("rc.bzl", Label("@vila//bazel/wdk:rc.bzl.tpl"), { "%{rc_compiler}": str(rc_compiler), "%{system_include}": win_include_dir, }) diff --git a/vila/bazel/wdk/wpp.bzl.tpl b/bazel/wdk/wpp.bzl.tpl similarity index 100% rename from vila/bazel/wdk/wpp.bzl.tpl rename to bazel/wdk/wpp.bzl.tpl diff --git a/tests/vila/BUILD.bazel b/tests/vila/BUILD.bazel index e25da92..53b8b7e 100644 --- a/tests/vila/BUILD.bazel +++ b/tests/vila/BUILD.bazel @@ -17,7 +17,7 @@ limitations under the License. load("@rules_cc//cc:defs.bzl", "cc_binary") load("@rules_python//python:defs.bzl", "py_test") load("@vila_pip_deps//:requirements.bzl", "requirement") -load("//vila/bazel/vila:vila.bzl", "vila_cc_test") +load("//bazel/vila:vila.bzl", "vila_cc_test") cc_binary( name = "tvm_ffi_call", diff --git a/tests/vila/bazel/sycl/BUILD.bazel b/tests/vila/bazel/sycl/BUILD.bazel index dd71c2a..ecaf025 100644 --- a/tests/vila/bazel/sycl/BUILD.bazel +++ b/tests/vila/bazel/sycl/BUILD.bazel @@ -14,12 +14,12 @@ See the License for the specific language governing permissions and limitations under the License. """ -load("//vila/bazel/vila:vila.bzl", "vila_cc_test") +load("//bazel/vila:vila.bzl", "vila_cc_test") vila_cc_test( name = "hello_sycl", srcs = ["hello_sycl.cc"], - target_compatible_with = ["//vila/bazel/toolchains:sycl"], + target_compatible_with = ["//bazel/toolchains:sycl"], deps = [ # We can't link gtest_main because it's not compiled by SYCL, and # SYCL won't able to locate entry point in that library. diff --git a/tests/vila/pch/BUILD.bazel b/tests/vila/pch/BUILD.bazel index 580329a..674a997 100644 --- a/tests/vila/pch/BUILD.bazel +++ b/tests/vila/pch/BUILD.bazel @@ -6,7 +6,7 @@ E-mail: wenyitang@outlook.com load("@rules_cc//cc:cc_binary.bzl", "cc_binary") load("@rules_cc//cc:cc_library.bzl", "cc_library") -load("//vila/bazel:pre_compile.bzl", "pch_library") +load("//bazel:pre_compile.bzl", "pch_library") flags = pch_library( name = "pch", diff --git a/vila/BUILD.bazel b/vila/BUILD.bazel index 4a3c6e5..61020c0 100644 --- a/vila/BUILD.bazel +++ b/vila/BUILD.bazel @@ -42,7 +42,7 @@ config_setting( name = "sycl", constraint_values = [ "@platforms//os:windows", - "@vila//vila/bazel/toolchains:sycl", + "@vila//bazel/toolchains:sycl", ], ) diff --git a/vila/config/BUILD.bazel b/vila/config/BUILD.bazel index 0be9fc0..ea42822 100644 --- a/vila/config/BUILD.bazel +++ b/vila/config/BUILD.bazel @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. """ -load("@vila//vila/bazel/vila:vila.bzl", "vila_cc_library") +load("@vila//bazel/vila:vila.bzl", "vila_cc_library") vila_cc_library( name = "json", diff --git a/vila/graph/BUILD.bazel b/vila/graph/BUILD.bazel index 62fa980..a3b3143 100644 --- a/vila/graph/BUILD.bazel +++ b/vila/graph/BUILD.bazel @@ -15,7 +15,7 @@ limitations under the License. FILE: graph architectures """ -load("@vila//vila/bazel/vila:vila.bzl", "vila_cc_library") +load("@vila//bazel/vila:vila.bzl", "vila_cc_library") package(default_visibility = ["//visibility:public"]) diff --git a/vila/logging/BUILD.bazel b/vila/logging/BUILD.bazel index 509dcd2..3503ed0 100644 --- a/vila/logging/BUILD.bazel +++ b/vila/logging/BUILD.bazel @@ -15,7 +15,7 @@ limitations under the License. """ load("@local_config_wdk//:wpp.bzl", "var_providing_rule") -load("@vila//vila/bazel/vila:vila.bzl", "vila_cc_library") +load("@vila//bazel/vila:vila.bzl", "vila_cc_library") var_providing_rule(name = "set_wpp_vars") diff --git a/vila/profiling/BUILD.bazel b/vila/profiling/BUILD.bazel index f85d461..20abaa2 100644 --- a/vila/profiling/BUILD.bazel +++ b/vila/profiling/BUILD.bazel @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. """ -load("@vila//vila/bazel/vila:vila.bzl", "vila_cc_library") +load("@vila//bazel/vila:vila.bzl", "vila_cc_library") package(default_visibility = ["//visibility:public"]) diff --git a/vila/status/BUILD.bazel b/vila/status/BUILD.bazel index bbe780f..365b8e7 100644 --- a/vila/status/BUILD.bazel +++ b/vila/status/BUILD.bazel @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. """ -load("@vila//vila/bazel/vila:vila.bzl", "vila_cc_library") +load("@vila//bazel/vila:vila.bzl", "vila_cc_library") vila_cc_library( name = "status", diff --git a/vila/widget/BUILD.bazel b/vila/widget/BUILD.bazel index aebe066..5fe8f00 100644 --- a/vila/widget/BUILD.bazel +++ b/vila/widget/BUILD.bazel @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. """ -load("@vila//vila/bazel/vila:vila.bzl", "vila_cc_library") +load("@vila//bazel/vila:vila.bzl", "vila_cc_library") vila_cc_library( name = "registration", diff --git a/vila/workspace0.bzl b/workspace0.bzl similarity index 54% rename from vila/workspace0.bzl rename to workspace0.bzl index c73c83d..eceed0a 100644 --- a/vila/workspace0.bzl +++ b/workspace0.bzl @@ -16,16 +16,17 @@ limitations under the License. load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") -def workspace(skylib = True, rules_cc = True, rules_foreign_cc = True, rules_python = True, pybind11 = True, nanobind = True): +def workspace(skylib = True, rules_cc = True, rules_foreign_cc = True, rules_python = True, rules_shell = True): """Declare basic workspace dependency + Bazel rules + Args: skylib: Whether to include Bazel Skylib. rules_cc: Whether to include Bazel Rules for C/C++. rules_foreign_cc: Whether to include Bazel Rules for Foreign C/C++. rules_python: Whether to include Bazel Rules for Python. - pybind11: Whether to include Pybind11. - nanobind: Whether to include nanobind. + rules_shell: Whether to include Bazel Rules for Shell. """ # https://github.com/bazelbuild/bazel-skylib/releases @@ -78,66 +79,12 @@ def workspace(skylib = True, rules_cc = True, rules_foreign_cc = True, rules_pyt url = "https://github.com/bazelbuild/rules_python/archive/refs/tags/%s.tar.gz" % rules_python_version, ) - # https://github.com/pybind/pybind11_bazel/releases - pybind11_version = "3.0.0" - if pybind11: - http_archive( - name = "pybind11_bazel", - integrity = "sha256-DS8PvRhMzZS4UpQ/kSw96H5f9jJbqcN+r+f0eTAmP9w=", - strip_prefix = "pybind11_bazel-%s" % pybind11_version, - url = "https://github.com/pybind/pybind11_bazel/archive/refs/tags/v%s.tar.gz" % pybind11_version, - ) - - # https://github.com/pybind/pybind11/releases - pybind11_major = int(pybind11_version.split(".")[0]) - pybind11_minor = int(pybind11_version.split(".")[1]) - http_archive( - name = "pybind11", - build_file = "@pybind11_bazel//:%s" % ("pybind11.BUILD" if (pybind11_major <= 2 and pybind11_minor <= 11) else "pybind11-BUILD.bazel"), - integrity = "sha256-RTsaPismbDrp2ockEcrbbWk6wYBjvXMibZbPtwFaIAw=", - strip_prefix = "pybind11-%s" % pybind11_version, - url = "https://github.com/pybind/pybind11/archive/refs/tags/v%s.tar.gz" % pybind11_version, - ) - - if nanobind: - nanobind_version = "2.10.2" - http_archive( - name = "nanobind_bazel", - integrity = "sha256-QJeB39Bx/m2i79HP+z9okTWEN5t4CcIRwFzJapnJmoY=", - strip_prefix = "nanobind-bazel-%s" % nanobind_version, - url = "https://github.com/nicholasjng/nanobind-bazel/archive/refs/tags/v%s.tar.gz" % nanobind_version, - ) - - robin_map_version = "1.4.0" - http_archive( - name = "robin-map", - integrity = "sha256-eTDb+WNKz8Amhth/YVwPTzMTWUgTC4kiMxwW2QoDJQw=", - strip_prefix = "robin-map-%s" % robin_map_version, - url = "https://github.com/Tessil/robin-map/archive/refs/tags/v%s.tar.gz" % robin_map_version, - build_file_content = """load("@rules_cc//cc:cc_library.bzl", "cc_library") - -config_setting( - name = "msvc_compiler", - flag_values = {"@bazel_tools//tools/cpp:compiler": "msvc-cl"}, -) - -cc_library( - name = "robin-map", - hdrs = glob(["include/tsl/*.h"]), - copts = select({ - ":msvc_compiler": ["/std:c++17"], - "//conditions:default": ["--std=c++17"], - }), - strip_include_prefix = "include/", - visibility = ["//visibility:public"], -) -""", - ) - + # https://github.com/bazelbuild/rules_shell/releases + rules_shell_version = "0.8.0" + if rules_shell: http_archive( - name = "nanobind", - build_file = "@nanobind_bazel//:nanobind.BUILD", - integrity = "sha256-W7f4ZvbJxkQFMItp3n52gdj3eTI+NFvXGgAZnB6uwHM=", - strip_prefix = "nanobind-%s" % nanobind_version, - url = "https://github.com/wjakob/nanobind/archive/refs/tags/v%s.tar.gz" % nanobind_version, + name = "rules_shell", + sha256 = "20721f63908879c083f94869e618ea8d4ff5edb91ff9a72a2ebee357fdbc352d", + strip_prefix = "rules_shell-%s" % rules_shell_version, + url = "https://github.com/bazelbuild/rules_shell/archive/refs/tags/v%s.tar.gz" % rules_shell_version, ) diff --git a/vila/workspace1.bzl b/workspace1.bzl similarity index 53% rename from vila/workspace1.bzl rename to workspace1.bzl index c036cfc..5c13b9f 100644 --- a/vila/workspace1.bzl +++ b/workspace1.bzl @@ -1,5 +1,5 @@ """ -Copyright (C) 2025-2026 The VILA Authors. +Copyright (C) 2026 The VILA Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -16,14 +16,24 @@ limitations under the License. load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") load( - "@vila//vila/bazel/bzlmod:extensions.bzl", + "@vila//bazel/bzlmod:extensions.bzl", "load_hedron", "load_ittapi", "load_rangev3", "load_spdlog", ) -def workspace(gtest = True, benchmark = True, protobuf = True, fmt = True, spdlog = True, rangev3 = True, hedron = True, ittapi = True): +def workspace( + gtest = True, + benchmark = True, + protobuf = True, + fmt = True, + spdlog = True, + rangev3 = True, + hedron = True, + ittapi = True, + pybind11 = True, + nanobind = True): """Loads a set of vila dependencies. To be used in a WORKSPACE file. Args: @@ -35,6 +45,8 @@ def workspace(gtest = True, benchmark = True, protobuf = True, fmt = True, spdlo rangev3: Whether to include range-v3. hedron: Whether to include Hedron. ittapi: Whether to include Intel ITT API. + pybind11: Whether to include Pybind11. + nanobind: Whether to include nanobind. """ # https://github.com/google/googletest/releases @@ -72,7 +84,7 @@ def workspace(gtest = True, benchmark = True, protobuf = True, fmt = True, spdlo if fmt: http_archive( name = "fmt", - build_file = "@vila//vila/bazel:fmt.BUILD", + build_file = "@vila//bazel:fmt.BUILD", integrity = "sha256-qj6Pu2oAZsA0VENK3R8fwjKZ6FdYzuwNfS2XRDFIHkA=", strip_prefix = "fmt-%s" % fmt_version, url = "https://github.com/fmtlib/fmt/archive/refs/tags/%s.tar.gz" % fmt_version, @@ -103,3 +115,67 @@ def workspace(gtest = True, benchmark = True, protobuf = True, fmt = True, spdlo # https://github.com/intel/ittapi if ittapi: load_ittapi(None) + + # https://github.com/pybind/pybind11_bazel/releases + pybind11_version = "3.0.0" + if pybind11: + http_archive( + name = "pybind11_bazel", + integrity = "sha256-DS8PvRhMzZS4UpQ/kSw96H5f9jJbqcN+r+f0eTAmP9w=", + strip_prefix = "pybind11_bazel-%s" % pybind11_version, + url = "https://github.com/pybind/pybind11_bazel/archive/refs/tags/v%s.tar.gz" % pybind11_version, + ) + + # https://github.com/pybind/pybind11/releases + pybind11_major = int(pybind11_version.split(".")[0]) + pybind11_minor = int(pybind11_version.split(".")[1]) + http_archive( + name = "pybind11", + build_file = "@pybind11_bazel//:%s" % ("pybind11.BUILD" if (pybind11_major <= 2 and pybind11_minor <= 11) else "pybind11-BUILD.bazel"), + integrity = "sha256-RTsaPismbDrp2ockEcrbbWk6wYBjvXMibZbPtwFaIAw=", + strip_prefix = "pybind11-%s" % pybind11_version, + url = "https://github.com/pybind/pybind11/archive/refs/tags/v%s.tar.gz" % pybind11_version, + ) + + if nanobind: + nanobind_version = "2.10.2" + http_archive( + name = "nanobind_bazel", + integrity = "sha256-QJeB39Bx/m2i79HP+z9okTWEN5t4CcIRwFzJapnJmoY=", + strip_prefix = "nanobind-bazel-%s" % nanobind_version, + url = "https://github.com/nicholasjng/nanobind-bazel/archive/refs/tags/v%s.tar.gz" % nanobind_version, + ) + + robin_map_version = "1.4.0" + http_archive( + name = "robin-map", + integrity = "sha256-eTDb+WNKz8Amhth/YVwPTzMTWUgTC4kiMxwW2QoDJQw=", + strip_prefix = "robin-map-%s" % robin_map_version, + url = "https://github.com/Tessil/robin-map/archive/refs/tags/v%s.tar.gz" % robin_map_version, + build_file_content = """load("@rules_cc//cc:cc_library.bzl", "cc_library") + +config_setting( + name = "msvc_compiler", + flag_values = {"@bazel_tools//tools/cpp:compiler": "msvc-cl"}, +) + +cc_library( + name = "robin-map", + hdrs = glob(["include/tsl/*.h"]), + copts = select({ + ":msvc_compiler": ["/std:c++17"], + "//conditions:default": ["--std=c++17"], + }), + strip_include_prefix = "include/", + visibility = ["//visibility:public"], +) +""", + ) + + http_archive( + name = "nanobind", + build_file = "@nanobind_bazel//:nanobind.BUILD", + integrity = "sha256-W7f4ZvbJxkQFMItp3n52gdj3eTI+NFvXGgAZnB6uwHM=", + strip_prefix = "nanobind-%s" % nanobind_version, + url = "https://github.com/wjakob/nanobind/archive/refs/tags/v%s.tar.gz" % nanobind_version, + ) diff --git a/vila/workspace2.bzl b/workspace2.bzl similarity index 82% rename from vila/workspace2.bzl rename to workspace2.bzl index e856e11..48d98e5 100644 --- a/vila/workspace2.bzl +++ b/workspace2.bzl @@ -1,5 +1,5 @@ """ -Copyright (C) 2025-2026 The VILA Authors. +Copyright (C) 2026 The VILA Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,14 +14,16 @@ See the License for the specific language governing permissions and limitations under the License. """ -load("@vila//vila/bazel:tvm_ffi_configure.bzl", "tvm_ffi_configure") -load("@vila//vila/bazel/toolchains:bullseye_cc_configure.bzl", "bullseye_configure") -load("@vila//vila/bazel/toolchains:sycl_cc_configure.bzl", "sycl_configure") -load("@vila//vila/bazel/wdk:wdk_configure.bzl", "wdk_configure") +load("@vila//bazel:tvm_ffi_configure.bzl", "tvm_ffi_configure") +load("@vila//bazel/toolchains:bullseye_cc_configure.bzl", "bullseye_configure") +load("@vila//bazel/toolchains:sycl_cc_configure.bzl", "sycl_configure") +load("@vila//bazel/wdk:wdk_configure.bzl", "wdk_configure") def workspace(bullseye = False, sycl = False, tvm_ffi = False): """Loads a set of vila dependencies. To be used in a WORKSPACE file. + Toolchain related dependencies. + Args: bullseye: Whether to include Bullseye Coverage. sycl: Whether to include oneAPI DPC++ compiler.