forked from M-Labs/nac3
1
0
Fork 0

Compare commits

...

45 Commits

Author SHA1 Message Date
lyken 819e1e4608 a 2024-07-27 12:35:22 +08:00
lyken 86ed0140cb core/model: add ListModel 2024-07-27 02:57:02 +08:00
lyken cd777dcb52 core/model: add Pointer::{is_null,is_not_null} 2024-07-27 02:12:55 +08:00
lyken d2ab7b89be core/model: add From<BasicValueEnum> for Opaque 2024-07-27 01:51:18 +08:00
lyken 5c6537565c core/ndstrides: implement general ndarray reshaping 2024-07-26 17:37:07 +08:00
lyken 7372ef0504 core/ndstrides: implement general ndarray basic indexing 2024-07-26 17:37:05 +08:00
lyken bf2026e010 core/ndstrides: implement IRRT slice
Needed by ndarray indexing
2024-07-26 16:31:42 +08:00
lyken 85ef06f1e2 core/ndstrides: implement ndarray np_{empty,ndarray,zeros,ones,full} 2024-07-26 16:23:11 +08:00
lyken fc9d47fb54 core/irrt: fix error context check logic error 2024-07-26 16:21:42 +08:00
lyken e14eba05d2 core/ndstrides: implement ndarray len() 2024-07-26 15:50:22 +08:00
lyken adb43958d0 core: make get_llvm_type return new NDArray with strides
NOTE: All old numpy functions are now impossible to run, until NDArray
with strides is fully implemented.
2024-07-26 15:45:32 +08:00
lyken ba79cfe39f core: allow clippy changes 2024-07-26 15:38:23 +08:00
lyken 04897ec8d4 core/ndstrides: add basic NDArray IRRT functions 2024-07-26 15:36:44 +08:00
lyken f78a60a644 core/codegen: add ArrayWriter & parse_input_shape_arg 2024-07-26 15:26:58 +08:00
lyken 19c2beffbb core/irrt: fix improper template def 2024-07-26 15:06:57 +08:00
lyken 92b97a9f4f core/ndstrides: add NDArray definition with strides 2024-07-26 15:06:14 +08:00
lyken 9c3a10377f core/irrt: add ErrorContext
ErrorContext allows IRRT to report a Python-like exception
2024-07-26 15:01:09 +08:00
lyken 80e56bc081 core: fix list_slice_assignment assert int type 2024-07-26 14:59:11 +08:00
lyken 8a6dc1c1e1 core/model: refactor core to use CSlice & Exception 2024-07-26 14:50:23 +08:00
lyken b304df8bcc core/model: add SizeTModel::constant 2024-07-26 13:37:04 +08:00
lyken 679315acad core/model: add CSlice & Exception models 2024-07-26 13:20:06 +08:00
lyken afab0a997c core/irrt: add cstr_utils 2024-07-26 12:39:59 +08:00
lyken ae88175c4c core/irrt: comment arrays_match() 2024-07-26 12:36:52 +08:00
lyken ab663c3ec8 core/model: introduce `Model<'ctx>` abstraction 2024-07-26 12:33:58 +08:00
lyken f9dc6bf40c core/irrt: introduce irrt testing
`cargo test -F test` would compile `nac3core/irrt/irrt_test.cpp`
targetted to the host machine (it gets to use `std`) and run the
test executable.
2024-07-26 12:32:41 +08:00
lyken e127171c81 core/irrt: split irrt.cpp into headers
To scale IRRT implementations
2024-07-26 12:32:11 +08:00
lyken 3e22e366ce core/irrt: build.rs capture IR defined constants 2024-07-26 12:29:16 +08:00
lyken 98f7547695 core/irrt: build.rs capture IR defined types 2024-07-26 12:29:16 +08:00
lyken e5fd93c0e0 core/irrt: reformat 2024-07-26 12:29:16 +08:00
lyken b8b9a589f8 core: add .clang-format 2024-07-26 12:27:46 +08:00
lyken 1f19a8b54b core/irrt: comment build.rs & move irrt to its own dir
To prepare for future IRRT implementations, and to also make cargo
only have to watch a single directory.
2024-07-22 17:32:32 +08:00
lyken 44487b76ae standalone: interpret_demo.py remove duplicated section 2024-07-22 17:23:35 +08:00
lyken 1332f113e8 standalone: fix interpret_demo.py comments 2024-07-22 17:06:14 +08:00
Sébastien Bourdeauducq 7632d6f72a cargo: update dependencies 2024-07-21 11:00:25 +08:00
David Mak 4948395ca2 core/toplevel/type_annotation: Add handling for mismatching class def
Primitive types only contain fields in its Type and not its TopLevelDef.
This causes primitive object types to lack some fields.
2024-07-19 14:42:14 +08:00
David Mak 3db3061d99 artiq/symbol_resolver: Handle type of zero-length lists 2024-07-19 14:42:14 +08:00
David Mak 51c2175c80 core/codegen/stmt: Convert assertion values to i1 2024-07-19 14:42:14 +08:00
lyken 1a31a50b8a
standalone: fix __nac3_raise def in demo.c 2024-07-17 21:22:08 +08:00
lyken 6c10e3d056 core: cargo clippy 2024-07-12 21:18:53 +08:00
lyken 2dbc1ec659 cargo fmt 2024-07-12 21:16:38 +08:00
Sebastien Bourdeauducq c80378063a add np_argmin/argmax to interpret_demo environment 2024-07-12 13:27:52 +02:00
abdul124 513d30152b core: support raise exception short form 2024-07-12 18:58:34 +08:00
abdul124 45e9360c4d standalone: Add np_argmax and np_argmin tests 2024-07-12 18:19:56 +08:00
abdul124 2e01b77fc8 core: refactor np_max/np_min functions 2024-07-12 18:18:54 +08:00
abdul124 cea7cade51 core: add np_argmax/np_argmin functions 2024-07-12 18:18:28 +08:00
82 changed files with 5903 additions and 1008 deletions

3
.clang-format Normal file
View File

@ -0,0 +1,3 @@
BasedOnStyle: Google
IndentWidth: 4
ReflowComments: false

46
Cargo.lock generated
View File

@ -117,9 +117,9 @@ checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
[[package]]
name = "cc"
version = "1.1.0"
version = "1.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eaff6f8ce506b9773fa786672d63fc7a191ffea1be33f72bbd4aeacefca9ffc8"
checksum = "2aba8f4e9906c7ce3c73463f62a7f0c65183ada1a2d47e397cc8810827f9694f"
[[package]]
name = "cfg-if"
@ -158,7 +158,7 @@ dependencies = [
"heck 0.5.0",
"proc-macro2",
"quote",
"syn 2.0.70",
"syn 2.0.71",
]
[[package]]
@ -421,7 +421,7 @@ checksum = "4fa4d8d74483041a882adaa9a29f633253a66dde85055f0495c121620ac484b2"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.70",
"syn 2.0.71",
]
[[package]]
@ -513,9 +513,9 @@ checksum = "97b3888a4aecf77e811145cadf6eef5901f4782c53886191b2f693f24761847c"
[[package]]
name = "libloading"
version = "0.8.4"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e310b3a6b5907f99202fcdb4960ff45b93735d7c7d96b760fcff8db2dc0e103d"
checksum = "4979f22fdb869068da03c9f7528f8297c6fd2606bc3a4affe42e6a823fdb8da4"
dependencies = [
"cfg-if",
"windows-targets",
@ -749,7 +749,7 @@ dependencies = [
"phf_shared 0.11.2",
"proc-macro2",
"quote",
"syn 2.0.70",
"syn 2.0.71",
]
[[package]]
@ -778,9 +778,9 @@ checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315"
[[package]]
name = "portable-atomic"
version = "1.6.0"
version = "1.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7170ef9988bc169ba16dd36a7fa041e5c4cbeb6a35b76d4c03daded371eae7c0"
checksum = "da544ee218f0d287a911e9c99a39a8c9bc8fcad3cb8db5959940044ecfc67265"
[[package]]
name = "ppv-lite86"
@ -850,7 +850,7 @@ dependencies = [
"proc-macro2",
"pyo3-macros-backend",
"quote",
"syn 2.0.70",
"syn 2.0.71",
]
[[package]]
@ -863,7 +863,7 @@ dependencies = [
"proc-macro2",
"pyo3-build-config",
"quote",
"syn 2.0.70",
"syn 2.0.71",
]
[[package]]
@ -927,9 +927,9 @@ dependencies = [
[[package]]
name = "redox_syscall"
version = "0.5.2"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c82cf8cff14456045f55ec4241383baeff27af886adb72ffb2162f99911de0fd"
checksum = "2a908a6e00f1fdd0dfd9c0eb08ce85126f6d8bbda50017e74bc4a4b7d4a926a4"
dependencies = [
"bitflags",
]
@ -1044,7 +1044,7 @@ checksum = "e0cd7e117be63d3c3678776753929474f3b04a43a080c744d6b0ae2a8c28e222"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.70",
"syn 2.0.71",
]
[[package]]
@ -1134,7 +1134,7 @@ dependencies = [
"proc-macro2",
"quote",
"rustversion",
"syn 2.0.70",
"syn 2.0.71",
]
[[package]]
@ -1150,9 +1150,9 @@ dependencies = [
[[package]]
name = "syn"
version = "2.0.70"
version = "2.0.71"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f0209b68b3613b093e0ec905354eccaedcfe83b8cb37cbdeae64026c3064c16"
checksum = "b146dcf730474b4bcd16c311627b31ede9ab149045db4d6088b3becaea046462"
dependencies = [
"proc-macro2",
"quote",
@ -1203,22 +1203,22 @@ dependencies = [
[[package]]
name = "thiserror"
version = "1.0.61"
version = "1.0.63"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c546c80d6be4bc6a00c0f01730c08df82eaa7a7a61f11d656526506112cc1709"
checksum = "c0342370b38b6a11b6cc11d6a805569958d54cfa061a29969c3b5ce2ea405724"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "1.0.61"
version = "1.0.63"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46c3384250002a6d5af4d114f2845d37b57521033f30d5c3f46c4d70e1197533"
checksum = "a4558b58466b9ad7ca0f102865eccc95938dca1a74a856f2b57b6629050da261"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.70",
"syn 2.0.71",
]
[[package]]
@ -1486,5 +1486,5 @@ checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.70",
"syn 2.0.71",
]

View File

@ -13,6 +13,7 @@
''
mkdir -p $out/bin
ln -s ${pkgs.llvmPackages_14.clang-unwrapped}/bin/clang $out/bin/clang-irrt
ln -s ${pkgs.llvmPackages_14.clang}/bin/clang $out/bin/clang-irrt-test
ln -s ${pkgs.llvmPackages_14.llvm.out}/bin/llvm-as $out/bin/llvm-as-irrt
'';
nac3artiq = pkgs.python3Packages.toPythonModule (
@ -23,6 +24,7 @@
cargoLock = {
lockFile = ./Cargo.lock;
};
cargoTestFlags = [ "--features" "test" ];
passthru.cargoLock = cargoLock;
nativeBuildInputs = [ pkgs.python3 pkgs.llvmPackages_14.clang llvm-tools-irrt pkgs.llvmPackages_14.llvm.out llvm-nac3 ];
buildInputs = [ pkgs.python3 llvm-nac3 ];
@ -149,7 +151,7 @@
buildInputs = with pkgs; [
# build dependencies
packages.x86_64-linux.llvm-nac3
llvmPackages_14.clang llvmPackages_14.llvm.out # for running nac3standalone demos
llvmPackages_14.clang llvmPackages_14.llvm.out llvmPackages_14.lldb.out # for running nac3standalone demos
packages.x86_64-linux.llvm-tools-irrt
cargo
rustc
@ -161,7 +163,9 @@
clippy
pre-commit
rustfmt
rust-analyzer
];
RUST_SRC_PATH = "${pkgs.rust.packages.stable.rustPlatform.rustLibSrc}";
};
devShells.x86_64-linux.msys2 = pkgs.mkShell {
name = "nac3-dev-shell-msys2";

View File

@ -0,0 +1,24 @@
from min_artiq import *
from numpy import int32
@nac3
class EmptyList:
core: KernelInvariant[Core]
def __init__(self):
self.core = Core()
@rpc
def get_empty(self) -> list[int32]:
return []
@kernel
def run(self):
a: list[int32] = self.get_empty()
if a != []:
raise ValueError
if __name__ == "__main__":
EmptyList().run()

View File

@ -991,8 +991,15 @@ impl InnerResolver {
}
_ => unreachable!("must be list"),
};
let ty = ctx.get_llvm_type(generator, elem_ty);
let size_t = generator.get_size_type(ctx.ctx);
let ty = if len == 0
&& matches!(&*ctx.unifier.get_ty_immutable(elem_ty), TypeEnum::TVar { .. })
{
// The default type for zero-length lists of unknown element type is size_t
size_t.into()
} else {
ctx.get_llvm_type(generator, elem_ty)
};
let arr_ty = ctx
.ctx
.struct_type(&[ty.ptr_type(AddressSpace::default()).into(), size_t.into()], false);

View File

@ -1,3 +1,6 @@
[features]
test = []
[package]
name = "nac3core"
version = "0.1.0"

View File

@ -3,20 +3,34 @@ use std::{
env,
fs::File,
io::Write,
path::Path,
path::{Path, PathBuf},
process::{Command, Stdio},
};
fn main() {
const FILE: &str = "src/codegen/irrt/irrt.cpp";
const CMD_IRRT_CLANG: &str = "clang-irrt";
const CMD_IRRT_CLANG_TEST: &str = "clang-irrt-test";
const CMD_IRRT_LLVM_AS: &str = "llvm-as-irrt";
fn get_out_dir() -> PathBuf {
PathBuf::from(env::var("OUT_DIR").unwrap())
}
fn get_irrt_dir() -> &'static Path {
Path::new("irrt")
}
/// Compile `irrt.cpp` for use in `src/codegen`
fn compile_irrt_cpp() {
let out_dir = get_out_dir();
let irrt_dir = get_irrt_dir();
/*
* HACK: Sadly, clang doesn't let us emit generic LLVM bitcode.
* Compiling for WASM32 and filtering the output with regex is the closest we can get.
*/
let irrt_cpp_path = irrt_dir.join("irrt.cpp");
let flags: &[&str] = &[
"--target=wasm32",
FILE,
"-x",
"c++",
"-fno-discard-value-names",
@ -33,13 +47,16 @@ fn main() {
"-Wextra",
"-o",
"-",
"-I",
irrt_dir.to_str().unwrap(),
irrt_cpp_path.to_str().unwrap(),
];
println!("cargo:rerun-if-changed={FILE}");
let out_dir = env::var("OUT_DIR").unwrap();
let out_path = Path::new(&out_dir);
// Tell Cargo to rerun if any file under `irrt_dir` (recursive) changes
println!("cargo:rerun-if-changed={}", irrt_dir.to_str().unwrap());
let output = Command::new("clang-irrt")
// Compile IRRT and capture the LLVM IR output
let output = Command::new(CMD_IRRT_CLANG)
.args(flags)
.output()
.map(|o| {
@ -52,7 +69,17 @@ fn main() {
let output = std::str::from_utf8(&output.stdout).unwrap().replace("\r\n", "\n");
let mut filtered_output = String::with_capacity(output.len());
let regex_filter = Regex::new(r"(?ms:^define.*?\}$)|(?m:^declare.*?$)").unwrap();
// Filter out irrelevant IR
//
// Regex:
// - `(?ms:^define.*?\}$)` captures LLVM `define` blocks
// - `(?m:^declare.*?$)` captures LLVM `declare` lines
// - `(?m:^%.+?=\s*type\s*\{.+?\}$)` captures LLVM `type` declarations
// - `(?m:^@.+?=.+$)` captures global constants
let regex_filter = Regex::new(
r"(?ms:^define.*?\}$)|(?m:^declare.*?$)|(?m:^%.+?=\s*type\s*\{.+?\}$)|(?m:^@.+?=.+$)",
)
.unwrap();
for f in regex_filter.captures_iter(&output) {
assert_eq!(f.len(), 1);
filtered_output.push_str(&f[0]);
@ -63,20 +90,71 @@ fn main() {
.unwrap()
.replace_all(&filtered_output, "");
println!("cargo:rerun-if-env-changed=DEBUG_DUMP_IRRT");
if env::var("DEBUG_DUMP_IRRT").is_ok() {
let mut file = File::create(out_path.join("irrt.ll")).unwrap();
// For debugging
// Doing `DEBUG_DUMP_IRRT=1 cargo build -p nac3core` dumps the LLVM IR generated
const DEBUG_DUMP_IRRT: &str = "DEBUG_DUMP_IRRT";
println!("cargo:rerun-if-env-changed={DEBUG_DUMP_IRRT}");
if env::var(DEBUG_DUMP_IRRT).is_ok() {
let mut file = File::create(out_dir.join("irrt.ll")).unwrap();
file.write_all(output.as_bytes()).unwrap();
let mut file = File::create(out_path.join("irrt-filtered.ll")).unwrap();
let mut file = File::create(out_dir.join("irrt-filtered.ll")).unwrap();
file.write_all(filtered_output.as_bytes()).unwrap();
}
let mut llvm_as = Command::new("llvm-as-irrt")
// Assemble the emitted and filtered IR to .bc
// That .bc will be integrated into nac3core's codegen
let mut llvm_as = Command::new(CMD_IRRT_LLVM_AS)
.stdin(Stdio::piped())
.arg("-o")
.arg(out_path.join("irrt.bc"))
.arg(out_dir.join("irrt.bc"))
.spawn()
.unwrap();
llvm_as.stdin.as_mut().unwrap().write_all(filtered_output.as_bytes()).unwrap();
assert!(llvm_as.wait().unwrap().success());
}
/// Compile `irrt_test.cpp` for testing
fn compile_irrt_test_cpp() {
let out_dir = get_out_dir();
let irrt_dir = get_irrt_dir();
let exe_path = out_dir.join("irrt_test.out"); // Output path of the compiled test executable
let irrt_test_cpp_path = irrt_dir.join("irrt_test.cpp");
let flags: &[&str] = &[
irrt_test_cpp_path.to_str().unwrap(),
"-x",
"c++",
"-I",
irrt_dir.to_str().unwrap(),
"-g",
"-fno-discard-value-names",
"-O0",
"-Wall",
"-Wextra",
"-Werror=return-type",
"-lm", // for `tgamma()`, `lgamma()`
"-o",
exe_path.to_str().unwrap(),
];
Command::new(CMD_IRRT_CLANG_TEST)
.args(flags)
.output()
.map(|o| {
assert!(o.status.success(), "{}", std::str::from_utf8(&o.stderr).unwrap());
o
})
.unwrap();
println!("cargo:rerun-if-changed={}", irrt_dir.to_str().unwrap());
}
fn main() {
compile_irrt_cpp();
// https://github.com/rust-lang/cargo/issues/2549
// `cargo test -F test` to also build `irrt_test.cpp
if cfg!(feature = "test") {
compile_irrt_test_cpp();
}
}

10
nac3core/irrt/irrt.cpp Normal file
View File

@ -0,0 +1,10 @@
#define IRRT_DEFINE_TYPEDEF_INTS
#include <irrt_everything.hpp>
/*
* All IRRT implementations.
*
* We don't have pre-compiled objects, so we are writing all implementations in
* headers and concatenate them with `#include` into one massive source file that
* contains all the IRRT stuff.
*/

View File

@ -0,0 +1,39 @@
#pragma once
#include <irrt/int_defs.hpp>
/*
This file defines all ARTIQ-specific structures
*/
/**
* @brief ARTIQ's `cslice` object
*
* See https://docs.rs/cslice/0.3.0/src/cslice/lib.rs.html#33-37
*/
template <typename SizeT>
struct CSlice {
const char *base;
SizeT len;
};
/**
* @brief Int type of ARTIQ's `Exception` IDs.
*/
typedef uint32_t ExceptionId;
/**
* @brief ARTIQ's `Exception` object
*
* See https://github.com/m-labs/artiq/blob/b0d2705c385f64b6e6711c1726cd9178f40b598e/artiq/firmware/libeh/eh_artiq.rs#L1C1-L17C1
*/
template <typename SizeT>
struct Exception {
ExceptionId id;
CSlice<SizeT> file;
uint32_t line;
uint32_t column;
CSlice<SizeT> function;
CSlice<SizeT> message;
uint32_t param;
};

View File

@ -1,27 +1,15 @@
using int8_t = _BitInt(8);
using uint8_t = unsigned _BitInt(8);
using int32_t = _BitInt(32);
using uint32_t = unsigned _BitInt(32);
using int64_t = _BitInt(64);
using uint64_t = unsigned _BitInt(64);
#pragma once
#include <irrt/int_defs.hpp>
#include <irrt/slice.hpp>
#include <irrt/utils.hpp>
// NDArray indices are always `uint32_t`.
using NDIndex = uint32_t;
// The type of an index or a value describing the length of a range/slice is always `int32_t`.
using SliceIndex = int32_t;
using NDIndexInt = uint32_t;
namespace {
template <typename T>
const T& max(const T& a, const T& b) {
return a > b ? a : b;
}
template <typename T>
const T& min(const T& a, const T& b) {
return a > b ? b : a;
}
// adapted from GNU Scientific Library: https://git.savannah.gnu.org/cgit/gsl.git/tree/sys/pow_int.c
// adapted from GNU Scientific Library:
// https://git.savannah.gnu.org/cgit/gsl.git/tree/sys/pow_int.c
// need to make sure `exp >= 0` before calling this function
template <typename T>
T __nac3_int_exp_impl(T base, T exp) {
@ -38,12 +26,8 @@ T __nac3_int_exp_impl(T base, T exp) {
}
template <typename SizeT>
SizeT __nac3_ndarray_calc_size_impl(
const SizeT* list_data,
SizeT list_len,
SizeT begin_idx,
SizeT end_idx
) {
SizeT __nac3_ndarray_calc_size_impl(const SizeT* list_data, SizeT list_len,
SizeT begin_idx, SizeT end_idx) {
__builtin_assume(end_idx <= list_len);
SizeT num_elems = 1;
@ -56,12 +40,8 @@ SizeT __nac3_ndarray_calc_size_impl(
}
template <typename SizeT>
void __nac3_ndarray_calc_nd_indices_impl(
SizeT index,
const SizeT* dims,
SizeT num_dims,
NDIndex* idxs
) {
void __nac3_ndarray_calc_nd_indices_impl(SizeT index, const SizeT* dims,
SizeT num_dims, NDIndexInt* idxs) {
SizeT stride = 1;
for (SizeT dim = 0; dim < num_dims; dim++) {
SizeT i = num_dims - dim - 1;
@ -72,12 +52,9 @@ void __nac3_ndarray_calc_nd_indices_impl(
}
template <typename SizeT>
SizeT __nac3_ndarray_flatten_index_impl(
const SizeT* dims,
SizeT num_dims,
const NDIndex* indices,
SizeT num_indices
) {
SizeT __nac3_ndarray_flatten_index_impl(const SizeT* dims, SizeT num_dims,
const NDIndexInt* indices,
SizeT num_indices) {
SizeT idx = 0;
SizeT stride = 1;
for (SizeT i = 0; i < num_dims; ++i) {
@ -93,18 +70,17 @@ SizeT __nac3_ndarray_flatten_index_impl(
}
template <typename SizeT>
void __nac3_ndarray_calc_broadcast_impl(
const SizeT* lhs_dims,
SizeT lhs_ndims,
const SizeT* rhs_dims,
SizeT rhs_ndims,
SizeT* out_dims
) {
void __nac3_ndarray_calc_broadcast_impl(const SizeT* lhs_dims, SizeT lhs_ndims,
const SizeT* rhs_dims, SizeT rhs_ndims,
SizeT* out_dims) {
SizeT max_ndims = lhs_ndims > rhs_ndims ? lhs_ndims : rhs_ndims;
for (SizeT i = 0; i < max_ndims; ++i) {
const SizeT* lhs_dim_sz = i < lhs_ndims ? &lhs_dims[lhs_ndims - i - 1] : nullptr;
const SizeT* rhs_dim_sz = i < rhs_ndims ? &rhs_dims[rhs_ndims - i - 1] : nullptr;
const SizeT* lhs_dim_sz =
i < lhs_ndims ? &lhs_dims[lhs_ndims - i - 1] : nullptr;
const SizeT* rhs_dim_sz =
i < rhs_ndims ? &rhs_dims[rhs_ndims - i - 1] : nullptr;
SizeT* out_dim = &out_dims[max_ndims - i - 1];
if (lhs_dim_sz == nullptr) {
@ -124,12 +100,10 @@ void __nac3_ndarray_calc_broadcast_impl(
}
template <typename SizeT>
void __nac3_ndarray_calc_broadcast_idx_impl(
const SizeT* src_dims,
SizeT src_ndims,
const NDIndex* in_idx,
NDIndex* out_idx
) {
void __nac3_ndarray_calc_broadcast_idx_impl(const SizeT* src_dims,
SizeT src_ndims,
const NDIndexInt* in_idx,
NDIndexInt* out_idx) {
for (SizeT i = 0; i < src_ndims; ++i) {
SizeT src_i = src_ndims - i - 1;
out_idx[src_i] = src_dims[src_i] == 1 ? 0 : in_idx[src_i];
@ -138,15 +112,15 @@ void __nac3_ndarray_calc_broadcast_idx_impl(
} // namespace
extern "C" {
#define DEF_nac3_int_exp_(T) \
T __nac3_int_exp_##T(T base, T exp) {\
return __nac3_int_exp_impl(base, exp);\
#define DEF_nac3_int_exp_(T) \
T __nac3_int_exp_##T(T base, T exp) { \
return __nac3_int_exp_impl(base, exp); \
}
DEF_nac3_int_exp_(int32_t)
DEF_nac3_int_exp_(int64_t)
DEF_nac3_int_exp_(uint32_t)
DEF_nac3_int_exp_(uint64_t)
DEF_nac3_int_exp_(int32_t);
DEF_nac3_int_exp_(int64_t);
DEF_nac3_int_exp_(uint32_t);
DEF_nac3_int_exp_(uint64_t);
SliceIndex __nac3_slice_index_bound(SliceIndex i, const SliceIndex len) {
if (i < 0) {
@ -160,11 +134,8 @@ SliceIndex __nac3_slice_index_bound(SliceIndex i, const SliceIndex len) {
return i;
}
SliceIndex __nac3_range_slice_len(
const SliceIndex start,
const SliceIndex end,
const SliceIndex step
) {
SliceIndex __nac3_range_slice_len(const SliceIndex start, const SliceIndex end,
const SliceIndex step) {
SliceIndex diff = end - start;
if (diff > 0 && step > 0) {
return ((diff - 1) / step) + 1;
@ -180,62 +151,52 @@ SliceIndex __nac3_range_slice_len(
// - All the index must *not* be out-of-bound or negative,
// - The end index is *inclusive*,
// - The length of src and dest slice size should already
// be checked: if dest.step == 1 then len(src) <= len(dest) else len(src) == len(dest)
// be checked: if dest.step == 1 then len(src) <= len(dest) else
// len(src) == len(dest)
SliceIndex __nac3_list_slice_assign_var_size(
SliceIndex dest_start,
SliceIndex dest_end,
SliceIndex dest_step,
uint8_t* dest_arr,
SliceIndex dest_arr_len,
SliceIndex src_start,
SliceIndex src_end,
SliceIndex src_step,
uint8_t* src_arr,
SliceIndex src_arr_len,
const SliceIndex size
) {
/* if dest_arr_len == 0, do nothing since we do not support extending list */
SliceIndex dest_start, SliceIndex dest_end, SliceIndex dest_step,
uint8_t* dest_arr, SliceIndex dest_arr_len, SliceIndex src_start,
SliceIndex src_end, SliceIndex src_step, uint8_t* src_arr,
SliceIndex src_arr_len, const SliceIndex size) {
/* if dest_arr_len == 0, do nothing since we do not support
* extending list
*/
if (dest_arr_len == 0) return dest_arr_len;
/* if both step is 1, memmove directly, handle the dropping of the list, and shrink size */
/* if both step is 1, memmove directly, handle the dropping of
* the list, and shrink size */
if (src_step == dest_step && dest_step == 1) {
const SliceIndex src_len = (src_end >= src_start) ? (src_end - src_start + 1) : 0;
const SliceIndex dest_len = (dest_end >= dest_start) ? (dest_end - dest_start + 1) : 0;
const SliceIndex src_len =
(src_end >= src_start) ? (src_end - src_start + 1) : 0;
const SliceIndex dest_len =
(dest_end >= dest_start) ? (dest_end - dest_start + 1) : 0;
if (src_len > 0) {
__builtin_memmove(
dest_arr + dest_start * size,
src_arr + src_start * size,
src_len * size
);
__builtin_memmove(dest_arr + dest_start * size,
src_arr + src_start * size, src_len * size);
}
if (dest_len > 0) {
/* dropping */
__builtin_memmove(
dest_arr + (dest_start + src_len) * size,
dest_arr + (dest_end + 1) * size,
(dest_arr_len - dest_end - 1) * size
);
__builtin_memmove(dest_arr + (dest_start + src_len) * size,
dest_arr + (dest_end + 1) * size,
(dest_arr_len - dest_end - 1) * size);
}
/* shrink size */
return dest_arr_len - (dest_len - src_len);
}
/* if two range overlaps, need alloca */
uint8_t need_alloca =
(dest_arr == src_arr)
&& !(
max(dest_start, dest_end) < min(src_start, src_end)
|| max(src_start, src_end) < min(dest_start, dest_end)
);
(dest_arr == src_arr) &&
!(max(dest_start, dest_end) < min(src_start, src_end) ||
max(src_start, src_end) < min(dest_start, dest_end));
if (need_alloca) {
uint8_t* tmp = reinterpret_cast<uint8_t *>(__builtin_alloca(src_arr_len * size));
uint8_t* tmp =
reinterpret_cast<uint8_t*>(__builtin_alloca(src_arr_len * size));
__builtin_memcpy(tmp, src_arr, src_arr_len * size);
src_arr = tmp;
}
SliceIndex src_ind = src_start;
SliceIndex dest_ind = dest_start;
for (;
(src_step > 0) ? (src_ind <= src_end) : (src_ind >= src_end);
src_ind += src_step, dest_ind += dest_step
) {
for (; (src_step > 0) ? (src_ind <= src_end) : (src_ind >= src_end);
src_ind += src_step, dest_ind += dest_step) {
/* for constant optimization */
if (size == 1) {
__builtin_memcpy(dest_arr + dest_ind, src_arr + src_ind, 1);
@ -244,30 +205,26 @@ SliceIndex __nac3_list_slice_assign_var_size(
} else if (size == 8) {
__builtin_memcpy(dest_arr + dest_ind * 8, src_arr + src_ind * 8, 8);
} else {
/* memcpy for var size, cannot overlap after previous alloca */
__builtin_memcpy(dest_arr + dest_ind * size, src_arr + src_ind * size, size);
/* memcpy for var size, cannot overlap after previous
* alloca */
__builtin_memcpy(dest_arr + dest_ind * size,
src_arr + src_ind * size, size);
}
}
/* only dest_step == 1 can we shrink the dest list. */
/* size should be ensured prior to calling this function */
if (dest_step == 1 && dest_end >= dest_start) {
__builtin_memmove(
dest_arr + dest_ind * size,
dest_arr + (dest_end + 1) * size,
(dest_arr_len - dest_end - 1) * size
);
dest_arr + dest_ind * size, dest_arr + (dest_end + 1) * size,
(dest_arr_len - dest_end - 1) * size + size + size + size);
return dest_arr_len - (dest_end - dest_ind) - 1;
}
return dest_arr_len;
}
int32_t __nac3_isinf(double x) {
return __builtin_isinf(x);
}
int32_t __nac3_isinf(double x) { return __builtin_isinf(x); }
int32_t __nac3_isnan(double x) {
return __builtin_isnan(x);
}
int32_t __nac3_isnan(double x) { return __builtin_isnan(x); }
double tgamma(double arg);
@ -320,95 +277,71 @@ double __nac3_j0(double x) {
return j0(x);
}
uint32_t __nac3_ndarray_calc_size(
const uint32_t* list_data,
uint32_t list_len,
uint32_t begin_idx,
uint32_t end_idx
) {
return __nac3_ndarray_calc_size_impl(list_data, list_len, begin_idx, end_idx);
uint32_t __nac3_ndarray_calc_size(const uint32_t* list_data, uint32_t list_len,
uint32_t begin_idx, uint32_t end_idx) {
return __nac3_ndarray_calc_size_impl(list_data, list_len, begin_idx,
end_idx);
}
uint64_t __nac3_ndarray_calc_size64(
const uint64_t* list_data,
uint64_t list_len,
uint64_t begin_idx,
uint64_t end_idx
) {
return __nac3_ndarray_calc_size_impl(list_data, list_len, begin_idx, end_idx);
uint64_t __nac3_ndarray_calc_size64(const uint64_t* list_data,
uint64_t list_len, uint64_t begin_idx,
uint64_t end_idx) {
return __nac3_ndarray_calc_size_impl(list_data, list_len, begin_idx,
end_idx);
}
void __nac3_ndarray_calc_nd_indices(
uint32_t index,
const uint32_t* dims,
uint32_t num_dims,
NDIndex* idxs
) {
void __nac3_ndarray_calc_nd_indices(uint32_t index, const uint32_t* dims,
uint32_t num_dims, NDIndexInt* idxs) {
__nac3_ndarray_calc_nd_indices_impl(index, dims, num_dims, idxs);
}
void __nac3_ndarray_calc_nd_indices64(
uint64_t index,
const uint64_t* dims,
uint64_t num_dims,
NDIndex* idxs
) {
void __nac3_ndarray_calc_nd_indices64(uint64_t index, const uint64_t* dims,
uint64_t num_dims, NDIndexInt* idxs) {
__nac3_ndarray_calc_nd_indices_impl(index, dims, num_dims, idxs);
}
uint32_t __nac3_ndarray_flatten_index(
const uint32_t* dims,
uint32_t num_dims,
const NDIndex* indices,
uint32_t num_indices
) {
return __nac3_ndarray_flatten_index_impl(dims, num_dims, indices, num_indices);
uint32_t __nac3_ndarray_flatten_index(const uint32_t* dims, uint32_t num_dims,
const NDIndexInt* indices,
uint32_t num_indices) {
return __nac3_ndarray_flatten_index_impl(dims, num_dims, indices,
num_indices);
}
uint64_t __nac3_ndarray_flatten_index64(
const uint64_t* dims,
uint64_t num_dims,
const NDIndex* indices,
uint64_t num_indices
) {
return __nac3_ndarray_flatten_index_impl(dims, num_dims, indices, num_indices);
uint64_t __nac3_ndarray_flatten_index64(const uint64_t* dims, uint64_t num_dims,
const NDIndexInt* indices,
uint64_t num_indices) {
return __nac3_ndarray_flatten_index_impl(dims, num_dims, indices,
num_indices);
}
void __nac3_ndarray_calc_broadcast(
const uint32_t* lhs_dims,
uint32_t lhs_ndims,
const uint32_t* rhs_dims,
uint32_t rhs_ndims,
uint32_t* out_dims
) {
return __nac3_ndarray_calc_broadcast_impl(lhs_dims, lhs_ndims, rhs_dims, rhs_ndims, out_dims);
void __nac3_ndarray_calc_broadcast(const uint32_t* lhs_dims, uint32_t lhs_ndims,
const uint32_t* rhs_dims, uint32_t rhs_ndims,
uint32_t* out_dims) {
return __nac3_ndarray_calc_broadcast_impl(lhs_dims, lhs_ndims, rhs_dims,
rhs_ndims, out_dims);
}
void __nac3_ndarray_calc_broadcast64(
const uint64_t* lhs_dims,
uint64_t lhs_ndims,
const uint64_t* rhs_dims,
uint64_t rhs_ndims,
uint64_t* out_dims
) {
return __nac3_ndarray_calc_broadcast_impl(lhs_dims, lhs_ndims, rhs_dims, rhs_ndims, out_dims);
void __nac3_ndarray_calc_broadcast64(const uint64_t* lhs_dims,
uint64_t lhs_ndims,
const uint64_t* rhs_dims,
uint64_t rhs_ndims, uint64_t* out_dims) {
return __nac3_ndarray_calc_broadcast_impl(lhs_dims, lhs_ndims, rhs_dims,
rhs_ndims, out_dims);
}
void __nac3_ndarray_calc_broadcast_idx(
const uint32_t* src_dims,
uint32_t src_ndims,
const NDIndex* in_idx,
NDIndex* out_idx
) {
__nac3_ndarray_calc_broadcast_idx_impl(src_dims, src_ndims, in_idx, out_idx);
void __nac3_ndarray_calc_broadcast_idx(const uint32_t* src_dims,
uint32_t src_ndims,
const NDIndexInt* in_idx,
NDIndexInt* out_idx) {
__nac3_ndarray_calc_broadcast_idx_impl(src_dims, src_ndims, in_idx,
out_idx);
}
void __nac3_ndarray_calc_broadcast_idx64(
const uint64_t* src_dims,
uint64_t src_ndims,
const NDIndex* in_idx,
NDIndex* out_idx
) {
__nac3_ndarray_calc_broadcast_idx_impl(src_dims, src_ndims, in_idx, out_idx);
void __nac3_ndarray_calc_broadcast_idx64(const uint64_t* src_dims,
uint64_t src_ndims,
const NDIndexInt* in_idx,
NDIndexInt* out_idx) {
__nac3_ndarray_calc_broadcast_idx_impl(src_dims, src_ndims, in_idx,
out_idx);
}
} // extern "C"

View File

@ -0,0 +1,94 @@
#pragma once
#include <irrt/artiq_defs.hpp>
#include <irrt/int_defs.hpp>
#include <irrt/utils.hpp>
namespace {
/**
* @brief A (limited) set of known Error IDs
*/
struct ErrorIds {
ExceptionId index_error;
ExceptionId value_error;
ExceptionId assertion_error;
ExceptionId runtime_error;
ExceptionId type_error;
};
/**
* @brief The IRRT error context object
*
* This object contains all the details needed to propagate Python-like Exceptions in
* IRRT - within IRRT itself or propagate out of extern calls from nac3core.
*/
struct ErrorContext {
/**
* @brief The set of all
*/
const ErrorIds *error_ids;
// Error thrown by IRRT
ExceptionId error_id;
const char *message_template;
uint64_t param1;
uint64_t param2;
uint64_t param3;
void initialize(const ErrorIds *error_ids) {
this->error_ids = error_ids;
clear_error();
}
void clear_error() {
// Point the message_template to an empty str. Don't set it to nullptr
// as a sentinel
this->message_template = "";
}
void set_error(ExceptionId error_id, const char *message,
uint64_t param1 = 0, uint64_t param2 = 0,
uint64_t param3 = 0) {
this->error_id = error_id;
this->message_template = message;
this->param1 = param1;
this->param2 = param2;
this->param3 = param3;
}
bool has_error() { return !cstr_utils::is_empty(message_template); }
template <typename SizeT>
void get_error_str(CSlice<SizeT> *dst_str) {
dst_str->base = message_template;
dst_str->len = (SizeT)cstr_utils::length(message_template);
}
};
} // namespace
extern "C" {
void __nac3_error_context_initialize(ErrorContext *errctx,
ErrorIds *error_ids) {
errctx->initialize(error_ids);
}
bool __nac3_error_context_has_error(ErrorContext *errctx) {
return errctx->has_error();
}
void __nac3_error_context_get_error_str(ErrorContext *errctx,
CSlice<int32_t> *dst_str) {
errctx->get_error_str<int32_t>(dst_str);
}
void __nac3_error_context_get_error_str64(ErrorContext *errctx,
CSlice<int64_t> *dst_str) {
errctx->get_error_str<int64_t>(dst_str);
}
// Used for testing
void __nac3_error_dummy_raise(ErrorContext *errctx) {
errctx->set_error(errctx->error_ids->runtime_error,
"Error thrown from __nac3_error_dummy_raise");
}
}

View File

@ -0,0 +1,12 @@
#pragma once
// This is made toggleable since `irrt_test.cpp` itself would include
// headers that define these typedefs
#ifdef IRRT_DEFINE_TYPEDEF_INTS
using int8_t = _BitInt(8);
using uint8_t = unsigned _BitInt(8);
using int32_t = _BitInt(32);
using uint32_t = unsigned _BitInt(32);
using int64_t = _BitInt(64);
using uint64_t = unsigned _BitInt(64);
#endif

View File

@ -0,0 +1,305 @@
#pragma once
#include <irrt/error_context.hpp>
#include <irrt/int_defs.hpp>
#include <irrt/ndarray/def.hpp>
namespace {
namespace ndarray {
namespace basic {
namespace util {
/**
* @brief Asserts that `shape` does not contain negative dimensions.
*
* @param ndims Number of dimensions in `shape`
* @param shape The shape to check on
*/
template <typename SizeT>
void assert_shape_no_negative(ErrorContext* errctx, SizeT ndims,
const SizeT* shape) {
for (SizeT axis = 0; axis < ndims; axis++) {
if (shape[axis] < 0) {
errctx->set_error(errctx->error_ids->value_error,
"negative dimensions are not allowed; axis {0} "
"has dimension {1}",
axis, shape[axis]);
return;
}
}
}
/**
* @brief Returns the number of elements of an ndarray given its shape.
*
* @param ndims Number of dimensions in `shape`
* @param shape The shape of the ndarray
*/
template <typename SizeT>
SizeT calc_size_from_shape(SizeT ndims, const SizeT* shape) {
SizeT size = 1;
for (SizeT axis = 0; axis < ndims; axis++) size *= shape[axis];
return size;
}
/**
* @brief Compute the array indices of the `nth` (0-based) element of an ndarray given only its shape.
*
* @param ndims Number of elements in `shape` and `indices`
* @param shape The shape of the ndarray
* @param indices The returned indices indexing the ndarray with shape `shape`.
* @param nth The index of the element of interest.
*/
template <typename SizeT>
void set_indices_by_nth(SizeT ndims, const SizeT* shape, SizeT* indices,
SizeT nth) {
for (int32_t i = 0; i < ndims; i++) {
int32_t axis = ndims - i - 1;
int32_t dim = shape[axis];
indices[axis] = nth % dim;
nth /= dim;
}
}
} // namespace util
/**
* @brief Return the number of elements of an `ndarray`
*
* This function corresponds to `<an_ndarray>.size`
*/
template <typename SizeT>
SizeT size(const NDArray<SizeT>* ndarray) {
return util::calc_size_from_shape(ndarray->ndims, ndarray->shape);
}
/**
* @brief Return of the number of its content of an `ndarray`.
*
* This function corresponds to `<an_ndarray>.nbytes`.
*/
template <typename SizeT>
SizeT nbytes(const NDArray<SizeT>* ndarray) {
return size(ndarray) * ndarray->itemsize;
}
/**
* @brief Update the strides of an ndarray given an ndarray `shape`
* and assuming that the ndarray is fully c-contagious.
*
* You might want to read https://ajcr.net/stride-guide-part-1/.
*/
template <typename SizeT>
void set_strides_by_shape(NDArray<SizeT>* ndarray) {
SizeT stride_product = 1;
for (SizeT i = 0; i < ndarray->ndims; i++) {
int axis = ndarray->ndims - i - 1;
ndarray->strides[axis] = stride_product * ndarray->itemsize;
stride_product *= ndarray->shape[axis];
}
}
/**
* @brief Return the pointer to the element indexed by `indices`.
*/
template <typename SizeT>
uint8_t* get_pelement_by_indices(const NDArray<SizeT>* ndarray,
const SizeT* indices) {
uint8_t* element = ndarray->data;
for (SizeT dim_i = 0; dim_i < ndarray->ndims; dim_i++)
element += indices[dim_i] * ndarray->strides[dim_i];
return element;
}
/**
* @brief Return the pointer to the nth (0-based) element in a flattened view of `ndarray`.
*/
template <typename SizeT>
uint8_t* get_nth_pelement(const NDArray<SizeT>* ndarray, SizeT nth) {
SizeT* indices = (SizeT*)__builtin_alloca(sizeof(SizeT) * ndarray->ndims);
util::set_indices_by_nth(ndarray->ndims, ndarray->shape, indices, nth);
return get_pelement_by_indices(ndarray, indices);
}
/**
* @brief Like `get_nth_pelement` but asserts that `nth` is in bounds.
*/
template <typename SizeT>
uint8_t* checked_get_nth_pelement(ErrorContext* errctx,
const NDArray<SizeT>* ndarray, SizeT nth) {
SizeT arr_size = ndarray->size();
if (!(0 <= nth && nth < arr_size)) {
errctx->set_error(
errctx->error_ids->index_error,
"index {0} is out of bounds, valid range is {1} <= index < {2}",
nth, 0, arr_size);
return 0;
}
return get_nth_pelement(ndarray, nth);
}
/**
* @brief Set an element in `ndarray`.
*
* @param pelement Pointer to the element in `ndarray` to be set.
* @param pvalue Pointer to the value `pelement` will be set to.
*/
template <typename SizeT>
void set_pelement_value(NDArray<SizeT>* ndarray, uint8_t* pelement,
const uint8_t* pvalue) {
__builtin_memcpy(pelement, pvalue, ndarray->itemsize);
}
/**
* @brief Get the `len()` of an ndarray, and asserts that `ndarray` is a sized object.
*
* This function corresponds to `<an_ndarray>.__len__`.
*
* @param dst_length The returned result
*/
template <typename SizeT>
void len(ErrorContext* errctx, const NDArray<SizeT>* ndarray,
SliceIndex* dst_length) {
// numpy prohibits `__len__` on unsized objects
if (ndarray->ndims == 0) {
errctx->set_error(errctx->error_ids->type_error,
"len() of unsized object");
return;
}
*dst_length = (SliceIndex)ndarray->shape[0];
}
/**
* @brief Copy data from one ndarray to another of the exact same size and itemsize.
*
* Both ndarrays will be viewed in their flatten views when copying the elements.
*/
template <typename SizeT>
void copy_data(const NDArray<SizeT>* src_ndarray, NDArray<SizeT>* dst_ndarray) {
__builtin_assume(src_ndarray->itemsize == dst_ndarray->itemsize);
for (SizeT i = 0; i < size(src_ndarray); i++) {
auto src_element = ndarray::basic::get_nth_pelement(src_ndarray, i);
auto dst_element = ndarray::basic::get_nth_pelement(dst_ndarray, i);
ndarray::basic::set_pelement_value(dst_ndarray, dst_element,
src_element);
}
}
/**
* @brief Return a boolean indicating if `ndarray` is (C-)contiguous.
*
* You may want to see: ndarray's rules for C-contiguity: https://github.com/numpy/numpy/blob/df256d0d2f3bc6833699529824781c58f9c6e697/numpy/core/src/multiarray/flagsobject.c#L95C1-L99C45
*/
template <typename SizeT>
bool is_c_contiguous(const NDArray<SizeT>* ndarray) {
// Other references:
// - tinynumpy's implementation: https://github.com/wadetb/tinynumpy/blob/0d23d22e07062ffab2afa287374c7b366eebdda1/tinynumpy/tinynumpy.py#L102
// - ndarray's flags["C_CONTIGUOUS"]: https://numpy.org/doc/stable/reference/generated/numpy.ndarray.flags.html#numpy.ndarray.flags
// - ndarray's rules for C-contiguity: https://github.com/numpy/numpy/blob/df256d0d2f3bc6833699529824781c58f9c6e697/numpy/core/src/multiarray/flagsobject.c#L95C1-L99C45
// From https://github.com/numpy/numpy/blob/df256d0d2f3bc6833699529824781c58f9c6e697/numpy/core/src/multiarray/flagsobject.c#L95C1-L99C45:
//
// The traditional rule is that for an array to be flagged as C contiguous,
// the following must hold:
//
// strides[-1] == itemsize
// strides[i] == shape[i+1] * strides[i + 1]
// [...]
// According to these rules, a 0- or 1-dimensional array is either both
// C- and F-contiguous, or neither; and an array with 2+ dimensions
// can be C- or F- contiguous, or neither, but not both. Though there
// there are exceptions for arrays with zero or one item, in the first
// case the check is relaxed up to and including the first dimension
// with shape[i] == 0. In the second case `strides == itemsize` will
// can be true for all dimensions and both flags are set.
if (ndarray->ndims == 0) {
return true;
}
if (ndarray->strides[ndarray->ndims - 1] != ndarray->itemsize) {
return false;
}
for (SizeT i = 1; i < ndarray->ndims; i++) {
SizeT axis_i = ndarray->ndims - i - 1;
if (ndarray->strides[axis_i] !=
ndarray->shape[axis_i + 1] + ndarray->strides[axis_i + 1]) {
return false;
}
}
return true;
}
} // namespace basic
} // namespace ndarray
} // namespace
extern "C" {
using namespace ndarray::basic;
uint32_t __nac3_ndarray_size(NDArray<int32_t>* ndarray) {
return size(ndarray);
}
uint64_t __nac3_ndarray_size64(NDArray<int64_t>* ndarray) {
return size(ndarray);
}
uint32_t __nac3_ndarray_nbytes(NDArray<int32_t>* ndarray) {
return nbytes(ndarray);
}
uint64_t __nac3_ndarray_nbytes64(NDArray<int64_t>* ndarray) {
return nbytes(ndarray);
}
void __nac3_ndarray_len(ErrorContext* errctx, NDArray<int32_t>* ndarray,
SliceIndex* dst_len) {
return len(errctx, ndarray, dst_len);
}
void __nac3_ndarray_len64(ErrorContext* errctx, NDArray<int64_t>* ndarray,
SliceIndex* dst_len) {
return len(errctx, ndarray, dst_len);
}
void __nac3_ndarray_util_assert_shape_no_negative(ErrorContext* errctx,
int32_t ndims,
int32_t* shape) {
util::assert_shape_no_negative(errctx, ndims, shape);
}
void __nac3_ndarray_util_assert_shape_no_negative64(ErrorContext* errctx,
int64_t ndims,
int64_t* shape) {
util::assert_shape_no_negative(errctx, ndims, shape);
}
void __nac3_ndarray_set_strides_by_shape(NDArray<int32_t>* ndarray) {
set_strides_by_shape(ndarray);
}
void __nac3_ndarray_set_strides_by_shape64(NDArray<int64_t>* ndarray) {
set_strides_by_shape(ndarray);
}
bool __nac3_ndarray_is_c_contiguous(NDArray<int32_t>* ndarray) {
return is_c_contiguous(ndarray);
}
bool __nac3_ndarray_is_c_contiguous64(NDArray<int64_t>* ndarray) {
return is_c_contiguous(ndarray);
}
void __nac3_ndarray_copy_data(NDArray<int32_t>* src_ndarray,
NDArray<int32_t>* dst_ndarray) {
copy_data(src_ndarray, dst_ndarray);
}
void __nac3_ndarray_copy_data64(NDArray<int64_t>* src_ndarray,
NDArray<int64_t>* dst_ndarray) {
copy_data(src_ndarray, dst_ndarray);
}
}

View File

@ -0,0 +1,44 @@
#pragma once
namespace {
/**
* @brief The NDArray object
*
* The official numpy implementations: https://github.com/numpy/numpy/blob/735a477f0bc2b5b84d0e72d92f224bde78d4e069/doc/source/reference/c-api/types-and-structures.rst
*/
template <typename SizeT>
struct NDArray {
/**
* @brief The underlying data this `ndarray` is pointing to.
*
* Must be set to `nullptr` to indicate that this NDArray's `data` is uninitialized.
*/
uint8_t* data;
/**
* @brief The number of bytes of a single element in `data`.
*/
SizeT itemsize;
/**
* @brief The number of dimensions of this shape.
*/
SizeT ndims;
/**
* @brief The NDArray shape, with length equal to `ndims`.
*
* Note that it may contain 0.
*/
SizeT* shape;
/**
* @brief Array strides, with length equal to `ndims`
*
* The stride values are in units of bytes, not number of elements.
*
* Note that `strides` can have negative values.
*/
SizeT* strides;
};
} // namespace

View File

@ -0,0 +1,38 @@
#pragma once
#include <irrt/ndarray/basic.hpp>
#include <irrt/ndarray/def.hpp>
namespace {
namespace ndarray {
namespace fill {
/**
* Fill an ndarray with a value.
*
* @param pvalue Pointer to the fill value, and the fill value should be of `ndarray->itemsize` bytes.
*/
template <typename SizeT>
void fill_generic(NDArray<SizeT>* ndarray, const uint8_t* pvalue) {
const SizeT size = ndarray::basic::size(ndarray);
for (SizeT i = 0; i < size; i++) {
uint8_t* pelement = ndarray::basic::get_nth_pelement(
ndarray, i); // No need for checked_get_nth_pelement
ndarray::basic::set_pelement_value(ndarray, pelement, pvalue);
}
}
} // namespace fill
} // namespace ndarray
} // namespace
extern "C" {
using namespace ndarray::fill;
void __nac3_ndarray_fill_generic(NDArray<int32_t>* ndarray, uint8_t* pvalue) {
fill_generic(ndarray, pvalue);
}
void __nac3_ndarray_fill_generic64(NDArray<int64_t>* ndarray, uint8_t* pvalue) {
fill_generic(ndarray, pvalue);
}
}

View File

@ -0,0 +1,200 @@
#pragma once
#include <irrt/error_context.hpp>
#include <irrt/ndarray/basic.hpp>
#include <irrt/ndarray/def.hpp>
#include <irrt/slice.hpp>
namespace {
typedef uint8_t NDIndexType;
/**
* @brief A single element index
*
* See https://numpy.org/doc/stable/user/basics.indexing.html#single-element-indexing
*
* `data` points to a `SliceIndex`.
*/
const NDIndexType ND_INDEX_TYPE_SINGLE_ELEMENT = 0;
/**
* @brief A slice index
*
* See https://numpy.org/doc/stable/user/basics.indexing.html#slicing-and-striding
*
* `data` points to a `UserRange`.
*/
const NDIndexType ND_INDEX_TYPE_SLICE = 1;
/**
* @brief An index used in ndarray indexing
*/
struct NDIndex {
/**
* @brief Enum tag to specify the type of index.
*
* Please see comments of each enum constant.
*/
NDIndexType type;
/**
* @brief The accompanying data associated with `type`.
*
* Please see comments of each enum constant.
*/
uint8_t* data;
};
} // namespace
namespace {
namespace ndarray {
namespace indexing {
namespace util {
/**
* @brief Return the expected rank of the resulting ndarray
* created by indexing an ndarray of rank `ndims` using `indexes`.
*/
template <typename SizeT>
void deduce_ndims_after_indexing(ErrorContext* errctx, SizeT* final_ndims,
SizeT ndims, SizeT num_indexes,
const NDIndex* indexes) {
if (num_indexes > ndims) {
errctx->set_error(errctx->error_ids->index_error,
"too many indices for array: array is "
"{0}-dimensional, but {1} were indexed",
ndims, num_indexes);
return;
}
*final_ndims = ndims;
for (SizeT i = 0; i < num_indexes; i++) {
if (indexes[i].type == ND_INDEX_TYPE_SINGLE_ELEMENT) {
// An index demotes the rank by 1
(*final_ndims)--;
}
}
}
} // namespace util
/**
* @brief Perform ndarray "basic indexing" (https://numpy.org/doc/stable/user/basics.indexing.html#basic-indexing)
*
* This is function very similar to performing `dst_ndarray = src_ndarray[indexes]` in Python (where the variables
* can all be found in the parameter of this function).
*
* In other words, this function takes in an ndarray (`src_ndarray`), index it with `indexes`, and return the
* indexed array (by writing the result to `dst_ndarray`).
*
* This function also does proper assertions on `indexes`.
*
* # Notes on `dst_ndarray`
* The caller is responsible for allocating space for the resulting ndarray.
* Here is what this function expects from `dst_ndarray` when called:
* - `dst_ndarray->data` does not have to be initialized.
* - `dst_ndarray->itemsize` does not have to be initialized.
* - `dst_ndarray->ndims` must be initialized, and it must be equal to the expected `ndims` of the `dst_ndarray` after
* indexing `src_ndarray` with `indexes`.
* - `dst_ndarray->shape` must be allocated, through it can contain uninitialized values.
* - `dst_ndarray->strides` must be allocated, through it can contain uninitialized values.
* When this function call ends:
* - `dst_ndarray->data` is set to `src_ndarray->data` (`dst_ndarray` is just a view to `src_ndarray`)
* - `dst_ndarray->itemsize` is set to `src_ndarray->itemsize`
* - `dst_ndarray->ndims` is unchanged.
* - `dst_ndarray->shape` is updated according to how `src_ndarray` is indexed.
* - `dst_ndarray->strides` is updated accordingly by how ndarray indexing works.
*
* @param indexes Indexes to index `src_ndarray`, ordered in the same way you would write them in Python.
* @param src_ndarray The NDArray to be indexed.
* @param dst_ndarray The resulting NDArray after indexing. Further details in the comments above,
*/
template <typename SizeT>
void index(ErrorContext* errctx, SizeT num_indexes, const NDIndex* indexes,
const NDArray<SizeT>* src_ndarray, NDArray<SizeT>* dst_ndarray) {
// Reference code: https://github.com/wadetb/tinynumpy/blob/0d23d22e07062ffab2afa287374c7b366eebdda1/tinynumpy/tinynumpy.py#L652
dst_ndarray->data = src_ndarray->data;
dst_ndarray->itemsize = src_ndarray->itemsize;
SizeT src_axis = 0;
SizeT dst_axis = 0;
for (SliceIndex i = 0; i < num_indexes; i++) {
const NDIndex* index = &indexes[i];
if (index->type == ND_INDEX_TYPE_SINGLE_ELEMENT) {
SliceIndex input = *((SliceIndex*)index->data);
SliceIndex k = slice::resolve_index_in_length(
src_ndarray->shape[src_axis], input);
if (k == slice::OUT_OF_BOUNDS) {
errctx->set_error(errctx->error_ids->index_error,
"index {0} is out of bounds for axis {1} "
"with size {2}",
input, src_axis,
src_ndarray->shape[src_axis]);
return;
}
dst_ndarray->data += k * src_ndarray->strides[src_axis];
src_axis++;
} else if (index->type == ND_INDEX_TYPE_SLICE) {
UserSlice* input = (UserSlice*)index->data;
Slice slice;
input->indices_checked(errctx, src_ndarray->shape[src_axis],
&slice);
if (errctx->has_error()) {
return;
}
dst_ndarray->data +=
(SizeT)slice.start * src_ndarray->strides[src_axis];
dst_ndarray->strides[dst_axis] =
((SizeT)slice.step) * src_ndarray->strides[src_axis];
dst_ndarray->shape[dst_axis] = (SizeT)slice.len();
dst_axis++;
src_axis++;
} else {
__builtin_unreachable();
}
}
for (; dst_axis < dst_ndarray->ndims; dst_axis++, src_axis++) {
dst_ndarray->shape[dst_axis] = src_ndarray->shape[src_axis];
dst_ndarray->strides[dst_axis] = src_ndarray->strides[src_axis];
}
}
} // namespace indexing
} // namespace ndarray
} // namespace
extern "C" {
using namespace ndarray::indexing;
void __nac3_ndarray_indexing_deduce_ndims_after_indexing(
ErrorContext* errctx, int32_t* result, int32_t ndims, int32_t num_indexes,
const NDIndex* indexes) {
ndarray::indexing::util::deduce_ndims_after_indexing(errctx, result, ndims,
num_indexes, indexes);
}
void __nac3_ndarray_indexing_deduce_ndims_after_indexing64(
ErrorContext* errctx, int64_t* result, int64_t ndims, int64_t num_indexes,
const NDIndex* indexes) {
ndarray::indexing::util::deduce_ndims_after_indexing(errctx, result, ndims,
num_indexes, indexes);
}
void __nac3_ndarray_index(ErrorContext* errctx, int32_t num_indexes,
NDIndex* indexes, NDArray<int32_t>* src_ndarray,
NDArray<int32_t>* dst_ndarray) {
index(errctx, num_indexes, indexes, src_ndarray, dst_ndarray);
}
void __nac3_ndarray_index64(ErrorContext* errctx, int64_t num_indexes,
NDIndex* indexes, NDArray<int64_t>* src_ndarray,
NDArray<int64_t>* dst_ndarray) {
index(errctx, num_indexes, indexes, src_ndarray, dst_ndarray);
}
}

View File

@ -0,0 +1,116 @@
#pragma once
#include <irrt/error_context.hpp>
#include <irrt/int_defs.hpp>
#include <irrt/ndarray/def.hpp>
namespace {
namespace ndarray {
namespace reshape {
namespace util {
/**
* @brief Perform assertions on and resolve unknown dimensions in `new_shape` in `np.reshape(<ndarray>, new_shape)`
*
* If `new_shape` indeed contains unknown dimensions (specified with `-1`, just like numpy), `new_shape` will be
* modified to contain the resolved dimension.
*
* To perform assertions on and resolve unknown dimensions in `new_shape`, we don't need the actual
* `<ndarray>` object itself, but only the `.size` of the `<ndarray>`.
*
* @param size The `.size` of `<ndarray>`
* @param new_ndims Number of elements in `new_shape`
* @param new_shape Target shape to reshape to
*/
template <typename SizeT>
void resolve_and_check_new_shape(ErrorContext* errctx, SizeT size,
SizeT new_ndims, SizeT* new_shape) {
// Is there a -1 in `new_shape`?
bool neg1_exists = false;
// Location of -1, only initialized if `neg1_exists` is true
SizeT neg1_axis_i;
// The computed ndarray size of `new_shape`
SizeT new_size = 1;
for (SizeT axis_i = 0; axis_i < new_ndims; axis_i++) {
SizeT dim = new_shape[axis_i];
if (dim < 0) {
if (dim == -1) {
if (neg1_exists) {
// Multiple `-1` found. Throw an error.
errctx->set_error(errctx->error_ids->value_error,
"can only specify one unknown dimension");
return;
} else {
neg1_exists = true;
neg1_axis_i = axis_i;
}
} else {
// TODO: What? In `np.reshape` any negative dimensions is
// treated like its `-1`.
//
// Try running `np.zeros((3, 4)).reshape((-999, 2))`
//
// It is not documented by numpy.
// Throw an error for now...
errctx->set_error(errctx->error_ids->value_error,
"Found negative dimension {0} on axis {1}",
dim, axis_i);
return;
}
} else {
new_size *= dim;
}
}
bool can_reshape;
if (neg1_exists) {
// Let `x` be the unknown dimension
// solve `x * <new_size> = <size>`
if (new_size == 0 && size == 0) {
// `x` has infinitely many solutions
can_reshape = false;
} else if (new_size == 0 && size != 0) {
// `x` has no solutions
can_reshape = false;
} else if (size % new_size != 0) {
// `x` has no integer solutions
can_reshape = false;
} else {
can_reshape = true;
new_shape[neg1_axis_i] = size / new_size; // Resolve dimension
}
} else {
can_reshape = (new_size == size);
}
if (!can_reshape) {
errctx->set_error(errctx->error_ids->value_error,
"cannot reshape array of size {0} into given shape",
size);
return;
}
}
} // namespace util
} // namespace reshape
} // namespace ndarray
} // namespace
extern "C" {
void __nac3_ndarray_resolve_and_check_new_shape(ErrorContext* errctx,
int32_t size, int32_t new_ndims,
int32_t* new_shape) {
ndarray::reshape::util::resolve_and_check_new_shape(errctx, size, new_ndims,
new_shape);
}
void __nac3_ndarray_resolve_and_check_new_shape64(ErrorContext* errctx,
int64_t size,
int64_t new_ndims,
int64_t* new_shape) {
ndarray::reshape::util::resolve_and_check_new_shape(errctx, size, new_ndims,
new_shape);
}
}

View File

@ -0,0 +1,162 @@
#pragma once
#include <irrt/int_defs.hpp>
#include <irrt/ndarray/def.hpp>
#include <irrt/slice.hpp>
/*
* Notes on `np.transpose(<array>, <axes>)`
*
* TODO: `axes`, if specified, can actually contain negative indices,
* but it is not documented in numpy.
*
* Supporting it for now.
*/
namespace {
namespace ndarray {
namespace transpose {
namespace util {
/**
* @brief Do assertions on `<axes>` in `np.transpose(<array>, <axes>)`.
*
* Note that `np.transpose`'s `<axe>` argument is optional. If the argument
* is specified but the user, use this function to do assertions on it.
*
* @param ndims The number of dimensions of `<array>`
* @param num_axes Number of elements in `<axes>` as specified by the user.
* This should be equal to `ndims`. If not, a "ValueError: axes don't match array" is thrown.
* @param axes The user specified `<axes>`.
*/
template <typename SizeT>
void assert_transpose_axes(ErrorContext* errctx, SizeT ndims, SizeT num_axes,
const SizeT* axes) {
/*
* TODO: `axes` can actually contain negative indices, but it is not documented in numpy.
*
* Supporting it for now.
*/
if (ndims != num_axes) {
errctx->set_error(errctx->error_ids->value_error,
"axes don't match array");
return;
}
// TODO: Optimize this
bool* axe_specified = (bool*)__builtin_alloca(sizeof(bool) * ndims);
for (SizeT i = 0; i < ndims; i++) axe_specified[i] = false;
for (SizeT i = 0; i < ndims; i++) {
SizeT axis = slice::resolve_index_in_length(ndims, axes[i]);
if (axis == slice::OUT_OF_BOUNDS) {
// TODO: numpy actually throws a `numpy.exceptions.AxisError`
errctx->set_error(
errctx->error_ids->value_error,
"axis {0} is out of bounds for array of dimension {1}", axis,
ndims);
return;
}
if (axe_specified[axis]) {
errctx->set_error(errctx->error_ids->value_error,
"repeated axis in transpose");
return;
}
axe_specified[axis] = true;
}
}
} // namespace util
/**
* @brief Create a transpose view of `src_ndarray` and perform proper assertions.
*
* This function is very similar to doing `dst_ndarray = np.transpose(src_ndarray, <axes>)`.
* If `<axes>` is supposed to be `None`, caller can pass in a `nullptr` to `<axes>`.
*
* The transpose view created is returned by modifying `dst_ndarray`.
*
* The caller is responsible for setting up `dst_ndarray` before calling this function.
* Here is what this function expects from `dst_ndarray` when called:
* - `dst_ndarray->data` does not have to be initialized.
* - `dst_ndarray->itemsize` does not have to be initialized.
* - `dst_ndarray->ndims` must be initialized, must be equal to `src_ndarray->ndims`.
* - `dst_ndarray->shape` must be allocated, through it can contain uninitialized values.
* - `dst_ndarray->strides` must be allocated, through it can contain uninitialized values.
* When this function call ends:
* - `dst_ndarray->data` is set to `src_ndarray->data` (`dst_ndarray` is just a view to `src_ndarray`)
* - `dst_ndarray->itemsize` is set to `src_ndarray->itemsize`
* - `dst_ndarray->ndims` is unchanged
* - `dst_ndarray->shape` is updated according to how `np.transpose` works
* - `dst_ndarray->strides` is updated according to how `np.transpose` works
*
* @param src_ndarray The NDArray to build a transpose view on
* @param dst_ndarray The resulting NDArray after transpose. Further details in the comments above,
* @param num_axes Number of elements in axes, can be undefined if `axes` is nullptr.
* @param axes Axes permutation. Set it to `nullptr` if `<axes>` is supposed to be `None`.
*/
template <typename SizeT>
void transpose(ErrorContext* errctx, const NDArray<SizeT>* src_ndarray,
NDArray<SizeT>* dst_ndarray, SizeT num_axes, const SizeT* axes) {
__builtin_assume(src_ndarray->ndims == dst_ndarray->ndims);
const auto ndims = src_ndarray->ndims;
if (axes != nullptr) {
util::assert_transpose_axes(errctx, ndims, num_axes, axes);
if (errctx->has_error()) return;
}
dst_ndarray->data = src_ndarray->data;
dst_ndarray->itemsize = src_ndarray->itemsize;
// Check out https://ajcr.net/stride-guide-part-2/ to see how `np.transpose` works behind the scenes.
if (axes == nullptr) {
// `np.transpose(<array>, axes=None)`
/*
* Minor note: `np.transpose(<array>, axes=None)` is equivalent to
* `np.transpose(<array>, axes=[N-1, N-2, ..., 0])` - basically it
* is reversing the order of strides and shape.
*
* This is a fast implementation to handle this special (but very common) case.
*/
for (SizeT axis = 0; axis < ndims; axis++) {
dst_ndarray->shape[axis] = src_ndarray->shape[ndims - axis - 1];
dst_ndarray->strides[axis] = src_ndarray->strides[ndims - axis - 1];
}
} else {
// `np.transpose(<array>, <axes>)`
// Permute strides and shape according to `axes`, while resolving negative indices in `axes`
for (SizeT axis = 0; axis < ndims; axis++) {
// `i` cannot be OUT_OF_BOUNDS because of assertions
SizeT i = slice::resolve_index_in_length(ndims, axes[axis]);
dst_ndarray->shape[axis] = src_ndarray->shape[i];
dst_ndarray->strides[axis] = src_ndarray->strides[i];
}
}
}
} // namespace transpose
} // namespace ndarray
} // namespace
extern "C" {
using namespace ndarray::transpose;
void __nac3_ndarray_transpose(ErrorContext* errctx,
const NDArray<int32_t>* src_ndarray,
NDArray<int32_t>* dst_ndarray, int32_t num_axes,
const int32_t* axes) {
transpose(errctx, src_ndarray, dst_ndarray, num_axes, axes);
}
void __nac3_ndarray_transpose64(ErrorContext* errctx,
const NDArray<int64_t>* src_ndarray,
NDArray<int64_t>* dst_ndarray, int64_t num_axes,
const int64_t* axes) {
transpose(errctx, src_ndarray, dst_ndarray, num_axes, axes);
}
}

View File

@ -0,0 +1,165 @@
#pragma once
#include <irrt/error_context.hpp>
#include <irrt/int_defs.hpp>
#include <irrt/slice.hpp>
#include <irrt/utils.hpp>
// The type of an index or a value describing the length of a
// range/slice is always `int32_t`.
using SliceIndex = int32_t;
namespace {
/**
* @brief A Python-like slice with resolved indices.
*
* "Resolved indices" means that `start` and `stop` must be positive and are
* bound to a known length.
*/
struct Slice {
SliceIndex start;
SliceIndex stop;
SliceIndex step;
/**
* @brief Calculate and return the length / the number of the slice.
*
* If this were a Python range, this function would be `len(range(start, stop, step))`.
*/
SliceIndex len() {
SliceIndex diff = stop - start;
if (diff > 0 && step > 0) {
return ((diff - 1) / step) + 1;
} else if (diff < 0 && step < 0) {
return ((diff + 1) / step) + 1;
} else {
return 0;
}
}
};
namespace slice {
/**
* @brief Resolve a slice index under a given length like Python indexing.
*
* In Python, if you have a `list` of length 100, `list[-1]` resolves to
* `list[99]`, so `resolve_index_in_length_clamped(100, -1)` returns `99`.
*
* If `length` is 0, 0 is returned for any value of `index`.
*
* If `index` is out of bounds, clamps the returned value between `0` and
* `length - 1` (inclusive).
*
*/
SliceIndex resolve_index_in_length_clamped(SliceIndex length,
SliceIndex index) {
if (index < 0) {
return max<SliceIndex>(length + index, 0);
} else {
return min<SliceIndex>(length, index);
}
}
const SliceIndex OUT_OF_BOUNDS = -1;
/**
* @brief Like `resolve_index_in_length_clamped`, but returns `OUT_OF_BOUNDS`
* if `index` is out of bounds.
*/
SliceIndex resolve_index_in_length(SliceIndex length, SliceIndex index) {
SliceIndex resolved = index < 0 ? length + index : index;
if (0 <= resolved && resolved < length) {
return resolved;
} else {
return OUT_OF_BOUNDS;
}
}
} // namespace slice
/**
* @brief A Python-like slice with **unresolved** indices.
*/
struct UserSlice {
bool start_defined;
SliceIndex start;
bool stop_defined;
SliceIndex stop;
bool step_defined;
SliceIndex step;
UserSlice() { this->reset(); }
void reset() {
this->start_defined = false;
this->stop_defined = false;
this->step_defined = false;
}
void set_start(SliceIndex start) {
this->start_defined = true;
this->start = start;
}
void set_stop(SliceIndex stop) {
this->stop_defined = true;
this->stop = stop;
}
void set_step(SliceIndex step) {
this->step_defined = true;
this->step = step;
}
/**
* @brief Resolve this slice.
*
* In Python, this would be `slice(start, stop, step).indices(length)`.
*
* @return A `Slice` with the resolved indices.
*/
Slice indices(SliceIndex length) {
Slice result;
result.step = step_defined ? step : 1;
bool step_is_negative = result.step < 0;
if (start_defined) {
result.start =
slice::resolve_index_in_length_clamped(length, start);
} else {
result.start = step_is_negative ? length - 1 : 0;
}
if (stop_defined) {
result.stop = slice::resolve_index_in_length_clamped(length, stop);
} else {
result.stop = step_is_negative ? -1 : length;
}
return result;
}
/**
* @brief Like `.indices()` but with assertions.
*/
void indices_checked(ErrorContext* errctx, SliceIndex length,
Slice* result) {
if (length < 0) {
errctx->set_error(errctx->error_ids->value_error,
"length should not be negative, got {0}", length);
return;
}
if (this->step_defined && this->step == 0) {
errctx->set_error(errctx->error_ids->value_error,
"slice step cannot be zero");
return;
}
*result = this->indices(length);
}
};
} // namespace

View File

@ -0,0 +1,104 @@
#pragma once
namespace {
template <typename T>
const T& max(const T& a, const T& b) {
return a > b ? a : b;
}
template <typename T>
const T& min(const T& a, const T& b) {
return a > b ? b : a;
}
/**
* @brief Compare contents of two arrays with the same length.
*/
template <typename T>
bool arrays_match(int len, T* as, T* bs) {
for (int i = 0; i < len; i++) {
if (as[i] != bs[i]) return false;
}
return true;
}
namespace cstr_utils {
/**
* @brief Return true if `str` is empty.
*/
bool is_empty(const char* str) { return str[0] == '\0'; }
/**
* @brief Implementation of `strcmp()`
*/
int8_t compare(const char* a, const char* b) {
uint32_t i = 0;
while (true) {
if (a[i] < b[i]) {
return -1;
} else if (a[i] > b[i]) {
return 1;
} else {
if (a[i] == '\0') {
return 0;
} else {
i++;
}
}
}
}
/**
* @brief Return true two strings have the same content.
*/
int8_t equal(const char* a, const char* b) { return compare(a, b) == 0; }
/**
* @brief Implementation of `strlen()`.
*/
uint32_t length(const char* str) {
uint32_t length = 0;
while (*str != '\0') {
length++;
str++;
}
return length;
}
/**
* @brief Copy a null-terminated string to a buffer with limited size and guaranteed null-termination.
*
* `dst_max_size` must be greater than 0, otherwise this function has undefined behavior.
*
* This function attempts to copy everything from `src` from `dst`, and *always* null-terminates `dst`.
*
* If the size of `dst` is too small, the final byte (`dst[dst_max_size - 1]`) of `dst` will be set to
* the null terminator.
*
* @param src String to copy from.
* @param dst Buffer to copy string to.
* @param dst_max_size
* Number of bytes of this buffer, including the space needed for the null terminator.
* Must be greater than 0.
* @return If `dst` is too small to contain everything in `src`.
*/
bool copy(const char* src, char* dst, uint32_t dst_max_size) {
for (uint32_t i = 0; i < dst_max_size; i++) {
bool is_last = i + 1 == dst_max_size;
if (is_last && src[i] != '\0') {
dst[i] = '\0';
return false;
}
if (src[i] == '\0') {
dst[i] = '\0';
return true;
}
dst[i] = src[i];
}
__builtin_unreachable();
}
} // namespace cstr_utils
} // namespace

View File

@ -0,0 +1,14 @@
#pragma once
#include <irrt/artiq_defs.hpp>
#include <irrt/core.hpp>
#include <irrt/error_context.hpp>
#include <irrt/int_defs.hpp>
#include <irrt/ndarray/basic.hpp>
#include <irrt/ndarray/def.hpp>
#include <irrt/ndarray/fill.hpp>
#include <irrt/ndarray/indexing.hpp>
#include <irrt/ndarray/reshape.hpp>
#include <irrt/ndarray/transpose.hpp>
#include <irrt/slice.hpp>
#include <irrt/utils.hpp>

View File

@ -0,0 +1,18 @@
// This file will be compiled like a real C++ program,
// and we do have the luxury to use the standard libraries.
// That is if the nix flakes do not have issues... especially on msys2...
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <test/test_core.hpp>
#include <test/test_ndarray_basic.hpp>
#include <test/test_ndarray_indexing.hpp>
#include <test/test_slice.hpp>
int main() {
test::core::run();
test::slice::run();
test::ndarray_basic::run();
test::ndarray_indexing::run();
return 0;
}

View File

@ -0,0 +1,11 @@
#pragma once
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <irrt_everything.hpp>
#include <test/util.hpp>
/*
Include this header for every test_*.cpp
*/

View File

@ -0,0 +1,16 @@
#pragma once
#include <test/includes.hpp>
namespace test {
namespace core {
void test_int_exp() {
BEGIN_TEST();
assert_values_match(125, __nac3_int_exp_impl<int32_t>(5, 3));
assert_values_match(3125, __nac3_int_exp_impl<int32_t>(5, 5));
}
void run() { test_int_exp(); }
} // namespace core
} // namespace test

View File

@ -0,0 +1,30 @@
#pragma once
#include <test/includes.hpp>
namespace test {
namespace ndarray_basic {
void test_calc_size_from_shape_normal() {
// Test shapes with normal values
BEGIN_TEST();
int32_t shape[4] = {2, 3, 5, 7};
assert_values_match(
210, ndarray::basic::util::calc_size_from_shape<int32_t>(4, shape));
}
void test_calc_size_from_shape_has_zero() {
// Test shapes with 0 in them
BEGIN_TEST();
int32_t shape[4] = {2, 0, 5, 7};
assert_values_match(
0, ndarray::basic::util::calc_size_from_shape<int32_t>(4, shape));
}
void run() {
test_calc_size_from_shape_normal();
test_calc_size_from_shape_has_zero();
}
} // namespace ndarray_basic
} // namespace test

View File

@ -0,0 +1,220 @@
#pragma once
#include <test/includes.hpp>
namespace test {
namespace ndarray_indexing {
void test_normal_1() {
/*
Reference Python code:
```python
ndarray = np.arange(12, dtype=np.float64).reshape((3, 4));
# array([[ 0., 1., 2., 3.],
# [ 4., 5., 6., 7.],
# [ 8., 9., 10., 11.]])
dst_ndarray = ndarray[-2:, 1::2]
# array([[ 5., 7.],
# [ 9., 11.]])
assert dst_ndarray.shape == (2, 2)
assert dst_ndarray.strides == (32, 16)
assert dst_ndarray[0, 0] == 5.0
assert dst_ndarray[0, 1] == 7.0
assert dst_ndarray[1, 0] == 9.0
assert dst_ndarray[1, 1] == 11.0
```
*/
BEGIN_TEST();
// Prepare src_ndarray
double src_data[12] = {0.0, 1.0, 2.0, 3.0, 4.0, 5.0,
6.0, 7.0, 8.0, 9.0, 10.0, 11.0};
int32_t src_itemsize = sizeof(double);
const int32_t src_ndims = 2;
int32_t src_shape[src_ndims] = {3, 4};
int32_t src_strides[src_ndims] = {};
NDArray<int32_t> src_ndarray = {.data = (uint8_t *)src_data,
.itemsize = src_itemsize,
.ndims = src_ndims,
.shape = src_shape,
.strides = src_strides};
ndarray::basic::set_strides_by_shape(&src_ndarray);
// Prepare dst_ndarray
const int32_t dst_ndims = 2;
int32_t dst_shape[dst_ndims] = {999, 999}; // Empty values
int32_t dst_strides[dst_ndims] = {999, 999}; // Empty values
NDArray<int32_t> dst_ndarray = {.data = nullptr,
.ndims = dst_ndims,
.shape = dst_shape,
.strides = dst_strides};
// Create the subscripts in `ndarray[-2::, 1::2]`
UserSlice subscript_1;
subscript_1.set_start(-2);
UserSlice subscript_2;
subscript_2.set_start(1);
subscript_2.set_step(2);
const int32_t num_indexes = 2;
NDIndex indexes[num_indexes] = {
{.type = ND_INDEX_TYPE_SLICE, .data = (uint8_t *)&subscript_1},
{.type = ND_INDEX_TYPE_SLICE, .data = (uint8_t *)&subscript_2}};
ErrorContext errctx = create_testing_errctx();
ndarray::indexing::index(&errctx, num_indexes, indexes, &src_ndarray,
&dst_ndarray);
assert_errctx_no_error(&errctx);
int32_t expected_shape[dst_ndims] = {2, 2};
int32_t expected_strides[dst_ndims] = {32, 16};
assert_arrays_match(dst_ndims, expected_shape, dst_ndarray.shape);
assert_arrays_match(dst_ndims, expected_strides, dst_ndarray.strides);
// dst_ndarray[0, 0]
assert_values_match(5.0,
*((double *)ndarray::basic::get_pelement_by_indices(
&dst_ndarray, (int32_t[dst_ndims]){0, 0})));
// dst_ndarray[0, 1]
assert_values_match(7.0,
*((double *)ndarray::basic::get_pelement_by_indices(
&dst_ndarray, (int32_t[dst_ndims]){0, 1})));
// dst_ndarray[1, 0]
assert_values_match(9.0,
*((double *)ndarray::basic::get_pelement_by_indices(
&dst_ndarray, (int32_t[dst_ndims]){1, 0})));
// dst_ndarray[1, 1]
assert_values_match(11.0,
*((double *)ndarray::basic::get_pelement_by_indices(
&dst_ndarray, (int32_t[dst_ndims]){1, 1})));
}
void test_normal_2() {
/*
```python
ndarray = np.arange(12, dtype=np.float64).reshape((3, 4))
# array([[ 0., 1., 2., 3.],
# [ 4., 5., 6., 7.],
# [ 8., 9., 10., 11.]])
dst_ndarray = ndarray[2, ::-2]
# array([11., 9.])
assert dst_ndarray.shape == (2,)
assert dst_ndarray.strides == (-16,)
assert dst_ndarray[0] == 11.0
assert dst_ndarray[1] == 9.0
```
*/
BEGIN_TEST();
// Prepare src_ndarray
double src_data[12] = {0.0, 1.0, 2.0, 3.0, 4.0, 5.0,
6.0, 7.0, 8.0, 9.0, 10.0, 11.0};
int32_t src_itemsize = sizeof(double);
const int32_t src_ndims = 2;
int32_t src_shape[src_ndims] = {3, 4};
int32_t src_strides[src_ndims] = {};
NDArray<int32_t> src_ndarray = {.data = (uint8_t *)src_data,
.itemsize = src_itemsize,
.ndims = src_ndims,
.shape = src_shape,
.strides = src_strides};
ndarray::basic::set_strides_by_shape(&src_ndarray);
// Prepare dst_ndarray
const int32_t dst_ndims = 1;
int32_t dst_shape[dst_ndims] = {999}; // Empty values
int32_t dst_strides[dst_ndims] = {999}; // Empty values
NDArray<int32_t> dst_ndarray = {.data = nullptr,
.ndims = dst_ndims,
.shape = dst_shape,
.strides = dst_strides};
// Create the subscripts in `ndarray[2, ::-2]`
int32_t subscript_1 = 2;
UserSlice subscript_2;
subscript_2.set_step(-2);
const int32_t num_indexes = 2;
NDIndex indexes[num_indexes] = {
{.type = ND_INDEX_TYPE_SINGLE_ELEMENT, .data = (uint8_t *)&subscript_1},
{.type = ND_INDEX_TYPE_SLICE, .data = (uint8_t *)&subscript_2}};
ErrorContext errctx = create_testing_errctx();
ndarray::indexing::index(&errctx, num_indexes, indexes, &src_ndarray,
&dst_ndarray);
assert_errctx_no_error(&errctx);
int32_t expected_shape[dst_ndims] = {2};
int32_t expected_strides[dst_ndims] = {-16};
assert_arrays_match(dst_ndims, expected_shape, dst_ndarray.shape);
assert_arrays_match(dst_ndims, expected_strides, dst_ndarray.strides);
assert_values_match(11.0,
*((double *)ndarray::basic::get_pelement_by_indices(
&dst_ndarray, (int32_t[dst_ndims]){0})));
assert_values_match(9.0,
*((double *)ndarray::basic::get_pelement_by_indices(
&dst_ndarray, (int32_t[dst_ndims]){1})));
}
void test_index_subscript_out_of_bounds() {
/*
# Consider `my_array`
print(my_array.shape)
# (4, 5, 6)
my_array[2, 100] # error, index subscript at axis 1 is out of bounds
*/
BEGIN_TEST();
// Prepare src_ndarray
const int32_t src_ndims = 2;
int32_t src_shape[src_ndims] = {3, 4};
int32_t src_strides[src_ndims] = {};
NDArray<int32_t> src_ndarray = {
.data = (uint8_t *)nullptr, // placeholder, we wouldn't access it
.itemsize = sizeof(double), // placeholder
.ndims = src_ndims,
.shape = src_shape,
.strides = src_strides};
ndarray::basic::set_strides_by_shape(&src_ndarray);
// Create the subscripts in `my_array[2, 100]`
int32_t subscript_1 = 2;
int32_t subscript_2 = 100;
const int32_t num_indexes = 2;
NDIndex indexes[num_indexes] = {
{.type = ND_INDEX_TYPE_SINGLE_ELEMENT, .data = (uint8_t *)&subscript_1},
{.type = ND_INDEX_TYPE_SINGLE_ELEMENT,
.data = (uint8_t *)&subscript_2}};
// Prepare dst_ndarray
const int32_t dst_ndims = 0;
int32_t dst_shape[dst_ndims] = {};
int32_t dst_strides[dst_ndims] = {};
NDArray<int32_t> dst_ndarray = {.data = nullptr, // placehloder
.ndims = dst_ndims,
.shape = dst_shape,
.strides = dst_strides};
ErrorContext errctx = create_testing_errctx();
ndarray::indexing::index(&errctx, num_indexes, indexes, &src_ndarray,
&dst_ndarray);
assert_errctx_has_error(&errctx, errctx.error_ids->index_error);
}
void run() {
test_normal_1();
test_normal_2();
test_index_subscript_out_of_bounds();
}
} // namespace ndarray_indexing
} // namespace test

View File

@ -0,0 +1,92 @@
#pragma once
#include <irrt_everything.hpp>
#include <test/includes.hpp>
namespace test {
namespace slice {
void test_slice_normal() {
// Normal situation
BEGIN_TEST();
UserSlice user_slice;
user_slice.set_stop(5);
Slice slice = user_slice.indices(100);
printf("%d, %d, %d\n", slice.start, slice.stop, slice.step);
assert_values_match(0, slice.start);
assert_values_match(5, slice.stop);
assert_values_match(1, slice.step);
}
void test_slice_start_too_large() {
// Start is too large and should be clamped to length
BEGIN_TEST();
UserSlice user_slice;
user_slice.set_start(400);
Slice slice = user_slice.indices(100);
assert_values_match(100, slice.start);
assert_values_match(100, slice.stop);
assert_values_match(1, slice.step);
}
void test_slice_negative_start_stop() {
// Negative start/stop should be resolved
BEGIN_TEST();
UserSlice user_slice;
user_slice.set_start(-10);
user_slice.set_stop(-5);
Slice slice = user_slice.indices(100);
assert_values_match(90, slice.start);
assert_values_match(95, slice.stop);
assert_values_match(1, slice.step);
}
void test_slice_only_negative_step() {
// Things like `[::-5]` should be handled correctly
BEGIN_TEST();
UserSlice user_slice;
user_slice.set_step(-5);
Slice slice = user_slice.indices(100);
assert_values_match(99, slice.start);
assert_values_match(-1, slice.stop);
assert_values_match(-5, slice.step);
}
void test_slice_step_zero() {
// Step = 0 is a value error
BEGIN_TEST();
ErrorContext errctx = create_testing_errctx();
UserSlice user_slice;
user_slice.set_start(2);
user_slice.set_stop(12);
user_slice.set_step(0);
Slice slice;
user_slice.indices_checked(&errctx, 100, &slice);
assert_errctx_has_error(&errctx, errctx.error_ids->value_error);
}
void run() {
test_slice_normal();
test_slice_start_too_large();
test_slice_negative_start_stop();
test_slice_only_negative_step();
test_slice_step_zero();
}
} // namespace slice
} // namespace test

179
nac3core/irrt/test/util.hpp Normal file
View File

@ -0,0 +1,179 @@
#pragma once
#include <cstdio>
#include <cstdlib>
template <class T>
void print_value(const T& value);
template <>
void print_value(const int8_t& value) {
printf("%d", value);
}
template <>
void print_value(const int32_t& value) {
printf("%d", value);
}
template <>
void print_value(const uint8_t& value) {
printf("%u", value);
}
template <>
void print_value(const uint32_t& value) {
printf("%u", value);
}
template <>
void print_value(const float& value) {
printf("%f", value);
}
template <>
void print_value(const double& value) {
printf("%f", value);
}
void __begin_test(const char* function_name, const char* file, int line) {
printf("######### Running %s @ %s:%d\n", function_name, file, line);
}
#define BEGIN_TEST() __begin_test(__FUNCTION__, __FILE__, __LINE__)
void test_fail() {
printf("[!] Test failed. Exiting with status code 1.\n");
exit(1);
}
template <typename T>
void debug_print_array(int len, const T* as) {
printf("[");
for (int i = 0; i < len; i++) {
if (i != 0) printf(", ");
print_value(as[i]);
}
printf("]");
}
void print_assertion_passed(const char* file, int line) {
printf("[*] Assertion passed on %s:%d\n", file, line);
}
void print_assertion_failed(const char* file, int line) {
printf("[!] Assertion failed on %s:%d\n", file, line);
}
void __assert_true(const char* file, int line, bool cond) {
if (cond) {
print_assertion_passed(file, line);
} else {
print_assertion_failed(file, line);
test_fail();
}
}
#define assert_true(cond) __assert_true(__FILE__, __LINE__, cond)
template <typename T>
void __assert_arrays_match(const char* file, int line, int len,
const T* expected, const T* got) {
if (arrays_match(len, expected, got)) {
print_assertion_passed(file, line);
} else {
print_assertion_failed(file, line);
printf("Expect = ");
debug_print_array(len, expected);
printf("\n");
printf(" Got = ");
debug_print_array(len, got);
printf("\n");
test_fail();
}
}
#define assert_arrays_match(len, expected, got) \
__assert_arrays_match(__FILE__, __LINE__, len, expected, got)
template <typename T>
void __assert_values_match(const char* file, int line, T expected, T got) {
if (expected == got) {
print_assertion_passed(file, line);
} else {
print_assertion_failed(file, line);
printf("Expect = ");
print_value(expected);
printf("\n");
printf(" Got = ");
print_value(got);
printf("\n");
test_fail();
}
}
#define assert_values_match(expected, got) \
__assert_values_match(__FILE__, __LINE__, expected, got)
// A fake set of ErrorIds for testing only
const ErrorIds TEST_ERROR_IDS = {
.index_error = 0,
.value_error = 1,
.assertion_error = 2,
.runtime_error = 3,
.type_error = 4,
};
ErrorContext create_testing_errctx() {
// Everything is global so it is fine to directly return a struct
// ErrorContext
ErrorContext errctx;
errctx.initialize(&TEST_ERROR_IDS);
return errctx;
}
void print_errctx_content(ErrorContext* errctx) {
if (errctx->has_error()) {
printf(
"(Error ID %d): %s ... where param1 = %ld, param2 = %ld, param3 = "
"%ld\n",
errctx->error_id, errctx->message_template, errctx->param1,
errctx->param2, errctx->param3);
} else {
printf("<no error>\n");
}
}
void __assert_errctx_no_error(const char* file, int line,
ErrorContext* errctx) {
if (errctx->has_error()) {
print_assertion_failed(file, line);
printf("Expecting no error but caught the following:\n\n");
print_errctx_content(errctx);
test_fail();
}
}
#define assert_errctx_no_error(errctx) \
__assert_errctx_no_error(__FILE__, __LINE__, errctx)
void __assert_errctx_has_error(const char* file, int line, ErrorContext* errctx,
ExceptionId expected_error_id) {
if (errctx->has_error()) {
if (errctx->error_id != expected_error_id) {
print_assertion_failed(file, line);
printf(
"Expecting error id %d but got error id %d. Error caught:\n\n",
expected_error_id, errctx->error_id);
print_errctx_content(errctx);
test_fail();
}
} else {
print_assertion_failed(file, line);
printf("Expecting an error, but there is none.");
test_fail();
}
}
#define assert_errctx_has_error(errctx, expected_error_id) \
__assert_errctx_has_error(__FILE__, __LINE__, errctx, expected_error_id)

View File

@ -661,90 +661,6 @@ pub fn call_min<'ctx>(
}
}
/// Invokes the `np_min` builtin function.
pub fn call_numpy_min<'ctx, G: CodeGenerator + ?Sized>(
generator: &mut G,
ctx: &mut CodeGenContext<'ctx, '_>,
a: (Type, BasicValueEnum<'ctx>),
) -> Result<BasicValueEnum<'ctx>, String> {
const FN_NAME: &str = "np_min";
let llvm_usize = generator.get_size_type(ctx.ctx);
let (a_ty, a) = a;
Ok(match a {
BasicValueEnum::IntValue(_) | BasicValueEnum::FloatValue(_) => {
debug_assert!([
ctx.primitives.bool,
ctx.primitives.int32,
ctx.primitives.uint32,
ctx.primitives.int64,
ctx.primitives.uint64,
ctx.primitives.float,
]
.iter()
.any(|ty| ctx.unifier.unioned(a_ty, *ty)));
a
}
BasicValueEnum::PointerValue(n)
if a_ty.obj_id(&ctx.unifier).is_some_and(|id| id == PrimDef::NDArray.id()) =>
{
let (elem_ty, _) = unpack_ndarray_var_tys(&mut ctx.unifier, a_ty);
let llvm_ndarray_ty = ctx.get_llvm_type(generator, elem_ty);
let n = NDArrayValue::from_ptr_val(n, llvm_usize, None);
let n_sz = irrt::call_ndarray_calc_size(generator, ctx, &n.dim_sizes(), (None, None));
if ctx.registry.llvm_options.opt_level == OptimizationLevel::None {
let n_sz_eqz = ctx
.builder
.build_int_compare(IntPredicate::NE, n_sz, n_sz.get_type().const_zero(), "")
.unwrap();
ctx.make_assert(
generator,
n_sz_eqz,
"0:ValueError",
"zero-size array to reduction operation minimum which has no identity",
[None, None, None],
ctx.current_loc,
);
}
let accumulator_addr = generator.gen_var_alloc(ctx, llvm_ndarray_ty, None)?;
unsafe {
let identity =
n.data().get_unchecked(ctx, generator, &llvm_usize.const_zero(), None);
ctx.builder.build_store(accumulator_addr, identity).unwrap();
}
gen_for_callback_incrementing(
generator,
ctx,
llvm_usize.const_int(1, false),
(n_sz, false),
|generator, ctx, _, idx| {
let elem = unsafe { n.data().get_unchecked(ctx, generator, &idx, None) };
let accumulator = ctx.builder.build_load(accumulator_addr, "").unwrap();
let result = call_min(ctx, (elem_ty, accumulator), (elem_ty, elem));
ctx.builder.build_store(accumulator_addr, result).unwrap();
Ok(())
},
llvm_usize.const_int(1, false),
)?;
let accumulator = ctx.builder.build_load(accumulator_addr, "").unwrap();
accumulator
}
_ => unsupported_type(ctx, FN_NAME, &[a_ty]),
})
}
/// Invokes the `np_minimum` builtin function.
pub fn call_numpy_minimum<'ctx, G: CodeGenerator + ?Sized>(
generator: &mut G,
@ -877,18 +793,20 @@ pub fn call_max<'ctx>(
}
}
/// Invokes the `np_max` builtin function.
pub fn call_numpy_max<'ctx, G: CodeGenerator + ?Sized>(
/// Invokes the `np_max`, `np_min`, `np_argmax`, `np_argmin` functions
/// * `fn_name`: Can be one of `"np_argmin"`, `"np_argmax"`, `"np_max"`, `"np_min"`
pub fn call_numpy_max_min<'ctx, G: CodeGenerator + ?Sized>(
generator: &mut G,
ctx: &mut CodeGenContext<'ctx, '_>,
a: (Type, BasicValueEnum<'ctx>),
fn_name: &str,
) -> Result<BasicValueEnum<'ctx>, String> {
const FN_NAME: &str = "np_max";
debug_assert!(["np_argmin", "np_argmax", "np_max", "np_min"].iter().any(|f| *f == fn_name));
let llvm_int64 = ctx.ctx.i64_type();
let llvm_usize = generator.get_size_type(ctx.ctx);
let (a_ty, a) = a;
Ok(match a {
BasicValueEnum::IntValue(_) | BasicValueEnum::FloatValue(_) => {
debug_assert!([
@ -902,9 +820,12 @@ pub fn call_numpy_max<'ctx, G: CodeGenerator + ?Sized>(
.iter()
.any(|ty| ctx.unifier.unioned(a_ty, *ty)));
a
match fn_name {
"np_argmin" | "np_argmax" => llvm_int64.const_zero().into(),
"np_max" | "np_min" => a,
_ => unreachable!(),
}
}
BasicValueEnum::PointerValue(n)
if a_ty.obj_id(&ctx.unifier).is_some_and(|id| id == PrimDef::NDArray.id()) =>
{
@ -923,41 +844,81 @@ pub fn call_numpy_max<'ctx, G: CodeGenerator + ?Sized>(
generator,
n_sz_eqz,
"0:ValueError",
"zero-size array to reduction operation minimum which has no identity",
format!("zero-size array to reduction operation {fn_name}").as_str(),
[None, None, None],
ctx.current_loc,
);
}
let accumulator_addr = generator.gen_var_alloc(ctx, llvm_ndarray_ty, None)?;
let res_idx = generator.gen_var_alloc(ctx, llvm_int64.into(), None)?;
unsafe {
let identity =
n.data().get_unchecked(ctx, generator, &llvm_usize.const_zero(), None);
ctx.builder.build_store(accumulator_addr, identity).unwrap();
ctx.builder.build_store(res_idx, llvm_int64.const_zero()).unwrap();
}
gen_for_callback_incrementing(
generator,
ctx,
llvm_usize.const_int(1, false),
llvm_int64.const_int(1, false),
(n_sz, false),
|generator, ctx, _, idx| {
let elem = unsafe { n.data().get_unchecked(ctx, generator, &idx, None) };
let accumulator = ctx.builder.build_load(accumulator_addr, "").unwrap();
let result = call_max(ctx, (elem_ty, accumulator), (elem_ty, elem));
let cur_idx = ctx.builder.build_load(res_idx, "").unwrap();
let result = match fn_name {
"np_argmin" | "np_min" => {
call_min(ctx, (elem_ty, accumulator), (elem_ty, elem))
}
"np_argmax" | "np_max" => {
call_max(ctx, (elem_ty, accumulator), (elem_ty, elem))
}
_ => unreachable!(),
};
let updated_idx = match (accumulator, result) {
(BasicValueEnum::IntValue(m), BasicValueEnum::IntValue(n)) => ctx
.builder
.build_select(
ctx.builder.build_int_compare(IntPredicate::NE, m, n, "").unwrap(),
idx.into(),
cur_idx,
"",
)
.unwrap(),
(BasicValueEnum::FloatValue(m), BasicValueEnum::FloatValue(n)) => ctx
.builder
.build_select(
ctx.builder
.build_float_compare(FloatPredicate::ONE, m, n, "")
.unwrap(),
idx.into(),
cur_idx,
"",
)
.unwrap(),
_ => unsupported_type(ctx, fn_name, &[elem_ty, elem_ty]),
};
ctx.builder.build_store(res_idx, updated_idx).unwrap();
ctx.builder.build_store(accumulator_addr, result).unwrap();
Ok(())
},
llvm_usize.const_int(1, false),
llvm_int64.const_int(1, false),
)?;
let accumulator = ctx.builder.build_load(accumulator_addr, "").unwrap();
accumulator
match fn_name {
"np_argmin" | "np_argmax" => ctx.builder.build_load(res_idx, "").unwrap(),
"np_max" | "np_min" => ctx.builder.build_load(accumulator_addr, "").unwrap(),
_ => unreachable!(),
}
}
_ => unsupported_type(ctx, FN_NAME, &[a_ty]),
_ => unsupported_type(ctx, fn_name, &[a_ty]),
})
}

View File

@ -1,10 +1,11 @@
use std::{collections::HashMap, convert::TryInto, iter::once, iter::zip};
use super::irrt::slice::{RustUserSlice, SliceIndex};
use crate::{
codegen::{
classes::{
ArrayLikeIndexer, ArrayLikeValue, ListType, ListValue, NDArrayValue, ProxyType,
ProxyValue, RangeValue, TypedArrayLikeAccessor, UntypedArrayLikeAccessor,
ProxyValue, RangeValue, UntypedArrayLikeAccessor,
},
concrete_type::{ConcreteFuncArg, ConcreteTypeEnum, ConcreteTypeStore},
gen_in_range_check, get_llvm_abi_type, get_llvm_type,
@ -21,11 +22,7 @@ use crate::{
CodeGenContext, CodeGenTask, CodeGenerator,
},
symbol_resolver::{SymbolValue, ValueEnum},
toplevel::{
helper::PrimDef,
numpy::{make_ndarray_ty, unpack_ndarray_var_tys},
DefinitionId, TopLevelDef,
},
toplevel::{helper::PrimDef, numpy::unpack_ndarray_var_tys, DefinitionId, TopLevelDef},
typecheck::{
magic_methods::{Binop, BinopVariant, HasOpInfo},
typedef::{FunSignature, FuncArg, Type, TypeEnum, TypeVarId, Unifier, VarMap},
@ -34,13 +31,26 @@ use crate::{
use inkwell::{
attributes::{Attribute, AttributeLoc},
types::{AnyType, BasicType, BasicTypeEnum},
values::{BasicValueEnum, CallSiteValue, FunctionValue, IntValue, PointerValue},
values::{BasicValue, BasicValueEnum, CallSiteValue, FunctionValue, IntValue, PointerValue},
AddressSpace, IntPredicate, OptimizationLevel,
};
use itertools::{chain, izip, Either, Itertools};
use nac3parser::ast::{
self, Boolop, Cmpop, Comprehension, Constant, Expr, ExprKind, Location, Operator, StrRef,
Unaryop,
self, Boolop, Cmpop, Comprehension, Constant, Expr, ExprKind, Located, Location, Operator,
StrRef, Unaryop,
};
use ndarray::{
allocation::alloca_ndarray,
indexing::{call_nac3_ndarray_index, RustNDIndex},
};
use super::{
model::*,
structs::{
cslice::CSlice,
exception::{Exception, ExceptionId},
ndarray::NpArray,
},
};
pub fn get_subst_key(
@ -281,24 +291,7 @@ impl<'ctx, 'a> CodeGenContext<'ctx, 'a> {
None
}
}
Constant::Str(v) => {
assert!(self.unifier.unioned(ty, self.primitives.str));
if let Some(v) = self.const_strings.get(v) {
Some(*v)
} else {
let str_ptr = self
.builder
.build_global_string_ptr(v, "const")
.map(|v| v.as_pointer_value().into())
.unwrap();
let size = generator.get_size_type(self.ctx).const_int(v.len() as u64, false);
let ty = self.get_llvm_type(generator, self.primitives.str);
let val =
ty.into_struct_type().const_named_struct(&[str_ptr, size.into()]).into();
self.const_strings.insert(v.to_string(), val);
Some(val)
}
}
Constant::Str(s) => Some(self.gen_string(generator, s).value.into()),
Constant::Ellipsis => {
let msg = self.gen_string(generator, "NotImplementedError");
@ -560,96 +553,135 @@ impl<'ctx, 'a> CodeGenContext<'ctx, 'a> {
}
/// Helper function for generating a LLVM variable storing a [String].
pub fn gen_string<G, S>(&mut self, generator: &mut G, s: S) -> BasicValueEnum<'ctx>
pub fn gen_string<G>(&mut self, generator: &mut G, string: &str) -> Struct<'ctx, CSlice<'ctx>>
where
G: CodeGenerator + ?Sized,
S: Into<String>,
{
self.gen_const(generator, &Constant::Str(s.into()), self.primitives.str).unwrap()
self.const_strings.get(string).copied().unwrap_or_else(|| {
let sizet = generator.get_sizet(self.ctx);
let pbyte_model = PointerModel(NIntModel(Byte));
let cslice_model = StructModel(CSlice { sizet });
// Create `base`, it has to be a global cstr
let base = self.builder.build_global_string_ptr(string, "constant_string").unwrap();
let base = pbyte_model.review_value(self.ctx, base.as_pointer_value()).unwrap();
// Create `len`, it also has to be global
let len = sizet.constant(self.ctx, string.len() as u64);
// Finally, create the global `CSlice` constant of the string.
let cslice = cslice_model.create_const(self, base, len);
// Cache it
self.const_strings.insert(string.to_owned(), cslice);
cslice
})
}
pub fn raise_exn_impl<G: CodeGenerator + ?Sized>(
&mut self,
generator: &mut G,
exn_id: NInt<'ctx, ExceptionId>,
msg: Struct<'ctx, CSlice<'ctx>>,
params: [Option<NInt<'ctx, Int64>>; 3],
loc: Location,
) {
let sizet = generator.get_sizet(self.ctx);
let exception_model = StructModel(Exception { sizet });
// Get `exn`
let exn = self.exception_val.unwrap_or_else(|| {
let exn = exception_model.var_alloc(generator, self, Some("exn")).unwrap();
*self.exception_val.insert(exn)
});
// Only have to store `exception_id`, `message`, and the parameters.
exn.gep(self, |f| f.exception_id).store(self, exn_id);
exn.gep(self, |f| f.message).store(self, msg);
for (i, param) in params.iter().enumerate() {
if let Some(param) = param {
exn.gep(self, |f| f.params[i]).store(self, *param);
}
}
gen_raise(generator, self, Some(exn), loc);
}
pub fn raise_exn<G: CodeGenerator + ?Sized>(
&mut self,
generator: &mut G,
name: &str,
msg: BasicValueEnum<'ctx>,
params: [Option<IntValue<'ctx>>; 3],
msg: Struct<'ctx, CSlice<'ctx>>,
params: [Option<NInt<'ctx, Int64>>; 3],
loc: Location,
) {
let zelf = if let Some(exception_val) = self.exception_val {
exception_val
} else {
let ty = self.get_llvm_type(generator, self.primitives.exception).into_pointer_type();
let zelf_ty: BasicTypeEnum = ty.get_element_type().into_struct_type().into();
let zelf = generator.gen_var_alloc(self, zelf_ty, Some("exn")).unwrap();
*self.exception_val.insert(zelf)
};
let int32 = self.ctx.i32_type();
let zero = int32.const_zero();
unsafe {
let id_ptr = self.builder.build_in_bounds_gep(zelf, &[zero, zero], "exn.id").unwrap();
let id = self.resolver.get_string_id(name);
self.builder.build_store(id_ptr, int32.const_int(id as u64, false)).unwrap();
let ptr = self
.builder
.build_in_bounds_gep(zelf, &[zero, int32.const_int(5, false)], "exn.msg")
.unwrap();
self.builder.build_store(ptr, msg).unwrap();
let i64_zero = self.ctx.i64_type().const_zero();
for (i, attr_ind) in [6, 7, 8].iter().enumerate() {
let ptr = self
.builder
.build_in_bounds_gep(
zelf,
&[zero, int32.const_int(*attr_ind, false)],
"exn.param",
)
.unwrap();
let val = params[i].map_or(i64_zero, |v| {
self.builder.build_int_s_extend(v, self.ctx.i64_type(), "sext").unwrap()
});
self.builder.build_store(ptr, val).unwrap();
}
}
gen_raise(generator, self, Some(&zelf.into()), loc);
let exn_id_model = NIntModel(ExceptionId::default());
let exn_id = self.resolver.get_string_id(name);
let exn_id = exn_id_model.constant(self.ctx, exn_id as u64);
self.raise_exn_impl(generator, exn_id, msg, params, loc);
}
pub fn make_assert<G: CodeGenerator + ?Sized>(
&mut self,
generator: &mut G,
cond: IntValue<'ctx>,
cond: IntValue<'ctx>, // IntType can have arbitrary bit width
err_name: &str,
err_msg: &str,
params: [Option<IntValue<'ctx>>; 3],
loc: Location,
) {
// Define all used models
let i64_model = NIntModel(Int64);
// Create a global `CSlice` constant from `err_msg`
let err_msg = self.gen_string(generator, err_msg);
// Check `params`
let ctx = self.ctx;
let params =
params.map(|param| param.map(|param| i64_model.review_value(ctx, param).unwrap()));
self.make_assert_impl(generator, cond, err_name, err_msg, params, loc);
}
pub fn make_assert_impl<G: CodeGenerator + ?Sized>(
&mut self,
generator: &mut G,
cond: IntValue<'ctx>,
cond: IntValue<'ctx>, // IntType can have arbitrary bit width
err_name: &str,
err_msg: BasicValueEnum<'ctx>,
params: [Option<IntValue<'ctx>>; 3],
err_msg: Struct<'ctx, CSlice<'ctx>>,
params: [Option<NInt<'ctx, Int64>>; 3],
loc: Location,
) {
let i1 = self.ctx.bool_type();
let i1_true = i1.const_all_ones();
// we assume that the condition is most probably true, so the normal path is the most
// probable path
// even if this assumption is violated, it does not matter as exception unwinding is
// slow anyway...
let cond = call_expect(self, cond, i1_true, Some("expect"));
// Define all used models
let bool_model = NIntModel(Bool);
// Truncate `cond` to a `i1`.
// So this could accept both nac3core's bool IntType (i8), and i1.
let cond = Int::from(cond);
let cond = cond.truncate(self, bool_model, "cond_bool");
// We assume that the condition is most probably true, so the normal path is the most
// probable path even if this assumption is violated, it does not matter as exception unwinding is.
let cond =
call_expect(self, cond.value, bool_model.const_true(self.ctx).value, Some("expect"));
let current_bb = self.builder.get_insert_block().unwrap();
let current_fun = current_bb.get_parent().unwrap();
let then_block = self.ctx.insert_basic_block_after(current_bb, "succ");
let exn_block = self.ctx.append_basic_block(current_fun, "fail");
self.builder.build_conditional_branch(cond, then_block, exn_block).unwrap();
// Inserting into `exn_block`
self.builder.position_at_end(exn_block);
self.raise_exn(generator, err_name, err_msg, params, loc);
// Continuation
self.builder.position_at_end(then_block);
}
}
@ -951,9 +983,9 @@ pub fn destructure_range<'ctx>(
/// Allocates a List structure with the given [type][ty] and [length]. The name of the resulting
/// LLVM value is `{name}.addr`, or `list.addr` if [name] is not specified.
///
/// Setting `ty` to [`None`] implies that the list does not have a known element type, which is only
/// valid for empty lists. It is undefined behavior to generate a sized list with an unknown element
/// type.
/// Setting `ty` to [`None`] implies that the list is empty **and** does not have a known element
/// type, and will therefore set the `list.data` type as `size_t*`. It is undefined behavior to
/// generate a sized list with an unknown element type.
pub fn allocate_list<'ctx, G: CodeGenerator + ?Sized>(
generator: &mut G,
ctx: &mut CodeGenContext<'ctx, '_>,
@ -2090,322 +2122,142 @@ pub fn gen_cmpop_expr<'ctx, G: CodeGenerator>(
/// Generates code for a subscript expression on an `ndarray`.
///
/// * `ty` - The `Type` of the `NDArray` elements.
/// * `elem_ty` - The `Type` of the `NDArray` elements.
/// * `ndims` - The `Type` of the `NDArray` number-of-dimensions `Literal`.
/// * `v` - The `NDArray` value.
/// * `slice` - The slice expression used to subscript into the `ndarray`.
/// * `src_ndarray` - The `NDArray` value.
/// * `subscript` - The subscript expression used to index into the `ndarray`.
fn gen_ndarray_subscript_expr<'ctx, G: CodeGenerator>(
generator: &mut G,
ctx: &mut CodeGenContext<'ctx, '_>,
ty: Type,
elem_ty: Type,
ndims: Type,
v: NDArrayValue<'ctx>,
slice: &Expr<Option<Type>>,
src_ndarray: Pointer<'ctx, StructModel<NpArray<'ctx>>>,
subscript: &Expr<Option<Type>>,
) -> Result<Option<ValueEnum<'ctx>>, String> {
let llvm_i1 = ctx.ctx.bool_type();
let llvm_i32 = ctx.ctx.i32_type();
let llvm_usize = generator.get_size_type(ctx.ctx);
// TODO: Support https://numpy.org/doc/stable/user/basics.indexing.html#dimensional-indexing-tools
let sizet = generator.get_sizet(ctx.ctx);
let slice_index_model = NIntModel(SliceIndex::default());
let TypeEnum::TLiteral { values, .. } = &*ctx.unifier.get_ty_immutable(ndims) else {
// Annoying notes about `slice`
// - `my_array[5]`
// - slice is a `Constant`
// - `my_array[:5]`
// - slice is a `Slice`
// - `my_array[:]`
// - slice is a `Slice`, but lower upper step would all be `Option::None`
// - `my_array[:, :]`
// - slice is now a `Tuple` of two `Slice`-s
//
// In summary:
// - when there is a comma "," within [], `slice` will be a `Tuple` of the entries.
// - when there is not comma "," within [] (i.e., just a single entry), `slice` will be that entry itself.
//
// So we first "flatten" out the slice expression
let index_exprs = match &subscript.node {
ExprKind::Tuple { elts, .. } => elts.iter().collect_vec(),
_ => vec![subscript],
};
// Process all index expressions
let mut rust_ndindexes: Vec<RustNDIndex> = Vec::with_capacity(index_exprs.len()); // Not using iterators here because `?` is used here.
for index_expr in index_exprs {
// NOTE: Currently nac3core's slices do not have an object representation,
// so the code/implementation looks awkward - we have to do pattern matching on the expression
let ndindex = if let ExprKind::Slice { lower: start, upper: stop, step } = &index_expr.node
{
// Helper function here to deduce code duplication
type ValueExpr = Option<Box<Located<ExprKind<Option<Type>>, Option<Type>>>>;
let mut help = |value_expr: &ValueExpr| -> Result<_, String> {
Ok(match value_expr {
None => None,
Some(value_expr) => {
let value_expr = generator
.gen_expr(ctx, value_expr)?
.unwrap()
.to_basic_value_enum(ctx, generator, ctx.primitives.int32)?;
let value_expr =
slice_index_model.review_value(ctx.ctx, value_expr).unwrap();
Some(value_expr)
}
})
};
let start = help(start)?;
let stop = help(stop)?;
let step = help(step)?;
RustNDIndex::Slice(RustUserSlice { start, stop, step })
} else {
// Anything else that is not a slice (might be illegal values),
// For nac3core, this should be e.g., an int32 constant, an int32 variable, otherwise its an error
let index = generator.gen_expr(ctx, index_expr)?.unwrap().to_basic_value_enum(
ctx,
generator,
ctx.primitives.int32,
)?;
let index = slice_index_model.review_value(ctx.ctx, index).unwrap();
RustNDIndex::SingleElement(index)
};
rust_ndindexes.push(ndindex);
}
// Extract the `ndims` from a `Type` to `i128`
// We *HAVE* to know this statically, this is used to determine
// whether this subscript expression returns a scalar or an ndarray
let TypeEnum::TLiteral { values: ndims_values, .. } = &*ctx.unifier.get_ty_immutable(ndims)
else {
unreachable!()
};
assert_eq!(ndims_values.len(), 1);
let src_ndims = i128::try_from(ndims_values[0].clone()).unwrap();
let ndims = values
.iter()
.map(|ndim| u64::try_from(ndim.clone()).map_err(|()| ndim.clone()))
.collect::<Result<Vec<_>, _>>()
.map_err(|val| {
format!(
"Expected non-negative literal for ndarray.ndims, got {}",
i128::try_from(val).unwrap()
)
})?;
assert!(!ndims.is_empty());
// The number of dimensions subscripted by the index expression.
// Slicing a ndarray will yield the same number of dimensions, whereas indexing into a
// dimension will remove a dimension.
let subscripted_dims = match &slice.node {
ExprKind::Tuple { elts, .. } => elts.iter().fold(0, |acc, value_subexpr| {
if let ExprKind::Slice { .. } = &value_subexpr.node {
acc
} else {
acc + 1
}
}),
ExprKind::Slice { .. } => 0,
_ => 1,
};
let ndarray_ndims_ty = ctx.unifier.get_fresh_literal(
ndims.iter().map(|v| SymbolValue::U64(v - subscripted_dims)).collect(),
None,
);
let ndarray_ty =
make_ndarray_ty(&mut ctx.unifier, &ctx.primitives, Some(ty), Some(ndarray_ndims_ty));
let llvm_pndarray_t = ctx.get_llvm_type(generator, ndarray_ty).into_pointer_type();
let llvm_ndarray_t = llvm_pndarray_t.get_element_type().into_struct_type();
let llvm_ndarray_data_t = ctx.get_llvm_type(generator, ty).as_basic_type_enum();
// Check that len is non-zero
let len = v.load_ndims(ctx);
ctx.make_assert(
generator,
ctx.builder.build_int_compare(IntPredicate::SGT, len, llvm_usize.const_zero(), "").unwrap(),
"0:IndexError",
"too many indices for array: array is {0}-dimensional but 1 were indexed",
[Some(len), None, None],
slice.location,
);
// Normalizes a possibly-negative index to its corresponding positive index
let normalize_index = |generator: &mut G,
ctx: &mut CodeGenContext<'ctx, '_>,
index: IntValue<'ctx>,
dim: u64| {
gen_if_else_expr_callback(
// Check for "too many indices for array: array is ..." error
if src_ndims < rust_ndindexes.len() as i128 {
ctx.make_assert(
generator,
ctx,
|_, ctx| {
Ok(ctx
.builder
.build_int_compare(IntPredicate::SGE, index, index.get_type().const_zero(), "")
.unwrap())
},
|_, _| Ok(Some(index)),
|generator, ctx| {
let llvm_i32 = ctx.ctx.i32_type();
ctx.ctx.bool_type().const_int(1, false),
"0:IndexError",
"too many indices for array: array is {0}-dimensional, but {1} were indexed",
[None, None, None],
ctx.current_loc,
);
}
let len = unsafe {
v.dim_sizes().get_typed_unchecked(
ctx,
generator,
&llvm_usize.const_int(dim, true),
None,
)
};
let dst_ndims = RustNDIndex::deduce_ndims_after_slicing(&rust_ndindexes, src_ndims as i32);
let dst_ndarray =
alloca_ndarray(generator, ctx, sizet.constant(ctx.ctx, dst_ndims as u64), "subndarray")?;
let index = ctx
.builder
.build_int_add(
len,
ctx.builder.build_int_s_extend(index, llvm_usize, "").unwrap(),
"",
)
.unwrap();
// Prepare the subscripts
let ndsubscript_array = RustNDIndex::alloca_ndindexes(generator, ctx, &rust_ndindexes);
Ok(Some(ctx.builder.build_int_truncate(index, llvm_i32, "").unwrap()))
},
)
.map(|v| v.map(BasicValueEnum::into_int_value))
};
// NOTE: IRRT does check for indexing errors
call_nac3_ndarray_index(
generator,
ctx,
ndsubscript_array.num_elements,
ndsubscript_array.pointer,
src_ndarray,
dst_ndarray,
);
// Converts a slice expression into a slice-range tuple
let expr_to_slice = |generator: &mut G,
ctx: &mut CodeGenContext<'ctx, '_>,
node: &ExprKind<Option<Type>>,
dim: u64| {
match node {
ExprKind::Constant { value: Constant::Int(v), .. } => {
let Some(index) =
normalize_index(generator, ctx, llvm_i32.const_int(*v as u64, true), dim)?
else {
return Ok(None);
};
// ...and return the result, with two cases
let result_llvm_value: BasicValueEnum<'_> = if dst_ndims == 0 {
// 1) ndims == 0 (this happens when you do `np.zerps((3, 4))[1, 1]`), return the element
let elem_model = OpaqueModel(ctx.get_llvm_type(generator, elem_ty));
Ok(Some((index, index, llvm_i32.const_int(1, true))))
}
ExprKind::Slice { lower, upper, step } => {
let dim_sz = unsafe {
v.dim_sizes().get_typed_unchecked(
ctx,
generator,
&llvm_usize.const_int(dim, false),
None,
)
};
handle_slice_indices(lower, upper, step, ctx, generator, dim_sz)
}
_ => {
let Some(index) = generator.gen_expr(ctx, slice)? else { return Ok(None) };
let index = index
.to_basic_value_enum(ctx, generator, slice.custom.unwrap())?
.into_int_value();
let Some(index) = normalize_index(generator, ctx, index, dim)? else {
return Ok(None);
};
Ok(Some((index, index, llvm_i32.const_int(1, true))))
}
}
};
let make_indices_arr = |generator: &mut G,
ctx: &mut CodeGenContext<'ctx, '_>|
-> Result<_, String> {
Ok(if let ExprKind::Tuple { elts, .. } = &slice.node {
let llvm_int_ty = ctx.get_llvm_type(generator, elts[0].custom.unwrap());
let index_addr = generator.gen_array_var_alloc(
ctx,
llvm_int_ty,
llvm_usize.const_int(elts.len() as u64, false),
None,
)?;
for (i, elt) in elts.iter().enumerate() {
let Some(index) = generator.gen_expr(ctx, elt)? else {
return Ok(None);
};
let index = index
.to_basic_value_enum(ctx, generator, elt.custom.unwrap())?
.into_int_value();
let Some(index) = normalize_index(generator, ctx, index, 0)? else {
return Ok(None);
};
let store_ptr = unsafe {
index_addr.ptr_offset_unchecked(
ctx,
generator,
&llvm_usize.const_int(i as u64, false),
None,
)
};
ctx.builder.build_store(store_ptr, index).unwrap();
}
Some(index_addr)
} else if let Some(index) = generator.gen_expr(ctx, slice)? {
let llvm_int_ty = ctx.get_llvm_type(generator, slice.custom.unwrap());
let index_addr = generator.gen_array_var_alloc(
ctx,
llvm_int_ty,
llvm_usize.const_int(1u64, false),
None,
)?;
let index =
index.to_basic_value_enum(ctx, generator, slice.custom.unwrap())?.into_int_value();
let Some(index) = normalize_index(generator, ctx, index, 0)? else { return Ok(None) };
let store_ptr = unsafe {
index_addr.ptr_offset_unchecked(ctx, generator, &llvm_usize.const_zero(), None)
};
ctx.builder.build_store(store_ptr, index).unwrap();
Some(index_addr)
} else {
None
})
};
Ok(Some(if ndims.len() == 1 && ndims[0] - subscripted_dims == 0 {
let Some(index_addr) = make_indices_arr(generator, ctx)? else { return Ok(None) };
v.data().get(ctx, generator, &index_addr, None).into()
// `*data` points to the first element by definition
let element_ptr = dst_ndarray.gep(ctx, |f| f.data).load(ctx, "pelement");
let element = element_ptr.cast_to(ctx, elem_model, "").load(ctx, "element");
element.value
} else {
match &slice.node {
ExprKind::Tuple { elts, .. } => {
let slices = elts
.iter()
.enumerate()
.map(|(dim, elt)| expr_to_slice(generator, ctx, &elt.node, dim as u64))
.take_while_inclusive(|slice| slice.as_ref().is_ok_and(Option::is_some))
.collect::<Result<Vec<_>, _>>()?;
if slices.len() < elts.len() {
return Ok(None);
}
let slices = slices.into_iter().map(Option::unwrap).collect_vec();
numpy::ndarray_sliced_copy(generator, ctx, ty, v, &slices)?.as_base_value().into()
}
ExprKind::Slice { .. } => {
let Some(slice) = expr_to_slice(generator, ctx, &slice.node, 0)? else {
return Ok(None);
};
numpy::ndarray_sliced_copy(generator, ctx, ty, v, &[slice])?.as_base_value().into()
}
_ => {
// Accessing an element from a multi-dimensional `ndarray`
let Some(index_addr) = make_indices_arr(generator, ctx)? else { return Ok(None) };
// Create a new array, remove the top dimension from the dimension-size-list, and copy the
// elements over
let subscripted_ndarray =
generator.gen_var_alloc(ctx, llvm_ndarray_t.into(), None)?;
let ndarray = NDArrayValue::from_ptr_val(subscripted_ndarray, llvm_usize, None);
let num_dims = v.load_ndims(ctx);
ndarray.store_ndims(
ctx,
generator,
ctx.builder
.build_int_sub(num_dims, llvm_usize.const_int(1, false), "")
.unwrap(),
);
let ndarray_num_dims = ndarray.load_ndims(ctx);
ndarray.create_dim_sizes(ctx, llvm_usize, ndarray_num_dims);
let ndarray_num_dims = ndarray.load_ndims(ctx);
let v_dims_src_ptr = unsafe {
v.dim_sizes().ptr_offset_unchecked(
ctx,
generator,
&llvm_usize.const_int(1, false),
None,
)
};
call_memcpy_generic(
ctx,
ndarray.dim_sizes().base_ptr(ctx, generator),
v_dims_src_ptr,
ctx.builder
.build_int_mul(ndarray_num_dims, llvm_usize.size_of(), "")
.map(Into::into)
.unwrap(),
llvm_i1.const_zero(),
);
let ndarray_num_elems = call_ndarray_calc_size(
generator,
ctx,
&ndarray.dim_sizes().as_slice_value(ctx, generator),
(None, None),
);
ndarray.create_data(ctx, llvm_ndarray_data_t, ndarray_num_elems);
let v_data_src_ptr = v.data().ptr_offset(ctx, generator, &index_addr, None);
call_memcpy_generic(
ctx,
ndarray.data().base_ptr(ctx, generator),
v_data_src_ptr,
ctx.builder
.build_int_mul(
ndarray_num_elems,
llvm_ndarray_data_t.size_of().unwrap(),
"",
)
.map(Into::into)
.unwrap(),
llvm_i1.const_zero(),
);
ndarray.as_base_value().into()
}
}
}))
// 2) ndims > 0 (other cases), return subndarray
dst_ndarray.value.as_basic_value_enum()
};
Ok(Some(ValueEnum::Dynamic(result_llvm_value)))
}
/// See [`CodeGenerator::gen_expr`].
@ -2457,7 +2309,29 @@ pub fn gen_expr<'ctx, G: CodeGenerator>(
Some((_, Some(static_value), _)) => ValueEnum::Static(static_value.clone()),
None => {
let resolver = ctx.resolver.clone();
resolver.get_symbol_value(*id, ctx).unwrap()
if let Some(res) = resolver.get_symbol_value(*id, ctx) {
res
} else {
// Allow "raise Exception" short form
let def_id = resolver.get_identifier_def(*id).map_err(|e| {
format!("{} (at {})", e.iter().next().unwrap(), expr.location)
})?;
let def = ctx.top_level.definitions.read();
if let TopLevelDef::Class { constructor, .. } = *def[def_id.0].read() {
let TypeEnum::TFunc(signature) =
ctx.unifier.get_ty(constructor.unwrap()).as_ref().clone()
else {
return Err(format!(
"Failed to resolve symbol {} (at {})",
id, expr.location
));
};
return Ok(generator
.gen_call(ctx, None, (&signature, def_id), Vec::default())?
.map(Into::into));
}
return Err(format!("Failed to resolve symbol {} (at {})", id, expr.location));
}
}
},
ExprKind::List { elts, .. } => {
@ -3026,17 +2900,22 @@ pub fn gen_expr<'ctx, G: CodeGenerator>(
}
}
TypeEnum::TObj { obj_id, params, .. } if *obj_id == PrimDef::NDArray.id() => {
let (ty, ndims) = params.iter().map(|(_, ty)| ty).collect_tuple().unwrap();
let (dtype, ndims) = params.iter().map(|(_, ty)| ty).collect_tuple().unwrap();
let v = if let Some(v) = generator.gen_expr(ctx, value)? {
v.to_basic_value_enum(ctx, generator, value.custom.unwrap())?
.into_pointer_value()
} else {
let sizet = generator.get_sizet(ctx.ctx);
let pndarray_model = PointerModel(StructModel(NpArray { sizet }));
let Some(ndarray) = generator.gen_expr(ctx, value)? else {
return Ok(None);
};
let v = NDArrayValue::from_ptr_val(v, usize, None);
return gen_ndarray_subscript_expr(generator, ctx, *ty, *ndims, v, slice);
let ndarray =
ndarray.to_basic_value_enum(ctx, generator, value.custom.unwrap())?;
let ndarray = pndarray_model.review_value(ctx.ctx, ndarray).unwrap();
return gen_ndarray_subscript_expr(
generator, ctx, *dtype, *ndims, ndarray, slice,
);
}
TypeEnum::TTuple { .. } => {
let index: u32 =

View File

@ -11,12 +11,18 @@ use inkwell::{
};
use nac3parser::ast::{Expr, Stmt, StrRef};
use super::model::SizeTModel;
pub trait CodeGenerator {
/// Return the module name for the code generator.
fn get_name(&self) -> &str;
fn get_size_type<'ctx>(&self, ctx: &'ctx Context) -> IntType<'ctx>;
fn get_sizet<'ctx>(&self, ctx: &'ctx Context) -> SizeTModel<'ctx> {
SizeTModel(self.get_size_type(ctx))
}
/// Generate function call and returns the function return value.
/// - obj: Optional object for method call.
/// - fun: Function signature and definition ID.

View File

@ -0,0 +1,195 @@
use crate::codegen::{model::*, structs::cslice::CSlice, CodeGenContext, CodeGenerator};
use super::util::get_sized_dependent_function_name;
/// The [`IntModel`] of nac3core's error ID.
///
/// It is always [`Int32`].
type ErrorId = Int32;
#[allow(clippy::struct_field_names)]
pub struct ErrorIdsFields {
pub index_error: Field<NIntModel<ErrorId>>,
pub value_error: Field<NIntModel<ErrorId>>,
pub assertion_error: Field<NIntModel<ErrorId>>,
pub runtime_error: Field<NIntModel<ErrorId>>,
pub type_error: Field<NIntModel<ErrorId>>,
}
/// Corresponds to IRRT's `struct ErrorIds`
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ErrorIds;
impl<'ctx> StructKind<'ctx> for ErrorIds {
type Fields = ErrorIdsFields;
fn struct_name(&self) -> &'static str {
"ErrorIds"
}
fn build_fields(&self, builder: &mut FieldBuilder) -> Self::Fields {
Self::Fields {
index_error: builder.add_field_auto("index_error"),
value_error: builder.add_field_auto("value_error"),
assertion_error: builder.add_field_auto("assertion_error"),
runtime_error: builder.add_field_auto("runtime_error"),
type_error: builder.add_field_auto("type_error"),
}
}
}
pub struct ErrorContextFields {
pub error_ids: Field<PointerModel<StructModel<ErrorIds>>>,
pub error_id: Field<NIntModel<ErrorId>>,
pub message_template: Field<PointerModel<NIntModel<Byte>>>,
pub param1: Field<NIntModel<Int64>>,
pub param2: Field<NIntModel<Int64>>,
pub param3: Field<NIntModel<Int64>>,
}
/// Corresponds to IRRT's `struct ErrorContext`
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ErrorContext;
impl<'ctx> StructKind<'ctx> for ErrorContext {
type Fields = ErrorContextFields;
fn struct_name(&self) -> &'static str {
"ErrorIds"
}
fn build_fields(&self, builder: &mut FieldBuilder) -> Self::Fields {
Self::Fields {
error_ids: builder.add_field_auto("error_ids"),
error_id: builder.add_field_auto("error_id"),
message_template: builder.add_field_auto("message_template"),
param1: builder.add_field_auto("param1"),
param2: builder.add_field_auto("param2"),
param3: builder.add_field_auto("param3"),
}
}
}
// Prepare ErrorIds
fn build_error_ids<'ctx>(ctx: &CodeGenContext<'ctx, '_>) -> Pointer<'ctx, StructModel<ErrorIds>> {
// ErrorIdsLens.get_fields(ctx.ctx).assertion_error.
let error_ids = StructModel(ErrorIds).alloca(ctx, "error_ids");
let i32_model = NIntModel(Int32);
// i32_model.make_constant()
let get_string_id =
|string_id| i32_model.constant(ctx.ctx, ctx.resolver.get_string_id(string_id) as u64);
error_ids.gep(ctx, |f| f.index_error).store(ctx, get_string_id("0:IndexError"));
error_ids.gep(ctx, |f| f.value_error).store(ctx, get_string_id("0:ValueError"));
error_ids.gep(ctx, |f| f.assertion_error).store(ctx, get_string_id("0:AssertionError"));
error_ids.gep(ctx, |f| f.runtime_error).store(ctx, get_string_id("0:RuntimeError"));
error_ids.gep(ctx, |f| f.type_error).store(ctx, get_string_id("0:TypeError"));
error_ids
}
pub fn call_nac3_error_context_initialize<'ctx>(
ctx: &CodeGenContext<'ctx, '_>,
perrctx: Pointer<'ctx, StructModel<ErrorContext>>,
perror_ids: Pointer<'ctx, StructModel<ErrorIds>>,
) {
FunctionBuilder::begin(ctx, "__nac3_error_context_initialize")
.arg("errctx", perrctx)
.arg("error_ids", perror_ids)
.returning_void();
}
pub fn call_nac3_error_context_has_error<'ctx>(
ctx: &CodeGenContext<'ctx, '_>,
errctx: Pointer<'ctx, StructModel<ErrorContext>>,
) -> NInt<'ctx, Bool> {
FunctionBuilder::begin(ctx, "__nac3_error_context_has_error")
.arg("errctx", errctx)
.returning("has_error", NIntModel(Bool))
}
pub fn call_nac3_error_context_get_error_str<'ctx, G: CodeGenerator + ?Sized>(
generator: &mut G,
ctx: &CodeGenContext<'ctx, '_>,
errctx: Pointer<'ctx, StructModel<ErrorContext>>,
dst_str: Pointer<'ctx, StructModel<CSlice<'ctx>>>,
) {
let sizet = generator.get_sizet(ctx.ctx);
FunctionBuilder::begin(
ctx,
&get_sized_dependent_function_name(sizet, "__nac3_error_context_get_error_str"),
)
.arg("errctx", errctx)
.arg("dst_str", dst_str)
.returning_void();
}
/// Setup a [`ErrorContext`] that could
/// be passed to IRRT functions taking in a `ErrorContext* errctx`
/// for error reporting purposes.
///
/// Also see: [`check_error_context`]
pub fn setup_error_context<'ctx>(
ctx: &CodeGenContext<'ctx, '_>,
) -> Pointer<'ctx, StructModel<ErrorContext>> {
let error_ids = build_error_ids(ctx);
let errctx_ptr = StructModel(ErrorContext).alloca(ctx, "errctx");
call_nac3_error_context_initialize(ctx, errctx_ptr, error_ids);
errctx_ptr
}
/// Check a [`ErrorContext`] to see
/// if it contains error.
///
/// If there is an error, an LLVM exception will be raised at runtime.
pub fn check_error_context<'ctx, G: CodeGenerator + ?Sized>(
generator: &mut G,
ctx: &mut CodeGenContext<'ctx, '_>,
errctx_ptr: Pointer<'ctx, StructModel<ErrorContext>>,
) {
let sizet = generator.get_sizet(ctx.ctx);
let cslice_model = StructModel(CSlice { sizet });
let current_bb = ctx.builder.get_insert_block().unwrap();
let irrt_has_error_bb = ctx.ctx.insert_basic_block_after(current_bb, "irrt_has_error");
let end_bb = ctx.ctx.insert_basic_block_after(irrt_has_error_bb, "end");
// Inserting into `current_bb`
let has_error = call_nac3_error_context_has_error(ctx, errctx_ptr);
ctx.builder.build_conditional_branch(has_error.value, irrt_has_error_bb, end_bb).unwrap();
// Inserting into `irrt_has_error_bb`
ctx.builder.position_at_end(irrt_has_error_bb);
// Load all the values for `ctx.make_assert_impl_by_id`
let pstr = cslice_model.alloca(ctx, "error_str");
call_nac3_error_context_get_error_str(generator, ctx, errctx_ptr, pstr);
let error_id = errctx_ptr.gep(ctx, |f| f.error_id).load(ctx, "error_id");
let msg = pstr.load(ctx, "msg");
let param1 = errctx_ptr.gep(ctx, |f| f.param1).load(ctx, "param1");
let param2 = errctx_ptr.gep(ctx, |f| f.param2).load(ctx, "param2");
let param3 = errctx_ptr.gep(ctx, |f| f.param3).load(ctx, "param3");
ctx.raise_exn_impl(
generator,
error_id,
msg,
[Some(param1), Some(param2), Some(param3)],
ctx.current_loc,
);
// Position to `end_bb` for continuation
ctx.builder.position_at_end(end_bb);
}
pub fn call_nac3_dummy_raise<G: CodeGenerator + ?Sized>(
generator: &mut G,
ctx: &mut CodeGenContext,
) {
let errctx = setup_error_context(ctx);
FunctionBuilder::begin(ctx, "__nac3_error_dummy_raise").arg("errctx", errctx).returning_void();
check_error_context(generator, ctx, errctx);
}

View File

@ -1,11 +1,17 @@
use crate::typecheck::typedef::Type;
mod error_context;
pub mod ndarray;
pub mod slice;
mod test;
mod util;
use super::{
classes::{
ArrayLikeIndexer, ArrayLikeValue, ArraySliceValue, ListValue, NDArrayValue,
TypedArrayLikeAdapter, UntypedArrayLikeAccessor,
},
llvm_intrinsics, CodeGenContext, CodeGenerator,
llvm_intrinsics, CodeGenContext, CodeGenerator, Int, Int64, NIntModel,
};
use crate::codegen::classes::TypedArrayLikeAccessor;
use crate::codegen::stmt::gen_for_callback_incrementing;
@ -414,14 +420,27 @@ pub fn list_slice_assignment<'ctx, G: CodeGenerator + ?Sized>(
.unwrap();
let cond_1 = ctx.builder.build_and(dest_step_eq_one, src_slt_dest, "slice_cond_1").unwrap();
let cond = ctx.builder.build_or(src_eq_dest, cond_1, "slice_cond").unwrap();
ctx.make_assert(
generator,
cond,
"0:ValueError",
"attempt to assign sequence of size {0} to slice of size {1} with step size {2}",
[Some(src_slice_len), Some(dest_slice_len), Some(dest_idx.2)],
ctx.current_loc,
);
// TODO: Temporary fix. Rewrite `list_slice_assignment` later
// Exception params should have been i64
{
let param_model = NIntModel(Int64);
let src_slice_len =
Int::from(src_slice_len).s_extend_or_bit_cast(ctx, param_model, "src_slice_len");
let dest_slice_len =
Int::from(dest_slice_len).s_extend_or_bit_cast(ctx, param_model, "dest_slice_len");
let dest_idx_2 = Int::from(dest_idx.2).s_extend_or_bit_cast(ctx, param_model, "dest_idx_2");
ctx.make_assert(
generator,
cond,
"0:ValueError",
"attempt to assign sequence of size {0} to slice of size {1} with step size {2}",
[Some(src_slice_len.value), Some(dest_slice_len.value), Some(dest_idx_2.value)],
ctx.current_loc,
);
}
let new_len = {
let args = vec![

View File

@ -0,0 +1,93 @@
use crate::codegen::model::*;
use crate::codegen::util::array_writer::ArrayWriter;
use crate::codegen::{structs::ndarray::NpArray, CodeGenContext, CodeGenerator};
use super::basic::{
call_nac3_ndarray_nbytes, call_nac3_ndarray_set_strides_by_shape,
call_nac3_ndarray_util_assert_shape_no_negative,
};
/**
Allocate an ndarray on the stack given its `ndims`.
`shape` and `strides` will be automatically allocated on the stack.
The returned ndarray's content will be:
- `data`: `nullptr`
- `itemsize`: **uninitialized** value
- `ndims`: initialized value, set to the input `ndims`
- `shape`: initialized pointer to an allocated stack with **uninitialized** values
- `strides`: initialized pointer to an allocated stack with **uninitialized** values
*/
pub fn alloca_ndarray<'ctx, G>(
generator: &mut G,
ctx: &mut CodeGenContext<'ctx, '_>,
ndims: SizeT<'ctx>,
name: &str,
) -> Result<Pointer<'ctx, StructModel<NpArray<'ctx>>>, String>
where
G: CodeGenerator + ?Sized,
{
let sizet = generator.get_sizet(ctx.ctx);
let ndarray_model = StructModel(NpArray { sizet });
let ndarray_data_model = PointerModel(NIntModel(Byte));
// Allocate ndarray
let ndarray_ptr = ndarray_model.alloca(ctx, name);
// Set data to nullptr
ndarray_ptr.gep(ctx, |f| f.data).store(ctx, ndarray_data_model.nullptr(ctx.ctx));
// Set ndims
ndarray_ptr.gep(ctx, |f| f.ndims).store(ctx, ndims);
// Allocate and set shape
let shape_array = sizet.array_alloca(ctx, ndims, "shape");
ndarray_ptr.gep(ctx, |f| f.shape).store(ctx, shape_array.pointer);
// Allocate and set strides
let strides_array = sizet.array_alloca(ctx, ndims, "strides");
ndarray_ptr.gep(ctx, |f| f.strides).store(ctx, strides_array.pointer);
Ok(ndarray_ptr)
}
/// Initialize an ndarray's `shape` and asserts on.
/// `shape`'s values and prohibit illegal inputs like negative dimensions.
pub fn init_ndarray_shape<'ctx, G: CodeGenerator + ?Sized>(
generator: &mut G,
ctx: &mut CodeGenContext<'ctx, '_>,
ndarray_ptr: Pointer<'ctx, StructModel<NpArray<'ctx>>>,
shape_writer: &ArrayWriter<'ctx, G, SizeTModel<'ctx>, SizeTModel<'ctx>>,
) -> Result<(), String> {
(shape_writer.write)(generator, ctx, &ndarray_ptr.shape_slice(ctx))?;
call_nac3_ndarray_util_assert_shape_no_negative(
generator,
ctx,
shape_writer.count,
ndarray_ptr.gep(ctx, |f| f.shape).load(ctx, "shape"),
);
Ok(())
}
/// Initialize an ndarray's `data` by allocating a buffer on the stack.
/// The allocated data buffer is considered to be *owned* by the ndarray.
///
/// `strides` of the ndarray will also be updated with `set_strides_by_shape`.
///
/// `shape` and `itemsize` of the ndarray ***must*** be initialized first.
pub fn init_ndarray_data_by_alloca<'ctx, G: CodeGenerator + ?Sized>(
generator: &mut G,
ctx: &mut CodeGenContext<'ctx, '_>,
ndarray_ptr: Pointer<'ctx, StructModel<NpArray<'ctx>>>,
) {
let ndarray_nbytes = call_nac3_ndarray_nbytes(generator, ctx, ndarray_ptr); // Needs `itemsize` initialized
let data_array = NIntModel(Byte).array_alloca(ctx, ndarray_nbytes, "data");
ndarray_ptr.gep(ctx, |f| f.data).store(ctx, data_array.pointer);
call_nac3_ndarray_set_strides_by_shape(generator, ctx, ndarray_ptr);
}

View File

@ -0,0 +1,117 @@
use crate::codegen::irrt::error_context::{check_error_context, setup_error_context};
use crate::codegen::irrt::slice::SliceIndex;
use crate::codegen::irrt::util::get_sized_dependent_function_name;
use crate::codegen::model::*;
use crate::codegen::{structs::ndarray::NpArray, CodeGenContext, CodeGenerator};
pub fn call_nac3_ndarray_size<'ctx, G: CodeGenerator + ?Sized>(
generator: &mut G,
ctx: &mut CodeGenContext<'ctx, '_>,
ndarray_ptr: Pointer<'ctx, StructModel<NpArray<'ctx>>>,
) -> SizeT<'ctx> {
let sizet = generator.get_sizet(ctx.ctx);
FunctionBuilder::begin(ctx, &get_sized_dependent_function_name(sizet, "__nac3_ndarray_size"))
.arg("ndarray", ndarray_ptr)
.returning("size", sizet)
}
pub fn call_nac3_ndarray_nbytes<'ctx, G: CodeGenerator + ?Sized>(
generator: &mut G,
ctx: &mut CodeGenContext<'ctx, '_>,
ndarray_ptr: Pointer<'ctx, StructModel<NpArray<'ctx>>>,
) -> SizeT<'ctx> {
let sizet = generator.get_sizet(ctx.ctx);
FunctionBuilder::begin(ctx, &get_sized_dependent_function_name(sizet, "__nac3_ndarray_nbytes"))
.arg("ndarray", ndarray_ptr)
.returning("nbytes", sizet)
}
pub fn call_nac3_ndarray_len<'ctx, G: CodeGenerator + ?Sized>(
generator: &mut G,
ctx: &mut CodeGenContext<'ctx, '_>,
ndarray_ptr: Pointer<'ctx, StructModel<NpArray<'ctx>>>,
) -> NInt<'ctx, SliceIndex> {
let sizet = generator.get_sizet(ctx.ctx);
let slice_index_model = NIntModel(SliceIndex::default());
let dst_len = slice_index_model.alloca(ctx, "dst_len");
let errctx = setup_error_context(ctx);
FunctionBuilder::begin(ctx, &get_sized_dependent_function_name(sizet, "__nac3_ndarray_len"))
.arg("errctx", errctx)
.arg("ndarray", ndarray_ptr)
.arg("dst_len", dst_len)
.returning_void();
check_error_context(generator, ctx, errctx);
dst_len.load(ctx, "len")
}
pub fn call_nac3_ndarray_util_assert_shape_no_negative<'ctx, G: CodeGenerator + ?Sized>(
generator: &mut G,
ctx: &mut CodeGenContext<'ctx, '_>,
ndims: SizeT<'ctx>,
shape_ptr: Pointer<'ctx, SizeTModel<'ctx>>,
) {
let sizet = generator.get_sizet(ctx.ctx);
let errctx = setup_error_context(ctx);
FunctionBuilder::begin(
ctx,
&get_sized_dependent_function_name(sizet, "__nac3_ndarray_util_assert_shape_no_negative"),
)
.arg("errctx", errctx)
.arg("ndims", ndims)
.arg("shape", shape_ptr)
.returning_void();
check_error_context(generator, ctx, errctx);
}
pub fn call_nac3_ndarray_set_strides_by_shape<'ctx, G: CodeGenerator + ?Sized>(
generator: &mut G,
ctx: &mut CodeGenContext<'ctx, '_>,
ndarray_ptr: Pointer<'ctx, StructModel<NpArray<'ctx>>>,
) {
let sizet = generator.get_sizet(ctx.ctx);
FunctionBuilder::begin(
ctx,
&get_sized_dependent_function_name(sizet, "__nac3_ndarray_set_strides_by_shape"),
)
.arg("ndarray", ndarray_ptr)
.returning_void();
}
pub fn call_nac3_ndarray_is_c_contiguous<'ctx, G: CodeGenerator + ?Sized>(
generator: &mut G,
ctx: &mut CodeGenContext<'ctx, '_>,
ndarray_ptr: Pointer<'ctx, StructModel<NpArray<'ctx>>>,
) -> NInt<'ctx, Bool> {
let sizet = generator.get_sizet(ctx.ctx);
FunctionBuilder::begin(
ctx,
&get_sized_dependent_function_name(sizet, "__nac3_ndarray_is_c_contiguous"),
)
.arg("ndarray", ndarray_ptr)
.returning("is_c_contiguous", NIntModel(Bool))
}
pub fn call_nac3_ndarray_copy_data<'ctx, G: CodeGenerator + ?Sized>(
generator: &mut G,
ctx: &mut CodeGenContext<'ctx, '_>,
src_ndarray: Pointer<'ctx, StructModel<NpArray<'ctx>>>,
dst_ndarray: Pointer<'ctx, StructModel<NpArray<'ctx>>>,
) -> NInt<'ctx, Bool> {
let sizet = generator.get_sizet(ctx.ctx);
FunctionBuilder::begin(
ctx,
&get_sized_dependent_function_name(sizet, "__nac3_ndarray_copy_data"),
)
.arg("src_ndarray", src_ndarray)
.arg("dst_ndarray", dst_ndarray)
.returning("is_c_contiguous", NIntModel(Bool))
}

View File

@ -0,0 +1,21 @@
use crate::codegen::{
irrt::util::get_sized_dependent_function_name, model::*, structs::ndarray::NpArray,
CodeGenContext, CodeGenerator,
};
pub fn call_nac3_ndarray_fill_generic<'ctx, G: CodeGenerator + ?Sized>(
generator: &mut G,
ctx: &mut CodeGenContext<'ctx, '_>,
ndarray_ptr: Pointer<'ctx, StructModel<NpArray<'ctx>>>,
fill_value_ptr: Pointer<'ctx, ByteModel>,
) {
let sizet = generator.get_sizet(ctx.ctx);
FunctionBuilder::begin(
ctx,
&get_sized_dependent_function_name(sizet, "__nac3_ndarray_fill_generic"),
)
.arg("ndarray", ndarray_ptr)
.arg("pvalue", fill_value_ptr)
.returning_void();
}

View File

@ -0,0 +1,169 @@
use crate::codegen::{
irrt::{
error_context::{check_error_context, setup_error_context},
slice::{RustUserSlice, SliceIndex, UserSlice},
util::get_sized_dependent_function_name,
},
model::*,
structs::ndarray::NpArray,
CodeGenContext, CodeGenerator,
};
#[derive(Debug, Clone, Copy)]
pub struct NDIndexFields {
pub type_: Field<ByteModel>, // Defined to be uint8_t in IRRT
pub data: Field<PointerModel<ByteModel>>,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct NDIndex;
impl<'ctx> StructKind<'ctx> for NDIndex {
type Fields = NDIndexFields;
fn struct_name(&self) -> &'static str {
"NDIndex"
}
fn build_fields(&self, builder: &mut FieldBuilder<'ctx>) -> Self::Fields {
Self::Fields { type_: builder.add_field_auto("type"), data: builder.add_field_auto("data") }
}
}
// An enum variant to store the content
// and type of an NDIndex in high level.
#[derive(Debug, Clone)]
pub enum RustNDIndex<'ctx> {
SingleElement(NInt<'ctx, SliceIndex>),
Slice(RustUserSlice<'ctx>),
}
impl<'ctx> RustNDIndex<'ctx> {
fn irrt_ndindex_id(&self) -> u64 {
// Defined in IRRT, must be in sync
match self {
RustNDIndex::SingleElement(_) => 0,
RustNDIndex::Slice(_) => 1,
}
}
fn write_to_ndindex(
&self,
ctx: &CodeGenContext<'ctx, '_>,
dst_ndindex_ptr: Pointer<'ctx, StructModel<NDIndex>>,
) {
let byte_model = ByteModel::default();
let slice_index_model = NIntModel(SliceIndex::default());
let user_slice_model = StructModel(UserSlice);
// Set `dst_ndindex_ptr->type`
dst_ndindex_ptr
.gep(ctx, |f| f.type_)
.store(ctx, byte_model.constant(ctx.ctx, self.irrt_ndindex_id()));
// Set `dst_ndindex_ptr->data`
let data = match self {
RustNDIndex::SingleElement(in_index) => {
let index_ptr = slice_index_model.alloca(ctx, "index");
index_ptr.store(ctx, *in_index);
index_ptr.cast_to(ctx, NIntModel(Byte), "")
}
RustNDIndex::Slice(in_rust_slice) => {
let user_slice_ptr = user_slice_model.alloca(ctx, "user_slice");
in_rust_slice.write_to_user_slice(ctx, user_slice_ptr);
user_slice_ptr.cast_to(ctx, NIntModel(Byte), "")
}
};
dst_ndindex_ptr.gep(ctx, |f| f.data).store(ctx, data);
}
// Allocate an array of `NDIndex`es onto the stack and return its stack pointer
pub fn alloca_ndindexes<G: CodeGenerator + ?Sized>(
generator: &mut G,
ctx: &CodeGenContext<'ctx, '_>,
ndindexes: &[RustNDIndex<'ctx>],
) -> ArraySlice<'ctx, SizeTModel<'ctx>, StructModel<NDIndex>> {
let sizet = generator.get_sizet(ctx.ctx);
let ndindex_model = StructModel(NDIndex);
let ndindex_array = ndindex_model.array_alloca(
ctx,
sizet.constant(ctx.ctx, ndindexes.len() as u64),
"ndindexs",
);
for (i, rust_ndindex) in ndindexes.iter().enumerate() {
let ndindex_ptr =
ndindex_array.ix_unchecked(ctx, sizet.constant(ctx.ctx, i as u64), "");
rust_ndindex.write_to_ndindex(ctx, ndindex_ptr);
}
ndindex_array
}
#[must_use]
pub fn deduce_ndims_after_slicing(slices: &[RustNDIndex], original_ndims: i32) -> i32 {
let mut final_ndims: i32 = original_ndims;
for slice in slices {
match slice {
RustNDIndex::SingleElement(_) => {
final_ndims -= 1;
}
RustNDIndex::Slice(_) => {}
}
}
final_ndims
}
}
pub fn call_nac3_ndarray_indexing_deduce_ndims_after_indexing<'ctx, G: CodeGenerator + ?Sized>(
generator: &mut G,
ctx: &mut CodeGenContext<'ctx, '_>,
ndims: Int<'ctx>,
num_ndindexs: SizeT<'ctx>,
ndindexs: Pointer<'ctx, StructModel<NDIndex>>,
) -> SizeT<'ctx> {
let sizet = generator.get_sizet(ctx.ctx);
let final_ndims = sizet.alloca(ctx, "result");
let errctx_ptr = setup_error_context(ctx);
FunctionBuilder::begin(
ctx,
&get_sized_dependent_function_name(
sizet,
"__nac3_ndarray_indexing_deduce_ndims_after_indexing",
),
)
.arg("errctx", errctx_ptr)
.arg("result", final_ndims)
.arg("ndims", ndims)
.arg("num_ndindexs", num_ndindexs)
.arg("ndindexs", ndindexs)
.returning_void();
check_error_context(generator, ctx, errctx_ptr);
final_ndims.load(ctx, "final_ndims")
}
pub fn call_nac3_ndarray_index<'ctx, G: CodeGenerator + ?Sized>(
generator: &mut G,
ctx: &mut CodeGenContext<'ctx, '_>,
num_indexes: SizeT<'ctx>,
indexes: Pointer<'ctx, StructModel<NDIndex>>,
src_ndarray: Pointer<'ctx, StructModel<NpArray<'ctx>>>,
dst_ndarray: Pointer<'ctx, StructModel<NpArray<'ctx>>>,
) {
let sizet = generator.get_sizet(ctx.ctx);
let errctx_ptr = setup_error_context(ctx);
FunctionBuilder::begin(ctx, &get_sized_dependent_function_name(sizet, "__nac3_ndarray_index"))
.arg("errctx", errctx_ptr)
.arg("num_indexes", num_indexes)
.arg("indexes", indexes)
.arg("src_ndarray", src_ndarray)
.arg("dst_ndarray", dst_ndarray)
.returning_void();
check_error_context(generator, ctx, errctx_ptr);
}

View File

@ -0,0 +1,6 @@
pub mod allocation;
pub mod basic;
pub mod fill;
pub mod indexing;
pub mod reshape;
pub mod transpose;

View File

@ -0,0 +1,30 @@
use crate::codegen::{
irrt::{
error_context::{check_error_context, setup_error_context},
util::get_sized_dependent_function_name,
},
model::*,
CodeGenContext, CodeGenerator,
};
pub fn call_nac3_ndarray_resolve_and_check_new_shape<'ctx, G: CodeGenerator + ?Sized>(
generator: &mut G,
ctx: &mut CodeGenContext<'ctx, '_>,
size: SizeT<'ctx>,
new_ndims: SizeT<'ctx>,
new_shape: Pointer<'ctx, SizeTModel<'ctx>>,
) {
let sizet = generator.get_sizet(ctx.ctx);
let perrctx = setup_error_context(ctx);
FunctionBuilder::begin(
ctx,
&get_sized_dependent_function_name(sizet, "__nac3_ndarray_resolve_and_check_new_shape"),
)
.arg("errctx", perrctx)
.arg("size", size)
.arg("new_ndims", new_ndims)
.arg("new_shape", new_shape)
.returning_void();
check_error_context(generator, ctx, perrctx);
}

View File

@ -0,0 +1,43 @@
use crate::codegen::{
irrt::{
error_context::{check_error_context, setup_error_context},
util::get_sized_dependent_function_name,
},
model::*,
structs::ndarray::NpArray,
CodeGenContext, CodeGenerator,
};
pub fn call_nac3_ndarray_transpose<'ctx, G: CodeGenerator + ?Sized>(
generator: &mut G,
ctx: &mut CodeGenContext<'ctx, '_>,
src_ndarray: Pointer<'ctx, StructModel<NpArray<'ctx>>>,
dst_ndarray: Pointer<'ctx, StructModel<NpArray<'ctx>>>,
axes_or_none: Option<ArraySlice<'ctx, SizeTModel<'ctx>, SizeTModel<'ctx>>>,
) -> Pointer<'ctx, StructModel<NpArray<'ctx>>> {
let sizet = generator.get_sizet(ctx.ctx);
let axes_model = PointerModel(sizet);
let (num_axes, axes) = match axes_or_none {
Some(axes) => (axes.num_elements, axes.pointer),
None => {
// Please refer to the comment in the IRRT implementation
(sizet.constant(ctx.ctx, 0), axes_model.nullptr(ctx.ctx))
}
};
let perrctx = setup_error_context(ctx);
FunctionBuilder::begin(
ctx,
&get_sized_dependent_function_name(sizet, "__nac3_ndarray_transpose"),
)
.arg("errctx", perrctx)
.arg("src_ndarray", src_ndarray)
.arg("dst_ndarray", dst_ndarray)
.arg("num_axes", num_axes)
.arg("axes", axes)
.returning_void();
check_error_context(generator, ctx, perrctx);
dst_ndarray
}

View File

@ -0,0 +1,84 @@
use crate::codegen::{model::*, CodeGenContext};
// nac3core's slicing index/length values are always int32_t
pub type SliceIndex = Int32;
#[derive(Debug, Clone)]
pub struct UserSliceFields {
pub start_defined: Field<BoolModel>,
pub start: Field<NIntModel<SliceIndex>>,
pub stop_defined: Field<BoolModel>,
pub stop: Field<NIntModel<SliceIndex>>,
pub step_defined: Field<BoolModel>,
pub step: Field<NIntModel<SliceIndex>>,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct UserSlice;
impl<'ctx> StructKind<'ctx> for UserSlice {
type Fields = UserSliceFields;
fn struct_name(&self) -> &'static str {
"UserSlice"
}
fn build_fields(&self, builder: &mut FieldBuilder<'ctx>) -> Self::Fields {
Self::Fields {
start_defined: builder.add_field_auto("start_defined"),
start: builder.add_field_auto("start"),
stop_defined: builder.add_field_auto("stop_defined"),
stop: builder.add_field_auto("stop"),
step_defined: builder.add_field_auto("step_defined"),
step: builder.add_field_auto("step"),
}
}
}
#[derive(Debug, Clone)]
pub struct RustUserSlice<'ctx> {
pub start: Option<NInt<'ctx, SliceIndex>>,
pub stop: Option<NInt<'ctx, SliceIndex>>,
pub step: Option<NInt<'ctx, SliceIndex>>,
}
impl<'ctx> RustUserSlice<'ctx> {
// Set the values of an LLVM UserSlice
// in the format of Python's `slice()`
pub fn write_to_user_slice(
&self,
ctx: &CodeGenContext<'ctx, '_>,
dst_slice_ptr: Pointer<'ctx, StructModel<UserSlice>>,
) {
// TODO: make this neater, with a helper lambda?
let bool_model = BoolModel::default();
let false_ = bool_model.constant(ctx.ctx, 0);
let true_ = bool_model.constant(ctx.ctx, 1);
match self.start {
Some(start) => {
dst_slice_ptr.gep(ctx, |f| f.start_defined).store(ctx, true_);
dst_slice_ptr.gep(ctx, |f| f.start).store(ctx, start);
}
None => dst_slice_ptr.gep(ctx, |f| f.start_defined).store(ctx, false_),
}
match self.stop {
Some(stop) => {
dst_slice_ptr.gep(ctx, |f| f.stop_defined).store(ctx, true_);
dst_slice_ptr.gep(ctx, |f| f.stop).store(ctx, stop);
}
None => dst_slice_ptr.gep(ctx, |f| f.stop_defined).store(ctx, false_),
}
match self.step {
Some(step) => {
dst_slice_ptr.gep(ctx, |f| f.step_defined).store(ctx, true_);
dst_slice_ptr.gep(ctx, |f| f.step).store(ctx, step);
}
None => dst_slice_ptr.gep(ctx, |f| f.step_defined).store(ctx, false_),
}
}
}

View File

@ -0,0 +1,26 @@
#[cfg(test)]
mod tests {
use std::{path::Path, process::Command};
#[test]
fn run_irrt_test() {
assert!(
cfg!(feature = "test"),
"Please do `cargo test -F test` to compile `irrt_test.out` and run test"
);
let irrt_test_out_path = Path::new(concat!(env!("OUT_DIR"), "/irrt_test.out"));
let output = Command::new(irrt_test_out_path.to_str().unwrap()).output().unwrap();
if !output.status.success() {
eprintln!("irrt_test failed with status {}:", output.status);
eprintln!("====== stdout ======");
eprintln!("{}", String::from_utf8(output.stdout).unwrap());
eprintln!("====== stderr ======");
eprintln!("{}", String::from_utf8(output.stderr).unwrap());
eprintln!("====================");
panic!("irrt_test failed");
}
}
}

View File

@ -0,0 +1,16 @@
use crate::codegen::model::*;
#[must_use]
pub fn get_sized_dependent_function_name(sizet: SizeTModel<'_>, fn_name: &str) -> String {
// When its 32-bits, the function name is "{fn_name}"
// When its 64-bits, the function name is "{fn_name}64"
let mut fn_name = fn_name.to_owned();
match sizet.0.get_bit_width() {
32 => {}
64 => fn_name.push_str("64"),
bit_width => {
panic!("Unsupported int type bit width {bit_width}, must be either 32-bits or 64-bits")
}
}
fn_name
}

View File

@ -1,7 +1,7 @@
use crate::{
codegen::classes::{ListType, NDArrayType, ProxyType, RangeType},
codegen::classes::{ListType, ProxyType, RangeType},
symbol_resolver::{StaticValue, SymbolResolver},
toplevel::{helper::PrimDef, numpy::unpack_ndarray_var_tys, TopLevelContext, TopLevelDef},
toplevel::{helper::PrimDef, TopLevelContext, TopLevelDef},
typecheck::{
type_inferencer::{CodeLocation, PrimitiveStore},
typedef::{CallId, FuncArg, Type, TypeEnum, Unifier},
@ -24,6 +24,7 @@ use inkwell::{
AddressSpace, IntPredicate, OptimizationLevel,
};
use itertools::Itertools;
use model::*;
use nac3parser::ast::{Location, Stmt, StrRef};
use parking_lot::{Condvar, Mutex};
use std::collections::{HashMap, HashSet};
@ -32,6 +33,7 @@ use std::sync::{
Arc,
};
use std::thread;
use structs::{cslice::CSlice, exception::Exception, ndarray::NpArray};
pub mod builtin_fns;
pub mod classes;
@ -41,11 +43,15 @@ pub mod extern_fns;
mod generator;
pub mod irrt;
pub mod llvm_intrinsics;
pub mod model;
pub mod numpy;
pub mod numpy_new;
pub mod stmt;
pub mod structs;
#[cfg(test)]
mod test;
pub mod util;
use concrete_type::{ConcreteType, ConcreteTypeEnum, ConcreteTypeStore};
pub use generator::{CodeGenerator, DefaultCodeGenerator};
@ -158,11 +164,11 @@ pub struct CodeGenContext<'ctx, 'a> {
pub registry: &'a WorkerRegistry,
/// Cache for constant strings.
pub const_strings: HashMap<String, BasicValueEnum<'ctx>>,
pub const_strings: HashMap<String, Struct<'ctx, CSlice<'ctx>>>,
/// [`BasicBlock`] containing all `alloca` statements for the current function.
pub init_bb: BasicBlock<'ctx>,
pub exception_val: Option<PointerValue<'ctx>>,
pub exception_val: Option<Pointer<'ctx, StructModel<Exception<'ctx>>>>,
/// The header and exit basic blocks of a loop in this context. See
/// <https://llvm.org/docs/LoopTerminology.html> for explanation of these terminology.
@ -471,12 +477,9 @@ fn get_llvm_type<'ctx, G: CodeGenerator + ?Sized>(
}
TObj { obj_id, .. } if *obj_id == PrimDef::NDArray.id() => {
let (dtype, _) = unpack_ndarray_var_tys(unifier, ty);
let element_type = get_llvm_type(
ctx, module, generator, unifier, top_level, type_cache, dtype,
);
NDArrayType::new(generator, ctx, element_type).as_base_type().into()
let sizet = generator.get_sizet(ctx);
let pndarray_model = PointerModel(StructModel(NpArray { sizet }));
pndarray_model.get_type(ctx).into()
}
_ => unreachable!(
@ -646,47 +649,24 @@ pub fn gen_func_impl<
..primitives
};
let mut type_cache: HashMap<_, _> = [
let sizet = generator.get_sizet(context);
let cslice_type = StructModel(CSlice { sizet });
let pexception_type = PointerModel(StructModel(Exception { sizet }));
let mut type_cache: HashMap<_, BasicTypeEnum<'ctx>> = [
(primitives.int32, context.i32_type().into()),
(primitives.int64, context.i64_type().into()),
(primitives.uint32, context.i32_type().into()),
(primitives.uint64, context.i64_type().into()),
(primitives.float, context.f64_type().into()),
(primitives.bool, context.i8_type().into()),
(primitives.str, {
let name = "str";
match module.get_struct_type(name) {
None => {
let str_type = context.opaque_struct_type("str");
let fields = [
context.i8_type().ptr_type(AddressSpace::default()).into(),
generator.get_size_type(context).into(),
];
str_type.set_body(&fields, false);
str_type.into()
}
Some(t) => t.as_basic_type_enum(),
}
}),
(primitives.str, cslice_type.get_type(context).into()),
(primitives.range, RangeType::new(context).as_base_type().into()),
(primitives.exception, {
let name = "Exception";
if let Some(t) = module.get_struct_type(name) {
t.ptr_type(AddressSpace::default()).as_basic_type_enum()
} else {
let exception = context.opaque_struct_type("Exception");
let int32 = context.i32_type().into();
let int64 = context.i64_type().into();
let str_ty = module.get_struct_type("str").unwrap().as_basic_type_enum();
let fields = [int32, str_ty, int32, int32, str_ty, str_ty, int64, int64, int64];
exception.set_body(&fields, false);
exception.ptr_type(AddressSpace::default()).as_basic_type_enum()
}
}),
(primitives.exception, pexception_type.get_type(context).into()),
]
.iter()
.copied()
.into_iter()
.collect();
// NOTE: special handling of option cannot use this type cache since it contains type var,
// handled inside get_llvm_type instead

View File

@ -0,0 +1,204 @@
use core::fmt;
use std::marker::PhantomData;
use inkwell::{
context::Context,
types::{BasicType, BasicTypeEnum, IntType},
values::{BasicValue, IntValue, PointerValue},
};
use crate::codegen::{CodeGenContext, CodeGenerator};
use super::{ArraySlice, Pointer, PointerModel};
/*
TODO: UPDATE when the Model finally stablizes
Explanation on the abstraction:
In LLVM, there are TYPES and VALUES.
Inkwell gives us TYPES [`BasicTypeEnum<'ctx>`] and VALUES [`BasicValueEnum<'ctx>`],
but by themselves, they lack a lot of Rust compile-time known info.
e.g., You did `let ptr = builder.build_alloca(my_llvm_ndarray_struct_ty)`,
but `ptr` is just a `PointerValue<'ctx>`, almost everything about the
underlying `my_llvm_ndarray_struct_ty` is gone.
The `Model` abstraction is a wrapper around inkwell TYPES and VALUES but with
a richer interface.
`Model<'ctx>` is a wrapper around for an inkwell TYPE:
- `NIntModel<Byte>` is a i8.
- `NIntModel<Int32>` is a i32.
- `NIntModel<Int64>` is a i64.
- `IntModel` is a carrier for an inkwell `IntType<'ctx>`,
used when the type is dynamic/cannot be specified in Rust compile-time.
- `PointerModel<'ctx, E>` is a wrapper for `PointerType<'ctx>`,
where `E` is another `Model<'ctx>` that describes the element type of the pointer.
- `StructModel<'ctx, NDArray>` is a wrapper for `StructType<'ctx>`,
with additional information encoded within `NDArray`. (See `IsStruct<'ctx>`)
`Model<'ctx>::Value`/`ModelValue<'ctx>` is a wrapper around for an inkwell VALUE:
- `NInt<'ctx, T>` is a value of `NIntModel<'ctx, T>`,
where `T` could be `Byte`, `Int32`, or `Int64`.
- `Pointer<'ctx, E>` is a value of `PointerModel<'ctx, E>`.
Other interesting utilities:
- Given a `Model<'ctx>`, say, `let ndarray_model = StructModel<'ctx, NDArray>`,
you are do `ndarray_model.alloca(ctx, "my_ndarray")` to get a `Pointer<'ctx, Struct<'ctx, NDArray>>`,
notice that all LLVM type information are preserved.
- For a `let my_ndarray = Pointer<'ctx, StructModel<NDArray>>`, you can access a field by doing
`my_ndarray.gep(ctx, |f| f.itemsize).load() // or .store()`, and you can chain them
together for nested structures.
A brief summary on the `Model<'ctx>` and `ModelValue<'ctx>` traits:
- Model<'ctx>
// The associated ModelValue of this Model
- type Value: ModelValue<'ctx>
// Get the LLVM type of this Model
- fn get_llvm_type(&self)
// Check if the input type is equal to the LLVM type of this Model
// NOTE: this function is provideed through `CanCheckLLVMType<'ctx>`
- fn check_llvm_type(&self, ty) -> Result<(), String>
// Check if the input value's type is equal to the LLVM type of this Model.
//
// If so, wrap it with `Self::Value`.
- fn review_value<V: BasicType<'ctx>>(&self, val: V) -> Result<Self::Value, String>
- ModelValue<'ctx>
// get the LLVM value of this ModelValue
- fn get_llvm_value(&self) -> BasicValueEnum<'ctx>
*/
#[derive(Debug, Clone)]
pub struct ModelError(pub String);
// NOTE: Should have been within [`Model<'ctx>`],
// but rust object safety requirements made it necessary to
// split the trait.
pub trait CanCheckLLVMType<'ctx> {
/// See [`Model::check_llvm_type`]
fn check_llvm_type_impl(
&self,
ctx: &'ctx Context,
ty: BasicTypeEnum<'ctx>,
) -> Result<(), ModelError>;
}
pub trait Model<'ctx>: fmt::Debug + Clone + Copy + CanCheckLLVMType<'ctx> + Sized + Eq {
/// The corresponding LLVM [`BasicValue<'ctx>`] of this Model.
type Value: BasicValue<'ctx>;
/// The corresponding LLVM [`BasicType<'ctx>`] of this Model.
type Type: BasicType<'ctx>;
/// Get the LLVM type of this [`Model<'ctx>`]
fn get_type(&self, ctx: &'ctx Context) -> Self::Type;
/// Check if the input type is equal to the LLVM type of this Model.
///
/// If it doesn't match, an [`Err`] with a human-readable message is
/// thrown explaining *how* it was different. Meant for debugging.
fn check_type<T: BasicType<'ctx>>(&self, ctx: &'ctx Context, ty: T) -> Result<(), ModelError> {
self.check_llvm_type_impl(ctx, ty.as_basic_type_enum())
}
/// Check if an LLVM value's type is equal to the LLVM type of this [`Model`].
/// If so, wrap it with [`Instance`].
fn review_value<V: BasicValue<'ctx>>(
&self,
ctx: &'ctx Context,
value: V,
) -> Result<Instance<'ctx, Self>, ModelError>;
/// Directly create an [`Instance`] of this [`Model`].
///
/// It is assumed that the LLVM type of `value` has been checked.
///
/// It is recommended that you use [`Model::review_value`] instead in order to
/// catch bugs.
fn believe_value(&self, value: Self::Value) -> Instance<'ctx, Self> {
Instance { model: *self, value, _phantom: PhantomData }
}
/// Build an instruction to allocate a value with the LLVM type of this [`Model<'ctx>`].
fn alloca(&self, ctx: &CodeGenContext<'ctx, '_>, name: &str) -> Pointer<'ctx, Self> {
let ptr_model = PointerModel(*self);
let ptr = ctx.builder.build_alloca(self.get_type(ctx.ctx), name).unwrap();
ptr_model.believe_value(ptr)
}
/// Build an instruction to allocate an array of the LLVM type of this [`Model<'ctx>`].
fn array_alloca<N>(
&self,
ctx: &CodeGenContext<'ctx, '_>,
num_elements: Instance<'ctx, N>,
name: &str,
) -> ArraySlice<'ctx, N, Self>
where
N: Model<'ctx, Value = IntValue<'ctx>, Type = IntType<'ctx>>,
{
let ptr_model = PointerModel(*self);
let ptr = ctx
.builder
.build_array_alloca(
self.get_type(ctx.ctx).as_basic_type_enum(),
num_elements.value,
name,
)
.unwrap();
let pointer = ptr_model.believe_value(ptr);
ArraySlice { pointer, num_elements }
}
/// Do [`CodeGenerator::gen_var_alloc`] with the LLVM type of this [`Model<'ctx>`].
fn var_alloc<G: CodeGenerator + ?Sized>(
&self,
generator: &mut G,
ctx: &mut CodeGenContext<'ctx, '_>,
name: Option<&str>,
) -> Result<Pointer<'ctx, Self>, String> {
let ptr_model = PointerModel(*self);
let ptr =
generator.gen_var_alloc(ctx, self.get_type(ctx.ctx).as_basic_type_enum(), name)?;
Ok(ptr_model.believe_value(ptr))
}
/// Do [`CodeGenerator::gen_array_var_alloc`] with the LLVM type of this [`Model<'ctx>`].
fn array_var_alloc<G: CodeGenerator + ?Sized, N>(
&self,
generator: &mut G,
ctx: &mut CodeGenContext<'ctx, '_>,
num_elements: Instance<'ctx, N>,
name: Option<&'ctx str>,
) -> Result<ArraySlice<'ctx, N, Self>, String>
where
N: Model<'ctx, Value = IntValue<'ctx>, Type = IntType<'ctx>>,
{
let ptr_model = PointerModel(*self);
// TODO: Remove ProxyType ArraySlice
let ptr = ptr_model.believe_value(PointerValue::from(generator.gen_array_var_alloc(
ctx,
self.get_type(ctx.ctx).as_basic_type_enum(),
num_elements.value,
name,
)?));
Ok(ArraySlice { num_elements, pointer: ptr })
}
}
/// An LLVM value of a type of a [`Model<'ctx>`].
///
/// It is guaranteed that [`Instance::value`]'s LLVM type
/// has been *checked* to match [`Instance::model`].
#[derive(Debug, Clone, Copy)]
pub struct Instance<'ctx, M: Model<'ctx>> {
pub model: M,
pub value: M::Value,
_phantom: PhantomData<&'ctx ()>,
}

View File

@ -0,0 +1,161 @@
use core::fmt;
use inkwell::{
context::Context,
types::{BasicTypeEnum, IntType},
values::{BasicValue, IntValue},
};
use super::{
core::*,
int_util::{check_int_llvm_type, int_constant, review_int_llvm_value},
Int, IntModel,
};
/// A marker trait to mark a singleton struct that describes a particular fixed integer type.
/// See [`Bool`], [`Byte`], [`Int32`], etc.
///
/// The [`Default`] trait is to enable auto-instantiations.
pub trait NIntKind: fmt::Debug + Clone + Copy + Default + PartialEq + Eq {
/// Get the [`IntType<'ctx>`] of this [`NIntKind`].
fn get_int_type(ctx: &Context) -> IntType<'_>;
/// Get the [`IntType<'ctx>`] of this [`NIntKind`].
///
/// Compared to using [`NIntKind::get_int_type`], this
/// function does not require [`Context`].
fn get_bit_width() -> u32;
}
/// A [`Model`] representing an [`IntType<'ctx>`] of a specified bit width.
///
/// Also see [`IntModel`], which is less constrained than [`NIntModel`],
/// but enables one to handle dynamic [`IntType<'ctx>`] at runtime.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct NIntModel<T: NIntKind>(pub T);
pub type NInt<'ctx, T> = Instance<'ctx, NIntModel<T>>;
impl<'ctx, T: NIntKind> CanCheckLLVMType<'ctx> for NIntModel<T> {
fn check_llvm_type_impl(
&self,
ctx: &'ctx Context,
ty: BasicTypeEnum<'ctx>,
) -> Result<(), ModelError> {
check_int_llvm_type(ty, T::get_int_type(ctx))
}
}
impl<'ctx, T: NIntKind> Model<'ctx> for NIntModel<T> {
type Type = IntType<'ctx>;
type Value = IntValue<'ctx>;
fn get_type(&self, ctx: &'ctx Context) -> Self::Type {
T::get_int_type(ctx)
}
fn review_value<V: BasicValue<'ctx>>(
&self,
ctx: &'ctx Context,
value: V,
) -> Result<NInt<'ctx, T>, ModelError> {
let value = review_int_llvm_value(value.as_basic_value_enum(), T::get_int_type(ctx))?;
Ok(self.believe_value(value))
}
}
impl<T: NIntKind> NIntModel<T> {
/// "Demote" this [`NIntModel<T>`] to an [`IntModel`].
///
/// Information about the [`NIntKind`] will be lost.
pub fn to_int_model(self, ctx: &Context) -> IntModel<'_> {
IntModel(T::get_int_type(ctx))
}
/// Create an unsigned constant of this [`NIntModel`].
pub fn constant<'ctx>(&self, ctx: &'ctx Context, value: u64) -> NInt<'ctx, T> {
int_constant(ctx, *self, value)
}
}
impl<'ctx, T: NIntKind> NInt<'ctx, T> {
/// "Demote" this [`NInt<T>`] to an [`Int`].
///
/// Information about the [`NIntKind`] will be lost.
pub fn to_int(self, ctx: &'ctx Context) -> Int<'ctx> {
let int_model = self.model.to_int_model(ctx);
int_model.believe_value(self.value)
}
}
// Some pre-defined fixed integer types
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Bool;
pub type BoolModel = NIntModel<Bool>;
impl NIntKind for Bool {
fn get_int_type(ctx: &Context) -> IntType<'_> {
ctx.bool_type()
}
fn get_bit_width() -> u32 {
1
}
}
// Extra utilities for [`Bool`]
impl NIntModel<Bool> {
/// Create a constant `false`
#[must_use]
pub fn const_false<'ctx>(&self, ctx: &'ctx Context) -> NInt<'ctx, Bool> {
self.constant(ctx, 0)
}
/// Create a constant `true`
#[must_use]
pub fn const_true<'ctx>(&self, ctx: &'ctx Context) -> NInt<'ctx, Bool> {
self.constant(ctx, 1)
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Byte;
pub type ByteModel = NIntModel<Byte>;
impl NIntKind for Byte {
fn get_int_type(ctx: &Context) -> IntType<'_> {
ctx.i8_type()
}
fn get_bit_width() -> u32 {
8
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Int32;
pub type Int32Model = NIntModel<Int32>;
impl NIntKind for Int32 {
fn get_int_type(ctx: &Context) -> IntType<'_> {
ctx.i32_type()
}
fn get_bit_width() -> u32 {
32
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Int64;
pub type Int64Model = NIntModel<Int64>;
impl NIntKind for Int64 {
fn get_int_type(ctx: &Context) -> IntType<'_> {
ctx.i64_type()
}
fn get_bit_width() -> u32 {
64
}
}

View File

@ -0,0 +1,66 @@
use inkwell::{
types::{BasicMetadataTypeEnum, BasicType},
values::{AnyValue, BasicMetadataValueEnum, BasicValue, BasicValueEnum},
};
use crate::codegen::{model::*, CodeGenContext};
// TODO: Variadic argument?
pub struct FunctionBuilder<'ctx, 'a> {
ctx: &'a CodeGenContext<'ctx, 'a>,
fn_name: &'a str,
arguments: Vec<(BasicMetadataTypeEnum<'ctx>, BasicMetadataValueEnum<'ctx>)>,
}
impl<'ctx, 'a> FunctionBuilder<'ctx, 'a> {
pub fn begin(ctx: &'a CodeGenContext<'ctx, 'a>, fn_name: &'a str) -> Self {
FunctionBuilder { ctx, fn_name, arguments: Vec::new() }
}
// NOTE: `_name` is for self-documentation
#[must_use]
#[allow(clippy::needless_pass_by_value)]
pub fn arg<M: Model<'ctx>>(mut self, _name: &'static str, arg: Instance<'ctx, M>) -> Self {
self.arguments.push((
arg.model.get_type(self.ctx.ctx).as_basic_type_enum().into(),
arg.value.as_basic_value_enum().into(),
));
self
}
pub fn returning<M: Model<'ctx>>(
self,
name: &'static str,
return_model: M,
) -> Instance<'ctx, M> {
let (param_tys, param_vals): (Vec<_>, Vec<_>) = self.arguments.into_iter().unzip();
// Get the LLVM function, create (by declaring) the function if it doesn't exist in `ctx.module`.
let function = self.ctx.module.get_function(self.fn_name).unwrap_or_else(|| {
let fn_type = return_model.get_type(self.ctx.ctx).fn_type(&param_tys, false);
self.ctx.module.add_function(self.fn_name, fn_type, None)
});
// Build call
let ret = self.ctx.builder.build_call(function, &param_vals, name).unwrap();
// Check the return value/type
let Ok(ret) = BasicValueEnum::try_from(ret.as_any_value_enum()) else {
panic!("Return type is not a BasicValue");
};
return_model.review_value(self.ctx.ctx, ret).unwrap()
}
// TODO: Code duplication, but otherwise returning<S: Optic<'ctx>> cannot resolve S if return_optic = None
pub fn returning_void(self) {
let (param_tys, param_vals): (Vec<_>, Vec<_>) = self.arguments.into_iter().unzip();
let function = self.ctx.module.get_function(self.fn_name).unwrap_or_else(|| {
let return_type = self.ctx.ctx.void_type();
let fn_type = return_type.fn_type(&param_tys, false);
self.ctx.module.add_function(self.fn_name, fn_type, None)
});
self.ctx.builder.build_call(function, &param_vals, "").unwrap();
}
}

View File

@ -0,0 +1,107 @@
use inkwell::{
context::Context,
types::{BasicTypeEnum, IntType},
values::{BasicValue, IntValue},
};
use super::{
core::*,
int_util::{check_int_llvm_type, int_constant, review_int_llvm_value},
};
/// A model representing an [`IntType<'ctx>`].
///
/// Also see [`NIntModel`][`super::NIntModel`], which is more constrained than [`IntModel`]
/// but provides more type-safe mechanisms and even auto-derivation of [`BasicTypeEnum<'ctx>`]
/// for creating LLVM structures.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct IntModel<'ctx>(pub IntType<'ctx>);
pub type Int<'ctx> = Instance<'ctx, IntModel<'ctx>>;
impl<'ctx> CanCheckLLVMType<'ctx> for IntModel<'ctx> {
fn check_llvm_type_impl(
&self,
_ctx: &'ctx Context,
ty: BasicTypeEnum<'ctx>,
) -> Result<(), ModelError> {
check_int_llvm_type(ty, self.0)
}
}
impl<'ctx> Model<'ctx> for IntModel<'ctx> {
type Value = IntValue<'ctx>;
type Type = IntType<'ctx>;
fn get_type(&self, _ctx: &'ctx Context) -> Self::Type {
self.0
}
fn review_value<V: BasicValue<'ctx>>(
&self,
_ctx: &'ctx Context,
value: V,
) -> Result<Int<'ctx>, ModelError> {
let value = review_int_llvm_value(value.as_basic_value_enum(), self.0)?;
Ok(self.believe_value(value))
}
}
impl<'ctx> IntModel<'ctx> {
/// Create a constant value that inhabits this [`IntModel<'ctx>`].
#[must_use]
pub fn constant(&self, ctx: &'ctx Context, value: u64) -> Int<'ctx> {
int_constant(ctx, *self, value)
}
}
impl<'ctx> From<IntValue<'ctx>> for Int<'ctx> {
fn from(value: IntValue<'ctx>) -> Self {
let model = IntModel(value.get_type());
model.believe_value(value)
}
}
/// A model representing an [`IntType<'ctx>`] that happens to be defined as `size_t`.
///
/// This is specifically created to guide developers to write `size_t`-dependent code.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SizeTModel<'ctx>(pub IntType<'ctx>);
pub type SizeT<'ctx> = Instance<'ctx, SizeTModel<'ctx>>;
impl<'ctx> CanCheckLLVMType<'ctx> for SizeTModel<'ctx> {
fn check_llvm_type_impl(
&self,
_ctx: &'ctx Context,
ty: BasicTypeEnum<'ctx>,
) -> Result<(), ModelError> {
check_int_llvm_type(ty, self.0)
}
}
impl<'ctx> Model<'ctx> for SizeTModel<'ctx> {
type Value = IntValue<'ctx>;
type Type = IntType<'ctx>;
fn get_type(&self, _ctx: &'ctx Context) -> Self::Type {
self.0
}
fn review_value<V: BasicValue<'ctx>>(
&self,
_ctx: &'ctx Context,
value: V,
) -> Result<SizeT<'ctx>, ModelError> {
let value = review_int_llvm_value(value.as_basic_value_enum(), self.0)?;
Ok(self.believe_value(value))
}
}
impl<'ctx> SizeTModel<'ctx> {
/// Create a constant value that inhabits this [`SizeTModel<'ctx>`].
#[must_use]
pub fn constant(&self, ctx: &'ctx Context, value: u64) -> SizeT<'ctx> {
int_constant(ctx, *self, value)
}
}

View File

@ -0,0 +1,87 @@
use inkwell::{
context::Context,
types::{BasicType, BasicTypeEnum, IntType},
values::{BasicValueEnum, IntValue},
};
use crate::codegen::CodeGenContext;
use super::{Instance, Model, ModelError};
/// Helper function to check if `scrutinee` is the same as `expected_int_type`
pub fn check_int_llvm_type<'ctx>(
ty: BasicTypeEnum<'ctx>,
expected_int_type: IntType<'ctx>,
) -> Result<(), ModelError> {
// Check if llvm_type is int type
let BasicTypeEnum::IntType(ty) = ty else {
return Err(ModelError(format!("Expecting an int type but got {ty:?}")));
};
// Check bit width
if ty.get_bit_width() != expected_int_type.get_bit_width() {
return Err(ModelError(format!(
"Expecting an int type of {}-bit(s) but got int type {}-bit(s)",
expected_int_type.get_bit_width(),
ty.get_bit_width()
)));
}
Ok(())
}
/// Helper function to cast `scrutinee` is into an [`IntValue<'ctx>`].
/// The LLVM type of `scrutinee` will be checked with [`check_int_llvm_type`].
pub fn review_int_llvm_value<'ctx>(
value: BasicValueEnum<'ctx>,
expected_int_type: IntType<'ctx>,
) -> Result<IntValue<'ctx>, ModelError> {
// Check if value is of int type, error if that is anything else
check_int_llvm_type(value.get_type().as_basic_type_enum(), expected_int_type)?;
// Ok, it is must be an int
Ok(value.into_int_value())
}
pub fn int_constant<'ctx, M>(ctx: &'ctx Context, model: M, value: u64) -> Instance<'ctx, M>
where
M: Model<'ctx, Value = IntValue<'ctx>, Type = IntType<'ctx>>,
{
let value = model.get_type(ctx).const_int(value, false);
model.believe_value(value)
}
impl<'ctx, M> Instance<'ctx, M>
where
M: Model<'ctx, Value = IntValue<'ctx>, Type = IntType<'ctx>>,
{
pub fn s_extend_or_bit_cast<N>(
&self,
ctx: &CodeGenContext<'ctx, '_>,
to_model: N,
name: &str,
) -> Instance<'ctx, N>
where
N: Model<'ctx, Value = IntValue<'ctx>, Type = IntType<'ctx>>,
{
let value = ctx
.builder
.build_int_s_extend_or_bit_cast(self.value, to_model.get_type(ctx.ctx), name)
.unwrap();
to_model.believe_value(value)
}
pub fn truncate<N>(
&self,
ctx: &CodeGenContext<'ctx, '_>,
to_model: N,
name: &str,
) -> Instance<'ctx, N>
where
N: Model<'ctx, Value = IntValue<'ctx>, Type = IntType<'ctx>>,
{
let value =
ctx.builder.build_int_truncate(self.value, to_model.get_type(ctx.ctx), name).unwrap();
to_model.believe_value(value)
}
}

View File

@ -0,0 +1,18 @@
pub mod core;
pub mod fixed_int;
pub mod function_builder;
pub mod int;
mod int_util;
pub mod opaque;
pub mod pointer;
pub mod slice;
pub mod structure;
pub use core::*;
pub use fixed_int::*;
pub use function_builder::*;
pub use int::*;
pub use opaque::*;
pub use pointer::*;
pub use slice::*;
pub use structure::*;

View File

@ -0,0 +1,57 @@
use inkwell::{
context::Context,
types::BasicTypeEnum,
values::{BasicValue, BasicValueEnum},
};
use super::*;
/// A [`Model`] that holds an arbitrary [`BasicTypeEnum`].
///
/// Use this and [`Opaque`] when you are dealing with a [`BasicTypeEnum<'ctx>`]
/// at runtime and there is no way to abstract your implementation
/// with [`Model`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OpaqueModel<'ctx>(pub BasicTypeEnum<'ctx>);
impl<'ctx> CanCheckLLVMType<'ctx> for OpaqueModel<'ctx> {
fn check_llvm_type_impl(
&self,
_ctx: &'ctx Context,
ty: BasicTypeEnum<'ctx>,
) -> Result<(), ModelError> {
if ty == self.0 {
Ok(())
} else {
Err(ModelError(format!("Expecting {}, but got {}", self.0, ty)))
}
}
}
impl<'ctx> Model<'ctx> for OpaqueModel<'ctx> {
type Value = BasicValueEnum<'ctx>;
type Type = BasicTypeEnum<'ctx>;
fn get_type(&self, _ctx: &'ctx Context) -> BasicTypeEnum<'ctx> {
self.0
}
fn review_value<V: BasicValue<'ctx>>(
&self,
ctx: &'ctx Context,
value: V,
) -> Result<Opaque<'ctx>, ModelError> {
let value = value.as_basic_value_enum();
self.check_type(ctx, value.get_type())?;
Ok(self.believe_value(value))
}
}
pub type Opaque<'ctx> = Instance<'ctx, OpaqueModel<'ctx>>;
impl<'ctx> From<BasicValueEnum<'ctx>> for Opaque<'ctx> {
fn from(value: BasicValueEnum<'ctx>) -> Self {
let model = OpaqueModel(value.get_type());
model.believe_value(value)
}
}

View File

@ -0,0 +1,126 @@
use inkwell::{
context::Context,
types::{BasicType, BasicTypeEnum, PointerType},
values::{BasicValue, PointerValue},
AddressSpace,
};
use crate::codegen::{model::*, CodeGenContext};
use super::{core::*, OpaqueModel};
/// A [`Model<'ctx>`] representing an LLVM [`PointerType<'ctx>`]
/// with *full* information on the element u
///
/// [`self.0`] contains [`Model<'ctx>`] that represents the
/// LLVM type of element of the [`PointerType<'ctx>`] is pointing at
/// (like `PointerType<'ctx>::get_element_type()`, but abstracted as a [`Model<'ctx>`]).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct PointerModel<E>(pub E);
pub type Pointer<'ctx, E> = Instance<'ctx, PointerModel<E>>;
impl<'ctx, E: Model<'ctx>> CanCheckLLVMType<'ctx> for PointerModel<E> {
fn check_llvm_type_impl(
&self,
ctx: &'ctx Context,
ty: BasicTypeEnum<'ctx>,
) -> Result<(), ModelError> {
// Check if scrutinee is even a PointerValue
let BasicTypeEnum::PointerType(ty) = ty else {
return Err(ModelError(format!("Expecting a pointer value, but got {ty:?}")));
};
// Check the type of what the pointer is pointing at
// TODO: This will be deprecated by inkwell > llvm14 because `get_element_type()` will be gone
let Ok(element_ty) = BasicTypeEnum::try_from(ty.get_element_type()) else {
return Err(ModelError(format!(
"Expecting pointer to point to an inkwell BasicValue, but got {ty:?}"
)));
};
self.0.check_type(ctx, element_ty) // TODO: Include backtrace?
}
}
impl<'ctx, E: Model<'ctx>> Model<'ctx> for PointerModel<E> {
type Value = PointerValue<'ctx>;
type Type = PointerType<'ctx>;
fn get_type(&self, ctx: &'ctx Context) -> Self::Type {
self.0.get_type(ctx).ptr_type(AddressSpace::default())
}
fn review_value<V: BasicValue<'ctx>>(
&self,
ctx: &'ctx Context,
value: V,
) -> Result<Pointer<'ctx, E>, ModelError> {
let value = value.as_basic_value_enum();
self.check_type(ctx, value.get_type())?;
Ok(self.believe_value(value.into_pointer_value()))
}
}
impl<'ctx, E: Model<'ctx>> PointerModel<E> {
/// Create a null [`Pointer`] of this [`PointerModel`]
pub fn nullptr(&self, ctx: &'ctx Context) -> Pointer<'ctx, E> {
let nullptr = self.get_type(ctx).const_null();
self.believe_value(nullptr)
}
}
impl<'ctx, E: Model<'ctx>> Pointer<'ctx, E> {
/// Build an instruction to store a value into this pointer
pub fn store(&self, ctx: &CodeGenContext<'ctx, '_>, instance: Instance<'ctx, E>) {
assert_eq!(
self.model.0, instance.model,
"Attempting to store an Instance of a different type"
);
ctx.builder.build_store(self.value, instance.value).unwrap();
}
/// Build an instruction to load a value from this pointer
pub fn load(&self, ctx: &CodeGenContext<'ctx, '_>, name: &str) -> Instance<'ctx, E> {
let value = ctx.builder.build_load(self.value, name).unwrap();
self.model.0.review_value(ctx.ctx, value).unwrap() // If unwrap() panics, there is a logic error in your code.
}
/// "Demote" the [`Model`] of the thing this pointer is pointing to.
pub fn cast_to_opaque(self, ctx: &'ctx Context) -> Pointer<'ctx, OpaqueModel<'ctx>> {
let ptr_model = PointerModel(OpaqueModel(self.model.get_type(ctx).as_basic_type_enum()));
ptr_model.believe_value(self.value)
}
/// Cast the [`Model`] of the thing this pointer is pointing to
/// and uses inkwell's [`Builder::build_pointer_cast`] to cast the LLVM pointer type.
pub fn cast_to<K: Model<'ctx>>(
self,
ctx: &CodeGenContext<'ctx, '_>,
element: K,
name: &str,
) -> Pointer<'ctx, K> {
let casted_ptr_model = PointerModel(element);
let casted_ptr = ctx
.builder
.build_pointer_cast(
self.value,
element.get_type(ctx.ctx).ptr_type(AddressSpace::default()),
name,
)
.unwrap();
casted_ptr_model.believe_value(casted_ptr)
}
pub fn is_null(&self, ctx: &CodeGenContext<'ctx, '_>, name: &str) -> NInt<'ctx, Bool> {
let model = NIntModel(Bool);
let value = ctx.builder.build_is_null(self.value, name).unwrap();
model.believe_value(value)
}
pub fn is_not_null(&self, ctx: &CodeGenContext<'ctx, '_>, name: &str) -> NInt<'ctx, Bool> {
let model = NIntModel(Bool);
let value = ctx.builder.build_is_not_null(self.value, name).unwrap();
model.believe_value(value)
}
}

View File

@ -0,0 +1,94 @@
use inkwell::{types::IntType, values::IntValue};
use crate::codegen::{CodeGenContext, CodeGenerator};
use super::{int_util::int_constant, Instance, Model, Pointer};
/// An LLVM "slice" - literally just a pointer and a length value.
/// The pointer points to a location with `num_elements` **contiguously** placed
/// values of [`E`][`Model<ctx>`] in memory.
///
/// NOTE: This is NOT a [`Model`]! This is simply a helper
/// structure to aggregate a length value and a pointer together.
pub struct ArraySlice<'ctx, N, E>
where
N: Model<'ctx, Value = IntValue<'ctx>, Type = IntType<'ctx>>,
E: Model<'ctx>,
{
pub pointer: Pointer<'ctx, E>,
pub num_elements: Instance<'ctx, N>,
}
impl<'ctx, N, E> ArraySlice<'ctx, N, E>
where
N: Model<'ctx, Value = IntValue<'ctx>, Type = IntType<'ctx>>,
E: Model<'ctx>,
{
/// Get the [Model][`super::Model`] of the element type of this [`ArraySlice`]
pub fn get_element_model(&self) -> E {
self.pointer.model.0
}
/// Get the `idx`-nth element of this [`ArraySlice`],
/// but doesn't do an assertion to see if `idx` is
/// out of bounds or not.
///
/// Also see [`ArraySlice::ix`].
pub fn ix_unchecked(
&self,
ctx: &CodeGenContext<'ctx, '_>,
idx: Instance<'ctx, N>,
name: &str,
) -> Pointer<'ctx, E> {
assert_eq!(idx.model, self.num_elements.model);
let element_ptr = unsafe {
ctx.builder.build_in_bounds_gep(self.pointer.value, &[idx.value], name).unwrap()
};
self.pointer.model.review_value(ctx.ctx, element_ptr).unwrap()
}
/// Call [`ArraySlice::ix_unchecked`], but
/// checks if `idx` is in bounds, otherwise
/// a runtime `IndexError` will be thrown.
pub fn ix<G: CodeGenerator + ?Sized>(
&self,
generator: &mut G,
ctx: &mut CodeGenContext<'ctx, '_>,
idx: Instance<'ctx, N>,
name: &str,
) -> Pointer<'ctx, E> {
assert_eq!(idx.model, self.num_elements.model);
let int_type = self.num_elements.model;
// Assert `0 <= idx < length` and throw an Exception if `idx` is out of bounds
let lower_bounded = ctx
.builder
.build_int_compare(
inkwell::IntPredicate::SLE,
int_constant(ctx.ctx, int_type, 0).value,
idx.value,
"lower_bounded",
)
.unwrap();
let upper_bounded = ctx
.builder
.build_int_compare(
inkwell::IntPredicate::SLT,
idx.value,
self.num_elements.value,
"upper_bounded",
)
.unwrap();
let bounded = ctx.builder.build_and(lower_bounded, upper_bounded, "bounded").unwrap();
ctx.make_assert(
generator,
bounded,
"0:IndexError",
"nac3core LLVM codegen attempting to access out of bounds array index {0}. Must satisfy 0 <= index < {2}",
[ Some(idx.value), Some(self.num_elements.value), None],
ctx.current_loc
);
self.ix_unchecked(ctx, idx, name)
}
}

View File

@ -0,0 +1,384 @@
use core::fmt;
use inkwell::{
context::Context,
types::{BasicType, BasicTypeEnum, StructType},
values::{BasicValue, StructValue},
};
use itertools::{izip, Itertools};
use crate::codegen::CodeGenContext;
use super::{core::CanCheckLLVMType, Instance, Model, ModelError, Pointer, PointerModel};
/// An LLVM struct's "field".
#[derive(Debug, Clone, Copy)]
pub struct Field<E> {
/// The GEP index of this field.
pub gep_index: u64,
/// The name of this field. Generally named
/// to how the field is named in ARTIQ or IRRT.
///
/// NOTE: This is only used for debugging.
pub name: &'static str,
/// The [`Model`] of this field.
pub model: E,
}
// A helper struct for [`FieldBuilder`]
struct FieldLLVM<'ctx> {
gep_index: u64,
name: &'ctx str,
// Only CanCheckLLVMType is needed, dont use `Model<'ctx>`
llvm_type_model: Box<dyn CanCheckLLVMType<'ctx> + 'ctx>,
llvm_type: BasicTypeEnum<'ctx>,
}
/// A helper struct to create [`Field`]-s in [`StructKind::build_fields`].
///
/// See [`StructKind`] for more details and see how [`FieldBuilder`] is put
/// into action.
pub struct FieldBuilder<'ctx> {
/// The [`Context`] this [`FieldBuilder`] is under.
///
/// Can be used in [`StructKind::build_fields`].
/// See [`StructKind`] for more details and see how [`FieldBuilder`] is put
/// into action.
pub ctx: &'ctx Context,
/// An incrementing counter for GEP indices when
/// doing [`FieldBuilder::add_field`] or [`FieldBuilder::add_field_auto`].
gep_index_counter: u64,
/// Name of the `struct` this [`FieldBuilder`] is currently
/// building.
///
/// NOTE: This is only used for debugging.
struct_name: &'ctx str,
/// The fields added so far.
fields: Vec<FieldLLVM<'ctx>>,
}
impl<'ctx> FieldBuilder<'ctx> {
#[must_use]
pub fn new(ctx: &'ctx Context, struct_name: &'ctx str) -> Self {
FieldBuilder { ctx, gep_index_counter: 0, struct_name, fields: Vec::new() }
}
fn next_gep_index(&mut self) -> u64 {
let index = self.gep_index_counter;
self.gep_index_counter += 1;
index
}
/// Add a new field.
///
/// - `name`: The name of the field. See [`Field::name`].
/// - `element`: The [`Model`] of the type of the field. See [`Field::element`].
pub fn add_field<E: Model<'ctx> + 'ctx>(&mut self, name: &'static str, element: E) -> Field<E> {
let gep_index = self.next_gep_index();
self.fields.push(FieldLLVM {
gep_index,
name,
llvm_type: element.get_type(self.ctx).as_basic_type_enum(),
llvm_type_model: Box::new(element),
});
Field { gep_index, name, model: element }
}
/// Like [`FieldBuilder::add_field`] but `element` can be **automatically derived**
/// if it has the `Default` instance.
///
/// Certain [`Model`] has a [`Default`] trait - [`Model`]s that are just singletons,
/// By deriving the [`Default`] trait on those [`Model`]s, Rust could automatically
/// construct the [`Model`] with [`Default::default`].
///
/// This function is equivalent to
/// ```ignore
/// self.add_field(name, E::default())
/// ```
pub fn add_field_auto<E: Model<'ctx> + Default + 'ctx>(
&mut self,
name: &'static str,
) -> Field<E> {
self.add_field(name, E::default())
}
}
/// A marker trait to mark singleton struct that
/// describes a particular LLVM structure.
///
/// It is a powerful inkwell abstraction that can reduce
/// a lot of inkwell boilerplate when dealing with LLVM structs,
/// `getelementptr`, `load`-ing and `store`-ing fields.
///
/// ### Usage
pub trait StructKind<'ctx>: fmt::Debug + Clone + Copy + PartialEq + Eq {
/// The type of the Rust `struct` that holds all the fields of this LLVM struct.
type Fields;
// TODO:
/// The name of this [`StructKind`].
///
/// The name should be the name of in
/// IRRT's `struct` or ARTIQ's definition.
fn struct_name(&self) -> &'static str;
/// Define the [`Field`]s of this [`StructKind`]
///
///
/// ### Syntax
///
/// Suppose you want to define the following C++ `struct`s in `nac3core`:
/// ```cpp
/// template <typename SizeT>
/// struct Str {
/// uint8_t* content; // NOTE: could be `void *`
/// SizeT length;
/// }
///
/// template <typename SizeT>
/// struct Exception {
/// uint32_t id;
/// Str message;
/// uint64_t param0;
/// uint64_t param1;
/// uint64_t param2;
/// }
/// ```
///
/// You write this in nac3core:
/// ```ignore
/// struct Str<'ctx> {
/// sizet: IntModel<'ctx>,
/// }
///
/// struct StrFields<'ctx> {
/// content: Field<PointerModel<ByteModel>>, // equivalent to `NIntModel<Byte>`.
/// length: Field<IntModel<'ctx>>, // `SizeT` is only known in runtime - `CodeGenerator::get_size_type()`. /// }
/// }
///
/// impl StructKind<'ctx> for Str<'ctx> {
/// fn struct_name() {
/// "Str"
/// }
///
/// fn build_fields(&self, builder: &mut FieldBuilder<'ctx>) -> Self::Fields {
/// // THE order of `builder.add_field*` is IMPORTANT!!!
/// // so the GEP indices would be correct.
/// StrFields {
/// content: builder.add_field_auto("content"), // `PointerModel<ByteModel>` has `Default` trait.
/// length: builder.add_field("length", IntModel(self.sizet)), // `PointerModel<ByteModel>` has `Default` trait.
/// }
/// }
/// }
///
/// struct Exception<'ctx> {
/// sizet: IntModel<'ctx>,
/// }
///
/// struct ExceptionFields<'ctx> {
/// id: Field<NIntModel<Int32>>,
/// message: Field<StructModel<Str>>,
/// param0: Field<NIntModel<Int64>>,
/// param1: Field<NIntModel<Int64>>,
/// param2: Field<NIntModel<Int64>>,
/// }
///
/// impl StructKind<'ctx> for Exception<'ctx> {
/// fn struct_name() {
/// "Exception"
/// }
///
/// fn build_fields(&self, builder: &mut FieldBuilder<'ctx>) -> Self::Fields {
/// // THE order of `builder.add_field*` is IMPORTANT!!!
/// // so the GEP indices would be correct.
/// ExceptionFields {
/// id: builder.add_field_auto("content"), // `NIntModel<Int32>` has `Default` trait.
/// message: builder.add_field("message", StructModel(Str { sizet: self.sizet })),
/// param0: builder.add_field_auto("param0"), // has `Default` trait
/// param1: builder.add_field_auto("param1"), // has `Default` trait
/// param2: builder.add_field_auto("param2"), // has `Default` trait
/// }
/// }
/// }
/// ```
///
/// Then to `alloca` an `Exception`, do this:
/// ```ignore
/// let generator: dyn CodeGenerator<'ctx>;
/// let ctx: &CodeGenContext<'ctx, '_>;
/// let sizet = generator.get_size_type();
/// let exn_model = StructModel(Exception { sizet });
/// let exn = exn_model.alloca(ctx, "my_exception"); // Every [`Model<'ctx>`] has an `.alloca()` function.
/// // exn: Pointer<'ctx, StructModel<Exception>>
/// ```
///
/// NOTE: In fact, it is possible to define `Str` and `Exception` like this:
/// ```ignore
/// struct Str<SizeT: NIntModel> {
/// _phantom: PhantomData<SizeT>,
/// }
///
/// struct Exception<T: NIntModel> {
/// _phantom: PhantomData<SizeT>,
/// }
/// ```
/// But issues arise by you don't know the nac3core
/// `CodeGenerator`'s `get_size_type()` before hand.
fn build_fields(&self, builder: &mut FieldBuilder<'ctx>) -> Self::Fields;
}
/// A [`Model<'ctx>`] that represents an LLVM struct.
///
/// `self.0` contains a [`StructKind<'ctx>`] that gives the details of the LLVM struct.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct StructModel<S>(pub S);
pub type Struct<'ctx, S> = Instance<'ctx, StructModel<S>>;
impl<'ctx, S: StructKind<'ctx>> CanCheckLLVMType<'ctx> for StructModel<S> {
fn check_llvm_type_impl(
&self,
ctx: &'ctx Context,
ty: BasicTypeEnum<'ctx>,
) -> Result<(), ModelError> {
// Check if scrutinee is even a struct type
let BasicTypeEnum::StructType(ty) = ty else {
return Err(ModelError(format!("Expecting a struct type, but got {ty:?}")));
};
// Ok. now check the struct type thoroughly
self.check_struct_type(ctx, ty)
}
}
impl<'ctx, S: StructKind<'ctx>> Model<'ctx> for StructModel<S> {
type Value = StructValue<'ctx>;
type Type = StructType<'ctx>;
fn get_type(&self, ctx: &'ctx Context) -> Self::Type {
self.get_struct_type(ctx)
}
fn review_value<V: BasicValue<'ctx>>(
&self,
ctx: &'ctx Context,
value: V,
) -> Result<Struct<'ctx, S>, ModelError> {
let value = value.as_basic_value_enum();
self.check_type(ctx, value.get_type())?;
Ok(self.believe_value(value.into_struct_value()))
}
}
impl<'ctx, S: StructKind<'ctx>> StructModel<S> {
/// Get the [`S::Fields`] of this [`StructModel`].
pub fn get_fields(&self, ctx: &'ctx Context) -> S::Fields {
let mut builder = FieldBuilder::new(ctx, self.0.struct_name());
self.0.build_fields(&mut builder)
}
/// Get the LLVM struct type this [`IsStruct<'ctx>`] is representing.
pub fn get_struct_type(&self, ctx: &'ctx Context) -> StructType<'ctx> {
let mut builder = FieldBuilder::new(ctx, self.0.struct_name());
self.0.build_fields(&mut builder); // Self::Fields is discarded
let field_types = builder.fields.iter().map(|f| f.llvm_type).collect_vec();
ctx.struct_type(&field_types, false)
}
/// Check if `scrutinee` matches the [`StructType<'ctx>`] this [`IsStruct<'ctx>`] is representing.
pub fn check_struct_type(
&self,
ctx: &'ctx Context,
scrutinee: StructType<'ctx>,
) -> Result<(), ModelError> {
// Details about scrutinee
let scrutinee_field_types = scrutinee.get_field_types();
// Details about the defined specifications of this struct
// We will access them through builder
let mut builder = FieldBuilder::new(ctx, self.0.struct_name());
self.0.build_fields(&mut builder);
// Check # of fields
if builder.fields.len() != scrutinee_field_types.len() {
return Err(ModelError(format!(
"Expecting struct to have {} field(s), but scrutinee has {} field(s)",
builder.fields.len(),
scrutinee_field_types.len()
)));
}
// Check the types of each field
// TODO: Traceback?
for (f, scrutinee_field_type) in izip!(builder.fields, scrutinee_field_types) {
f.llvm_type_model
.check_llvm_type_impl(ctx, scrutinee_field_type.as_basic_type_enum())?;
}
Ok(())
}
}
impl<'ctx, S: StructKind<'ctx>> Pointer<'ctx, StructModel<S>> {
/// Build an instruction that does `getelementptr` on an LLVM structure referenced by this pointer.
///
/// This provides a nice syntax to chain up `getelementptr` in an intuitive and type-safe way:
///
/// ```ignore
/// let ctx: &CodeGenContext<'ctx, '_>;
/// let ndarray: Pointer<'ctx, StructModel<NpArray<'ctx>>>;
/// ndarray.gep(ctx, |f| f.ndims).store();
/// ```
///
/// You might even write chains `gep`, i.e.,
/// ```ignore
/// let exn_ptr: Pointer<'ctx, StructModel<Exception>>;
/// let value: Int<'ctx>; // Suppose it has the correct inkwell `IntType<'ctx>`.
///
/// // To do `exn.message.length = value`:
/// let exn_message_ptr = exn_ptr.gep(ctx, |f| f.message);
/// let exn_message_length_ptr = exn_message_ptr.gep(ctx, |f| f.length);
/// exn_message_length_ptr.store(ctx, my_value);
///
/// // or simply:
/// exn_ptr
/// .gep(ctx, |f| f.message)
/// .gep(ctx, |f| f.length)
/// .store(ctx, my_value) // Equivalent to `my_struct.thing1.value = my_value`
/// ```
pub fn gep<E, GetFieldFn>(
&self,
ctx: &CodeGenContext<'ctx, '_>,
get_field: GetFieldFn,
) -> Pointer<'ctx, E>
where
E: Model<'ctx>,
GetFieldFn: FnOnce(S::Fields) -> Field<E>,
{
let fields = self.model.0.get_fields(ctx.ctx);
let field = get_field(fields);
// TODO: I think I'm not supposed to *just* use i32 for GEP like that
let llvm_i32 = ctx.ctx.i32_type();
let ptr_model = PointerModel(field.model);
let ptr = unsafe {
ctx.builder
.build_in_bounds_gep(
self.value,
&[llvm_i32.const_zero(), llvm_i32.const_int(field.gep_index, false)],
field.name,
)
.unwrap()
};
ptr_model.believe_value(ptr)
}
}

View File

@ -252,7 +252,7 @@ fn ndarray_zero_value<'ctx, G: CodeGenerator + ?Sized>(
} else if ctx.unifier.unioned(elem_ty, ctx.primitives.bool) {
ctx.ctx.bool_type().const_zero().into()
} else if ctx.unifier.unioned(elem_ty, ctx.primitives.str) {
ctx.gen_string(generator, "")
ctx.gen_string(generator, "").value.into()
} else {
unreachable!()
}
@ -280,7 +280,7 @@ fn ndarray_one_value<'ctx, G: CodeGenerator + ?Sized>(
} else if ctx.unifier.unioned(elem_ty, ctx.primitives.bool) {
ctx.ctx.bool_type().const_int(1, false).into()
} else if ctx.unifier.unioned(elem_ty, ctx.primitives.str) {
ctx.gen_string(generator, "1")
ctx.gen_string(generator, "1").value.into()
} else {
unreachable!()
}

View File

@ -0,0 +1,213 @@
use inkwell::{
types::BasicType,
values::{BasicValue, BasicValueEnum, PointerValue},
};
use nac3parser::ast::StrRef;
use crate::{
codegen::{
irrt::ndarray::{
allocation::{alloca_ndarray, init_ndarray_data_by_alloca, init_ndarray_shape},
fill::call_nac3_ndarray_fill_generic,
},
model::*,
structs::ndarray::NpArray,
util::shape::parse_input_shape_arg,
CodeGenContext, CodeGenerator,
},
symbol_resolver::ValueEnum,
toplevel::DefinitionId,
typecheck::typedef::{FunSignature, Type},
};
/// Helper function to create an ndarray with uninitialized values
///
/// * `elem_ty` - The [`Type`] of the ndarray elements
/// * `shape` - The user input shape argument
/// * `shape_ty` - The [`Type`] of the shape argument
/// * `name` - LLVM IR name of the returned ndarray
fn create_empty_ndarray<'ctx, G>(
generator: &mut G,
ctx: &mut CodeGenContext<'ctx, '_>,
elem_ty: Type,
shape: BasicValueEnum<'ctx>,
shape_ty: Type,
name: &str,
) -> Result<Pointer<'ctx, StructModel<NpArray<'ctx>>>, String>
where
G: CodeGenerator + ?Sized,
{
let sizet = generator.get_sizet(ctx.ctx);
let shape_writer = parse_input_shape_arg(generator, ctx, shape, shape_ty);
let ndims = shape_writer.count;
let ndarray = alloca_ndarray(generator, ctx, ndims, name)?;
init_ndarray_shape(generator, ctx, ndarray, &shape_writer)?;
let itemsize = sizet
.review_value(ctx.ctx, ctx.get_llvm_type(generator, elem_ty).size_of().unwrap())
.unwrap();
ndarray.gep(ctx, |f| f.itemsize).store(ctx, itemsize);
init_ndarray_data_by_alloca(generator, ctx, ndarray); // Needs `itemsize` and `shape` initialized first
Ok(ndarray)
}
/// Helper function to create an ndarray full of a value.
///
/// * `elem_ty` - The [`Type`] of the ndarray elements and the fill value
/// * `shape` - The user input shape argument
/// * `shape_ty` - The [`Type`] of the shape argument
/// * `fill_value` - The user specified fill value
/// * `name` - LLVM IR name of the returned ndarray
fn create_full_ndarray<'ctx, G>(
generator: &mut G,
ctx: &mut CodeGenContext<'ctx, '_>,
elem_ty: Type,
shape: BasicValueEnum<'ctx>,
shape_ty: Type,
fill_value: BasicValueEnum<'ctx>,
name: &str,
) -> Result<Pointer<'ctx, StructModel<NpArray<'ctx>>>, String>
where
G: CodeGenerator + ?Sized,
{
let byte_model = NIntModel(Byte);
let fill_value_model = OpaqueModel(fill_value.get_type());
// Caller has to put fill_value on the stack and pass its address
let fill_value_ptr = fill_value_model.alloca(ctx, "fill_value_ptr");
fill_value_ptr.store(ctx, fill_value_model.believe_value(fill_value));
let fill_value_ptr = fill_value_ptr.cast_to(ctx, byte_model, "fill_value_bytes_ptr");
let ndarray_ptr = create_empty_ndarray(generator, ctx, elem_ty, shape, shape_ty, name)?;
call_nac3_ndarray_fill_generic(generator, ctx, ndarray_ptr, fill_value_ptr);
Ok(ndarray_ptr)
}
/// Generates LLVM IR for `np.empty`.
pub fn gen_ndarray_empty<'ctx>(
context: &mut CodeGenContext<'ctx, '_>,
obj: &Option<(Type, ValueEnum<'ctx>)>,
fun: (&FunSignature, DefinitionId),
args: &[(Option<StrRef>, ValueEnum<'ctx>)],
generator: &mut dyn CodeGenerator,
) -> Result<PointerValue<'ctx>, String> {
assert!(obj.is_none());
assert_eq!(args.len(), 1);
// Parse arguments
let shape_ty = fun.0.args[0].ty;
let shape = args[0].1.clone().to_basic_value_enum(context, generator, shape_ty)?;
// Implementation
let ndarray_ptr = create_empty_ndarray(
generator,
context,
context.primitives.float,
shape,
shape_ty,
"ndarray",
)?;
Ok(ndarray_ptr.value)
}
/// Generates LLVM IR for `np.zeros`.
pub fn gen_ndarray_zeros<'ctx>(
context: &mut CodeGenContext<'ctx, '_>,
obj: &Option<(Type, ValueEnum<'ctx>)>,
fun: (&FunSignature, DefinitionId),
args: &[(Option<StrRef>, ValueEnum<'ctx>)],
generator: &mut dyn CodeGenerator,
) -> Result<PointerValue<'ctx>, String> {
assert!(obj.is_none());
assert_eq!(args.len(), 1);
// Parse arguments
let shape_ty = fun.0.args[0].ty;
let shape = args[0].1.clone().to_basic_value_enum(context, generator, shape_ty)?;
// Implementation
// NOTE: Currently nac3's `np.zeros` is always `float64`.
let float64_ty = context.primitives.float;
let float64_llvm_type = context.get_llvm_type(generator, float64_ty).into_float_type();
let ndarray_ptr = create_full_ndarray(
generator,
context,
float64_ty, // `elem_ty` is always `float64`
shape,
shape_ty,
float64_llvm_type.const_zero().as_basic_value_enum(),
"ndarray",
)?;
Ok(ndarray_ptr.value)
}
/// Generates LLVM IR for `np.ones`.
pub fn gen_ndarray_ones<'ctx>(
context: &mut CodeGenContext<'ctx, '_>,
obj: &Option<(Type, ValueEnum<'ctx>)>,
fun: (&FunSignature, DefinitionId),
args: &[(Option<StrRef>, ValueEnum<'ctx>)],
generator: &mut dyn CodeGenerator,
) -> Result<PointerValue<'ctx>, String> {
assert!(obj.is_none());
assert_eq!(args.len(), 1);
// Parse arguments
let shape_ty = fun.0.args[0].ty;
let shape = args[0].1.clone().to_basic_value_enum(context, generator, shape_ty)?;
// Implementation
// NOTE: Currently nac3's `np.ones` is always `float64`.
let float64_ty = context.primitives.float;
let float64_llvm_type = context.get_llvm_type(generator, float64_ty).into_float_type();
let ndarray_ptr = create_full_ndarray(
generator,
context,
float64_ty, // `elem_ty` is always `float64`
shape,
shape_ty,
float64_llvm_type.const_float(1.0).as_basic_value_enum(),
"ndarray",
)?;
Ok(ndarray_ptr.value)
}
/// Generates LLVM IR for `np.full`.
pub fn gen_ndarray_full<'ctx>(
context: &mut CodeGenContext<'ctx, '_>,
obj: &Option<(Type, ValueEnum<'ctx>)>,
fun: (&FunSignature, DefinitionId),
args: &[(Option<StrRef>, ValueEnum<'ctx>)],
generator: &mut dyn CodeGenerator,
) -> Result<PointerValue<'ctx>, String> {
assert!(obj.is_none());
assert_eq!(args.len(), 2);
// Parse argument #1 shape
let shape_ty = fun.0.args[0].ty;
let shape_arg = args[0].1.clone().to_basic_value_enum(context, generator, shape_ty)?;
// Parse argument #2 fill_value
let fill_value_ty = fun.0.args[1].ty;
let fill_value_arg =
args[1].1.clone().to_basic_value_enum(context, generator, fill_value_ty)?;
// Implementation
let ndarray_ptr = create_full_ndarray(
generator,
context,
fill_value_ty,
shape_arg,
shape_ty,
fill_value_arg,
"ndarray",
)?;
Ok(ndarray_ptr.value)
}

View File

@ -0,0 +1,2 @@
pub mod factory;
pub mod view;

View File

@ -0,0 +1,169 @@
use inkwell::values::PointerValue;
use nac3parser::ast::StrRef;
use crate::{
codegen::{
irrt::ndarray::{
allocation::{alloca_ndarray, init_ndarray_shape},
basic::{
call_nac3_ndarray_is_c_contiguous, call_nac3_ndarray_nbytes,
call_nac3_ndarray_set_strides_by_shape, call_nac3_ndarray_size,
},
reshape::call_nac3_ndarray_resolve_and_check_new_shape,
transpose::call_nac3_ndarray_transpose,
},
model::*,
structs::{list::List, ndarray::NpArray},
util::{array_writer::ArrayWriter, shape::parse_input_shape_arg},
CodeGenContext, CodeGenerator,
},
symbol_resolver::ValueEnum,
toplevel::DefinitionId,
typecheck::typedef::{FunSignature, Type},
};
fn reshape_ndarray_or_copy<'ctx, G: CodeGenerator + ?Sized>(
generator: &mut G,
ctx: &mut CodeGenContext<'ctx, '_>,
src_ndarray: Pointer<'ctx, StructModel<NpArray<'ctx>>>,
new_shape: &ArrayWriter<'ctx, G, SizeTModel<'ctx>, SizeTModel<'ctx>>,
) -> Result<Pointer<'ctx, StructModel<NpArray<'ctx>>>, String> {
let byte_model = NIntModel(Byte);
/*
Reference pseudo-code:
```c
NDArray<SizeT>* src_ndarray;
NDArray<SizeT>* dst_ndarray = __builtin_alloca(...);
dst_ndarray->ndims = ...
dst_ndarray->strides = __builtin_alloca(...);
dst_ndarray->shape = ... // Directly set by user, may contain -1, or even illegal values.
dst_ndarray->itemsize = src_ndarray->itemsize;
set_strides_by_shape(dst_ndarray);
// Do assertions on `dst_ndarray->shape` and resolve -1
resolve_and_check_new_shape(ndarray_size(src_ndarray), dst_ndarray->shape);
if (is_c_contiguous(src_ndarray)) {
dst_ndarray->data = src_ndarray->data;
} else {
dst_ndarray->data = __builtin_alloca( ndarray_nbytes(dst_ndarray) );
copy_data(src_ndarray, dst_ndarray);
}
return dst_ndarray;
```
*/
let current_bb = ctx.builder.get_insert_block().unwrap();
let then_bb = ctx.ctx.insert_basic_block_after(current_bb, "then");
let else_bb = ctx.ctx.insert_basic_block_after(then_bb, "else_bb");
let end_bb = ctx.ctx.insert_basic_block_after(else_bb, "end_bb");
// current_bb
let dst_ndarray = alloca_ndarray(generator, ctx, new_shape.count, "ndarray").unwrap();
init_ndarray_shape(generator, ctx, dst_ndarray, new_shape)?;
dst_ndarray
.gep(ctx, |f| f.itemsize)
.store(ctx, src_ndarray.gep(ctx, |f| f.itemsize).load(ctx, "itemsize"));
call_nac3_ndarray_set_strides_by_shape(generator, ctx, dst_ndarray);
let src_ndarray_size = call_nac3_ndarray_size(generator, ctx, src_ndarray);
call_nac3_ndarray_resolve_and_check_new_shape(
generator,
ctx,
src_ndarray_size,
dst_ndarray.gep(ctx, |f| f.ndims).load(ctx, "ndims"),
dst_ndarray.gep(ctx, |f| f.shape).load(ctx, "shape"),
);
let is_c_contiguous = call_nac3_ndarray_is_c_contiguous(generator, ctx, src_ndarray);
ctx.builder.build_conditional_branch(is_c_contiguous.value, then_bb, else_bb).unwrap();
// then_bb: reshape is possible without copying
ctx.builder.position_at_end(then_bb);
dst_ndarray.gep(ctx, |f| f.data).store(ctx, src_ndarray.gep(ctx, |f| f.data).load(ctx, "data"));
ctx.builder.build_unconditional_branch(end_bb).unwrap();
// else_bb: reshape is impossible without copying
ctx.builder.position_at_end(else_bb);
let dst_ndarray_nbytes = call_nac3_ndarray_nbytes(generator, ctx, dst_ndarray);
let data = byte_model.array_alloca(ctx, dst_ndarray_nbytes, "new_data").pointer;
dst_ndarray.gep(ctx, |f| f.data).store(ctx, data);
ctx.builder.build_unconditional_branch(end_bb).unwrap();
// Reposition for continuation
ctx.builder.position_at_end(end_bb);
Ok(dst_ndarray)
}
/// Generates LLVM IR for `np.reshape`.
pub fn gen_ndarray_reshape<'ctx>(
context: &mut CodeGenContext<'ctx, '_>,
obj: &Option<(Type, ValueEnum<'ctx>)>,
fun: (&FunSignature, DefinitionId),
args: &[(Option<StrRef>, ValueEnum<'ctx>)],
generator: &mut dyn CodeGenerator,
) -> Result<PointerValue<'ctx>, String> {
assert!(obj.is_none());
assert_eq!(args.len(), 2);
// Parse argument #1 ndarray
let ndarray_ty = fun.0.args[0].ty;
let ndarray_arg = args[0].1.clone().to_basic_value_enum(context, generator, ndarray_ty)?;
// Parse argument #2 shape
let shape_ty = fun.0.args[1].ty;
let shape_arg = args[1].1.clone().to_basic_value_enum(context, generator, shape_ty)?;
let sizet = generator.get_sizet(context.ctx);
let pndarray_model = PointerModel(StructModel(NpArray { sizet }));
let src_ndarray = pndarray_model.review_value(context.ctx, ndarray_arg).unwrap();
let new_shape = parse_input_shape_arg(generator, context, shape_arg, shape_ty);
let reshaped_ndarray = reshape_ndarray_or_copy(generator, context, src_ndarray, &new_shape)?;
Ok(reshaped_ndarray.value)
}
pub fn gen_ndarray_transpose<'ctx>(
context: &mut CodeGenContext<'ctx, '_>,
obj: &Option<(Type, ValueEnum<'ctx>)>,
fun: (&FunSignature, DefinitionId),
args: &[(Option<StrRef>, ValueEnum<'ctx>)],
generator: &mut dyn CodeGenerator,
) -> Result<PointerValue<'ctx>, String> {
assert!(obj.is_none());
assert!(matches!(args.len(), 1 | 2));
let sizet = generator.get_sizet(context.ctx);
let in_axes_model = PointerModel(StructModel(List { sizet, element: NIntModel(Int32) }));
// Parse argument #1 ndarray
let ndarray_ty = fun.0.args[0].ty;
let ndarray_arg = args[0].1.clone().to_basic_value_enum(context, generator, ndarray_ty)?;
// Parse argument #2 axes (optional)
let in_axes = if args.len() == 2 {
let in_shape_ty = fun.0.args[1].ty;
let in_shape_arg =
args[1].1.clone().to_basic_value_enum(context, generator, in_shape_ty)?;
let in_shape = in_axes_model.review_value(context.ctx, in_shape_arg).unwrap();
let num_axes = in_shape.gep(context, |f| f.size).load(context, "num_axes");
let axes = sizet.array_alloca(context, num_axes, "num_axes");
Some((in_shape_ty, in_shape_arg))
} else {
None
};
// call_nac3_ndarray_transpose(generator, ctx, src_ndarray, dst_ndarray, axes_or_none)
todo!()
}

View File

@ -2,6 +2,8 @@ use super::{
super::symbol_resolver::ValueEnum,
expr::destructure_range,
irrt::{handle_slice_indices, list_slice_assignment},
model::*,
structs::{cslice::CSlice, exception::Exception},
CodeGenContext, CodeGenerator,
};
use crate::{
@ -1113,47 +1115,37 @@ pub fn exn_constructor<'ctx>(
pub fn gen_raise<'ctx, G: CodeGenerator + ?Sized>(
generator: &mut G,
ctx: &mut CodeGenContext<'ctx, '_>,
exception: Option<&BasicValueEnum<'ctx>>,
exception: Option<Pointer<'ctx, StructModel<Exception<'ctx>>>>,
loc: Location,
) {
if let Some(exception) = exception {
unsafe {
let int32 = ctx.ctx.i32_type();
let zero = int32.const_zero();
let exception = exception.into_pointer_value();
let file_ptr = ctx
.builder
.build_in_bounds_gep(exception, &[zero, int32.const_int(1, false)], "file_ptr")
.unwrap();
let filename = ctx.gen_string(generator, loc.file.0);
ctx.builder.build_store(file_ptr, filename).unwrap();
let row_ptr = ctx
.builder
.build_in_bounds_gep(exception, &[zero, int32.const_int(2, false)], "row_ptr")
.unwrap();
ctx.builder.build_store(row_ptr, int32.const_int(loc.row as u64, false)).unwrap();
let col_ptr = ctx
.builder
.build_in_bounds_gep(exception, &[zero, int32.const_int(3, false)], "col_ptr")
.unwrap();
ctx.builder.build_store(col_ptr, int32.const_int(loc.column as u64, false)).unwrap();
if let Some(pexn) = exception {
let sizet = generator.get_sizet(ctx.ctx);
let i32_model = NIntModel(Int32);
let cslice_model = StructModel(CSlice { sizet });
let current_fun = ctx.builder.get_insert_block().unwrap().get_parent().unwrap();
let fun_name = ctx.gen_string(generator, current_fun.get_name().to_str().unwrap());
let name_ptr = ctx
.builder
.build_in_bounds_gep(exception, &[zero, int32.const_int(4, false)], "name_ptr")
.unwrap();
ctx.builder.build_store(name_ptr, fun_name).unwrap();
}
// Get and store filename
let filename = loc.file.0;
let filename = ctx.gen_string(generator, &String::from(filename)).value;
let filename = cslice_model.review_value(ctx.ctx, filename).unwrap();
pexn.gep(ctx, |f| f.filename).store(ctx, filename);
let row = i32_model.constant(ctx.ctx, loc.row as u64);
pexn.gep(ctx, |f| f.line).store(ctx, row);
let column = i32_model.constant(ctx.ctx, loc.column as u64);
pexn.gep(ctx, |f| f.column).store(ctx, column);
let current_fn = ctx.builder.get_insert_block().unwrap().get_parent().unwrap();
let fn_name = ctx.gen_string(generator, current_fn.get_name().to_str().unwrap());
pexn.gep(ctx, |f| f.function_name).store(ctx, fn_name);
let raise = get_builtins(generator, ctx, "__nac3_raise");
let exception = *exception;
ctx.build_call_or_invoke(raise, &[exception], "raise");
ctx.build_call_or_invoke(raise, &[pexn.value.into()], "raise");
} else {
let resume = get_builtins(generator, ctx, "__nac3_resume");
ctx.build_call_or_invoke(resume, &[], "resume");
}
ctx.builder.build_unreachable().unwrap();
}
@ -1609,35 +1601,50 @@ pub fn gen_stmt<G: CodeGenerator>(
StmtKind::Try { .. } => gen_try(generator, ctx, stmt)?,
StmtKind::Raise { exc, .. } => {
if let Some(exc) = exc {
let exc = if let Some(v) = generator.gen_expr(ctx, exc)? {
v.to_basic_value_enum(ctx, generator, exc.custom.unwrap())?
} else {
// Define all used models
let sizet = generator.get_sizet(ctx.ctx);
let pexn_model = PointerModel(StructModel(Exception { sizet }));
let Some(exn) = generator.gen_expr(ctx, exc)? else {
return Ok(());
};
gen_raise(generator, ctx, Some(&exc), stmt.location);
let pexn = exn.to_basic_value_enum(ctx, generator, ctx.primitives.exception)?;
let pexn = pexn_model.review_value(ctx.ctx, pexn).unwrap();
gen_raise(generator, ctx, Some(pexn), stmt.location);
} else {
gen_raise(generator, ctx, None, stmt.location);
}
}
StmtKind::Assert { test, msg, .. } => {
let test = if let Some(v) = generator.gen_expr(ctx, test)? {
v.to_basic_value_enum(ctx, generator, test.custom.unwrap())?
} else {
// Define all used models
let sizet = generator.get_sizet(ctx.ctx);
let byte_model = NIntModel(Byte);
let cslice_model = StructModel(CSlice { sizet });
// Check `test`
let Some(test) = generator.gen_expr(ctx, test)? else {
return Ok(());
};
let test = test.to_basic_value_enum(ctx, generator, ctx.primitives.bool)?;
let test = byte_model.review_value(ctx.ctx, test).unwrap(); // Python `bool`s are represented as `i8` in nac3core
// Check `msg`
let err_msg = match msg {
Some(msg) => {
if let Some(v) = generator.gen_expr(ctx, msg)? {
v.to_basic_value_enum(ctx, generator, msg.custom.unwrap())?
} else {
let Some(msg) = generator.gen_expr(ctx, msg)? else {
return Ok(());
}
};
let msg = msg.to_basic_value_enum(ctx, generator, ctx.primitives.str)?;
cslice_model.review_value(ctx.ctx, msg).unwrap()
}
None => ctx.gen_string(generator, ""),
};
ctx.make_assert_impl(
generator,
test.into_int_value(),
test.value,
"0:AssertionError",
err_msg,
[None, None, None],

View File

@ -0,0 +1,50 @@
use crate::codegen::{model::*, CodeGenContext};
/// Fields of [`CSlice<'ctx>`].
pub struct CSliceFields<'ctx> {
/// Pointer to the data.
pub base: Field<PointerModel<ByteModel>>,
/// Number of bytes of the data.
pub len: Field<SizeTModel<'ctx>>,
}
/// See <https://crates.io/crates/cslice>.
///
/// Additionally, see <https://github.com/m-labs/artiq/blob/b0d2705c385f64b6e6711c1726cd9178f40b598e/artiq/firmware/libeh/eh_artiq.rs>)
/// for ARTIQ-specific notes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CSlice<'ctx> {
pub sizet: SizeTModel<'ctx>,
}
impl<'ctx> StructKind<'ctx> for CSlice<'ctx> {
type Fields = CSliceFields<'ctx>;
fn struct_name(&self) -> &'static str {
"CSlice"
}
fn build_fields(&self, builder: &mut FieldBuilder<'ctx>) -> Self::Fields {
Self::Fields {
base: builder.add_field_auto("content"),
len: builder.add_field("length", self.sizet),
}
}
}
impl<'ctx> StructModel<CSlice<'ctx>> {
/// Create a [`CSlice`].
///
/// `base` and `len` must be LLVM global constants.
pub fn create_const(
&self,
ctx: &CodeGenContext<'ctx, '_>,
base: Pointer<'ctx, ByteModel>,
len: SizeT<'ctx>,
) -> Struct<'ctx, CSlice<'ctx>> {
let value = self
.get_struct_type(ctx.ctx)
.const_named_struct(&[base.value.into(), len.value.into()]);
self.believe_value(value)
}
}

View File

@ -0,0 +1,78 @@
use crate::codegen::model::*;
use super::cslice::CSlice;
/// The LLVM int type of an Exception ID.
pub type ExceptionId = Int32;
/// Fields of [`Exception<'ctx>`]
///
/// The definition came from `pub struct Exception<'a>` in
/// <https://github.com/m-labs/artiq/blob/master/artiq/firmware/libeh/eh_artiq.rs>.
pub struct ExceptionFields<'ctx> {
/// nac3core's ID of the exception
pub exception_id: Field<NIntModel<ExceptionId>>,
/// The name of the file this `Exception` was raised in.
pub filename: Field<StructModel<CSlice<'ctx>>>,
/// The line number in the file this `Exception` was raised in.
pub line: Field<NIntModel<Int32>>,
/// The column number in the file this `Exception` was raised in.
pub column: Field<NIntModel<Int32>>,
/// The name of the Python function this `Exception` was raised in.
pub function_name: Field<StructModel<CSlice<'ctx>>>,
/// The message of this Exception.
///
/// The message can optionally contain integer parameters `{0}`, `{1}`, and `{2}` in its string,
/// where they will be substituted by `params[0]`, `params[1]`, and `params[2]` respectively (as `int64_t`s).
/// Here is an example:
///
/// ```ignore
/// "Index {0} is out of bounds! List only has {1} element(s)."
/// ```
///
/// In this case, `params[0]` and `params[1]` must be specified, and `params[2]` is ***unused***.
/// Having only 3 parameters is a constraint in ARTIQ.
pub message: Field<StructModel<CSlice<'ctx>>>,
pub params: [Field<NIntModel<Int64>>; 3],
}
/// nac3core & ARTIQ's Exception
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Exception<'ctx> {
/// The `SizeT` type of this string.
pub sizet: SizeTModel<'ctx>,
}
impl<'ctx> StructKind<'ctx> for Exception<'ctx> {
type Fields = ExceptionFields<'ctx>;
fn struct_name(&self) -> &'static str {
"Exception"
}
fn build_fields(&self, builder: &mut FieldBuilder<'ctx>) -> Self::Fields {
let str = StructModel(CSlice { sizet: self.sizet });
let exception_id = builder.add_field_auto("exception_id");
let file_name = builder.add_field("file_name", str);
let line = builder.add_field_auto("line");
let column = builder.add_field_auto("column");
let function_name = builder.add_field("function_name", str);
let message = builder.add_field("message", str);
let params = [
builder.add_field_auto("param0"),
builder.add_field_auto("param1"),
builder.add_field_auto("param2"),
];
Self::Fields {
exception_id,
filename: file_name,
line,
column,
function_name,
message,
params,
}
}
}

View File

@ -0,0 +1,42 @@
use crate::codegen::{model::*, CodeGenContext};
/// Fields of [`List`]
pub struct ListFields<'ctx, T: Model<'ctx>> {
/// Length of the list
pub size: Field<SizeTModel<'ctx>>,
/// Base pointer of the list
pub data: Field<PointerModel<T>>,
}
/// nac3core's `List` definition
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct List<'ctx, T: Model<'ctx>> {
pub sizet: SizeTModel<'ctx>,
pub element: T,
}
impl<'ctx, T: Model<'ctx> + 'ctx> StructKind<'ctx> for List<'ctx, T> {
type Fields = ListFields<'ctx, T>;
fn struct_name(&self) -> &'static str {
"List"
}
fn build_fields(&self, builder: &mut FieldBuilder<'ctx>) -> Self::Fields {
Self::Fields {
size: builder.add_field("size", self.sizet),
data: builder.add_field("data", PointerModel(self.element)),
}
}
}
impl<'ctx, T: Model<'ctx> + 'ctx> Pointer<'ctx, StructModel<List<'ctx, T>>> {
pub fn as_slice(
&self,
ctx: &CodeGenContext<'ctx, '_>,
) -> ArraySlice<'ctx, SizeTModel<'ctx>, T> {
let num_elements = self.gep(ctx, |f| f.size).load(ctx, "num_elements");
let pointer = self.gep(ctx, |f| f.data).load(ctx, "base");
ArraySlice { num_elements, pointer }
}
}

View File

@ -0,0 +1,4 @@
pub mod cslice;
pub mod exception;
pub mod list;
pub mod ndarray;

View File

@ -0,0 +1,54 @@
use crate::codegen::*;
pub struct NpArrayFields<'ctx> {
pub data: Field<PointerModel<ByteModel>>,
pub itemsize: Field<SizeTModel<'ctx>>,
pub ndims: Field<SizeTModel<'ctx>>,
pub shape: Field<PointerModel<SizeTModel<'ctx>>>,
pub strides: Field<PointerModel<SizeTModel<'ctx>>>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct NpArray<'ctx> {
pub sizet: SizeTModel<'ctx>,
}
impl<'ctx> StructKind<'ctx> for NpArray<'ctx> {
type Fields = NpArrayFields<'ctx>;
fn struct_name(&self) -> &'static str {
"NDArray"
}
fn build_fields(&self, builder: &mut FieldBuilder<'ctx>) -> Self::Fields {
NpArrayFields {
data: builder.add_field_auto("data"),
itemsize: builder.add_field("itemsize", self.sizet),
ndims: builder.add_field("ndims", self.sizet),
shape: builder.add_field("shape", PointerModel(self.sizet)),
strides: builder.add_field("strides", PointerModel(self.sizet)),
}
}
}
impl<'ctx> Pointer<'ctx, StructModel<NpArray<'ctx>>> {
/// Get an [`ArraySlice`] of [`NpArrayFields::shape`] with [`NpArrayFields::ndims`] as its length.
pub fn shape_slice(
&self,
ctx: &CodeGenContext<'ctx, '_>,
) -> ArraySlice<'ctx, SizeTModel<'ctx>, SizeTModel<'ctx>> {
let ndims = self.gep(ctx, |f| f.ndims).load(ctx, "ndims");
let shape_base_ptr = self.gep(ctx, |f| f.shape).load(ctx, "shape");
ArraySlice { num_elements: ndims, pointer: shape_base_ptr }
}
/// Get an [`ArraySlice`] of [`NpArrayFields::strides`] with [`NpArrayFields::ndims`] as its length.
pub fn strides_slice(
&self,
ctx: &CodeGenContext<'ctx, '_>,
) -> ArraySlice<'ctx, SizeTModel<'ctx>, SizeTModel<'ctx>> {
let ndims = self.gep(ctx, |f| f.ndims).load(ctx, "ndims");
let strides_base_ptr = self.gep(ctx, |f| f.strides).load(ctx, "strides");
ArraySlice { num_elements: ndims, pointer: strides_base_ptr }
}
}

View File

@ -0,0 +1,17 @@
use inkwell::{types::IntType, values::IntValue};
use crate::codegen::{model::*, CodeGenContext, CodeGenerator};
pub type ArrayWriterWrite<'ctx, G, N, E> = Box<
dyn Fn(&mut G, &mut CodeGenContext<'ctx, '_>, &ArraySlice<'ctx, N, E>) -> Result<(), String>
+ 'ctx,
>;
// TODO: Document
pub struct ArrayWriter<'ctx, G: CodeGenerator + ?Sized, N, E: Model<'ctx>>
where
N: Model<'ctx, Value = IntValue<'ctx>, Type = IntType<'ctx>>,
{
pub count: Instance<'ctx, N>,
pub write: ArrayWriterWrite<'ctx, G, N, E>,
}

View File

@ -0,0 +1,28 @@
use inkwell::{types::IntType, values::IntValue};
use crate::codegen::{model::*, CodeGenContext, CodeGenerator};
/// Convenient structure that looks like
/// Python `range`, with a dependent int type.
pub struct ForRange<T> {
pub start: T,
pub stop: T,
pub step: T,
}
impl<'ctx, T> ForRange<T>
where
T: Model<'ctx, Value = IntValue<'ctx>, Type = IntType<'ctx>>,
{
pub fn end(ctx: &'ctx Context, end: T) -> Self {
todo!()
}
}
pub fn for_range<'ctx, G: CodeGenerator + ?Sized>(
generator: &mut G,
ctx: &mut CodeGenContext<'ctx, 'a>,
range: ForRange,
body: BodyFn,
) {
}

View File

@ -0,0 +1,3 @@
pub mod array_writer;
pub mod control_flow;
pub mod shape;

View File

@ -0,0 +1,144 @@
use inkwell::values::BasicValueEnum;
use crate::{
codegen::{
classes::{ListValue, UntypedArrayLikeAccessor},
model::*,
stmt::gen_for_callback_incrementing,
CodeGenContext, CodeGenerator,
},
typecheck::typedef::{Type, TypeEnum},
};
use super::array_writer::ArrayWriter;
/// TODO: UPDATE DOCUMENTATION
/// LLVM-typed implementation for generating a [`ArrayWriter`] that sets a list of ints.
///
/// * `elem_ty` - The element type of the `NDArray`.
/// * `shape` - The `shape` parameter used to construct the `NDArray`.
///
/// ### Notes on `shape`
///
/// Just like numpy, the `shape` argument can be:
/// 1. A list of `int32`; e.g., `np.empty([600, 800, 3])`
/// 2. A tuple of `int32`; e.g., `np.empty((600, 800, 3))`
/// 3. A scalar `int32`; e.g., `np.empty(3)`, this is functionally equivalent to `np.empty([3])`
///
/// See also [`typecheck::type_inferencer::fold_numpy_function_call_shape_argument`] to
/// learn how `shape` gets from being a Python user expression to here.
pub fn parse_input_shape_arg<'ctx, G>(
generator: &mut G,
ctx: &mut CodeGenContext<'ctx, '_>,
shape: BasicValueEnum<'ctx>,
shape_ty: Type,
) -> ArrayWriter<'ctx, G, SizeTModel<'ctx>, SizeTModel<'ctx>>
where
G: CodeGenerator + ?Sized,
{
let sizet = generator.get_sizet(ctx.ctx);
match &*ctx.unifier.get_ty(shape_ty) {
TypeEnum::TObj { obj_id, .. }
if *obj_id == ctx.primitives.list.obj_id(&ctx.unifier).unwrap() =>
{
// 1. A list of ints; e.g., `np.empty([600, 800, 3])`
// A list has to be a PointerValue
let shape_list = ListValue::from_ptr_val(shape.into_pointer_value(), sizet.0, None);
// Create `ArrayWriter`
let ndims =
sizet.review_value(ctx.ctx, shape_list.load_size(ctx, Some("count"))).unwrap();
ArrayWriter {
count: ndims,
write: Box::new(move |generator, ctx, dst_array| {
// Basically iterate through the list and write to `dst_slice` accordingly
let init_val = sizet.constant(ctx.ctx, 0).value;
let max_val = (ndims.value, false);
let incr_val = sizet.constant(ctx.ctx, 1).value;
gen_for_callback_incrementing(
generator,
ctx,
init_val,
max_val,
|generator, ctx, _hooks, axis| {
let axis = sizet.review_value(ctx.ctx, axis).unwrap();
// TODO: Remove ProxyValue ListValue
// Get the dimension at `axis`
let dim: Int<'ctx> = shape_list
.data()
.get(ctx, generator, &axis.value, None)
.into_int_value()
.into();
let dim = dim.s_extend_or_bit_cast(ctx, sizet, "dim_casted");
dst_array.ix(generator, ctx, axis, "dim").store(ctx, dim);
Ok(())
},
incr_val,
)
}),
}
}
TypeEnum::TTuple { ty: tuple_types } => {
// 2. A tuple of ints; e.g., `np.empty((600, 800, 3))`
// Get the length/size of the tuple, which also happens to be the value of `ndims`.
let ndims = tuple_types.len();
// A tuple has to be a StructValue
// Read [`codegen::expr::gen_expr`] to see how `nac3core` translates a Python tuple into LLVM.
let shape_tuple = shape.into_struct_value();
ArrayWriter {
count: sizet.constant(ctx.ctx, ndims as u64),
write: Box::new(move |generator, ctx, dst_array| {
for axis in 0..ndims {
// Get the dimension at `axis`
let dim: Int<'ctx> = ctx
.builder
.build_extract_value(
shape_tuple,
axis as u32,
format!("dim{axis}").as_str(),
)
.unwrap()
.into_int_value()
.into();
let dim = dim.s_extend_or_bit_cast(ctx, sizet, "dim_casted");
dst_array
.ix(generator, ctx, sizet.constant(ctx.ctx, axis as u64), "dim")
.store(ctx, dim);
}
Ok(())
}),
}
}
TypeEnum::TObj { obj_id, .. }
if *obj_id == ctx.primitives.int32.obj_id(&ctx.unifier).unwrap() =>
{
// 3. A scalar int; e.g., `np.empty(3)`, this is functionally equivalent to `np.empty([3])`
// The value has to be an integer
let shape_int: Int<'ctx> = shape.into_int_value().into();
ArrayWriter {
count: sizet.constant(ctx.ctx, 1),
write: Box::new(move |generator, ctx, dst_array| {
// Cast `shape_int` to SizeT
let dim = shape_int.s_extend_or_bit_cast(ctx, sizet, "dim_casted");
// Set shape[0] = shape_int
dst_array.ix(generator, ctx, sizet.constant(ctx.ctx, 0), "dim").store(ctx, dim);
Ok(())
}),
}
}
_ => panic!("parse_input_shape_arg encountered unknown type"),
}
}

View File

@ -9,16 +9,20 @@ use inkwell::{
IntPredicate,
};
use itertools::Either;
use ndarray::basic::call_nac3_ndarray_len;
use strum::IntoEnumIterator;
use crate::{
codegen::{
builtin_fns,
classes::{ArrayLikeValue, NDArrayValue, ProxyValue, RangeValue, TypedArrayLikeAccessor},
classes::{ProxyValue, RangeValue},
expr::destructure_range,
irrt::*,
model::*,
numpy::*,
numpy_new,
stmt::exn_constructor,
structs::ndarray::NpArray,
},
symbol_resolver::SymbolValue,
toplevel::{helper::PrimDef, numpy::make_ndarray_ty},
@ -492,6 +496,10 @@ impl<'a> BuiltinBuilder<'a> {
| PrimDef::FunNpEye
| PrimDef::FunNpIdentity => self.build_ndarray_other_factory_function(prim),
PrimDef::FunNpReshape | PrimDef::FunNpTranspose => {
self.build_ndarray_view_functions(prim)
}
PrimDef::FunStr => self.build_str_function(),
PrimDef::FunFloor | PrimDef::FunFloor64 | PrimDef::FunCeil | PrimDef::FunCeil64 => {
@ -510,7 +518,9 @@ impl<'a> BuiltinBuilder<'a> {
PrimDef::FunMin | PrimDef::FunMax => self.build_min_max_function(prim),
PrimDef::FunNpMin | PrimDef::FunNpMax => self.build_np_min_max_function(prim),
PrimDef::FunNpArgmin | PrimDef::FunNpArgmax | PrimDef::FunNpMin | PrimDef::FunNpMax => {
self.build_np_max_min_function(prim)
}
PrimDef::FunNpMinimum | PrimDef::FunNpMaximum => {
self.build_np_minimum_maximum_function(prim)
@ -562,7 +572,7 @@ impl<'a> BuiltinBuilder<'a> {
match (&tld, prim.details()) {
(
TopLevelDef::Class { name, object_id, .. },
PrimDefDetails::PrimClass { name: exp_name },
PrimDefDetails::PrimClass { name: exp_name, .. },
) => {
let exp_object_id = prim.id();
assert_eq!(name, &exp_name.into());
@ -1200,9 +1210,11 @@ impl<'a> BuiltinBuilder<'a> {
&[(self.ndarray_factory_fn_shape_arg_tvar.ty, "shape")],
Box::new(move |ctx, obj, fun, args, generator| {
let func = match prim {
PrimDef::FunNpNDArray | PrimDef::FunNpEmpty => gen_ndarray_empty,
PrimDef::FunNpZeros => gen_ndarray_zeros,
PrimDef::FunNpOnes => gen_ndarray_ones,
PrimDef::FunNpNDArray | PrimDef::FunNpEmpty => {
numpy_new::factory::gen_ndarray_empty
}
PrimDef::FunNpZeros => numpy_new::factory::gen_ndarray_zeros,
PrimDef::FunNpOnes => numpy_new::factory::gen_ndarray_ones,
_ => unreachable!(),
};
func(ctx, &obj, fun, &args, generator).map(|val| Some(val.as_basic_value_enum()))
@ -1270,7 +1282,7 @@ impl<'a> BuiltinBuilder<'a> {
// type variable
&[(self.list_int32, "shape"), (tv.ty, "fill_value")],
Box::new(move |ctx, obj, fun, args, generator| {
gen_ndarray_full(ctx, &obj, fun, &args, generator)
numpy_new::factory::gen_ndarray_full(ctx, &obj, fun, &args, generator)
.map(|val| Some(val.as_basic_value_enum()))
}),
)
@ -1325,6 +1337,89 @@ impl<'a> BuiltinBuilder<'a> {
}
}
// Build functions related to NDArray views
fn build_ndarray_view_functions(&mut self, prim: PrimDef) -> TopLevelDef {
debug_assert_prim_is_allowed(prim, &[PrimDef::FunNpReshape, PrimDef::FunNpTranspose]);
match prim {
PrimDef::FunNpReshape => {
let new_ndim_ty = self.unifier.get_fresh_var(Some("NewNDim".into()), None);
let returned_ndarray_ty = make_ndarray_ty(
self.unifier,
self.primitives,
Some(self.ndarray_dtype_tvar.ty),
Some(new_ndim_ty.ty),
);
create_fn_by_codegen(
self.unifier,
&into_var_map([self.ndarray_dtype_tvar, self.ndarray_ndims_tvar, new_ndim_ty]),
prim.name(),
returned_ndarray_ty,
&[
(self.primitives.ndarray, "array"),
(self.ndarray_factory_fn_shape_arg_tvar.ty, "shape"),
],
Box::new(|ctx, obj, fun, args, generator| {
numpy_new::view::gen_ndarray_reshape(ctx, &obj, fun, &args, generator)
.map(|val| Some(val.as_basic_value_enum()))
}),
)
}
PrimDef::FunNpTranspose => {
/*
# NDim has to be known (for checking axes's len)
def np_transpose(
array: NDArray[DType, NDim],
axes: Optional[List[int32]] = None,
) -> NDArray[DType, NDim]
*/
// TODO: Allow tuples (or even general iterables in the very far future) on `axes`
let optional_axes_ty = self
.unifier
.subst(
self.primitives.option,
&VarMap::from([(self.option_tvar.id, self.list_int32)]),
)
.unwrap();
TopLevelDef::Function {
name: prim.name().into(),
simple_name: prim.simple_name().into(),
signature: self.unifier.add_ty(TypeEnum::TFunc(FunSignature {
args: vec![
FuncArg {
name: "array".into(),
ty: self.primitives.ndarray,
default_value: None,
},
FuncArg {
name: "axes".into(),
ty: optional_axes_ty,
default_value: Some(SymbolValue::OptionNone),
},
],
ret: self.primitives.ndarray,
vars: VarMap::default(),
})),
var_id: vec![self.ndarray_ndims_tvar.id],
instance_to_symbol: HashMap::default(),
instance_to_stmt: HashMap::default(),
resolver: None,
codegen_callback: Some(Arc::new(GenCall::new(Box::new(
|ctx, obj, fun, args, generator| {
numpy_new::view::gen_ndarray_transpose(ctx, &obj, fun, &args, generator)
.map(|val| Some(val.as_basic_value_enum()))
},
)))),
loc: None,
}
}
_ => unreachable!(),
}
}
/// Build the `str()` function.
fn build_str_function(&mut self) -> TopLevelDef {
let prim = PrimDef::FunStr;
@ -1462,51 +1557,12 @@ impl<'a> BuiltinBuilder<'a> {
}
}
TypeEnum::TObj { obj_id, .. } if *obj_id == PrimDef::NDArray.id() => {
let llvm_i32 = ctx.ctx.i32_type();
let llvm_usize = generator.get_size_type(ctx.ctx);
let sizet = generator.get_sizet(ctx.ctx);
let pndarray_model = PointerModel(StructModel(NpArray { sizet }));
let arg = NDArrayValue::from_ptr_val(
arg.into_pointer_value(),
llvm_usize,
None,
);
let ndims = arg.dim_sizes().size(ctx, generator);
ctx.make_assert(
generator,
ctx.builder
.build_int_compare(
IntPredicate::NE,
ndims,
llvm_usize.const_zero(),
"",
)
.unwrap(),
"0:TypeError",
&format!("{name}() of unsized object", name = prim.name()),
[None, None, None],
ctx.current_loc,
);
let len = unsafe {
arg.dim_sizes().get_typed_unchecked(
ctx,
generator,
&llvm_usize.const_zero(),
None,
)
};
if len.get_type().get_bit_width() == 32 {
Some(len.into())
} else {
Some(
ctx.builder
.build_int_truncate(len, llvm_i32, "len")
.map(Into::into)
.unwrap(),
)
}
let ndarray = pndarray_model.review_value(ctx.ctx, arg).unwrap();
let len = call_nac3_ndarray_len(generator, ctx, ndarray);
Some(len.value.as_basic_value_enum())
}
_ => unreachable!(),
}
@ -1555,39 +1611,45 @@ impl<'a> BuiltinBuilder<'a> {
}
}
/// Build the functions `np_min()` and `np_max()`.
fn build_np_min_max_function(&mut self, prim: PrimDef) -> TopLevelDef {
debug_assert_prim_is_allowed(prim, &[PrimDef::FunNpMin, PrimDef::FunNpMax]);
/// Build the functions `np_max()`, `np_min()`, `np_argmax()` and `np_argmin()`
/// Calls `call_numpy_max_min` with the function name
fn build_np_max_min_function(&mut self, prim: PrimDef) -> TopLevelDef {
debug_assert_prim_is_allowed(
prim,
&[PrimDef::FunNpArgmin, PrimDef::FunNpArgmax, PrimDef::FunNpMin, PrimDef::FunNpMax],
);
let ret_ty = self.unifier.get_fresh_var(Some("R".into()), None);
let var_map = self
.num_or_ndarray_var_map
.clone()
.into_iter()
.chain(once((ret_ty.id, ret_ty.ty)))
.collect::<IndexMap<_, _>>();
let (var_map, ret_ty) = match prim {
PrimDef::FunNpArgmax | PrimDef::FunNpArgmin => {
(self.num_or_ndarray_var_map.clone(), self.primitives.int64)
}
PrimDef::FunNpMax | PrimDef::FunNpMin => {
let ret_ty = self.unifier.get_fresh_var(Some("R".into()), None);
let var_map = self
.num_or_ndarray_var_map
.clone()
.into_iter()
.chain(once((ret_ty.id, ret_ty.ty)))
.collect::<IndexMap<_, _>>();
(var_map, ret_ty.ty)
}
_ => unreachable!(),
};
create_fn_by_codegen(
self.unifier,
&var_map,
prim.name(),
ret_ty.ty,
&[(self.float_or_ndarray_ty.ty, "a")],
ret_ty,
&[(self.num_or_ndarray_ty.ty, "a")],
Box::new(move |ctx, _, fun, args, generator| {
let a_ty = fun.0.args[0].ty;
let a = args[0].1.clone().to_basic_value_enum(ctx, generator, a_ty)?;
let func = match prim {
PrimDef::FunNpMin => builtin_fns::call_numpy_min,
PrimDef::FunNpMax => builtin_fns::call_numpy_max,
_ => unreachable!(),
};
Ok(Some(func(generator, ctx, (a_ty, a))?))
Ok(Some(builtin_fns::call_numpy_max_min(generator, ctx, (a_ty, a), prim.name())?))
}),
)
}
/// Build the functions `np_minimum()` and `np_maximum()`.
fn build_np_minimum_maximum_function(&mut self, prim: PrimDef) -> TopLevelDef {
debug_assert_prim_is_allowed(prim, &[PrimDef::FunNpMinimum, PrimDef::FunNpMaximum]);

View File

@ -766,6 +766,7 @@ impl TopLevelComposer {
let target_ty = get_type_from_type_annotation_kinds(
&temp_def_list,
unifier,
primitives,
&def,
&mut subst_list,
)?;
@ -936,6 +937,7 @@ impl TopLevelComposer {
let ty = get_type_from_type_annotation_kinds(
temp_def_list.as_ref(),
unifier,
primitives_store,
&type_annotation,
&mut None,
)?;
@ -1002,6 +1004,7 @@ impl TopLevelComposer {
get_type_from_type_annotation_kinds(
&temp_def_list,
unifier,
primitives_store,
&return_ty_annotation,
&mut None,
)?
@ -1622,6 +1625,7 @@ impl TopLevelComposer {
let self_type = get_type_from_type_annotation_kinds(
&def_list,
unifier,
primitives_ty,
&make_self_type_annotation(type_vars, *object_id),
&mut None,
)?;
@ -1803,7 +1807,11 @@ impl TopLevelComposer {
let ty_ann = make_self_type_annotation(type_vars, *class_id);
let self_ty = get_type_from_type_annotation_kinds(
&def_list, unifier, &ty_ann, &mut None,
&def_list,
unifier,
primitives_ty,
&ty_ann,
&mut None,
)?;
vars.extend(type_vars.iter().map(|ty| {
let TypeEnum::TVar { id, .. } = &*unifier.get_ty(*ty) else {

View File

@ -46,6 +46,8 @@ pub enum PrimDef {
FunNpArray,
FunNpEye,
FunNpIdentity,
FunNpReshape,
FunNpTranspose,
FunRound,
FunRound64,
FunNpRound,
@ -62,9 +64,11 @@ pub enum PrimDef {
FunMin,
FunNpMin,
FunNpMinimum,
FunNpArgmin,
FunMax,
FunNpMax,
FunNpMaximum,
FunNpArgmax,
FunAbs,
FunNpIsNan,
FunNpIsInf,
@ -111,7 +115,7 @@ pub enum PrimDef {
/// Associated details of a [`PrimDef`]
pub enum PrimDefDetails {
PrimFunction { name: &'static str, simple_name: &'static str },
PrimClass { name: &'static str },
PrimClass { name: &'static str, get_ty_fn: fn(&PrimitiveStore) -> Type },
}
impl PrimDef {
@ -153,15 +157,17 @@ impl PrimDef {
#[must_use]
pub fn name(&self) -> &'static str {
match self.details() {
PrimDefDetails::PrimFunction { name, .. } | PrimDefDetails::PrimClass { name } => name,
PrimDefDetails::PrimFunction { name, .. } | PrimDefDetails::PrimClass { name, .. } => {
name
}
}
}
/// Get the associated details of this [`PrimDef`]
#[must_use]
pub fn details(self) -> PrimDefDetails {
fn class(name: &'static str) -> PrimDefDetails {
PrimDefDetails::PrimClass { name }
fn class(name: &'static str, get_ty_fn: fn(&PrimitiveStore) -> Type) -> PrimDefDetails {
PrimDefDetails::PrimClass { name, get_ty_fn }
}
fn fun(name: &'static str, simple_name: Option<&'static str>) -> PrimDefDetails {
@ -169,22 +175,22 @@ impl PrimDef {
}
match self {
PrimDef::Int32 => class("int32"),
PrimDef::Int64 => class("int64"),
PrimDef::Float => class("float"),
PrimDef::Bool => class("bool"),
PrimDef::None => class("none"),
PrimDef::Range => class("range"),
PrimDef::Str => class("str"),
PrimDef::Exception => class("Exception"),
PrimDef::UInt32 => class("uint32"),
PrimDef::UInt64 => class("uint64"),
PrimDef::Option => class("Option"),
PrimDef::Int32 => class("int32", |primitives| primitives.int32),
PrimDef::Int64 => class("int64", |primitives| primitives.int64),
PrimDef::Float => class("float", |primitives| primitives.float),
PrimDef::Bool => class("bool", |primitives| primitives.bool),
PrimDef::None => class("none", |primitives| primitives.none),
PrimDef::Range => class("range", |primitives| primitives.range),
PrimDef::Str => class("str", |primitives| primitives.str),
PrimDef::Exception => class("Exception", |primitives| primitives.exception),
PrimDef::UInt32 => class("uint32", |primitives| primitives.uint32),
PrimDef::UInt64 => class("uint64", |primitives| primitives.uint64),
PrimDef::Option => class("Option", |primitives| primitives.option),
PrimDef::OptionIsSome => fun("Option.is_some", Some("is_some")),
PrimDef::OptionIsNone => fun("Option.is_none", Some("is_none")),
PrimDef::OptionUnwrap => fun("Option.unwrap", Some("unwrap")),
PrimDef::List => class("list"),
PrimDef::NDArray => class("ndarray"),
PrimDef::List => class("list", |primitives| primitives.list),
PrimDef::NDArray => class("ndarray", |primitives| primitives.ndarray),
PrimDef::NDArrayCopy => fun("ndarray.copy", Some("copy")),
PrimDef::NDArrayFill => fun("ndarray.fill", Some("fill")),
PrimDef::FunInt32 => fun("int32", None),
@ -200,6 +206,8 @@ impl PrimDef {
PrimDef::FunNpArray => fun("np_array", None),
PrimDef::FunNpEye => fun("np_eye", None),
PrimDef::FunNpIdentity => fun("np_identity", None),
PrimDef::FunNpReshape => fun("np_reshape", None),
PrimDef::FunNpTranspose => fun("np_transpose", None),
PrimDef::FunRound => fun("round", None),
PrimDef::FunRound64 => fun("round64", None),
PrimDef::FunNpRound => fun("np_round", None),
@ -216,9 +224,11 @@ impl PrimDef {
PrimDef::FunMin => fun("min", None),
PrimDef::FunNpMin => fun("np_min", None),
PrimDef::FunNpMinimum => fun("np_minimum", None),
PrimDef::FunNpArgmin => fun("np_argmin", None),
PrimDef::FunMax => fun("max", None),
PrimDef::FunNpMax => fun("np_max", None),
PrimDef::FunNpMaximum => fun("np_maximum", None),
PrimDef::FunNpArgmax => fun("np_argmax", None),
PrimDef::FunAbs => fun("abs", None),
PrimDef::FunNpIsNan => fun("np_isnan", None),
PrimDef::FunNpIsInf => fun("np_isinf", None),

View File

@ -5,7 +5,7 @@ expression: res_vec
[
"Class {\nname: \"Generic_A\",\nancestors: [\"Generic_A[V]\", \"B\"],\nfields: [\"aa\", \"a\"],\nmethods: [(\"__init__\", \"fn[[], none]\"), (\"foo\", \"fn[[b:T], none]\"), (\"fun\", \"fn[[a:int32], V]\")],\ntype_vars: [\"V\"]\n}\n",
"Function {\nname: \"Generic_A.__init__\",\nsig: \"fn[[], none]\",\nvar_id: []\n}\n",
"Function {\nname: \"Generic_A.fun\",\nsig: \"fn[[a:int32], V]\",\nvar_id: [TypeVarId(245)]\n}\n",
"Function {\nname: \"Generic_A.fun\",\nsig: \"fn[[a:int32], V]\",\nvar_id: [TypeVarId(248)]\n}\n",
"Class {\nname: \"B\",\nancestors: [\"B\"],\nfields: [\"aa\"],\nmethods: [(\"__init__\", \"fn[[], none]\"), (\"foo\", \"fn[[b:T], none]\")],\ntype_vars: []\n}\n",
"Function {\nname: \"B.__init__\",\nsig: \"fn[[], none]\",\nvar_id: []\n}\n",
"Function {\nname: \"B.foo\",\nsig: \"fn[[b:T], none]\",\nvar_id: []\n}\n",

View File

@ -7,7 +7,7 @@ expression: res_vec
"Function {\nname: \"A.__init__\",\nsig: \"fn[[t:T], none]\",\nvar_id: []\n}\n",
"Function {\nname: \"A.fun\",\nsig: \"fn[[a:int32, b:T], list[virtual[B[bool]]]]\",\nvar_id: []\n}\n",
"Function {\nname: \"A.foo\",\nsig: \"fn[[c:C], none]\",\nvar_id: []\n}\n",
"Class {\nname: \"B\",\nancestors: [\"B[typevar234]\", \"A[float]\"],\nfields: [\"a\", \"b\", \"c\", \"d\"],\nmethods: [(\"__init__\", \"fn[[], none]\"), (\"fun\", \"fn[[a:int32, b:T], list[virtual[B[bool]]]]\"), (\"foo\", \"fn[[c:C], none]\")],\ntype_vars: [\"typevar234\"]\n}\n",
"Class {\nname: \"B\",\nancestors: [\"B[typevar237]\", \"A[float]\"],\nfields: [\"a\", \"b\", \"c\", \"d\"],\nmethods: [(\"__init__\", \"fn[[], none]\"), (\"fun\", \"fn[[a:int32, b:T], list[virtual[B[bool]]]]\"), (\"foo\", \"fn[[c:C], none]\")],\ntype_vars: [\"typevar237\"]\n}\n",
"Function {\nname: \"B.__init__\",\nsig: \"fn[[], none]\",\nvar_id: []\n}\n",
"Function {\nname: \"B.fun\",\nsig: \"fn[[a:int32, b:T], list[virtual[B[bool]]]]\",\nvar_id: []\n}\n",
"Class {\nname: \"C\",\nancestors: [\"C\", \"B[bool]\", \"A[float]\"],\nfields: [\"a\", \"b\", \"c\", \"d\", \"e\"],\nmethods: [(\"__init__\", \"fn[[], none]\"), (\"fun\", \"fn[[a:int32, b:T], list[virtual[B[bool]]]]\"), (\"foo\", \"fn[[c:C], none]\")],\ntype_vars: []\n}\n",

View File

@ -5,8 +5,8 @@ expression: res_vec
[
"Function {\nname: \"foo\",\nsig: \"fn[[a:list[int32], b:tuple[T, float]], A[B, bool]]\",\nvar_id: []\n}\n",
"Class {\nname: \"A\",\nancestors: [\"A[T, V]\"],\nfields: [\"a\", \"b\"],\nmethods: [(\"__init__\", \"fn[[v:V], none]\"), (\"fun\", \"fn[[a:T], V]\")],\ntype_vars: [\"T\", \"V\"]\n}\n",
"Function {\nname: \"A.__init__\",\nsig: \"fn[[v:V], none]\",\nvar_id: [TypeVarId(247)]\n}\n",
"Function {\nname: \"A.fun\",\nsig: \"fn[[a:T], V]\",\nvar_id: [TypeVarId(252)]\n}\n",
"Function {\nname: \"A.__init__\",\nsig: \"fn[[v:V], none]\",\nvar_id: [TypeVarId(250)]\n}\n",
"Function {\nname: \"A.fun\",\nsig: \"fn[[a:T], V]\",\nvar_id: [TypeVarId(255)]\n}\n",
"Function {\nname: \"gfun\",\nsig: \"fn[[a:A[list[float], int32]], none]\",\nvar_id: []\n}\n",
"Class {\nname: \"B\",\nancestors: [\"B\"],\nfields: [],\nmethods: [(\"__init__\", \"fn[[], none]\")],\ntype_vars: []\n}\n",
"Function {\nname: \"B.__init__\",\nsig: \"fn[[], none]\",\nvar_id: []\n}\n",

View File

@ -3,7 +3,7 @@ source: nac3core/src/toplevel/test.rs
expression: res_vec
---
[
"Class {\nname: \"A\",\nancestors: [\"A[typevar233, typevar234]\"],\nfields: [\"a\", \"b\"],\nmethods: [(\"__init__\", \"fn[[a:A[float, bool], b:B], none]\"), (\"fun\", \"fn[[a:A[float, bool]], A[bool, int32]]\")],\ntype_vars: [\"typevar233\", \"typevar234\"]\n}\n",
"Class {\nname: \"A\",\nancestors: [\"A[typevar236, typevar237]\"],\nfields: [\"a\", \"b\"],\nmethods: [(\"__init__\", \"fn[[a:A[float, bool], b:B], none]\"), (\"fun\", \"fn[[a:A[float, bool]], A[bool, int32]]\")],\ntype_vars: [\"typevar236\", \"typevar237\"]\n}\n",
"Function {\nname: \"A.__init__\",\nsig: \"fn[[a:A[float, bool], b:B], none]\",\nvar_id: []\n}\n",
"Function {\nname: \"A.fun\",\nsig: \"fn[[a:A[float, bool]], A[bool, int32]]\",\nvar_id: []\n}\n",
"Class {\nname: \"B\",\nancestors: [\"B\", \"A[int64, bool]\"],\nfields: [\"a\", \"b\"],\nmethods: [(\"__init__\", \"fn[[], none]\"), (\"fun\", \"fn[[a:A[float, bool]], A[bool, int32]]\"), (\"foo\", \"fn[[b:B], B]\"), (\"bar\", \"fn[[a:A[list[B], int32]], tuple[A[virtual[A[B, int32]], bool], B]]\")],\ntype_vars: []\n}\n",

View File

@ -6,12 +6,12 @@ expression: res_vec
"Class {\nname: \"A\",\nancestors: [\"A\"],\nfields: [\"a\"],\nmethods: [(\"__init__\", \"fn[[], none]\"), (\"fun\", \"fn[[b:B], none]\"), (\"foo\", \"fn[[a:T, b:V], none]\")],\ntype_vars: []\n}\n",
"Function {\nname: \"A.__init__\",\nsig: \"fn[[], none]\",\nvar_id: []\n}\n",
"Function {\nname: \"A.fun\",\nsig: \"fn[[b:B], none]\",\nvar_id: []\n}\n",
"Function {\nname: \"A.foo\",\nsig: \"fn[[a:T, b:V], none]\",\nvar_id: [TypeVarId(253)]\n}\n",
"Function {\nname: \"A.foo\",\nsig: \"fn[[a:T, b:V], none]\",\nvar_id: [TypeVarId(256)]\n}\n",
"Class {\nname: \"B\",\nancestors: [\"B\", \"C\", \"A\"],\nfields: [\"a\"],\nmethods: [(\"__init__\", \"fn[[], none]\"), (\"fun\", \"fn[[b:B], none]\"), (\"foo\", \"fn[[a:T, b:V], none]\")],\ntype_vars: []\n}\n",
"Function {\nname: \"B.__init__\",\nsig: \"fn[[], none]\",\nvar_id: []\n}\n",
"Class {\nname: \"C\",\nancestors: [\"C\", \"A\"],\nfields: [\"a\"],\nmethods: [(\"__init__\", \"fn[[], none]\"), (\"fun\", \"fn[[b:B], none]\"), (\"foo\", \"fn[[a:T, b:V], none]\")],\ntype_vars: []\n}\n",
"Function {\nname: \"C.__init__\",\nsig: \"fn[[], none]\",\nvar_id: []\n}\n",
"Function {\nname: \"C.fun\",\nsig: \"fn[[b:B], none]\",\nvar_id: []\n}\n",
"Function {\nname: \"foo\",\nsig: \"fn[[a:A], none]\",\nvar_id: []\n}\n",
"Function {\nname: \"ff\",\nsig: \"fn[[a:T], V]\",\nvar_id: [TypeVarId(261)]\n}\n",
"Function {\nname: \"ff\",\nsig: \"fn[[a:T], V]\",\nvar_id: [TypeVarId(264)]\n}\n",
]

View File

@ -1,8 +1,9 @@
use super::*;
use crate::symbol_resolver::SymbolValue;
use crate::toplevel::helper::PrimDef;
use crate::toplevel::helper::{PrimDef, PrimDefDetails};
use crate::typecheck::typedef::VarMap;
use nac3parser::ast::Constant;
use strum::IntoEnumIterator;
#[derive(Clone, Debug)]
pub enum TypeAnnotation {
@ -357,6 +358,7 @@ pub fn parse_ast_to_type_annotation_kinds<T, S: std::hash::BuildHasher + Clone>(
pub fn get_type_from_type_annotation_kinds(
top_level_defs: &[Arc<RwLock<TopLevelDef>>],
unifier: &mut Unifier,
primitives: &PrimitiveStore,
ann: &TypeAnnotation,
subst_list: &mut Option<Vec<Type>>,
) -> Result<Type, HashSet<String>> {
@ -379,100 +381,141 @@ pub fn get_type_from_type_annotation_kinds(
let param_ty = params
.iter()
.map(|x| {
get_type_from_type_annotation_kinds(top_level_defs, unifier, x, subst_list)
get_type_from_type_annotation_kinds(
top_level_defs,
unifier,
primitives,
x,
subst_list,
)
})
.collect::<Result<Vec<_>, _>>()?;
let subst = {
// check for compatible range
// TODO: if allow type var to be applied(now this disallowed in the parse_to_type_annotation), need more check
let mut result = VarMap::new();
for (tvar, p) in type_vars.iter().zip(param_ty) {
match unifier.get_ty(*tvar).as_ref() {
TypeEnum::TVar {
id,
range,
fields: None,
name,
loc,
is_const_generic: false,
} => {
let ok: bool = {
// create a temp type var and unify to check compatibility
p == *tvar || {
let temp = unifier.get_fresh_var_with_range(
range.as_slice(),
*name,
*loc,
);
unifier.unify(temp.ty, p).is_ok()
}
};
if ok {
result.insert(*id, p);
} else {
return Err(HashSet::from([format!(
"cannot apply type {} to type variable with id {:?}",
unifier.internal_stringify(
p,
&mut |id| format!("class{id}"),
&mut |id| format!("typevar{id}"),
&mut None
),
*id
)]));
}
}
let ty = if let Some(prim_def) = PrimDef::iter().find(|prim| prim.id() == *obj_id) {
// Primitive TopLevelDefs do not contain all fields that are present in their Type
// counterparts, so directly perform subst on the Type instead.
TypeEnum::TVar { id, range, name, loc, is_const_generic: true, .. } => {
let ty = range[0];
let ok: bool = {
// create a temp type var and unify to check compatibility
p == *tvar || {
let temp = unifier.get_fresh_const_generic_var(ty, *name, *loc);
unifier.unify(temp.ty, p).is_ok()
}
};
if ok {
result.insert(*id, p);
} else {
return Err(HashSet::from([format!(
"cannot apply type {} to type variable {}",
unifier.stringify(p),
name.unwrap_or_else(|| format!("typevar{id}").into()),
)]));
}
}
let PrimDefDetails::PrimClass { get_ty_fn, .. } = prim_def.details() else {
unreachable!()
};
_ => unreachable!("must be generic type var"),
let base_ty = get_ty_fn(primitives);
let params =
if let TypeEnum::TObj { params, .. } = &*unifier.get_ty_immutable(base_ty) {
params.clone()
} else {
unreachable!()
};
unifier
.subst(
get_ty_fn(primitives),
&params
.iter()
.zip(param_ty)
.map(|(obj_tv, param)| (*obj_tv.0, param))
.collect(),
)
.unwrap_or(base_ty)
} else {
let subst = {
// check for compatible range
// TODO: if allow type var to be applied(now this disallowed in the parse_to_type_annotation), need more check
let mut result = VarMap::new();
for (tvar, p) in type_vars.iter().zip(param_ty) {
match unifier.get_ty(*tvar).as_ref() {
TypeEnum::TVar {
id,
range,
fields: None,
name,
loc,
is_const_generic: false,
} => {
let ok: bool = {
// create a temp type var and unify to check compatibility
p == *tvar || {
let temp = unifier.get_fresh_var_with_range(
range.as_slice(),
*name,
*loc,
);
unifier.unify(temp.ty, p).is_ok()
}
};
if ok {
result.insert(*id, p);
} else {
return Err(HashSet::from([format!(
"cannot apply type {} to type variable with id {:?}",
unifier.internal_stringify(
p,
&mut |id| format!("class{id}"),
&mut |id| format!("typevar{id}"),
&mut None
),
*id
)]));
}
}
TypeEnum::TVar {
id, range, name, loc, is_const_generic: true, ..
} => {
let ty = range[0];
let ok: bool = {
// create a temp type var and unify to check compatibility
p == *tvar || {
let temp =
unifier.get_fresh_const_generic_var(ty, *name, *loc);
unifier.unify(temp.ty, p).is_ok()
}
};
if ok {
result.insert(*id, p);
} else {
return Err(HashSet::from([format!(
"cannot apply type {} to type variable {}",
unifier.stringify(p),
name.unwrap_or_else(|| format!("typevar{id}").into()),
)]));
}
}
_ => unreachable!("must be generic type var"),
}
}
result
};
// Class Attributes keep a copy with Class Definition and are not added to objects
let mut tobj_fields = methods
.iter()
.map(|(name, ty, _)| {
let subst_ty = unifier.subst(*ty, &subst).unwrap_or(*ty);
// methods are immutable
(*name, (subst_ty, false))
})
.collect::<HashMap<_, _>>();
tobj_fields.extend(fields.iter().map(|(name, ty, mutability)| {
let subst_ty = unifier.subst(*ty, &subst).unwrap_or(*ty);
(*name, (subst_ty, *mutability))
}));
let need_subst = !subst.is_empty();
let ty = unifier.add_ty(TypeEnum::TObj {
obj_id: *obj_id,
fields: tobj_fields,
params: subst,
});
if need_subst {
if let Some(wl) = subst_list.as_mut() {
wl.push(ty);
}
}
result
ty
};
// Class Attributes keep a copy with Class Definition and are not added to objects
let mut tobj_fields = methods
.iter()
.map(|(name, ty, _)| {
let subst_ty = unifier.subst(*ty, &subst).unwrap_or(*ty);
// methods are immutable
(*name, (subst_ty, false))
})
.collect::<HashMap<_, _>>();
tobj_fields.extend(fields.iter().map(|(name, ty, mutability)| {
let subst_ty = unifier.subst(*ty, &subst).unwrap_or(*ty);
(*name, (subst_ty, *mutability))
}));
let need_subst = !subst.is_empty();
let ty = unifier.add_ty(TypeEnum::TObj {
obj_id: *obj_id,
fields: tobj_fields,
params: subst,
});
if need_subst {
if let Some(wl) = subst_list.as_mut() {
wl.push(ty);
}
}
Ok(ty)
}
TypeAnnotation::Primitive(ty) | TypeAnnotation::TypeVar(ty) => Ok(*ty),
@ -490,6 +533,7 @@ pub fn get_type_from_type_annotation_kinds(
let ty = get_type_from_type_annotation_kinds(
top_level_defs,
unifier,
primitives,
ty.as_ref(),
subst_list,
)?;
@ -499,7 +543,13 @@ pub fn get_type_from_type_annotation_kinds(
let tys = tys
.iter()
.map(|x| {
get_type_from_type_annotation_kinds(top_level_defs, unifier, x, subst_list)
get_type_from_type_annotation_kinds(
top_level_defs,
unifier,
primitives,
x,
subst_list,
)
})
.collect::<Result<Vec<_>, _>>()?;
Ok(unifier.add_ty(TypeEnum::TTuple { ty: tys }))

View File

@ -398,7 +398,10 @@ impl<'a> Fold<()> for Inferencer<'a> {
}
if let Some(exc) = exc {
self.virtual_checks.push((
exc.custom.unwrap(),
match &*self.unifier.get_ty(exc.custom.unwrap()) {
TypeEnum::TFunc(sign) => sign.ret,
_ => exc.custom.unwrap(),
},
self.primitives.exception,
exc.location,
));
@ -1387,6 +1390,55 @@ impl<'a> Inferencer<'a> {
}));
}
// Handle `np.reshape(<array>, <shape>)`
if ["np_reshape".into()].contains(id) && args.len() == 2 {
// Extract arguments
let array_expr = args.remove(0);
let shape_expr = args.remove(0);
// Fold `<array>`
let array = self.fold_expr(array_expr)?;
let array_ty = array.custom.unwrap();
let (array_dtype, _) = unpack_ndarray_var_tys(self.unifier, array_ty);
// Fold `<shape>`
let (target_ndims, target_shape) =
self.fold_numpy_function_call_shape_argument(*id, 0, shape_expr)?;
let target_shape_ty = target_shape.custom.unwrap();
// ... and deduce the return type of the call
let target_ndims_ty =
self.unifier.get_fresh_literal(vec![SymbolValue::U64(target_ndims)], None);
let ret = make_ndarray_ty(
self.unifier,
self.primitives,
Some(array_dtype),
Some(target_ndims_ty),
);
let custom = self.unifier.add_ty(TypeEnum::TFunc(FunSignature {
args: vec![
FuncArg { name: "array".into(), ty: array_ty, default_value: None },
FuncArg { name: "shape".into(), ty: target_shape_ty, default_value: None },
],
ret,
vars: VarMap::new(),
}));
return Ok(Some(Located {
location,
custom: Some(ret),
node: ExprKind::Call {
func: Box::new(Located {
custom: Some(custom),
location: func.location,
node: ExprKind::Name { id: *id, ctx: *ctx },
}),
args: vec![array, target_shape],
keywords: vec![],
},
}));
}
// 2-argument ndarray n-dimensional creation functions
if id == &"np_full".into() && args.len() == 2 {
let ExprKind::List { elts, .. } = &args[0].node else {

View File

@ -107,8 +107,25 @@ uint32_t __nac3_personality(uint32_t state, uint32_t exception_object, uint32_t
__builtin_unreachable();
}
uint32_t __nac3_raise(uint32_t state, uint32_t exception_object, uint32_t context) {
printf("__nac3_raise(state: %u, exception_object: %u, context: %u)\n", state, exception_object, context);
// See `struct Exception<'a>` in
// https://github.com/m-labs/artiq/blob/master/artiq/firmware/libeh/eh_artiq.rs
struct Exception {
uint32_t id;
struct cslice file;
uint32_t line;
uint32_t column;
struct cslice function;
struct cslice message;
int64_t param[3];
};
uint32_t __nac3_raise(struct Exception* e) {
printf("__nac3_raise called. Exception details:\n");
printf(" ID: %lld\n", e->id);
printf(" Location: %*s:%lld:%lld\n" , e->file.len, (const char*) e->file.data, e->line, e->column);
printf(" Function: %*s\n" , e->function.len, (const char*) e->function.data);
printf(" Message: \"%*s\"\n" , e->message.len, (const char*) e->message.data);
printf(" Params: {0}=%lld, {1}=%lld, {2}=%lld\n", e->param[0], e->param[1], e->param[2]);
exit(101);
__builtin_unreachable();
}

View File

@ -167,7 +167,7 @@ def patch(module):
module.ceil64 = _ceil
module.np_ceil = np.ceil
# NumPy ndarray functions
# NumPy NDArray factory functions
module.ndarray = NDArray
module.np_ndarray = np.ndarray
module.np_empty = np.empty
@ -178,13 +178,19 @@ def patch(module):
module.np_identity = np.identity
module.np_array = np.array
# NumPy view functions
module.np_reshape = np.reshape
module.np_transpose = np.transpose
# NumPy Math functions
module.np_isnan = np.isnan
module.np_isinf = np.isinf
module.np_min = np.min
module.np_minimum = np.minimum
module.np_argmin = np.argmin
module.np_max = np.max
module.np_maximum = np.maximum
module.np_argmax = np.argmax
module.np_sin = np.sin
module.np_cos = np.cos
module.np_exp = np.exp
@ -216,7 +222,7 @@ def patch(module):
module.np_hypot = np.hypot
module.np_nextafter = np.nextafter
# SciPy Math Functions
# SciPy Math functions
module.sp_spec_erf = special.erf
module.sp_spec_erfc = special.erfc
module.sp_spec_gamma = special.gamma
@ -224,15 +230,6 @@ def patch(module):
module.sp_spec_j0 = special.j0
module.sp_spec_j1 = special.j1
# NumPy NDArray Functions
module.np_ndarray = np.ndarray
module.np_empty = np.empty
module.np_zeros = np.zeros
module.np_ones = np.ones
module.np_full = np.full
module.np_eye = np.eye
module.np_identity = np.identity
def file_import(filename, prefix="file_import_"):
filename = pathlib.Path(filename)
modname = prefix + filename.stem

View File

@ -867,6 +867,13 @@ def test_ndarray_minimum_broadcast_rhs_scalar():
output_ndarray_float_2(min_x_zeros)
output_ndarray_float_2(min_x_ones)
def test_ndarray_argmin():
x = np_array([[1., 2.], [3., 4.]])
y = np_argmin(x)
output_ndarray_float_2(x)
output_int64(y)
def test_ndarray_max():
x = np_identity(2)
y = np_max(x)
@ -910,6 +917,13 @@ def test_ndarray_maximum_broadcast_rhs_scalar():
output_ndarray_float_2(max_x_zeros)
output_ndarray_float_2(max_x_ones)
def test_ndarray_argmax():
x = np_array([[1., 2.], [3., 4.]])
y = np_argmax(x)
output_ndarray_float_2(x)
output_int64(y)
def test_ndarray_abs():
x = np_identity(2)
y = abs(x)
@ -1524,11 +1538,13 @@ def run() -> int32:
test_ndarray_minimum_broadcast()
test_ndarray_minimum_broadcast_lhs_scalar()
test_ndarray_minimum_broadcast_rhs_scalar()
test_ndarray_argmin()
test_ndarray_max()
test_ndarray_maximum()
test_ndarray_maximum_broadcast()
test_ndarray_maximum_broadcast_lhs_scalar()
test_ndarray_maximum_broadcast_rhs_scalar()
test_ndarray_argmax()
test_ndarray_abs()
test_ndarray_isnan()
test_ndarray_isinf()

View File

@ -113,7 +113,9 @@ fn handle_typevar_definition(
x,
HashMap::new(),
)?;
get_type_from_type_annotation_kinds(def_list, unifier, &ty, &mut None)
get_type_from_type_annotation_kinds(
def_list, unifier, primitives, &ty, &mut None,
)
})
.collect::<Result<Vec<_>, _>>()?;
let loc = func.location;
@ -152,7 +154,7 @@ fn handle_typevar_definition(
HashMap::new(),
)?;
let constraint =
get_type_from_type_annotation_kinds(def_list, unifier, &ty, &mut None)?;
get_type_from_type_annotation_kinds(def_list, unifier, primitives, &ty, &mut None)?;
let loc = func.location;
Ok(unifier.get_fresh_const_generic_var(constraint, Some(generic_name), Some(loc)).ty)