Repository: HKalbasi/zngur
Branch: main
Commit: cce4441a58de
Files: 213
Total size: 508.1 KB
Directory structure:
gitextract_ukr27c6s/
├── .cargo/
│ └── config.toml
├── .github/
│ └── workflows/
│ ├── ci.yml
│ ├── publish.yml
│ └── site.yml
├── .gitignore
├── Cargo.toml
├── LICENSE-APACHE
├── LICENSE-MIT
├── README.md
├── benchmark/
│ ├── .gitignore
│ ├── Cargo.toml
│ ├── benches/
│ │ └── simple.rs
│ ├── build.rs
│ ├── impls.cpp
│ ├── main.zng
│ └── src/
│ └── lib.rs
├── cspell-words.txt
├── cspell.json
├── dprint.json
├── examples/
│ ├── .gitignore
│ ├── char/
│ │ ├── .gitignore
│ │ ├── Cargo.toml
│ │ ├── Makefile
│ │ ├── NMakefile
│ │ ├── expected_output.txt
│ │ ├── main.cpp
│ │ ├── main.zng
│ │ └── src/
│ │ └── lib.rs
│ ├── conditional/
│ │ ├── .gitignore
│ │ ├── Cargo.toml
│ │ ├── Makefile
│ │ ├── NMakefile
│ │ ├── README.md
│ │ ├── expected_output.txt
│ │ ├── main.cpp
│ │ ├── main.zng
│ │ └── src/
│ │ └── lib.rs
│ ├── cxx_demo/
│ │ ├── .gitignore
│ │ ├── Cargo.toml
│ │ ├── README.md
│ │ ├── blobstore.cpp
│ │ ├── build.rs
│ │ ├── expected_output.txt
│ │ ├── main.zng
│ │ └── src/
│ │ └── main.rs
│ ├── cxx_demo_split/
│ │ ├── .gitignore
│ │ ├── Cargo.toml
│ │ ├── README.md
│ │ ├── blobstore.cpp
│ │ ├── build.rs
│ │ ├── expected_output.txt
│ │ ├── main.zng
│ │ └── src/
│ │ └── main.rs
│ ├── impl_trait/
│ │ ├── .gitignore
│ │ ├── Cargo.toml
│ │ ├── Makefile
│ │ ├── NMakefile
│ │ ├── README.md
│ │ ├── expected_output.txt
│ │ ├── main.cpp
│ │ ├── main.zng
│ │ └── src/
│ │ └── lib.rs
│ ├── memory_management/
│ │ ├── .gitignore
│ │ ├── Cargo.toml
│ │ ├── Makefile
│ │ ├── NMakefile
│ │ ├── README.md
│ │ ├── expected_output.txt
│ │ ├── main.cpp
│ │ ├── main.zng
│ │ └── src/
│ │ └── lib.rs
│ ├── multiple_modules/
│ │ ├── Cargo.toml
│ │ ├── Makefile
│ │ ├── aggregation/
│ │ │ ├── Cargo.toml
│ │ │ ├── aggregation.zng
│ │ │ ├── impls.cpp
│ │ │ ├── src/
│ │ │ │ └── lib.rs
│ │ │ └── stats.h
│ │ ├── expected_output.txt
│ │ ├── main.cpp
│ │ ├── packet/
│ │ │ ├── Cargo.toml
│ │ │ ├── packet.zng
│ │ │ └── src/
│ │ │ └── lib.rs
│ │ ├── processor/
│ │ │ ├── Cargo.toml
│ │ │ ├── processor.zng
│ │ │ └── src/
│ │ │ └── lib.rs
│ │ ├── receiver/
│ │ │ ├── Cargo.toml
│ │ │ ├── receiver.zng
│ │ │ └── src/
│ │ │ └── lib.rs
│ │ └── src/
│ │ └── lib.rs
│ ├── raw_pointer/
│ │ ├── .gitignore
│ │ ├── Cargo.toml
│ │ ├── Makefile
│ │ ├── NMakefile
│ │ ├── README.md
│ │ ├── expected_output.txt
│ │ ├── main.cpp
│ │ ├── main.zng
│ │ └── src/
│ │ └── lib.rs
│ ├── rayon/
│ │ ├── .gitignore
│ │ ├── Cargo.toml
│ │ ├── Makefile
│ │ ├── NMakefile
│ │ ├── README.md
│ │ ├── expected_output.txt
│ │ ├── main.cpp
│ │ ├── main.zng
│ │ └── src/
│ │ └── lib.rs
│ ├── rayon_split/
│ │ ├── .gitignore
│ │ ├── Cargo.toml
│ │ ├── Makefile
│ │ ├── NMakefile
│ │ ├── README.md
│ │ ├── expected_output.txt
│ │ ├── main.cpp
│ │ ├── main.zng
│ │ └── src/
│ │ └── lib.rs
│ ├── regression_test1/
│ │ ├── .gitignore
│ │ ├── Cargo.toml
│ │ ├── Makefile
│ │ ├── NMakefile
│ │ ├── README.md
│ │ ├── expected_output.txt
│ │ ├── main.cpp
│ │ ├── main.zng
│ │ └── src/
│ │ └── lib.rs
│ ├── rustyline/
│ │ ├── .gitignore
│ │ ├── Cargo.toml
│ │ ├── Makefile
│ │ ├── NMakefile
│ │ ├── README.md
│ │ ├── expected_output.txt
│ │ ├── main.cpp
│ │ ├── main.zng
│ │ └── src/
│ │ └── lib.rs
│ ├── simple/
│ │ ├── .gitignore
│ │ ├── Cargo.toml
│ │ ├── Makefile
│ │ ├── NMakefile
│ │ ├── README.md
│ │ ├── expected_output.txt
│ │ ├── main.cpp
│ │ ├── main.zng
│ │ └── src/
│ │ └── lib.rs
│ ├── simple_import/
│ │ ├── .gitignore
│ │ ├── Cargo.toml
│ │ ├── Makefile
│ │ ├── NMakefile
│ │ ├── README.md
│ │ ├── bar.cpp
│ │ ├── bar.zng
│ │ ├── expected_output.txt
│ │ ├── foo.cpp
│ │ ├── foo.zng
│ │ ├── main.cpp
│ │ ├── main.zng
│ │ ├── primitives.zng
│ │ └── src/
│ │ └── lib.rs
│ ├── tutorial/
│ │ ├── .gitignore
│ │ ├── Cargo.toml
│ │ ├── Makefile
│ │ ├── NMakefile
│ │ ├── README.md
│ │ ├── expected_output.txt
│ │ ├── main.cpp
│ │ ├── main.zng
│ │ └── src/
│ │ └── lib.rs
│ ├── tutorial-wasm32/
│ │ ├── .gitignore
│ │ ├── Cargo.toml
│ │ ├── Makefile
│ │ ├── NMakefile
│ │ ├── README.md
│ │ ├── expected_output.txt
│ │ ├── main.cpp
│ │ ├── main32.zng
│ │ └── src/
│ │ └── lib.rs
│ └── tutorial_cpp/
│ ├── Cargo.toml
│ ├── README.md
│ ├── build.rs
│ ├── expected_output.txt
│ ├── impls.cpp
│ ├── inventory.h
│ ├── main.zng
│ └── src/
│ └── main.rs
├── mise.toml
├── xtask/
│ ├── Cargo.toml
│ └── src/
│ ├── ci.rs
│ ├── format_book.rs
│ ├── format_templates.rs
│ └── main.rs
├── zngur/
│ ├── Cargo.toml
│ └── src/
│ └── lib.rs
├── zngur-autozng/
│ ├── Cargo.toml
│ └── src/
│ └── main.rs
├── zngur-cli/
│ ├── Cargo.toml
│ └── src/
│ ├── cfg_extractor.rs
│ └── main.rs
├── zngur-def/
│ ├── Cargo.toml
│ └── src/
│ ├── lib.rs
│ └── merge.rs
├── zngur-generator/
│ ├── Cargo.toml
│ ├── src/
│ │ ├── cpp.rs
│ │ ├── lib.rs
│ │ ├── rust.rs
│ │ └── template.rs
│ └── templates/
│ ├── cpp_header.sptl
│ ├── cpp_source.sptl
│ └── zng_header.sptl
└── zngur-parser/
├── Cargo.toml
└── src/
├── cfg.rs
├── conditional.rs
├── lib.rs
└── tests.rs
================================================
FILE CONTENTS
================================================
================================================
FILE: .cargo/config.toml
================================================
[alias]
xtask = "run --package xtask --"
================================================
FILE: .github/workflows/ci.yml
================================================
name: CI
on:
push:
branches: ["main"]
pull_request:
branches: ["main"]
env:
CARGO_TERM_COLOR: always
jobs:
build-mac:
runs-on: macos-14
strategy:
fail-fast: false
steps:
- uses: actions/checkout@v3
- uses: jdx/mise-action@v3
- name: Install Rust stable
run: |
rustup toolchain install stable
rustup target add wasm32-wasip1
rustup component add rustfmt
- name: Install Clang 19
run: brew install llvm@19
- name: Run `cargo xtask ci`
run: CC=$(brew --prefix llvm@19)/bin/clang CXX=$(brew --prefix llvm@19)/bin/clang++ cargo xtask ci
build:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
cpp_compiler:
- clang++
- g++
env:
CXX: ${{ matrix.cpp_compiler }}
steps:
- uses: actions/checkout@v3
- uses: jdx/mise-action@v3
- name: Install Rust stable
run: |
rustup toolchain install stable
rustup target add wasm32-wasip1
rustup component add rustfmt
- name: Install LLD for clang++
if: matrix.cpp_compiler == 'clang++'
run: sudo apt-get update && sudo apt-get install -y lld
- name: Run CI (clang++)
if: matrix.cpp_compiler == 'clang++'
run: CC=clang cargo xtask ci
- name: Run CI (g++)
if: matrix.cpp_compiler == 'g++'
run: cargo xtask ci
build-nightly:
runs-on: ubuntu-latest
strategy:
fail-fast: false
env:
CXX: g++
steps:
- uses: actions/checkout@v3
- uses: jdx/mise-action@v3
- name: Install Rust nightly
run: |
rustup toolchain install nightly
rustup default nightly
rustup target add wasm32-wasip1
rustup component add rustfmt
- name: Run CI (g++ nightly)
run: cargo xtask ci
build-win:
runs-on: windows-2022
steps:
- name: Turn off autocrlf
run: |
git config --global core.autocrlf false
- uses: actions/checkout@v3
- name: Enter VS Developer shell
uses: ilammy/msvc-dev-cmd@v1
with:
arch: amd64
vsversion: 2022
- uses: jdx/mise-action@v3
- name: Install Rust stable
run: |
rustup toolchain install stable
rustup target add wasm32-wasip1
rustup component add rustfmt
- name: Run `cargo xtask ci`
run: cargo xtask ci
================================================
FILE: .github/workflows/publish.yml
================================================
name: Publish
on:
workflow_dispatch:
jobs:
publish:
name: Publish
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v2
with:
token: ${{ secrets.PAT }}
fetch-depth: 0
- name: Install Rust toolchain
uses: actions-rs/toolchain@v1
with:
toolchain: stable
profile: minimal
override: true
- name: Install cargo-workspaces
uses: actions-rs/install@v0.1
with:
crate: cargo-workspaces
version: 0.2.44
- name: Release
env:
CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
shell: bash
run: |
# Check if we can skip releasing a new version
# (there are no changes and the job was not manually triggered)
export CHANGED=$(cargo workspaces changed --include-merged-tags --ignore-changes "**/Cargo.toml")
if [[ -z "$CHANGED" && "$GITHUB_EVENT_NAME" != "workflow_dispatch" ]]; then
# Nothing has changed, so don't publish a new version
echo "No changes detected, skipping publish."
exit 0
fi
# Update version
git config --global user.email "runner@gha.local"
git config --global user.name "Github Action"
cargo workspaces -v version -ay --force '*' --include-merged-tags --no-git-commit --exact minor
export VERSION=$(cd zngur; cargo pkgid | sed -E 's/.*#(.*)/\1/g')
# Commit and publish
git commit -am "Release $VERSION"
git tag "v$VERSION"
cargo workspaces -v publish --from-git --skip-published
git push --tags
git push
================================================
FILE: .github/workflows/site.yml
================================================
name: Deploy
on:
push:
branches:
- main
paths:
- book/**
- .github/workflows/site.yml
workflow_dispatch:
jobs:
deploy:
name: Deploy
runs-on: ubuntu-latest
permissions:
contents: write
timeout-minutes: 30
steps:
- uses: actions/checkout@v3
- uses: dtolnay/install@mdbook
- run: mdbook --version
- name: Build
run: |
cd book
mdbook build
- uses: crazy-max/ghaction-github-pages@v3.1.0
with:
build_dir: book/book
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
================================================
FILE: .gitignore
================================================
/target
a.out
a.out.dSYM
*.exe
*.obj
*.bat
*.a
*.o
.vscode
compile_commands.json
zngur-autozng/doc.json
perf.data
perf.data.old
actual_output.txt
flamegraph.svg
generated*.*
================================================
FILE: Cargo.toml
================================================
[workspace]
members = [
"zngur",
"zngur-cli",
"zngur-def",
"zngur-generator",
"zngur-parser",
"zngur-autozng",
"examples/*",
"xtask",
"benchmark",
]
# Exclude tutorial-wasm32 from default workspace builds since it requires extra dependencies
exclude = [
"examples/tutorial-wasm32",
]
resolver = "2"
[workspace.package]
edition = "2024"
rust-version = "1.85"
license = "MIT OR Apache-2.0"
[profile.dev]
opt-level = 3
[profile.release]
lto = true
================================================
FILE: LICENSE-APACHE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
================================================
FILE: LICENSE-MIT
================================================
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
================================================
FILE: README.md
================================================
# Zngur
[
](https://github.com/hkalbasi/zngur)
[
](https://crates.io/crates/zngur)
[
](https://docs.rs/zngur)
[
](https://github.com/hkalbasi/zngur/actions?query=branch%3Amain)
Zngur (/zængɑr/) is a C++/Rust interop tool. It tries to expose arbitrary Rust types, methods and functions, while preserving its
semantics and ergonomics as much as possible. Using Zngur, you can use arbitrary Rust crates in your C++ code as easily as using it in
normal Rust code, and you can write idiomatic Rusty APIs for your C++ library inside C++. See [the documentation](https://hkalbasi.github.io/zngur/)
for more info.
## Demo
```C++
#include
#include
#include "./generated.h"
// Rust values are available in the `::rust` namespace from their absolute path
// in Rust
template using Vec = rust::std::vec::Vec;
template using Option = rust::std::option::Option;
template using BoxDyn = rust::Box>;
// You can implement Rust traits for your classes
template
class VectorIterator : public rust::std::iter::Iterator {
std::vector vec;
size_t pos;
public:
VectorIterator(std::vector &&v) : vec(v), pos(0) {}
~VectorIterator() {
std::cout << "vector iterator has been destructed" << std::endl;
}
Option next() override {
if (pos >= vec.size()) {
return Option::None();
}
T value = vec[pos++];
// You can construct Rust enum with fields in C++
return Option::Some(value);
}
};
int main() {
// You can call Rust functions that return things by value, and store that
// value in your stack.
auto s = Vec::new_();
s.push(2);
Vec::push(s, 5);
s.push(7);
Vec::push(s, 3);
// You can call Rust functions just like normal Rust.
std::cout << s.clone().into_iter().sum() << std::endl;
// You can catch Rust panics as C++ exceptions
try {
std::cout << "s[2] = " << *s.get(2).unwrap() << std::endl;
std::cout << "s[4] = " << *s.get(4).unwrap() << std::endl;
} catch (rust::Panic e) {
std::cout << "Rust panic happened" << std::endl;
}
int state = 0;
// You can convert a C++ lambda into a `Box` and friends.
auto f = BoxDyn>::make_box([&](int32_t x) {
state += x;
std::cout << "hello " << x << " " << state << "\n";
return x * 2;
});
// And pass it to Rust functions that accept closures.
auto x = s.into_iter().map(std::move(f)).sum();
std::cout << x << " " << state << "\n";
std::vector vec{10, 20, 60};
// You can convert a C++ type that implements `Trait` to a `Box`.
// `make_box` is similar to the `make_unique`, it takes constructor arguments
// and construct it inside the `Box` (instead of `unique_ptr`).
auto vec_as_iter = BoxDyn>::make_box<
VectorIterator>(std::move(vec));
// Then use it like a normal Rust value.
auto t = vec_as_iter.collect();
// Some utilities are also provided. For example, `zngur_dbg` is the
// equivalent of `dbg!` macro.
zngur_dbg(t);
}
```
Output:
```
17
s[2] = 7
thread '' panicked at 'called `Option::unwrap()` on a `None` value', examples/simple/src/generated.rs:186:39
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
s[4] = Rust panic happened
hello 2 2
hello 5 7
hello 7 14
hello 3 17
34 17
vector iterator has been destructed
[main.cpp:71] t = [
10,
20,
60,
]
```
See the [`examples/simple`](https://github.com/HKalbasi/zngur/blob/main/examples/simple) if you want to build and run it.
## Installation
The `zngur` CLI tool can be installed with cargo:
```
cargo install zngur-cli
```
## Contributing
Because our examples require invoking a built `zngur` binary, we use `xtask` to orchestrate the build process and validate correctness across all examples.
1. **Install mise**: This project uses `mise` for tool management. Install it from [mise.jdx.dev](https://mise.jdx.dev/) or via your package manager.
2. **Install dependencies**: Run `mise install` to install the required tools. See [`mise.toml`](/mise.toml) for the list of installed tools.
3. **Run the CI locally**: The official command to run our CI is:
```bash
CXX=clang++ cargo xtask ci
```
You can use any of the C++ compilers mentioned in our CI workflow: `clang++` or `g++`.
Other compilers may work, but are not guaranteed to by our CI testing.
### Formatting
You may run `cargo xtask format-book` to run `mdformat` on the `/book` directory.
#### License
Licensed under either of Apache License, Version
2.0 or MIT license at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in this project by you, as defined in the Apache-2.0 license,
shall be dual licensed as above, without any additional terms or conditions.
================================================
FILE: benchmark/.gitignore
================================================
/target
================================================
FILE: benchmark/Cargo.toml
================================================
[package]
name = "benchmark"
version = "0.9.0"
edition.workspace = true
rust-version.workspace = true
license.workspace = true
publish = false
[dependencies]
[dev-dependencies]
criterion = { version = "0.5", features = ["html_reports"] }
[build-dependencies]
cc = "1.0"
build-rs = "0.1.2"
zngur = { path = "../zngur" }
[[bench]]
name = "simple"
harness = false
================================================
FILE: benchmark/benches/simple.rs
================================================
use criterion::{Criterion, criterion_group, criterion_main};
use std::hint::black_box;
fn criterion_benchmark(c: &mut Criterion) {
c.bench_function("build_vec_by_push 10_000 rust", |b| {
b.iter(|| benchmark::build_vec_by_push_rust(black_box(10_000)))
});
c.bench_function("build_vec_by_push 10_000 cpp", |b| {
b.iter(|| benchmark::build_vec_by_push_cpp(black_box(10_000)))
});
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
================================================
FILE: benchmark/build.rs
================================================
use zngur::Zngur;
fn main() {
build::rerun_if_changed("main.zng");
build::rerun_if_changed("impls.cpp");
#[cfg(not(target_os = "windows"))]
let cxx = std::env::var("CXX").unwrap_or("c++".to_owned());
#[cfg(not(target_os = "windows"))]
let lto_enabled = cxx.ends_with("clang++") && cfg!(target_os = "linux");
#[cfg(not(target_os = "windows"))]
if lto_enabled {
build::rustc_env("RUSTC_FLAGS", "-C linker-plugin-lto -C linker=clang");
build::rustc_link_arg("-fuse-ld=lld");
}
let crate_dir = build::cargo_manifest_dir();
let out_dir = build::out_dir();
Zngur::from_zng_file(crate_dir.join("main.zng"))
.with_cpp_file(out_dir.join("generated.cpp"))
.with_h_file(out_dir.join("generated.h"))
.with_rs_file(out_dir.join("generated.rs"))
.with_zng_header_in_place_as(true)
.generate();
let my_build = &mut cc::Build::new();
let my_build = my_build.cpp(true).std("c++17");
#[cfg(not(target_os = "windows"))]
my_build.compiler(cxx);
my_build.include(&crate_dir).include(&out_dir);
#[cfg(not(target_os = "windows"))]
if lto_enabled {
my_build.flag("-flto");
}
let my_build = || my_build.clone();
my_build()
.file(out_dir.join("generated.cpp"))
.compile("zngur_generated");
my_build().file("impls.cpp").compile("impls");
}
================================================
FILE: benchmark/impls.cpp
================================================
#include
template
using Vec = rust::std::vec::Vec;
using u64 = uint64_t;
namespace rust::exported_functions {
auto build_vec_by_push_cpp(u64 n) -> Vec {
auto v = Vec::new_();
for (u64 i = 0; i < n; ++i) {
v.push(i);
}
return v;
}
}
================================================
FILE: benchmark/main.zng
================================================
type ::std::vec::Vec {
#layout(size = 24, align = 8);
wellknown_traits(Debug);
fn new() -> ::std::vec::Vec;
fn push(&mut self, u64);
}
extern "C++" {
fn build_vec_by_push_cpp(u64) -> ::std::vec::Vec;
}
================================================
FILE: benchmark/src/lib.rs
================================================
mod generated {
include!(concat!(env!("OUT_DIR"), "/generated.rs"));
}
pub fn build_vec_by_push_rust(n: u64) -> Vec {
let mut v = Vec::new();
for i in 0..n {
v.push(i);
}
v
}
pub fn build_vec_by_push_cpp(n: u64) -> Vec {
generated::build_vec_by_push_cpp(n)
}
================================================
FILE: cspell-words.txt
================================================
alignas
alignof
assocs
autozng
barbaz
barbazxxx
blobstore
cerr
chumsky
cloneable
Conds
constexpr
cout
cplusplus
CPTE
Crubit
csignal
cstddef
cstdint
cstring
CXXFLAGS
decltype
delem
deinit
depfile
digset
discontiguous
emsdk
endl
fastlink
flto
foldl
foldr
funcs
fvec
GNUC
hkalbasi
ilog
impls
indexmap
inplace
itertools
libexample
LIBPATH
libyourcrate
lwasi
mdformat
memcpy
moveit
msvc
newtype
noexcept
nmake
ntdll
pmut
primitve
println
ptrdiff
refmut
relpath
repr
respecify
rlib
rustc
RUSTC
RUSTFLAGS
RUSTLIB
Rustup
rustup
rustyline
Rustyline
scrutinee
scrutinees
serde
SIGSEGV
sptl
sref
ssize
staticlib
strvec
stmnt
unimportability
Uninit
uninit
usize
userenv
WASI
WINLIBS
wasi
WASIFLAGS
wasip
wasmtime
xshell
xtask
zngur
Zngur
Zngur's
zngur's
zængɑr
zigza
zoop
ifndef
endif
ifdef
selectany
declspec
elif
askama
endfor
================================================
FILE: cspell.json
================================================
{
"$schema": "https://raw.githubusercontent.com/streetsidesoftware/cspell/main/cspell.schema.json",
"version": "0.2",
"dictionaryDefinitions": [
{
"name": "project-words",
"path": "./cspell-words.txt",
"addWords": true
}
],
"dictionaries": [
"project-words"
],
"ignorePaths": [
"target",
"*generated*.*",
"/cspell-words.txt",
"*.zng.h",
"*.svg",
"examples/**/Makefile",
"examples/**/NMakefile",
"actual_output.txt"
]
}
================================================
FILE: dprint.json
================================================
{
"markdown": {
"lineWidth": 100,
"emphasisKind": "asterisks",
"strongKind": "asterisks",
"textWrap": "maintain",
"ignoreDirective": "dprint-ignore",
"ignoreFileDirective": "dprint-ignore-file",
"ignoreStartDirective": "dprint-ignore-start",
"ignoreEndDirective": "dprint-ignore-end",
"newLineKind": "lf"
},
"includes": ["book/src/**/*.md", "*.md"],
"excludes": [],
"plugins": ["https://plugins.dprint.dev/markdown-0.17.8.wasm"]
}
================================================
FILE: examples/.gitignore
================================================
zngur.h
*.zng.*
================================================
FILE: examples/char/.gitignore
================================================
generated.h
generated.rs
================================================
FILE: examples/char/Cargo.toml
================================================
[package]
name = "example-char"
version = "0.9.0"
edition.workspace = true
rust-version.workspace = true
license.workspace = true
publish = false
[lib]
crate-type = ["staticlib"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
================================================
FILE: examples/char/Makefile
================================================
a.out: main.cpp generated.h src/generated.rs src/lib.rs ../../target/release/libexample_char.a
${CXX} -std=c++11 -Werror -I. main.cpp -g -L ../../target/release/ -l example_char
../../target/release/libexample_char.a:
cargo build --release
generated.h ./src/generated.rs: main.zng
cd ../../zngur-cli && cargo run g -i ../examples/char/main.zng --crate-name "crate"
.PHONY: ../../target/release/libexample_char.a generated.h clean
clean:
rm -f generated.h generated.cpp src/generated.rs a.out actual_output.txt
================================================
FILE: examples/char/NMakefile
================================================
CXX = cl.exe
# MSVC doesn't support earlier that c++14
CXXFLAGS = /W4 /DEBUG /EHsc /std:c++14
WINLIBS = ntdll.lib
EXAMPLE_NAME = char
GENERATED = generated.h src/generated.rs
RUSTLIB_PATH = ../../target/release/
RUSTLIB = example_$(EXAMPLE_NAME).lib
a.exe : main.cpp src/lib.rs $(GENERATED) $(RUSTLIB_PATH)/$(RUSTLIB)
$(CXX) $(CXXFLAGS) main.cpp /Fe:a.exe /link $(WINLIBS) $(RUSTLIB) /LIBPATH:$(RUSTLIB_PATH)
$(RUSTLIB_PATH)/$(RUSTLIB) :
cargo build --release
$(GENERATED) : main.zng
cd ../../zngur-cli && cargo run g -i ../examples/$(EXAMPLE_NAME)/main.zng --crate-name "crate"
clean :
- del /f /q generated.h generated.cpp src\generated.rs a.exe main.obj actual_output.txt 2>nul
================================================
FILE: examples/char/expected_output.txt
================================================
Rust received char: 'A' (U+0041)
Rust received char: 'é' (U+00E9)
Rust received char: 'Z' (U+005A)
Rust received char: '�' (U+FFFD)
================================================
FILE: examples/char/main.cpp
================================================
#include "./generated.h"
using ::operator""_rs;
int main() {
// Pass a char literal directly using the _rs suffix
rust::crate::CharPrinter::print(U'A'_rs);
// Pass a char from a char32_t variable
char32_t c = U'\u00E9'; // é
rust::crate::CharPrinter::print(operator""_rs(c));
// Use a char in a predicate
if (rust::crate::CharPrinter::is_alphabetic(U'z'_rs)) {
rust::crate::CharPrinter::print(rust::crate::CharPrinter::to_uppercase(U'z'_rs));
}
// Invalid chars are replaced with U+FFFD
char32_t invalid = 0xD800; // Surrogate code point
rust::crate::CharPrinter::print(operator""_rs(invalid));
return 0;
}
================================================
FILE: examples/char/main.zng
================================================
type char {
#layout(size = 4, align = 4);
wellknown_traits(Copy);
}
type bool {
#layout(size = 1, align = 1);
wellknown_traits(Copy);
}
type crate::CharPrinter {
#layout(size = 0, align = 1);
fn print(char);
fn is_alphabetic(char) -> bool;
fn to_uppercase(char) -> char;
}
================================================
FILE: examples/char/src/lib.rs
================================================
#[rustfmt::skip]
mod generated;
struct CharPrinter;
impl CharPrinter {
fn print(c: char) {
println!("Rust received char: '{}' (U+{:04X})", c, c as u32);
}
fn is_alphabetic(c: char) -> bool {
c.is_alphabetic()
}
fn to_uppercase(c: char) -> char {
c.to_uppercase().next().unwrap_or(c)
}
}
================================================
FILE: examples/conditional/.gitignore
================================================
generated.h
generated.rs
generated*.rs
generated.cpp
history.txt
b.out
================================================
FILE: examples/conditional/Cargo.toml
================================================
[package]
name = "example-conditional"
version = "0.9.0"
edition.workspace = true
rust-version.workspace = true
license.workspace = true
publish = false
[lib]
crate-type = ["staticlib"]
[features]
default = []
float-values = []
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
================================================
FILE: examples/conditional/Makefile
================================================
both:: a.out b.out
a.out: main.cpp include/float/generated.h src/lib.rs ../../target/release/libexample_conditional.a
${CXX} -std=c++20 -Werror main.cpp -g -I include/float -o a.out -L../../target/release -l example_conditional
b.out: main.cpp include/int/generated.h src/lib.rs ../../target/debug/libexample_conditional.a
${CXX} -std=c++20 -Werror main.cpp -g -I include/int -o b.out -L../../target/debug -l example_conditional
../../target/release/libexample_conditional.a: ./src/generated_float.rs
cargo build --release -F "float-values"
../../target/debug/libexample_conditional.a: ./src/generated_int.rs
cargo build
include/float/generated.h ./src/generated_float.rs: main.zng
mkdir -p include/float
cd ../../zngur-cli && cargo run g -i ../examples/conditional/main.zng --h-file ../examples/conditional/include/float/generated.h --rs-file ../examples/conditional/src/generated_float.rs -F "float-values" --load-cfg-from-rustc --use-cargo-rustc --profile=release --package example-conditional --crate-name "crate"
include/int/generated.h ./src/generated_int.rs: main.zng
mkdir -p include/int
cd ../../zngur-cli && cargo run g -i ../examples/conditional/main.zng --h-file ../examples/conditional/include/int/generated.h --rs-file ../examples/conditional/src/generated_int.rs --load-cfg-from-rustc --crate-name "crate"
.PHONY: ../../target/release/libexample_conditional.a ../../target/debug/libexample_conditional.a include/float/generated.h include/int/generated.h clean
clean:
rm -f include/float/generated.h include/int/generated.h generated.cpp src/generated_float.rs src/generated_int.rs a.out b.out actual_output.txt
================================================
FILE: examples/conditional/NMakefile
================================================
CXX = cl.exe
CXXFLAGS = /W4 /DEBUG /EHsc /std:c++20
WINLIBS = ntdll.lib Userenv.lib Ws2_32.lib
EXAMPLE_NAME = conditional
GENERATED_A = include/float/generated.h ./src/generated_float.rs
GENERATED_B = include/int/generated.h ./src/generated_int.rs
RUSTLIB_PATH_A = ../../target/release/
RUSTLIB_PATH_B = ../../target/debug/
RUSTLIB = example_$(EXAMPLE_NAME).lib
all : a.exe b.exe
a.exe : main.cpp src/lib.rs $(GENERATED_A) $(RUSTLIB_PATH_A)/$(RUSTLIB)
$(CXX) $(CXXFLAGS) /c main.cpp /I include/float /Fo: "a"
$(CXX) $(CXXFLAGS) a.obj /Fe:a.exe /link $(WINLIBS) $(RUSTLIB) /LIBPATH:$(RUSTLIB_PATH_A)
b.exe : main.cpp src/lib.rs $(GENERATED_B) $(RUSTLIB_PATH_B)/$(RUSTLIB)
$(CXX) $(CXXFLAGS) /c main.cpp /I include/int /Fo: "b"
$(CXX) $(CXXFLAGS) b.obj /Fe:b.exe /link $(WINLIBS) $(RUSTLIB) /LIBPATH:$(RUSTLIB_PATH_B)
$(RUSTLIB_PATH_A)/$(RUSTLIB) :
cargo build --release -F "float-values"
$(RUSTLIB_PATH_B)/$(RUSTLIB) :
cargo build
$(GENERATED_A) : main.zng
IF NOT EXIST "include" mkdir include
IF NOT EXIST "include\float" mkdir "include\float"
cd ../../zngur-cli && cargo run g -i ../examples/$(EXAMPLE_NAME)/main.zng --h-file ../examples/$(EXAMPLE_NAME)/include/float/generated.h --rs-file ../examples/$(EXAMPLE_NAME)/src/generated_float.rs -F "float-values" --load-cfg-from-rustc --use-cargo-rustc --profile=release --package example-conditional --crate-name "crate"
$(GENERATED_B) : main.zng
IF NOT EXIST "include" mkdir include
IF NOT EXIST "include\int" mkdir "include\int"
cd ../../zngur-cli && cargo run g -i ../examples/$(EXAMPLE_NAME)/main.zng --h-file ../examples/$(EXAMPLE_NAME)/include/int/generated.h --rs-file ../examples/$(EXAMPLE_NAME)/src/generated_int.rs --load-cfg-from-rustc --crate-name "crate"
clean :
- del /f /q include\float\generated.h include\int\generated.h generated.cpp src\generated_float.rs src\generated_int.rs a.exe b.exe a.obj b.obj actual_output.txt 2>nul
================================================
FILE: examples/conditional/README.md
================================================
# Example: Conditional
A example, used to demonstrate conditional compilation
To run this example:
```
make
./a.out
```
================================================
FILE: examples/conditional/expected_output.txt
================================================
KVPair(size = 32, align = 8){foo : 1.000000}
[main.cpp:44] pair = KeyValuePair[f64] { key: "foo", value: 1.0, }
KVPair(size = 32, align = 8){bar : 2.000000}
[main.cpp:44] pair = KeyValuePair[f64] { key: "bar", value: 2.0, }
KVPair(size = 32, align = 8){baz : 3.000000}
[main.cpp:44] pair = KeyValuePair[f64] { key: "baz", value: 3.0, }
KVPair(size = 32, align = 8){abc : 4.000000}
[main.cpp:44] pair = KeyValuePair[f64] { key: "abc", value: 4.0, }
KVPair(size = 32, align = 8){foo : 1}
[main.cpp:44] pair = KeyValuePair[i32] { key: "foo", value: 1, }(with debug_assertions)
KVPair(size = 32, align = 8){bar : 2}
[main.cpp:44] pair = KeyValuePair[i32] { key: "bar", value: 2, }(with debug_assertions)
KVPair(size = 32, align = 8){baz : 3}
[main.cpp:44] pair = KeyValuePair[i32] { key: "baz", value: 3, }(with debug_assertions)
KVPair(size = 32, align = 8){abc : 4}
[main.cpp:44] pair = KeyValuePair[i32] { key: "abc", value: 4, }(with debug_assertions)
================================================
FILE: examples/conditional/main.cpp
================================================
#include
#include
#include
#include
#include
#include
#include "generated.h"
// Rust values are available in the `::rust` namespace from their absolute path
// in Rust
template using Vec = rust::std::vec::Vec;
template using Option = rust::std::option::Option;
using KVPair = rust::crate::KeyValuePair;
#ifdef ZNGUR_CFG_FEATURE_FLOAT_VALUES
using KVPairValue_T = ::std::double_t;
#else
using KVPairValue_T = ::std::int32_t;
#endif
int main() {
auto s = Vec::new_();
std::vector, int>> pairs = {
{"foo"_rs, 1}, {"bar"_rs, 2}, {"baz"_rs, 3}, {"abc"_rs, 4}};
for (const auto &[key, value] : pairs) {
s.push(KVPair{key.to_owned(), static_cast(value)});
}
auto it = s.iter();
for (auto next = it.next(); next.matches_Some(); next = it.next()) {
auto pair = next.unwrap();
rust::Ref key = pair.key;
KVPairValue_T value = pair.value;
std::cout << "KVPair(size = " << KVPair::self_size()
<< ", align = " << KVPair::self_align() << "){"
<< std::string_view(
reinterpret_cast(key.as_str().as_ptr()),
key.len())
<< " : " << std::to_string(value) << "}\n";
zngur_dbg(pair);
}
}
================================================
FILE: examples/conditional/main.zng
================================================
#convert_panic_to_exception
#unstable(cfg_if)
type str {
wellknown_traits(?Sized, Debug);
fn as_ptr(&self) -> *const u8;
fn len(&self) -> usize;
fn to_owned(&self) -> ::std::string::String;
}
type ::std::string::String {
#layout(size = 24, align = 8);
wellknown_traits(Debug);
fn clone(&self) -> ::std::string::String;
fn push_str(&mut self, &str);
fn len(&self) -> usize;
fn as_str(&self) -> &str;
}
mod crate {
type KeyValuePair {
#layout(size = 32, align = 8);
wellknown_traits(Debug);
#if cfg!(feature."float-values") {
constructor { key: ::std::string::String, value: f64 };
} #else {
constructor { key: ::std::string::String, value: i32 };
}
fn self_size() -> usize;
fn self_align() -> usize;
field key (offset = 0, type = ::std::string::String );
#if cfg!(feature."float-values") {
field value (offset = 24, type = f64 );
} #else {
field value (offset = 24, type = i32 );
}
}
}
mod ::std {
type option::Option {
#layout(size = 16, align = 8);
constructor None;
constructor Some(usize);
fn unwrap(self) -> usize;
}
type option::Option {
#layout(size = 32, align = 8);
constructor None;
constructor Some(crate::KeyValuePair);
fn unwrap(self) -> crate::KeyValuePair;
}
type option::Option<&crate::KeyValuePair> {
#layout(size = 8, align = 8);
wellknown_traits(Copy);
constructor None;
constructor Some(&crate::KeyValuePair);
fn unwrap(self) -> &crate::KeyValuePair;
}
mod vec {
type Vec {
#layout(size = 24, align = 8);
wellknown_traits(Debug);
fn new() -> Vec;
fn push(&mut self, crate::KeyValuePair);
fn get(&self, usize) -> ::std::option::Option<&crate::KeyValuePair> deref [crate::KeyValuePair];
fn iter(&self) -> ::std::slice::Iter deref [crate::KeyValuePair];
}
}
mod slice {
type Iter {
#layout(size = 16, align = 8);
fn len(&self) -> usize;
fn size_hint(&self) -> (usize, ::std::option::Option);
fn count(self) -> usize;
fn next(&mut self) -> ::std::option::Option<&crate::KeyValuePair>;
}
}
}
type (usize, ::std::option::Option) {
#layout(size = 24, align = 8);
wellknown_traits(Debug);
field 0 (offset = 0, type = usize);
field 1 (offset = 8, type = ::std::option::Option );
}
================================================
FILE: examples/conditional/src/lib.rs
================================================
/// only in place to allow both build to build sid by side in CI
#[rustfmt::skip]
#[cfg(feature = "float-values")]
mod generated_float;
#[rustfmt::skip]
#[cfg(not(feature = "float-values"))]
mod generated_int;
struct KeyValuePair {
pub key: String,
#[cfg(feature = "float-values")]
pub value: f64,
#[cfg(not(feature = "float-values"))]
pub value: i32,
}
impl KeyValuePair {
fn self_size() -> usize {
std::mem::size_of::()
}
fn self_align() -> usize {
std::mem::align_of::()
}
}
#[cfg(debug_assertions)]
impl std::fmt::Debug for KeyValuePair {
#[cfg(feature = "float-values")]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"KeyValuePair[f64] {{ key: {:?}, value: {:?}, }}(with debug_assertions)",
&self.key, &self.value
)
}
#[cfg(not(feature = "float-values"))]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"KeyValuePair[i32] {{ key: {:?}, value: {:?}, }}(with debug_assertions)",
&self.key, &self.value
)
}
}
#[cfg(not(debug_assertions))]
impl std::fmt::Debug for KeyValuePair {
#[cfg(feature = "float-values")]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"KeyValuePair[f64] {{ key: {:?}, value: {:?}, }}",
&self.key, &self.value
)
}
#[cfg(not(feature = "float-values"))]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"KeyValuePair[i32] {{ key: {:?}, value: {:?}, }}",
&self.key, &self.value
)
}
}
================================================
FILE: examples/cxx_demo/.gitignore
================================================
generated.h
generated.rs
generated.cpp
history.txt
================================================
FILE: examples/cxx_demo/Cargo.toml
================================================
[package]
name = "example-cxx_demo"
version = "0.9.0"
edition.workspace = true
rust-version.workspace = true
license.workspace = true
publish = false
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
[build-dependencies]
cc = "1.0"
build-rs = "0.1.2"
zngur = { path = "../../zngur" }
================================================
FILE: examples/cxx_demo/README.md
================================================
# Example: CXX demo
This example tries to replicate [the CXX demo](https://github.com/dtolnay/cxx/tree/master/demo) using Zngur. It tries to keep it as close
as possible to the original CXX example, so it doesn't use Zngur features that may make the code easier, more readable, and more
performant. To see an example that uses all Zngur features in C++ to Rust codes, go to the osmium example.
To run this example:
```
cargo run
```
================================================
FILE: examples/cxx_demo/blobstore.cpp
================================================
#include
#include
#include
#include
#include "./generated.h"
class BlobStore : public rust::crate::BlobStoreTrait {
class Impl {
friend BlobStore;
using Blob = struct {
std::string data;
std::set tags;
};
std::unordered_map blobs;
};
public:
uint64_t put(rust::RefMut buf) override {
std::string contents;
// Traverse the caller's chunk iterator.
//
// In reality there might be sophisticated batching of chunks and/or
// parallel upload implemented by the blob_store's C++ client.
while (true) {
auto chunk = buf.next_chunk();
if (chunk.len() == 0) {
break;
}
contents.append(reinterpret_cast(chunk.as_ptr()),
chunk.len());
}
// Insert into map and provide caller the handle.
auto blob_id = std::hash{}(contents);
impl.blobs[blob_id] = {std::move(contents), {}};
return blob_id;
}
rust::Unit tag(::uint64_t blob_id,
rust::Ref tag) override {
impl.blobs[blob_id].tags.emplace((char *)tag.as_ptr(), tag.len());
return rust::Unit{};
}
rust::crate::BlobMetadata metadata(::uint64_t blob_id) override {
rust::crate::BlobMetadata r = rust::crate::BlobMetadata::default_();
auto blob = impl.blobs.find(blob_id);
if (blob != impl.blobs.end()) {
r.set_size(blob->second.data.size());
std::for_each(blob->second.tags.cbegin(), blob->second.tags.cend(),
[&](auto &t) {
r.push_tag(reinterpret_cast(t.c_str()));
});
}
return r;
}
private:
Impl impl;
};
rust::Box>
rust::exported_functions::new_blob_store_client() {
return rust::Box>::make_box<
BlobStore>();
}
================================================
FILE: examples/cxx_demo/build.rs
================================================
#[cfg(not(target_os = "windows"))]
use std::env;
use zngur::Zngur;
fn main() {
build::rerun_if_changed("main.zng");
build::rerun_if_changed("blobstore.cpp");
build::rerun_if_changed("src/");
build::rerun_if_env_changed("CXX");
#[cfg(not(target_os = "windows"))]
let cxx = env::var("CXX").unwrap_or("c++".to_owned());
let crate_dir = build::cargo_manifest_dir();
Zngur::from_zng_file(crate_dir.join("main.zng"))
.with_cpp_file(crate_dir.join("generated.cpp"))
.with_h_file(crate_dir.join("generated.h"))
.with_rs_file(crate_dir.join("./src/generated.rs"))
.with_crate_name("crate")
.with_zng_header_in_place()
.generate();
let my_build = &mut cc::Build::new();
let my_build = my_build.cpp(true).std("c++17");
#[cfg(not(target_os = "windows"))]
my_build.compiler(&cxx);
let my_build = || my_build.clone();
my_build().file("generated.cpp").compile("zngur_generated");
my_build().file("blobstore.cpp").compile("blobstore");
}
================================================
FILE: examples/cxx_demo/expected_output.txt
================================================
metadata = BlobMetadata { size: 19, tags: ["rust"] }
================================================
FILE: examples/cxx_demo/main.zng
================================================
type [u8] {
wellknown_traits(?Sized);
fn as_ptr(&self) -> *const u8;
fn len(&self) -> usize;
}
type str {
wellknown_traits(?Sized);
fn as_ptr(&self) -> *const u8;
fn len(&self) -> usize;
}
mod crate {
type MultiBuf {
#layout(size = 32, align = 8);
fn next_chunk(&mut self) -> &[u8];
}
type BlobMetadata {
#layout(size = 32, align = 8);
fn default() -> BlobMetadata;
fn set_size(&mut self, usize);
fn push_tag(&mut self, *const i8);
}
trait BlobStoreTrait {
fn put(&self, &mut MultiBuf) -> u64;
fn tag(&self, u64, &str);
fn metadata(&self, u64) -> BlobMetadata;
}
type Box {
#layout(size = 16, align = 8);
fn put(&self, &mut MultiBuf) -> u64 deref dyn BlobStoreTrait;
fn tag(&self, u64, &str) deref dyn BlobStoreTrait;
fn metadata(&self, u64) -> BlobMetadata deref dyn BlobStoreTrait;
}
}
extern "C++" {
fn new_blob_store_client() -> Box;
}
================================================
FILE: examples/cxx_demo/src/main.rs
================================================
#[rustfmt::skip]
mod generated;
use generated::new_blob_store_client;
// An iterator over contiguous chunks of a discontiguous file object. Toy
// implementation uses a Vec> but in reality this might be iterating
// over some more complex Rust data structure like a rope, or maybe loading
// chunks lazily from somewhere.
pub struct MultiBuf {
chunks: Vec>,
pos: usize,
}
impl MultiBuf {
pub fn next_chunk(&mut self) -> &[u8] {
let next = self.chunks.get(self.pos);
self.pos += 1;
next.map_or(&[], Vec::as_slice)
}
}
#[derive(Debug, Default)]
struct BlobMetadata {
size: usize,
tags: Vec,
}
impl BlobMetadata {
fn set_size(&mut self, size: usize) {
self.size = size;
}
fn push_tag(&mut self, c: *const i8) {
self.tags.push(
String::from_utf8_lossy(unsafe { std::ffi::CStr::from_ptr(c).to_bytes() }).to_string(),
);
}
}
trait BlobStoreTrait {
fn put(&self, buf: &mut MultiBuf) -> u64;
fn tag(&self, blob_id: u64, tag: &str);
fn metadata(&self, blob_id: u64) -> BlobMetadata;
}
fn main() {
let client = new_blob_store_client();
// Upload a blob_.
let chunks = vec![b"fearless".to_vec(), b"concurrency".to_vec()];
let mut buf = MultiBuf { chunks, pos: 0 };
let blob_id = client.put(&mut buf);
// Add a tag.
client.tag(blob_id, "rust");
// Read back the tags.
let metadata = client.metadata(blob_id);
println!("metadata = {:?}", metadata);
}
================================================
FILE: examples/cxx_demo_split/.gitignore
================================================
generated.h
generated.rs
generated.cpp
history.txt
================================================
FILE: examples/cxx_demo_split/Cargo.toml
================================================
[package]
name = "example-cxx_demo_split"
version = "0.9.0"
edition.workspace = true
rust-version.workspace = true
license.workspace = true
publish = false
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
[build-dependencies]
cc = "1.0"
build-rs = "0.1.2"
zngur = { path = "../../zngur" }
================================================
FILE: examples/cxx_demo_split/README.md
================================================
# Example: CXX demo
This example tries to replicate [the CXX demo](https://github.com/dtolnay/cxx/tree/master/demo) using Zngur. It tries to keep it as close
as possible to the original CXX example, so it doesn't use Zngur features that may make the code easier, more readable, and more
performant. To see an example that uses all Zngur features in C++ to Rust codes, go to the osmium example.
To run this example:
```
cargo run
```
================================================
FILE: examples/cxx_demo_split/blobstore.cpp
================================================
#include
#include
#include
#include
#include "./generated.h"
class BlobStore : public rust::crate::BlobStoreTrait {
class Impl {
friend BlobStore;
using Blob = struct {
std::string data;
std::set tags;
};
std::unordered_map blobs;
};
public:
uint64_t put(rust::RefMut buf) override {
std::string contents;
// Traverse the caller's chunk iterator.
//
// In reality there might be sophisticated batching of chunks and/or
// parallel upload implemented by the blob_store's C++ client.
while (true) {
auto chunk = buf.next_chunk();
if (chunk.len() == 0) {
break;
}
contents.append(reinterpret_cast(chunk.as_ptr()),
chunk.len());
}
// Insert into map and provide caller the handle.
auto blob_id = std::hash{}(contents);
impl.blobs[blob_id] = {std::move(contents), {}};
return blob_id;
}
rust::Unit tag(::uint64_t blob_id,
rust::Ref tag) override {
impl.blobs[blob_id].tags.emplace((char *)tag.as_ptr(), tag.len());
return rust::Unit{};
}
rust::crate::BlobMetadata metadata(::uint64_t blob_id) override {
rust::crate::BlobMetadata r = rust::crate::BlobMetadata::default_();
auto blob = impl.blobs.find(blob_id);
if (blob != impl.blobs.end()) {
r.set_size(blob->second.data.size());
std::for_each(blob->second.tags.cbegin(), blob->second.tags.cend(),
[&](auto &t) {
r.push_tag(reinterpret_cast(t.c_str()));
});
}
return r;
}
private:
Impl impl;
};
rust::Box>
rust::exported_functions::new_blob_store_client() {
return rust::Box>::make_box<
BlobStore>();
}
================================================
FILE: examples/cxx_demo_split/build.rs
================================================
#[cfg(not(target_os = "windows"))]
use std::env;
use zngur::Zngur;
fn main() {
build::rerun_if_changed("main.zng");
build::rerun_if_changed("blobstore.cpp");
build::rerun_if_changed("src/");
build::rerun_if_changed("zngur.h");
build::rerun_if_env_changed("CXX");
#[cfg(not(target_os = "windows"))]
let cxx = env::var("CXX").unwrap_or("c++".to_owned());
let crate_dir = build::cargo_manifest_dir();
Zngur::from_zng_file(crate_dir.join("main.zng"))
.with_cpp_file(crate_dir.join("generated.cpp"))
.with_h_file(crate_dir.join("generated.h"))
.with_rs_file(crate_dir.join("./src/generated.rs"))
.with_crate_name("crate")
.with_zng_header("zngur.h")
.generate();
let my_build = &mut cc::Build::new();
let my_build = my_build.cpp(true).std("c++17").include(".");
#[cfg(not(target_os = "windows"))]
my_build.compiler(&cxx);
let my_build = || my_build.clone();
my_build().file("generated.cpp").compile("zngur_generated");
my_build().file("blobstore.cpp").compile("blobstore");
}
================================================
FILE: examples/cxx_demo_split/expected_output.txt
================================================
metadata = BlobMetadata { size: 19, tags: ["rust"] }
================================================
FILE: examples/cxx_demo_split/main.zng
================================================
type [u8] {
wellknown_traits(?Sized);
fn as_ptr(&self) -> *const u8;
fn len(&self) -> usize;
}
type str {
wellknown_traits(?Sized);
fn as_ptr(&self) -> *const u8;
fn len(&self) -> usize;
}
mod crate {
type MultiBuf {
#layout(size = 32, align = 8);
fn next_chunk(&mut self) -> &[u8];
}
type BlobMetadata {
#layout(size = 32, align = 8);
fn default() -> BlobMetadata;
fn set_size(&mut self, usize);
fn push_tag(&mut self, *const i8);
}
trait BlobStoreTrait {
fn put(&self, &mut MultiBuf) -> u64;
fn tag(&self, u64, &str);
fn metadata(&self, u64) -> BlobMetadata;
}
type Box {
#layout(size = 16, align = 8);
fn put(&self, &mut MultiBuf) -> u64 deref dyn BlobStoreTrait;
fn tag(&self, u64, &str) deref dyn BlobStoreTrait;
fn metadata(&self, u64) -> BlobMetadata deref dyn BlobStoreTrait;
}
}
extern "C++" {
fn new_blob_store_client() -> Box;
}
================================================
FILE: examples/cxx_demo_split/src/main.rs
================================================
#[rustfmt::skip]
mod generated;
use generated::new_blob_store_client;
// An iterator over contiguous chunks of a discontiguous file object. Toy
// implementation uses a Vec> but in reality this might be iterating
// over some more complex Rust data structure like a rope, or maybe loading
// chunks lazily from somewhere.
pub struct MultiBuf {
chunks: Vec>,
pos: usize,
}
impl MultiBuf {
pub fn next_chunk(&mut self) -> &[u8] {
let next = self.chunks.get(self.pos);
self.pos += 1;
next.map_or(&[], Vec::as_slice)
}
}
#[derive(Debug, Default)]
struct BlobMetadata {
size: usize,
tags: Vec,
}
impl BlobMetadata {
fn set_size(&mut self, size: usize) {
self.size = size;
}
fn push_tag(&mut self, c: *const i8) {
self.tags.push(
String::from_utf8_lossy(unsafe { std::ffi::CStr::from_ptr(c).to_bytes() }).to_string(),
);
}
}
trait BlobStoreTrait {
fn put(&self, buf: &mut MultiBuf) -> u64;
fn tag(&self, blob_id: u64, tag: &str);
fn metadata(&self, blob_id: u64) -> BlobMetadata;
}
fn main() {
let client = new_blob_store_client();
// Upload a blob_.
let chunks = vec![b"fearless".to_vec(), b"concurrency".to_vec()];
let mut buf = MultiBuf { chunks, pos: 0 };
let blob_id = client.put(&mut buf);
// Add a tag.
client.tag(blob_id, "rust");
// Read back the tags.
let metadata = client.metadata(blob_id);
println!("metadata = {:?}", metadata);
}
================================================
FILE: examples/impl_trait/.gitignore
================================================
generated.h
generated.rs
generated.cpp
================================================
FILE: examples/impl_trait/Cargo.toml
================================================
[package]
name = "example-impl-trait"
version = "0.9.0"
edition.workspace = true
rust-version.workspace = true
license.workspace = true
publish = false
[lib]
crate-type = ["staticlib"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
================================================
FILE: examples/impl_trait/Makefile
================================================
a.out: main.cpp generated.h src/generated.rs src/lib.rs ../../target/release/libexample_impl_trait.a
${CXX} -std=c++20 -Werror main.cpp -g -L ../../target/release/ -l example_impl_trait
../../target/release/libexample_impl_trait.a:
cargo build --release
generated.h ./src/generated.rs: main.zng
cd ../../zngur-cli && cargo run g -i ../examples/impl_trait/main.zng --crate-name "crate"
.PHONY: ../../target/release/libexample_impl_trait.a generated.h clean
clean:
rm -f generated.h generated.cpp src/generated.rs a.out actual_output.txt
================================================
FILE: examples/impl_trait/NMakefile
================================================
CXX = cl.exe
CXXFLAGS = /W4 /DEBUG /EHsc /std:c++20
WINLIBS = ntdll.lib
EXAMPLE_NAME = impl_trait
GENERATED = generated.h src/generated.rs
RUSTLIB_PATH = ../../target/release/
RUSTLIB = example_$(EXAMPLE_NAME).lib
a.exe : main.cpp src/lib.rs $(GENERATED) $(RUSTLIB_PATH)/$(RUSTLIB)
$(CXX) $(CXXFLAGS) main.cpp /Fe:a.exe /link $(WINLIBS) $(RUSTLIB) /LIBPATH:$(RUSTLIB_PATH)
$(RUSTLIB_PATH)/$(RUSTLIB) :
cargo build --release
$(GENERATED) : main.zng
cd ../../zngur-cli && cargo run g -i ../examples/$(EXAMPLE_NAME)/main.zng --crate-name "crate"
clean :
- del /f /q generated.h generated.cpp src\generated.rs a.exe main.obj actual_output.txt 2>nul
================================================
FILE: examples/impl_trait/README.md
================================================
# Example: Regression test 1
A example, used to check previous Zngur problems in CI.
To run this example:
```
make
./a.out
```
================================================
FILE: examples/impl_trait/expected_output.txt
================================================
Print debug -- 5
Print debug -- "hello"
Print debug -- 4
Print debug -- "foo"
Print debug -- "foo"
Print debug -- "Rust futures are lazy"
Async func 1
Future done with result 43
Async func 2
Future done with result 44
Print debug -- "Before calling impl_future"
Before async block
Print debug -- "Before polling impl_future"
Inside async block
Future done with result 45
================================================
FILE: examples/impl_trait/main.cpp
================================================
#include
#include
#include "./generated.h"
using DynDebug = rust::Dyn;
int main() {
rust::crate::argument_position_impl_trait(5);
rust::crate::argument_position_impl_trait("hello"_rs.to_owned());
rust::crate::argument_position_impl_trait(
rust::crate::return_position_impl_trait());
rust::Box elem = rust::crate::both_impl_trait("foo"_rs);
rust::crate::argument_position_impl_trait(elem.deref());
rust::crate::argument_position_impl_trait(std::move(elem));
auto future = rust::crate::async_func1();
rust::crate::argument_position_impl_trait(
"Rust futures are lazy"_rs.to_owned());
rust::crate::busy_wait_future(std::move(future));
rust::crate::busy_wait_future(rust::crate::async_func2());
rust::crate::argument_position_impl_trait(
"Before calling impl_future"_rs.to_owned());
future = rust::crate::impl_future();
rust::crate::argument_position_impl_trait(
"Before polling impl_future"_rs.to_owned());
rust::crate::busy_wait_future(std::move(future));
}
================================================
FILE: examples/impl_trait/main.zng
================================================
#convert_panic_to_exception
type str {
wellknown_traits(?Sized, Debug);
fn as_ptr(&self) -> *const u8;
fn len(&self) -> usize;
fn to_owned(&self) -> ::std::string::String;
}
type dyn ::std::fmt::Debug {
wellknown_traits(?Sized, Debug);
}
type Box {
#layout(size = 16, align = 8);
fn deref(&self) -> &dyn ::std::fmt::Debug use ::std::ops::Deref;
}
type Box> {
#layout(size = 16, align = 8);
}
type ::std::string::String {
#layout(size = 24, align = 8);
wellknown_traits(Debug);
fn clone(&self) -> ::std::string::String;
fn push_str(&mut self, &str);
fn len(&self) -> usize;
}
mod crate {
fn argument_position_impl_trait(i32);
fn argument_position_impl_trait(::std::string::String);
fn argument_position_impl_trait(Box);
fn argument_position_impl_trait(&dyn ::std::fmt::Debug);
fn return_position_impl_trait() -> impl ::std::fmt::Debug;
fn both_impl_trait(&str) -> impl ::std::fmt::Debug;
fn async_func1() -> impl ::std::future::Future