From 87fc9733d641b3d6cc0ed57c1f510c020169fcf6 Mon Sep 17 00:00:00 2001 From: Sicheng Pan Date: Wed, 17 May 2023 19:49:15 -0700 Subject: [PATCH 01/24] Update flake --- flake.lock | 54 +++++++++++++++++++++++++----------------------- flake.nix | 44 ++++++++++++++++++++------------------- man/nanoarrow.Rd | 8 +++---- 3 files changed, 55 insertions(+), 51 deletions(-) diff --git a/flake.lock b/flake.lock index 6c2b5dc6e..ca5321065 100644 --- a/flake.lock +++ b/flake.lock @@ -6,26 +6,30 @@ "rust-analyzer-src": "rust-analyzer-src" }, "locked": { - "lastModified": 1678083931, - "narHash": "sha256-RO45RWYuIAej5+0x+NHzrkGJ/9p5/gUGMKFX+lSlJ2I=", + "lastModified": 1682038649, + "narHash": "sha256-HwGwWLMKdIT24xhDf+mRoCehA8yUlLmuJgS9JeMt4IM=", "owner": "nix-community", "repo": "fenix", - "rev": "51c621ea8f64dafb9d3ce6c98718ca9fee1e05bb", + "rev": "37b3a6dad6d6060bd305eb7d3628d3b476c87bb6", "type": "github" }, "original": { "owner": "nix-community", + "ref": "monthly", "repo": "fenix", "type": "github" } }, "flake-utils": { + "inputs": { + "systems": "systems" + }, "locked": { - "lastModified": 1676283394, - "narHash": "sha256-XX2f9c3iySLCw54rJ/CZs+ZK6IQy7GXNY4nSOyu2QG4=", + "lastModified": 1681202837, + "narHash": "sha256-H+Rh19JDwRtpVPAWp64F+rlEtxUWBAQW28eAi3SRSzg=", "owner": "numtide", "repo": "flake-utils", - "rev": "3db36a8b464d0c4532ba1c7dda728f4576d6d073", + "rev": "cfacdce06f30d2b68473a46042957675eebb3401", "type": "github" }, "original": { @@ -36,11 +40,11 @@ }, "nixpkgs": { "locked": { - "lastModified": 1677932085, - "narHash": "sha256-+AB4dYllWig8iO6vAiGGYl0NEgmMgGHpy9gzWJ3322g=", + "lastModified": 1684215771, + "narHash": "sha256-fsum28z+g18yreNa1Y7MPo9dtps5h1VkHfZbYQ+YPbk=", "owner": "nixos", "repo": "nixpkgs", - "rev": "3c5319ad3aa51551182ac82ea17ab1c6b0f0df89", + "rev": "963006aab35e3e8ebbf6052b6bf4ea712fdd3c28", "type": "github" }, "original": { @@ -52,11 +56,11 @@ }, "nixpkgs_2": { "locked": { - "lastModified": 1677932085, - "narHash": "sha256-+AB4dYllWig8iO6vAiGGYl0NEgmMgGHpy9gzWJ3322g=", + "lastModified": 1684215771, + "narHash": "sha256-fsum28z+g18yreNa1Y7MPo9dtps5h1VkHfZbYQ+YPbk=", "owner": "nixos", "repo": "nixpkgs", - "rev": "3c5319ad3aa51551182ac82ea17ab1c6b0f0df89", + "rev": "963006aab35e3e8ebbf6052b6bf4ea712fdd3c28", "type": "github" }, "original": { @@ -70,18 +74,17 @@ "inputs": { "fenix": "fenix", "flake-utils": "flake-utils", - "nixpkgs": "nixpkgs_2", - "rustPlatformFix": "rustPlatformFix" + "nixpkgs": "nixpkgs_2" } }, "rust-analyzer-src": { "flake": false, "locked": { - "lastModified": 1678033668, - "narHash": "sha256-Njlus+vY3N++qWE0JXrGjwcXY2QDFuOV/7NruBBMETY=", + "lastModified": 1684145961, + "narHash": "sha256-Ms99ML1P53EC50TnznmV55QwhOJtql75BbXfyiGuFvU=", "owner": "rust-lang", "repo": "rust-analyzer", - "rev": "0a956ec9326eca09725d64d9f1b63896f93505d1", + "rev": "2f8cd66fb4c98026d2bdbdf17270e3472e1ca42a", "type": "github" }, "original": { @@ -91,19 +94,18 @@ "type": "github" } }, - "rustPlatformFix": { + "systems": { "locked": { - "lastModified": 1677984525, - "narHash": "sha256-SEb2MPuvZkYlVaSkl60yzRuxhnursc32UGqlV4l/TvM=", - "owner": "winterqt", - "repo": "nixpkgs", - "rev": "798e26aff817d3a227b86f4c31e4adb6ddaf4448", + "lastModified": 1681028828, + "narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=", + "owner": "nix-systems", + "repo": "default", + "rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e", "type": "github" }, "original": { - "owner": "winterqt", - "ref": "import-cargo-lock-git-dep-workspace-inheritance", - "repo": "nixpkgs", + "owner": "nix-systems", + "repo": "default", "type": "github" } } diff --git a/flake.nix b/flake.nix index 78ed56ea3..da5ed2697 100644 --- a/flake.nix +++ b/flake.nix @@ -1,19 +1,27 @@ { inputs = { - fenix.url = "github:nix-community/fenix"; + fenix.url = "github:nix-community/fenix/monthly"; flake-utils.url = "github:numtide/flake-utils"; nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable"; - rustPlatformFix.url = - "github:winterqt/nixpkgs/import-cargo-lock-git-dep-workspace-inheritance"; }; - outputs = { self, fenix, flake-utils, nixpkgs, rustPlatformFix }: + outputs = { self, fenix, flake-utils, nixpkgs }: flake-utils.lib.eachDefaultSystem (system: let + pkgs = nixpkgs.legacyPackages.${system}; rustNightly = fenix.packages.${system}.complete; - pkgs = nixpkgs.legacyPackages.${system}.extend (final: prev: { - inherit (rustPlatformFix.legacyPackages.${system}) rustPlatform; - }); + rdeps = with pkgs; [ + curl + fontconfig + fribidi + harfbuzz + libjpeg + libpng + libtiff + libxml2 + openssl + pkg-config + ]; # Build r-polars from source rpolars = pkgs.rPackages.buildRPackage { name = "polars"; @@ -21,14 +29,12 @@ cargoDeps = pkgs.rustPlatform.importCargoLock { lockFile = "${self}/${rpolars.cargoRoot}/Cargo.lock"; outputHashes = { - "arrow2-0.16.0" = - "sha256-Ac/DhiLKd16ffBmmZXK2ph7gWrm/2YgioOclSpzTMx8="; + "arrow2-0.17.0" = "sha256-c3g7SjMWOpyurn/iZWjLdLWeywl+kmFzY25pCM5S3AA="; "extendr-api-0.4.0" = - "sha256-HOglEF9PLLV12uP3gWr/6pSZFfn38I+ATcJPBbGzpJI="; + "sha256-tbA8+aaGz2p71BfPSgPBRxqwgD+XHGoSrMfGM/RKZHo="; "jsonpath_lib-0.3.0" = "sha256-NKszYpDGG8VxfZSMbsTlzcMGFHBOUeFojNw4P2wM3qk="; - "polars-0.27.2" = - "sha256-8FBAcs5dh0EmeNmguUH4FDS+GVFRimX39nX/vyk6wMk="; + "polars-0.28.0" = "sha256-QNg9cIfeACiKSV4Hr7KC0dG4CQVzCSxxNycsmcmOJEk="; }; }; cargoRoot = "src/rust"; @@ -37,21 +43,17 @@ ++ pkgs.lib.singleton rustNightly.toolchain; }; # Create R development environment with r-polars and other useful libraries - renv = pkgs.rWrapper.override { - packages = with pkgs.rPackages; [ devtools rextendr rpolars ]; + rvenv = pkgs.rWrapper.override { + packages = with pkgs.rPackages; [ renv ]; }; in { packages.default = rpolars; devShells.default = pkgs.mkShell { + buildInputs = rdeps; inputsFrom = pkgs.lib.singleton rpolars; - packages = pkgs.lib.singleton renv; + packages = pkgs.lib.singleton rvenv; + LD_LIBRARY_PATH = pkgs.lib.strings.makeLibraryPath rdeps; }; }); - nixConfig = { - extra-substituters = [ "https://r-polars.cachix.org" ]; - extra-trusted-public-keys = - [ "r-polars.cachix.org-1:LhIYJk3lSZay+OuJ30RU4WkvAc8VY0QvaSy7rIcQ31w=" ]; - }; - } diff --git a/man/nanoarrow.Rd b/man/nanoarrow.Rd index 3ecaf02a4..7af2018a2 100644 --- a/man/nanoarrow.Rd +++ b/man/nanoarrow.Rd @@ -16,13 +16,13 @@ \alias{as_record_batch_reader.DataFrame} \title{polars to nanoarrow and arrow} \usage{ -\method{as_nanoarrow_array_stream}{DataFrame}(x, ..., schema = NULL) +as_nanoarrow_array_stream.DataFrame(x, ..., schema = NULL) -\method{infer_nanoarrow_schema}{DataFrame}(x, ...) +infer_nanoarrow_schema.DataFrame(x, ...) -\method{as_arrow_table}{DataFrame}(x, ...) +as_arrow_table.DataFrame(x, ...) -\method{as_record_batch_reader}{DataFrame}(x, ..., schema = NULL) +as_record_batch_reader.DataFrame(x, ..., schema = NULL) } \arguments{ \item{x}{a polars DataFrame} From 70a8164631190da6ec5c5793f4e1ee51bccc8c5d Mon Sep 17 00:00:00 2001 From: Sicheng Pan Date: Sun, 4 Jun 2023 22:40:39 -0700 Subject: [PATCH 02/24] Designing ranyhow --- NAMESPACE | 2 ++ R/extendr-wrappers.R | 10 +++++++ src/rust/Cargo.lock | 7 +++++ src/rust/Cargo.toml | 1 + src/rust/src/lib.rs | 2 ++ src/rust/src/ranyhow.rs | 43 +++++++++++++++++++++++++++++ src/rust/src/rdataframe/read_ipc.rs | 23 ++++++++------- 7 files changed, 78 insertions(+), 10 deletions(-) create mode 100644 src/rust/src/ranyhow.rs diff --git a/NAMESPACE b/NAMESPACE index 47f582288..0374f2448 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -22,6 +22,7 @@ S3method("$",ProtoExprArray) S3method("$",RField) S3method("$",RNullValues) S3method("$",RPolarsDataType) +S3method("$",Rerr) S3method("$",Series) S3method("$",VecDataFrame) S3method("$",When) @@ -64,6 +65,7 @@ S3method("[[",ProtoExprArray) S3method("[[",RField) S3method("[[",RNullValues) S3method("[[",RPolarsDataType) +S3method("[[",Rerr) S3method("[[",Series) S3method("[[",VecDataFrame) S3method("[[",When) diff --git a/R/extendr-wrappers.R b/R/extendr-wrappers.R index 58736603b..fdf298ff1 100644 --- a/R/extendr-wrappers.R +++ b/R/extendr-wrappers.R @@ -53,6 +53,16 @@ test_robj_to_i64 <- function(robj) .Call(wrap__test_robj_to_i64, robj) test_robj_to_u32 <- function(robj) .Call(wrap__test_robj_to_u32, robj) +Rerr <- new.env(parent = emptyenv()) + +Rerr$print <- function() invisible(.Call(wrap__Rerr__print, self)) + +#' @export +`$.Rerr` <- function (self, name) { func <- Rerr[[name]]; environment(func) <- environment(); func } + +#' @export +`[[.Rerr` <- `$.Rerr` + DataFrame <- new.env(parent = emptyenv()) DataFrame$shape <- function() .Call(wrap__DataFrame__shape, self) diff --git a/src/rust/Cargo.lock b/src/rust/Cargo.lock index 64480685e..5b10878cc 100644 --- a/src/rust/Cargo.lock +++ b/src/rust/Cargo.lock @@ -59,6 +59,12 @@ dependencies = [ "libc", ] +[[package]] +name = "anyhow" +version = "1.0.71" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c7d0618f0e0b7e8ff11427422b64564d5fb0be1940354bfe2e0529b18a9d9b8" + [[package]] name = "argminmax" version = "0.6.1" @@ -1760,6 +1766,7 @@ dependencies = [ name = "r-polars" version = "0.1.0" dependencies = [ + "anyhow", "extendr-api", "flume", "jemallocator", diff --git a/src/rust/Cargo.toml b/src/rust/Cargo.toml index 66233efdf..1d73ebf87 100644 --- a/src/rust/Cargo.toml +++ b/src/rust/Cargo.toml @@ -19,6 +19,7 @@ jemallocator = { version = "0.5.0", features = ["disable_initial_exec_tls"] } extendr-api = {git = "https://github.com/rpolars/extendr", branch = "errorhandling", default-features = false, features= ["result_list"]} #extendr-api = {path = "../../../extendr/extendr-api", default-features = false, features= ["result_list"]} +anyhow = "1.0.71" flume = "0.10.14" state = "0.5.3" rayon = "1.6.1" diff --git a/src/rust/src/lib.rs b/src/rust/src/lib.rs index 55d0f0e3c..2fd90d4bb 100644 --- a/src/rust/src/lib.rs +++ b/src/rust/src/lib.rs @@ -15,6 +15,7 @@ pub mod lazy; pub mod arrow_interop; pub mod conversion_r_to_s; pub mod conversion_s_to_r; +pub mod ranyhow; pub mod rdataframe; pub mod rdatatype; pub mod rlib; @@ -37,6 +38,7 @@ static CONFIG: ThreadComStorage = Storage::new(); // Macro to generate exports extendr_module! { mod polars; + use ranyhow; use rdataframe; use lazy; use series; diff --git a/src/rust/src/ranyhow.rs b/src/rust/src/ranyhow.rs new file mode 100644 index 000000000..7ea090f5c --- /dev/null +++ b/src/rust/src/ranyhow.rs @@ -0,0 +1,43 @@ +use anyhow::Error; +pub use anyhow::{anyhow as ranyhow, Context}; +use extendr_api::{ + extendr, extendr_module, print_r_output, rprintln, symbol::class_symbol, Attributes, + Rinternals, Robj, +}; + +#[derive(Debug)] +pub struct Rerr(Error); +pub type Result = core::result::Result; + +#[extendr] +impl Rerr { + fn print(&self) { + rprintln!("{}", self); + } +} + +impl From for Rerr { + fn from(err: Error) -> Self { + Rerr(err) + } +} + +impl std::fmt::Display for Rerr { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", self.0) + } +} + +impl std::error::Error for Rerr { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + self.0.source() + } +} + +// unsafe impl Send for Rerr {} +// unsafe impl Sync for Rerr {} + +extendr_module! { + mod ranyhow; + impl Rerr; +} diff --git a/src/rust/src/rdataframe/read_ipc.rs b/src/rust/src/rdataframe/read_ipc.rs index 371ca9cc6..029831e5c 100644 --- a/src/rust/src/rdataframe/read_ipc.rs +++ b/src/rust/src/rdataframe/read_ipc.rs @@ -1,5 +1,6 @@ use crate::lazy::dataframe::LazyFrame as RLazyFrame; -use crate::{robj_to, Error::Other, Result}; +use crate::ranyhow::{ranyhow, Context, Result}; +use crate::robj_to; use extendr_api::prelude::*; use polars::io::RowCount; use polars::prelude::{LazyFrame, ScanArgsIpc}; @@ -15,17 +16,19 @@ pub fn import_arrow_ipc( memmap: Robj, ) -> Result { let args = ScanArgsIpc { - n_rows: robj_to!(Option, usize, n_rows)?, - cache: robj_to!(bool, cache)?, - rechunk: robj_to!(bool, rechunk)?, - row_count: robj_to!(Option, String, row_name)? + n_rows: robj_to!(Option, usize, n_rows).map_err(|msg| ranyhow!(msg))?, + cache: robj_to!(bool, cache).map_err(|msg| ranyhow!(msg))?, + rechunk: robj_to!(bool, rechunk).map_err(|msg| ranyhow!(msg))?, + row_count: robj_to!(Option, String, row_name) + .map_err(|msg| ranyhow!(msg))? .map(|name| robj_to!(u32, row_count).map(|offset| RowCount { name, offset })) - .transpose()?, - memmap: robj_to!(bool, memmap)?, + .transpose() + .map_err(|msg| ranyhow!(msg))?, + memmap: robj_to!(bool, memmap).map_err(|msg| ranyhow!(msg))?, }; - LazyFrame::scan_ipc(robj_to!(String, path)?, args) - .map_err(|x| Other(format!("Polaris internal error: {x}"))) - .map(RLazyFrame) + let lf = LazyFrame::scan_ipc(robj_to!(String, path).map_err(|msg| ranyhow!(msg))?, args) + .context("Pola-rs internal import for Arrow")?; + Ok(RLazyFrame(lf)) } extendr_module! { From 6ebb2489e978c49b66d67ac177754a391a6df48c Mon Sep 17 00:00:00 2001 From: Sicheng Pan Date: Mon, 5 Jun 2023 18:17:19 -0700 Subject: [PATCH 03/24] Implement prototype ranyhow --- NAMESPACE | 1 + R/extendr-wrappers.R | 6 +++++- R/s3_methods.R | 4 ++++ src/rust/src/ranyhow.rs | 22 ++++++++++++---------- 4 files changed, 22 insertions(+), 11 deletions(-) diff --git a/NAMESPACE b/NAMESPACE index 0374f2448..7bc280cfc 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -86,6 +86,7 @@ S3method(.DollarNames,WhenThen) S3method(.DollarNames,WhenThenThen) S3method(.DollarNames,method_environment) S3method(.DollarNames,polars_option_list) +S3method(as.character,Rerr) S3method(as.character,Series) S3method(as.data.frame,DataFrame) S3method(as.data.frame,LazyFrame) diff --git a/R/extendr-wrappers.R b/R/extendr-wrappers.R index fdf298ff1..11814dfed 100644 --- a/R/extendr-wrappers.R +++ b/R/extendr-wrappers.R @@ -55,7 +55,11 @@ test_robj_to_u32 <- function(robj) .Call(wrap__test_robj_to_u32, robj) Rerr <- new.env(parent = emptyenv()) -Rerr$print <- function() invisible(.Call(wrap__Rerr__print, self)) +Rerr$info <- function() .Call(wrap__Rerr__info, self) + +Rerr$debug <- function() .Call(wrap__Rerr__debug, self) + +Rerr$chain <- function() .Call(wrap__Rerr__chain, self) #' @export `$.Rerr` <- function (self, name) { func <- Rerr[[name]]; environment(func) <- environment(); func } diff --git a/R/s3_methods.R b/R/s3_methods.R index 76c4b1c9d..7979d6a79 100644 --- a/R/s3_methods.R +++ b/R/s3_methods.R @@ -1,3 +1,7 @@ +#' @export +#' @noRd +as.character.Rerr = function(x) x$info() + #' @export #' @noRd `[.DataFrame` = function(x, i, j, ..., drop = TRUE) { diff --git a/src/rust/src/ranyhow.rs b/src/rust/src/ranyhow.rs index 7ea090f5c..3a01b49eb 100644 --- a/src/rust/src/ranyhow.rs +++ b/src/rust/src/ranyhow.rs @@ -1,9 +1,6 @@ use anyhow::Error; pub use anyhow::{anyhow as ranyhow, Context}; -use extendr_api::{ - extendr, extendr_module, print_r_output, rprintln, symbol::class_symbol, Attributes, - Rinternals, Robj, -}; +use extendr_api::{extendr, extendr_module, symbol::class_symbol, Attributes, Rinternals, Robj}; #[derive(Debug)] pub struct Rerr(Error); @@ -11,8 +8,16 @@ pub type Result = core::result::Result; #[extendr] impl Rerr { - fn print(&self) { - rprintln!("{}", self); + fn info(&self) -> String { + format!("{:#}", self.0) + } + + fn debug(&self) -> String { + format!("{:?}", self.0) + } + + fn chain(&self) -> Vec { + self.0.chain().map(|cause| format!("{:#}", cause)).collect() } } @@ -24,7 +29,7 @@ impl From for Rerr { impl std::fmt::Display for Rerr { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", self.0) + write!(f, "{:#}", self.0) } } @@ -34,9 +39,6 @@ impl std::error::Error for Rerr { } } -// unsafe impl Send for Rerr {} -// unsafe impl Sync for Rerr {} - extendr_module! { mod ranyhow; impl Rerr; From f5b0addead2896a9671b90265f2ad33b3545306e Mon Sep 17 00:00:00 2001 From: Sicheng Pan Date: Tue, 6 Jun 2023 17:52:42 -0700 Subject: [PATCH 04/24] Implement Rerr from string --- DESCRIPTION | 1 + NAMESPACE | 1 + R/rerr.R | 14 ++++++++++++++ R/s3_methods.R | 4 ---- man/dot-DollarNames.Rerr.Rd | 17 +++++++++++++++++ man/nanoarrow.Rd | 8 ++++---- src/rust/src/ranyhow.rs | 13 ++++++++++--- src/rust/src/rdataframe/read_ipc.rs | 20 +++++++++----------- 8 files changed, 56 insertions(+), 22 deletions(-) create mode 100644 R/rerr.R create mode 100644 man/dot-DollarNames.Rerr.Rd diff --git a/DESCRIPTION b/DESCRIPTION index fc51d51f6..00ed698f4 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -74,6 +74,7 @@ Collate: 'parquet.R' 'pkg-knitr.R' 'pkg-nanoarrow.R' + 'rerr.R' 'rlang.R' 'rust_result.R' 's3_methods.R' diff --git a/NAMESPACE b/NAMESPACE index 7bc280cfc..b153fb07a 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -79,6 +79,7 @@ S3method(.DollarNames,GroupBy) S3method(.DollarNames,LazyFrame) S3method(.DollarNames,PolarsBackgroundHandle) S3method(.DollarNames,RField) +S3method(.DollarNames,Rerr) S3method(.DollarNames,Series) S3method(.DollarNames,VecDataFrame) S3method(.DollarNames,When) diff --git a/R/rerr.R b/R/rerr.R new file mode 100644 index 000000000..44e9ad680 --- /dev/null +++ b/R/rerr.R @@ -0,0 +1,14 @@ +#' @title auto complete $-access into a polars object +#' @description called by the interactive R session internally +#' @param x Rerr +#' @param pattern code-stump as string to auto-complete +#' @export +#' @keywords internal +.DollarNames.Rerr = function(x, pattern = "") { + get_method_usages(Rerr, pattern = pattern) +} + +#' @export +#' @noRd +as.character.Rerr = function(x) x$info() + diff --git a/R/s3_methods.R b/R/s3_methods.R index 7979d6a79..76c4b1c9d 100644 --- a/R/s3_methods.R +++ b/R/s3_methods.R @@ -1,7 +1,3 @@ -#' @export -#' @noRd -as.character.Rerr = function(x) x$info() - #' @export #' @noRd `[.DataFrame` = function(x, i, j, ..., drop = TRUE) { diff --git a/man/dot-DollarNames.Rerr.Rd b/man/dot-DollarNames.Rerr.Rd new file mode 100644 index 000000000..e0f3d1f40 --- /dev/null +++ b/man/dot-DollarNames.Rerr.Rd @@ -0,0 +1,17 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/rerr.R +\name{.DollarNames.Rerr} +\alias{.DollarNames.Rerr} +\title{auto complete $-access into a polars object} +\usage{ +\method{.DollarNames}{Rerr}(x, pattern = "") +} +\arguments{ +\item{x}{Rerr} + +\item{pattern}{code-stump as string to auto-complete} +} +\description{ +called by the interactive R session internally +} +\keyword{internal} diff --git a/man/nanoarrow.Rd b/man/nanoarrow.Rd index 7af2018a2..3ecaf02a4 100644 --- a/man/nanoarrow.Rd +++ b/man/nanoarrow.Rd @@ -16,13 +16,13 @@ \alias{as_record_batch_reader.DataFrame} \title{polars to nanoarrow and arrow} \usage{ -as_nanoarrow_array_stream.DataFrame(x, ..., schema = NULL) +\method{as_nanoarrow_array_stream}{DataFrame}(x, ..., schema = NULL) -infer_nanoarrow_schema.DataFrame(x, ...) +\method{infer_nanoarrow_schema}{DataFrame}(x, ...) -as_arrow_table.DataFrame(x, ...) +\method{as_arrow_table}{DataFrame}(x, ...) -as_record_batch_reader.DataFrame(x, ..., schema = NULL) +\method{as_record_batch_reader}{DataFrame}(x, ..., schema = NULL) } \arguments{ \item{x}{a polars DataFrame} diff --git a/src/rust/src/ranyhow.rs b/src/rust/src/ranyhow.rs index 3a01b49eb..1df6974bb 100644 --- a/src/rust/src/ranyhow.rs +++ b/src/rust/src/ranyhow.rs @@ -1,10 +1,10 @@ -use anyhow::Error; -pub use anyhow::{anyhow as ranyhow, Context}; +pub use anyhow::Context; +use anyhow::{anyhow, Error}; use extendr_api::{extendr, extendr_module, symbol::class_symbol, Attributes, Rinternals, Robj}; #[derive(Debug)] pub struct Rerr(Error); -pub type Result = core::result::Result; +pub type RResult = core::result::Result; #[extendr] impl Rerr { @@ -27,6 +27,13 @@ impl From for Rerr { } } +// Implementation for transition +impl From for Rerr { + fn from(err_msg: String) -> Self { + Rerr(anyhow!(err_msg)) + } +} + impl std::fmt::Display for Rerr { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{:#}", self.0) diff --git a/src/rust/src/rdataframe/read_ipc.rs b/src/rust/src/rdataframe/read_ipc.rs index 029831e5c..f681f6fab 100644 --- a/src/rust/src/rdataframe/read_ipc.rs +++ b/src/rust/src/rdataframe/read_ipc.rs @@ -1,5 +1,5 @@ use crate::lazy::dataframe::LazyFrame as RLazyFrame; -use crate::ranyhow::{ranyhow, Context, Result}; +use crate::ranyhow::{Context, RResult}; use crate::robj_to; use extendr_api::prelude::*; use polars::io::RowCount; @@ -14,19 +14,17 @@ pub fn import_arrow_ipc( row_name: Robj, row_count: Robj, memmap: Robj, -) -> Result { +) -> RResult { let args = ScanArgsIpc { - n_rows: robj_to!(Option, usize, n_rows).map_err(|msg| ranyhow!(msg))?, - cache: robj_to!(bool, cache).map_err(|msg| ranyhow!(msg))?, - rechunk: robj_to!(bool, rechunk).map_err(|msg| ranyhow!(msg))?, - row_count: robj_to!(Option, String, row_name) - .map_err(|msg| ranyhow!(msg))? + n_rows: robj_to!(Option, usize, n_rows)?, + cache: robj_to!(bool, cache)?, + rechunk: robj_to!(bool, rechunk)?, + row_count: robj_to!(Option, String, row_name)? .map(|name| robj_to!(u32, row_count).map(|offset| RowCount { name, offset })) - .transpose() - .map_err(|msg| ranyhow!(msg))?, - memmap: robj_to!(bool, memmap).map_err(|msg| ranyhow!(msg))?, + .transpose()?, + memmap: robj_to!(bool, memmap)?, }; - let lf = LazyFrame::scan_ipc(robj_to!(String, path).map_err(|msg| ranyhow!(msg))?, args) + let lf = LazyFrame::scan_ipc(robj_to!(String, path)?, args) .context("Pola-rs internal import for Arrow")?; Ok(RLazyFrame(lf)) } From 691865e83c958a30a3ab8fb02224849c7b5c227e Mon Sep 17 00:00:00 2001 From: Sicheng Pan Date: Thu, 8 Jun 2023 18:14:47 -0700 Subject: [PATCH 05/24] Derive error from extendr> --- src/rust/src/ranyhow.rs | 68 ++++++++++++++++++++++++++++++++++++++--- 1 file changed, 63 insertions(+), 5 deletions(-) diff --git a/src/rust/src/ranyhow.rs b/src/rust/src/ranyhow.rs index 1df6974bb..617cb3474 100644 --- a/src/rust/src/ranyhow.rs +++ b/src/rust/src/ranyhow.rs @@ -1,9 +1,8 @@ pub use anyhow::Context; -use anyhow::{anyhow, Error}; use extendr_api::{extendr, extendr_module, symbol::class_symbol, Attributes, Rinternals, Robj}; #[derive(Debug)] -pub struct Rerr(Error); +pub struct Rerr(anyhow::Error); pub type RResult = core::result::Result; #[extendr] @@ -21,8 +20,8 @@ impl Rerr { } } -impl From for Rerr { - fn from(err: Error) -> Self { +impl From for Rerr { + fn from(err: anyhow::Error) -> Self { Rerr(err) } } @@ -30,7 +29,66 @@ impl From for Rerr { // Implementation for transition impl From for Rerr { fn from(err_msg: String) -> Self { - Rerr(anyhow!(err_msg)) + Rerr(anyhow::anyhow!(err_msg)) + } +} + +impl From for Rerr { + fn from(extendr_err: extendr_api::Error) -> Self { + use extendr_api::error::Error::*; + let rdebug = |robj| anyhow::anyhow!("{:?}", robj); + let anyhow_err = match extendr_err { + Panic(robj) => rdebug(robj).context("Panic"), + NotFound(robj) => rdebug(robj).context("NotFound"), + EvalError(robj) => rdebug(robj).context("EvalError"), + ParseError(robj) => rdebug(robj).context("ParseError"), + NamesLengthMismatch(robj) => rdebug(robj).context("NamesLengthMismatch"), + ExpectedNull(robj) => rdebug(robj).context("ExpectedNull"), + ExpectedSymbol(robj) => rdebug(robj).context("ExpectedSymbol"), + ExpectedPairlist(robj) => rdebug(robj).context("ExpectedPairlist"), + ExpectedFunction(robj) => rdebug(robj).context("ExpectedFunction"), + ExpectedEnvironment(robj) => rdebug(robj).context("ExpectedEnvironment"), + ExpectedPromise(robj) => rdebug(robj).context("ExpectedPromise"), + ExpectedLanguage(robj) => rdebug(robj).context("ExpectedLanguage"), + ExpectedSpecial(robj) => rdebug(robj).context("ExpectedSpecial"), + ExpectedBuiltin(robj) => rdebug(robj).context("ExpectedBuiltin"), + ExpectedRstr(robj) => rdebug(robj).context("ExpectedRstr"), + ExpectedLogical(robj) => rdebug(robj).context("ExpectedLogical"), + ExpectedInteger(robj) => rdebug(robj).context("ExpectedInteger"), + ExpectedReal(robj) => rdebug(robj).context("ExpectedReal"), + ExpectedComplex(robj) => rdebug(robj).context("ExpectedComplex"), + ExpectedString(robj) => rdebug(robj).context("ExpectedString"), + ExpectedDot(robj) => rdebug(robj).context("ExpectedDot"), + ExpectedAny(robj) => rdebug(robj).context("ExpectedAny"), + ExpectedList(robj) => rdebug(robj).context("ExpectedList"), + ExpectedExpression(robj) => rdebug(robj).context("ExpectedExpression"), + ExpectedBytecode(robj) => rdebug(robj).context("ExpectedBytecode"), + ExpectedExternalPtr(robj) => rdebug(robj).context("ExpectedExternalPtr"), + ExpectedWeakRef(robj) => rdebug(robj).context("ExpectedWeakRef"), + ExpectedRaw(robj) => rdebug(robj).context("ExpectedRaw"), + ExpectedS4(robj) => rdebug(robj).context("ExpectedS4"), + ExpectedPrimitive(robj) => rdebug(robj).context("ExpectedPrimitive"), + ExpectedScalar(robj) => rdebug(robj).context("ExpectedScalar"), + ExpectedVector(robj) => rdebug(robj).context("ExpectedVector"), + ExpectedMatrix(robj) => rdebug(robj).context("ExpectedMatrix"), + ExpectedMatrix3D(robj) => rdebug(robj).context("ExpectedMatrix3D"), + ExpectedNumeric(robj) => rdebug(robj).context("ExpectedNumeric"), + ExpectedAltrep(robj) => rdebug(robj).context("ExpectedAltrep"), + ExpectedDataframe(robj) => rdebug(robj).context("ExpectedDataframe"), + OutOfRange(robj) => rdebug(robj).context("OutOfRange"), + MustNotBeNA(robj) => rdebug(robj).context("MustNotBeNA"), + ExpectedNonZeroLength(robj) => rdebug(robj).context("ExpectedNonZeroLength"), + ExpectedWholeNumber(robj) => rdebug(robj).context("ExpectedWholeNumber"), + OutOfLimits(robj) => rdebug(robj).context("OutOfLimits"), + TypeMismatch(robj) => rdebug(robj).context("TypeMismatch"), + NamespaceNotFound(robj) => rdebug(robj).context("NamespaceNotFound"), + NoGraphicsDevices(robj) => rdebug(robj).context("NoGraphicsDevices"), + ExpectedExternalPtrType(robj, s) => { + anyhow::anyhow!("s:{}, robj:{:?}", s, robj).context("ExpectedExternalPtrType") + } + Other(s) => anyhow::anyhow!(s).context("Other"), + }; + anyhow_err.context("Extendr").into() } } From 3349349ad2ef6d3fcfc546920bf047688757aecc Mon Sep 17 00:00:00 2001 From: Sicheng Pan Date: Sat, 10 Jun 2023 17:17:24 -0700 Subject: [PATCH 06/24] Refactor Rerr --- NAMESPACE | 1 + R/extendr-wrappers.R | 10 ++- R/rerr.R | 3 + src/rust/Cargo.lock | 7 -- src/rust/Cargo.toml | 1 - src/rust/src/lazy/dataframe.rs | 5 ++ src/rust/src/lib.rs | 4 +- src/rust/src/ranyhow.rs | 110 ----------------------- src/rust/src/rdataframe/read_ipc.rs | 5 +- src/rust/src/rerr.rs | 130 ++++++++++++++++++++++++++++ 10 files changed, 150 insertions(+), 126 deletions(-) delete mode 100644 src/rust/src/ranyhow.rs create mode 100644 src/rust/src/rerr.rs diff --git a/NAMESPACE b/NAMESPACE index b153fb07a..98779e913 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -124,6 +124,7 @@ S3method(print,PTime) S3method(print,PolarsBackgroundHandle) S3method(print,RField) S3method(print,RPolarsDataType) +S3method(print,Rerr) S3method(print,Series) S3method(print,When) S3method(print,WhenThen) diff --git a/R/extendr-wrappers.R b/R/extendr-wrappers.R index 11814dfed..1f9eadea7 100644 --- a/R/extendr-wrappers.R +++ b/R/extendr-wrappers.R @@ -11,6 +11,8 @@ #' @useDynLib polars, .registration = TRUE NULL +test_rerr <- function() .Call(wrap__test_rerr) + rlazy_csv_reader <- function(path, sep, has_header, ignore_errors, skip_rows, n_rows, cache, overwrite_dtype, low_memory, comment_char, quote_char, null_values, infer_schema_length, skip_rows_after_header, encoding, row_count_name, row_count_offset, parse_dates) .Call(wrap__rlazy_csv_reader, path, sep, has_header, ignore_errors, skip_rows, n_rows, cache, overwrite_dtype, low_memory, comment_char, quote_char, null_values, infer_schema_length, skip_rows_after_header, encoding, row_count_name, row_count_offset, parse_dates) import_arrow_ipc <- function(path, n_rows, cache, rechunk, row_name, row_count, memmap) .Call(wrap__import_arrow_ipc, path, n_rows, cache, rechunk, row_name, row_count, memmap) @@ -55,11 +57,11 @@ test_robj_to_u32 <- function(robj) .Call(wrap__test_robj_to_u32, robj) Rerr <- new.env(parent = emptyenv()) -Rerr$info <- function() .Call(wrap__Rerr__info, self) +Rerr$new <- function() .Call(wrap__Rerr__new) -Rerr$debug <- function() .Call(wrap__Rerr__debug, self) +Rerr$info <- function() .Call(wrap__Rerr__info, self) -Rerr$chain <- function() .Call(wrap__Rerr__chain, self) +Rerr$contexts <- function() .Call(wrap__Rerr__contexts, self) #' @export `$.Rerr` <- function (self, name) { func <- Rerr[[name]]; environment(func) <- environment(); func } @@ -843,6 +845,8 @@ LazyFrame$collect_background <- function() .Call(wrap__LazyFrame__collect_backgr LazyFrame$collect <- function() .Call(wrap__LazyFrame__collect, self) +LazyFrame$collect_handled <- function() .Call(wrap__LazyFrame__collect_handled, self) + LazyFrame$first <- function() .Call(wrap__LazyFrame__first, self) LazyFrame$last <- function() .Call(wrap__LazyFrame__last, self) diff --git a/R/rerr.R b/R/rerr.R index 44e9ad680..d5be23000 100644 --- a/R/rerr.R +++ b/R/rerr.R @@ -12,3 +12,6 @@ #' @noRd as.character.Rerr = function(x) x$info() +#' @export +#' @noRd +print.Rerr = function(x) writeLines(x$info()) diff --git a/src/rust/Cargo.lock b/src/rust/Cargo.lock index 5b10878cc..64480685e 100644 --- a/src/rust/Cargo.lock +++ b/src/rust/Cargo.lock @@ -59,12 +59,6 @@ dependencies = [ "libc", ] -[[package]] -name = "anyhow" -version = "1.0.71" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c7d0618f0e0b7e8ff11427422b64564d5fb0be1940354bfe2e0529b18a9d9b8" - [[package]] name = "argminmax" version = "0.6.1" @@ -1766,7 +1760,6 @@ dependencies = [ name = "r-polars" version = "0.1.0" dependencies = [ - "anyhow", "extendr-api", "flume", "jemallocator", diff --git a/src/rust/Cargo.toml b/src/rust/Cargo.toml index 1d73ebf87..66233efdf 100644 --- a/src/rust/Cargo.toml +++ b/src/rust/Cargo.toml @@ -19,7 +19,6 @@ jemallocator = { version = "0.5.0", features = ["disable_initial_exec_tls"] } extendr-api = {git = "https://github.com/rpolars/extendr", branch = "errorhandling", default-features = false, features= ["result_list"]} #extendr-api = {path = "../../../extendr/extendr-api", default-features = false, features= ["result_list"]} -anyhow = "1.0.71" flume = "0.10.14" state = "0.5.3" rayon = "1.6.1" diff --git a/src/rust/src/lazy/dataframe.rs b/src/rust/src/lazy/dataframe.rs index 69f5f239c..231ceb321 100644 --- a/src/rust/src/lazy/dataframe.rs +++ b/src/rust/src/lazy/dataframe.rs @@ -75,6 +75,11 @@ impl LazyFrame { }) } + pub fn collect_handled(&self) -> crate::rerr::RResult { + use crate::rerr::WithRctx; + handle_thread_r_requests(self.clone().0).when("calling $collect() on LazyFrame") + } + fn first(&self) -> Self { self.0.clone().first().into() } diff --git a/src/rust/src/lib.rs b/src/rust/src/lib.rs index 2fd90d4bb..b2bb25c6e 100644 --- a/src/rust/src/lib.rs +++ b/src/rust/src/lib.rs @@ -15,9 +15,9 @@ pub mod lazy; pub mod arrow_interop; pub mod conversion_r_to_s; pub mod conversion_s_to_r; -pub mod ranyhow; pub mod rdataframe; pub mod rdatatype; +pub mod rerr; pub mod rlib; pub mod series; pub mod utils; @@ -38,7 +38,7 @@ static CONFIG: ThreadComStorage = Storage::new(); // Macro to generate exports extendr_module! { mod polars; - use ranyhow; + use rerr; use rdataframe; use lazy; use series; diff --git a/src/rust/src/ranyhow.rs b/src/rust/src/ranyhow.rs deleted file mode 100644 index 617cb3474..000000000 --- a/src/rust/src/ranyhow.rs +++ /dev/null @@ -1,110 +0,0 @@ -pub use anyhow::Context; -use extendr_api::{extendr, extendr_module, symbol::class_symbol, Attributes, Rinternals, Robj}; - -#[derive(Debug)] -pub struct Rerr(anyhow::Error); -pub type RResult = core::result::Result; - -#[extendr] -impl Rerr { - fn info(&self) -> String { - format!("{:#}", self.0) - } - - fn debug(&self) -> String { - format!("{:?}", self.0) - } - - fn chain(&self) -> Vec { - self.0.chain().map(|cause| format!("{:#}", cause)).collect() - } -} - -impl From for Rerr { - fn from(err: anyhow::Error) -> Self { - Rerr(err) - } -} - -// Implementation for transition -impl From for Rerr { - fn from(err_msg: String) -> Self { - Rerr(anyhow::anyhow!(err_msg)) - } -} - -impl From for Rerr { - fn from(extendr_err: extendr_api::Error) -> Self { - use extendr_api::error::Error::*; - let rdebug = |robj| anyhow::anyhow!("{:?}", robj); - let anyhow_err = match extendr_err { - Panic(robj) => rdebug(robj).context("Panic"), - NotFound(robj) => rdebug(robj).context("NotFound"), - EvalError(robj) => rdebug(robj).context("EvalError"), - ParseError(robj) => rdebug(robj).context("ParseError"), - NamesLengthMismatch(robj) => rdebug(robj).context("NamesLengthMismatch"), - ExpectedNull(robj) => rdebug(robj).context("ExpectedNull"), - ExpectedSymbol(robj) => rdebug(robj).context("ExpectedSymbol"), - ExpectedPairlist(robj) => rdebug(robj).context("ExpectedPairlist"), - ExpectedFunction(robj) => rdebug(robj).context("ExpectedFunction"), - ExpectedEnvironment(robj) => rdebug(robj).context("ExpectedEnvironment"), - ExpectedPromise(robj) => rdebug(robj).context("ExpectedPromise"), - ExpectedLanguage(robj) => rdebug(robj).context("ExpectedLanguage"), - ExpectedSpecial(robj) => rdebug(robj).context("ExpectedSpecial"), - ExpectedBuiltin(robj) => rdebug(robj).context("ExpectedBuiltin"), - ExpectedRstr(robj) => rdebug(robj).context("ExpectedRstr"), - ExpectedLogical(robj) => rdebug(robj).context("ExpectedLogical"), - ExpectedInteger(robj) => rdebug(robj).context("ExpectedInteger"), - ExpectedReal(robj) => rdebug(robj).context("ExpectedReal"), - ExpectedComplex(robj) => rdebug(robj).context("ExpectedComplex"), - ExpectedString(robj) => rdebug(robj).context("ExpectedString"), - ExpectedDot(robj) => rdebug(robj).context("ExpectedDot"), - ExpectedAny(robj) => rdebug(robj).context("ExpectedAny"), - ExpectedList(robj) => rdebug(robj).context("ExpectedList"), - ExpectedExpression(robj) => rdebug(robj).context("ExpectedExpression"), - ExpectedBytecode(robj) => rdebug(robj).context("ExpectedBytecode"), - ExpectedExternalPtr(robj) => rdebug(robj).context("ExpectedExternalPtr"), - ExpectedWeakRef(robj) => rdebug(robj).context("ExpectedWeakRef"), - ExpectedRaw(robj) => rdebug(robj).context("ExpectedRaw"), - ExpectedS4(robj) => rdebug(robj).context("ExpectedS4"), - ExpectedPrimitive(robj) => rdebug(robj).context("ExpectedPrimitive"), - ExpectedScalar(robj) => rdebug(robj).context("ExpectedScalar"), - ExpectedVector(robj) => rdebug(robj).context("ExpectedVector"), - ExpectedMatrix(robj) => rdebug(robj).context("ExpectedMatrix"), - ExpectedMatrix3D(robj) => rdebug(robj).context("ExpectedMatrix3D"), - ExpectedNumeric(robj) => rdebug(robj).context("ExpectedNumeric"), - ExpectedAltrep(robj) => rdebug(robj).context("ExpectedAltrep"), - ExpectedDataframe(robj) => rdebug(robj).context("ExpectedDataframe"), - OutOfRange(robj) => rdebug(robj).context("OutOfRange"), - MustNotBeNA(robj) => rdebug(robj).context("MustNotBeNA"), - ExpectedNonZeroLength(robj) => rdebug(robj).context("ExpectedNonZeroLength"), - ExpectedWholeNumber(robj) => rdebug(robj).context("ExpectedWholeNumber"), - OutOfLimits(robj) => rdebug(robj).context("OutOfLimits"), - TypeMismatch(robj) => rdebug(robj).context("TypeMismatch"), - NamespaceNotFound(robj) => rdebug(robj).context("NamespaceNotFound"), - NoGraphicsDevices(robj) => rdebug(robj).context("NoGraphicsDevices"), - ExpectedExternalPtrType(robj, s) => { - anyhow::anyhow!("s:{}, robj:{:?}", s, robj).context("ExpectedExternalPtrType") - } - Other(s) => anyhow::anyhow!(s).context("Other"), - }; - anyhow_err.context("Extendr").into() - } -} - -impl std::fmt::Display for Rerr { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{:#}", self.0) - } -} - -impl std::error::Error for Rerr { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - self.0.source() - } -} - -extendr_module! { - mod ranyhow; - impl Rerr; -} diff --git a/src/rust/src/rdataframe/read_ipc.rs b/src/rust/src/rdataframe/read_ipc.rs index f681f6fab..78842ed46 100644 --- a/src/rust/src/rdataframe/read_ipc.rs +++ b/src/rust/src/rdataframe/read_ipc.rs @@ -1,5 +1,5 @@ use crate::lazy::dataframe::LazyFrame as RLazyFrame; -use crate::ranyhow::{Context, RResult}; +use crate::rerr::RResult; use crate::robj_to; use extendr_api::prelude::*; use polars::io::RowCount; @@ -24,8 +24,7 @@ pub fn import_arrow_ipc( .transpose()?, memmap: robj_to!(bool, memmap)?, }; - let lf = LazyFrame::scan_ipc(robj_to!(String, path)?, args) - .context("Pola-rs internal import for Arrow")?; + let lf = LazyFrame::scan_ipc(robj_to!(String, path)?, args)?; Ok(RLazyFrame(lf)) } diff --git a/src/rust/src/rerr.rs b/src/rust/src/rerr.rs new file mode 100644 index 000000000..fc0a34440 --- /dev/null +++ b/src/rust/src/rerr.rs @@ -0,0 +1,130 @@ +use extendr_api::{extendr, extendr_module, symbol::class_symbol, Attributes, Rinternals, Robj}; + +#[derive(Clone, Debug)] +pub enum Rctx { + Extendr(String), + Hint(String), + Plain(String), + Polars(String), + When(String), + TypeMismatch(String, String, String), +} + +#[derive(Clone, Debug)] +pub struct Rerr(Vec); +pub type RResult = core::result::Result; + +pub trait WithRctx { + fn ctx(self, rctx: Rctx) -> RResult; + fn hint>(self, msg: S) -> RResult; + fn when>(self, msg: S) -> RResult; +} + +impl> WithRctx for core::result::Result { + fn ctx(self, rctx: Rctx) -> RResult { + self.map_err(|e| { + let mut rerr = e.into(); + rerr.0.push(rctx); + rerr + }) + } + + fn hint>(self, msg: S) -> RResult { + self.ctx(Rctx::Hint(msg.into())) + } + + fn when>(self, msg: S) -> RResult { + self.ctx(Rctx::When(msg.into())) + } +} + +#[extendr] +impl Rerr { + pub fn new() -> Self { + Rerr(Vec::new()) + } + + pub fn info(&self) -> String { + self.0 + .iter() + .rev() + .map(|rctx| match rctx { + Rctx::Extendr(e) => format!("Encountered the following error in Extendr:\n{}", e), + Rctx::Hint(e) => format!("An error occured likely because {}", e), + Rctx::Plain(e) => e.clone(), + Rctx::Polars(e) => format!("Encountered the following error in Polars:\n{}", e), + Rctx::TypeMismatch(name, expected, received) => { + format!( + "The argument [{}] should be a [{}] value, but got [{}] instead", + name, expected, received + ) + } + Rctx::When(e) => format!("When {}", e), + }) + .fold(String::from("Error"), |msg, ctx| { + format!("{}: {}", msg, ctx) + }) + } + + pub fn contexts(&self) -> Vec<&str> { + self.0 + .iter() + .rev() + .map(|rctx| match rctx { + Rctx::Extendr(_) => "Extendr", + Rctx::Hint(_) => "Hint", + Rctx::Plain(_) => "Plain", + Rctx::Polars(_) => "Polars", + Rctx::TypeMismatch(_, _, _) => "TypeMismatch", + Rctx::When(_) => "When", + }) + .collect() + } +} + +// Implementation for transition +impl From for Rerr { + fn from(err_msg: String) -> Self { + Rerr(vec![Rctx::Plain(err_msg)]) + } +} + +impl From for Rerr { + fn from(extendr_err: extendr_api::Error) -> Self { + Rerr(vec![Rctx::Extendr(format!("{:?}", extendr_err))]) + } +} + +impl From for Rerr { + fn from(polars_err: polars::error::PolarsError) -> Self { + let mut rerr = Rerr::new(); + rerr.0.push(Rctx::Polars(format!("{:?}", polars_err))); + match polars_err { + polars::prelude::PolarsError::InvalidOperation(x) => { + rerr.0.push(Rctx::Hint(format!( + "something (likely a column) with name {:?} is not found", + x + ))); + } + _ => {} + }; + rerr + } +} + +#[extendr] +pub fn test_rerr() -> RResult { + Err(Rerr::new()) + .ctx(Rctx::TypeMismatch( + "path".to_string(), + "String".to_string(), + "2.0".to_string(), + )) + .when("calling test function") +} + +extendr_module! { + mod rerr; + impl Rerr; + fn test_rerr; +} From bb905a9c4d44218166998fbf2e44c2379a5bfe28 Mon Sep 17 00:00:00 2001 From: Sicheng Pan Date: Tue, 13 Jun 2023 19:47:22 -0700 Subject: [PATCH 07/24] Use thiserror to refactor Rerr --- src/rust/Cargo.lock | 60 +++++++++++++++++++++--------------- src/rust/Cargo.toml | 1 + src/rust/src/rerr.rs | 73 +++++++++++++++++++++----------------------- 3 files changed, 72 insertions(+), 62 deletions(-) diff --git a/src/rust/Cargo.lock b/src/rust/Cargo.lock index 64480685e..3c1a9a6f0 100644 --- a/src/rust/Cargo.lock +++ b/src/rust/Cargo.lock @@ -138,7 +138,7 @@ checksum = "10f203db73a71dfa2fb6dd22763990fa26f3d2625a6da2da900d23b87d26be27" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 1.0.107", ] [[package]] @@ -149,7 +149,7 @@ checksum = "689894c2db1ea643a50834b999abf1c110887402542955ff5451dab8f861f9ed" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 1.0.107", ] [[package]] @@ -237,7 +237,7 @@ checksum = "1aca418a974d83d40a0c1f0c5cba6ff4bc28d8df099109ca459a2118d40b6322" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 1.0.107", ] [[package]] @@ -458,7 +458,7 @@ dependencies = [ "proc-macro2", "quote", "scratch", - "syn", + "syn 1.0.107", ] [[package]] @@ -475,7 +475,7 @@ checksum = "65e07508b90551e610910fa648a1878991d367064997a596135b86df30daf07e" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 1.0.107", ] [[package]] @@ -519,7 +519,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn", + "syn 1.0.107", ] [[package]] @@ -555,7 +555,7 @@ source = "git+https://github.com/rpolars/extendr?branch=errorhandling#d5eba3affd dependencies = [ "proc-macro2", "quote", - "syn", + "syn 1.0.107", ] [[package]] @@ -671,7 +671,7 @@ checksum = "bdfb8ce053d86b91919aad980c220b1fb8401a9394410e1c289ed7e66b61835d" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 1.0.107", ] [[package]] @@ -1203,7 +1203,7 @@ checksum = "1af1abf82261d780d114014eff4b555e47d823f3b84f893c4388572b40e089fb" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 1.0.107", "target-features", ] @@ -1454,7 +1454,7 @@ checksum = "069bdb1e05adc7a8990dce9cc75370895fbe4e3d58b9b73bf1aee56359344a55" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 1.0.107", ] [[package]] @@ -1740,18 +1740,18 @@ checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" [[package]] name = "proc-macro2" -version = "1.0.50" +version = "1.0.60" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ef7d57beacfaf2d8aee5937dab7b7f28de3cb8b1828479bb5de2a7106f2bae2" +checksum = "dec2b086b7a862cf4de201096214fa870344cf922b2b30c167badb3af3195406" dependencies = [ "unicode-ident", ] [[package]] name = "quote" -version = "1.0.23" +version = "1.0.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8856d8364d252a14d474036ea1358d63c9e6965c8e5c1885c18f73d70bff9c7b" +checksum = "1b9ab9c7eadfd8df19006f1cf1a4aed13540ed5cbc047010ece5826e10825488" dependencies = [ "proc-macro2", ] @@ -1770,6 +1770,7 @@ dependencies = [ "serde_json", "smartstring", "state", + "thiserror", ] [[package]] @@ -1960,7 +1961,7 @@ checksum = "af487d118eecd09402d70a5d72551860e788df87b464af30e5ea6a38c75c541e" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 1.0.107", ] [[package]] @@ -2153,7 +2154,7 @@ dependencies = [ "proc-macro2", "quote", "rustversion", - "syn", + "syn 1.0.107", ] [[package]] @@ -2167,6 +2168,17 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "syn" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32d41677bcbe24c20c52e7c70b0d8db04134c5d1066bf98662e2871ad200ea3e" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "sysinfo" version = "0.28.4" @@ -2198,22 +2210,22 @@ dependencies = [ [[package]] name = "thiserror" -version = "1.0.38" +version = "1.0.40" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a9cd18aa97d5c45c6603caea1da6628790b37f7a34b6ca89522331c5180fed0" +checksum = "978c9a314bd8dc99be594bc3c175faaa9794be04a5a5e153caba6915336cebac" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.38" +version = "1.0.40" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fb327af4685e4d03fa8cbcf1716380da910eeb2bb8be417e7f9fd3fb164f36f" +checksum = "f9456a42c5b0d803c8cd86e73dd7cc9edd429499f37a3550d286d5e86720569f" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.18", ] [[package]] @@ -2270,7 +2282,7 @@ checksum = "4017f8f45139870ca7e672686113917c71c7a6e02d4924eda67186083c03081a" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 1.0.107", ] [[package]] @@ -2381,7 +2393,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn", + "syn 1.0.107", "wasm-bindgen-shared", ] @@ -2415,7 +2427,7 @@ checksum = "07bc0c051dc5f23e307b13285f9d75df86bfdf816c5721e573dec1f9b8aa193c" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 1.0.107", "wasm-bindgen-backend", "wasm-bindgen-shared", ] diff --git a/src/rust/Cargo.toml b/src/rust/Cargo.toml index 66233efdf..a64c28fa7 100644 --- a/src/rust/Cargo.toml +++ b/src/rust/Cargo.toml @@ -24,6 +24,7 @@ state = "0.5.3" rayon = "1.6.1" smartstring = "1.0.1" serde_json = "*" +thiserror = "1.0.40" polars-core = {git = "https://github.com/pola-rs/polars.git", rev = "e973f6386a28f16136fb8ba5a737103f95911861", default_features= false} diff --git a/src/rust/src/rerr.rs b/src/rust/src/rerr.rs index fc0a34440..dd6908585 100644 --- a/src/rust/src/rerr.rs +++ b/src/rust/src/rerr.rs @@ -1,13 +1,22 @@ use extendr_api::{extendr, extendr_module, symbol::class_symbol, Attributes, Rinternals, Robj}; +use thiserror::Error; -#[derive(Clone, Debug)] +#[derive(Clone, Debug, Error)] pub enum Rctx { + #[error("The argument [{0}] casuse an error because")] + BadArgument(String), + #[error("Encountered the following error in Extendr:\n{0}")] Extendr(String), + #[error("Possibly {0}")] Hint(String), + #[error("{0}")] Plain(String), + #[error("Encountered the following error in Polars:\n{0}")] Polars(String), + #[error("When {0}")] When(String), - TypeMismatch(String, String, String), + #[error("Expected a value of type [{0}], but got [{1}] instead")] + TypeMismatch(String, String), } #[derive(Clone, Debug)] @@ -16,11 +25,13 @@ pub type RResult = core::result::Result; pub trait WithRctx { fn ctx(self, rctx: Rctx) -> RResult; - fn hint>(self, msg: S) -> RResult; - fn when>(self, msg: S) -> RResult; + fn on_arg>(self, arg: S) -> RResult; + fn type_mismatch, S: Into>(self, ty: R, val: S) -> RResult; + fn hint>(self, cause: S) -> RResult; + fn when>(self, env: S) -> RResult; } -impl> WithRctx for core::result::Result { +impl> WithRctx for core::result::Result { fn ctx(self, rctx: Rctx) -> RResult { self.map_err(|e| { let mut rerr = e.into(); @@ -29,12 +40,20 @@ impl> WithRctx for core::result::Result { }) } - fn hint>(self, msg: S) -> RResult { - self.ctx(Rctx::Hint(msg.into())) + fn on_arg>(self, arg: S) -> RResult { + self.ctx(Rctx::BadArgument(arg.into())) + } + + fn type_mismatch, S: Into>(self, ty: R, val: S) -> RResult { + self.ctx(Rctx::TypeMismatch(ty.into(), val.into())) } - fn when>(self, msg: S) -> RResult { - self.ctx(Rctx::When(msg.into())) + fn hint>(self, cause: S) -> RResult { + self.ctx(Rctx::Hint(cause.into())) + } + + fn when>(self, env: S) -> RResult { + self.ctx(Rctx::When(env.into())) } } @@ -48,36 +67,17 @@ impl Rerr { self.0 .iter() .rev() - .map(|rctx| match rctx { - Rctx::Extendr(e) => format!("Encountered the following error in Extendr:\n{}", e), - Rctx::Hint(e) => format!("An error occured likely because {}", e), - Rctx::Plain(e) => e.clone(), - Rctx::Polars(e) => format!("Encountered the following error in Polars:\n{}", e), - Rctx::TypeMismatch(name, expected, received) => { - format!( - "The argument [{}] should be a [{}] value, but got [{}] instead", - name, expected, received - ) - } - Rctx::When(e) => format!("When {}", e), - }) - .fold(String::from("Error"), |msg, ctx| { - format!("{}: {}", msg, ctx) + .map(|rerr| format!("{}", rerr)) + .fold(String::from("Error"), |msg, rerr| { + format!("{}: {}", msg, rerr) }) } - pub fn contexts(&self) -> Vec<&str> { + pub fn contexts(&self) -> Vec { self.0 .iter() .rev() - .map(|rctx| match rctx { - Rctx::Extendr(_) => "Extendr", - Rctx::Hint(_) => "Hint", - Rctx::Plain(_) => "Plain", - Rctx::Polars(_) => "Polars", - Rctx::TypeMismatch(_, _, _) => "TypeMismatch", - Rctx::When(_) => "When", - }) + .map(|rerr| format!("{:?}", rerr)) .collect() } } @@ -115,11 +115,8 @@ impl From for Rerr { #[extendr] pub fn test_rerr() -> RResult { Err(Rerr::new()) - .ctx(Rctx::TypeMismatch( - "path".to_string(), - "String".to_string(), - "2.0".to_string(), - )) + .type_mismatch("usize", "-1") + .on_arg("") .when("calling test function") } From 3790129abdb8b19ab7f47fa8386cf165366be873 Mon Sep 17 00:00:00 2001 From: Sicheng Pan Date: Sat, 17 Jun 2023 14:54:31 -0700 Subject: [PATCH 08/24] Refactor robj_to! --- src/rust/src/lazy/dataframe.rs | 4 +- src/rust/src/lazy/dsl.rs | 11 +- src/rust/src/lib.rs | 1 + src/rust/src/rerr.rs | 107 ++++++--- src/rust/src/rlib.rs | 13 +- src/rust/src/utils/mod.rs | 421 ++++++++++++++------------------- 6 files changed, 266 insertions(+), 291 deletions(-) diff --git a/src/rust/src/lazy/dataframe.rs b/src/rust/src/lazy/dataframe.rs index 231ceb321..aded7d951 100644 --- a/src/rust/src/lazy/dataframe.rs +++ b/src/rust/src/lazy/dataframe.rs @@ -4,6 +4,7 @@ use crate::rdatatype::new_asof_strategy; use crate::rdatatype::new_join_type; use crate::rdatatype::new_quantile_interpolation_option; use crate::rdatatype::new_unique_keep_strategy; +use crate::rerr::{Rctx, WithRctx}; use crate::robj_to; use crate::utils::wrappers::null_to_opt; use crate::utils::{r_result_list, try_f64_into_usize}; @@ -285,7 +286,8 @@ impl LazyFrame { .how(JoinType::AsOf(AsOfOptions { strategy: robj_to!(str, strategy).and_then(|s| { new_asof_strategy(s) - .map_err(|err| format!("param [strategy] error because {}", err)) + .map_err(Rctx::Plain) + .bad_arg("stragegy") })?, left_by: left_by.map(|opt_vec_s| opt_vec_s.into_iter().map(|s| s.into()).collect()), right_by: right_by diff --git a/src/rust/src/lazy/dsl.rs b/src/rust/src/lazy/dsl.rs index ebdc11117..eada4da01 100644 --- a/src/rust/src/lazy/dsl.rs +++ b/src/rust/src/lazy/dsl.rs @@ -813,8 +813,10 @@ impl Expr { } pub fn reshape(&self, dims: Vec) -> List { - let dims_result: Result, String> = - dims.iter().map(|x| try_f64_into_i64(*x)).collect(); + let dims_result: Result, String> = dims + .iter() + .map(|x| try_f64_into_i64(*x).map_err(String::from)) + .collect(); let expr_result = dims_result .map(|dims| Expr(self.0.clone().reshape(&dims[..]))) .map_err(|err| format!("reshape: {}", err)); @@ -1793,7 +1795,7 @@ impl Expr { } pub fn str_zfill(&self, alignment: Robj) -> List { - let res = robj_to!(usize, alignment, "in str$zfill(): {:?}") + let res = robj_to!(usize, alignment, "in str$zfill()") .map(|alignment| Expr(self.clone().0.str().zfill(alignment))); r_result_list(res) } @@ -2193,7 +2195,8 @@ impl Expr { //the only cat ns function from dsl.rs fn cat_set_ordering(&self, ordering: Robj) -> Result { let ordering = robj_to!(Map, str, ordering, |s| { - crate::rdatatype::new_categorical_ordering(s) + use crate::rerr::Rctx; + Ok(crate::rdatatype::new_categorical_ordering(s).map_err(Rctx::Plain)?) })?; Ok(self.0.clone().cat().set_ordering(ordering).into()) } diff --git a/src/rust/src/lib.rs b/src/rust/src/lib.rs index b2bb25c6e..af3f21bf9 100644 --- a/src/rust/src/lib.rs +++ b/src/rust/src/lib.rs @@ -1,3 +1,4 @@ +#![feature(min_specialization)] #[cfg(all(target_os = "linux", not(use_mimalloc)))] use jemallocator::Jemalloc; #[cfg(any(not(target_os = "linux"), use_mimalloc))] diff --git a/src/rust/src/rerr.rs b/src/rust/src/rerr.rs index dd6908585..0cc1af409 100644 --- a/src/rust/src/rerr.rs +++ b/src/rust/src/rerr.rs @@ -3,20 +3,24 @@ use thiserror::Error; #[derive(Clone, Debug, Error)] pub enum Rctx { - #[error("The argument [{0}] casuse an error because")] - BadArgument(String), + #[error("The argument [{0}] casuse an error")] + BadArg(String), + #[error("Got value [{0}]")] + BadVal(String), #[error("Encountered the following error in Extendr:\n{0}")] Extendr(String), - #[error("Possibly {0}")] + #[error("Possibly because {0}")] Hint(String), + #[error("Expected a value of type [{0}]")] + Mistyped(String), + #[error("Expected a value that {0}")] + Misvalued(String), #[error("{0}")] Plain(String), #[error("Encountered the following error in Polars:\n{0}")] Polars(String), #[error("When {0}")] When(String), - #[error("Expected a value of type [{0}], but got [{1}] instead")] - TypeMismatch(String, String), } #[derive(Clone, Debug)] @@ -25,9 +29,13 @@ pub type RResult = core::result::Result; pub trait WithRctx { fn ctx(self, rctx: Rctx) -> RResult; - fn on_arg>(self, arg: S) -> RResult; - fn type_mismatch, S: Into>(self, ty: R, val: S) -> RResult; + fn bad_arg>(self, arg: S) -> RResult; + fn bad_robj(self, robj: &Robj) -> RResult; + fn bad_val>(self, val: S) -> RResult; fn hint>(self, cause: S) -> RResult; + fn mistyped>(self, ty: S) -> RResult; + fn misvalued>(self, scope: S) -> RResult; + fn plain>(self, msg: S) -> RResult; fn when>(self, env: S) -> RResult; } @@ -40,18 +48,34 @@ impl> WithRctx for core::result::Result { }) } - fn on_arg>(self, arg: S) -> RResult { - self.ctx(Rctx::BadArgument(arg.into())) + fn bad_arg>(self, arg: S) -> RResult { + self.ctx(Rctx::BadArg(arg.into())) } - fn type_mismatch, S: Into>(self, ty: R, val: S) -> RResult { - self.ctx(Rctx::TypeMismatch(ty.into(), val.into())) + fn bad_robj(self, robj: &Robj) -> RResult { + self.bad_val(rdbg(robj)) + } + + fn bad_val>(self, val: S) -> RResult { + self.ctx(Rctx::BadVal(val.into())) } fn hint>(self, cause: S) -> RResult { self.ctx(Rctx::Hint(cause.into())) } + fn mistyped>(self, ty: S) -> RResult { + self.ctx(Rctx::Mistyped(ty.into())) + } + + fn misvalued>(self, scope: S) -> RResult { + self.ctx(Rctx::Misvalued(scope.into())) + } + + fn plain>(self, msg: S) -> RResult { + self.ctx(Rctx::Plain(msg.into())) + } + fn when>(self, env: S) -> RResult { self.ctx(Rctx::When(env.into())) } @@ -64,41 +88,51 @@ impl Rerr { } pub fn info(&self) -> String { - self.0 - .iter() - .rev() - .map(|rerr| format!("{}", rerr)) - .fold(String::from("Error"), |msg, rerr| { - format!("{}: {}", msg, rerr) - }) + format!("{}", self) } pub fn contexts(&self) -> Vec { - self.0 - .iter() - .rev() - .map(|rerr| format!("{:?}", rerr)) - .collect() + self.0.iter().rev().map(|rerr| rdbg(rerr)).collect() + } +} + +impl std::fmt::Display for Rerr { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "{}", + self.0 + .iter() + .rev() + .map(|rerr| format!("{}", rerr)) + .reduce(|msg, rerr| { format!("{}: {}", msg, rerr) }) + .unwrap_or(String::new()) + ) } } -// Implementation for transition -impl From for Rerr { - fn from(err_msg: String) -> Self { - Rerr(vec![Rctx::Plain(err_msg)]) +impl From for String { + fn from(rerr: Rerr) -> Self { + rerr.info() + } +} + +impl From for Rerr { + default fn from(err: E) -> Self { + Rerr(vec![Rctx::Plain(rdbg(err))]) } } impl From for Rerr { fn from(extendr_err: extendr_api::Error) -> Self { - Rerr(vec![Rctx::Extendr(format!("{:?}", extendr_err))]) + Rerr(vec![Rctx::Extendr(rdbg(extendr_err))]) } } impl From for Rerr { fn from(polars_err: polars::error::PolarsError) -> Self { let mut rerr = Rerr::new(); - rerr.0.push(Rctx::Polars(format!("{:?}", polars_err))); + rerr.0.push(Rctx::Polars(rdbg(&polars_err))); match polars_err { polars::prelude::PolarsError::InvalidOperation(x) => { rerr.0.push(Rctx::Hint(format!( @@ -112,11 +146,20 @@ impl From for Rerr { } } +pub fn rerr() -> RResult { + Err(Rerr::new()) +} + +pub fn rdbg(o: T) -> String { + format!("{:?}", o) +} + #[extendr] pub fn test_rerr() -> RResult { - Err(Rerr::new()) - .type_mismatch("usize", "-1") - .on_arg("") + rerr() + .bad_val("-1") + .mistyped("usize") + .bad_arg("path") .when("calling test function") } diff --git a/src/rust/src/rlib.rs b/src/rust/src/rlib.rs index 738e60bc0..2bf89ad9c 100644 --- a/src/rust/src/rlib.rs +++ b/src/rust/src/rlib.rs @@ -1,5 +1,6 @@ use crate::lazy::dsl::Expr; use crate::rdataframe::DataFrame; +use crate::rerr::{rdbg, RResult}; use crate::{rdataframe::VecDataFrame, utils::r_result_list}; use crate::lazy::dsl::ProtoExprArray; @@ -250,17 +251,17 @@ fn rb_list_to_df(r_batches: List, names: Vec) -> Result Result { - robj_to!(usize, robj).map(|x| x.to_string()) +fn test_robj_to_usize(robj: Robj) -> RResult { + robj_to!(usize, robj).map(rdbg) } #[extendr] -fn test_robj_to_i64(robj: Robj) -> Result { - robj_to!(i64, robj).map(|x| x.to_string()) +fn test_robj_to_i64(robj: Robj) -> RResult { + robj_to!(i64, robj).map(rdbg) } #[extendr] -fn test_robj_to_u32(robj: Robj) -> Result { - robj_to!(u32, robj).map(|x| x.to_string()) +fn test_robj_to_u32(robj: Robj) -> RResult { + robj_to!(u32, robj).map(rdbg) } extendr_module! { diff --git a/src/rust/src/utils/mod.rs b/src/rust/src/utils/mod.rs index e082af50a..6ad97dbd7 100644 --- a/src/rust/src/utils/mod.rs +++ b/src/rust/src/utils/mod.rs @@ -3,7 +3,9 @@ pub mod extendr_concurrent; pub mod wrappers; use crate::lazy::dsl::Expr; use crate::rdatatype::RPolarsDataType; +use crate::rerr::{rdbg, rerr, RResult, Rerr, WithRctx}; use extendr_api::prelude::list; +use std::any::type_name as tn; use extendr_api::Attributes; use extendr_api::ExternalPtr; @@ -247,55 +249,55 @@ const USIZE_MAX_INTO_F64: f64 = usize::MAX as f64; const U32_MAX_INTO_F64: f64 = u32::MAX as f64; pub const BIT64_NA_ECODING: i64 = -9223372036854775808i64; -const MSG_INTEGERISH_MAX: &str = - "exceeds double->integer unambigious conversion bound of 2^52 = 4503599627370496.0"; -const MSG_INTEGERISH_MIN: &str = - "exceeds double->integer unambigious conversion bound of -(2^52)= -4503599627370496.0"; -const MSG_NAN: &str = "the value cannot be NaN"; -const MSG_NO_LESS_ONE: &str = "cannot be less than one"; - -pub fn try_f64_into_usize_no_zero(x: f64) -> std::result::Result { +const WITHIN_INT_MAX: &str = + "cannot exceeds double->integer unambigious conversion bound of 2^52 = 4503599627370496.0"; +const WITHIN_INT_MIN: &str = + "cannot exceeds double->integer unambigious conversion bound of -(2^52)= -4503599627370496.0"; +const WITHIN_USIZE_MAX: &str = "cannot exceed the upper bound for usize"; +const WITHIN_U32_MAX: &str = "cannot exceed the upper bound for u32 of 4294967295"; +const WITHIN_U8_MAX: &str = "cannot exceed the upper bound for u8 of 255"; +const NOT_NAN: &str = "cannot be NaN"; +const NO_LESS_THAN_ONE: &str = "cannot be less than one"; +const NO_LESS_THAN_ZERO: &str = "cannot be less than zero"; + +pub fn try_f64_into_usize_no_zero(x: f64) -> RResult { + let base_err = rerr().bad_val(rdbg(x)); match x { - _ if x.is_nan() => Err(MSG_NAN.to_string()), - _ if x < 1.0 => Err(format!("the value {} {}", x, MSG_NO_LESS_ONE)), - _ if x > R_MAX_INTEGERISH => Err(format!("the value {} {}", x, MSG_INTEGERISH_MAX)), - _ if x > USIZE_MAX_INTO_F64 => Err(format!( - "the value {} cannot exceed usize::MAX {}", - x, - usize::MAX - )), + _ if x.is_nan() => base_err.misvalued(NOT_NAN), + _ if x < 1.0 => base_err.misvalued(NO_LESS_THAN_ONE), + _ if x > R_MAX_INTEGERISH => base_err.misvalued(WITHIN_INT_MAX), + _ if x > USIZE_MAX_INTO_F64 => base_err.misvalued(WITHIN_USIZE_MAX), _ => Ok(x as usize), } } -pub fn try_f64_into_usize(x: f64) -> std::result::Result { +pub fn try_f64_into_usize(x: f64) -> RResult { + let base_err = rerr().bad_val(rdbg(x)); match x { - _ if x.is_nan() => Err(MSG_NAN.to_string()), - _ if x < 0.0 => Err(format!("the value {} cannot be less than zero", x)), - _ if x > R_MAX_INTEGERISH => Err(format!("the value {} {}", x, MSG_INTEGERISH_MAX)), - _ if x > USIZE_MAX_INTO_F64 => Err(format!( - "the value {} cannot exceed usize::MAX {}", - x, - usize::MAX - )), + _ if x.is_nan() => base_err.misvalued(NOT_NAN), + _ if x < 0.0 => base_err.misvalued(NO_LESS_THAN_ZERO), + _ if x > R_MAX_INTEGERISH => base_err.misvalued(WITHIN_INT_MAX), + _ if x > USIZE_MAX_INTO_F64 => base_err.misvalued(WITHIN_USIZE_MAX), _ => Ok(x as usize), } } -pub fn try_f64_into_u64(x: f64) -> std::result::Result { +pub fn try_f64_into_u64(x: f64) -> RResult { + let base_err = rerr().bad_val(rdbg(x)); match x { - _ if x.is_nan() => Err(MSG_NAN.to_string()), - _ if x < 0.0 => Err(format!("the value {} cannot be less than zero", x)), - _ if x > R_MAX_INTEGERISH => Err(format!("the value {} {}", x, MSG_INTEGERISH_MAX)), + _ if x.is_nan() => base_err.misvalued(NOT_NAN), + _ if x < 0.0 => base_err.misvalued(NO_LESS_THAN_ZERO), + _ if x > R_MAX_INTEGERISH => base_err.misvalued(WITHIN_INT_MAX), _ => Ok(x as u64), } } -pub fn try_f64_into_i64(x: f64) -> std::result::Result { +pub fn try_f64_into_i64(x: f64) -> RResult { + let base_err = rerr().bad_val(rdbg(x)); match x { - _ if x.is_nan() => Err(MSG_NAN.to_string()), - _ if x < R_MIN_INTEGERISH => Err(format!("the value {} {}", x, MSG_INTEGERISH_MIN)), - _ if x > R_MAX_INTEGERISH => Err(format!("the value {} {}", x, MSG_INTEGERISH_MAX)), + _ if x.is_nan() => base_err.misvalued(NOT_NAN), + _ if x < R_MIN_INTEGERISH => base_err.misvalued(WITHIN_INT_MIN), + _ if x > R_MAX_INTEGERISH => base_err.misvalued(WITHIN_INT_MAX), // should not matter // _ if x > I64_MAX_INTO_F64 => Err(format!( // "the value {} cannot exceed i64::MAX {}", @@ -306,54 +308,63 @@ pub fn try_f64_into_i64(x: f64) -> std::result::Result { // "the value {} cannot exceed i64::MIN {}", // x, // i64::MIN - // )), + // )) _ => Ok(x as i64), } } -pub fn try_f64_into_u32(x: f64) -> std::result::Result { +pub fn try_f64_into_u32(x: f64) -> RResult { + let base_err = rerr().bad_val(rdbg(x)); match x { - _ if x.is_nan() => Err(MSG_NAN.to_string()), - _ if x < 0.0 => Err(format!("the value {} cannot be less than zero", x)), - _ if x > U32_MAX_INTO_F64 => Err(format!( - "the value {} cannot exceed u32::MAX {}", - x, - u32::MAX - )), + _ if x.is_nan() => base_err.misvalued(NOT_NAN), + _ if x < 0.0 => base_err.misvalued(NO_LESS_THAN_ZERO), + _ if x > U32_MAX_INTO_F64 => base_err.misvalued(WITHIN_U32_MAX), _ => Ok(x as u32), } } -pub fn try_i64_into_u64(x: i64) -> std::result::Result { +pub fn try_i64_into_u64(x: i64) -> RResult { + let base_err = rerr().bad_val(rdbg(x)); match x { - _ if x < 0 => Err(format!("the value {} cannot be less than zero", x)), + _ if x < 0 => base_err.misvalued(NO_LESS_THAN_ZERO), _ => Ok(x as u64), } } -pub fn try_i64_into_usize(x: i64) -> std::result::Result { +pub fn try_i64_into_usize(x: i64) -> RResult { + let base_err = rerr().bad_val(rdbg(x)); match x { - _ if x < 0 => Err(format!("the value {} cannot be less than zero", x)), + _ if x < 0 => base_err.misvalued(NO_LESS_THAN_ZERO), _ => Ok(x as usize), } } -pub fn try_i64_into_u32(x: i64) -> std::result::Result { +pub fn try_i64_into_u32(x: i64) -> RResult { + let base_err = rerr().bad_val(rdbg(x)); match x { - _ if x < 0 => Err(format!("the value {} cannot be less than zero", x)), - _ if x > u32::MAX as i64 => Err("exceeds u32 max value".to_string()), + _ if x < 0 => base_err.misvalued(NO_LESS_THAN_ZERO), + _ if x > u32::MAX as i64 => base_err.misvalued(WITHIN_U32_MAX), _ => Ok(x as u32), } } -pub fn try_i64_into_u8(x: i64) -> std::result::Result { +pub fn try_i64_into_u8(x: i64) -> RResult { + let base_err = rerr().bad_val(rdbg(x)); match x { - _ if x < 0 => Err(format!("the value {} cannot be less than zero", x)), - _ if x > u8::MAX as i64 => Err("exceeds u8 max value".to_string()), + _ if x < 0 => base_err.misvalued(NO_LESS_THAN_ZERO), + _ if x > u8::MAX as i64 => base_err.misvalued(WITHIN_U8_MAX), _ => Ok(x as u8), } } +pub fn try_u64_into_usize(x: u64) -> RResult { + let base_err = rerr().bad_val(rdbg(x)); + match x { + _ if x > usize::MAX as u64 => base_err.misvalued(WITHIN_USIZE_MAX), + _ => Ok(x as usize), + } +} + use extendr_api::Robj; pub fn r_result_list(result: Result) -> list::List where @@ -405,22 +416,21 @@ pub fn reinterpret(s: &pl::Series, signed: bool) -> pl::PolarsResult } } -pub fn unpack_r_result_list(robj: extendr_api::Robj) -> std::result::Result { +pub fn unpack_r_result_list(robj: extendr_api::Robj) -> RResult { use extendr_api::*; if robj.inherits("extendr_result") { let l = robj.as_list().unwrap(); let ok = l.elt(0).unwrap(); let err = l.elt(1).unwrap(); match (ok.rtype(), err.rtype()) { - (Rtype::Null, Rtype::Null) => Ok(ok), + (_, Rtype::Null) => Ok(ok), (Rtype::Null, _) => { if let Some(err_msg) = err.as_str() { - Err(err_msg.to_string()) + rerr().plain(err_msg) } else { - Err(format!("{:?}", err)) + rerr().plain(rdbg(err)) } } - (_, Rtype::Null) => Ok(ok), (_, _) => unreachable!("Internal error: failed to unpack r_result_list"), } } else { @@ -428,7 +438,7 @@ pub fn unpack_r_result_list(robj: extendr_api::Robj) -> std::result::Result std::result::Result { +pub fn robj_to_char(robj: extendr_api::Robj) -> RResult { let robj = unpack_r_result_list(robj)?; let mut fchar_iter = if let Some(char_str) = robj.as_str() { char_str.chars() @@ -437,173 +447,88 @@ pub fn robj_to_char(robj: extendr_api::Robj) -> std::result::Result Ok(x), - (_, _) => Err(format!("is not a single char string, but {:?}", robj)), + (_, _) => rerr().bad_robj(&robj).mistyped(tn::()), } } -pub fn robj_to_string(robj: extendr_api::Robj) -> std::result::Result { +pub fn robj_to_string(robj: extendr_api::Robj) -> RResult { let robj = unpack_r_result_list(robj)?; use extendr_api::Length; match (robj.as_str(), robj.len()) { (Some(x), 1) => Ok(x.to_string()), - (_, _) => Err(format!("is not a single string, but {:?}", robj)), + (_, _) => rerr().bad_robj(&robj).mistyped(tn::()), } } -pub fn robj_to_str<'a>(robj: extendr_api::Robj) -> std::result::Result<&'a str, String> { +pub fn robj_to_str<'a>(robj: extendr_api::Robj) -> RResult<&'a str> { let robj = unpack_r_result_list(robj)?; use extendr_api::Length; match (robj.as_str(), robj.len()) { (Some(x), 1) => Ok(x), - (_, _) => Err(format!("is not a single string, but {:?}", robj)), + (_, _) => rerr().bad_robj(&robj).mistyped(tn::<&'a str>()), } } -pub fn robj_to_usize(robj: extendr_api::Robj) -> std::result::Result { - let robj = unpack_r_result_list(robj)?; - use extendr_api::*; - if robj.rtype() == Rtype::Strings && robj.len() == 1 { - let us = robj - .as_str() - .unwrap_or("empty string") - .parse::() - .map_err(|err| format!("failed parsing {:?} to usize", err)); - return us; - } - - match (robj.rtype(), robj.len()) { - (Rtype::Strings, 1) => { - let us = robj - .as_str() - .unwrap_or("empty string") - .parse::() - .map_err(|err| format!("failed parsing {:?} to usize", err)); - return us; - } - (Rtype::Doubles, 1) if robj.inherits("integer64") => { - let usize_result = robj_to_i64(robj).and_then(try_i64_into_usize); - return usize_result; - } - (Rtype::Doubles, 1) => robj.as_real(), - (Rtype::Integers, 1) => robj.as_integer().map(|i| i as f64), - (_, _) => None, - } - .ok_or_else(|| { - format!( - "is not a scalar integer or double as required, but {:?}", - robj - ) - }) - .and_then(try_f64_into_usize) +pub fn robj_to_usize(robj: extendr_api::Robj) -> RResult { + robj_to_u64(robj).and_then(try_u64_into_usize) } -pub fn robj_to_i64(robj: extendr_api::Robj) -> std::result::Result { +pub fn robj_to_i64(robj: extendr_api::Robj) -> RResult { let robj = unpack_r_result_list(robj)?; use extendr_api::*; - match (robj.rtype(), robj.len()) { - (Rtype::Strings, 1) => { - let us = robj - .as_str() - .unwrap_or("empty string") - .parse::() - .map_err(|err| format!("failed parsing {:?} to usize", err)); - return us; - } + return match (robj.rtype(), robj.len()) { + (Rtype::Strings, 1) => robj + .as_str() + .unwrap_or("") + .parse::() + .ok(), //specialized integer64 conversion - (Rtype::Doubles, 1) if robj.inherits("integer64") => { - let res = robj - .as_real() - .ok_or_else(|| format!("integer64 conversion failed for, but {:?}", robj)) - .and_then(|x| { - let x = x.to_bits() as i64; - if x == crate::utils::BIT64_NA_ECODING { - Err("scalar arguments do not support integer64 NA value".to_string()) - } else { - Ok(x) - } - }); - - return res; - } + (Rtype::Doubles, 1) if robj.inherits("integer64") => robj + .as_real() + .and_then(|v| i64::try_from(v.to_bits()).ok()) + .filter(|val| *val != crate::utils::BIT64_NA_ECODING), //from R doubles or integers - (Rtype::Doubles, 1) => robj.as_real(), - (Rtype::Integers, 1) => robj.as_integer().map(|i| i as f64), + (Rtype::Doubles, 1) => robj.as_real().and_then(|v| try_f64_into_i64(v).ok()), + (Rtype::Integers, 1) => robj.as_integer().map(i64::from), (_, _) => None, } - .ok_or_else(|| format!("not a scalar integer or double as required, but {:?}", robj)) - .and_then(try_f64_into_i64) + .ok_or(Rerr::new()) + .bad_robj(&robj) + .mistyped(tn::()); } -pub fn robj_to_u64(robj: extendr_api::Robj) -> std::result::Result { - let robj = unpack_r_result_list(robj)?; - use extendr_api::*; - match (robj.rtype(), robj.len()) { - (Rtype::Strings, 1) => return robj_to_usize(robj).map(|x| x as u64), - //specialized integer64 conversion - (Rtype::Doubles, 1) if robj.inherits("integer64") => { - let usize_result = robj_to_i64(robj).and_then(try_i64_into_u64); - return usize_result; - } - (Rtype::Doubles, 1) => robj.as_real(), - (Rtype::Integers, 1) => robj.as_integer().map(|i| i as f64), - (_, _) => None, - } - .ok_or_else(|| { - format!( - "is not a scalar integer or double as required, but {:?}", - robj - ) - }) - .and_then(try_f64_into_u64) +pub fn robj_to_u64(robj: extendr_api::Robj) -> RResult { + robj_to_i64(robj).and_then(try_i64_into_u64) } -pub fn robj_to_u32(robj: extendr_api::Robj) -> std::result::Result { - let robj = unpack_r_result_list(robj)?; - use extendr_api::*; - match (robj.rtype(), robj.len()) { - (Rtype::Strings, 1) => return robj_to_i64(robj).and_then(try_i64_into_u32), - (Rtype::Doubles, 1) if robj.inherits("integer64") => { - let usize_result = robj_to_i64(robj).and_then(try_i64_into_u32); - return usize_result; - } - (Rtype::Doubles, 1) => robj.as_real(), - (Rtype::Integers, 1) => robj.as_integer().map(|i| i as f64), - (_, _) => None, - } - .ok_or_else(|| { - format!( - "is not a scalar integer or double as required, but {:?}", - robj - ) - }) - .and_then(try_f64_into_u32) +pub fn robj_to_u32(robj: extendr_api::Robj) -> RResult { + robj_to_i64(robj).and_then(try_i64_into_u32) } -pub fn robj_to_u8(robj: extendr_api::Robj) -> std::result::Result { - let robj = unpack_r_result_list(robj)?; +pub fn robj_to_u8(robj: extendr_api::Robj) -> RResult { robj_to_i64(robj).and_then(try_i64_into_u8) } -pub fn robj_to_bool(robj: extendr_api::Robj) -> std::result::Result { +pub fn robj_to_bool(robj: extendr_api::Robj) -> RResult { let robj = unpack_r_result_list(robj)?; - use extendr_api::*; - match (robj.rtype(), robj.len()) { - (Rtype::Logicals, 1) => robj.as_bool(), - (_, _) => None, - } - .ok_or_else(|| format!("is not a single bool as required, but {:?}", robj)) + robj.as_bool() + .ok_or(Rerr::new()) + .bad_robj(&robj) + .mistyped(tn::()) } -pub fn robj_to_binary_vec(robj: extendr_api::Robj) -> std::result::Result, String> { +pub fn robj_to_binary_vec(robj: extendr_api::Robj) -> RResult> { let robj = unpack_r_result_list(robj)?; let binary_vec: Vec = robj .as_raw_slice() - .ok_or_else(|| format!("is not an R raw as required, but {:?}", robj))? + .ok_or(Rerr::new()) + .bad_robj(&robj) + .mistyped(tn::>())? .to_vec(); Ok(binary_vec) } -pub fn robj_to_rarrow_schema(robj: extendr_api::Robj) -> std::result::Result { +pub fn robj_to_rarrow_schema(robj: extendr_api::Robj) -> RResult { let robj = unpack_r_result_list(robj)?; let is_arrow_schema = robj @@ -618,14 +543,13 @@ pub fn robj_to_rarrow_schema(robj: extendr_api::Robj) -> std::result::Result std::result::Result { +pub fn robj_to_rarrow_field(robj: extendr_api::Robj) -> RResult { let robj = unpack_r_result_list(robj)?; let is_arrow_schema = robj @@ -639,58 +563,51 @@ pub fn robj_to_rarrow_field(robj: extendr_api::Robj) -> std::result::Result std::result::Result { +pub fn robj_to_datatype(robj: extendr_api::Robj) -> RResult { + let rv = rdbg(&robj); let res: ExtendrResult> = robj.try_into(); - let ext_dt = res.map_err(|err| format!("not an DataType, because {:?}", err))?; + let ext_dt = res.bad_val(rv).mistyped(tn::())?; Ok(RPolarsDataType(ext_dt.0.clone())) } -pub fn robj_to_rexpr( - robj: extendr_api::Robj, - str_to_lit: bool, -) -> std::result::Result { +pub fn robj_to_rexpr(robj: extendr_api::Robj, str_to_lit: bool) -> RResult { let robj = unpack_r_result_list(robj)?; + let rv = rdbg(&robj); //call wrap_e on R side use extendr_api::*; - let new_col_expr = - extendr_api::call!("polars:::wrap_e", robj, str_to_lit).map_err(|err| err.to_string())?; + let new_col_expr = extendr_api::call!("polars:::wrap_e", robj, str_to_lit)?; //convert output into Expr let res: ExtendrResult> = new_col_expr.try_into(); - let ext_expr = res.map_err(|err| format!("not an Expr, because {:?}", err))?; + let ext_expr = res.bad_val(rv).mistyped(tn::())?; Ok(Expr(ext_expr.0.clone())) } -pub fn robj_to_lazyframe( - robj: extendr_api::Robj, -) -> std::result::Result { +pub fn robj_to_lazyframe(robj: extendr_api::Robj) -> RResult { let robj = unpack_r_result_list(robj)?; + let rv = rdbg(&robj); use crate::rdataframe::LazyFrame; let res: Result, _> = robj.try_into(); - let ext_ldf = res.map_err(|err| format!("not an LazyFrame, because {:?}", err))?; + let ext_ldf = res.bad_val(rv).mistyped(tn::())?; Ok(LazyFrame(ext_ldf.0.clone())) } -pub fn list_expr_to_vec_pl_expr( - robj: Robj, - str_to_lit: bool, -) -> std::result::Result, String> { +pub fn list_expr_to_vec_pl_expr(robj: Robj, str_to_lit: bool) -> RResult> { use extendr_api::*; let robj = unpack_r_result_list(robj)?; - let l = robj.as_list().ok_or_else(|| "is not a list".to_string())?; + let l = robj.as_list().ok_or(Rerr::new()).mistyped(tn::())?; let iter = l .iter() .map(|(_, robj)| robj_to_rexpr(robj, str_to_lit).map(|e| e.0)); - crate::utils::collect_hinted_result::(l.len(), iter) + crate::utils::collect_hinted_result_rerr::(l.len(), iter) } pub fn iter_pl_expr_to_list_expr(ite: T) -> extendr_api::List @@ -787,63 +704,60 @@ macro_rules! robj_to_inner { #[macro_export] macro_rules! robj_to { (Option, $type:ident, $a:ident) => {{ + use $crate::rerr::WithRctx; $crate::utils::unpack_r_result_list($a).and_then(|$a| { if ($a.is_null()) { Ok(None) } else { - Some( - $crate::robj_to_inner!($type, $a) - .map_err(|err| format!("the arg [{}] {}", stringify!($a), err)), - ) - .transpose() + Some($crate::robj_to_inner!($type, $a).bad_arg(stringify!($a))).transpose() } }) }}; //iterate list and call this macro again on inner objects (Vec, $type:ident, $a:ident) => {{ + use $crate::rerr::WithRctx; //unpack raise any R result error - $crate::utils::unpack_r_result_list($a) - .map_err(|err| format!("the arg [{}] {}", stringify!($a), err)) - .and_then(|x: Robj| { - //coerce R vectors into list - let x = if !x.is_list() && x.len() > 1 { - extendr_api::call!("as.list", x) - .map_err(|err| format!("could not coerce to list: {}", err))? - } else { - x - }; - - if x.is_list() { - // convert each element in list to $type - let iter = x.as_list().unwrap().iter().enumerate().map(|(i, (_, $a))| { - robj_to!($type, $a, format!("element no. [{}] of ", i + 1)) - }); - $crate::utils::collect_hinted_result::<$type, String>(x.len(), iter) - } else { - // single value without list, convert as is and wrap in a list - let $a = x; - Ok(vec![robj_to!($type, $a)?]) - } - }) + $crate::utils::unpack_r_result_list($a).and_then(|x: Robj| { + //coerce R vectors into list + let x = if !x.is_list() && x.len() > 1 { + extendr_api::call!("as.list", x).mistyped(std::any::type_name::())? + } else { + x + }; + + if x.is_list() { + // convert each element in list to $type + let iter = x.as_list().unwrap().iter().enumerate().map(|(i, (_, $a))| { + robj_to!($type, $a, format!("element no. [{}] of ", i + 1)) + }); + $crate::utils::collect_hinted_result_rerr::<$type>(x.len(), iter) + } else { + // single value without list, convert as is and wrap in a list + let $a = x; + Ok(vec![robj_to!($type, $a)?]) + } + }) }}; - (Map, $type:ident, $a:ident, $f:expr) => { + (Map, $type:ident, $a:ident, $f:expr) => {{ + use $crate::rerr::WithRctx; $crate::robj_to_inner!($type, $a) .and_then($f) - .map_err(|err| format!("the arg [{}] {}", stringify!($a), err)) - }; + .bad_arg(stringify!($a)) + }}; - ($type:ident, $a:ident) => { - $crate::robj_to_inner!($type, $a) - .map_err(|err| format!("the arg [{}] {}", stringify!($a), err)) - }; + ($type:ident, $a:ident) => {{ + use $crate::rerr::WithRctx; + $crate::robj_to_inner!($type, $a).bad_arg(stringify!($a)) + }}; - ($type:ident, $a:ident, $b:expr) => { + ($type:ident, $a:ident, $b:expr) => {{ + use $crate::rerr::WithRctx; $crate::robj_to_inner!($type, $a) - .map_err(|err| format!("the arg [{}] {}", stringify!($a), err)) - .map_err(|err| format!("{} {}", $b, err)) - }; + .hint($b) + .bad_arg(stringify!($a)) + }}; } pub fn collect_hinted_result( @@ -856,3 +770,14 @@ pub fn collect_hinted_result( } Ok(new_vec) } + +pub fn collect_hinted_result_rerr( + size: usize, + iter: impl IntoIterator>, +) -> RResult> { + let mut new_vec = Vec::with_capacity(size); + for item in iter { + new_vec.push(item?); + } + Ok(new_vec) +} From 26c5d8c8815eaf444551f62f3e226aa04fac8bea Mon Sep 17 00:00:00 2001 From: Sicheng Pan Date: Sat, 17 Jun 2023 15:27:39 -0700 Subject: [PATCH 09/24] Convert Rerr contexts to named vec for R --- src/rust/src/rerr.rs | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/src/rust/src/rerr.rs b/src/rust/src/rerr.rs index 0cc1af409..4a5998746 100644 --- a/src/rust/src/rerr.rs +++ b/src/rust/src/rerr.rs @@ -1,4 +1,6 @@ -use extendr_api::{extendr, extendr_module, symbol::class_symbol, Attributes, Rinternals, Robj}; +use extendr_api::{ + extendr, extendr_module, symbol::class_symbol, Attributes, Pairlist, Rinternals, Robj, +}; use thiserror::Error; #[derive(Clone, Debug, Error)] @@ -91,8 +93,18 @@ impl Rerr { format!("{}", self) } - pub fn contexts(&self) -> Vec { - self.0.iter().rev().map(|rerr| rdbg(rerr)).collect() + pub fn contexts(&self) -> Pairlist { + Pairlist::from_pairs(self.0.iter().rev().map(|rctx| match rctx { + Rctx::BadArg(arg) => ("BadArgument", arg), + Rctx::BadVal(val) => ("BadValue", val), + Rctx::Extendr(err) => ("ExtendrError", err), + Rctx::Hint(msg) => ("Hint", msg), + Rctx::Mistyped(ty) => ("TypeMismatch", ty), + Rctx::Misvalued(scope) => ("ValueOutOfScope", scope), + Rctx::Plain(msg) => ("PlainErrorMessage", msg), + Rctx::Polars(err) => ("PolarsError", err), + Rctx::When(target) => ("When", target), + })) } } From 8bd8bbf5d177b75cdbfe3475ef5304bc14803f64 Mon Sep 17 00:00:00 2001 From: Sicheng Pan Date: Sun, 18 Jun 2023 19:03:58 -0700 Subject: [PATCH 10/24] Update unit tests --- R/rust_result.R | 31 ++++++++++++++++++++++++ flake.nix | 2 +- tests/testthat/helper.R | 11 +++++++++ tests/testthat/test-bit64.R | 36 ++++++++++++++-------------- tests/testthat/test-dataframe.R | 4 ++-- tests/testthat/test-expr.R | 4 ++-- tests/testthat/test-expr_string.R | 32 ++++++++++++------------- tests/testthat/test-expr_struct.R | 6 ++--- tests/testthat/test-lazy.R | 8 +++---- tests/testthat/test-lazy_functions.R | 4 ++-- 10 files changed, 90 insertions(+), 48 deletions(-) diff --git a/R/rust_result.R b/R/rust_result.R index b26e99395..f3e568d29 100644 --- a/R/rust_result.R +++ b/R/rust_result.R @@ -180,3 +180,34 @@ result = function(x, msg = "an error because:\n") { } ) } + +# Alternative unwrap that keeps the Rerr +unwrap_rerr = function(result) { + if (!is_result(result)) { + stopf("Internal error: cannot unwrap non result") + } + if (polars:::is_ok(result)) return(result$ok) + err = result$err + cond = errorCondition( + capture.output(print(err)) + ) + if(inherits(err, "Rerr")) { + cond$Rerr = err + class(cond) = c("Rerr_error", "error", "condition") + } + + stop(cond) +} + +# Alternative result that captures the Rerr from the alternative unwrap +result_rerr = function(expr) { + tryCatch( + polars:::Ok(expr), + Rerr_error = function(err) { + polars:::Err(err$Rerr) + }, + error = function(err) { + polars:::Err(err) + } + ) +} \ No newline at end of file diff --git a/flake.nix b/flake.nix index ad4be1b3a..73055f3eb 100644 --- a/flake.nix +++ b/flake.nix @@ -38,7 +38,7 @@ }; # Create R development environment with r-polars and other useful libraries rvenv = pkgs.rWrapper.override { - packages = with pkgs.rPackages; [ renv ]; + packages = with pkgs.rPackages; [ languageserver renv ]; }; in { packages.default = rpolars; diff --git a/tests/testthat/helper.R b/tests/testthat/helper.R index 1a8eafdaf..4c3547d88 100644 --- a/tests/testthat/helper.R +++ b/tests/testthat/helper.R @@ -74,3 +74,14 @@ make_print_cases = function() { "POLARS_FMT_MAX_ROWS", "2", ) } + +# Expect a Rerr with given contexts +expect_rerr = function(expr, ctxs) { + result = result_rerr(expr) + expect_true(is_err(result)) + expect_identical(class(result$err), "Rerr") + expect_identical( + names(result$err$contexts()), + ctxs + ) +} diff --git a/tests/testthat/test-bit64.R b/tests/testthat/test-bit64.R index 49b5f07cc..67804dd61 100644 --- a/tests/testthat/test-bit64.R +++ b/tests/testthat/test-bit64.R @@ -44,34 +44,34 @@ test_that("robj_to! from bit64", { ) # NO NA - expect_grepl_error( - unwrap(polars:::test_robj_to_i64(bit64::as.integer64(NA))), - "scalar arguments do not support integer64 NA value" + expect_rerr( + unwrap_rerr(polars:::test_robj_to_i64(bit64::as.integer64(NA))), + c("BadArgument", "TypeMismatch", "BadValue") ) - expect_grepl_error( - unwrap(polars:::test_robj_to_usize(bit64::as.integer64(NA))), - "scalar arguments do not support integer64 NA value" + expect_rerr( + unwrap_rerr(polars:::test_robj_to_usize(bit64::as.integer64(NA))), + c("BadArgument", "TypeMismatch", "BadValue") ) # NO OVERFLOW - expect_grepl_error( - unwrap(polars:::test_robj_to_u32(2^57)), - "the value 144115188075855870 cannot exceed u32\\:\\:MAX 4294967295" + expect_rerr( + unwrap_rerr(polars:::test_robj_to_u32(2^57)), + c("BadArgument", "TypeMismatch", "BadValue") ) # NO NEGATIVE - expect_grepl_error( - unwrap(polars:::test_robj_to_usize(bit64::as.integer64(-1))), - "the value -1 cannot be less than zero" + expect_rerr( + unwrap_rerr(polars:::test_robj_to_usize(bit64::as.integer64(-1))), + c("BadArgument", "TypeMismatch", "BadValue") ) - expect_grepl_error( - unwrap(polars:::test_robj_to_u32(bit64::as.integer64(-1))), - "the value -1 cannot be less than zero" + expect_rerr( + unwrap_rerr(polars:::test_robj_to_u32(bit64::as.integer64(-1))), + c("BadArgument", "TypeMismatch", "BadValue") ) # NO length>1 - expect_grepl_error( - unwrap(polars:::test_robj_to_usize(bit64::as.integer64(c(1:2)))), - "is not a scalar integer or double as required" + expect_rerr( + unwrap_rerr(polars:::test_robj_to_usize(bit64::as.integer64(c(1:2)))), + c("BadArgument", "TypeMismatch", "BadValue") ) }) diff --git a/tests/testthat/test-dataframe.R b/tests/testthat/test-dataframe.R index e5b8e8564..a65b7083b 100644 --- a/tests/testthat/test-dataframe.R +++ b/tests/testthat/test-dataframe.R @@ -461,10 +461,10 @@ test_that("simple translations", { expect_equal(a, 2816, tolerance = .1) # trigger u8 conversion errors - expect_grepl_error(pl$DataFrame(mtcars)$std(256), c("ddof", "exceeds u8 max value")) + expect_grepl_error(pl$DataFrame(mtcars)$std(256), c("ddof", "exceed the upper bound for u8 of 255")) expect_grepl_error( pl$DataFrame(mtcars)$var(-1), - c("ddof", "the value -1 cannot be less than zero") + c("ddof", "cannot be less than zero") ) }) diff --git a/tests/testthat/test-expr.R b/tests/testthat/test-expr.R index 6d0bdea02..db3c0179d 100644 --- a/tests/testthat/test-expr.R +++ b/tests/testthat/test-expr.R @@ -1159,8 +1159,8 @@ test_that("std var", { expect_true(pl$select(pl$lit(1:5)$var(3))$to_list()[[1L]] != var(1:5)) # trigger u8 conversion errors - expect_grepl_error(pl$lit(1:321)$std(256), c("ddof", "exceeds u8 max value")) - expect_grepl_error(pl$lit(1:321)$var(-1), c("ddof", "the value -1 cannot be less than zero")) + expect_grepl_error(pl$lit(1:321)$std(256), c("ddof", "cannot exceed the upper bound for u8 of 255")) + expect_grepl_error(pl$lit(1:321)$var(-1), c("ddof", "cannot be less than zero")) }) diff --git a/tests/testthat/test-expr_string.R b/tests/testthat/test-expr_string.R index 210f73f50..1c9010ac2 100644 --- a/tests/testthat/test-expr_string.R +++ b/tests/testthat/test-expr_string.R @@ -189,13 +189,13 @@ test_that("zfill", { pl$lit(c(-1, 2, 10, "5"))$str$zfill("a")$to_r(), "something" ), - "failed parsing ParseIntError" + "i64" ) # test wrong input range expect_grepl_error( pl$lit(c(-1, 2, 10, "5"))$str$zfill(-3)$to_r(), - r"{the arg \[alignment\] the value -3 cannot be less than zero}" + "cannot be less than zero" ) }) @@ -215,15 +215,15 @@ test_that("str$ljust str$rjust", { expect_grepl_error( df$select(pl$col("a")$str$ljust("wrong_string", "w"))$to_list(), - "\\[width\\] failed parsing ParseIntError" + "i64" ) expect_grepl_error( df$select(pl$col("a")$str$ljust(-2, "w"))$to_list(), - r"{in str\$ljust\: "the arg \[width\] the value -2 cannot be less than zero}" + "cannot be less than zero" ) expect_grepl_error( df$select(pl$col("a")$str$ljust(5, "multiple_chars"))$to_list(), - r"{the arg \[fillchar\] is not a single char string, but}" + "char" ) @@ -240,15 +240,15 @@ test_that("str$ljust str$rjust", { expect_grepl_error( df$select(pl$col("a")$str$rjust("wrong_string", "w"))$to_list(), - c("\\[width\\]", "failed parsing ParseIntError") + "i64" ) expect_grepl_error( df$select(pl$col("a")$str$rjust(-2, "w"))$to_list(), - r"{in str\$rjust\: "the arg \[width\] the value -2 cannot be less than zero}" + "cannot be less than zero" ) expect_grepl_error( df$select(pl$col("a")$str$rjust(5, "multiple_chars"))$to_list(), - r"{in str\$rjust\: "the arg \[fillchar\] is not a single char string, but}" + "char" ) }) @@ -377,7 +377,7 @@ test_that("str$extract", { expect_grepl_error( pl$lit("abc")$str$extract(42, 42), - r"(in str\$extract\: the arg \[pattern\] is not a single string)", + "String" ) expect_true( @@ -386,7 +386,7 @@ test_that("str$extract", { expect_grepl_error( pl$lit("abc")$str$extract("a", "a"), - c(r"(str\$extract\: the arg \[group_index\])", "failed parsing ParseIntError", "InvalidDigit") + "i64" ) }) @@ -418,7 +418,7 @@ test_that("str$count_match", { expect_grepl_error( pl$col("foo")$str$count_match(5), - r"(in str\$count_match\: the arg \[pattern\] is not a single string, but 5.0)", + "String" ) }) @@ -441,12 +441,12 @@ test_that("str$split", { expect_grepl_error( pl$lit("42")$str$split(by = 42L, inclusive = TRUE), - r"{in str\$split\: the arg \[by\] is not a single string, but 42}" + "str" ) expect_grepl_error( pl$lit("42")$str$split(by = "blop", inclusive = 42), - r"{in str\$split\: the arg \[inclusive\] is not a single bool as required}" + "bool" ) }) @@ -468,17 +468,17 @@ test_that("str$split_exact", { expect_grepl_error( pl$lit("42")$str$split_exact(by = 42L, n = 1, inclusive = TRUE), - r"{in str\$split_exact\: the arg \[by\] is not a single string, but 42}" + "str" ) expect_grepl_error( pl$lit("42")$str$split_exact(by = "a", n = -1, inclusive = TRUE), - r"{str\$split_exact\: the arg \[n\] the value -1 cannot be less than zero}" + "cannot be less than zero" ) expect_grepl_error( pl$lit("42")$str$split_exact(by = "a", n = 2, inclusive = "joe"), - r"{str\$split_exact\: the arg \[inclusive\] is not a single bool as required, but}" + "bool" ) }) diff --git a/tests/testthat/test-expr_struct.R b/tests/testthat/test-expr_struct.R index 4cd9490ab..322c43e1c 100644 --- a/tests/testthat/test-expr_struct.R +++ b/tests/testthat/test-expr_struct.R @@ -18,9 +18,9 @@ test_that("expr struct$field", { ) err_state = result(df$select(pl$col("struct_col")$struct$field(42))) - expect_grepl_error(unwrap(err_state), "is not a single string") + expect_grepl_error(unwrap(err_state), "str") expect_grepl_error(unwrap(err_state), "\\[name\\]") - expect_grepl_error(unwrap(err_state), "in struct\\$field:") + expect_grepl_error(unwrap(err_state), "str") expect_grepl_error(unwrap(err_state), "42.0") }) @@ -55,7 +55,7 @@ test_that("expr struct$rename_fields", { ) err_state = result(pl$col()$struct$rename_fields(42)) - expect_grepl_error(unwrap(err_state), "is not a single string") + expect_grepl_error(unwrap(err_state), "str") expect_grepl_error(unwrap(err_state), "\\[names\\]") expect_grepl_error(unwrap(err_state), "in struct\\$rename_fields:") expect_grepl_error(unwrap(err_state), "42.0") diff --git a/tests/testthat/test-lazy.R b/tests/testthat/test-lazy.R index 63ae4581d..0f6d6213d 100644 --- a/tests/testthat/test-lazy.R +++ b/tests/testthat/test-lazy.R @@ -155,10 +155,10 @@ test_that("simple translations", { expect_true(all(a != b)) # trigger u8 conversion errors - expect_grepl_error(pl$DataFrame(mtcars)$lazy()$std(256), c("ddof", "exceeds u8 max value")) + expect_grepl_error(pl$DataFrame(mtcars)$lazy()$std(256), c("ddof", "cannot exceed the upper bound for u8 of 255")) expect_grepl_error( pl$DataFrame(mtcars)$lazy()$var(-1), - c("ddof", "the value -1 cannot be less than zero") + c("ddof", "cannot be less than zero") ) }) @@ -317,12 +317,12 @@ test_that("sort", { # TODO refine this error msg in robj_to! it does not have to be a "single" here expect_grepl_error( pl$DataFrame(mtcars)$lazy()$sort(by = c("cyl", "mpg", "cyl"), descending = 42)$collect(), - c("the arg", "descending", "is not a single bool as required, but 42") + c("the arg", "descending", "bool") ) expect_grepl_error( pl$DataFrame(mtcars)$lazy()$sort(by = c("cyl", "mpg", "cyl"), nulls_last = 42)$collect(), - c("the arg", "nulls_last", "is not a single bool as required, but 42") + c("the arg", "nulls_last", "bool") ) df = pl$DataFrame(mtcars)$lazy() diff --git a/tests/testthat/test-lazy_functions.R b/tests/testthat/test-lazy_functions.R index 13205b371..02b4d306d 100644 --- a/tests/testthat/test-lazy_functions.R +++ b/tests/testthat/test-lazy_functions.R @@ -237,7 +237,7 @@ test_that("pl$head", { expect_grepl_error( pl$head(df$get_column("a"), -2), - "the arg \\[n\\] the value -2 cannot be less than zero" + "cannot be less than zero" ) }) @@ -270,6 +270,6 @@ test_that("pl$tail", { expect_grepl_error( pl$tail(df$get_column("a"), -2), - "the arg \\[n\\] the value -2 cannot be less than zero" + "cannot be less than zero" ) }) From 8d9219a796fc83d36a673fda039279ee01c9db03 Mon Sep 17 00:00:00 2001 From: Sicheng Pan Date: Mon, 19 Jun 2023 17:24:15 -0700 Subject: [PATCH 11/24] Add bad_arg on R side --- R/extendr-wrappers.R | 2 ++ src/rust/src/rerr.rs | 8 +++++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/R/extendr-wrappers.R b/R/extendr-wrappers.R index 9255b975e..369c75236 100644 --- a/R/extendr-wrappers.R +++ b/R/extendr-wrappers.R @@ -63,6 +63,8 @@ Rerr$info <- function() .Call(wrap__Rerr__info, self) Rerr$contexts <- function() .Call(wrap__Rerr__contexts, self) +Rerr$bad_arg <- function(arg) .Call(wrap__Rerr__bad_arg, self, arg) + #' @export `$.Rerr` <- function (self, name) { func <- Rerr[[name]]; environment(func) <- environment(); func } diff --git a/src/rust/src/rerr.rs b/src/rust/src/rerr.rs index 4a5998746..4fd0af787 100644 --- a/src/rust/src/rerr.rs +++ b/src/rust/src/rerr.rs @@ -106,6 +106,12 @@ impl Rerr { Rctx::When(target) => ("When", target), })) } + + pub fn bad_arg(&self, arg: String) -> Self { + let mut rerr = self.clone(); + rerr.0.push(Rctx::BadArg(arg)); + rerr + } } impl std::fmt::Display for Rerr { @@ -118,7 +124,7 @@ impl std::fmt::Display for Rerr { .rev() .map(|rerr| format!("{}", rerr)) .reduce(|msg, rerr| { format!("{}: {}", msg, rerr) }) - .unwrap_or(String::new()) + .unwrap_or(String::from("Missing contexts from the Rust side")) ) } } From 2080c44d6b18a014052ea3232483ad8769575246 Mon Sep 17 00:00:00 2001 From: sorhawell Date: Wed, 21 Jun 2023 00:53:47 +0200 Subject: [PATCH 12/24] error_trait.R + error_conversion.R + expose Rerr --- DESCRIPTION | 3 ++ R/after-wrappers.R | 2 +- R/error_conversion.R | 57 ++++++++++++++++++++ R/error_trait.R | 92 +++++++++++++++++++++++++++++++ R/extendr-wrappers.R | 20 ++++++- R/rerr.R | 27 +++++++++- R/rust_result.R | 104 +----------------------------------- R/string_error.R | 16 ++++++ man/dot-pr.Rd | 2 +- man/plain.Rd | 20 +++++++ man/pstop.Rd | 2 +- man/result.Rd | 20 +++++++ man/to_condition.Rd | 24 +++++++++ man/unwrap.Rd | 2 +- man/when_calling.Rd | 26 +++++++++ man/where_in.Rd | 23 ++++++++ src/rust/src/rerr.rs | 72 ++++++++++++++++++++----- tests/testthat/helper.R | 10 ++-- tests/testthat/test-Rerr.R | 18 +++++++ tests/testthat/test-bit64.R | 22 ++++---- 20 files changed, 420 insertions(+), 142 deletions(-) create mode 100644 R/error_conversion.R create mode 100644 R/error_trait.R create mode 100644 R/string_error.R create mode 100644 man/plain.Rd create mode 100644 man/result.Rd create mode 100644 man/to_condition.Rd create mode 100644 man/when_calling.Rd create mode 100644 man/where_in.Rd create mode 100644 tests/testthat/test-Rerr.R diff --git a/DESCRIPTION b/DESCRIPTION index 050fcab90..180ae9f9e 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -53,6 +53,8 @@ Collate: 'dataframe__frame.R' 'datatype.R' 'docs.R' + 'error_conversion.R' + 'error_trait.R' 'expr__binary.R' 'expr__categorical.R' 'expr__datetime.R' @@ -79,6 +81,7 @@ Collate: 'rust_result.R' 's3_methods.R' 'series__series.R' + 'string_error.R' 'translation.R' 'vctrs.R' 'zzz.R' diff --git a/R/after-wrappers.R b/R/after-wrappers.R index 747962fe2..8089250d8 100644 --- a/R/after-wrappers.R +++ b/R/after-wrappers.R @@ -76,7 +76,7 @@ extendr_method_to_pure_functions = function(env, class_name = NULL) { .pr$WhenThenThen = extendr_method_to_pure_functions(WhenThenThen) .pr$VecDataFrame = extendr_method_to_pure_functions(VecDataFrame) .pr$RNullValues = extendr_method_to_pure_functions(RNullValues) - +.pr$Rerr = extendr_method_to_pure_functions(Rerr) # TODO remove export diff --git a/R/error_conversion.R b/R/error_conversion.R new file mode 100644 index 000000000..2b3c52182 --- /dev/null +++ b/R/error_conversion.R @@ -0,0 +1,57 @@ +#THIS FILE IMPLEMENTS ERROR CONVERSION, FOR R TO Result-list & FOR Result-list TO R + +# TODO unwrap should be eventually renamed to unwrap_with_context (or similar) +# a simpler unwrap without where_in and when_calling should be defined in rust_result.R + +#' rust-like unwrapping of result. Useful to keep error handling on the R side. +#' +#' @param result a list here either element ok or err is NULL, or both if ok is litteral NULL +#' @param call context of error or string +#' @param context a msg to prefix a raised error with +#' +#' @return the ok-element of list , or a error will be thrown +#' @keywords internal +#' @export +#' +#' @examples +#' +#' structure(list(ok = "foo", err = NULL), class = "extendr_result") +#' +#' tryCatch( +#' unwrap( +#' structure( +#' list(ok = NULL, err = "something happen on the rust side"), +#' class = "extendr_result" +#' ) +#' ), +#' error = function(err) as.character(err) +#' ) +unwrap = function(result, context = NULL, call = sys.call(1L)) { + if(is_ok(result)) { + result$ok + } else { + result$err |> + where_in(context) |> + when_calling(call) |> + to_condition() |> + stop() + } +} + + +#' catches any R error and return a rust-Result +#' @param expr code to capture any error from and wrap as Result +#' @param msg easy way to add a context msg +#' @keywords internal +#' @return Result +result = function(expr, msg = NULL) { + tryCatch( + Ok(expr), + error = function(cond) { + cond$value %||% + cond$message |> + plain(msg) |> + Err() + } + ) +} diff --git a/R/error_trait.R b/R/error_trait.R new file mode 100644 index 000000000..8ddd07844 --- /dev/null +++ b/R/error_trait.R @@ -0,0 +1,92 @@ +# ANY NEW ERROR MUST IMPLEMENT THESE S3 METHODS, these are the "trait" of a polars error +# ALSO MUST IMPLEMENT BASE THESE METHODS: print + +#' Internal generic method to add call to error +#' @param err any type which impl as.character +#' @param call calling context +#' @details +#' Additional details... +#' +#' @keywords internal +#' @return err as string +#' @examples +#' # +when_calling = function(err, call) { + if (polars_optenv$do_not_repeat_call || is.null(call)) { + err + } else { + UseMethod("when_calling", err) + } +} +when_calling.default = function(err, call) { + stop("internal error: an error-type was not fully implemented") +} +#support function to convert a call to a string +call_to_string = function(call) { + paste( + "\n", + paste(capture.output(print(call)), collapse = "\n") + ) +} + + +#' Internal generic method to point to which public method the user got wrong +#' @param err any type which impl as.character +#' @param call calling context +#' @keywords internal +#' @return err as string +#' @examples +#' # +where_in = function(err, context) { + + if(is.null(context)) { + return(err) + } + if(!is_string(context)) stop( + paste( + "internal error: where_in context must be a string or NULL it was: ", + str_string(context) + ) + ) + UseMethod("where_in", err) +} +where_in.default = function(err, context) { + stop("internal error: an error-type was not fully implemented") +} + +#' Internal generic method to convert an error_type to condition. +#' @param err any type which impl as.character +#' @param call calling context +#' @keywords internal +#' @details +#' this method is needed to preserve state of err without upcasting to a string message +#' an implementation will describe how to store the error in the condition +#' @return condition +to_condition = function(err) { + UseMethod("to_condition", err) +} +to_condition.default = function(err) { + errorCondition( + paste(capture.output(print(err)), collapse = "\n"), + class = c("default_error"), + value = err, + call = NULL + ) +} + + + +#' Internal generic method to add plain text to error message +#' @param err some error type object +#' @param msg string to add +#' @keywords internal +#' @return condition +plain = function(err, msg) { + if(is.null(msg)) return(err) + UseMethod("plain", err) +} +plain.default = function(err, msg) { + paste0(msg, err$message) +} + + diff --git a/R/extendr-wrappers.R b/R/extendr-wrappers.R index 369c75236..ee12324cf 100644 --- a/R/extendr-wrappers.R +++ b/R/extendr-wrappers.R @@ -63,7 +63,25 @@ Rerr$info <- function() .Call(wrap__Rerr__info, self) Rerr$contexts <- function() .Call(wrap__Rerr__contexts, self) -Rerr$bad_arg <- function(arg) .Call(wrap__Rerr__bad_arg, self, arg) +Rerr$bad_arg <- function(x) .Call(wrap__Rerr__bad_arg, self, x) + +Rerr$bad_robj <- function(x) .Call(wrap__Rerr__bad_robj, self, x) + +Rerr$bad_val <- function(x) .Call(wrap__Rerr__bad_val, self, x) + +Rerr$hint <- function(x) .Call(wrap__Rerr__hint, self, x) + +Rerr$mistyped <- function(x) .Call(wrap__Rerr__mistyped, self, x) + +Rerr$misvalued <- function(x) .Call(wrap__Rerr__misvalued, self, x) + +Rerr$plain <- function(x) .Call(wrap__Rerr__plain, self, x) + +Rerr$when <- function(x) .Call(wrap__Rerr__when, self, x) + +Rerr$when_last <- function(x) .Call(wrap__Rerr__when_last, self, x) + +Rerr$wherein <- function(x) .Call(wrap__Rerr__wherein, self, x) #' @export `$.Rerr` <- function (self, name) { func <- Rerr[[name]]; environment(func) <- environment(); func } diff --git a/R/rerr.R b/R/rerr.R index d5be23000..923be33bf 100644 --- a/R/rerr.R +++ b/R/rerr.R @@ -1,3 +1,5 @@ + + #' @title auto complete $-access into a polars object #' @description called by the interactive R session internally #' @param x Rerr @@ -10,8 +12,29 @@ #' @export #' @noRd -as.character.Rerr = function(x) x$info() +as.character.Rerr = function(x, ...) x$info() + #' @export #' @noRd -print.Rerr = function(x) writeLines(x$info()) +print.Rerr = function(x, ...) writeLines(x$info()) + + +## Rerr IPLEMENTS IPLEMENTS R-POLARS error_trait.R +when_calling.Rerr = function(err, call) { + err$when_last(paste("calling:", call_to_string(call))) +} +where_in.Rerr = function(err, context) { + err$wherein(context) +} +to_condition.Rerr = function(err) { + errorCondition( + err$info(), + class = c("Rerr_error"), + value = err, + call = NULL + ) +} +plain.Rerr = function(err, msg) { + err$value$plain(msg) +} diff --git a/R/rust_result.R b/R/rust_result.R index f3e568d29..7aa03245a 100644 --- a/R/rust_result.R +++ b/R/rust_result.R @@ -95,67 +95,7 @@ or_else = function(x, f) { } -#' rust-like unwrapping of result. Useful to keep error handling on the R side. -#' -#' @param result a list here either element ok or err is NULL, or both if ok is litteral NULL -#' @param call context of error or string -#' @param context a msg to prefix a raised error with -#' -#' @return the ok-element of list , or a error will be thrown -#' @keywords internal -#' @export -#' -#' @examples -#' -#' structure(list(ok = "foo", err = NULL), class = "extendr_result") -#' -#' tryCatch( -#' unwrap( -#' structure( -#' list(ok = NULL, err = "something happen on the rust side"), -#' class = "extendr_result" -#' ) -#' ), -#' error = function(err) as.character(err) -#' ) -unwrap = function(result, context = NULL, call = sys.call(1L)) { - # if not a result - if (!is_result(result)) { - stopf("Internal error: cannot unwrap non result") - } - - # if result is ok (ok can be be valid null, hence OK if both ok and err is null) - if (is.null(result$err)) { - return(result$ok) - } - - # if result is error, make a pretty with context - if (is.null(result$ok) && !is.null(result$err)) { - if (!is.null(context)) { - result$err = paste(context, result$err) - } - - stop( - paste( - result$err, - if (!polars_optenv$do_not_repeat_call) { - paste( - "\n when calling :\n", - paste(capture.output(print(call)), collapse = "\n") - ) - } - ), - domain = NA, - call. = FALSE - ) - } - - # if not ok XOR error, then roll over - stopf("Internal error: result object corrupted") -} - - -#' Internal preferred function to throw errors +#' pstop #' @description DEPRECATED USE stopf instead #' @param err error msg string #' @param call calling context @@ -169,45 +109,3 @@ unwrap = function(result, context = NULL, call = sys.call(1L)) { pstop = function(err, call = sys.call(1L)) { unwrap(list(ok = NULL, err = err), call = call) } - -# capture error in any R side arguments, and pass to rust side to preserve context and write -# really sweet error messages -result = function(x, msg = "an error because:\n") { - tryCatch( - Ok(x), - error = function(err) { - Err(paste0(msg, err$message)) - } - ) -} - -# Alternative unwrap that keeps the Rerr -unwrap_rerr = function(result) { - if (!is_result(result)) { - stopf("Internal error: cannot unwrap non result") - } - if (polars:::is_ok(result)) return(result$ok) - err = result$err - cond = errorCondition( - capture.output(print(err)) - ) - if(inherits(err, "Rerr")) { - cond$Rerr = err - class(cond) = c("Rerr_error", "error", "condition") - } - - stop(cond) -} - -# Alternative result that captures the Rerr from the alternative unwrap -result_rerr = function(expr) { - tryCatch( - polars:::Ok(expr), - Rerr_error = function(err) { - polars:::Err(err$Rerr) - }, - error = function(err) { - polars:::Err(err) - } - ) -} \ No newline at end of file diff --git a/R/string_error.R b/R/string_error.R new file mode 100644 index 000000000..97bf40095 --- /dev/null +++ b/R/string_error.R @@ -0,0 +1,16 @@ +## STRING/CHARACTER IPLEMENTS R-POLARS error_trait.R +when_calling.character = function(err, call) { + paste(err, "When calling:", call_to_string(call)) +} +where_in.character = function(err, context) { + paste(context, err) +} +to_condition.character = function(err) { + if(!is_string(err)) { + stop(paste("Internal error: an error msg was not of length 1, but was:",str_string(err))) + } + errorCondition(err) +} +plain.character = function(err, msg) { + paste0(msg, err) +} diff --git a/man/dot-pr.Rd b/man/dot-pr.Rd index 51eeffbb5..9881308e8 100644 --- a/man/dot-pr.Rd +++ b/man/dot-pr.Rd @@ -5,7 +5,7 @@ \alias{.pr} \title{polars-API: private calls to rust-polars} \format{ -An object of class \code{environment} of length 16. +An object of class \code{environment} of length 17. } \usage{ .pr diff --git a/man/plain.Rd b/man/plain.Rd new file mode 100644 index 000000000..e4b73b166 --- /dev/null +++ b/man/plain.Rd @@ -0,0 +1,20 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/error_trait.R +\name{plain} +\alias{plain} +\title{Internal generic method to add plain text to error message} +\usage{ +plain(err, msg) +} +\arguments{ +\item{err}{some error type object} + +\item{msg}{string to add} +} +\value{ +condition +} +\description{ +Internal generic method to add plain text to error message +} +\keyword{internal} diff --git a/man/pstop.Rd b/man/pstop.Rd index 6f51fb08e..7473cee47 100644 --- a/man/pstop.Rd +++ b/man/pstop.Rd @@ -2,7 +2,7 @@ % Please edit documentation in R/rust_result.R \name{pstop} \alias{pstop} -\title{Internal preferred function to throw errors} +\title{pstop} \usage{ pstop(err, call = sys.call(1L)) } diff --git a/man/result.Rd b/man/result.Rd new file mode 100644 index 000000000..31a3ada66 --- /dev/null +++ b/man/result.Rd @@ -0,0 +1,20 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/error_conversion.R +\name{result} +\alias{result} +\title{catches any R error and return a rust-Result} +\usage{ +result(expr, msg = NULL) +} +\arguments{ +\item{expr}{code to capture any error from and wrap as Result} + +\item{msg}{easy way to add a context msg} +} +\value{ +Result +} +\description{ +catches any R error and return a rust-Result +} +\keyword{internal} diff --git a/man/to_condition.Rd b/man/to_condition.Rd new file mode 100644 index 000000000..5b1566f7b --- /dev/null +++ b/man/to_condition.Rd @@ -0,0 +1,24 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/error_trait.R +\name{to_condition} +\alias{to_condition} +\title{Internal generic method to convert an error_type to condition.} +\usage{ +to_condition(err) +} +\arguments{ +\item{err}{any type which impl as.character} + +\item{call}{calling context} +} +\value{ +condition +} +\description{ +Internal generic method to convert an error_type to condition. +} +\details{ +this method is needed to preserve state of err without upcasting to a string message +an implementation will describe how to store the error in the condition +} +\keyword{internal} diff --git a/man/unwrap.Rd b/man/unwrap.Rd index 699945618..26d2fe44a 100644 --- a/man/unwrap.Rd +++ b/man/unwrap.Rd @@ -1,5 +1,5 @@ % Generated by roxygen2: do not edit by hand -% Please edit documentation in R/rust_result.R +% Please edit documentation in R/error_conversion.R \name{unwrap} \alias{unwrap} \title{rust-like unwrapping of result. Useful to keep error handling on the R side.} diff --git a/man/when_calling.Rd b/man/when_calling.Rd new file mode 100644 index 000000000..48af20178 --- /dev/null +++ b/man/when_calling.Rd @@ -0,0 +1,26 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/error_trait.R +\name{when_calling} +\alias{when_calling} +\title{Internal generic method to add call to error} +\usage{ +when_calling(err, call) +} +\arguments{ +\item{err}{any type which impl as.character} + +\item{call}{calling context} +} +\value{ +err as string +} +\description{ +Internal generic method to add call to error +} +\details{ +Additional details... +} +\examples{ +# +} +\keyword{internal} diff --git a/man/where_in.Rd b/man/where_in.Rd new file mode 100644 index 000000000..23036dc16 --- /dev/null +++ b/man/where_in.Rd @@ -0,0 +1,23 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/error_trait.R +\name{where_in} +\alias{where_in} +\title{Internal generic method to point to which public method the user got wrong} +\usage{ +where_in(err, context) +} +\arguments{ +\item{err}{any type which impl as.character} + +\item{call}{calling context} +} +\value{ +err as string +} +\description{ +Internal generic method to point to which public method the user got wrong +} +\examples{ +# +} +\keyword{internal} diff --git a/src/rust/src/rerr.rs b/src/rust/src/rerr.rs index 4fd0af787..70226d93d 100644 --- a/src/rust/src/rerr.rs +++ b/src/rust/src/rerr.rs @@ -1,3 +1,5 @@ +use std::collections::VecDeque; + use extendr_api::{ extendr, extendr_module, symbol::class_symbol, Attributes, Pairlist, Rinternals, Robj, }; @@ -23,10 +25,12 @@ pub enum Rctx { Polars(String), #[error("When {0}")] When(String), + #[error("In {0}")] + Wherein(String), } #[derive(Clone, Debug)] -pub struct Rerr(Vec); +pub struct Rerr(VecDeque); pub type RResult = core::result::Result; pub trait WithRctx { @@ -39,13 +43,14 @@ pub trait WithRctx { fn misvalued>(self, scope: S) -> RResult; fn plain>(self, msg: S) -> RResult; fn when>(self, env: S) -> RResult; + fn wherein>(self, env: S) -> RResult; } impl> WithRctx for core::result::Result { fn ctx(self, rctx: Rctx) -> RResult { self.map_err(|e| { let mut rerr = e.into(); - rerr.0.push(rctx); + rerr.0.push_back(rctx); rerr }) } @@ -81,12 +86,16 @@ impl> WithRctx for core::result::Result { fn when>(self, env: S) -> RResult { self.ctx(Rctx::When(env.into())) } + + fn wherein>(self, env: S) -> RResult { + self.ctx(Rctx::Wherein(env.into())) + } } #[extendr] impl Rerr { pub fn new() -> Self { - Rerr(Vec::new()) + Rerr(VecDeque::new()) } pub fn info(&self) -> String { @@ -104,12 +113,51 @@ impl Rerr { Rctx::Plain(msg) => ("PlainErrorMessage", msg), Rctx::Polars(err) => ("PolarsError", err), Rctx::When(target) => ("When", target), + Rctx::Wherein(target) => ("Wherein", target), })) } - pub fn bad_arg(&self, arg: String) -> Self { + pub fn bad_arg(&self, x: String) -> Self { + self.push_back_rctx(Rctx::BadArg(x)) + } + pub fn bad_robj(&self, x: Robj) -> Self { + self.push_back_rctx(Rctx::BadArg(rdbg(x))) + } + pub fn bad_val(&self, x: String) -> Self { + self.push_back_rctx(Rctx::BadVal(x)) + } + pub fn hint(&self, x: String) -> Self { + self.push_back_rctx(Rctx::Hint(x)) + } + pub fn mistyped(&self, x: String) -> Self { + self.push_back_rctx(Rctx::Mistyped(x)) + } + pub fn misvalued(&self, x: String) -> Self { + self.push_back_rctx(Rctx::Misvalued(x)) + } + pub fn plain(&self, x: String) -> Self { + self.push_back_rctx(Rctx::Plain(x)) + } + pub fn when(&self, x: String) -> Self { + self.push_back_rctx(Rctx::When(x)) + } + pub fn when_last(&self, x: String) -> Self { + self.push_front_rctx(Rctx::When(x)) + } + pub fn wherein(&self, x: String) -> Self { + self.push_back_rctx(Rctx::Wherein(x)) + } +} +//methods not to export with extendr +impl Rerr { + pub fn push_front_rctx(&self, rctx: Rctx) -> Self { + let mut rerr = self.clone(); + rerr.0.push_front(rctx); + rerr + } + pub fn push_back_rctx(&self, rctx: Rctx) -> Self { let mut rerr = self.clone(); - rerr.0.push(Rctx::BadArg(arg)); + rerr.0.push_back(rctx); rerr } } @@ -137,23 +185,23 @@ impl From for String { impl From for Rerr { default fn from(err: E) -> Self { - Rerr(vec![Rctx::Plain(rdbg(err))]) + Rerr(VecDeque::from([Rctx::Plain(rdbg(err))])) } } impl From for Rerr { fn from(extendr_err: extendr_api::Error) -> Self { - Rerr(vec![Rctx::Extendr(rdbg(extendr_err))]) + Rerr(VecDeque::from([Rctx::Extendr(rdbg(extendr_err))])) } } impl From for Rerr { fn from(polars_err: polars::error::PolarsError) -> Self { let mut rerr = Rerr::new(); - rerr.0.push(Rctx::Polars(rdbg(&polars_err))); + rerr.0.push_back(Rctx::Polars(rdbg(&polars_err))); match polars_err { polars::prelude::PolarsError::InvalidOperation(x) => { - rerr.0.push(Rctx::Hint(format!( + rerr.0.push_back(Rctx::Hint(format!( "something (likely a column) with name {:?} is not found", x ))); @@ -174,11 +222,7 @@ pub fn rdbg(o: T) -> String { #[extendr] pub fn test_rerr() -> RResult { - rerr() - .bad_val("-1") - .mistyped("usize") - .bad_arg("path") - .when("calling test function") + rerr().bad_val("-1").mistyped("usize").bad_arg("path") } extendr_module! { diff --git a/tests/testthat/helper.R b/tests/testthat/helper.R index 4c3547d88..b9dc701eb 100644 --- a/tests/testthat/helper.R +++ b/tests/testthat/helper.R @@ -77,11 +77,7 @@ make_print_cases = function() { # Expect a Rerr with given contexts expect_rerr = function(expr, ctxs) { - result = result_rerr(expr) - expect_true(is_err(result)) - expect_identical(class(result$err), "Rerr") - expect_identical( - names(result$err$contexts()), - ctxs - ) + res = result(expr) + expect_identical(class(res$err), "Rerr") + expect_identical(names(res$err$contexts()), ctxs) } diff --git a/tests/testthat/test-Rerr.R b/tests/testthat/test-Rerr.R new file mode 100644 index 000000000..e2fa175bd --- /dev/null +++ b/tests/testthat/test-Rerr.R @@ -0,0 +1,18 @@ +test_that("can add any context to err", { + + err_types = c( + "bad_arg", "bad_robj", "bad_val", "hint", + "mistyped", "misvalued", "plain", "when" + ) + rerr = .pr$Rerr$new() + for (i in err_types) rerr = rerr[[i]](i) + + expect_identical( + names(rerr$contexts()), + c( + "When", "PlainErrorMessage", "ValueOutOfScope", "TypeMismatch", + "Hint", "BadValue", "BadArgument", "BadArgument" + ) + ) + +}) diff --git a/tests/testthat/test-bit64.R b/tests/testthat/test-bit64.R index 67804dd61..7e320361a 100644 --- a/tests/testthat/test-bit64.R +++ b/tests/testthat/test-bit64.R @@ -24,54 +24,54 @@ test_that("from r to series and reverse", { test_that("robj_to! from bit64", { testthat::skip_if_not_installed("bit64") expect_identical( - unwrap(polars:::test_robj_to_i64(bit64::as.integer64(1))), + unwrap(test_robj_to_i64(bit64::as.integer64(1))), as.character(bit64::as.integer64(1)) ) expect_identical( - unwrap(polars:::test_robj_to_u32(bit64::as.integer64(2^27))), + unwrap(test_robj_to_u32(bit64::as.integer64(2^27))), as.character(2^27) ) expect_identical( - unwrap(polars:::test_robj_to_usize(bit64::as.integer64("2305843009213693952"))), + unwrap(test_robj_to_usize(bit64::as.integer64("2305843009213693952"))), as.character(2^61) ) expect_identical( - unwrap(polars:::test_robj_to_usize(bit64::as.integer64(2^61))), + unwrap(test_robj_to_usize(bit64::as.integer64(2^61))), as.character(2^61) ) - # NO NA + # NO NA expect_rerr( - unwrap_rerr(polars:::test_robj_to_i64(bit64::as.integer64(NA))), + unwrap(test_robj_to_i64(bit64::as.integer64(NA)), call= NULL), c("BadArgument", "TypeMismatch", "BadValue") ) expect_rerr( - unwrap_rerr(polars:::test_robj_to_usize(bit64::as.integer64(NA))), + unwrap(test_robj_to_usize(bit64::as.integer64(NA)), call= NULL), c("BadArgument", "TypeMismatch", "BadValue") ) # NO OVERFLOW expect_rerr( - unwrap_rerr(polars:::test_robj_to_u32(2^57)), + unwrap(test_robj_to_u32(2^57), call= NULL), c("BadArgument", "TypeMismatch", "BadValue") ) # NO NEGATIVE expect_rerr( - unwrap_rerr(polars:::test_robj_to_usize(bit64::as.integer64(-1))), + unwrap(test_robj_to_usize(bit64::as.integer64(-1)), call = NULL), c("BadArgument", "TypeMismatch", "BadValue") ) expect_rerr( - unwrap_rerr(polars:::test_robj_to_u32(bit64::as.integer64(-1))), + unwrap(test_robj_to_u32(bit64::as.integer64(-1)), call = NULL), c("BadArgument", "TypeMismatch", "BadValue") ) # NO length>1 expect_rerr( - unwrap_rerr(polars:::test_robj_to_usize(bit64::as.integer64(c(1:2)))), + unwrap(test_robj_to_usize(bit64::as.integer64(c(1:2))), call = NULL), c("BadArgument", "TypeMismatch", "BadValue") ) }) From ac2d576cdaed3afbbc0e82a4a3809b41248e42a2 Mon Sep 17 00:00:00 2001 From: sorhawell Date: Wed, 21 Jun 2023 13:02:03 +0200 Subject: [PATCH 13/24] do not export unwrap --- NAMESPACE | 1 - 1 file changed, 1 deletion(-) diff --git a/NAMESPACE b/NAMESPACE index 98779e913..40598d252 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -153,7 +153,6 @@ export(nrow.DataFrame) export(pl) export(read_csv_) export(scan_parquet) -export(unwrap) importFrom(stats,median) importFrom(stats,na.omit) importFrom(utils,.DollarNames) From cce6a943d13f682ecee8bb65de936070be73e5d9 Mon Sep 17 00:00:00 2001 From: sorhawell Date: Wed, 21 Jun 2023 13:02:23 +0200 Subject: [PATCH 14/24] with last --- R/error_conversion.R | 2 -- 1 file changed, 2 deletions(-) diff --git a/R/error_conversion.R b/R/error_conversion.R index 2b3c52182..057f4ae55 100644 --- a/R/error_conversion.R +++ b/R/error_conversion.R @@ -11,8 +11,6 @@ #' #' @return the ok-element of list , or a error will be thrown #' @keywords internal -#' @export -#' #' @examples #' #' structure(list(ok = "foo", err = NULL), class = "extendr_result") From 8a7ebc7813856963a6fd7714c2a2cc82e49aa4b4 Mon Sep 17 00:00:00 2001 From: sorhawell Date: Wed, 21 Jun 2023 13:04:19 +0200 Subject: [PATCH 15/24] print Rerr without escapes --- R/rerr.R | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/R/rerr.R b/R/rerr.R index 923be33bf..af65ecafb 100644 --- a/R/rerr.R +++ b/R/rerr.R @@ -17,7 +17,7 @@ as.character.Rerr = function(x, ...) x$info() #' @export #' @noRd -print.Rerr = function(x, ...) writeLines(x$info()) +print.Rerr = function(x, ...) cat(x$info()) ## Rerr IPLEMENTS IPLEMENTS R-POLARS error_trait.R From 33fda5c0b48a05ac2a15720036b2046551fe3c69 Mon Sep 17 00:00:00 2001 From: sorhawell Date: Wed, 21 Jun 2023 13:33:27 +0200 Subject: [PATCH 16/24] error_conversion examples, unwrap_err, fiddle print --- R/error_conversion.R | 38 ++++++++++++++++++++++++++++++-------- R/error_trait.R | 2 +- R/extendr-wrappers.R | 4 ++-- R/string_error.R | 2 +- man/result.Rd | 20 +++++++++++++++++--- man/unwrap_err.Rd | 21 +++++++++++++++++++++ 6 files changed, 72 insertions(+), 15 deletions(-) create mode 100644 man/unwrap_err.Rd diff --git a/R/error_conversion.R b/R/error_conversion.R index 057f4ae55..82729590f 100644 --- a/R/error_conversion.R +++ b/R/error_conversion.R @@ -36,20 +36,42 @@ unwrap = function(result, context = NULL, call = sys.call(1L)) { } } +#' rust-like unwrap_err, internal use only +#' @details +#' throwed error info is sparse because only for internal errors +#' @keywords internal +#' @param result a Result, see rust_result.R#' +#' @return some error type +unwrap_err = function(result) { + if(is_ok(result)) { + stop("internal error: Cannot unwrap_err an Ok-value") + } else { + result$err + } +} -#' catches any R error and return a rust-Result + +#' Capture any R error and return a rust-like Result #' @param expr code to capture any error from and wrap as Result -#' @param msg easy way to add a context msg +#' @param msg handy way to add a context msg #' @keywords internal #' @return Result +#' @examples +#' #capture regular R errors or Rerr +#' +#' throw_simpleError = \() stop("Imma simple error") +#' result(throw_simpleError()) +#' +#' throw_Rerr = \() unwrap( +#' Err(.pr$Rerr$new()$bad_robj(42)$mistyped("String")$when("doing something")) +#' ) +#' res_Rerr = result(throw_Rerr()) +#' str(res_Rerr) +#' Rerr = unwrap_err(res_Rerr) +#' Rerr$contexts() result = function(expr, msg = NULL) { tryCatch( Ok(expr), - error = function(cond) { - cond$value %||% - cond$message |> - plain(msg) |> - Err() - } + error = \(cond) cond$value %||% cond$message |> plain(msg) |> Err() ) } diff --git a/R/error_trait.R b/R/error_trait.R index 8ddd07844..509b7d03b 100644 --- a/R/error_trait.R +++ b/R/error_trait.R @@ -86,7 +86,7 @@ plain = function(err, msg) { UseMethod("plain", err) } plain.default = function(err, msg) { - paste0(msg, err$message) + paste0(msg,": ", err) } diff --git a/R/extendr-wrappers.R b/R/extendr-wrappers.R index ee12324cf..910a0193d 100644 --- a/R/extendr-wrappers.R +++ b/R/extendr-wrappers.R @@ -65,10 +65,10 @@ Rerr$contexts <- function() .Call(wrap__Rerr__contexts, self) Rerr$bad_arg <- function(x) .Call(wrap__Rerr__bad_arg, self, x) -Rerr$bad_robj <- function(x) .Call(wrap__Rerr__bad_robj, self, x) - Rerr$bad_val <- function(x) .Call(wrap__Rerr__bad_val, self, x) +Rerr$bad_robj <- function(x) .Call(wrap__Rerr__bad_robj, self, x) + Rerr$hint <- function(x) .Call(wrap__Rerr__hint, self, x) Rerr$mistyped <- function(x) .Call(wrap__Rerr__mistyped, self, x) diff --git a/R/string_error.R b/R/string_error.R index 97bf40095..6452856cb 100644 --- a/R/string_error.R +++ b/R/string_error.R @@ -12,5 +12,5 @@ to_condition.character = function(err) { errorCondition(err) } plain.character = function(err, msg) { - paste0(msg, err) + NextMethod("plain",err) } diff --git a/man/result.Rd b/man/result.Rd index 31a3ada66..0d9f8fb09 100644 --- a/man/result.Rd +++ b/man/result.Rd @@ -2,19 +2,33 @@ % Please edit documentation in R/error_conversion.R \name{result} \alias{result} -\title{catches any R error and return a rust-Result} +\title{Capture any R error and return a rust-like Result} \usage{ result(expr, msg = NULL) } \arguments{ \item{expr}{code to capture any error from and wrap as Result} -\item{msg}{easy way to add a context msg} +\item{msg}{handy way to add a context msg} } \value{ Result } \description{ -catches any R error and return a rust-Result +Capture any R error and return a rust-like Result +} +\examples{ + #capture regular R errors or Rerr + + throw_simpleError = \() stop("Imma simple error") + result(throw_simpleError()) + + throw_Rerr = \() unwrap( + Err(.pr$Rerr$new()$bad_robj(42)$mistyped("String")$when("doing something")) + ) + res_Rerr = result(throw_Rerr()) + str(res_Rerr) + Rerr = unwrap_err(res_Rerr) + Rerr$contexts() } \keyword{internal} diff --git a/man/unwrap_err.Rd b/man/unwrap_err.Rd new file mode 100644 index 000000000..2a1b50e7f --- /dev/null +++ b/man/unwrap_err.Rd @@ -0,0 +1,21 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/error_conversion.R +\name{unwrap_err} +\alias{unwrap_err} +\title{rust-like unwrap_err, internal use only} +\usage{ +unwrap_err(result) +} +\arguments{ +\item{result}{a Result, see rust_result.R#'} +} +\value{ +some error type +} +\description{ +rust-like unwrap_err, internal use only +} +\details{ +throwed error info is sparse because only for internal errors +} +\keyword{internal} From 079b8a38a6c6735e0e460b8fb3a1facc52210c54 Mon Sep 17 00:00:00 2001 From: sorhawell Date: Wed, 21 Jun 2023 13:34:52 +0200 Subject: [PATCH 17/24] bug R-side Rerr bad_robj was mapped BadArg context --- src/rust/src/rerr.rs | 6 +++--- tests/testthat/test-Rerr.R | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/rust/src/rerr.rs b/src/rust/src/rerr.rs index 70226d93d..aeb1d4f33 100644 --- a/src/rust/src/rerr.rs +++ b/src/rust/src/rerr.rs @@ -120,12 +120,12 @@ impl Rerr { pub fn bad_arg(&self, x: String) -> Self { self.push_back_rctx(Rctx::BadArg(x)) } - pub fn bad_robj(&self, x: Robj) -> Self { - self.push_back_rctx(Rctx::BadArg(rdbg(x))) - } pub fn bad_val(&self, x: String) -> Self { self.push_back_rctx(Rctx::BadVal(x)) } + pub fn bad_robj(&self, x: Robj) -> Self { + self.bad_val(robj_dbg(&x)) + } pub fn hint(&self, x: String) -> Self { self.push_back_rctx(Rctx::Hint(x)) } diff --git a/tests/testthat/test-Rerr.R b/tests/testthat/test-Rerr.R index e2fa175bd..63b6085a4 100644 --- a/tests/testthat/test-Rerr.R +++ b/tests/testthat/test-Rerr.R @@ -11,7 +11,7 @@ test_that("can add any context to err", { names(rerr$contexts()), c( "When", "PlainErrorMessage", "ValueOutOfScope", "TypeMismatch", - "Hint", "BadValue", "BadArgument", "BadArgument" + "Hint", "BadValue", "BadValue", "BadArgument" ) ) From 5ec11c875d5043ec77bcd0ab524836e271f4f894 Mon Sep 17 00:00:00 2001 From: sorhawell Date: Wed, 21 Jun 2023 13:35:31 +0200 Subject: [PATCH 18/24] show both value, sexp and class in bad_robj --- src/rust/src/rerr.rs | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/src/rust/src/rerr.rs b/src/rust/src/rerr.rs index aeb1d4f33..d192eb94a 100644 --- a/src/rust/src/rerr.rs +++ b/src/rust/src/rerr.rs @@ -2,12 +2,13 @@ use std::collections::VecDeque; use extendr_api::{ extendr, extendr_module, symbol::class_symbol, Attributes, Pairlist, Rinternals, Robj, + Operators, eval_string, call, Types, }; use thiserror::Error; #[derive(Clone, Debug, Error)] pub enum Rctx { - #[error("The argument [{0}] casuse an error")] + #[error("The argument [{0}] cause an error")] BadArg(String), #[error("Got value [{0}]")] BadVal(String), @@ -59,14 +60,16 @@ impl> WithRctx for core::result::Result { self.ctx(Rctx::BadArg(arg.into())) } - fn bad_robj(self, robj: &Robj) -> RResult { - self.bad_val(rdbg(robj)) - } - fn bad_val>(self, val: S) -> RResult { self.ctx(Rctx::BadVal(val.into())) } + fn bad_robj(self, robj: &Robj) -> RResult { + self.bad_val(robj_dbg(robj)) + } + + + fn hint>(self, cause: S) -> RResult { self.ctx(Rctx::Hint(cause.into())) } @@ -216,10 +219,23 @@ pub fn rerr() -> RResult { Err(Rerr::new()) } +//any rust impl Debug to string pub fn rdbg(o: T) -> String { format!("{:?}", o) } +//detailed debug of Robj to string +pub fn robj_dbg(robj: &Robj) -> String { + let s = rdbg(robj); + format!( + "Rvalue: {}{}, Rsexp: {:?}, Rclass: {:?}", + &s[0..(s.len().min(128))], + if s.len()>128 {"...] "} else {""}, + robj.rtype(), + call!("base::class", robj).expect("internal error: could not use base::class(robj)") + ) +} + #[extendr] pub fn test_rerr() -> RResult { rerr().bad_val("-1").mistyped("usize").bad_arg("path") From 5b6765840f78c77aa95ded98a25ed79a98d20140 Mon Sep 17 00:00:00 2001 From: sorhawell Date: Wed, 21 Jun 2023 13:56:39 +0200 Subject: [PATCH 19/24] fix check examples --- R/error_conversion.R | 11 ++++++++++- man/result.Rd | 8 +++++++- man/unwrap.Rd | 3 +++ 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/R/error_conversion.R b/R/error_conversion.R index 82729590f..cf200c7de 100644 --- a/R/error_conversion.R +++ b/R/error_conversion.R @@ -13,6 +13,9 @@ #' @keywords internal #' @examples #' +#' #get unwrap without using ::: +#' unwrap = environment(polars::pl$all)$unwrap +#' #' structure(list(ok = "foo", err = NULL), class = "extendr_result") #' #' tryCatch( @@ -57,8 +60,14 @@ unwrap_err = function(result) { #' @keywords internal #' @return Result #' @examples -#' #capture regular R errors or Rerr #' +#' #user internal functions without using ::: +#' result = environment(polars::pl$all)$result +#' unwrap_err = environment(polars::pl$all)$unwrap_err +#' unwrap = environment(polars::pl$all)$unwrap +#' Err = environment(polars::pl$all)$Err +#' +#' #capture regular R errors or Rerr #' throw_simpleError = \() stop("Imma simple error") #' result(throw_simpleError()) #' diff --git a/man/result.Rd b/man/result.Rd index 0d9f8fb09..be19202de 100644 --- a/man/result.Rd +++ b/man/result.Rd @@ -18,8 +18,14 @@ Result Capture any R error and return a rust-like Result } \examples{ - #capture regular R errors or Rerr + #user internal functions without using ::: + result = environment(polars::pl$all)$result + unwrap_err = environment(polars::pl$all)$unwrap_err + unwrap = environment(polars::pl$all)$unwrap + Err = environment(polars::pl$all)$Err + + #capture regular R errors or Rerr throw_simpleError = \() stop("Imma simple error") result(throw_simpleError()) diff --git a/man/unwrap.Rd b/man/unwrap.Rd index 26d2fe44a..db472f460 100644 --- a/man/unwrap.Rd +++ b/man/unwrap.Rd @@ -21,6 +21,9 @@ rust-like unwrapping of result. Useful to keep error handling on the R side. } \examples{ +#get unwrap without using ::: +unwrap = environment(polars::pl$all)$unwrap + structure(list(ok = "foo", err = NULL), class = "extendr_result") tryCatch( From 8d504f2bbb5f0a5b7320b0c6031cfa8e930d9600 Mon Sep 17 00:00:00 2001 From: sorhawell Date: Wed, 21 Jun 2023 14:04:54 +0200 Subject: [PATCH 20/24] a first round of renaming --- NAMESPACE | 10 +++--- R/after-wrappers.R | 2 +- R/error_conversion.R | 8 ++--- R/extendr-wrappers.R | 32 ++++++++--------- R/rerr.R | 20 +++++------ ....Rerr.Rd => dot-DollarNames.RPolarsErr.Rd} | 8 ++--- man/nanoarrow.Rd | 8 ++--- man/result.Rd | 8 ++--- src/rust/src/rerr.rs | 34 +++++++++---------- src/rust/src/utils/mod.rs | 10 +++--- tests/testthat/helper.R | 4 +-- tests/testthat/test-Rerr.R | 2 +- 12 files changed, 73 insertions(+), 73 deletions(-) rename man/{dot-DollarNames.Rerr.Rd => dot-DollarNames.RPolarsErr.Rd} (68%) diff --git a/NAMESPACE b/NAMESPACE index 40598d252..6e7ef675b 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -22,7 +22,7 @@ S3method("$",ProtoExprArray) S3method("$",RField) S3method("$",RNullValues) S3method("$",RPolarsDataType) -S3method("$",Rerr) +S3method("$",RPolarsErr) S3method("$",Series) S3method("$",VecDataFrame) S3method("$",When) @@ -65,7 +65,7 @@ S3method("[[",ProtoExprArray) S3method("[[",RField) S3method("[[",RNullValues) S3method("[[",RPolarsDataType) -S3method("[[",Rerr) +S3method("[[",RPolarsErr) S3method("[[",Series) S3method("[[",VecDataFrame) S3method("[[",When) @@ -79,7 +79,7 @@ S3method(.DollarNames,GroupBy) S3method(.DollarNames,LazyFrame) S3method(.DollarNames,PolarsBackgroundHandle) S3method(.DollarNames,RField) -S3method(.DollarNames,Rerr) +S3method(.DollarNames,RPolarsErr) S3method(.DollarNames,Series) S3method(.DollarNames,VecDataFrame) S3method(.DollarNames,When) @@ -87,7 +87,7 @@ S3method(.DollarNames,WhenThen) S3method(.DollarNames,WhenThenThen) S3method(.DollarNames,method_environment) S3method(.DollarNames,polars_option_list) -S3method(as.character,Rerr) +S3method(as.character,RPolarsErr) S3method(as.character,Series) S3method(as.data.frame,DataFrame) S3method(as.data.frame,LazyFrame) @@ -124,7 +124,7 @@ S3method(print,PTime) S3method(print,PolarsBackgroundHandle) S3method(print,RField) S3method(print,RPolarsDataType) -S3method(print,Rerr) +S3method(print,RPolarsErr) S3method(print,Series) S3method(print,When) S3method(print,WhenThen) diff --git a/R/after-wrappers.R b/R/after-wrappers.R index 8089250d8..66f11b8bb 100644 --- a/R/after-wrappers.R +++ b/R/after-wrappers.R @@ -76,7 +76,7 @@ extendr_method_to_pure_functions = function(env, class_name = NULL) { .pr$WhenThenThen = extendr_method_to_pure_functions(WhenThenThen) .pr$VecDataFrame = extendr_method_to_pure_functions(VecDataFrame) .pr$RNullValues = extendr_method_to_pure_functions(RNullValues) -.pr$Rerr = extendr_method_to_pure_functions(Rerr) +.pr$RPolarsErr = extendr_method_to_pure_functions(RPolarsErr) # TODO remove export diff --git a/R/error_conversion.R b/R/error_conversion.R index cf200c7de..b58155c54 100644 --- a/R/error_conversion.R +++ b/R/error_conversion.R @@ -67,17 +67,17 @@ unwrap_err = function(result) { #' unwrap = environment(polars::pl$all)$unwrap #' Err = environment(polars::pl$all)$Err #' -#' #capture regular R errors or Rerr +#' #capture regular R errors or RPolarsErr #' throw_simpleError = \() stop("Imma simple error") #' result(throw_simpleError()) #' #' throw_Rerr = \() unwrap( -#' Err(.pr$Rerr$new()$bad_robj(42)$mistyped("String")$when("doing something")) +#' Err(.pr$RPolarsErr$new()$bad_robj(42)$mistyped("String")$when("doing something")) #' ) #' res_Rerr = result(throw_Rerr()) #' str(res_Rerr) -#' Rerr = unwrap_err(res_Rerr) -#' Rerr$contexts() +#' RPolarsErr = unwrap_err(res_Rerr) +#' RPolarsErr$contexts() result = function(expr, msg = NULL) { tryCatch( Ok(expr), diff --git a/R/extendr-wrappers.R b/R/extendr-wrappers.R index 910a0193d..5c6918fa9 100644 --- a/R/extendr-wrappers.R +++ b/R/extendr-wrappers.R @@ -55,39 +55,39 @@ test_robj_to_i64 <- function(robj) .Call(wrap__test_robj_to_i64, robj) test_robj_to_u32 <- function(robj) .Call(wrap__test_robj_to_u32, robj) -Rerr <- new.env(parent = emptyenv()) +RPolarsErr <- new.env(parent = emptyenv()) -Rerr$new <- function() .Call(wrap__Rerr__new) +RPolarsErr$new <- function() .Call(wrap__RPolarsErr__new) -Rerr$info <- function() .Call(wrap__Rerr__info, self) +RPolarsErr$info <- function() .Call(wrap__RPolarsErr__info, self) -Rerr$contexts <- function() .Call(wrap__Rerr__contexts, self) +RPolarsErr$contexts <- function() .Call(wrap__RPolarsErr__contexts, self) -Rerr$bad_arg <- function(x) .Call(wrap__Rerr__bad_arg, self, x) +RPolarsErr$bad_arg <- function(x) .Call(wrap__RPolarsErr__bad_arg, self, x) -Rerr$bad_val <- function(x) .Call(wrap__Rerr__bad_val, self, x) +RPolarsErr$bad_val <- function(x) .Call(wrap__RPolarsErr__bad_val, self, x) -Rerr$bad_robj <- function(x) .Call(wrap__Rerr__bad_robj, self, x) +RPolarsErr$bad_robj <- function(x) .Call(wrap__RPolarsErr__bad_robj, self, x) -Rerr$hint <- function(x) .Call(wrap__Rerr__hint, self, x) +RPolarsErr$hint <- function(x) .Call(wrap__RPolarsErr__hint, self, x) -Rerr$mistyped <- function(x) .Call(wrap__Rerr__mistyped, self, x) +RPolarsErr$mistyped <- function(x) .Call(wrap__RPolarsErr__mistyped, self, x) -Rerr$misvalued <- function(x) .Call(wrap__Rerr__misvalued, self, x) +RPolarsErr$misvalued <- function(x) .Call(wrap__RPolarsErr__misvalued, self, x) -Rerr$plain <- function(x) .Call(wrap__Rerr__plain, self, x) +RPolarsErr$plain <- function(x) .Call(wrap__RPolarsErr__plain, self, x) -Rerr$when <- function(x) .Call(wrap__Rerr__when, self, x) +RPolarsErr$when <- function(x) .Call(wrap__RPolarsErr__when, self, x) -Rerr$when_last <- function(x) .Call(wrap__Rerr__when_last, self, x) +RPolarsErr$when_last <- function(x) .Call(wrap__RPolarsErr__when_last, self, x) -Rerr$wherein <- function(x) .Call(wrap__Rerr__wherein, self, x) +RPolarsErr$wherein <- function(x) .Call(wrap__RPolarsErr__wherein, self, x) #' @export -`$.Rerr` <- function (self, name) { func <- Rerr[[name]]; environment(func) <- environment(); func } +`$.RPolarsErr` <- function (self, name) { func <- RPolarsErr[[name]]; environment(func) <- environment(); func } #' @export -`[[.Rerr` <- `$.Rerr` +`[[.RPolarsErr` <- `$.RPolarsErr` DataFrame <- new.env(parent = emptyenv()) diff --git a/R/rerr.R b/R/rerr.R index af65ecafb..8adb6102c 100644 --- a/R/rerr.R +++ b/R/rerr.R @@ -2,32 +2,32 @@ #' @title auto complete $-access into a polars object #' @description called by the interactive R session internally -#' @param x Rerr +#' @param x RPolarsErr #' @param pattern code-stump as string to auto-complete #' @export #' @keywords internal -.DollarNames.Rerr = function(x, pattern = "") { - get_method_usages(Rerr, pattern = pattern) +.DollarNames.RPolarsErr = function(x, pattern = "") { + get_method_usages(RPolarsErr, pattern = pattern) } #' @export #' @noRd -as.character.Rerr = function(x, ...) x$info() +as.character.RPolarsErr = function(x, ...) x$info() #' @export #' @noRd -print.Rerr = function(x, ...) cat(x$info()) +print.RPolarsErr = function(x, ...) cat(x$info()) -## Rerr IPLEMENTS IPLEMENTS R-POLARS error_trait.R -when_calling.Rerr = function(err, call) { +## RPolarsErr IPLEMENTS IPLEMENTS R-POLARS error_trait.R +when_calling.RPolarsErr = function(err, call) { err$when_last(paste("calling:", call_to_string(call))) } -where_in.Rerr = function(err, context) { +where_in.RPolarsErr = function(err, context) { err$wherein(context) } -to_condition.Rerr = function(err) { +to_condition.RPolarsErr = function(err) { errorCondition( err$info(), class = c("Rerr_error"), @@ -35,6 +35,6 @@ to_condition.Rerr = function(err) { call = NULL ) } -plain.Rerr = function(err, msg) { +plain.RPolarsErr = function(err, msg) { err$value$plain(msg) } diff --git a/man/dot-DollarNames.Rerr.Rd b/man/dot-DollarNames.RPolarsErr.Rd similarity index 68% rename from man/dot-DollarNames.Rerr.Rd rename to man/dot-DollarNames.RPolarsErr.Rd index e0f3d1f40..a15910444 100644 --- a/man/dot-DollarNames.Rerr.Rd +++ b/man/dot-DollarNames.RPolarsErr.Rd @@ -1,13 +1,13 @@ % Generated by roxygen2: do not edit by hand % Please edit documentation in R/rerr.R -\name{.DollarNames.Rerr} -\alias{.DollarNames.Rerr} +\name{.DollarNames.RPolarsErr} +\alias{.DollarNames.RPolarsErr} \title{auto complete $-access into a polars object} \usage{ -\method{.DollarNames}{Rerr}(x, pattern = "") +\method{.DollarNames}{RPolarsErr}(x, pattern = "") } \arguments{ -\item{x}{Rerr} +\item{x}{RPolarsErr} \item{pattern}{code-stump as string to auto-complete} } diff --git a/man/nanoarrow.Rd b/man/nanoarrow.Rd index 3ecaf02a4..7af2018a2 100644 --- a/man/nanoarrow.Rd +++ b/man/nanoarrow.Rd @@ -16,13 +16,13 @@ \alias{as_record_batch_reader.DataFrame} \title{polars to nanoarrow and arrow} \usage{ -\method{as_nanoarrow_array_stream}{DataFrame}(x, ..., schema = NULL) +as_nanoarrow_array_stream.DataFrame(x, ..., schema = NULL) -\method{infer_nanoarrow_schema}{DataFrame}(x, ...) +infer_nanoarrow_schema.DataFrame(x, ...) -\method{as_arrow_table}{DataFrame}(x, ...) +as_arrow_table.DataFrame(x, ...) -\method{as_record_batch_reader}{DataFrame}(x, ..., schema = NULL) +as_record_batch_reader.DataFrame(x, ..., schema = NULL) } \arguments{ \item{x}{a polars DataFrame} diff --git a/man/result.Rd b/man/result.Rd index be19202de..93b864982 100644 --- a/man/result.Rd +++ b/man/result.Rd @@ -25,16 +25,16 @@ Capture any R error and return a rust-like Result unwrap = environment(polars::pl$all)$unwrap Err = environment(polars::pl$all)$Err - #capture regular R errors or Rerr + #capture regular R errors or RPolarsErr throw_simpleError = \() stop("Imma simple error") result(throw_simpleError()) throw_Rerr = \() unwrap( - Err(.pr$Rerr$new()$bad_robj(42)$mistyped("String")$when("doing something")) + Err(.pr$RPolarsErr$new()$bad_robj(42)$mistyped("String")$when("doing something")) ) res_Rerr = result(throw_Rerr()) str(res_Rerr) - Rerr = unwrap_err(res_Rerr) - Rerr$contexts() + RPolarsErr = unwrap_err(res_Rerr) + RPolarsErr$contexts() } \keyword{internal} diff --git a/src/rust/src/rerr.rs b/src/rust/src/rerr.rs index d192eb94a..dc0a82cf2 100644 --- a/src/rust/src/rerr.rs +++ b/src/rust/src/rerr.rs @@ -31,8 +31,8 @@ pub enum Rctx { } #[derive(Clone, Debug)] -pub struct Rerr(VecDeque); -pub type RResult = core::result::Result; +pub struct RPolarsErr(VecDeque); +pub type RResult = core::result::Result; pub trait WithRctx { fn ctx(self, rctx: Rctx) -> RResult; @@ -47,7 +47,7 @@ pub trait WithRctx { fn wherein>(self, env: S) -> RResult; } -impl> WithRctx for core::result::Result { +impl> WithRctx for core::result::Result { fn ctx(self, rctx: Rctx) -> RResult { self.map_err(|e| { let mut rerr = e.into(); @@ -96,9 +96,9 @@ impl> WithRctx for core::result::Result { } #[extendr] -impl Rerr { +impl RPolarsErr { pub fn new() -> Self { - Rerr(VecDeque::new()) + RPolarsErr(VecDeque::new()) } pub fn info(&self) -> String { @@ -152,7 +152,7 @@ impl Rerr { } } //methods not to export with extendr -impl Rerr { +impl RPolarsErr { pub fn push_front_rctx(&self, rctx: Rctx) -> Self { let mut rerr = self.clone(); rerr.0.push_front(rctx); @@ -165,7 +165,7 @@ impl Rerr { } } -impl std::fmt::Display for Rerr { +impl std::fmt::Display for RPolarsErr { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, @@ -180,27 +180,27 @@ impl std::fmt::Display for Rerr { } } -impl From for String { - fn from(rerr: Rerr) -> Self { +impl From for String { + fn from(rerr: RPolarsErr) -> Self { rerr.info() } } -impl From for Rerr { +impl From for RPolarsErr { default fn from(err: E) -> Self { - Rerr(VecDeque::from([Rctx::Plain(rdbg(err))])) + RPolarsErr(VecDeque::from([Rctx::Plain(rdbg(err))])) } } -impl From for Rerr { +impl From for RPolarsErr { fn from(extendr_err: extendr_api::Error) -> Self { - Rerr(VecDeque::from([Rctx::Extendr(rdbg(extendr_err))])) + RPolarsErr(VecDeque::from([Rctx::Extendr(rdbg(extendr_err))])) } } -impl From for Rerr { +impl From for RPolarsErr { fn from(polars_err: polars::error::PolarsError) -> Self { - let mut rerr = Rerr::new(); + let mut rerr = RPolarsErr::new(); rerr.0.push_back(Rctx::Polars(rdbg(&polars_err))); match polars_err { polars::prelude::PolarsError::InvalidOperation(x) => { @@ -216,7 +216,7 @@ impl From for Rerr { } pub fn rerr() -> RResult { - Err(Rerr::new()) + Err(RPolarsErr::new()) } //any rust impl Debug to string @@ -243,6 +243,6 @@ pub fn test_rerr() -> RResult { extendr_module! { mod rerr; - impl Rerr; + impl RPolarsErr; fn test_rerr; } diff --git a/src/rust/src/utils/mod.rs b/src/rust/src/utils/mod.rs index 634ca13ba..ceab75653 100644 --- a/src/rust/src/utils/mod.rs +++ b/src/rust/src/utils/mod.rs @@ -3,7 +3,7 @@ pub mod extendr_concurrent; pub mod wrappers; use crate::lazy::dsl::Expr; use crate::rdatatype::RPolarsDataType; -use crate::rerr::{rdbg, rerr, RResult, Rerr, WithRctx}; +use crate::rerr::{rdbg, rerr, RResult, RPolarsErr, WithRctx}; use extendr_api::prelude::list; use std::any::type_name as tn; @@ -492,7 +492,7 @@ pub fn robj_to_i64(robj: extendr_api::Robj) -> RResult { (Rtype::Integers, 1) => robj.as_integer().map(i64::from), (_, _) => None, } - .ok_or(Rerr::new()) + .ok_or(RPolarsErr::new()) .bad_robj(&robj) .mistyped(tn::()); } @@ -512,7 +512,7 @@ pub fn robj_to_u8(robj: extendr_api::Robj) -> RResult { pub fn robj_to_bool(robj: extendr_api::Robj) -> RResult { let robj = unpack_r_result_list(robj)?; robj.as_bool() - .ok_or(Rerr::new()) + .ok_or(RPolarsErr::new()) .bad_robj(&robj) .mistyped(tn::()) } @@ -521,7 +521,7 @@ pub fn robj_to_binary_vec(robj: extendr_api::Robj) -> RResult> { let robj = unpack_r_result_list(robj)?; let binary_vec: Vec = robj .as_raw_slice() - .ok_or(Rerr::new()) + .ok_or(RPolarsErr::new()) .bad_robj(&robj) .mistyped(tn::>())? .to_vec(); @@ -603,7 +603,7 @@ pub fn robj_to_lazyframe(robj: extendr_api::Robj) -> RResult RResult> { use extendr_api::*; let robj = unpack_r_result_list(robj)?; - let l = robj.as_list().ok_or(Rerr::new()).mistyped(tn::())?; + let l = robj.as_list().ok_or(RPolarsErr::new()).mistyped(tn::())?; let iter = l .iter() .map(|(_, robj)| robj_to_rexpr(robj, str_to_lit).map(|e| e.0)); diff --git a/tests/testthat/helper.R b/tests/testthat/helper.R index b9dc701eb..9e1b265c8 100644 --- a/tests/testthat/helper.R +++ b/tests/testthat/helper.R @@ -75,9 +75,9 @@ make_print_cases = function() { ) } -# Expect a Rerr with given contexts +# Expect a RPolarsErr with given contexts expect_rerr = function(expr, ctxs) { res = result(expr) - expect_identical(class(res$err), "Rerr") + expect_identical(class(res$err), "RPolarsErr") expect_identical(names(res$err$contexts()), ctxs) } diff --git a/tests/testthat/test-Rerr.R b/tests/testthat/test-Rerr.R index 63b6085a4..096384c31 100644 --- a/tests/testthat/test-Rerr.R +++ b/tests/testthat/test-Rerr.R @@ -4,7 +4,7 @@ test_that("can add any context to err", { "bad_arg", "bad_robj", "bad_val", "hint", "mistyped", "misvalued", "plain", "when" ) - rerr = .pr$Rerr$new() + rerr = .pr$RPolarsErr$new() for (i in err_types) rerr = rerr[[i]](i) expect_identical( From ee1914efb7acde27d2e463a856339128d8e871f2 Mon Sep 17 00:00:00 2001 From: sorhawell Date: Wed, 21 Jun 2023 15:52:27 +0200 Subject: [PATCH 21/24] finalize renaming --- DESCRIPTION | 2 +- R/error_conversion.R | 8 ++++---- R/extendr-wrappers.R | 2 +- R/{rerr.R => rpolarserr.R} | 2 +- man/dot-DollarNames.RPolarsErr.Rd | 2 +- man/result.Rd | 8 ++++---- src/rust/src/lazy/dataframe.rs | 6 +++--- src/rust/src/lazy/dsl.rs | 4 ++-- src/rust/src/lib.rs | 4 ++-- src/rust/src/rdataframe/read_ipc.rs | 2 +- src/rust/src/rlib.rs | 2 +- src/rust/src/{rerr.rs => rpolarserr.rs} | 14 ++++++-------- src/rust/src/utils/mod.rs | 17 ++++++++++------- tests/testthat/helper.R | 2 +- tests/testthat/test-Rerr.R | 6 +++--- tests/testthat/test-bit64.R | 12 ++++++------ 16 files changed, 47 insertions(+), 46 deletions(-) rename R/{rerr.R => rpolarserr.R} (96%) rename src/rust/src/{rerr.rs => rpolarserr.rs} (96%) diff --git a/DESCRIPTION b/DESCRIPTION index 180ae9f9e..959b46794 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -76,8 +76,8 @@ Collate: 'parquet.R' 'pkg-knitr.R' 'pkg-nanoarrow.R' - 'rerr.R' 'rlang.R' + 'rpolarserr.R' 'rust_result.R' 's3_methods.R' 'series__series.R' diff --git a/R/error_conversion.R b/R/error_conversion.R index b58155c54..3010b55f1 100644 --- a/R/error_conversion.R +++ b/R/error_conversion.R @@ -71,12 +71,12 @@ unwrap_err = function(result) { #' throw_simpleError = \() stop("Imma simple error") #' result(throw_simpleError()) #' -#' throw_Rerr = \() unwrap( +#' throw_RPolarsErr = \() unwrap( #' Err(.pr$RPolarsErr$new()$bad_robj(42)$mistyped("String")$when("doing something")) #' ) -#' res_Rerr = result(throw_Rerr()) -#' str(res_Rerr) -#' RPolarsErr = unwrap_err(res_Rerr) +#' res_RPolarsErr = result(throw_RPolarsErr()) +#' str(res_RPolarsErr) +#' RPolarsErr = unwrap_err(res_RPolarsErr) #' RPolarsErr$contexts() result = function(expr, msg = NULL) { tryCatch( diff --git a/R/extendr-wrappers.R b/R/extendr-wrappers.R index 5c6918fa9..c54a66cd9 100644 --- a/R/extendr-wrappers.R +++ b/R/extendr-wrappers.R @@ -11,7 +11,7 @@ #' @useDynLib polars, .registration = TRUE NULL -test_rerr <- function() .Call(wrap__test_rerr) +test_rpolarserr <- function() .Call(wrap__test_rpolarserr) rlazy_csv_reader <- function(path, sep, has_header, ignore_errors, skip_rows, n_rows, cache, overwrite_dtype, low_memory, comment_char, quote_char, null_values, infer_schema_length, skip_rows_after_header, encoding, row_count_name, row_count_offset, parse_dates) .Call(wrap__rlazy_csv_reader, path, sep, has_header, ignore_errors, skip_rows, n_rows, cache, overwrite_dtype, low_memory, comment_char, quote_char, null_values, infer_schema_length, skip_rows_after_header, encoding, row_count_name, row_count_offset, parse_dates) diff --git a/R/rerr.R b/R/rpolarserr.R similarity index 96% rename from R/rerr.R rename to R/rpolarserr.R index 8adb6102c..a0fb37403 100644 --- a/R/rerr.R +++ b/R/rpolarserr.R @@ -30,7 +30,7 @@ where_in.RPolarsErr = function(err, context) { to_condition.RPolarsErr = function(err) { errorCondition( err$info(), - class = c("Rerr_error"), + class = c("RPolarsErr_error"), value = err, call = NULL ) diff --git a/man/dot-DollarNames.RPolarsErr.Rd b/man/dot-DollarNames.RPolarsErr.Rd index a15910444..e6a9e58d9 100644 --- a/man/dot-DollarNames.RPolarsErr.Rd +++ b/man/dot-DollarNames.RPolarsErr.Rd @@ -1,5 +1,5 @@ % Generated by roxygen2: do not edit by hand -% Please edit documentation in R/rerr.R +% Please edit documentation in R/rpolarserr.R \name{.DollarNames.RPolarsErr} \alias{.DollarNames.RPolarsErr} \title{auto complete $-access into a polars object} diff --git a/man/result.Rd b/man/result.Rd index 93b864982..ea9e31166 100644 --- a/man/result.Rd +++ b/man/result.Rd @@ -29,12 +29,12 @@ Capture any R error and return a rust-like Result throw_simpleError = \() stop("Imma simple error") result(throw_simpleError()) - throw_Rerr = \() unwrap( + throw_RPolarsErr = \() unwrap( Err(.pr$RPolarsErr$new()$bad_robj(42)$mistyped("String")$when("doing something")) ) - res_Rerr = result(throw_Rerr()) - str(res_Rerr) - RPolarsErr = unwrap_err(res_Rerr) + res_RPolarsErr = result(throw_RPolarsErr()) + str(res_RPolarsErr) + RPolarsErr = unwrap_err(res_RPolarsErr) RPolarsErr$contexts() } \keyword{internal} diff --git a/src/rust/src/lazy/dataframe.rs b/src/rust/src/lazy/dataframe.rs index 126a33ef5..6abf9996d 100644 --- a/src/rust/src/lazy/dataframe.rs +++ b/src/rust/src/lazy/dataframe.rs @@ -5,8 +5,8 @@ use crate::rdatatype::new_asof_strategy; use crate::rdatatype::new_join_type; use crate::rdatatype::new_quantile_interpolation_option; use crate::rdatatype::new_unique_keep_strategy; -use crate::rerr::{Rctx, WithRctx}; use crate::robj_to; +use crate::rpolarserr::{Rctx, WithRctx}; use crate::utils::wrappers::null_to_opt; use crate::utils::{r_result_list, try_f64_into_usize}; use extendr_api::prelude::*; @@ -78,8 +78,8 @@ impl LazyFrame { }) } - pub fn collect_handled(&self) -> crate::rerr::RResult { - use crate::rerr::WithRctx; + pub fn collect_handled(&self) -> crate::rpolarserr::RResult { + use crate::rpolarserr::WithRctx; handle_thread_r_requests(self.clone().0).when("calling $collect() on LazyFrame") } diff --git a/src/rust/src/lazy/dsl.rs b/src/rust/src/lazy/dsl.rs index eada4da01..73d0d4c93 100644 --- a/src/rust/src/lazy/dsl.rs +++ b/src/rust/src/lazy/dsl.rs @@ -5,6 +5,7 @@ use crate::rdatatype::new_rank_method; use crate::rdatatype::robj_to_timeunit; use crate::rdatatype::{DataTypeVector, RPolarsDataType}; use crate::robj_to; +use crate::rpolarserr; use crate::series::Series; use crate::utils::extendr_concurrent::{ParRObj, ThreadCom}; use crate::utils::parse_fill_null_strategy; @@ -2195,8 +2196,7 @@ impl Expr { //the only cat ns function from dsl.rs fn cat_set_ordering(&self, ordering: Robj) -> Result { let ordering = robj_to!(Map, str, ordering, |s| { - use crate::rerr::Rctx; - Ok(crate::rdatatype::new_categorical_ordering(s).map_err(Rctx::Plain)?) + Ok(crate::rdatatype::new_categorical_ordering(s).map_err(rpolarserr::Rctx::Plain)?) })?; Ok(self.0.clone().cat().set_ordering(ordering).into()) } diff --git a/src/rust/src/lib.rs b/src/rust/src/lib.rs index e8e1ce6dc..af1ae7d03 100644 --- a/src/rust/src/lib.rs +++ b/src/rust/src/lib.rs @@ -19,8 +19,8 @@ pub mod conversion_r_to_s; pub mod conversion_s_to_r; pub mod rdataframe; pub mod rdatatype; -pub mod rerr; pub mod rlib; +pub mod rpolarserr; pub mod series; pub mod utils; @@ -40,7 +40,7 @@ static CONFIG: ThreadComStorage = Storage::new(); // Macro to generate exports extendr_module! { mod polars; - use rerr; + use rpolarserr; use rdataframe; use lazy; use series; diff --git a/src/rust/src/rdataframe/read_ipc.rs b/src/rust/src/rdataframe/read_ipc.rs index 78842ed46..2c0b5de16 100644 --- a/src/rust/src/rdataframe/read_ipc.rs +++ b/src/rust/src/rdataframe/read_ipc.rs @@ -1,6 +1,6 @@ use crate::lazy::dataframe::LazyFrame as RLazyFrame; -use crate::rerr::RResult; use crate::robj_to; +use crate::rpolarserr::RResult; use extendr_api::prelude::*; use polars::io::RowCount; use polars::prelude::{LazyFrame, ScanArgsIpc}; diff --git a/src/rust/src/rlib.rs b/src/rust/src/rlib.rs index 2bf89ad9c..080219f7e 100644 --- a/src/rust/src/rlib.rs +++ b/src/rust/src/rlib.rs @@ -1,6 +1,6 @@ use crate::lazy::dsl::Expr; use crate::rdataframe::DataFrame; -use crate::rerr::{rdbg, RResult}; +use crate::rpolarserr::{rdbg, RResult}; use crate::{rdataframe::VecDataFrame, utils::r_result_list}; use crate::lazy::dsl::ProtoExprArray; diff --git a/src/rust/src/rerr.rs b/src/rust/src/rpolarserr.rs similarity index 96% rename from src/rust/src/rerr.rs rename to src/rust/src/rpolarserr.rs index dc0a82cf2..008d1efd1 100644 --- a/src/rust/src/rerr.rs +++ b/src/rust/src/rpolarserr.rs @@ -1,8 +1,8 @@ use std::collections::VecDeque; use extendr_api::{ - extendr, extendr_module, symbol::class_symbol, Attributes, Pairlist, Rinternals, Robj, - Operators, eval_string, call, Types, + call, eval_string, extendr, extendr_module, symbol::class_symbol, Attributes, Operators, + Pairlist, Rinternals, Robj, Types, }; use thiserror::Error; @@ -67,8 +67,6 @@ impl> WithRctx for core::result::Result { fn bad_robj(self, robj: &Robj) -> RResult { self.bad_val(robj_dbg(robj)) } - - fn hint>(self, cause: S) -> RResult { self.ctx(Rctx::Hint(cause.into())) @@ -230,19 +228,19 @@ pub fn robj_dbg(robj: &Robj) -> String { format!( "Rvalue: {}{}, Rsexp: {:?}, Rclass: {:?}", &s[0..(s.len().min(128))], - if s.len()>128 {"...] "} else {""}, + if s.len() > 128 { "...] " } else { "" }, robj.rtype(), call!("base::class", robj).expect("internal error: could not use base::class(robj)") ) } #[extendr] -pub fn test_rerr() -> RResult { +pub fn test_rpolarserr() -> RResult { rerr().bad_val("-1").mistyped("usize").bad_arg("path") } extendr_module! { - mod rerr; + mod rpolarserr; impl RPolarsErr; - fn test_rerr; + fn test_rpolarserr; } diff --git a/src/rust/src/utils/mod.rs b/src/rust/src/utils/mod.rs index ceab75653..5800dbc7a 100644 --- a/src/rust/src/utils/mod.rs +++ b/src/rust/src/utils/mod.rs @@ -3,7 +3,7 @@ pub mod extendr_concurrent; pub mod wrappers; use crate::lazy::dsl::Expr; use crate::rdatatype::RPolarsDataType; -use crate::rerr::{rdbg, rerr, RResult, RPolarsErr, WithRctx}; +use crate::rpolarserr::{rdbg, rerr, RPolarsErr, RResult, WithRctx}; use extendr_api::prelude::list; use std::any::type_name as tn; @@ -603,7 +603,10 @@ pub fn robj_to_lazyframe(robj: extendr_api::Robj) -> RResult RResult> { use extendr_api::*; let robj = unpack_r_result_list(robj)?; - let l = robj.as_list().ok_or(RPolarsErr::new()).mistyped(tn::())?; + let l = robj + .as_list() + .ok_or(RPolarsErr::new()) + .mistyped(tn::())?; let iter = l .iter() .map(|(_, robj)| robj_to_rexpr(robj, str_to_lit).map(|e| e.0)); @@ -718,7 +721,7 @@ macro_rules! robj_to { }}; (Option, $type:ident, $a:ident) => {{ - use $crate::rerr::WithRctx; + use $crate::rpolarserr::WithRctx; $crate::utils::unpack_r_result_list($a).and_then(|$a| { if ($a.is_null()) { Ok(None) @@ -730,7 +733,7 @@ macro_rules! robj_to { //iterate list and call this macro again on inner objects (Vec, $type:ident, $a:ident) => {{ - use $crate::rerr::WithRctx; + use $crate::rpolarserr::WithRctx; //unpack raise any R result error $crate::utils::unpack_r_result_list($a).and_then(|x: Robj| { //coerce R vectors into list @@ -756,19 +759,19 @@ macro_rules! robj_to { }}; (Map, $type:ident, $a:ident, $f:expr) => {{ - use $crate::rerr::WithRctx; + use $crate::rpolarserr::WithRctx; $crate::robj_to_inner!($type, $a) .and_then($f) .bad_arg(stringify!($a)) }}; ($type:ident, $a:ident) => {{ - use $crate::rerr::WithRctx; + use $crate::rpolarserr::WithRctx; $crate::robj_to_inner!($type, $a).bad_arg(stringify!($a)) }}; ($type:ident, $a:ident, $b:expr) => {{ - use $crate::rerr::WithRctx; + use $crate::rpolarserr::WithRctx; $crate::robj_to_inner!($type, $a) .hint($b) .bad_arg(stringify!($a)) diff --git a/tests/testthat/helper.R b/tests/testthat/helper.R index 9e1b265c8..914a9c45b 100644 --- a/tests/testthat/helper.R +++ b/tests/testthat/helper.R @@ -76,7 +76,7 @@ make_print_cases = function() { } # Expect a RPolarsErr with given contexts -expect_rerr = function(expr, ctxs) { +expect_rpolarserr = function(expr, ctxs) { res = result(expr) expect_identical(class(res$err), "RPolarsErr") expect_identical(names(res$err$contexts()), ctxs) diff --git a/tests/testthat/test-Rerr.R b/tests/testthat/test-Rerr.R index 096384c31..00c6d0809 100644 --- a/tests/testthat/test-Rerr.R +++ b/tests/testthat/test-Rerr.R @@ -4,11 +4,11 @@ test_that("can add any context to err", { "bad_arg", "bad_robj", "bad_val", "hint", "mistyped", "misvalued", "plain", "when" ) - rerr = .pr$RPolarsErr$new() - for (i in err_types) rerr = rerr[[i]](i) + rpolarserr = .pr$RPolarsErr$new() + for (i in err_types) rpolarserr = rpolarserr[[i]](i) expect_identical( - names(rerr$contexts()), + names(rpolarserr$contexts()), c( "When", "PlainErrorMessage", "ValueOutOfScope", "TypeMismatch", "Hint", "BadValue", "BadValue", "BadArgument" diff --git a/tests/testthat/test-bit64.R b/tests/testthat/test-bit64.R index 7e320361a..7019ad2b6 100644 --- a/tests/testthat/test-bit64.R +++ b/tests/testthat/test-bit64.R @@ -44,33 +44,33 @@ test_that("robj_to! from bit64", { ) # NO NA - expect_rerr( + expect_rpolarserr( unwrap(test_robj_to_i64(bit64::as.integer64(NA)), call= NULL), c("BadArgument", "TypeMismatch", "BadValue") ) - expect_rerr( + expect_rpolarserr( unwrap(test_robj_to_usize(bit64::as.integer64(NA)), call= NULL), c("BadArgument", "TypeMismatch", "BadValue") ) # NO OVERFLOW - expect_rerr( + expect_rpolarserr( unwrap(test_robj_to_u32(2^57), call= NULL), c("BadArgument", "TypeMismatch", "BadValue") ) # NO NEGATIVE - expect_rerr( + expect_rpolarserr( unwrap(test_robj_to_usize(bit64::as.integer64(-1)), call = NULL), c("BadArgument", "TypeMismatch", "BadValue") ) - expect_rerr( + expect_rpolarserr( unwrap(test_robj_to_u32(bit64::as.integer64(-1)), call = NULL), c("BadArgument", "TypeMismatch", "BadValue") ) # NO length>1 - expect_rerr( + expect_rpolarserr( unwrap(test_robj_to_usize(bit64::as.integer64(c(1:2))), call = NULL), c("BadArgument", "TypeMismatch", "BadValue") ) From 59702554f5a243193b06c82d9d292c913d5041ee Mon Sep 17 00:00:00 2001 From: sorhawell Date: Wed, 21 Jun 2023 16:13:53 +0200 Subject: [PATCH 22/24] auto style all --- R/error_conversion.R | 40 +- R/error_trait.R | 25 +- R/extendr-wrappers.R | 1096 ++++++++++++++++++++++-------------------- R/rpolarserr.R | 2 - R/string_error.R | 6 +- man/result.Rd | 28 +- man/unwrap.Rd | 2 +- 7 files changed, 632 insertions(+), 567 deletions(-) diff --git a/R/error_conversion.R b/R/error_conversion.R index 3010b55f1..9e87ccc71 100644 --- a/R/error_conversion.R +++ b/R/error_conversion.R @@ -1,4 +1,4 @@ -#THIS FILE IMPLEMENTS ERROR CONVERSION, FOR R TO Result-list & FOR Result-list TO R +# THIS FILE IMPLEMENTS ERROR CONVERSION, FOR R TO Result-list & FOR Result-list TO R # TODO unwrap should be eventually renamed to unwrap_with_context (or similar) # a simpler unwrap without where_in and when_calling should be defined in rust_result.R @@ -13,7 +13,7 @@ #' @keywords internal #' @examples #' -#' #get unwrap without using ::: +#' # get unwrap without using ::: #' unwrap = environment(polars::pl$all)$unwrap #' #' structure(list(ok = "foo", err = NULL), class = "extendr_result") @@ -28,7 +28,7 @@ #' error = function(err) as.character(err) #' ) unwrap = function(result, context = NULL, call = sys.call(1L)) { - if(is_ok(result)) { + if (is_ok(result)) { result$ok } else { result$err |> @@ -46,7 +46,7 @@ unwrap = function(result, context = NULL, call = sys.call(1L)) { #' @param result a Result, see rust_result.R#' #' @return some error type unwrap_err = function(result) { - if(is_ok(result)) { + if (is_ok(result)) { stop("internal error: Cannot unwrap_err an Ok-value") } else { result$err @@ -61,26 +61,28 @@ unwrap_err = function(result) { #' @return Result #' @examples #' -#' #user internal functions without using ::: -#' result = environment(polars::pl$all)$result -#' unwrap_err = environment(polars::pl$all)$unwrap_err -#' unwrap = environment(polars::pl$all)$unwrap -#' Err = environment(polars::pl$all)$Err +#' # user internal functions without using ::: +#' result = environment(polars::pl$all)$result +#' unwrap_err = environment(polars::pl$all)$unwrap_err +#' unwrap = environment(polars::pl$all)$unwrap +#' Err = environment(polars::pl$all)$Err #' -#' #capture regular R errors or RPolarsErr -#' throw_simpleError = \() stop("Imma simple error") -#' result(throw_simpleError()) +#' # capture regular R errors or RPolarsErr +#' throw_simpleError = \() stop("Imma simple error") +#' result(throw_simpleError()) #' -#' throw_RPolarsErr = \() unwrap( +#' throw_RPolarsErr = \() unwrap( #' Err(.pr$RPolarsErr$new()$bad_robj(42)$mistyped("String")$when("doing something")) -#' ) -#' res_RPolarsErr = result(throw_RPolarsErr()) -#' str(res_RPolarsErr) -#' RPolarsErr = unwrap_err(res_RPolarsErr) -#' RPolarsErr$contexts() +#' ) +#' res_RPolarsErr = result(throw_RPolarsErr()) +#' str(res_RPolarsErr) +#' RPolarsErr = unwrap_err(res_RPolarsErr) +#' RPolarsErr$contexts() result = function(expr, msg = NULL) { tryCatch( Ok(expr), - error = \(cond) cond$value %||% cond$message |> plain(msg) |> Err() + error = \(cond) cond$value %||% cond$message |> + plain(msg) |> + Err() ) } diff --git a/R/error_trait.R b/R/error_trait.R index 509b7d03b..73c6eafdc 100644 --- a/R/error_trait.R +++ b/R/error_trait.R @@ -21,7 +21,7 @@ when_calling = function(err, call) { when_calling.default = function(err, call) { stop("internal error: an error-type was not fully implemented") } -#support function to convert a call to a string +# support function to convert a call to a string call_to_string = function(call) { paste( "\n", @@ -38,16 +38,17 @@ call_to_string = function(call) { #' @examples #' # where_in = function(err, context) { - - if(is.null(context)) { + if (is.null(context)) { return(err) } - if(!is_string(context)) stop( - paste( - "internal error: where_in context must be a string or NULL it was: ", - str_string(context) + if (!is_string(context)) { + stop( + paste( + "internal error: where_in context must be a string or NULL it was: ", + str_string(context) + ) ) - ) + } UseMethod("where_in", err) } where_in.default = function(err, context) { @@ -82,11 +83,11 @@ to_condition.default = function(err) { #' @keywords internal #' @return condition plain = function(err, msg) { - if(is.null(msg)) return(err) + if (is.null(msg)) { + return(err) + } UseMethod("plain", err) } plain.default = function(err, msg) { - paste0(msg,": ", err) + paste0(msg, ": ", err) } - - diff --git a/R/extendr-wrappers.R b/R/extendr-wrappers.R index c54a66cd9..c8f790a1c 100644 --- a/R/extendr-wrappers.R +++ b/R/extendr-wrappers.R @@ -11,1069 +11,1133 @@ #' @useDynLib polars, .registration = TRUE NULL -test_rpolarserr <- function() .Call(wrap__test_rpolarserr) +test_rpolarserr = function() .Call(wrap__test_rpolarserr) -rlazy_csv_reader <- function(path, sep, has_header, ignore_errors, skip_rows, n_rows, cache, overwrite_dtype, low_memory, comment_char, quote_char, null_values, infer_schema_length, skip_rows_after_header, encoding, row_count_name, row_count_offset, parse_dates) .Call(wrap__rlazy_csv_reader, path, sep, has_header, ignore_errors, skip_rows, n_rows, cache, overwrite_dtype, low_memory, comment_char, quote_char, null_values, infer_schema_length, skip_rows_after_header, encoding, row_count_name, row_count_offset, parse_dates) +rlazy_csv_reader = function(path, sep, has_header, ignore_errors, skip_rows, n_rows, cache, overwrite_dtype, low_memory, comment_char, quote_char, null_values, infer_schema_length, skip_rows_after_header, encoding, row_count_name, row_count_offset, parse_dates) .Call(wrap__rlazy_csv_reader, path, sep, has_header, ignore_errors, skip_rows, n_rows, cache, overwrite_dtype, low_memory, comment_char, quote_char, null_values, infer_schema_length, skip_rows_after_header, encoding, row_count_name, row_count_offset, parse_dates) -import_arrow_ipc <- function(path, n_rows, cache, rechunk, row_name, row_count, memmap) .Call(wrap__import_arrow_ipc, path, n_rows, cache, rechunk, row_name, row_count, memmap) +import_arrow_ipc = function(path, n_rows, cache, rechunk, row_name, row_count, memmap) .Call(wrap__import_arrow_ipc, path, n_rows, cache, rechunk, row_name, row_count, memmap) -new_from_parquet <- function(path, n_rows, cache, parallel, rechunk, row_name, row_count, low_memory) .Call(wrap__new_from_parquet, path, n_rows, cache, parallel, rechunk, row_name, row_count, low_memory) +new_from_parquet = function(path, n_rows, cache, parallel, rechunk, row_name, row_count, low_memory) .Call(wrap__new_from_parquet, path, n_rows, cache, parallel, rechunk, row_name, row_count, low_memory) -concat_df <- function(vdf) .Call(wrap__concat_df, vdf) +concat_df = function(vdf) .Call(wrap__concat_df, vdf) -hor_concat_df <- function(dfs) .Call(wrap__hor_concat_df, dfs) +hor_concat_df = function(dfs) .Call(wrap__hor_concat_df, dfs) -diag_concat_df <- function(dfs) .Call(wrap__diag_concat_df, dfs) +diag_concat_df = function(dfs) .Call(wrap__diag_concat_df, dfs) -min_exprs <- function(exprs) .Call(wrap__min_exprs, exprs) +min_exprs = function(exprs) .Call(wrap__min_exprs, exprs) -max_exprs <- function(exprs) .Call(wrap__max_exprs, exprs) +max_exprs = function(exprs) .Call(wrap__max_exprs, exprs) -coalesce_exprs <- function(exprs) .Call(wrap__coalesce_exprs, exprs) +coalesce_exprs = function(exprs) .Call(wrap__coalesce_exprs, exprs) -sum_exprs <- function(exprs) .Call(wrap__sum_exprs, exprs) +sum_exprs = function(exprs) .Call(wrap__sum_exprs, exprs) -mem_address <- function(robj) .Call(wrap__mem_address, robj) +mem_address = function(robj) .Call(wrap__mem_address, robj) -concat_lst <- function(exprs) .Call(wrap__concat_lst, exprs) +concat_lst = function(exprs) .Call(wrap__concat_lst, exprs) -r_date_range <- function(start, stop, every, closed, name, tu, tz) .Call(wrap__r_date_range, start, stop, every, closed, name, tu, tz) +r_date_range = function(start, stop, every, closed, name, tu, tz) .Call(wrap__r_date_range, start, stop, every, closed, name, tu, tz) -r_date_range_lazy <- function(start, end, every, closed, name, tz) .Call(wrap__r_date_range_lazy, start, end, every, closed, name, tz) +r_date_range_lazy = function(start, end, every, closed, name, tz) .Call(wrap__r_date_range_lazy, start, end, every, closed, name, tz) -as_struct <- function(exprs) .Call(wrap__as_struct, exprs) +as_struct = function(exprs) .Call(wrap__as_struct, exprs) -struct_ <- function(exprs, eager, schema) .Call(wrap__struct_, exprs, eager, schema) +struct_ = function(exprs, eager, schema) .Call(wrap__struct_, exprs, eager, schema) -rb_list_to_df <- function(r_batches, names) .Call(wrap__rb_list_to_df, r_batches, names) +rb_list_to_df = function(r_batches, names) .Call(wrap__rb_list_to_df, r_batches, names) -arrow_stream_to_rust <- function(rbr) invisible(.Call(wrap__arrow_stream_to_rust, rbr)) +arrow_stream_to_rust = function(rbr) invisible(.Call(wrap__arrow_stream_to_rust, rbr)) -test_robj_to_usize <- function(robj) .Call(wrap__test_robj_to_usize, robj) +test_robj_to_usize = function(robj) .Call(wrap__test_robj_to_usize, robj) -test_robj_to_i64 <- function(robj) .Call(wrap__test_robj_to_i64, robj) +test_robj_to_i64 = function(robj) .Call(wrap__test_robj_to_i64, robj) -test_robj_to_u32 <- function(robj) .Call(wrap__test_robj_to_u32, robj) +test_robj_to_u32 = function(robj) .Call(wrap__test_robj_to_u32, robj) -RPolarsErr <- new.env(parent = emptyenv()) +RPolarsErr = new.env(parent = emptyenv()) -RPolarsErr$new <- function() .Call(wrap__RPolarsErr__new) +RPolarsErr$new = function() .Call(wrap__RPolarsErr__new) -RPolarsErr$info <- function() .Call(wrap__RPolarsErr__info, self) +RPolarsErr$info = function() .Call(wrap__RPolarsErr__info, self) -RPolarsErr$contexts <- function() .Call(wrap__RPolarsErr__contexts, self) +RPolarsErr$contexts = function() .Call(wrap__RPolarsErr__contexts, self) -RPolarsErr$bad_arg <- function(x) .Call(wrap__RPolarsErr__bad_arg, self, x) +RPolarsErr$bad_arg = function(x) .Call(wrap__RPolarsErr__bad_arg, self, x) -RPolarsErr$bad_val <- function(x) .Call(wrap__RPolarsErr__bad_val, self, x) +RPolarsErr$bad_val = function(x) .Call(wrap__RPolarsErr__bad_val, self, x) -RPolarsErr$bad_robj <- function(x) .Call(wrap__RPolarsErr__bad_robj, self, x) +RPolarsErr$bad_robj = function(x) .Call(wrap__RPolarsErr__bad_robj, self, x) -RPolarsErr$hint <- function(x) .Call(wrap__RPolarsErr__hint, self, x) +RPolarsErr$hint = function(x) .Call(wrap__RPolarsErr__hint, self, x) -RPolarsErr$mistyped <- function(x) .Call(wrap__RPolarsErr__mistyped, self, x) +RPolarsErr$mistyped = function(x) .Call(wrap__RPolarsErr__mistyped, self, x) -RPolarsErr$misvalued <- function(x) .Call(wrap__RPolarsErr__misvalued, self, x) +RPolarsErr$misvalued = function(x) .Call(wrap__RPolarsErr__misvalued, self, x) -RPolarsErr$plain <- function(x) .Call(wrap__RPolarsErr__plain, self, x) +RPolarsErr$plain = function(x) .Call(wrap__RPolarsErr__plain, self, x) -RPolarsErr$when <- function(x) .Call(wrap__RPolarsErr__when, self, x) +RPolarsErr$when = function(x) .Call(wrap__RPolarsErr__when, self, x) -RPolarsErr$when_last <- function(x) .Call(wrap__RPolarsErr__when_last, self, x) +RPolarsErr$when_last = function(x) .Call(wrap__RPolarsErr__when_last, self, x) -RPolarsErr$wherein <- function(x) .Call(wrap__RPolarsErr__wherein, self, x) +RPolarsErr$wherein = function(x) .Call(wrap__RPolarsErr__wherein, self, x) #' @export -`$.RPolarsErr` <- function (self, name) { func <- RPolarsErr[[name]]; environment(func) <- environment(); func } +`$.RPolarsErr` = function(self, name) { + func = RPolarsErr[[name]] + environment(func) = environment() + func +} #' @export -`[[.RPolarsErr` <- `$.RPolarsErr` +`[[.RPolarsErr` = `$.RPolarsErr` -DataFrame <- new.env(parent = emptyenv()) +DataFrame = new.env(parent = emptyenv()) -DataFrame$shape <- function() .Call(wrap__DataFrame__shape, self) +DataFrame$shape = function() .Call(wrap__DataFrame__shape, self) -DataFrame$clone_see_me_macro <- function() .Call(wrap__DataFrame__clone_see_me_macro, self) +DataFrame$clone_see_me_macro = function() .Call(wrap__DataFrame__clone_see_me_macro, self) -DataFrame$default <- function() .Call(wrap__DataFrame__default) +DataFrame$default = function() .Call(wrap__DataFrame__default) -DataFrame$lazy <- function() .Call(wrap__DataFrame__lazy, self) +DataFrame$lazy = function() .Call(wrap__DataFrame__lazy, self) -DataFrame$new_with_capacity <- function(capacity) .Call(wrap__DataFrame__new_with_capacity, capacity) +DataFrame$new_with_capacity = function(capacity) .Call(wrap__DataFrame__new_with_capacity, capacity) -DataFrame$set_column_from_robj <- function(robj, name) .Call(wrap__DataFrame__set_column_from_robj, self, robj, name) +DataFrame$set_column_from_robj = function(robj, name) .Call(wrap__DataFrame__set_column_from_robj, self, robj, name) -DataFrame$set_column_from_series <- function(x) .Call(wrap__DataFrame__set_column_from_series, self, x) +DataFrame$set_column_from_series = function(x) .Call(wrap__DataFrame__set_column_from_series, self, x) -DataFrame$new_par_from_list <- function(robj_list) .Call(wrap__DataFrame__new_par_from_list, robj_list) +DataFrame$new_par_from_list = function(robj_list) .Call(wrap__DataFrame__new_par_from_list, robj_list) -DataFrame$print <- function() .Call(wrap__DataFrame__print, self) +DataFrame$print = function() .Call(wrap__DataFrame__print, self) -DataFrame$columns <- function() .Call(wrap__DataFrame__columns, self) +DataFrame$columns = function() .Call(wrap__DataFrame__columns, self) -DataFrame$set_column_names_mut <- function(names) .Call(wrap__DataFrame__set_column_names_mut, self, names) +DataFrame$set_column_names_mut = function(names) .Call(wrap__DataFrame__set_column_names_mut, self, names) -DataFrame$get_column <- function(name) .Call(wrap__DataFrame__get_column, self, name) +DataFrame$get_column = function(name) .Call(wrap__DataFrame__get_column, self, name) -DataFrame$get_columns <- function() .Call(wrap__DataFrame__get_columns, self) +DataFrame$get_columns = function() .Call(wrap__DataFrame__get_columns, self) -DataFrame$dtypes <- function() .Call(wrap__DataFrame__dtypes, self) +DataFrame$dtypes = function() .Call(wrap__DataFrame__dtypes, self) -DataFrame$dtype_strings <- function() .Call(wrap__DataFrame__dtype_strings, self) +DataFrame$dtype_strings = function() .Call(wrap__DataFrame__dtype_strings, self) -DataFrame$schema <- function() .Call(wrap__DataFrame__schema, self) +DataFrame$schema = function() .Call(wrap__DataFrame__schema, self) -DataFrame$to_list <- function() .Call(wrap__DataFrame__to_list, self) +DataFrame$to_list = function() .Call(wrap__DataFrame__to_list, self) -DataFrame$to_list_unwind <- function() .Call(wrap__DataFrame__to_list_unwind, self) +DataFrame$to_list_unwind = function() .Call(wrap__DataFrame__to_list_unwind, self) -DataFrame$to_list_tag_structs <- function() .Call(wrap__DataFrame__to_list_tag_structs, self) +DataFrame$to_list_tag_structs = function() .Call(wrap__DataFrame__to_list_tag_structs, self) -DataFrame$frame_equal <- function(other) .Call(wrap__DataFrame__frame_equal, self, other) +DataFrame$frame_equal = function(other) .Call(wrap__DataFrame__frame_equal, self, other) -DataFrame$select_at_idx <- function(idx) .Call(wrap__DataFrame__select_at_idx, self, idx) +DataFrame$select_at_idx = function(idx) .Call(wrap__DataFrame__select_at_idx, self, idx) -DataFrame$drop_in_place <- function(names) .Call(wrap__DataFrame__drop_in_place, self, names) +DataFrame$drop_in_place = function(names) .Call(wrap__DataFrame__drop_in_place, self, names) -DataFrame$select <- function(exprs) .Call(wrap__DataFrame__select, self, exprs) +DataFrame$select = function(exprs) .Call(wrap__DataFrame__select, self, exprs) -DataFrame$by_agg <- function(group_exprs, agg_exprs, maintain_order) .Call(wrap__DataFrame__by_agg, self, group_exprs, agg_exprs, maintain_order) +DataFrame$by_agg = function(group_exprs, agg_exprs, maintain_order) .Call(wrap__DataFrame__by_agg, self, group_exprs, agg_exprs, maintain_order) -DataFrame$to_struct <- function(name) .Call(wrap__DataFrame__to_struct, self, name) +DataFrame$to_struct = function(name) .Call(wrap__DataFrame__to_struct, self, name) -DataFrame$unnest <- function(names) .Call(wrap__DataFrame__unnest, self, names) +DataFrame$unnest = function(names) .Call(wrap__DataFrame__unnest, self, names) -DataFrame$export_stream <- function(stream_ptr) invisible(.Call(wrap__DataFrame__export_stream, self, stream_ptr)) +DataFrame$export_stream = function(stream_ptr) invisible(.Call(wrap__DataFrame__export_stream, self, stream_ptr)) -DataFrame$from_arrow_record_batches <- function(rbr) .Call(wrap__DataFrame__from_arrow_record_batches, rbr) +DataFrame$from_arrow_record_batches = function(rbr) .Call(wrap__DataFrame__from_arrow_record_batches, rbr) -DataFrame$estimated_size <- function() .Call(wrap__DataFrame__estimated_size, self) +DataFrame$estimated_size = function() .Call(wrap__DataFrame__estimated_size, self) -DataFrame$null_count <- function() .Call(wrap__DataFrame__null_count, self) +DataFrame$null_count = function() .Call(wrap__DataFrame__null_count, self) -DataFrame$melt <- function(id_vars, value_vars, value_name, variable_name) .Call(wrap__DataFrame__melt, self, id_vars, value_vars, value_name, variable_name) +DataFrame$melt = function(id_vars, value_vars, value_name, variable_name) .Call(wrap__DataFrame__melt, self, id_vars, value_vars, value_name, variable_name) -DataFrame$pivot_expr <- function(values, index, columns, maintain_order, sort_columns, aggregate_expr, separator) .Call(wrap__DataFrame__pivot_expr, self, values, index, columns, maintain_order, sort_columns, aggregate_expr, separator) +DataFrame$pivot_expr = function(values, index, columns, maintain_order, sort_columns, aggregate_expr, separator) .Call(wrap__DataFrame__pivot_expr, self, values, index, columns, maintain_order, sort_columns, aggregate_expr, separator) #' @export -`$.DataFrame` <- function (self, name) { func <- DataFrame[[name]]; environment(func) <- environment(); func } +`$.DataFrame` = function(self, name) { + func = DataFrame[[name]] + environment(func) = environment() + func +} #' @export -`[[.DataFrame` <- `$.DataFrame` +`[[.DataFrame` = `$.DataFrame` -VecDataFrame <- new.env(parent = emptyenv()) +VecDataFrame = new.env(parent = emptyenv()) -VecDataFrame$with_capacity <- function(n) .Call(wrap__VecDataFrame__with_capacity, n) +VecDataFrame$with_capacity = function(n) .Call(wrap__VecDataFrame__with_capacity, n) -VecDataFrame$push <- function(df) invisible(.Call(wrap__VecDataFrame__push, self, df)) +VecDataFrame$push = function(df) invisible(.Call(wrap__VecDataFrame__push, self, df)) -VecDataFrame$print <- function() invisible(.Call(wrap__VecDataFrame__print, self)) +VecDataFrame$print = function() invisible(.Call(wrap__VecDataFrame__print, self)) #' @export -`$.VecDataFrame` <- function (self, name) { func <- VecDataFrame[[name]]; environment(func) <- environment(); func } +`$.VecDataFrame` = function(self, name) { + func = VecDataFrame[[name]] + environment(func) = environment() + func +} #' @export -`[[.VecDataFrame` <- `$.VecDataFrame` +`[[.VecDataFrame` = `$.VecDataFrame` -RNullValues <- new.env(parent = emptyenv()) +RNullValues = new.env(parent = emptyenv()) -RNullValues$new_all_columns <- function(x) .Call(wrap__RNullValues__new_all_columns, x) +RNullValues$new_all_columns = function(x) .Call(wrap__RNullValues__new_all_columns, x) -RNullValues$new_columns <- function(x) .Call(wrap__RNullValues__new_columns, x) +RNullValues$new_columns = function(x) .Call(wrap__RNullValues__new_columns, x) -RNullValues$new_named <- function(robj) .Call(wrap__RNullValues__new_named, robj) +RNullValues$new_named = function(robj) .Call(wrap__RNullValues__new_named, robj) #' @export -`$.RNullValues` <- function (self, name) { func <- RNullValues[[name]]; environment(func) <- environment(); func } +`$.RNullValues` = function(self, name) { + func = RNullValues[[name]] + environment(func) = environment() + func +} #' @export -`[[.RNullValues` <- `$.RNullValues` +`[[.RNullValues` = `$.RNullValues` -RPolarsDataType <- new.env(parent = emptyenv()) +RPolarsDataType = new.env(parent = emptyenv()) -RPolarsDataType$new <- function(s) .Call(wrap__RPolarsDataType__new, s) +RPolarsDataType$new = function(s) .Call(wrap__RPolarsDataType__new, s) -RPolarsDataType$new_datetime <- function(tu, tz) .Call(wrap__RPolarsDataType__new_datetime, tu, tz) +RPolarsDataType$new_datetime = function(tu, tz) .Call(wrap__RPolarsDataType__new_datetime, tu, tz) -RPolarsDataType$new_duration <- function() .Call(wrap__RPolarsDataType__new_duration) +RPolarsDataType$new_duration = function() .Call(wrap__RPolarsDataType__new_duration) -RPolarsDataType$new_list <- function(inner) .Call(wrap__RPolarsDataType__new_list, inner) +RPolarsDataType$new_list = function(inner) .Call(wrap__RPolarsDataType__new_list, inner) -RPolarsDataType$new_object <- function() .Call(wrap__RPolarsDataType__new_object) +RPolarsDataType$new_object = function() .Call(wrap__RPolarsDataType__new_object) -RPolarsDataType$new_struct <- function(l) .Call(wrap__RPolarsDataType__new_struct, l) +RPolarsDataType$new_struct = function(l) .Call(wrap__RPolarsDataType__new_struct, l) -RPolarsDataType$get_all_simple_type_names <- function() .Call(wrap__RPolarsDataType__get_all_simple_type_names) +RPolarsDataType$get_all_simple_type_names = function() .Call(wrap__RPolarsDataType__get_all_simple_type_names) -RPolarsDataType$print <- function() invisible(.Call(wrap__RPolarsDataType__print, self)) +RPolarsDataType$print = function() invisible(.Call(wrap__RPolarsDataType__print, self)) -RPolarsDataType$eq <- function(other) .Call(wrap__RPolarsDataType__eq, self, other) +RPolarsDataType$eq = function(other) .Call(wrap__RPolarsDataType__eq, self, other) -RPolarsDataType$ne <- function(other) .Call(wrap__RPolarsDataType__ne, self, other) +RPolarsDataType$ne = function(other) .Call(wrap__RPolarsDataType__ne, self, other) -RPolarsDataType$same_outer_datatype <- function(other) .Call(wrap__RPolarsDataType__same_outer_datatype, self, other) +RPolarsDataType$same_outer_datatype = function(other) .Call(wrap__RPolarsDataType__same_outer_datatype, self, other) -RPolarsDataType$get_insides <- function() .Call(wrap__RPolarsDataType__get_insides, self) +RPolarsDataType$get_insides = function() .Call(wrap__RPolarsDataType__get_insides, self) -RPolarsDataType$is_temporal <- function() .Call(wrap__RPolarsDataType__is_temporal, self) +RPolarsDataType$is_temporal = function() .Call(wrap__RPolarsDataType__is_temporal, self) #' @export -`$.RPolarsDataType` <- function (self, name) { func <- RPolarsDataType[[name]]; environment(func) <- environment(); func } +`$.RPolarsDataType` = function(self, name) { + func = RPolarsDataType[[name]] + environment(func) = environment() + func +} #' @export -`[[.RPolarsDataType` <- `$.RPolarsDataType` +`[[.RPolarsDataType` = `$.RPolarsDataType` -DataTypeVector <- new.env(parent = emptyenv()) +DataTypeVector = new.env(parent = emptyenv()) -DataTypeVector$new <- function() .Call(wrap__DataTypeVector__new) +DataTypeVector$new = function() .Call(wrap__DataTypeVector__new) -DataTypeVector$push <- function(colname, datatype) invisible(.Call(wrap__DataTypeVector__push, self, colname, datatype)) +DataTypeVector$push = function(colname, datatype) invisible(.Call(wrap__DataTypeVector__push, self, colname, datatype)) -DataTypeVector$print <- function() invisible(.Call(wrap__DataTypeVector__print, self)) +DataTypeVector$print = function() invisible(.Call(wrap__DataTypeVector__print, self)) -DataTypeVector$from_rlist <- function(list) .Call(wrap__DataTypeVector__from_rlist, list) +DataTypeVector$from_rlist = function(list) .Call(wrap__DataTypeVector__from_rlist, list) #' @export -`$.DataTypeVector` <- function (self, name) { func <- DataTypeVector[[name]]; environment(func) <- environment(); func } +`$.DataTypeVector` = function(self, name) { + func = DataTypeVector[[name]] + environment(func) = environment() + func +} #' @export -`[[.DataTypeVector` <- `$.DataTypeVector` +`[[.DataTypeVector` = `$.DataTypeVector` -RField <- new.env(parent = emptyenv()) +RField = new.env(parent = emptyenv()) -RField$new <- function(name, datatype) .Call(wrap__RField__new, name, datatype) +RField$new = function(name, datatype) .Call(wrap__RField__new, name, datatype) -RField$print <- function() invisible(.Call(wrap__RField__print, self)) +RField$print = function() invisible(.Call(wrap__RField__print, self)) -RField$clone <- function() .Call(wrap__RField__clone, self) +RField$clone = function() .Call(wrap__RField__clone, self) -RField$get_name <- function() .Call(wrap__RField__get_name, self) +RField$get_name = function() .Call(wrap__RField__get_name, self) -RField$get_datatype <- function() .Call(wrap__RField__get_datatype, self) +RField$get_datatype = function() .Call(wrap__RField__get_datatype, self) -RField$set_name_mut <- function(name) invisible(.Call(wrap__RField__set_name_mut, self, name)) +RField$set_name_mut = function(name) invisible(.Call(wrap__RField__set_name_mut, self, name)) -RField$set_datatype_mut <- function(datatype) invisible(.Call(wrap__RField__set_datatype_mut, self, datatype)) +RField$set_datatype_mut = function(datatype) invisible(.Call(wrap__RField__set_datatype_mut, self, datatype)) #' @export -`$.RField` <- function (self, name) { func <- RField[[name]]; environment(func) <- environment(); func } +`$.RField` = function(self, name) { + func = RField[[name]] + environment(func) = environment() + func +} #' @export -`[[.RField` <- `$.RField` +`[[.RField` = `$.RField` -Expr <- new.env(parent = emptyenv()) +Expr = new.env(parent = emptyenv()) -Expr$col <- function(name) .Call(wrap__Expr__col, name) +Expr$col = function(name) .Call(wrap__Expr__col, name) -Expr$dtype_cols <- function(dtypes) .Call(wrap__Expr__dtype_cols, dtypes) +Expr$dtype_cols = function(dtypes) .Call(wrap__Expr__dtype_cols, dtypes) -Expr$cols <- function(names) .Call(wrap__Expr__cols, names) +Expr$cols = function(names) .Call(wrap__Expr__cols, names) -Expr$lit <- function(robj) .Call(wrap__Expr__lit, robj) +Expr$lit = function(robj) .Call(wrap__Expr__lit, robj) -Expr$gt <- function(other) .Call(wrap__Expr__gt, self, other) +Expr$gt = function(other) .Call(wrap__Expr__gt, self, other) -Expr$gt_eq <- function(other) .Call(wrap__Expr__gt_eq, self, other) +Expr$gt_eq = function(other) .Call(wrap__Expr__gt_eq, self, other) -Expr$lt <- function(other) .Call(wrap__Expr__lt, self, other) +Expr$lt = function(other) .Call(wrap__Expr__lt, self, other) -Expr$lt_eq <- function(other) .Call(wrap__Expr__lt_eq, self, other) +Expr$lt_eq = function(other) .Call(wrap__Expr__lt_eq, self, other) -Expr$neq <- function(other) .Call(wrap__Expr__neq, self, other) +Expr$neq = function(other) .Call(wrap__Expr__neq, self, other) -Expr$eq <- function(other) .Call(wrap__Expr__eq, self, other) +Expr$eq = function(other) .Call(wrap__Expr__eq, self, other) -Expr$and <- function(other) .Call(wrap__Expr__and, self, other) +Expr$and = function(other) .Call(wrap__Expr__and, self, other) -Expr$or <- function(other) .Call(wrap__Expr__or, self, other) +Expr$or = function(other) .Call(wrap__Expr__or, self, other) -Expr$xor <- function(other) .Call(wrap__Expr__xor, self, other) +Expr$xor = function(other) .Call(wrap__Expr__xor, self, other) -Expr$is_in <- function(other) .Call(wrap__Expr__is_in, self, other) +Expr$is_in = function(other) .Call(wrap__Expr__is_in, self, other) -Expr$to_physical <- function() .Call(wrap__Expr__to_physical, self) +Expr$to_physical = function() .Call(wrap__Expr__to_physical, self) -Expr$cast <- function(data_type, strict) .Call(wrap__Expr__cast, self, data_type, strict) +Expr$cast = function(data_type, strict) .Call(wrap__Expr__cast, self, data_type, strict) -Expr$sort <- function(descending, nulls_last) .Call(wrap__Expr__sort, self, descending, nulls_last) +Expr$sort = function(descending, nulls_last) .Call(wrap__Expr__sort, self, descending, nulls_last) -Expr$arg_sort <- function(descending, nulls_last) .Call(wrap__Expr__arg_sort, self, descending, nulls_last) +Expr$arg_sort = function(descending, nulls_last) .Call(wrap__Expr__arg_sort, self, descending, nulls_last) -Expr$top_k <- function(k) .Call(wrap__Expr__top_k, self, k) +Expr$top_k = function(k) .Call(wrap__Expr__top_k, self, k) -Expr$bottom_k <- function(k) .Call(wrap__Expr__bottom_k, self, k) +Expr$bottom_k = function(k) .Call(wrap__Expr__bottom_k, self, k) -Expr$arg_max <- function() .Call(wrap__Expr__arg_max, self) +Expr$arg_max = function() .Call(wrap__Expr__arg_max, self) -Expr$arg_min <- function() .Call(wrap__Expr__arg_min, self) +Expr$arg_min = function() .Call(wrap__Expr__arg_min, self) -Expr$search_sorted <- function(element) .Call(wrap__Expr__search_sorted, self, element) +Expr$search_sorted = function(element) .Call(wrap__Expr__search_sorted, self, element) -Expr$take <- function(idx) .Call(wrap__Expr__take, self, idx) +Expr$take = function(idx) .Call(wrap__Expr__take, self, idx) -Expr$sort_by <- function(by, reverse) .Call(wrap__Expr__sort_by, self, by, reverse) +Expr$sort_by = function(by, reverse) .Call(wrap__Expr__sort_by, self, by, reverse) -Expr$backward_fill <- function(limit) .Call(wrap__Expr__backward_fill, self, limit) +Expr$backward_fill = function(limit) .Call(wrap__Expr__backward_fill, self, limit) -Expr$forward_fill <- function(limit) .Call(wrap__Expr__forward_fill, self, limit) +Expr$forward_fill = function(limit) .Call(wrap__Expr__forward_fill, self, limit) -Expr$shift <- function(periods) .Call(wrap__Expr__shift, self, periods) +Expr$shift = function(periods) .Call(wrap__Expr__shift, self, periods) -Expr$shift_and_fill <- function(periods, fill_value) .Call(wrap__Expr__shift_and_fill, self, periods, fill_value) +Expr$shift_and_fill = function(periods, fill_value) .Call(wrap__Expr__shift_and_fill, self, periods, fill_value) -Expr$fill_null <- function(expr) .Call(wrap__Expr__fill_null, self, expr) +Expr$fill_null = function(expr) .Call(wrap__Expr__fill_null, self, expr) -Expr$fill_null_with_strategy <- function(strategy, limit) .Call(wrap__Expr__fill_null_with_strategy, self, strategy, limit) +Expr$fill_null_with_strategy = function(strategy, limit) .Call(wrap__Expr__fill_null_with_strategy, self, strategy, limit) -Expr$fill_nan <- function(expr) .Call(wrap__Expr__fill_nan, self, expr) +Expr$fill_nan = function(expr) .Call(wrap__Expr__fill_nan, self, expr) -Expr$reverse <- function() .Call(wrap__Expr__reverse, self) +Expr$reverse = function() .Call(wrap__Expr__reverse, self) -Expr$std <- function(ddof) .Call(wrap__Expr__std, self, ddof) +Expr$std = function(ddof) .Call(wrap__Expr__std, self, ddof) -Expr$var <- function(ddof) .Call(wrap__Expr__var, self, ddof) +Expr$var = function(ddof) .Call(wrap__Expr__var, self, ddof) -Expr$max <- function() .Call(wrap__Expr__max, self) +Expr$max = function() .Call(wrap__Expr__max, self) -Expr$min <- function() .Call(wrap__Expr__min, self) +Expr$min = function() .Call(wrap__Expr__min, self) -Expr$nan_min <- function() .Call(wrap__Expr__nan_min, self) +Expr$nan_min = function() .Call(wrap__Expr__nan_min, self) -Expr$nan_max <- function() .Call(wrap__Expr__nan_max, self) +Expr$nan_max = function() .Call(wrap__Expr__nan_max, self) -Expr$mean <- function() .Call(wrap__Expr__mean, self) +Expr$mean = function() .Call(wrap__Expr__mean, self) -Expr$median <- function() .Call(wrap__Expr__median, self) +Expr$median = function() .Call(wrap__Expr__median, self) -Expr$sum <- function() .Call(wrap__Expr__sum, self) +Expr$sum = function() .Call(wrap__Expr__sum, self) -Expr$product <- function() .Call(wrap__Expr__product, self) +Expr$product = function() .Call(wrap__Expr__product, self) -Expr$n_unique <- function() .Call(wrap__Expr__n_unique, self) +Expr$n_unique = function() .Call(wrap__Expr__n_unique, self) -Expr$null_count <- function() .Call(wrap__Expr__null_count, self) +Expr$null_count = function() .Call(wrap__Expr__null_count, self) -Expr$arg_unique <- function() .Call(wrap__Expr__arg_unique, self) +Expr$arg_unique = function() .Call(wrap__Expr__arg_unique, self) -Expr$is_duplicated <- function() .Call(wrap__Expr__is_duplicated, self) +Expr$is_duplicated = function() .Call(wrap__Expr__is_duplicated, self) -Expr$quantile <- function(quantile, interpolation) .Call(wrap__Expr__quantile, self, quantile, interpolation) +Expr$quantile = function(quantile, interpolation) .Call(wrap__Expr__quantile, self, quantile, interpolation) -Expr$filter <- function(predicate) .Call(wrap__Expr__filter, self, predicate) +Expr$filter = function(predicate) .Call(wrap__Expr__filter, self, predicate) -Expr$explode <- function() .Call(wrap__Expr__explode, self) +Expr$explode = function() .Call(wrap__Expr__explode, self) -Expr$flatten <- function() .Call(wrap__Expr__flatten, self) +Expr$flatten = function() .Call(wrap__Expr__flatten, self) -Expr$take_every <- function(n) .Call(wrap__Expr__take_every, self, n) +Expr$take_every = function(n) .Call(wrap__Expr__take_every, self, n) -Expr$hash <- function(seed, seed_1, seed_2, seed_3) .Call(wrap__Expr__hash, self, seed, seed_1, seed_2, seed_3) +Expr$hash = function(seed, seed_1, seed_2, seed_3) .Call(wrap__Expr__hash, self, seed, seed_1, seed_2, seed_3) -Expr$reinterpret <- function(signed) .Call(wrap__Expr__reinterpret, self, signed) +Expr$reinterpret = function(signed) .Call(wrap__Expr__reinterpret, self, signed) -Expr$interpolate <- function(method) .Call(wrap__Expr__interpolate, self, method) +Expr$interpolate = function(method) .Call(wrap__Expr__interpolate, self, method) -Expr$rolling_min <- function(window_size, weights_robj, min_periods_float, center, by_null, closed_null) .Call(wrap__Expr__rolling_min, self, window_size, weights_robj, min_periods_float, center, by_null, closed_null) +Expr$rolling_min = function(window_size, weights_robj, min_periods_float, center, by_null, closed_null) .Call(wrap__Expr__rolling_min, self, window_size, weights_robj, min_periods_float, center, by_null, closed_null) -Expr$rolling_max <- function(window_size, weights_robj, min_periods_float, center, by_null, closed_null) .Call(wrap__Expr__rolling_max, self, window_size, weights_robj, min_periods_float, center, by_null, closed_null) +Expr$rolling_max = function(window_size, weights_robj, min_periods_float, center, by_null, closed_null) .Call(wrap__Expr__rolling_max, self, window_size, weights_robj, min_periods_float, center, by_null, closed_null) -Expr$rolling_mean <- function(window_size, weights_robj, min_periods_float, center, by_null, closed_null) .Call(wrap__Expr__rolling_mean, self, window_size, weights_robj, min_periods_float, center, by_null, closed_null) +Expr$rolling_mean = function(window_size, weights_robj, min_periods_float, center, by_null, closed_null) .Call(wrap__Expr__rolling_mean, self, window_size, weights_robj, min_periods_float, center, by_null, closed_null) -Expr$rolling_sum <- function(window_size, weights_robj, min_periods_float, center, by_null, closed_null) .Call(wrap__Expr__rolling_sum, self, window_size, weights_robj, min_periods_float, center, by_null, closed_null) +Expr$rolling_sum = function(window_size, weights_robj, min_periods_float, center, by_null, closed_null) .Call(wrap__Expr__rolling_sum, self, window_size, weights_robj, min_periods_float, center, by_null, closed_null) -Expr$rolling_std <- function(window_size, weights_robj, min_periods_float, center, by_null, closed_null) .Call(wrap__Expr__rolling_std, self, window_size, weights_robj, min_periods_float, center, by_null, closed_null) +Expr$rolling_std = function(window_size, weights_robj, min_periods_float, center, by_null, closed_null) .Call(wrap__Expr__rolling_std, self, window_size, weights_robj, min_periods_float, center, by_null, closed_null) -Expr$rolling_var <- function(window_size, weights_robj, min_periods_float, center, by_null, closed_null) .Call(wrap__Expr__rolling_var, self, window_size, weights_robj, min_periods_float, center, by_null, closed_null) +Expr$rolling_var = function(window_size, weights_robj, min_periods_float, center, by_null, closed_null) .Call(wrap__Expr__rolling_var, self, window_size, weights_robj, min_periods_float, center, by_null, closed_null) -Expr$rolling_median <- function(window_size, weights_robj, min_periods_float, center, by_null, closed_null) .Call(wrap__Expr__rolling_median, self, window_size, weights_robj, min_periods_float, center, by_null, closed_null) +Expr$rolling_median = function(window_size, weights_robj, min_periods_float, center, by_null, closed_null) .Call(wrap__Expr__rolling_median, self, window_size, weights_robj, min_periods_float, center, by_null, closed_null) -Expr$rolling_quantile <- function(quantile, interpolation, window_size, weights_robj, min_periods_float, center, by_null, closed_null) .Call(wrap__Expr__rolling_quantile, self, quantile, interpolation, window_size, weights_robj, min_periods_float, center, by_null, closed_null) +Expr$rolling_quantile = function(quantile, interpolation, window_size, weights_robj, min_periods_float, center, by_null, closed_null) .Call(wrap__Expr__rolling_quantile, self, quantile, interpolation, window_size, weights_robj, min_periods_float, center, by_null, closed_null) -Expr$rolling_skew <- function(window_size_f, bias) .Call(wrap__Expr__rolling_skew, self, window_size_f, bias) +Expr$rolling_skew = function(window_size_f, bias) .Call(wrap__Expr__rolling_skew, self, window_size_f, bias) -Expr$abs <- function() .Call(wrap__Expr__abs, self) +Expr$abs = function() .Call(wrap__Expr__abs, self) -Expr$rank <- function(method, reverse) .Call(wrap__Expr__rank, self, method, reverse) +Expr$rank = function(method, reverse) .Call(wrap__Expr__rank, self, method, reverse) -Expr$diff <- function(n_float, null_behavior) .Call(wrap__Expr__diff, self, n_float, null_behavior) +Expr$diff = function(n_float, null_behavior) .Call(wrap__Expr__diff, self, n_float, null_behavior) -Expr$pct_change <- function(n_float) .Call(wrap__Expr__pct_change, self, n_float) +Expr$pct_change = function(n_float) .Call(wrap__Expr__pct_change, self, n_float) -Expr$skew <- function(bias) .Call(wrap__Expr__skew, self, bias) +Expr$skew = function(bias) .Call(wrap__Expr__skew, self, bias) -Expr$kurtosis <- function(fisher, bias) .Call(wrap__Expr__kurtosis, self, fisher, bias) +Expr$kurtosis = function(fisher, bias) .Call(wrap__Expr__kurtosis, self, fisher, bias) -Expr$clip <- function(min, max) .Call(wrap__Expr__clip, self, min, max) +Expr$clip = function(min, max) .Call(wrap__Expr__clip, self, min, max) -Expr$clip_min <- function(min) .Call(wrap__Expr__clip_min, self, min) +Expr$clip_min = function(min) .Call(wrap__Expr__clip_min, self, min) -Expr$clip_max <- function(max) .Call(wrap__Expr__clip_max, self, max) +Expr$clip_max = function(max) .Call(wrap__Expr__clip_max, self, max) -Expr$lower_bound <- function() .Call(wrap__Expr__lower_bound, self) +Expr$lower_bound = function() .Call(wrap__Expr__lower_bound, self) -Expr$upper_bound <- function() .Call(wrap__Expr__upper_bound, self) +Expr$upper_bound = function() .Call(wrap__Expr__upper_bound, self) -Expr$sign <- function() .Call(wrap__Expr__sign, self) +Expr$sign = function() .Call(wrap__Expr__sign, self) -Expr$sin <- function() .Call(wrap__Expr__sin, self) +Expr$sin = function() .Call(wrap__Expr__sin, self) -Expr$cos <- function() .Call(wrap__Expr__cos, self) +Expr$cos = function() .Call(wrap__Expr__cos, self) -Expr$tan <- function() .Call(wrap__Expr__tan, self) +Expr$tan = function() .Call(wrap__Expr__tan, self) -Expr$arcsin <- function() .Call(wrap__Expr__arcsin, self) +Expr$arcsin = function() .Call(wrap__Expr__arcsin, self) -Expr$arccos <- function() .Call(wrap__Expr__arccos, self) +Expr$arccos = function() .Call(wrap__Expr__arccos, self) -Expr$arctan <- function() .Call(wrap__Expr__arctan, self) +Expr$arctan = function() .Call(wrap__Expr__arctan, self) -Expr$sinh <- function() .Call(wrap__Expr__sinh, self) +Expr$sinh = function() .Call(wrap__Expr__sinh, self) -Expr$cosh <- function() .Call(wrap__Expr__cosh, self) +Expr$cosh = function() .Call(wrap__Expr__cosh, self) -Expr$tanh <- function() .Call(wrap__Expr__tanh, self) +Expr$tanh = function() .Call(wrap__Expr__tanh, self) -Expr$arcsinh <- function() .Call(wrap__Expr__arcsinh, self) +Expr$arcsinh = function() .Call(wrap__Expr__arcsinh, self) -Expr$arccosh <- function() .Call(wrap__Expr__arccosh, self) +Expr$arccosh = function() .Call(wrap__Expr__arccosh, self) -Expr$arctanh <- function() .Call(wrap__Expr__arctanh, self) +Expr$arctanh = function() .Call(wrap__Expr__arctanh, self) -Expr$reshape <- function(dims) .Call(wrap__Expr__reshape, self, dims) +Expr$reshape = function(dims) .Call(wrap__Expr__reshape, self, dims) -Expr$shuffle <- function(seed) .Call(wrap__Expr__shuffle, self, seed) +Expr$shuffle = function(seed) .Call(wrap__Expr__shuffle, self, seed) -Expr$sample_n <- function(n, with_replacement, shuffle, seed) .Call(wrap__Expr__sample_n, self, n, with_replacement, shuffle, seed) +Expr$sample_n = function(n, with_replacement, shuffle, seed) .Call(wrap__Expr__sample_n, self, n, with_replacement, shuffle, seed) -Expr$sample_frac <- function(frac, with_replacement, shuffle, seed) .Call(wrap__Expr__sample_frac, self, frac, with_replacement, shuffle, seed) +Expr$sample_frac = function(frac, with_replacement, shuffle, seed) .Call(wrap__Expr__sample_frac, self, frac, with_replacement, shuffle, seed) -Expr$ewm_mean <- function(alpha, adjust, min_periods, ignore_nulls) .Call(wrap__Expr__ewm_mean, self, alpha, adjust, min_periods, ignore_nulls) +Expr$ewm_mean = function(alpha, adjust, min_periods, ignore_nulls) .Call(wrap__Expr__ewm_mean, self, alpha, adjust, min_periods, ignore_nulls) -Expr$ewm_std <- function(alpha, adjust, bias, min_periods, ignore_nulls) .Call(wrap__Expr__ewm_std, self, alpha, adjust, bias, min_periods, ignore_nulls) +Expr$ewm_std = function(alpha, adjust, bias, min_periods, ignore_nulls) .Call(wrap__Expr__ewm_std, self, alpha, adjust, bias, min_periods, ignore_nulls) -Expr$ewm_var <- function(alpha, adjust, bias, min_periods, ignore_nulls) .Call(wrap__Expr__ewm_var, self, alpha, adjust, bias, min_periods, ignore_nulls) +Expr$ewm_var = function(alpha, adjust, bias, min_periods, ignore_nulls) .Call(wrap__Expr__ewm_var, self, alpha, adjust, bias, min_periods, ignore_nulls) -Expr$extend_constant <- function(value, n) .Call(wrap__Expr__extend_constant, self, value, n) +Expr$extend_constant = function(value, n) .Call(wrap__Expr__extend_constant, self, value, n) -Expr$rep <- function(n, rechunk) .Call(wrap__Expr__rep, self, n, rechunk) +Expr$rep = function(n, rechunk) .Call(wrap__Expr__rep, self, n, rechunk) -Expr$value_counts <- function(multithreaded, sorted) .Call(wrap__Expr__value_counts, self, multithreaded, sorted) +Expr$value_counts = function(multithreaded, sorted) .Call(wrap__Expr__value_counts, self, multithreaded, sorted) -Expr$unique_counts <- function() .Call(wrap__Expr__unique_counts, self) +Expr$unique_counts = function() .Call(wrap__Expr__unique_counts, self) -Expr$entropy <- function(base, normalize) .Call(wrap__Expr__entropy, self, base, normalize) +Expr$entropy = function(base, normalize) .Call(wrap__Expr__entropy, self, base, normalize) -Expr$cumulative_eval <- function(expr, min_periods, parallel) .Call(wrap__Expr__cumulative_eval, self, expr, min_periods, parallel) +Expr$cumulative_eval = function(expr, min_periods, parallel) .Call(wrap__Expr__cumulative_eval, self, expr, min_periods, parallel) -Expr$implode <- function() .Call(wrap__Expr__implode, self) +Expr$implode = function() .Call(wrap__Expr__implode, self) -Expr$shrink_dtype <- function() .Call(wrap__Expr__shrink_dtype, self) +Expr$shrink_dtype = function() .Call(wrap__Expr__shrink_dtype, self) -Expr$arr_lengths <- function() .Call(wrap__Expr__arr_lengths, self) +Expr$arr_lengths = function() .Call(wrap__Expr__arr_lengths, self) -Expr$arr_contains <- function(other) .Call(wrap__Expr__arr_contains, self, other) +Expr$arr_contains = function(other) .Call(wrap__Expr__arr_contains, self, other) -Expr$lst_max <- function() .Call(wrap__Expr__lst_max, self) +Expr$lst_max = function() .Call(wrap__Expr__lst_max, self) -Expr$lst_min <- function() .Call(wrap__Expr__lst_min, self) +Expr$lst_min = function() .Call(wrap__Expr__lst_min, self) -Expr$lst_sum <- function() .Call(wrap__Expr__lst_sum, self) +Expr$lst_sum = function() .Call(wrap__Expr__lst_sum, self) -Expr$lst_mean <- function() .Call(wrap__Expr__lst_mean, self) +Expr$lst_mean = function() .Call(wrap__Expr__lst_mean, self) -Expr$lst_sort <- function(reverse) .Call(wrap__Expr__lst_sort, self, reverse) +Expr$lst_sort = function(reverse) .Call(wrap__Expr__lst_sort, self, reverse) -Expr$lst_reverse <- function() .Call(wrap__Expr__lst_reverse, self) +Expr$lst_reverse = function() .Call(wrap__Expr__lst_reverse, self) -Expr$lst_unique <- function() .Call(wrap__Expr__lst_unique, self) +Expr$lst_unique = function() .Call(wrap__Expr__lst_unique, self) -Expr$lst_take <- function(index, null_on_oob) .Call(wrap__Expr__lst_take, self, index, null_on_oob) +Expr$lst_take = function(index, null_on_oob) .Call(wrap__Expr__lst_take, self, index, null_on_oob) -Expr$lst_get <- function(index) .Call(wrap__Expr__lst_get, self, index) +Expr$lst_get = function(index) .Call(wrap__Expr__lst_get, self, index) -Expr$lst_join <- function(separator) .Call(wrap__Expr__lst_join, self, separator) +Expr$lst_join = function(separator) .Call(wrap__Expr__lst_join, self, separator) -Expr$lst_arg_min <- function() .Call(wrap__Expr__lst_arg_min, self) +Expr$lst_arg_min = function() .Call(wrap__Expr__lst_arg_min, self) -Expr$lst_arg_max <- function() .Call(wrap__Expr__lst_arg_max, self) +Expr$lst_arg_max = function() .Call(wrap__Expr__lst_arg_max, self) -Expr$lst_diff <- function(n, null_behavior) .Call(wrap__Expr__lst_diff, self, n, null_behavior) +Expr$lst_diff = function(n, null_behavior) .Call(wrap__Expr__lst_diff, self, n, null_behavior) -Expr$lst_shift <- function(periods) .Call(wrap__Expr__lst_shift, self, periods) +Expr$lst_shift = function(periods) .Call(wrap__Expr__lst_shift, self, periods) -Expr$lst_slice <- function(offset, length) .Call(wrap__Expr__lst_slice, self, offset, length) +Expr$lst_slice = function(offset, length) .Call(wrap__Expr__lst_slice, self, offset, length) -Expr$lst_eval <- function(expr, parallel) .Call(wrap__Expr__lst_eval, self, expr, parallel) +Expr$lst_eval = function(expr, parallel) .Call(wrap__Expr__lst_eval, self, expr, parallel) -Expr$lst_to_struct <- function(width_strat, name_gen, upper_bound) .Call(wrap__Expr__lst_to_struct, self, width_strat, name_gen, upper_bound) +Expr$lst_to_struct = function(width_strat, name_gen, upper_bound) .Call(wrap__Expr__lst_to_struct, self, width_strat, name_gen, upper_bound) -Expr$str_parse_date <- function(format, strict, exact, cache) .Call(wrap__Expr__str_parse_date, self, format, strict, exact, cache) +Expr$str_parse_date = function(format, strict, exact, cache) .Call(wrap__Expr__str_parse_date, self, format, strict, exact, cache) -Expr$str_parse_datetime <- function(format, strict, exact, cache, tz_aware, utc, tu) .Call(wrap__Expr__str_parse_datetime, self, format, strict, exact, cache, tz_aware, utc, tu) +Expr$str_parse_datetime = function(format, strict, exact, cache, tz_aware, utc, tu) .Call(wrap__Expr__str_parse_datetime, self, format, strict, exact, cache, tz_aware, utc, tu) -Expr$str_parse_time <- function(format, strict, exact, cache) .Call(wrap__Expr__str_parse_time, self, format, strict, exact, cache) +Expr$str_parse_time = function(format, strict, exact, cache) .Call(wrap__Expr__str_parse_time, self, format, strict, exact, cache) -Expr$dt_truncate <- function(every, offset) .Call(wrap__Expr__dt_truncate, self, every, offset) +Expr$dt_truncate = function(every, offset) .Call(wrap__Expr__dt_truncate, self, every, offset) -Expr$dt_round <- function(every, offset) .Call(wrap__Expr__dt_round, self, every, offset) +Expr$dt_round = function(every, offset) .Call(wrap__Expr__dt_round, self, every, offset) -Expr$dt_combine <- function(time, tu) .Call(wrap__Expr__dt_combine, self, time, tu) +Expr$dt_combine = function(time, tu) .Call(wrap__Expr__dt_combine, self, time, tu) -Expr$dt_strftime <- function(fmt) .Call(wrap__Expr__dt_strftime, self, fmt) +Expr$dt_strftime = function(fmt) .Call(wrap__Expr__dt_strftime, self, fmt) -Expr$dt_year <- function() .Call(wrap__Expr__dt_year, self) +Expr$dt_year = function() .Call(wrap__Expr__dt_year, self) -Expr$dt_iso_year <- function() .Call(wrap__Expr__dt_iso_year, self) +Expr$dt_iso_year = function() .Call(wrap__Expr__dt_iso_year, self) -Expr$dt_quarter <- function() .Call(wrap__Expr__dt_quarter, self) +Expr$dt_quarter = function() .Call(wrap__Expr__dt_quarter, self) -Expr$dt_month <- function() .Call(wrap__Expr__dt_month, self) +Expr$dt_month = function() .Call(wrap__Expr__dt_month, self) -Expr$dt_week <- function() .Call(wrap__Expr__dt_week, self) +Expr$dt_week = function() .Call(wrap__Expr__dt_week, self) -Expr$dt_weekday <- function() .Call(wrap__Expr__dt_weekday, self) +Expr$dt_weekday = function() .Call(wrap__Expr__dt_weekday, self) -Expr$dt_day <- function() .Call(wrap__Expr__dt_day, self) +Expr$dt_day = function() .Call(wrap__Expr__dt_day, self) -Expr$dt_ordinal_day <- function() .Call(wrap__Expr__dt_ordinal_day, self) +Expr$dt_ordinal_day = function() .Call(wrap__Expr__dt_ordinal_day, self) -Expr$dt_hour <- function() .Call(wrap__Expr__dt_hour, self) +Expr$dt_hour = function() .Call(wrap__Expr__dt_hour, self) -Expr$dt_minute <- function() .Call(wrap__Expr__dt_minute, self) +Expr$dt_minute = function() .Call(wrap__Expr__dt_minute, self) -Expr$dt_second <- function() .Call(wrap__Expr__dt_second, self) +Expr$dt_second = function() .Call(wrap__Expr__dt_second, self) -Expr$dt_millisecond <- function() .Call(wrap__Expr__dt_millisecond, self) +Expr$dt_millisecond = function() .Call(wrap__Expr__dt_millisecond, self) -Expr$dt_microsecond <- function() .Call(wrap__Expr__dt_microsecond, self) +Expr$dt_microsecond = function() .Call(wrap__Expr__dt_microsecond, self) -Expr$dt_nanosecond <- function() .Call(wrap__Expr__dt_nanosecond, self) +Expr$dt_nanosecond = function() .Call(wrap__Expr__dt_nanosecond, self) -Expr$timestamp <- function(tu) .Call(wrap__Expr__timestamp, self, tu) +Expr$timestamp = function(tu) .Call(wrap__Expr__timestamp, self, tu) -Expr$dt_epoch_seconds <- function() .Call(wrap__Expr__dt_epoch_seconds, self) +Expr$dt_epoch_seconds = function() .Call(wrap__Expr__dt_epoch_seconds, self) -Expr$dt_with_time_unit <- function(tu) .Call(wrap__Expr__dt_with_time_unit, self, tu) +Expr$dt_with_time_unit = function(tu) .Call(wrap__Expr__dt_with_time_unit, self, tu) -Expr$dt_cast_time_unit <- function(tu) .Call(wrap__Expr__dt_cast_time_unit, self, tu) +Expr$dt_cast_time_unit = function(tu) .Call(wrap__Expr__dt_cast_time_unit, self, tu) -Expr$dt_convert_time_zone <- function(tz) .Call(wrap__Expr__dt_convert_time_zone, self, tz) +Expr$dt_convert_time_zone = function(tz) .Call(wrap__Expr__dt_convert_time_zone, self, tz) -Expr$dt_replace_time_zone <- function(tz, use_earliest) .Call(wrap__Expr__dt_replace_time_zone, self, tz, use_earliest) +Expr$dt_replace_time_zone = function(tz, use_earliest) .Call(wrap__Expr__dt_replace_time_zone, self, tz, use_earliest) -Expr$dt_tz_localize <- function(tz) .Call(wrap__Expr__dt_tz_localize, self, tz) +Expr$dt_tz_localize = function(tz) .Call(wrap__Expr__dt_tz_localize, self, tz) -Expr$duration_days <- function() .Call(wrap__Expr__duration_days, self) +Expr$duration_days = function() .Call(wrap__Expr__duration_days, self) -Expr$duration_hours <- function() .Call(wrap__Expr__duration_hours, self) +Expr$duration_hours = function() .Call(wrap__Expr__duration_hours, self) -Expr$duration_minutes <- function() .Call(wrap__Expr__duration_minutes, self) +Expr$duration_minutes = function() .Call(wrap__Expr__duration_minutes, self) -Expr$duration_seconds <- function() .Call(wrap__Expr__duration_seconds, self) +Expr$duration_seconds = function() .Call(wrap__Expr__duration_seconds, self) -Expr$duration_nanoseconds <- function() .Call(wrap__Expr__duration_nanoseconds, self) +Expr$duration_nanoseconds = function() .Call(wrap__Expr__duration_nanoseconds, self) -Expr$duration_microseconds <- function() .Call(wrap__Expr__duration_microseconds, self) +Expr$duration_microseconds = function() .Call(wrap__Expr__duration_microseconds, self) -Expr$duration_milliseconds <- function() .Call(wrap__Expr__duration_milliseconds, self) +Expr$duration_milliseconds = function() .Call(wrap__Expr__duration_milliseconds, self) -Expr$dt_offset_by <- function(by) .Call(wrap__Expr__dt_offset_by, self, by) +Expr$dt_offset_by = function(by) .Call(wrap__Expr__dt_offset_by, self, by) -Expr$pow <- function(exponent) .Call(wrap__Expr__pow, self, exponent) +Expr$pow = function(exponent) .Call(wrap__Expr__pow, self, exponent) -Expr$repeat_by <- function(by) .Call(wrap__Expr__repeat_by, self, by) +Expr$repeat_by = function(by) .Call(wrap__Expr__repeat_by, self, by) -Expr$log10 <- function() .Call(wrap__Expr__log10, self) +Expr$log10 = function() .Call(wrap__Expr__log10, self) -Expr$log <- function(base) .Call(wrap__Expr__log, self, base) +Expr$log = function(base) .Call(wrap__Expr__log, self, base) -Expr$exp <- function() .Call(wrap__Expr__exp, self) +Expr$exp = function() .Call(wrap__Expr__exp, self) -Expr$exclude <- function(columns) .Call(wrap__Expr__exclude, self, columns) +Expr$exclude = function(columns) .Call(wrap__Expr__exclude, self, columns) -Expr$exclude_dtype <- function(columns) .Call(wrap__Expr__exclude_dtype, self, columns) +Expr$exclude_dtype = function(columns) .Call(wrap__Expr__exclude_dtype, self, columns) -Expr$keep_name <- function() .Call(wrap__Expr__keep_name, self) +Expr$keep_name = function() .Call(wrap__Expr__keep_name, self) -Expr$alias <- function(s) .Call(wrap__Expr__alias, self, s) +Expr$alias = function(s) .Call(wrap__Expr__alias, self, s) -Expr$is_null <- function() .Call(wrap__Expr__is_null, self) +Expr$is_null = function() .Call(wrap__Expr__is_null, self) -Expr$is_not_null <- function() .Call(wrap__Expr__is_not_null, self) +Expr$is_not_null = function() .Call(wrap__Expr__is_not_null, self) -Expr$is_finite <- function() .Call(wrap__Expr__is_finite, self) +Expr$is_finite = function() .Call(wrap__Expr__is_finite, self) -Expr$is_infinite <- function() .Call(wrap__Expr__is_infinite, self) +Expr$is_infinite = function() .Call(wrap__Expr__is_infinite, self) -Expr$is_nan <- function() .Call(wrap__Expr__is_nan, self) +Expr$is_nan = function() .Call(wrap__Expr__is_nan, self) -Expr$is_not_nan <- function() .Call(wrap__Expr__is_not_nan, self) +Expr$is_not_nan = function() .Call(wrap__Expr__is_not_nan, self) -Expr$drop_nulls <- function() .Call(wrap__Expr__drop_nulls, self) +Expr$drop_nulls = function() .Call(wrap__Expr__drop_nulls, self) -Expr$drop_nans <- function() .Call(wrap__Expr__drop_nans, self) +Expr$drop_nans = function() .Call(wrap__Expr__drop_nans, self) -Expr$cumsum <- function(reverse) .Call(wrap__Expr__cumsum, self, reverse) +Expr$cumsum = function(reverse) .Call(wrap__Expr__cumsum, self, reverse) -Expr$cumprod <- function(reverse) .Call(wrap__Expr__cumprod, self, reverse) +Expr$cumprod = function(reverse) .Call(wrap__Expr__cumprod, self, reverse) -Expr$cummin <- function(reverse) .Call(wrap__Expr__cummin, self, reverse) +Expr$cummin = function(reverse) .Call(wrap__Expr__cummin, self, reverse) -Expr$cummax <- function(reverse) .Call(wrap__Expr__cummax, self, reverse) +Expr$cummax = function(reverse) .Call(wrap__Expr__cummax, self, reverse) -Expr$cumcount <- function(reverse) .Call(wrap__Expr__cumcount, self, reverse) +Expr$cumcount = function(reverse) .Call(wrap__Expr__cumcount, self, reverse) -Expr$floor <- function() .Call(wrap__Expr__floor, self) +Expr$floor = function() .Call(wrap__Expr__floor, self) -Expr$ceil <- function() .Call(wrap__Expr__ceil, self) +Expr$ceil = function() .Call(wrap__Expr__ceil, self) -Expr$round <- function(decimals) .Call(wrap__Expr__round, self, decimals) +Expr$round = function(decimals) .Call(wrap__Expr__round, self, decimals) -Expr$dot <- function(other) .Call(wrap__Expr__dot, self, other) +Expr$dot = function(other) .Call(wrap__Expr__dot, self, other) -Expr$mode <- function() .Call(wrap__Expr__mode, self) +Expr$mode = function() .Call(wrap__Expr__mode, self) -Expr$first <- function() .Call(wrap__Expr__first, self) +Expr$first = function() .Call(wrap__Expr__first, self) -Expr$last <- function() .Call(wrap__Expr__last, self) +Expr$last = function() .Call(wrap__Expr__last, self) -Expr$head <- function(n) .Call(wrap__Expr__head, self, n) +Expr$head = function(n) .Call(wrap__Expr__head, self, n) -Expr$tail <- function(n) .Call(wrap__Expr__tail, self, n) +Expr$tail = function(n) .Call(wrap__Expr__tail, self, n) -Expr$unique <- function() .Call(wrap__Expr__unique, self) +Expr$unique = function() .Call(wrap__Expr__unique, self) -Expr$unique_stable <- function() .Call(wrap__Expr__unique_stable, self) +Expr$unique_stable = function() .Call(wrap__Expr__unique_stable, self) -Expr$agg_groups <- function() .Call(wrap__Expr__agg_groups, self) +Expr$agg_groups = function() .Call(wrap__Expr__agg_groups, self) -Expr$all <- function() .Call(wrap__Expr__all, self) +Expr$all = function() .Call(wrap__Expr__all, self) -Expr$any <- function() .Call(wrap__Expr__any, self) +Expr$any = function() .Call(wrap__Expr__any, self) -Expr$count <- function() .Call(wrap__Expr__count, self) +Expr$count = function() .Call(wrap__Expr__count, self) -Expr$len <- function() .Call(wrap__Expr__len, self) +Expr$len = function() .Call(wrap__Expr__len, self) -Expr$slice <- function(offset, length) .Call(wrap__Expr__slice, self, offset, length) +Expr$slice = function(offset, length) .Call(wrap__Expr__slice, self, offset, length) -Expr$append <- function(other, upcast) .Call(wrap__Expr__append, self, other, upcast) +Expr$append = function(other, upcast) .Call(wrap__Expr__append, self, other, upcast) -Expr$rechunk <- function() .Call(wrap__Expr__rechunk, self) +Expr$rechunk = function() .Call(wrap__Expr__rechunk, self) -Expr$add <- function(other) .Call(wrap__Expr__add, self, other) +Expr$add = function(other) .Call(wrap__Expr__add, self, other) -Expr$sub <- function(other) .Call(wrap__Expr__sub, self, other) +Expr$sub = function(other) .Call(wrap__Expr__sub, self, other) -Expr$mul <- function(other) .Call(wrap__Expr__mul, self, other) +Expr$mul = function(other) .Call(wrap__Expr__mul, self, other) -Expr$div <- function(other) .Call(wrap__Expr__div, self, other) +Expr$div = function(other) .Call(wrap__Expr__div, self, other) -Expr$is_not <- function() .Call(wrap__Expr__is_not, self) +Expr$is_not = function() .Call(wrap__Expr__is_not, self) -Expr$over <- function(proto_exprs) .Call(wrap__Expr__over, self, proto_exprs) +Expr$over = function(proto_exprs) .Call(wrap__Expr__over, self, proto_exprs) -Expr$print <- function() invisible(.Call(wrap__Expr__print, self)) +Expr$print = function() invisible(.Call(wrap__Expr__print, self)) -Expr$map <- function(lambda, output_type, agg_list) .Call(wrap__Expr__map, self, lambda, output_type, agg_list) +Expr$map = function(lambda, output_type, agg_list) .Call(wrap__Expr__map, self, lambda, output_type, agg_list) -Expr$is_unique <- function() .Call(wrap__Expr__is_unique, self) +Expr$is_unique = function() .Call(wrap__Expr__is_unique, self) -Expr$approx_unique <- function() .Call(wrap__Expr__approx_unique, self) +Expr$approx_unique = function() .Call(wrap__Expr__approx_unique, self) -Expr$is_first <- function() .Call(wrap__Expr__is_first, self) +Expr$is_first = function() .Call(wrap__Expr__is_first, self) -Expr$map_alias <- function(lambda) .Call(wrap__Expr__map_alias, self, lambda) +Expr$map_alias = function(lambda) .Call(wrap__Expr__map_alias, self, lambda) -Expr$suffix <- function(suffix) .Call(wrap__Expr__suffix, self, suffix) +Expr$suffix = function(suffix) .Call(wrap__Expr__suffix, self, suffix) -Expr$prefix <- function(prefix) .Call(wrap__Expr__prefix, self, prefix) +Expr$prefix = function(prefix) .Call(wrap__Expr__prefix, self, prefix) -Expr$str_lengths <- function() .Call(wrap__Expr__str_lengths, self) +Expr$str_lengths = function() .Call(wrap__Expr__str_lengths, self) -Expr$str_n_chars <- function() .Call(wrap__Expr__str_n_chars, self) +Expr$str_n_chars = function() .Call(wrap__Expr__str_n_chars, self) -Expr$str_concat <- function(delimiter) .Call(wrap__Expr__str_concat, self, delimiter) +Expr$str_concat = function(delimiter) .Call(wrap__Expr__str_concat, self, delimiter) -Expr$str_to_uppercase <- function() .Call(wrap__Expr__str_to_uppercase, self) +Expr$str_to_uppercase = function() .Call(wrap__Expr__str_to_uppercase, self) -Expr$str_to_lowercase <- function() .Call(wrap__Expr__str_to_lowercase, self) +Expr$str_to_lowercase = function() .Call(wrap__Expr__str_to_lowercase, self) -Expr$str_strip <- function(matches) .Call(wrap__Expr__str_strip, self, matches) +Expr$str_strip = function(matches) .Call(wrap__Expr__str_strip, self, matches) -Expr$str_rstrip <- function(matches) .Call(wrap__Expr__str_rstrip, self, matches) +Expr$str_rstrip = function(matches) .Call(wrap__Expr__str_rstrip, self, matches) -Expr$str_lstrip <- function(matches) .Call(wrap__Expr__str_lstrip, self, matches) +Expr$str_lstrip = function(matches) .Call(wrap__Expr__str_lstrip, self, matches) -Expr$str_zfill <- function(alignment) .Call(wrap__Expr__str_zfill, self, alignment) +Expr$str_zfill = function(alignment) .Call(wrap__Expr__str_zfill, self, alignment) -Expr$str_ljust <- function(width, fillchar) .Call(wrap__Expr__str_ljust, self, width, fillchar) +Expr$str_ljust = function(width, fillchar) .Call(wrap__Expr__str_ljust, self, width, fillchar) -Expr$str_rjust <- function(width, fillchar) .Call(wrap__Expr__str_rjust, self, width, fillchar) +Expr$str_rjust = function(width, fillchar) .Call(wrap__Expr__str_rjust, self, width, fillchar) -Expr$str_contains <- function(pat, literal, strict) .Call(wrap__Expr__str_contains, self, pat, literal, strict) +Expr$str_contains = function(pat, literal, strict) .Call(wrap__Expr__str_contains, self, pat, literal, strict) -Expr$str_ends_with <- function(sub) .Call(wrap__Expr__str_ends_with, self, sub) +Expr$str_ends_with = function(sub) .Call(wrap__Expr__str_ends_with, self, sub) -Expr$str_starts_with <- function(sub) .Call(wrap__Expr__str_starts_with, self, sub) +Expr$str_starts_with = function(sub) .Call(wrap__Expr__str_starts_with, self, sub) -Expr$str_json_path_match <- function(pat) .Call(wrap__Expr__str_json_path_match, self, pat) +Expr$str_json_path_match = function(pat) .Call(wrap__Expr__str_json_path_match, self, pat) -Expr$str_json_extract <- function(dtype) .Call(wrap__Expr__str_json_extract, self, dtype) +Expr$str_json_extract = function(dtype) .Call(wrap__Expr__str_json_extract, self, dtype) -Expr$str_hex_encode <- function() .Call(wrap__Expr__str_hex_encode, self) +Expr$str_hex_encode = function() .Call(wrap__Expr__str_hex_encode, self) -Expr$str_hex_decode <- function(strict) .Call(wrap__Expr__str_hex_decode, self, strict) +Expr$str_hex_decode = function(strict) .Call(wrap__Expr__str_hex_decode, self, strict) -Expr$str_base64_encode <- function() .Call(wrap__Expr__str_base64_encode, self) +Expr$str_base64_encode = function() .Call(wrap__Expr__str_base64_encode, self) -Expr$str_base64_decode <- function(strict) .Call(wrap__Expr__str_base64_decode, self, strict) +Expr$str_base64_decode = function(strict) .Call(wrap__Expr__str_base64_decode, self, strict) -Expr$str_extract <- function(pattern, group_index) .Call(wrap__Expr__str_extract, self, pattern, group_index) +Expr$str_extract = function(pattern, group_index) .Call(wrap__Expr__str_extract, self, pattern, group_index) -Expr$str_extract_all <- function(pattern) .Call(wrap__Expr__str_extract_all, self, pattern) +Expr$str_extract_all = function(pattern) .Call(wrap__Expr__str_extract_all, self, pattern) -Expr$str_count_match <- function(pattern) .Call(wrap__Expr__str_count_match, self, pattern) +Expr$str_count_match = function(pattern) .Call(wrap__Expr__str_count_match, self, pattern) -Expr$str_split <- function(by, inclusive) .Call(wrap__Expr__str_split, self, by, inclusive) +Expr$str_split = function(by, inclusive) .Call(wrap__Expr__str_split, self, by, inclusive) -Expr$str_split_exact <- function(by, n, inclusive) .Call(wrap__Expr__str_split_exact, self, by, n, inclusive) +Expr$str_split_exact = function(by, n, inclusive) .Call(wrap__Expr__str_split_exact, self, by, n, inclusive) -Expr$str_splitn <- function(by, n) .Call(wrap__Expr__str_splitn, self, by, n) +Expr$str_splitn = function(by, n) .Call(wrap__Expr__str_splitn, self, by, n) -Expr$str_replace <- function(pattern, value, literal) .Call(wrap__Expr__str_replace, self, pattern, value, literal) +Expr$str_replace = function(pattern, value, literal) .Call(wrap__Expr__str_replace, self, pattern, value, literal) -Expr$str_replace_all <- function(pattern, value, literal) .Call(wrap__Expr__str_replace_all, self, pattern, value, literal) +Expr$str_replace_all = function(pattern, value, literal) .Call(wrap__Expr__str_replace_all, self, pattern, value, literal) -Expr$str_slice <- function(offset, length) .Call(wrap__Expr__str_slice, self, offset, length) +Expr$str_slice = function(offset, length) .Call(wrap__Expr__str_slice, self, offset, length) -Expr$str_parse_int <- function(radix, strict) .Call(wrap__Expr__str_parse_int, self, radix, strict) +Expr$str_parse_int = function(radix, strict) .Call(wrap__Expr__str_parse_int, self, radix, strict) -Expr$bin_contains <- function(lit) .Call(wrap__Expr__bin_contains, self, lit) +Expr$bin_contains = function(lit) .Call(wrap__Expr__bin_contains, self, lit) -Expr$bin_starts_with <- function(sub) .Call(wrap__Expr__bin_starts_with, self, sub) +Expr$bin_starts_with = function(sub) .Call(wrap__Expr__bin_starts_with, self, sub) -Expr$bin_ends_with <- function(sub) .Call(wrap__Expr__bin_ends_with, self, sub) +Expr$bin_ends_with = function(sub) .Call(wrap__Expr__bin_ends_with, self, sub) -Expr$bin_encode_hex <- function() .Call(wrap__Expr__bin_encode_hex, self) +Expr$bin_encode_hex = function() .Call(wrap__Expr__bin_encode_hex, self) -Expr$bin_encode_base64 <- function() .Call(wrap__Expr__bin_encode_base64, self) +Expr$bin_encode_base64 = function() .Call(wrap__Expr__bin_encode_base64, self) -Expr$bin_decode_hex <- function(strict) .Call(wrap__Expr__bin_decode_hex, self, strict) +Expr$bin_decode_hex = function(strict) .Call(wrap__Expr__bin_decode_hex, self, strict) -Expr$bin_decode_base64 <- function(strict) .Call(wrap__Expr__bin_decode_base64, self, strict) +Expr$bin_decode_base64 = function(strict) .Call(wrap__Expr__bin_decode_base64, self, strict) -Expr$struct_field_by_name <- function(name) .Call(wrap__Expr__struct_field_by_name, self, name) +Expr$struct_field_by_name = function(name) .Call(wrap__Expr__struct_field_by_name, self, name) -Expr$struct_rename_fields <- function(names) .Call(wrap__Expr__struct_rename_fields, self, names) +Expr$struct_rename_fields = function(names) .Call(wrap__Expr__struct_rename_fields, self, names) -Expr$meta_pop <- function() .Call(wrap__Expr__meta_pop, self) +Expr$meta_pop = function() .Call(wrap__Expr__meta_pop, self) -Expr$meta_eq <- function(other) .Call(wrap__Expr__meta_eq, self, other) +Expr$meta_eq = function(other) .Call(wrap__Expr__meta_eq, self, other) -Expr$meta_roots <- function() .Call(wrap__Expr__meta_roots, self) +Expr$meta_roots = function() .Call(wrap__Expr__meta_roots, self) -Expr$meta_output_name <- function() .Call(wrap__Expr__meta_output_name, self) +Expr$meta_output_name = function() .Call(wrap__Expr__meta_output_name, self) -Expr$meta_undo_aliases <- function() .Call(wrap__Expr__meta_undo_aliases, self) +Expr$meta_undo_aliases = function() .Call(wrap__Expr__meta_undo_aliases, self) -Expr$meta_has_multiple_outputs <- function() .Call(wrap__Expr__meta_has_multiple_outputs, self) +Expr$meta_has_multiple_outputs = function() .Call(wrap__Expr__meta_has_multiple_outputs, self) -Expr$meta_is_regex_projection <- function() .Call(wrap__Expr__meta_is_regex_projection, self) +Expr$meta_is_regex_projection = function() .Call(wrap__Expr__meta_is_regex_projection, self) -Expr$cat_set_ordering <- function(ordering) .Call(wrap__Expr__cat_set_ordering, self, ordering) +Expr$cat_set_ordering = function(ordering) .Call(wrap__Expr__cat_set_ordering, self, ordering) -Expr$new_count <- function() .Call(wrap__Expr__new_count) +Expr$new_count = function() .Call(wrap__Expr__new_count) -Expr$new_first <- function() .Call(wrap__Expr__new_first) +Expr$new_first = function() .Call(wrap__Expr__new_first) -Expr$new_last <- function() .Call(wrap__Expr__new_last) +Expr$new_last = function() .Call(wrap__Expr__new_last) #' @export -`$.Expr` <- function (self, name) { func <- Expr[[name]]; environment(func) <- environment(); func } +`$.Expr` = function(self, name) { + func = Expr[[name]] + environment(func) = environment() + func +} #' @export -`[[.Expr` <- `$.Expr` +`[[.Expr` = `$.Expr` -ProtoExprArray <- new.env(parent = emptyenv()) +ProtoExprArray = new.env(parent = emptyenv()) -ProtoExprArray$new <- function() .Call(wrap__ProtoExprArray__new) +ProtoExprArray$new = function() .Call(wrap__ProtoExprArray__new) -ProtoExprArray$push_back_str <- function(s) invisible(.Call(wrap__ProtoExprArray__push_back_str, self, s)) +ProtoExprArray$push_back_str = function(s) invisible(.Call(wrap__ProtoExprArray__push_back_str, self, s)) -ProtoExprArray$push_back_rexpr <- function(r) invisible(.Call(wrap__ProtoExprArray__push_back_rexpr, self, r)) +ProtoExprArray$push_back_rexpr = function(r) invisible(.Call(wrap__ProtoExprArray__push_back_rexpr, self, r)) -ProtoExprArray$print <- function() invisible(.Call(wrap__ProtoExprArray__print, self)) +ProtoExprArray$print = function() invisible(.Call(wrap__ProtoExprArray__print, self)) #' @export -`$.ProtoExprArray` <- function (self, name) { func <- ProtoExprArray[[name]]; environment(func) <- environment(); func } +`$.ProtoExprArray` = function(self, name) { + func = ProtoExprArray[[name]] + environment(func) = environment() + func +} #' @export -`[[.ProtoExprArray` <- `$.ProtoExprArray` +`[[.ProtoExprArray` = `$.ProtoExprArray` -When <- new.env(parent = emptyenv()) +When = new.env(parent = emptyenv()) -When$when <- function(predicate) .Call(wrap__When__when, predicate) +When$when = function(predicate) .Call(wrap__When__when, predicate) -When$then <- function(expr) .Call(wrap__When__then, self, expr) +When$then = function(expr) .Call(wrap__When__then, self, expr) -When$print <- function() invisible(.Call(wrap__When__print, self)) +When$print = function() invisible(.Call(wrap__When__print, self)) #' @export -`$.When` <- function (self, name) { func <- When[[name]]; environment(func) <- environment(); func } +`$.When` = function(self, name) { + func = When[[name]] + environment(func) = environment() + func +} #' @export -`[[.When` <- `$.When` +`[[.When` = `$.When` -WhenThen <- new.env(parent = emptyenv()) +WhenThen = new.env(parent = emptyenv()) -WhenThen$when <- function(predicate) .Call(wrap__WhenThen__when, self, predicate) +WhenThen$when = function(predicate) .Call(wrap__WhenThen__when, self, predicate) -WhenThen$otherwise <- function(expr) .Call(wrap__WhenThen__otherwise, self, expr) +WhenThen$otherwise = function(expr) .Call(wrap__WhenThen__otherwise, self, expr) -WhenThen$print <- function() invisible(.Call(wrap__WhenThen__print, self)) +WhenThen$print = function() invisible(.Call(wrap__WhenThen__print, self)) #' @export -`$.WhenThen` <- function (self, name) { func <- WhenThen[[name]]; environment(func) <- environment(); func } +`$.WhenThen` = function(self, name) { + func = WhenThen[[name]] + environment(func) = environment() + func +} #' @export -`[[.WhenThen` <- `$.WhenThen` +`[[.WhenThen` = `$.WhenThen` -WhenThenThen <- new.env(parent = emptyenv()) +WhenThenThen = new.env(parent = emptyenv()) -WhenThenThen$when <- function(predicate) .Call(wrap__WhenThenThen__when, self, predicate) +WhenThenThen$when = function(predicate) .Call(wrap__WhenThenThen__when, self, predicate) -WhenThenThen$then <- function(expr) .Call(wrap__WhenThenThen__then, self, expr) +WhenThenThen$then = function(expr) .Call(wrap__WhenThenThen__then, self, expr) -WhenThenThen$otherwise <- function(expr) .Call(wrap__WhenThenThen__otherwise, self, expr) +WhenThenThen$otherwise = function(expr) .Call(wrap__WhenThenThen__otherwise, self, expr) -WhenThenThen$print <- function() invisible(.Call(wrap__WhenThenThen__print, self)) +WhenThenThen$print = function() invisible(.Call(wrap__WhenThenThen__print, self)) #' @export -`$.WhenThenThen` <- function (self, name) { func <- WhenThenThen[[name]]; environment(func) <- environment(); func } +`$.WhenThenThen` = function(self, name) { + func = WhenThenThen[[name]] + environment(func) = environment() + func +} #' @export -`[[.WhenThenThen` <- `$.WhenThenThen` +`[[.WhenThenThen` = `$.WhenThenThen` -LazyFrame <- new.env(parent = emptyenv()) +LazyFrame = new.env(parent = emptyenv()) -LazyFrame$print <- function() .Call(wrap__LazyFrame__print, self) +LazyFrame$print = function() .Call(wrap__LazyFrame__print, self) -LazyFrame$describe_plan <- function() invisible(.Call(wrap__LazyFrame__describe_plan, self)) +LazyFrame$describe_plan = function() invisible(.Call(wrap__LazyFrame__describe_plan, self)) -LazyFrame$debug_plan <- function() .Call(wrap__LazyFrame__debug_plan, self) +LazyFrame$debug_plan = function() .Call(wrap__LazyFrame__debug_plan, self) -LazyFrame$describe_optimized_plan <- function() .Call(wrap__LazyFrame__describe_optimized_plan, self) +LazyFrame$describe_optimized_plan = function() .Call(wrap__LazyFrame__describe_optimized_plan, self) -LazyFrame$collect_background <- function() .Call(wrap__LazyFrame__collect_background, self) +LazyFrame$collect_background = function() .Call(wrap__LazyFrame__collect_background, self) -LazyFrame$collect <- function() .Call(wrap__LazyFrame__collect, self) +LazyFrame$collect = function() .Call(wrap__LazyFrame__collect, self) -LazyFrame$collect_handled <- function() .Call(wrap__LazyFrame__collect_handled, self) +LazyFrame$collect_handled = function() .Call(wrap__LazyFrame__collect_handled, self) -LazyFrame$first <- function() .Call(wrap__LazyFrame__first, self) +LazyFrame$first = function() .Call(wrap__LazyFrame__first, self) -LazyFrame$last <- function() .Call(wrap__LazyFrame__last, self) +LazyFrame$last = function() .Call(wrap__LazyFrame__last, self) -LazyFrame$max <- function() .Call(wrap__LazyFrame__max, self) +LazyFrame$max = function() .Call(wrap__LazyFrame__max, self) -LazyFrame$min <- function() .Call(wrap__LazyFrame__min, self) +LazyFrame$min = function() .Call(wrap__LazyFrame__min, self) -LazyFrame$mean <- function() .Call(wrap__LazyFrame__mean, self) +LazyFrame$mean = function() .Call(wrap__LazyFrame__mean, self) -LazyFrame$median <- function() .Call(wrap__LazyFrame__median, self) +LazyFrame$median = function() .Call(wrap__LazyFrame__median, self) -LazyFrame$sum <- function() .Call(wrap__LazyFrame__sum, self) +LazyFrame$sum = function() .Call(wrap__LazyFrame__sum, self) -LazyFrame$std <- function(ddof) .Call(wrap__LazyFrame__std, self, ddof) +LazyFrame$std = function(ddof) .Call(wrap__LazyFrame__std, self, ddof) -LazyFrame$var <- function(ddof) .Call(wrap__LazyFrame__var, self, ddof) +LazyFrame$var = function(ddof) .Call(wrap__LazyFrame__var, self, ddof) -LazyFrame$quantile <- function(quantile, interpolation) .Call(wrap__LazyFrame__quantile, self, quantile, interpolation) +LazyFrame$quantile = function(quantile, interpolation) .Call(wrap__LazyFrame__quantile, self, quantile, interpolation) -LazyFrame$shift <- function(periods) .Call(wrap__LazyFrame__shift, self, periods) +LazyFrame$shift = function(periods) .Call(wrap__LazyFrame__shift, self, periods) -LazyFrame$shift_and_fill <- function(fill_value, periods) .Call(wrap__LazyFrame__shift_and_fill, self, fill_value, periods) +LazyFrame$shift_and_fill = function(fill_value, periods) .Call(wrap__LazyFrame__shift_and_fill, self, fill_value, periods) -LazyFrame$reverse <- function() .Call(wrap__LazyFrame__reverse, self) +LazyFrame$reverse = function() .Call(wrap__LazyFrame__reverse, self) -LazyFrame$drop <- function(columns) .Call(wrap__LazyFrame__drop, self, columns) +LazyFrame$drop = function(columns) .Call(wrap__LazyFrame__drop, self, columns) -LazyFrame$fill_nan <- function(fill_value) .Call(wrap__LazyFrame__fill_nan, self, fill_value) +LazyFrame$fill_nan = function(fill_value) .Call(wrap__LazyFrame__fill_nan, self, fill_value) -LazyFrame$fill_null <- function(fill_value) .Call(wrap__LazyFrame__fill_null, self, fill_value) +LazyFrame$fill_null = function(fill_value) .Call(wrap__LazyFrame__fill_null, self, fill_value) -LazyFrame$slice <- function(offset, length) .Call(wrap__LazyFrame__slice, self, offset, length) +LazyFrame$slice = function(offset, length) .Call(wrap__LazyFrame__slice, self, offset, length) -LazyFrame$select <- function(exprs) .Call(wrap__LazyFrame__select, self, exprs) +LazyFrame$select = function(exprs) .Call(wrap__LazyFrame__select, self, exprs) -LazyFrame$limit <- function(n) .Call(wrap__LazyFrame__limit, self, n) +LazyFrame$limit = function(n) .Call(wrap__LazyFrame__limit, self, n) -LazyFrame$tail <- function(n) .Call(wrap__LazyFrame__tail, self, n) +LazyFrame$tail = function(n) .Call(wrap__LazyFrame__tail, self, n) -LazyFrame$filter <- function(expr) .Call(wrap__LazyFrame__filter, self, expr) +LazyFrame$filter = function(expr) .Call(wrap__LazyFrame__filter, self, expr) -LazyFrame$drop_nulls <- function(subset) .Call(wrap__LazyFrame__drop_nulls, self, subset) +LazyFrame$drop_nulls = function(subset) .Call(wrap__LazyFrame__drop_nulls, self, subset) -LazyFrame$unique <- function(subset, keep, maintain_order) .Call(wrap__LazyFrame__unique, self, subset, keep, maintain_order) +LazyFrame$unique = function(subset, keep, maintain_order) .Call(wrap__LazyFrame__unique, self, subset, keep, maintain_order) -LazyFrame$groupby <- function(exprs, maintain_order) .Call(wrap__LazyFrame__groupby, self, exprs, maintain_order) +LazyFrame$groupby = function(exprs, maintain_order) .Call(wrap__LazyFrame__groupby, self, exprs, maintain_order) -LazyFrame$with_columns <- function(exprs) .Call(wrap__LazyFrame__with_columns, self, exprs) +LazyFrame$with_columns = function(exprs) .Call(wrap__LazyFrame__with_columns, self, exprs) -LazyFrame$with_column <- function(expr) .Call(wrap__LazyFrame__with_column, self, expr) +LazyFrame$with_column = function(expr) .Call(wrap__LazyFrame__with_column, self, expr) -LazyFrame$join_asof <- function(other, left_on, right_on, left_by, right_by, allow_parallel, force_parallel, suffix, strategy, tolerance, tolerance_str) .Call(wrap__LazyFrame__join_asof, self, other, left_on, right_on, left_by, right_by, allow_parallel, force_parallel, suffix, strategy, tolerance, tolerance_str) +LazyFrame$join_asof = function(other, left_on, right_on, left_by, right_by, allow_parallel, force_parallel, suffix, strategy, tolerance, tolerance_str) .Call(wrap__LazyFrame__join_asof, self, other, left_on, right_on, left_by, right_by, allow_parallel, force_parallel, suffix, strategy, tolerance, tolerance_str) -LazyFrame$join <- function(other, left_on, right_on, how, suffix, allow_parallel, force_parallel) .Call(wrap__LazyFrame__join, self, other, left_on, right_on, how, suffix, allow_parallel, force_parallel) +LazyFrame$join = function(other, left_on, right_on, how, suffix, allow_parallel, force_parallel) .Call(wrap__LazyFrame__join, self, other, left_on, right_on, how, suffix, allow_parallel, force_parallel) -LazyFrame$sort_by_exprs <- function(by, descending, nulls_last) .Call(wrap__LazyFrame__sort_by_exprs, self, by, descending, nulls_last) +LazyFrame$sort_by_exprs = function(by, descending, nulls_last) .Call(wrap__LazyFrame__sort_by_exprs, self, by, descending, nulls_last) -LazyFrame$melt <- function(id_vars, value_vars, value_name, variable_name, streamable) .Call(wrap__LazyFrame__melt, self, id_vars, value_vars, value_name, variable_name, streamable) +LazyFrame$melt = function(id_vars, value_vars, value_name, variable_name, streamable) .Call(wrap__LazyFrame__melt, self, id_vars, value_vars, value_name, variable_name, streamable) -LazyFrame$rename <- function(existing, new) .Call(wrap__LazyFrame__rename, self, existing, new) +LazyFrame$rename = function(existing, new) .Call(wrap__LazyFrame__rename, self, existing, new) #' @export -`$.LazyFrame` <- function (self, name) { func <- LazyFrame[[name]]; environment(func) <- environment(); func } +`$.LazyFrame` = function(self, name) { + func = LazyFrame[[name]] + environment(func) = environment() + func +} #' @export -`[[.LazyFrame` <- `$.LazyFrame` +`[[.LazyFrame` = `$.LazyFrame` -LazyGroupBy <- new.env(parent = emptyenv()) +LazyGroupBy = new.env(parent = emptyenv()) -LazyGroupBy$print <- function() invisible(.Call(wrap__LazyGroupBy__print, self)) +LazyGroupBy$print = function() invisible(.Call(wrap__LazyGroupBy__print, self)) -LazyGroupBy$agg <- function(exprs) .Call(wrap__LazyGroupBy__agg, self, exprs) +LazyGroupBy$agg = function(exprs) .Call(wrap__LazyGroupBy__agg, self, exprs) -LazyGroupBy$head <- function(n) .Call(wrap__LazyGroupBy__head, self, n) +LazyGroupBy$head = function(n) .Call(wrap__LazyGroupBy__head, self, n) -LazyGroupBy$tail <- function(n) .Call(wrap__LazyGroupBy__tail, self, n) +LazyGroupBy$tail = function(n) .Call(wrap__LazyGroupBy__tail, self, n) #' @export -`$.LazyGroupBy` <- function (self, name) { func <- LazyGroupBy[[name]]; environment(func) <- environment(); func } +`$.LazyGroupBy` = function(self, name) { + func = LazyGroupBy[[name]] + environment(func) = environment() + func +} #' @export -`[[.LazyGroupBy` <- `$.LazyGroupBy` +`[[.LazyGroupBy` = `$.LazyGroupBy` -Series <- new.env(parent = emptyenv()) +Series = new.env(parent = emptyenv()) -Series$new <- function(x, name) .Call(wrap__Series__new, x, name) +Series$new = function(x, name) .Call(wrap__Series__new, x, name) -Series$clone <- function() .Call(wrap__Series__clone, self) +Series$clone = function() .Call(wrap__Series__clone, self) -Series$sleep <- function(millis) .Call(wrap__Series__sleep, self, millis) +Series$sleep = function(millis) .Call(wrap__Series__sleep, self, millis) -Series$panic <- function() .Call(wrap__Series__panic, self) +Series$panic = function() .Call(wrap__Series__panic, self) -Series$to_r <- function() .Call(wrap__Series__to_r, self) +Series$to_r = function() .Call(wrap__Series__to_r, self) -Series$rename_mut <- function(name) invisible(.Call(wrap__Series__rename_mut, self, name)) +Series$rename_mut = function(name) invisible(.Call(wrap__Series__rename_mut, self, name)) -Series$dtype <- function() .Call(wrap__Series__dtype, self) +Series$dtype = function() .Call(wrap__Series__dtype, self) -Series$n_unique <- function() .Call(wrap__Series__n_unique, self) +Series$n_unique = function() .Call(wrap__Series__n_unique, self) -Series$name <- function() .Call(wrap__Series__name, self) +Series$name = function() .Call(wrap__Series__name, self) -Series$sort_mut <- function(reverse) .Call(wrap__Series__sort_mut, self, reverse) +Series$sort_mut = function(reverse) .Call(wrap__Series__sort_mut, self, reverse) -Series$value_counts <- function(multithreaded, sorted) .Call(wrap__Series__value_counts, self, multithreaded, sorted) +Series$value_counts = function(multithreaded, sorted) .Call(wrap__Series__value_counts, self, multithreaded, sorted) -Series$arg_min <- function() .Call(wrap__Series__arg_min, self) +Series$arg_min = function() .Call(wrap__Series__arg_min, self) -Series$arg_max <- function() .Call(wrap__Series__arg_max, self) +Series$arg_max = function() .Call(wrap__Series__arg_max, self) -Series$is_sorted_flag <- function() .Call(wrap__Series__is_sorted_flag, self) +Series$is_sorted_flag = function() .Call(wrap__Series__is_sorted_flag, self) -Series$is_sorted_reverse_flag <- function() .Call(wrap__Series__is_sorted_reverse_flag, self) +Series$is_sorted_reverse_flag = function() .Call(wrap__Series__is_sorted_reverse_flag, self) -Series$is_sorted <- function(reverse, nulls_last) .Call(wrap__Series__is_sorted, self, reverse, nulls_last) +Series$is_sorted = function(reverse, nulls_last) .Call(wrap__Series__is_sorted, self, reverse, nulls_last) -Series$series_equal <- function(other, null_equal, strict) .Call(wrap__Series__series_equal, self, other, null_equal, strict) +Series$series_equal = function(other, null_equal, strict) .Call(wrap__Series__series_equal, self, other, null_equal, strict) -Series$get_fmt <- function(index, str_length) .Call(wrap__Series__get_fmt, self, index, str_length) +Series$get_fmt = function(index, str_length) .Call(wrap__Series__get_fmt, self, index, str_length) -Series$to_fmt_char <- function(str_length) .Call(wrap__Series__to_fmt_char, self, str_length) +Series$to_fmt_char = function(str_length) .Call(wrap__Series__to_fmt_char, self, str_length) -Series$compare <- function(other, op) .Call(wrap__Series__compare, self, other, op) +Series$compare = function(other, op) .Call(wrap__Series__compare, self, other, op) -Series$rep <- function(n, rechunk) .Call(wrap__Series__rep, self, n, rechunk) +Series$rep = function(n, rechunk) .Call(wrap__Series__rep, self, n, rechunk) -Series$shape <- function() .Call(wrap__Series__shape, self) +Series$shape = function() .Call(wrap__Series__shape, self) -Series$len <- function() .Call(wrap__Series__len, self) +Series$len = function() .Call(wrap__Series__len, self) -Series$chunk_lengths <- function() .Call(wrap__Series__chunk_lengths, self) +Series$chunk_lengths = function() .Call(wrap__Series__chunk_lengths, self) -Series$abs <- function() .Call(wrap__Series__abs, self) +Series$abs = function() .Call(wrap__Series__abs, self) -Series$alias <- function(name) .Call(wrap__Series__alias, self, name) +Series$alias = function(name) .Call(wrap__Series__alias, self, name) -Series$all <- function() .Call(wrap__Series__all, self) +Series$all = function() .Call(wrap__Series__all, self) -Series$any <- function() .Call(wrap__Series__any, self) +Series$any = function() .Call(wrap__Series__any, self) -Series$add <- function(other) .Call(wrap__Series__add, self, other) +Series$add = function(other) .Call(wrap__Series__add, self, other) -Series$sub <- function(other) .Call(wrap__Series__sub, self, other) +Series$sub = function(other) .Call(wrap__Series__sub, self, other) -Series$mul <- function(other) .Call(wrap__Series__mul, self, other) +Series$mul = function(other) .Call(wrap__Series__mul, self, other) -Series$div <- function(other) .Call(wrap__Series__div, self, other) +Series$div = function(other) .Call(wrap__Series__div, self, other) -Series$rem <- function(other) .Call(wrap__Series__rem, self, other) +Series$rem = function(other) .Call(wrap__Series__rem, self, other) -Series$append_mut <- function(other) .Call(wrap__Series__append_mut, self, other) +Series$append_mut = function(other) .Call(wrap__Series__append_mut, self, other) -Series$apply <- function(robj, rdatatype, strict, allow_fail_eval) .Call(wrap__Series__apply, self, robj, rdatatype, strict, allow_fail_eval) +Series$apply = function(robj, rdatatype, strict, allow_fail_eval) .Call(wrap__Series__apply, self, robj, rdatatype, strict, allow_fail_eval) -Series$mean <- function() .Call(wrap__Series__mean, self) +Series$mean = function() .Call(wrap__Series__mean, self) -Series$median <- function() .Call(wrap__Series__median, self) +Series$median = function() .Call(wrap__Series__median, self) -Series$min <- function() .Call(wrap__Series__min, self) +Series$min = function() .Call(wrap__Series__min, self) -Series$max <- function() .Call(wrap__Series__max, self) +Series$max = function() .Call(wrap__Series__max, self) -Series$sum <- function() .Call(wrap__Series__sum, self) +Series$sum = function() .Call(wrap__Series__sum, self) -Series$std <- function(ddof) .Call(wrap__Series__std, self, ddof) +Series$std = function(ddof) .Call(wrap__Series__std, self, ddof) -Series$var <- function(ddof) .Call(wrap__Series__var, self, ddof) +Series$var = function(ddof) .Call(wrap__Series__var, self, ddof) -Series$ceil <- function() .Call(wrap__Series__ceil, self) +Series$ceil = function() .Call(wrap__Series__ceil, self) -Series$floor <- function() .Call(wrap__Series__floor, self) +Series$floor = function() .Call(wrap__Series__floor, self) -Series$print <- function() invisible(.Call(wrap__Series__print, self)) +Series$print = function() invisible(.Call(wrap__Series__print, self)) -Series$cumsum <- function(reverse) .Call(wrap__Series__cumsum, self, reverse) +Series$cumsum = function(reverse) .Call(wrap__Series__cumsum, self, reverse) -Series$to_frame <- function() .Call(wrap__Series__to_frame, self) +Series$to_frame = function() .Call(wrap__Series__to_frame, self) -Series$set_sorted_mut <- function(reverse) invisible(.Call(wrap__Series__set_sorted_mut, self, reverse)) +Series$set_sorted_mut = function(reverse) invisible(.Call(wrap__Series__set_sorted_mut, self, reverse)) -Series$from_arrow <- function(name, array) .Call(wrap__Series__from_arrow, name, array) +Series$from_arrow = function(name, array) .Call(wrap__Series__from_arrow, name, array) #' @export -`$.Series` <- function (self, name) { func <- Series[[name]]; environment(func) <- environment(); func } +`$.Series` = function(self, name) { + func = Series[[name]] + environment(func) = environment() + func +} #' @export -`[[.Series` <- `$.Series` +`[[.Series` = `$.Series` -PolarsBackgroundHandle <- new.env(parent = emptyenv()) +PolarsBackgroundHandle = new.env(parent = emptyenv()) -PolarsBackgroundHandle$new <- function(lazy_df) .Call(wrap__PolarsBackgroundHandle__new, lazy_df) +PolarsBackgroundHandle$new = function(lazy_df) .Call(wrap__PolarsBackgroundHandle__new, lazy_df) -PolarsBackgroundHandle$join <- function() .Call(wrap__PolarsBackgroundHandle__join, self) +PolarsBackgroundHandle$join = function() .Call(wrap__PolarsBackgroundHandle__join, self) -PolarsBackgroundHandle$is_exhausted <- function() .Call(wrap__PolarsBackgroundHandle__is_exhausted, self) +PolarsBackgroundHandle$is_exhausted = function() .Call(wrap__PolarsBackgroundHandle__is_exhausted, self) #' @export -`$.PolarsBackgroundHandle` <- function (self, name) { func <- PolarsBackgroundHandle[[name]]; environment(func) <- environment(); func } +`$.PolarsBackgroundHandle` = function(self, name) { + func = PolarsBackgroundHandle[[name]] + environment(func) = environment() + func +} #' @export -`[[.PolarsBackgroundHandle` <- `$.PolarsBackgroundHandle` +`[[.PolarsBackgroundHandle` = `$.PolarsBackgroundHandle` # nolint end diff --git a/R/rpolarserr.R b/R/rpolarserr.R index a0fb37403..27c31c6f7 100644 --- a/R/rpolarserr.R +++ b/R/rpolarserr.R @@ -1,5 +1,3 @@ - - #' @title auto complete $-access into a polars object #' @description called by the interactive R session internally #' @param x RPolarsErr diff --git a/R/string_error.R b/R/string_error.R index 6452856cb..a74bb1e9c 100644 --- a/R/string_error.R +++ b/R/string_error.R @@ -6,11 +6,11 @@ where_in.character = function(err, context) { paste(context, err) } to_condition.character = function(err) { - if(!is_string(err)) { - stop(paste("Internal error: an error msg was not of length 1, but was:",str_string(err))) + if (!is_string(err)) { + stop(paste("Internal error: an error msg was not of length 1, but was:", str_string(err))) } errorCondition(err) } plain.character = function(err, msg) { - NextMethod("plain",err) + NextMethod("plain", err) } diff --git a/man/result.Rd b/man/result.Rd index ea9e31166..44361ef0d 100644 --- a/man/result.Rd +++ b/man/result.Rd @@ -19,22 +19,22 @@ Capture any R error and return a rust-like Result } \examples{ - #user internal functions without using ::: - result = environment(polars::pl$all)$result - unwrap_err = environment(polars::pl$all)$unwrap_err - unwrap = environment(polars::pl$all)$unwrap - Err = environment(polars::pl$all)$Err +# user internal functions without using ::: +result = environment(polars::pl$all)$result +unwrap_err = environment(polars::pl$all)$unwrap_err +unwrap = environment(polars::pl$all)$unwrap +Err = environment(polars::pl$all)$Err - #capture regular R errors or RPolarsErr - throw_simpleError = \() stop("Imma simple error") - result(throw_simpleError()) +# capture regular R errors or RPolarsErr +throw_simpleError = \() stop("Imma simple error") +result(throw_simpleError()) - throw_RPolarsErr = \() unwrap( +throw_RPolarsErr = \() unwrap( Err(.pr$RPolarsErr$new()$bad_robj(42)$mistyped("String")$when("doing something")) - ) - res_RPolarsErr = result(throw_RPolarsErr()) - str(res_RPolarsErr) - RPolarsErr = unwrap_err(res_RPolarsErr) - RPolarsErr$contexts() +) +res_RPolarsErr = result(throw_RPolarsErr()) +str(res_RPolarsErr) +RPolarsErr = unwrap_err(res_RPolarsErr) +RPolarsErr$contexts() } \keyword{internal} diff --git a/man/unwrap.Rd b/man/unwrap.Rd index db472f460..35869bd23 100644 --- a/man/unwrap.Rd +++ b/man/unwrap.Rd @@ -21,7 +21,7 @@ rust-like unwrapping of result. Useful to keep error handling on the R side. } \examples{ -#get unwrap without using ::: +# get unwrap without using ::: unwrap = environment(polars::pl$all)$unwrap structure(list(ok = "foo", err = NULL), class = "extendr_result") From b8f4d276ccef65ac655d2dd90627f2f58d7732e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=B8ren=20Havelund=20Welling?= Date: Tue, 20 Jun 2023 13:40:33 +0200 Subject: [PATCH 23/24] fix release pipeline misses devtools (#246) Co-authored-by: eitsupi <50911393+eitsupi@users.noreply.github.com> --- .github/workflows/release.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index 4031e508e..c42d05375 100644 --- a/.github/workflows/release.yaml +++ b/.github/workflows/release.yaml @@ -53,7 +53,7 @@ jobs: - uses: r-lib/actions/setup-r-dependencies@v2 with: extra-packages: any::rcmdcheck - needs: check + needs: dev pak-version: devel env: CI: false From d75ce6a00001b390a1c62691cbf79d3e8aaf4045 Mon Sep 17 00:00:00 2001 From: sorhawell Date: Wed, 21 Jun 2023 22:09:46 +0200 Subject: [PATCH 24/24] add news --- NEWS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/NEWS.md b/NEWS.md index a17b00455..77aa27f96 100644 --- a/NEWS.md +++ b/NEWS.md @@ -5,6 +5,7 @@ - `$unique()` and `$unique()` gain a `maintain_order` argument (#238). - New `pl$LazyFrame()` to quickly create a `LazyFrame`, mostly in examples or for demonstration purposes (#240). +- Polars is internally moving away from string errors to a new error-type called `RPolarsErr` both on rust- and R-side. Final error messages should look very similar (#233). # polars 0.6.1 ## What's changed