Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
dfalbel committed Jan 24, 2022
0 parents commit 03342c0
Show file tree
Hide file tree
Showing 11 changed files with 265 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .Rbuildignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
^torchexport\.Rproj$
^\.Rproj\.user$
^LICENSE\.md$
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
.Rproj.user
.Rhistory
.Rdata
.httr-oauth
.DS_Store
17 changes: 17 additions & 0 deletions DESCRIPTION
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
Package: torchexport
Title: Code Generation for 'C++' Interfaces for 'torch'.
Version: 0.0.1.9000
Authors@R:
person("Daniel", "Falbel", , "[email protected]", role = c("aut", "cre"))
Description: Generates code to automatically handle errors and to correctly export
functions when creating 'C++' extensions for torch.
License: MIT + file LICENSE
Encoding: UTF-8
Roxygen: list(markdown = TRUE)
RoxygenNote: 7.1.2
Imports:
fs,
glue,
pkgload,
purrr,
readr
2 changes: 2 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
YEAR: 2022
COPYRIGHT HOLDER: torchexport authors
21 changes: 21 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# MIT License

Copyright (c) 2022 torchexport authors

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
3 changes: 3 additions & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Generated by roxygen2: do not edit by hand

export(export)
17 changes: 17 additions & 0 deletions R/declarations.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@


get_package_name <- function() {
toupper(desc::desc_get("Package"))
}

get_src_files <- function() {
src_files <- fs::dir_ls("csrc/src/")
}

get_declarations <- function() {
src_files <- get_src_files()
decors <- decor::cpp_decorations(files = src_files)
subset(decors, decoration == "torch::export")
}


99 changes: 99 additions & 0 deletions R/export.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
#' Generates code that exports code from C++ extensions
#'
#' This function is used by the CmakeList.txt file template to autogenerate
#' headers and declarations for exported functions in torch C++ extensions.
#'
#' @inheritParams pkgload::load_all
#'
#' @export
export <- function(pkg = pkg_path()) {
withr::with_dir(pkg, {
decls <- get_declarations()

if (nrow(decls) == 0)
return(invisible(NULL))

decls <- lapply(decls$context, generate_decls)
decls <- purrr::transpose(decls)

export_cpp <- exports_cpp(decls$error_handled)
export_h <- exports_h(decls$empty_decl, decls$wrapper)

readr::write_lines(export_cpp, "csrc/src/exports.cpp")
readr::write_lines(export_h, fs::path("csrc/include/", get_package_name(), "exports.h"))
})

invisible(NULL)
}

pkg_path <- pkgload::pkg_path


generate_decls <- function(context) {
parsed <- decor::parse_cpp_function(context)
list(
error_handled = make_error_handled(parsed),
wrapper = make_wrapper(parsed),
empty_decl = make_empty_declaration(parsed)
)
}


make_error_handled <- function(parsed) {
glue_code("
<<make_declaration(parsed, macro = '', prefix = '')>>;
<<make_declaration(parsed)>> {
try {
<<make_return(parsed)>> <<parsed$name>>(<<make_call(parsed)>>);
} <<get_package_name()>>_HANDLE_EXCEPTION
<<if (parsed$return_type != 'void') paste('return (',parsed$return_type,') NULL')>>;
}
")
}

make_wrapper <- function(parsed) {
glue_code("
<<make_declaration(parsed, macro = '', prefix = '', inline = TRUE)>> {
<<if (parsed$return_type != 'void') 'auto ret = ' else ''>> _<<parsed$name>>(<<make_call(parsed)>>);
host_exception_handler();
<<if (parsed$return_type != 'void') 'return ret;' else ''>>
}
")
}

make_empty_declaration <- function(parsed) {
glue_code("<<make_declaration(parsed)>>;")
}


glue_code <- function(..., .envir = parent.frame()) {
glue::glue(..., .open = "<<", .close = ">>", .envir = .envir)
}

make_declaration <- function(parsed, prefix = "_", macro = NULL, inline = FALSE) {
if (is.null(macro)) {
macro <- glue_code("<<get_package_name()>>_API ")
} else {
macro <- macro
}
inline <- ifelse(inline, "inline ", "")
glue_code("<<macro>><<inline>><<parsed$return_type>> <<prefix>><<parsed$name>> (<<make_signature(parsed)>>)")
}

make_signature <- function(parsed) {
args <- parsed$args[[1]]
paste(args$type, args$name) |>
paste(collapse = ", ")
}

make_call <- function(parsed) {
args <- parsed$args[[1]]
paste(args$name, collapse = ", ")
}

make_return <- function(parsed) {
if (parsed$return_type == "void")
""
else
"return "
}
64 changes: 64 additions & 0 deletions R/templates.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@

exports_cpp <- function(functions) {
NAME <- get_package_name()
name <- tolower(NAME)
glue_code(
'
#include "<<name>>/exports.h"
#include <lantern/types.h>
void * p_<<name>>_last_error = NULL;
<<NAME>>_API void* lltm_last_error()
{
return p_<<name>>_last_error;
}
<<NAME>>_API void <<name>>_last_error_clear()
{
p_<<name>>_last_error = NULL;
}
#ifndef <<NAME>>_HANDLE_EXCEPTION
#define <<NAME>>_HANDLE_EXCEPTION \\\\\n
catch(const std::exception& ex) { \\\\\n
p_<<name>>_last_error = make_raw::string(ex.what()); \\\\\n
} catch (std::string& ex) { \\\\\n
p_<<name>>_last_error = make_raw::string(ex); \\\\\n
} catch (...) { \\\\\n
p_<<name>>_last_error = make_raw::string("Unknown error. "); \\\\\n
}
#endif
<<paste(functions, collapse = "\n")>>
'
)
}

exports_h <- function(declarations, wrappers) {
NAME <- get_package_name()
name <- tolower(NAME)
glue_code(
'
#ifdef _WIN32
#ifndef <<NAME>>_HEADERS_ONLY
#define <<NAME>>_API extern "C" __declspec(dllexport)
#else
#define <<NAME>>_API extern "C" __declspec(dllimport)
#endif
#else
#define <<NAME>>_API extern "C"
#endif
void host_exception_handler ();
extern void* p_<<name>>_last_error;
<<NAME>>_API void* <<name>>_last_error ();
<<NAME>>_API void <<name>>_last_error_clear();
<<paste(declarations, collapse = "\n")>>
#ifdef RCPP_VERSION
<<paste(wrappers, collapse = "\n")>>
#endif // RCPP_VERSION
'
)
}
12 changes: 12 additions & 0 deletions man/export.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

22 changes: 22 additions & 0 deletions torchexport.Rproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
Version: 1.0

RestoreWorkspace: No
SaveWorkspace: No
AlwaysSaveHistory: Default

EnableCodeIndexing: Yes
UseSpacesForTab: Yes
NumSpacesForTab: 2
Encoding: UTF-8

RnwWeave: Sweave
LaTeX: pdfLaTeX

AutoAppendNewline: Yes
StripTrailingWhitespace: Yes
LineEndingConversion: Posix

BuildType: Package
PackageUseDevtools: Yes
PackageInstallArgs: --no-multiarch --with-keep.source
PackageRoxygenize: rd,collate,namespace

0 comments on commit 03342c0

Please sign in to comment.