RcppTOML/0000755000176200001440000000000013762016170011655 5ustar liggesusersRcppTOML/NAMESPACE0000644000176200001440000000027213065560631013077 0ustar liggesusersuseDynLib("RcppTOML", .registration=TRUE) importFrom("Rcpp", "evalCpp") export("parseToml", "parseTOML", "tomlparse") S3method("print", "toml") S3method("summary", "toml") RcppTOML/ChangeLog0000644000176200001440000003303013761446607013441 0ustar liggesusers2020-12-01 Dirk Eddelbuettel * man/parseTOML.Rd: Update URL to https://toml.io/en/ * man/RcppTOML-package.Rd: Idem * inst/NEWS.Rd: Idem * DESCRIPTION: Idem * README.md: Idem, also update three more URLs * .travis.yml: Use r-ci with focal and bspm for CI 2020-11-30 Dirk Eddelbuettel * DESCRIPTION (Version, Date): Roll minor version * inst/include/cpptoml.h: Add limits header for g++-11 (also sent upstream as PR #123) * cleanup: Use /bin/sh to not depend on bash [CRAN] 2020-05-23 Dirk Eddelbuettel * DESCRIPTION (Version, Date): Roll minor version * README.md: Add 'last commit' badge * .travis.yml: Updated to 'bionic' and R 4.0.0 2019-06-29 Dirk Eddelbuettel * .travis.yml (install): Use r-cran-tinytest from PPA 2019-06-26 Dirk Eddelbuettel * DESCRIPTION (SystemRequirements, Description): State g++ requires 4.9.3 or newer; remove 'modern' before C++11 as it is standard now 2019-06-25 Dirk Eddelbuettel * DESCRIPTION (Version, Date): Release 0.1.6 * README.md (tinytest): Mention post-install testing 2019-06-24 Václav Hausenblas * inst/tinytest/test_examples.R: Refine UTF-8 test for Windows 2019-06-24 Dirk Eddelbuettel * inst/tinytest/test_bool_datetime.R: Skip some on tests on Solaris * inst/tinytest/test_dates_times.R: Idem * inst/tinytest/test_examples.R: Idem * inst/tinytest/test_misc.R: Idem 2019-06-22 Dirk Eddelbuettel * DESCRIPTION (Version, Date): Roll minor version * inst/tinytest/test_misc.R: Added, based on tests/strings.R * inst/tinytest/test_strings.R: Added, based on tests/strings.R * inst/tinytest/strings.toml: Moved from tests/tables.toml * inst/tinytest/test_tables.R: Added, based on tests/tables.R * inst/tinytest/tables.toml: Moved from tests/tables.toml * inst/tinytest/test_examples.R: Added, based on tests/tomlExamples.R * inst/tinytest/toml_example-v0.4.0.toml: Moved from tests/toml_example-v0.4.0.toml * inst/tinytest/toml_example.toml: Moved from tests/toml_example.toml * inst/tinytest/toml_hard_example.toml: Moved from tests/toml_hard_example.toml * tests/*.Rout.save: Moved old test results to local/old_tests/ * .codecov.yml (coverage): Make patch behaviour more quiet * ChangeLog: Add entries for PRs since last release * inst/NEWS: Idem 2019-06-21 Dirk Eddelbuettel * .travis.yml (install): Install tinytest * inst/tinytest/test_bool_datetime.R: Added, based on tests/bool_datetime.R * inst/tinytest/bool_datetime.toml: Moved from tests/bool_datetime.toml * inst/tinytest/test_float.R: Added, based on inst/tinytest/float.R * inst/tinytest/float.toml: Moved from tests/float.toml * inst/tinytest/test_integer.R: Added, based on tests/integer.R * inst/tinytest/integer.toml: Moved from tests/integer.toml 2019-06-20 Dirk Eddelbuettel * inst/tinytest/test_arrays.R: Moved from tests/arrays.R * inst/tinytest/arrays.toml: Moved from tests/arrays.toml 2019-06-19 Dirk Eddelbuettel * DESCRIPTION: Added Suggests: tinytest * tests/tinytest.R: Added * inst/tinytest/test_dates_times.R: Added, based on tests/dates_and_times.R * inst/tinytest/dates_times.toml: Moved from tests/dates_and times.toml 2019-05-14 Watal M. Iwasaki * README.md: Correct to state v0.5.0 support for TOML standard 2019-04-27 Václav Hausenblas * src/parse.cpp: Encoding in arrays ensures all strings are UTF-8 2019-01-23 Václav Hausenblas * src/parse.cpp: Escape switch to calls of \code{getTable()} and \code{getArray()} 2018-10-31 Dirk Eddelbuettel * DESCRIPTION (Version, Date): Release 0.1.5 * man/parseTOML.Rd: Reformat example to fit line length 2018-10-26 Václav Hausenblas * src/parse.cpp: Encoding of strings returned by the parser declared as UTF-8 * R/parseToml.R: Non-file text inputs are converted to UTF-8 if necessary * man/parseTOML.Rd: Documentation 2018-10-25 Dirk Eddelbuettel * src/parse.cpp (getValue): Support local time 2018-10-24 Václav Hausenblas * src/parse.cpp: New flag 'escape' to support escape chars * R/parseToml.R: Idem * man/parseTOML.Rd: Documentation 2018-10-23 Dirk Eddelbuettel * DESCRIPTION (Version, Date): Release 0.1.4 * README.md: Added dependencies badge 2018-10-22 Dirk Eddelbuettel * inst/include/cpptoml.h: Synchronised with (fixed) upstream with support for TOML v0.5.0 * tests/dates_and_times.toml: New tests * tests/dates_and_times.R: Invocation for new tests 2018-09-02 Dirk Eddelbuettel * .travis.yml: Minor update to commented-out PPA for R 3.5 2017-11-16 Dirk Eddelbuettel * inst/include/cpptoml.h: Added '// #nocov' tags * inst/include/includize.hpp: Idem * inst/include/toml.hpp: Idem 2017-11-14 Dirk Eddelbuettel * DESCRIPTION (Version, Date): New minor version * src/parse.cpp (tomlparseImpl): New argument 'includize' * R/parseToml.R (parseTOML): Support new argument * man/parseTOML.Rd: Document it * tests/misc.R: Added test for parse from string, summary() * tests/misc.Rout.save: Reference output * src/init.c: Removed, registration now in src/RcppExports.cpp 2017-11-13 Dirk Eddelbuettel * DESCRIPTION (Version, Date): New minor version * src/parse.cpp (tomlparseImpl): Add support for includize pre-processor; add its toml.hpp header * inst/include/includize.hpp: Included copy from @dcdillon's repo * inst/include/toml.hpp: Idem * inst/include/includize.hpp (includize): Do without codecvt * .travis.yml: Upgrade gcc and g++ to 4.9 2017-05-02 Dirk Eddelbuettel * src/parse.cpp (tomlparseImpl): Convert the StretchyList to List when inserting so they are seen as Lists in R (cf discussion in #16) * tests/arrays.Rout.save: Update reference output * tests/tomlExamples.Rout.save: Idem 2017-04-25 Dirk Eddelbuettel * DESCRIPTION (Version, Date): Release 0.1.3 2017-04-24 Dirk Eddelbuettel * DESCRIPTION (Version, Date): Roll minor version * src/parse.cpp (getTable): Nested TableArray types are now recognised; condition print statement on verbose mode * tests/arrays.Rout.save: Update reference output * tests/tomlExamples.Rout.save: Idem 2017-03-26 Dirk Eddelbuettel * DESCRIPTION (Version, Date): Release 0.1.2 * src/init.c (R_init_RcppTOML): all R_registerRoutines() and R_useDynamicSymbols() * NAMESPACE: Use .registration=TRUE on useDynLib * LICENSE: Added to repository * .Rbuildignore: Do not include LICENSE in package * inst/toml/ex4.toml (bla): Uncomment Datetimevector * inst/toml/example.toml: Updated to upstream README.md version * README.md: Expanded with example and screenshot * local/emacsAndTOML.png: Added for README * .Rbuildignore: Do not include local/ in package 2017-03-25 Dirk Eddelbuettel * DESCRIPTION (Version, Date): Roll minor version * src/parse.cpp (tomlparseImpl): Correct TableArray type assignment * tests/arrays.Rout.save: Update reference output * tests/tomlExamples.Rout.save: Ditto * .codecov.yml (comment): Add coverage support * .travis.yml: Ditto 2017-03-17 Dirk Eddelbuettel * DESCRIPTION (Version, Date): Roll minor version * src/parse.cpp (collapsedList): Preserve type for Date and Datetime vectors as well as boolean vectors 2017-02-12 Dirk Eddelbuettel * DESCRIPTION (Version, Date): Release 0.1.1 2017-02-08 Dirk Eddelbuettel * inst/include/cpptoml.h: Sync'ed with cpptoml upstream 2017-01-29 Dirk Eddelbuettel * R/parseToml.R: Output from print.toml() method without final NULL * tests/arrays.Rout.save: Updated reference output * tests/bool_datetime.Rout.save: Idem * tests/float.Rout.save: Idem * tests/integer.Rout.save: Idem * tests/strings.Rout.save: Idem * tests/tables.Rout.save: Idem * tests/tomlExamples.Rout.save: Idem 2017-01-24 Dirk Eddelbuettel * src/parse.cpp (tomlparseImpl): Suppport TOML parsing from a character variable (with thanks to Charles for a hint in #7) * R/parseToml.R (parseTOML): Additional argument to select filemode (default) or parse from character * man/parseTOML.Rd: Document new argument 2017-01-23 Dirk Eddelbuettel * DESCRIPTION (Version, Date): New minor version * src/parse.cpp: Extended to support local_date(time) * inst/toml/ex2.toml: Extended for new types 2017-01-22 Dirk Eddelbuettel * inst/include/cpptoml.h: Sync'ed with cpptoml upstream 2017-01-05 Dirk Eddelbuettel * DESCRIPTION: Release 0.1.0 * inst/include/cpptoml.h: Sync'ed with cpptoml upstream * src/parse.cpp: Added copyright header * R/parseToml.R: Idem * .travis.yml: Switch to using run.sh for Travis CI * README.md: Updated * inst/NEWS.Rd: Added 2017-01-04 Dirk Eddelbuettel * DESCRIPTION (Version, Date): New minor version (BugReports, URL): Added * src/parse.cpp (local_timegm): Restore parts of old behaviour * src/Makevars.win: Added * .travis.yml: Use trusty, also dump logs on failure 2017-01-03 Devin Pastoor * src/parse.cpp (local_timegm): On Windows, use Rcpp::mktime00 (as suggested by Dirk in GitHub Issue #5) 2015-12-19 Dirk Eddelbuettel * DESCRIPTION: Release 0.0.5 2015-12-17 Dirk Eddelbuettel * inst/include/cpptoml.h: Sync'ed with cpptoml upstream * src/parse.cpp: Small accomodations for changed cpptoml.h * tests/float.toml: No longer attempt to parse double number which previously overflowed and is now rejected by cpptoml * tests/toml_example-v0.4.0.toml: Ditto * tests/float.Rout.save: Ditto * tests/tomlExamples.Rout.save: Ditto 2015-07-16 Dirk Eddelbuettel * DESCRIPTION: Release 0.0.4 2015-07-15 Dirk Eddelbuettel * inst/include/cpptoml.h: Minor update to upstream version * R/parseToml.R: Use utils::str() instead of str() * DESCRIPTION: More quoting of terms, rolled Version and Date 2015-07-09 Dirk Eddelbuettel * src/parse.cpp (collapsedList): Ensure list has content before iterating over it 2015-04-27 Dirk Eddelbuettel * DESCRIPTION: Release 0.0.3 * DESCRIPTION: More quoting of terms, rolled Version and Date, added URL * src/parse.cpp (local_timegm): Expand if defined() to Apple and BSDs 2015-04-25 Dirk Eddelbuettel * DESCRIPTION: Renamed to RcppTOML, rolled Version and Date * NAMESPACE: Renamed to RcppTOML * README.md: Ditto * man/RcppTOML-package.Rd: Ditto * tests/*: Ditto * R/parseToml.R: Main function is parseTOML() now, keep aliases * README.md: Update current status, added Travis CI shield * man/RcppTOML-package.Rd: Expanded examples section and aliases * man/parseTOML.Rd: New manual page for main function * R/parseToml.R: Support verbose argument * src/parse.cpp (local_timegm): Add wrapper for timegm() using TZ resetting dance for OSs which do not have timegm() 2015-04-24 Dirk Eddelbuettel * DESCRIPTION (OS_type): Set to unix while Windows still labours along with a non-C++11 compiler * src/parse.cpp (getValue): Use timegm() as we are translating a UTC time into time_t, not a local time * tests/*.R: Simplify tests call as we no longer need explicit sorting * tests/*.Rout.save: Update reference output as well * .travis.yml: Set g++-4.9 via update-alternatives 2015-04-23 Dirk Eddelbuettel * src/Makevars: Enable compile-time option to use std::map now that out pull request to cpptoml.h has been accepted * R/parseToml.R: Beginnings of an R class wrapper with simple print and summary methods 2015-04-20 Dirk Eddelbuettel * src/parse.cpp (tomlparse): Added one missing if (verbose) 2015-04-19 Dirk Eddelbuettel * R/sort.R (.sort): Add internal sort function to recursively sort objects returned as the C++ unordered_hash representation leads to different returns on different platforms (eg 32 vs 64 Linux) 2015-04-04 Dirk Eddelbuettel * DESCRIPTION (OS_type): Mention need for a genuine C++11 compiler * tests/toml_example.toml: Added regression tests from toml-lang repo * tests/toml_hard_example.toml: Ditto * teststoml_example-v0.4.0.toml: Ditto (with line 56 edited) * tests/tomlExamples.R: Added caller for toml examples * tests/tomlExamples.Rout.save: Added reference output 2015-04-03 Dirk Eddelbuettel * .travis.yml: Added, later disabled as Travis appears to be currently borked for new projects requiring C++11 2015-04-02 Dirk Eddelbuettel * src/parse.cpp: Simplification / correction to ordering; recursion into table_array 2015-04-02 Dirk Eddelbuettel * src/parse.cpp: Now with nested arrays 2015-04-01 Dirk Eddelbuettel * src/parse.cpp: Arrays are now 'flattened' into vectors 2015-03-31 Dirk Eddelbuettel * src/parse.cpp: Basic array functionality; nested tables; basic value types, 'verbose' flag 2015-03-30 Dirk Eddelbuettel * src/parse.cpp: Beginnings of package; use StretchyList RcppTOML/README.md0000644000176200001440000001002513761445615013143 0ustar liggesusers## RcppTOML: Rcpp bindings for [TOML](https://toml.io/en/) [![Build Status](https://travis-ci.org/eddelbuettel/rcpptoml.svg)](https://travis-ci.org/eddelbuettel/rcpptoml) [![License](https://img.shields.io/badge/license-GPL%20%28%3E=%202%29-brightgreen.svg?style=flat)](https://www.gnu.org/licenses/gpl-2.0.html) [![CRAN](https://www.r-pkg.org/badges/version/RcppTOML)](https://cran.r-project.org/package=RcppTOML) [![Dependencies](https://tinyverse.netlify.com/badge/RcppTOML)](https://cran.r-project.org/package=RcppTOML) [![Downloads](https://cranlogs.r-pkg.org/badges/RcppTOML?color=brightgreen)](https://www.r-pkg.org/pkg/RcppTOML) [![Last Commit](https://img.shields.io/github/last-commit/eddelbuettel/rcpptoml)](https://github.com/eddelbuettel/rcpptoml) ### What is TOML? [TOML](https://toml.io/en/) is a configuration file grammar for humans. It is easier to read and edit than the alternatives yet arguably more useful as it is strongly typed: values come back as integer, double, (multiline-) character (strings), boolean or Datetime. Moreover, complex nesting and arrays are supported as well. This package uses the C++11 implementation written by Chase Geigle in [cpptoml](https://github.com/skystrife/cpptoml) to provide a parser that can be used by R. ### Example Consider the following [TOML](https://toml.io/en/) input example input: ```toml # This is a TOML document. title = "TOML Example" [owner] name = "Tom Preston-Werner" dob = 1979-05-27T07:32:00-08:00 # First class dates [database] server = "192.168.1.1" ports = [ 8001, 8001, 8002 ] connection_max = 5000 enabled = true [servers] # Indentation (tabs and/or spaces) is allowed but not required [servers.alpha] ip = "10.0.0.1" dc = "eqdc10" [servers.beta] ip = "10.0.0.2" dc = "eqdc10" [clients] data = [ ["gamma", "delta"], [1, 2] ] # Line breaks are OK when inside arrays hosts = [ "alpha", "omega" ] ``` Once parsed, note how R has properly typed input: ```r R> library(RcppTOML) R> parseTOML("inst/toml/example.toml") List of 5 $ clients :List of 2 ..$ data :List of 2 .. ..$ : chr [1:2] "gamma" "delta" .. ..$ : int [1:2] 1 2 ..$ hosts: chr [1:2] "alpha" "omega" $ database:List of 4 ..$ connection_max: int 5000 ..$ enabled : logi TRUE ..$ ports : int [1:3] 8001 8001 8002 ..$ server : chr "192.168.1.1" $ owner :List of 2 ..$ dob : POSIXct[1:1], format: "1979-05-27 15:32:00" ..$ name: chr "Tom Preston-Werner" $ servers :List of 2 ..$ alpha:List of 2 .. ..$ dc: chr "eqdc10" .. ..$ ip: chr "10.0.0.1" ..$ beta :List of 2 .. ..$ dc: chr "eqdc10" .. ..$ ip: chr "10.0.0.2" $ title : chr "TOML Example" R> ``` See the other examples and the [upstream documentation](https://toml.io/en/) for more. Also note that most decent editors have proper [TOML](https://toml.io/en/) support which makes editing and previewing a breeze: ![](https://raw.githubusercontent.com/eddelbuettel/rcpptoml/master/local/emacsAndTOML.png) ### Installation The package is on [CRAN](https://cran.r-project.org) and can be installed from every mirror via ```{.r} install.packages("RcppTOML") ``` Development releases may be provided by the [ghrr](https://ghrr.github.io/drat/) repository which can accessed via ```{.r} ## if needed, first do: install.packages("drat") drat::addRepo("ghrr") ``` ### Status Feature-complete with [TOML v0.5.0](https://toml.io/en/v0.5.0), see the [tests/](https://github.com/eddelbuettel/rcpptoml/tree/master/tests) directory. It parses everything that the underlying [cpptoml](https://github.com/skystrife/cpptoml) parses with the same (sole) exception of unicode escape characters in strings. ### Installation The package is on [CRAN](https://cran.r-project.org) and can be installed via a standard ```r install.packages("RcppTOML") ``` ### Continued Testing As we rely on the [tinytest](https://cran.r-project.org/package=tinytest) package, the already-installed package can also be verified via ```r tinytest::test_package("RcppTOML") ``` at any later point. ### Author Dirk Eddelbuettel ### License GPL (>= 2) RcppTOML/man/0000755000176200001440000000000013366302666012440 5ustar liggesusersRcppTOML/man/RcppTOML-package.Rd0000644000176200001440000000243513761446065015725 0ustar liggesusers\name{RcppTOML-package} \alias{RcppTOML-package} \alias{RcppTOML} \docType{package} \title{ R Access to Parser for TOML (Tom's Obvious Markup Language) } \description{ TOML (\dQuote{Tom's Obvious Markup Language}) is a configuration file grammar for humans. It is easier to read and edit than the alternatives yet arguably more useful as it is stronly types: values come back as integer, double, (multiline-) character (strings), boolean or Datetime. Moreover, complex nesting and arrays are supported as well. } \details{ At present, a single parsing function \code{parseTOML} (with convenience aliases \code{tomlparse} and \code{parseToml}) is implemented. It returns a list object corresponding to the configuration from the supplied file. } \author{ Dirk Eddelbuettel put togther the R package. Charles Geigle wrote the cpptoml parser. Tom Preston-Werner is the Tom behind TOML. Maintainer: Dirk Eddelbuettel } \references{ TOML: \url{https://toml.io/en/} } \keyword{package} \examples{ library(RcppTOML) file <- system.file("toml", "example.toml", package="RcppTOML") toml <- parseTOML(file) # given file, return parsed object summary(toml) # really sparse summary method print(toml) # print is a wrapper around str() } RcppTOML/man/parseTOML.Rd0000644000176200001440000000661013761446050014533 0ustar liggesusers\name{parseTOML} \alias{parseTOML} \alias{tomlparse} \alias{parseToml} \alias{print.toml} \alias{summary.toml} \title{ Parse a TOML configuration file } \description{ The \code{parseTOML} function parses \sQuote{TOML} (for \sQuote{Tom's Obvious Markup Language}) files. The TOML format both highly readable and expressive, allows comments, indentation and other aspects suitable for \emph{human} readers, contains typed objects yet allows everything similar configuration languages permit. } \usage{ parseTOML(input, verbose = FALSE, fromFile=TRUE, includize=FALSE, escape=TRUE) \S3method{print}{toml} (x, ...) \S3method{summary}{toml} (object, ...) } \arguments{ \item{input}{A character object either denoting a path and file (where tilde-expansion is performed as well) from parsing from file, or a containing a suitable \sQuote{TOML} expression that is parsed from this expression.} \item{verbose}{A logical switch to turn on (very) verbose operation which can be useful in debugging a parsing issue in a file.} \item{fromFile}{A logical switch indicating whether \code{input} is interpreted as a filename (with path) which is to be parsed, or a whether the \sQuote{TOML} expression in the string is parsed; default is file mode.} \item{includize}{A logical switch indicating whether the \code{includize} stream buffer class for (non-standard but very useful) include statements should be used.} \item{escape}{A logical switch indicating whether special characters in strings (namely new line, double quotation mark and backslash) should be escaped in both printed output (when verbose = TRUE) and returned values or only in the printed output. Defaults to TRUE for the sake of backward compatibility.} \item{x}{A toml object.} \item{object}{A toml object.} \item{...}{Furter arguments.} } \details{ The package uses the \sQuote{cpptoml} C++11 parser by Charles Geigle. This requires a recent-enough C++11 compiler which excludes one deployed by Rtools on Windows at the time the package was initially put together. Following TOML specification this package assumes that any file input is a UTF-8 encoded text file. Any non-file input (when \code{fromFile = FALSE}) is converted to UTF-8 if necessary (using R's \code{enc2utf()}. Note that the conversion to UTF-8 may fail for input with "unknown" declared encoding if the true encoding does not match system's locale. } \value{ A \code{toml} object is returned, which is really just a list object with a class attribute to allow for \code{print} and \code{summary} methods. } \references{ TOML: \url{https://toml.io/en/} cpptoml: \url{https://github.com/skystrife/cpptoml} } \author{ Dirk Eddelbuettel put togther the R package. Charles Geigle wrote the cpptoml parser. Tom Preston-Werner is the Tom behind TOML. Maintainer: Dirk Eddelbuettel } \examples{ library(RcppTOML) file <- system.file("toml", "example.toml", package="RcppTOML") toml <- parseTOML(file) # given file, return parsed object summary(toml) # really sparse summary method print(toml) # print is a wrapper around str() txt <- "value='''\nHello\nWorld!'''" # input with \n is .. parseTOML(input = txt, fromFile = FALSE) # ... (doubly) escaped by default parseTOML(input = txt, fromFile = FALSE, escape = FALSE) # ... kept 'as is' } \keyword{package} RcppTOML/DESCRIPTION0000644000176200001440000000172013762016170013363 0ustar liggesusersPackage: RcppTOML Type: Package Title: 'Rcpp' Bindings to Parser for Tom's Obvious Markup Language Version: 0.1.7 Date: 2020-12-01 Author: Dirk Eddelbuettel Maintainer: Dirk Eddelbuettel Description: The configuration format defined by 'TOML' (which expands to "Tom's Obvious Markup Language") specifies an excellent format (described at ) suitable for both human editing as well as the common uses of a machine-readable format. This package uses 'Rcpp' to connect the 'cpptoml' parser written by Chase Geigle (in C++11) to R. SystemRequirements: A C++11 compiler; g++ (>= 4.9.*) or newer works. BugReports: https://github.com/eddelbuettel/rcpptoml/issues URL: http://dirk.eddelbuettel.com/code/rcpp.toml.html Imports: Rcpp (>= 0.11.5) Depends: R (>= 3.3.0) LinkingTo: Rcpp Suggests: tinytest License: GPL (>= 2) NeedsCompilation: yes Packaged: 2020-12-01 14:05:37 UTC; edd Repository: CRAN Date/Publication: 2020-12-02 23:00:08 UTC RcppTOML/tests/0000755000176200001440000000000013503466503013021 5ustar liggesusersRcppTOML/tests/tinytest.R0000644000176200001440000000070513503466503015031 0ustar liggesusers if (requireNamespace("tinytest", quietly=TRUE)) { ## Set a seed to make the test deterministic set.seed(42) ## there are several more granular ways to test files in a ## tinytest directory, see its package vignette; tests can also ## run once the package is installed using the same command ## we need version 0.9.4 or later if (packageVersion("tinytest") >= "0.9.4") { tinytest::test_package("RcppTOML") } } RcppTOML/src/0000755000176200001440000000000013761446661012457 5ustar liggesusersRcppTOML/src/parse.cpp0000644000176200001440000003114113761212746014270 0ustar liggesusers// -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; indent-tabs-mode: nil; -*- // // RcppTOML -- Rcpp bindings to TOML via cpptoml // // Copyright (C) 2015 - 2018 Dirk Eddelbuettel // // This file is part of RcppTOML // // RcppTOML is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 2 of the License, or // (at your option) any later version. // // RcppTOML is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with RcppTOML. If not, see . #include #include // include for the includize stream preprocessor // but don't use codecvt (g++-5 or later) #define INCLUDIZE_NO_CODECVT 1 #include // use the new vector which will be default by late 2017 #define RCPP_NEW_DATE_DATETIME_VECTORS 1 #include // this function is borrowed with credits from cpptoml :) std::string escapeString(const std::string& str) { std::string res; for (auto it = str.begin(); it != str.end(); ++it) { if (*it == '\\') res += "\\\\"; else if (*it == '"') res += "\\\""; else if (*it == '\n') res += "\\n"; else res += *it; } return res; } void printValue(std::ostream& o, const std::shared_ptr& base) { if (auto v = base->as()) { o << "{\"type\":\"string\",\"value\":\"" << escapeString(v->get()) << "\"}"; } else if (auto v = base->as()) { o << "{\"type\":\"integer\",\"value\":\"" << v->get() << "\"}"; } else if (auto v = base->as()) { o << "{\"type\":\"float\",\"value\":\"" << v->get() << "\"}"; } else if (auto v = base->as()) { o << "{\"type\":\"offset_datetime\",\"value\":\"" << v->get() << "\"}"; } else if (auto v = base->as()) { o << "{\"type\":\"local_datetime\",\"value\":\"" << v->get() << "\"}"; } else if (auto v = base->as()) { o << "{\"type\":\"local_date\",\"value\":\"" << v->get() << "\"}"; } else if (auto v = base->as()) { o << "{\"type\":\"bool\",\"value\":\"" //v->print(o); << v.get() << "\"}"; } } // cf 'man timegm' for the workaround on non-Linux systems inline time_t local_timegm(struct tm *tm) { #if defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) // and there may be more OSs that have timegm() ... return timegm(tm); #elif defined(__MINGW32__) || defined(__MINGW64__) return Rcpp::mktime00(*tm); // Rcpp exports a copy of the R-internal function #else char *tz = getenv("TZ"); if (tz) tz = strdup(tz); setenv("TZ", "", 1); tzset(); time_t ret = mktime(tm); if (tz) { setenv("TZ", tz, 1); free(tz); } else unsetenv("TZ"); tzset(); return ret; #endif } SEXP getValue(const std::shared_ptr& base, bool escape=true) { if (auto v = base->as()) { std::string s(v->get()); if (escape) { s = escapeString(s); } Rcpp::String se(s, CE_UTF8); return Rcpp::wrap(se); } else if (auto v = base->as()) { std::int64_t s(v->get()); int t = static_cast(s); // we need int for wrap to work return Rcpp::wrap(t); } else if (auto v = base->as()) { double s(v->get()); return Rcpp::wrap(s); } else if (auto v = base->as()) { bool s(v->get()); return Rcpp::wrap(s); } else if (auto v = base->as()) { cpptoml::local_date s(v->get()); Rcpp::Date d(s.year,s.month,s.day); return Rcpp::wrap(d); } else if (auto v = base->as()) { cpptoml::local_datetime s(v->get()); struct tm tm; tm.tm_year = s.year - 1900; tm.tm_mon = s.month - 1; tm.tm_mday = s.day; tm.tm_hour = s.hour; tm.tm_min = s.minute; tm.tm_sec = s.second; time_t tt = local_timegm(&tm); //tt = tt - s.hour_offset*60*60 - s.minute_offset*60; Rcpp::DatetimeVector dt(1, "UTC"); dt[0] = tt + s.microsecond * 1.0e-6; return Rcpp::wrap(dt); } else if (auto v = base->as()) { cpptoml::offset_datetime s(v->get()); struct tm tm; tm.tm_year = s.year - 1900; tm.tm_mon = s.month - 1; tm.tm_mday = s.day; tm.tm_hour = s.hour; tm.tm_min = s.minute; tm.tm_sec = s.second; time_t tt = local_timegm(&tm); tt = tt - s.hour_offset*60*60 - s.minute_offset*60; Rcpp::DatetimeVector dt(1, "UTC"); dt[0] = tt + s.microsecond * 1.0e-6; return Rcpp::wrap(dt); } else if (auto v = base->as()) { cpptoml::local_time t(v->get()); char txt[32]; if (t.microsecond != 0) { snprintf(txt, 31, "%02d:%02d:%02d.%d", t.hour, t.minute, t.second, t.microsecond); } else { snprintf(txt, 31, "%02d:%02d:%02d", t.hour, t.minute, t.second); } std::string s(txt); return Rcpp::wrap(s); } else { Rcpp::warning("Unparsed value, returning null"); return R_NilValue; } } void printArray(std::ostream& o, cpptoml::array& arr) { o << "{\"type\":\"array\",\"value\":["; auto it = arr.get().begin(); while (it != arr.get().end()) { if ((*it)->is_array()) printArray(o, *(*it)->as_array()); else printValue(o, *it); if (++it != arr.get().end()) o << ", "; } o << "]}"; } SEXP collapsedList(Rcpp::List ll) { if (ll.length() == 0) return R_NilValue; Rcpp::List::iterator it = ll.begin(); switch(TYPEOF(*it)) { case REALSXP: { Rcpp::NumericVector v(ll.begin(), ll.end()); Rcpp::RObject ro = ll[0]; if (ro.hasAttribute("class")) { Rcpp::CharacterVector cv = ro.attr("class"); if ((cv.size() == 1) && std::string(cv[0]) == "Date") { Rcpp::DateVector dv(v); return dv; } if ((cv.size() == 2) && std::string(cv[1]) == "POSIXt") { Rcpp::DatetimeVector dtv(v); return dtv; } } return v; break; // not reached ... } case INTSXP: { Rcpp::IntegerVector v(ll.begin(), ll.end()); return v; break; // not reached ... } case LGLSXP: { Rcpp::LogicalVector v(ll.begin(), ll.end()); return v; break; // not reached ... } case STRSXP: { // minor code smell that this is different :-/ int n = ll.size(); Rcpp::CharacterVector v(n); for (int i=0; i(ll[i]); Rcpp::String se(s, CE_UTF8); v[i] = se; } return v; break; // not reached ... } } return ll; } SEXP getArray(const cpptoml::array& arr, bool escape=true) { Rcpp::StretchyList sl; bool nonested = true; // ie no embedded array auto it = arr.get().begin(); while (it != arr.get().end()) { if ((*it)->is_array()) { sl.push_back(getArray(*(*it)->as_array(), escape)); nonested = false; } else { sl.push_back(getValue(*it, escape)); nonested = true; } it++; } if (nonested) { return collapsedList(Rcpp::as(sl)); } else { return Rcpp::as(sl); } } SEXP getTable(const std::shared_ptr& t, bool verbose=false, bool escape=true) { Rcpp::StretchyList sl; for (auto & p : *t) { if (p.second->is_table()) { auto ga = std::dynamic_pointer_cast(p.second); if (verbose) Rcpp::Rcout << "Table: " << p.first << std::endl; sl.push_back(Rcpp::Named(p.first) = getTable(ga, verbose, escape)); } else if (p.second->is_array()) { auto ga = std::dynamic_pointer_cast(p.second); if (verbose) { Rcpp::Rcout << "Array: " << p.first << std::endl; printArray(Rcpp::Rcout, *ga); } sl.push_back(Rcpp::Named(p.first) = getArray(*ga, escape)); } else if (p.second->is_value()) { if (verbose) { Rcpp::Rcout << "Value: " << p.first << "\n :"; printValue(Rcpp::Rcout, p.second); Rcpp::Rcout << std::endl; } sl.push_back(Rcpp::Named(p.first) = getValue(p.second, escape)); } else if (p.second->is_table_array()) { if (verbose) Rcpp::Rcout << "TableArray: " << p.first << std::endl; Rcpp::StretchyList l; auto arr = t->get_table_array(p.first)->get(); auto ait = arr.begin(); while (ait != arr.end()) { auto ta = std::dynamic_pointer_cast(*ait); l.push_back (getTable(ta, verbose, escape)); ++ait; } sl.push_back(Rcpp::Named(p.first) = Rcpp::as(l)); } else { if (verbose) Rcpp::Rcout << "Other: " << p.first << std::endl; sl.push_back(p.first); } } return Rcpp::as(sl); } // [[Rcpp::export]] Rcpp::List tomlparseImpl(const std::string input, bool verbose=false, bool fromfile=true, bool includize=false, bool escape=true) { if (fromfile && access(input.c_str(), R_OK)) { Rcpp::stop("Cannot read given file '" + input + "'."); } std::shared_ptr g; if (fromfile) { if (includize) { includize::toml_preprocessor pp(input.c_str()); cpptoml::parser included_parser(pp); g = included_parser.parse(); } else { g = cpptoml::parse_file(input.c_str()); } } else { std::stringstream strstream(input); cpptoml::parser p(strstream); g = p.parse(); } if (verbose) { Rcpp::Rcout << "\n" << (*g) << "\n" << std::endl; } Rcpp::StretchyList sl; for (auto & p : (*g)) { if (p.second->is_table_array()) { if (verbose) Rcpp::Rcout << "TableArray: " << p.first << std::endl; //auto ga = std::dynamic_pointer_cast(p.second); Rcpp::StretchyList l; auto arr = g->get_table_array(p.first)->get(); auto ait = arr.begin(); while (ait != arr.end()) { auto ta = std::dynamic_pointer_cast(*ait); l.push_back (getTable(ta, verbose, escape)); ++ait; } sl.push_back(Rcpp::Named(p.first) = Rcpp::as(l)); } else if (p.second->is_table()) { auto ga = std::dynamic_pointer_cast(p.second); if (verbose) Rcpp::Rcout << "Table: " << p.first << std::endl; sl.push_back(Rcpp::Named(p.first) = getTable(ga, verbose, escape)); } else if (p.second->is_array()) { auto ga = std::dynamic_pointer_cast(p.second); if (verbose) Rcpp::Rcout << "Array: " << p.first << std::endl; sl.push_back(Rcpp::Named(p.first) = getArray(*ga, escape)); } else if (p.second->is_value()) { if (verbose) { Rcpp::Rcout << "Value: " << p.first << "\n :"; printValue(Rcpp::Rcout, p.second); Rcpp::Rcout << std::endl; } sl.push_back(Rcpp::Named(p.first) = getValue(p.second, escape)); } else { if (verbose) Rcpp::Rcout << "Other: " << p.first << std::endl; sl.push_front(p.first); } } return Rcpp::as(sl); } RcppTOML/src/Makevars0000644000176200001440000000022612541011572014133 0ustar liggesusers ## This is a C++11 package CXX_STD = CXX11 ## We need the header in inst/include, and a define PKG_CPPFLAGS = -I../inst/include/ -DCPPTOML_USE_MAP RcppTOML/src/Makevars.win0000644000176200001440000000022513033264130014723 0ustar liggesusers ## This is a C++11 package CXX_STD = CXX11 ## We need the header in inst/include, and a define PKG_CPPFLAGS = -I../inst/include/ -DCPPTOML_USE_MAP RcppTOML/src/RcppExports.cpp0000644000176200001440000000242413364317332015445 0ustar liggesusers// Generated by using Rcpp::compileAttributes() -> do not edit by hand // Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 #include using namespace Rcpp; // tomlparseImpl Rcpp::List tomlparseImpl(const std::string input, bool verbose, bool fromfile, bool includize, bool escape); RcppExport SEXP _RcppTOML_tomlparseImpl(SEXP inputSEXP, SEXP verboseSEXP, SEXP fromfileSEXP, SEXP includizeSEXP, SEXP escapeSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< const std::string >::type input(inputSEXP); Rcpp::traits::input_parameter< bool >::type verbose(verboseSEXP); Rcpp::traits::input_parameter< bool >::type fromfile(fromfileSEXP); Rcpp::traits::input_parameter< bool >::type includize(includizeSEXP); Rcpp::traits::input_parameter< bool >::type escape(escapeSEXP); rcpp_result_gen = Rcpp::wrap(tomlparseImpl(input, verbose, fromfile, includize, escape)); return rcpp_result_gen; END_RCPP } static const R_CallMethodDef CallEntries[] = { {"_RcppTOML_tomlparseImpl", (DL_FUNC) &_RcppTOML_tomlparseImpl, 5}, {NULL, NULL, 0} }; RcppExport void R_init_RcppTOML(DllInfo *dll) { R_registerRoutines(dll, NULL, CallEntries, NULL, NULL); R_useDynamicSymbols(dll, FALSE); } RcppTOML/R/0000755000176200001440000000000013364713045012061 5ustar liggesusersRcppTOML/R/parseToml.R0000644000176200001440000000316713364713045014161 0ustar liggesusers## RcppTOML -- Rcpp bindings to TOML via cpptoml ## ## Copyright (C) 2015 - 2017 Dirk Eddelbuettel ## ## This file is part of RcppTOML. ## ## RcppTOML is free software: you can redistribute it and/or modify it ## under the terms of the GNU General Public License as published by ## the Free Software Foundation, either version 2 of the License, or ## (at your option) any later version. ## ## RcppTOML is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with RcppTOML. If not, see . parseTOML <- function(input, verbose=FALSE, fromFile=TRUE, includize=FALSE, escape=TRUE) { if (fromFile) { toml <- tomlparseImpl(path.expand(input), verbose, fromFile, includize, escape) } else { toml <- tomlparseImpl(enc2utf8(input), verbose, fromFile, includize, escape) } class(toml) <- c("toml", "list") attr(toml, "file") <- input toml } ## alias for now, to be renamed tomlparse <- function(...) parseTOML(...) ## alias for now, to be renamed parseToml <- function(...) parseTOML(...) print.toml <- function(x, ...) { cat(utils::str(x, give.attr=FALSE)) # convenient shortcut invisible(x) } summary.toml <- function(object, ...) { cat("toml object with top-level slots:\n") cat(" ", paste(names(object), collapse=", "), "\n") cat("read from '", attr(object, "file"), "'\n") invisible(NULL) } RcppTOML/R/RcppExports.R0000644000176200001440000000047313364317332014500 0ustar liggesusers# Generated by using Rcpp::compileAttributes() -> do not edit by hand # Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 tomlparseImpl <- function(input, verbose = FALSE, fromfile = TRUE, includize = FALSE, escape = TRUE) { .Call(`_RcppTOML_tomlparseImpl`, input, verbose, fromfile, includize, escape) } RcppTOML/MD50000644000176200001440000000470713762016170012175 0ustar liggesusersaab55d488ef939760488be84d5df251c *ChangeLog 467940547ac83ea28e1c5d9d09702b9c *DESCRIPTION 8695c7fd3ad2d90aca32137a3da7c0f1 *NAMESPACE 54a43910c0a0025b64ff07be7af1fd1a *R/RcppExports.R 844fe80599f25e7a2c7808c616718b1c *R/parseToml.R be87c5220c1aaf193b4d4b78781c201f *README.md 314cee712fb09b8346fe804ccb77076d *cleanup 0875838795ab1a91b0c8df9db2cfbcb4 *inst/NEWS.Rd b96ead9efdee19ad150d7830dba18adc *inst/include/cpptoml.h 1d7c49a963cc17752988c43946b05323 *inst/include/includize.hpp 3646ebd84baa1af2574dd87462ee9fa2 *inst/include/toml.hpp 4c0ba4af235fa244e3d888dc3153a392 *inst/tinytest/arrays.toml b35a7d3d1188f852df79cb56b45f057f *inst/tinytest/bool_datetime.toml 5747cdac9b493a928d5125cc7da481b4 *inst/tinytest/dates_and_times.toml 98c15766ffcfd93f81fcbba3e6fdb1f2 *inst/tinytest/float.toml edbf0dd24dae72644d2e0a73c10e1acb *inst/tinytest/integer.toml 8ff7997c82e35bda88ff8f33354b5b3a *inst/tinytest/strings.toml 5072b4d7309d7e7e4129dd78f6b6aab4 *inst/tinytest/tables.toml c6d9e29d5382633665e03b3114d6e62a *inst/tinytest/test_arrays.R c1eb543fa0328245a1551ea3df8189b0 *inst/tinytest/test_bool_datetime.R 5ab7808d55516e8a8b19012487b5e79b *inst/tinytest/test_dates_times.R 8bf020278b87d31c66b5e22b3304cb64 *inst/tinytest/test_examples.R 855cc8bd6b5595d862c5388e19475246 *inst/tinytest/test_float.R 8a188b4f4d40b43425f3398081368495 *inst/tinytest/test_integer.R 6d56b25e217f030bff6c968b029fa15d *inst/tinytest/test_misc.R 10177b21356907e2458a4c98ba71dd12 *inst/tinytest/test_strings.R d9c95b12e5f2cf286308c0a4eb1b34fd *inst/tinytest/test_tables.R 1258c54536c3ac3b109ac6838a6a1ee7 *inst/tinytest/toml_example-v0.4.0.toml 7ac85a8fc59c76ee1a3cf2e31968435e *inst/tinytest/toml_example.toml a771cda2fd660a0725c6491f6de8eb70 *inst/tinytest/toml_hard_example.toml 2f404e57fbf1e01e8c5da012b9fd7dd2 *inst/toml/ex1.toml 2edae36993ce3b693fe0af875dfa70b7 *inst/toml/ex2.toml 8ba4380f4291ebe34e854796c235a065 *inst/toml/ex3.toml a13dbf43f65e66db58d19a295d4b4035 *inst/toml/ex4.toml 5a81a94db8bb8a98e76dd6a6f574ddb6 *inst/toml/example.toml ab88821b38f109c60f8ee59919891348 *inst/toml/strings.toml 525cecb569e337e4d4f173c4b37e097f *inst/toml/tablearray.toml e1418805ae3593051cecc5e1efe23b9d *man/RcppTOML-package.Rd 2ecb3c53a5fea5d0b877f25281950dbf *man/parseTOML.Rd 478972599843c382d7c8884481b84c9b *src/Makevars 8e4745642644de963fbb3588902356b3 *src/Makevars.win 15887f628ac5da366c73f5eea217f042 *src/RcppExports.cpp 97800ebe190effeb6be6758e7f5c3cc4 *src/parse.cpp 12692a8d99291385743163b4d9ad7fc9 *tests/tinytest.R RcppTOML/inst/0000755000176200001440000000000013761443540012636 5ustar liggesusersRcppTOML/inst/toml/0000755000176200001440000000000013363430014013577 5ustar liggesusersRcppTOML/inst/toml/strings.toml0000644000176200001440000000054412510065505016172 0ustar liggesusers# From https://github.com/toml-lang/toml/blob/master/versions/en/toml-v0.4.0.md # The following strings are byte-for-byte equivalent: key1 = "The quick brown fox jumps over the lazy dog." key2 = """ The quick brown \ fox jumps over \ the lazy dog.""" key3 = """\ The quick brown \ fox jumps over \ the lazy dog.\ """ RcppTOML/inst/toml/ex4.toml0000644000176200001440000000043113065732447015210 0ustar liggesusers [secA] foo = [ 1, 2, 3 ] bar = [ 1.1, 2.2, 3.3 ] biz = [ "1", "2", "3" ] bla = [ 1979-05-27T07:32:00Z, 1979-05-28T07:32:00Z ] [secA.subA] bar = 1 biz = 7 [secA.subA.subsubA] bing = 22 bong = 33 [secA.subB] gin = 102 fizz = 99 [final] allgood = true RcppTOML/inst/toml/ex2.toml0000644000176200001440000000057313043476757015222 0ustar liggesusers# This is a document # # Printing is in reverse title = "Some text for title" fltnum = 3.14 boolval = true intnum = 42 dattim = 2015-03-28T16:35:01.123456Z # does now work: dat = 2015-03-28 [dateSection] date1 = 1979-05-27T07:32:00Z date2 = 1979-05-27T00:32:00-07:00 date3 = 1979-05-27T00:32:00.999999-07:00 date4 = 1979-05-27T07:32:00 date5 = 1979-05-27T07:32:00.999999 RcppTOML/inst/toml/tablearray.toml0000644000176200001440000000030712510065505016624 0ustar liggesusers# From https://github.com/toml-lang/toml/blob/master/versions/en/toml-v0.4.0.md [[products]] name = "Hammer" sku = 738594937 [[products]] [[products]] name = "Nail" sku = 284758393 color = "gray" RcppTOML/inst/toml/example.toml0000644000176200001440000000104113065733746016144 0ustar liggesusers# This is a TOML document. title = "TOML Example" [owner] name = "Tom Preston-Werner" dob = 1979-05-27T07:32:00-08:00 # First class dates [database] server = "192.168.1.1" ports = [ 8001, 8001, 8002 ] connection_max = 5000 enabled = true [servers] # Indentation (tabs and/or spaces) is allowed but not required [servers.alpha] ip = "10.0.0.1" dc = "eqdc10" [servers.beta] ip = "10.0.0.2" dc = "eqdc10" [clients] data = [ ["gamma", "delta"], [1, 2] ] # Line breaks are OK when inside arrays hosts = [ "alpha", "omega" ] RcppTOML/inst/toml/ex3.toml0000644000176200001440000000041512510065505015175 0ustar liggesusers ## An int array xint = [ 1, 2, 3 ] ## A double array yflt = [ 1.1, 2.2, 3.3 ] ## A char array ztxt = [ "the", "quick", "brown", "fox" ] ## No logical array ## A nested array aa = [ [ 1, 2], [ 3, 4] ] ## A twice nested array bb = [ [ 1, 2], [ [3, 4], [5, 6 ] ] ] RcppTOML/inst/toml/ex1.toml0000644000176200001440000000067212510065505015200 0ustar liggesusers# This is a document # # Printing is in reverse title = "Some text for title" fltnum = 3.14 boolval = true intnum = 42 [secA] aaa = "1" bbb = "2" ccc = "3" [secB] ## NB these don't seem to come in a integers aaa = 1 bbb = 2 ccc = 3 [secC] aaa = 1.1 bbb = 2.2 ccc = 3.3 [secD] foo = [ 1, 2, 3 ] bar = [ 1.1, 2.2, 3.3 ] biz = [ "1", "2", "3" ] # bla = [ 1979-05-27T07:32:00Z, 1979-05-28T07:32:00Z ] [secD.subA] bar = 1 biz = 7 RcppTOML/inst/include/0000755000176200001440000000000013761206352014257 5ustar liggesusersRcppTOML/inst/include/includize.hpp0000644000176200001440000002730613343012013016747 0ustar liggesusers#ifndef INCLUDIZE_HPP #define INCLUDIZE_HPP #include #include #include #include #include #include #include #if !defined(INCLUDIZE_NO_CODECVT) #include #endif namespace includize // #nocov start { template< typename INCLUDE_SPEC, typename CHAR_T, typename TRAITS = std::char_traits< CHAR_T > > class basic_streambuf : public std::basic_streambuf< CHAR_T, TRAITS > { public: using include_spec_type = INCLUDE_SPEC; using base_type = typename std::basic_streambuf< CHAR_T, TRAITS >; using char_type = typename base_type::char_type; using traits_type = typename base_type::traits_type; using int_type = typename base_type::int_type; using pos_type = typename base_type::pos_type; using off_type = typename base_type::off_type; using istream_type = typename std::basic_istream< char_type, traits_type >; using ifstream_type = typename std::basic_ifstream< char_type, traits_type >; using string_type = typename std::basic_string< char_type, traits_type >; using regex_type = typename std::basic_regex< char_type >; using regex_match_type = typename std::match_results< typename string_type::const_iterator >; public: basic_streambuf(std::basic_istream< char_type, traits_type > &s, const std::string &path = "") : stream_(s) , included_file_(NULL) , included_file_pp_(NULL) , included_stream_(NULL) { base_type::setg(nullptr, nullptr, nullptr); path_ = path; if (path.size() && !(*path.rbegin() == '/')) { path_ += "/"; } } basic_streambuf(basic_streambuf &&) = default; basic_streambuf(basic_streambuf &) = delete; ~basic_streambuf() { remove_included_stream(); } protected: int_type underflow() override { buffer_next(); if (!included_buffer_.empty()) { return *included_buffer_.begin(); } else if (!buffer_.empty()) { int_type c = *buffer_.begin(); buffer_.erase(buffer_.begin()); if (check_for_include(c)) { return buffer_next(); } else { buffer_.insert(0, 1, static_cast< char_type >(c)); if (buffer_.empty()) { buffer_next(); } return c; } return *buffer_.begin(); } return traits_type::eof(); } int_type uflow() override { underflow(); if (!included_buffer_.empty()) { int_type c = *included_buffer_.begin(); included_buffer_.erase(included_buffer_.begin()); if (included_buffer_.empty()) { underflow(); } return c; } if (!buffer_.empty()) { int_type c = *buffer_.begin(); buffer_.erase(buffer_.begin()); if (check_for_include(c)) { return uflow(); } else { if (buffer_.empty()) { buffer_next(); } return c; } } return traits_type::eof(); } private: int_type buffer_next() { if (included_file_pp_) { int_type c = included_stream_->get(); if (c != traits_type::eof()) { included_buffer_.push_back(c); return *included_buffer_.begin(); } remove_included_stream(); } int_type c = get_next_from_stream(); if (c != traits_type::eof()) { buffer_.push_back(c); return *buffer_.begin(); } assert(c == traits_type::eof()); return c; } int_type get_next_from_stream() { if (stream_.good()) { const int_type c = stream_.get(); return c; } return traits_type::eof(); } void remove_included_stream() { if (included_file_pp_) { delete included_stream_; delete included_file_pp_; delete included_file_; included_stream_ = nullptr; included_file_pp_ = nullptr; included_file_ = nullptr; } } bool open_included_stream(const string_type &file_name) { std::string name = convert_file_name(file_name); std::string path = get_file_path(name); if (name[0] != '/') { name = path_ + name; } included_file_ = new ifstream_type(name.c_str(), std::ios::in | std::ios::binary); prepare_include_stream(*included_file_); included_file_pp_ = new basic_streambuf(*included_file_, path); included_stream_ = new istream_type(included_file_pp_); if (included_stream_->good()) { buffer_next(); return true; } return false; } void buffer_line_from_stream() { do { int_type c = get_next_from_stream(); if (c == traits_type::eof()) { break; } else if (static_cast< char_type >(c) != stream_.widen('\n')) { buffer_.push_back(c); } else { buffer_.push_back(c); break; } } while (true); } bool check_for_include(int_type c) { if (c == include_spec_type::header_start()) { string_type line; typename string_type::size_type pos = string_type::npos; if (!buffer_.empty()) { pos = buffer_.find(stream_.widen('\n')); if (pos != string_type::npos) { line = buffer_.substr(0, pos); } else { buffer_line_from_stream(); line = buffer_; } } else { buffer_line_from_stream(); line = buffer_; } regex_match_type match; if (std::regex_search(line, match, regex_type(include_spec_type::regex()))) { string_type file_name = match[include_spec_type::file_name_index()]; if (pos != string_type::npos && pos < buffer_.size()) { buffer_.erase(0, pos); } else { buffer_.clear(); } if (!include_spec_type::discard_characters_after_include()) { buffer_ += match.suffix(); } return open_included_stream(file_name); } } return false; } void prepare_include_stream(ifstream_type &s) { s.imbue(stream_.getloc()); } #if !defined(INCLUDIZE_NO_CODECVT) template< typename T, typename TTRAITS > typename std::enable_if< sizeof(char) != sizeof(T), std::string >::type convert_file_name(const std::basic_string< T, TTRAITS > &file_name) { std::wstring_convert< std::codecvt_utf8_utf16< wchar_t >, wchar_t > converter; return include_spec_type::unescape_filename(converter.to_bytes(file_name)); } #endif template< typename T, typename TTRAITS > typename std::enable_if< sizeof(char) == sizeof(T), std::string >::type convert_file_name(const std::basic_string< T, TTRAITS > &file_name) { return include_spec_type::unescape_filename(file_name); } std::string get_file_path(const std::string file_name) { if (file_name.length()) { std::string::size_type pos = file_name.rfind("/"); std::string path = (pos != std::string::npos) ? file_name.substr(0, pos + 1) : ""; return (file_name[0] != '/') ? path_ + path : path; } return ""; } private: istream_type &stream_; ifstream_type *included_file_; basic_streambuf *included_file_pp_; istream_type *included_stream_; string_type included_buffer_; string_type buffer_; std::string path_; }; template< typename INCLUDE_SPEC > using streambuf = basic_streambuf< INCLUDE_SPEC, char >; #if !defined(INCLUDIZE_NO_CODECVT) template< typename INCLUDE_SPEC > using wstreambuf = basic_streambuf< INCLUDE_SPEC, wchar_t >; #endif template< typename INCLUDE_SPEC, typename CHAR_T, typename TRAITS = std::char_traits< CHAR_T > > class basic_preprocessor { public: using include_spec_type = INCLUDE_SPEC; using char_type = CHAR_T; using traits_type = TRAITS; using istream_type = typename std::basic_istream< char_type, traits_type >; using ifstream_type = typename std::basic_ifstream< char_type, traits_type >; using streambuf_type = basic_streambuf< include_spec_type, char_type, traits_type >; public: basic_preprocessor(const std::string &file_name) { std::string path = ""; if (file_name[0] != '/') { char buf[8192]; if (getcwd(buf, 8192)) { std::string path = buf; if (*path.rbegin() != '/') { path += '/'; } } } path += extract_path(file_name); fstream_.reset(new ifstream_type(file_name.c_str(), std::ios::in | std::ios::binary)); prepare_ifstream(*fstream_); streambuf_.reset(new streambuf_type(*fstream_, path)); stream_.reset(new istream_type(streambuf_.get())); } istream_type &stream() { return *stream_; } operator istream_type &() { return *stream_; } private: static std::string extract_path(const std::string file_name) { std::string::size_type pos = file_name.rfind("/"); std::string path = (pos != std::string::npos) ? file_name.substr(0, pos + 1) : ""; return path; } #if !defined(INCLUDIZE_NO_CODECVT) template< typename T, typename TTRAITS > static typename std::enable_if< sizeof(char) != sizeof(T), void >::type prepare_ifstream(std::basic_ifstream< T, TTRAITS > &s) { s.imbue(std::locale(s.getloc(), new std::codecvt_utf16< wchar_t, 0x10ffff, std::consume_header >)); } #endif template< typename T, typename TTRAITS > static typename std::enable_if< sizeof(char) == sizeof(T), void >::type prepare_ifstream(std::basic_ifstream< T, TTRAITS > &s) { } std::unique_ptr< istream_type > stream_; std::unique_ptr< ifstream_type > fstream_; std::unique_ptr< streambuf_type > streambuf_; }; template< typename INCLUDE_SPEC > using preprocessor = basic_preprocessor< INCLUDE_SPEC, char >; #if !defined(INCLUDIZE_NO_CODECVT) template< typename INCLUDE_SPEC > using wpreprocessor = basic_preprocessor< INCLUDE_SPEC, wchar_t >; #endif } // #nocov end #endif RcppTOML/inst/include/toml.hpp0000644000176200001440000000373613343012013015735 0ustar liggesusers#ifndef INCLUDIZE_TOML_HPP #define INCLUDIZE_TOML_HPP #include "includize.hpp" #include namespace includize // #nocov start { template< typename CHAR_TYPE > struct toml_spec { }; template<> struct toml_spec< char > { static constexpr char header_start() { return '#'; } static constexpr const char *regex() { return R"..(\s*\[\[include\s*"(([^"]|\")+)"\s*]]).."; } static constexpr std::size_t file_name_index() { return 1; }; static constexpr bool discard_characters_after_include() { return true; } static std::string unescape_filename(const std::string &str) { return std::regex_replace(str, std::regex("\\\\\""), "\""); } }; #if !defined(INCLUDIZE_NO_CODECVT) template<> struct toml_spec< wchar_t > { static constexpr wchar_t header_start() { return L'#'; } static constexpr const wchar_t *regex() { return LR"..(\s*\[\[include\s*"(([^"]|\")+)"\s*]]).."; } static constexpr std::size_t file_name_index() { return 1; }; static constexpr bool discard_characters_after_include() { return true; } static std::string unescape_filename(const std::string &str) { return std::regex_replace(str, std::regex("\\\\\""), "\""); } }; #endif template< typename CHAR_T, typename TRAITS = std::char_traits< CHAR_T > > using basic_toml_streambuf = basic_streambuf< toml_spec< CHAR_T >, CHAR_T, TRAITS >; using toml_streambuf = basic_toml_streambuf< char >; #if !defined(INCLUDIZE_NO_CODECVT) using wtoml_streambuf = basic_toml_streambuf< wchar_t >; #endif template< typename CHAR_T, typename TRAITS = std::char_traits< CHAR_T > > using basic_toml_preprocessor = basic_preprocessor< toml_spec< CHAR_T >, CHAR_T, TRAITS >; using toml_preprocessor = basic_toml_preprocessor< char >; #if !defined(INCLUDIZE_NO_CODECVT) using wtoml_preprocessor = basic_toml_preprocessor< wchar_t >; #endif } // namespace includize // #nocov end #endif RcppTOML/inst/include/cpptoml.h0000644000176200001440000027366513761206352016131 0ustar liggesusers/** * @file cpptoml.h * @author Chase Geigle * @date May 2013 */ #ifndef CPPTOML_H #define CPPTOML_H #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if __cplusplus > 201103L #define CPPTOML_DEPRECATED(reason) [[deprecated(reason)]] #elif defined(__clang__) #define CPPTOML_DEPRECATED(reason) __attribute__((deprecated(reason))) #elif defined(__GNUG__) #define CPPTOML_DEPRECATED(reason) __attribute__((deprecated)) #elif defined(_MSC_VER) #if _MSC_VER < 1910 #define CPPTOML_DEPRECATED(reason) __declspec(deprecated) #else #define CPPTOML_DEPRECATED(reason) [[deprecated(reason)]] #endif #endif namespace cpptoml { class writer; // forward declaration class base; // forward declaration #if defined(CPPTOML_USE_MAP) // a std::map will ensure that entries a sorted, albeit at a slight // performance penalty relative to the (default) unordered_map using string_to_base_map = std::map>; #else // by default an unordered_map is used for best performance as the // toml specification does not require entries to be sorted using string_to_base_map = std::unordered_map>; #endif // if defined, `base` will retain type information in form of an enum class // such that static_cast can be used instead of dynamic_cast // #define CPPTOML_NO_RTTI template class option { public: option() : empty_{true} { // nothing } option(T value) : empty_{false}, value_(std::move(value)) { // nothing } explicit operator bool() const { return !empty_; } const T& operator*() const { return value_; } const T* operator->() const { return &value_; } template T value_or(U&& alternative) const { if (!empty_) return value_; return static_cast(std::forward(alternative)); } private: bool empty_; T value_; }; struct local_date { int year = 0; int month = 0; int day = 0; }; struct local_time { int hour = 0; int minute = 0; int second = 0; int microsecond = 0; }; struct zone_offset { int hour_offset = 0; int minute_offset = 0; }; struct local_datetime : local_date, local_time { }; struct offset_datetime : local_datetime, zone_offset { static inline struct offset_datetime from_zoned(const struct tm& t) { offset_datetime dt; dt.year = t.tm_year + 1900; dt.month = t.tm_mon + 1; dt.day = t.tm_mday; dt.hour = t.tm_hour; dt.minute = t.tm_min; dt.second = t.tm_sec; char buf[16]; strftime(buf, 16, "%z", &t); int offset = std::stoi(buf); dt.hour_offset = offset / 100; dt.minute_offset = offset % 100; return dt; } CPPTOML_DEPRECATED("from_local has been renamed to from_zoned") static inline struct offset_datetime from_local(const struct tm& t) { return from_zoned(t); } static inline struct offset_datetime from_utc(const struct tm& t) { offset_datetime dt; dt.year = t.tm_year + 1900; dt.month = t.tm_mon + 1; dt.day = t.tm_mday; dt.hour = t.tm_hour; dt.minute = t.tm_min; dt.second = t.tm_sec; return dt; } }; CPPTOML_DEPRECATED("datetime has been renamed to offset_datetime") typedef offset_datetime datetime; class fill_guard { public: fill_guard(std::ostream& os) : os_(os), fill_{os.fill()} { // nothing } ~fill_guard() { os_.fill(fill_); } private: std::ostream& os_; std::ostream::char_type fill_; }; inline std::ostream& operator<<(std::ostream& os, const local_date& dt) { fill_guard g{os}; os.fill('0'); using std::setw; os << setw(4) << dt.year << "-" << setw(2) << dt.month << "-" << setw(2) << dt.day; return os; } inline std::ostream& operator<<(std::ostream& os, const local_time& ltime) { fill_guard g{os}; os.fill('0'); using std::setw; os << setw(2) << ltime.hour << ":" << setw(2) << ltime.minute << ":" << setw(2) << ltime.second; if (ltime.microsecond > 0) { os << "."; int power = 100000; for (int curr_us = ltime.microsecond; curr_us; power /= 10) { auto num = curr_us / power; os << num; curr_us -= num * power; } } return os; } inline std::ostream& operator<<(std::ostream& os, const zone_offset& zo) { fill_guard g{os}; os.fill('0'); using std::setw; if (zo.hour_offset != 0 || zo.minute_offset != 0) { if (zo.hour_offset > 0) { os << "+"; } else { os << "-"; } os << setw(2) << std::abs(zo.hour_offset) << ":" << setw(2) << std::abs(zo.minute_offset); } else { os << "Z"; } return os; } inline std::ostream& operator<<(std::ostream& os, const local_datetime& dt) { return os << static_cast(dt) << "T" << static_cast(dt); } inline std::ostream& operator<<(std::ostream& os, const offset_datetime& dt) { return os << static_cast(dt) << static_cast(dt); } template struct is_one_of; template struct is_one_of : std::is_same { }; template struct is_one_of { const static bool value = std::is_same::value || is_one_of::value; }; template class value; template struct valid_value : is_one_of { }; template struct value_traits; template struct valid_value_or_string_convertible { const static bool value = valid_value::type>::value || std::is_convertible::value; }; template struct value_traits::value>::type> { using value_type = typename std::conditional< valid_value::type>::value, typename std::decay::type, std::string>::type; using type = value; static value_type construct(T&& val) { return value_type(val); } }; template struct value_traits< T, typename std::enable_if< !valid_value_or_string_convertible::value && std::is_floating_point::type>::value>::type> { using value_type = typename std::decay::type; using type = value; static value_type construct(T&& val) { return value_type(val); } }; template struct value_traits< T, typename std::enable_if< !valid_value_or_string_convertible::value && !std::is_floating_point::type>::value && std::is_signed::type>::value>::type> { using value_type = int64_t; using type = value; static value_type construct(T&& val) { if (val < (std::numeric_limits::min)()) throw std::underflow_error{"constructed value cannot be " "represented by a 64-bit signed " "integer"}; if (val > (std::numeric_limits::max)()) throw std::overflow_error{"constructed value cannot be represented " "by a 64-bit signed integer"}; return static_cast(val); } }; template struct value_traits< T, typename std::enable_if< !valid_value_or_string_convertible::value && std::is_unsigned::type>::value>::type> { using value_type = int64_t; using type = value; static value_type construct(T&& val) { if (val > static_cast((std::numeric_limits::max)())) throw std::overflow_error{"constructed value cannot be represented " "by a 64-bit signed integer"}; return static_cast(val); } }; class array; class table; class table_array; template struct array_of_trait { using return_type = option>; }; template <> struct array_of_trait { using return_type = option>>; }; template inline std::shared_ptr::type> make_value(T&& val); inline std::shared_ptr make_array(); namespace detail { template inline std::shared_ptr make_element(); } inline std::shared_ptr make_table(); inline std::shared_ptr make_table_array(bool is_inline = false); #if defined(CPPTOML_NO_RTTI) /// Base type used to store underlying data type explicitly if RTTI is disabled enum class base_type { NONE, STRING, LOCAL_TIME, LOCAL_DATE, LOCAL_DATETIME, OFFSET_DATETIME, INT, FLOAT, BOOL, TABLE, ARRAY, TABLE_ARRAY }; /// Type traits class to convert C++ types to enum member template struct base_type_traits; template <> struct base_type_traits { static const base_type type = base_type::STRING; }; template <> struct base_type_traits { static const base_type type = base_type::LOCAL_TIME; }; template <> struct base_type_traits { static const base_type type = base_type::LOCAL_DATE; }; template <> struct base_type_traits { static const base_type type = base_type::LOCAL_DATETIME; }; template <> struct base_type_traits { static const base_type type = base_type::OFFSET_DATETIME; }; template <> struct base_type_traits { static const base_type type = base_type::INT; }; template <> struct base_type_traits { static const base_type type = base_type::FLOAT; }; template <> struct base_type_traits { static const base_type type = base_type::BOOL; }; template <> struct base_type_traits
{ static const base_type type = base_type::TABLE; }; template <> struct base_type_traits { static const base_type type = base_type::ARRAY; }; template <> struct base_type_traits { static const base_type type = base_type::TABLE_ARRAY; }; #endif /** * A generic base TOML value used for type erasure. */ class base : public std::enable_shared_from_this { public: virtual ~base() = default; virtual std::shared_ptr clone() const = 0; /** * Determines if the given TOML element is a value. */ virtual bool is_value() const { return false; } /** * Determines if the given TOML element is a table. */ virtual bool is_table() const { return false; } /** * Converts the TOML element into a table. */ std::shared_ptr
as_table() { if (is_table()) return std::static_pointer_cast
(shared_from_this()); return nullptr; } /** * Determines if the TOML element is an array of "leaf" elements. */ virtual bool is_array() const { return false; } /** * Converts the TOML element to an array. */ std::shared_ptr as_array() { if (is_array()) return std::static_pointer_cast(shared_from_this()); return nullptr; } /** * Determines if the given TOML element is an array of tables. */ virtual bool is_table_array() const { return false; } /** * Converts the TOML element into a table array. */ std::shared_ptr as_table_array() { if (is_table_array()) return std::static_pointer_cast(shared_from_this()); return nullptr; } /** * Attempts to coerce the TOML element into a concrete TOML value * of type T. */ template std::shared_ptr> as(); template std::shared_ptr> as() const; template void accept(Visitor&& visitor, Args&&... args) const; #if defined(CPPTOML_NO_RTTI) base_type type() const { return type_; } protected: base(const base_type t) : type_(t) { // nothing } private: const base_type type_ = base_type::NONE; #else protected: base() { // nothing } #endif }; /** * A concrete TOML value representing the "leaves" of the "tree". */ template class value : public base { struct make_shared_enabler { // nothing; this is a private key accessible only to friends }; template friend std::shared_ptr::type> cpptoml::make_value(U&& val); public: static_assert(valid_value::value, "invalid value type"); std::shared_ptr clone() const override; value(const make_shared_enabler&, const T& val) : value(val) { // nothing; note that users cannot actually invoke this function // because they lack access to the make_shared_enabler. } bool is_value() const override { return true; } /** * Gets the data associated with this value. */ T& get() { return data_; } /** * Gets the data associated with this value. Const version. */ const T& get() const { return data_; } private: T data_; /** * Constructs a value from the given data. */ #if defined(CPPTOML_NO_RTTI) value(const T& val) : base(base_type_traits::type), data_(val) { } #else value(const T& val) : data_(val) { } #endif value(const value& val) = delete; value& operator=(const value& val) = delete; }; template std::shared_ptr::type> make_value(T&& val) { using value_type = typename value_traits::type; using enabler = typename value_type::make_shared_enabler; return std::make_shared( enabler{}, value_traits::construct(std::forward(val))); } template inline std::shared_ptr> base::as() { #if defined(CPPTOML_NO_RTTI) if (type() == base_type_traits::type) return std::static_pointer_cast>(shared_from_this()); else return nullptr; #else return std::dynamic_pointer_cast>(shared_from_this()); #endif } // special case value to allow getting an integer parameter as a // double value template <> inline std::shared_ptr> base::as() { #if defined(CPPTOML_NO_RTTI) if (type() == base_type::FLOAT) return std::static_pointer_cast>(shared_from_this()); if (type() == base_type::INT) { auto v = std::static_pointer_cast>(shared_from_this()); return make_value(static_cast(v->get())); } #else if (auto v = std::dynamic_pointer_cast>(shared_from_this())) return v; if (auto v = std::dynamic_pointer_cast>(shared_from_this())) return make_value(static_cast(v->get())); #endif return nullptr; } template inline std::shared_ptr> base::as() const { #if defined(CPPTOML_NO_RTTI) if (type() == base_type_traits::type) return std::static_pointer_cast>(shared_from_this()); else return nullptr; #else return std::dynamic_pointer_cast>(shared_from_this()); #endif } // special case value to allow getting an integer parameter as a // double value template <> inline std::shared_ptr> base::as() const { #if defined(CPPTOML_NO_RTTI) if (type() == base_type::FLOAT) return std::static_pointer_cast>( shared_from_this()); if (type() == base_type::INT) { auto v = as(); // the below has to be a non-const value due to a bug in // libc++: https://llvm.org/bugs/show_bug.cgi?id=18843 return make_value(static_cast(v->get())); } #else if (auto v = std::dynamic_pointer_cast>(shared_from_this())) return v; if (auto v = as()) { // the below has to be a non-const value due to a bug in // libc++: https://llvm.org/bugs/show_bug.cgi?id=18843 return make_value(static_cast(v->get())); } #endif return nullptr; } /** * Exception class for array insertion errors. */ class array_exception : public std::runtime_error { public: array_exception(const std::string& err) : std::runtime_error{err} { } }; class array : public base { public: friend std::shared_ptr make_array(); std::shared_ptr clone() const override; virtual bool is_array() const override { return true; } using size_type = std::size_t; /** * arrays can be iterated over */ using iterator = std::vector>::iterator; /** * arrays can be iterated over. Const version. */ using const_iterator = std::vector>::const_iterator; iterator begin() { return values_.begin(); } const_iterator begin() const { return values_.begin(); } iterator end() { return values_.end(); } const_iterator end() const { return values_.end(); } /** * Obtains the array (vector) of base values. */ std::vector>& get() { return values_; } /** * Obtains the array (vector) of base values. Const version. */ const std::vector>& get() const { return values_; } std::shared_ptr at(size_t idx) const { return values_.at(idx); } /** * Obtains an array of values. Note that elements may be * nullptr if they cannot be converted to a value. */ template std::vector>> array_of() const { std::vector>> result(values_.size()); std::transform(values_.begin(), values_.end(), result.begin(), [&](std::shared_ptr v) { return v->as(); }); return result; } /** * Obtains a option>. The option will be empty if the array * contains values that are not of type T. */ template inline typename array_of_trait::return_type get_array_of() const { std::vector result; result.reserve(values_.size()); for (const auto& val : values_) { if (auto v = val->as()) result.push_back(v->get()); else return {}; } return {std::move(result)}; } /** * Obtains an array of arrays. Note that elements may be nullptr * if they cannot be converted to a array. */ std::vector> nested_array() const { std::vector> result(values_.size()); std::transform(values_.begin(), values_.end(), result.begin(), [&](std::shared_ptr v) -> std::shared_ptr { if (v->is_array()) return std::static_pointer_cast(v); return std::shared_ptr{}; }); return result; } /** * Add a value to the end of the array */ template void push_back(const std::shared_ptr>& val) { if (values_.empty() || values_[0]->as()) { values_.push_back(val); } else { throw array_exception{"Arrays must be homogenous."}; } } /** * Add an array to the end of the array */ void push_back(const std::shared_ptr& val) { if (values_.empty() || values_[0]->is_array()) { values_.push_back(val); } else { throw array_exception{"Arrays must be homogenous."}; } } /** * Convenience function for adding a simple element to the end * of the array. */ template void push_back(T&& val, typename value_traits::type* = 0) { push_back(make_value(std::forward(val))); } /** * Insert a value into the array */ template iterator insert(iterator position, const std::shared_ptr>& value) { if (values_.empty() || values_[0]->as()) { return values_.insert(position, value); } else { throw array_exception{"Arrays must be homogenous."}; } } /** * Insert an array into the array */ iterator insert(iterator position, const std::shared_ptr& value) { if (values_.empty() || values_[0]->is_array()) { return values_.insert(position, value); } else { throw array_exception{"Arrays must be homogenous."}; } } /** * Convenience function for inserting a simple element in the array */ template iterator insert(iterator position, T&& val, typename value_traits::type* = 0) { return insert(position, make_value(std::forward(val))); } /** * Erase an element from the array */ iterator erase(iterator position) { return values_.erase(position); } /** * Clear the array */ void clear() { values_.clear(); } /** * Reserve space for n values. */ void reserve(size_type n) { values_.reserve(n); } private: #if defined(CPPTOML_NO_RTTI) array() : base(base_type::ARRAY) { // empty } #else array() = default; #endif template array(InputIterator begin, InputIterator end) : values_{begin, end} { // nothing } array(const array& obj) = delete; array& operator=(const array& obj) = delete; std::vector> values_; }; inline std::shared_ptr make_array() { struct make_shared_enabler : public array { make_shared_enabler() { // nothing } }; return std::make_shared(); } namespace detail { template <> inline std::shared_ptr make_element() { return make_array(); } } // namespace detail /** * Obtains a option>. The option will be empty if the array * contains values that are not of type T. */ template <> inline typename array_of_trait::return_type array::get_array_of() const { std::vector> result; result.reserve(values_.size()); for (const auto& val : values_) { if (auto v = val->as_array()) result.push_back(v); else return {}; } return {std::move(result)}; } class table; class table_array : public base { friend class table; friend std::shared_ptr make_table_array(bool); public: std::shared_ptr clone() const override; using size_type = std::size_t; /** * arrays can be iterated over */ using iterator = std::vector>::iterator; /** * arrays can be iterated over. Const version. */ using const_iterator = std::vector>::const_iterator; iterator begin() { return array_.begin(); } const_iterator begin() const { return array_.begin(); } iterator end() { return array_.end(); } const_iterator end() const { return array_.end(); } virtual bool is_table_array() const override { return true; } std::vector>& get() { return array_; } const std::vector>& get() const { return array_; } /** * Add a table to the end of the array */ void push_back(const std::shared_ptr
& val) { array_.push_back(val); } /** * Insert a table into the array */ iterator insert(iterator position, const std::shared_ptr
& value) { return array_.insert(position, value); } /** * Erase an element from the array */ iterator erase(iterator position) { return array_.erase(position); } /** * Clear the array */ void clear() { array_.clear(); } /** * Reserve space for n tables. */ void reserve(size_type n) { array_.reserve(n); } /** * Whether or not the table array is declared inline. This mostly * matters for parsing, where statically defined arrays cannot be * appended to using the array-of-table syntax. */ bool is_inline() const { return is_inline_; } private: #if defined(CPPTOML_NO_RTTI) table_array(bool is_inline = false) : base(base_type::TABLE_ARRAY), is_inline_(is_inline) { // nothing } #else table_array(bool is_inline = false) : is_inline_(is_inline) { // nothing } #endif table_array(const table_array& obj) = delete; table_array& operator=(const table_array& rhs) = delete; std::vector> array_; const bool is_inline_ = false; }; inline std::shared_ptr make_table_array(bool is_inline) { struct make_shared_enabler : public table_array { make_shared_enabler(bool mse_is_inline) : table_array(mse_is_inline) { // nothing } }; return std::make_shared(is_inline); } namespace detail { template <> inline std::shared_ptr make_element() { return make_table_array(true); } } // namespace detail // The below are overloads for fetching specific value types out of a value // where special casting behavior (like bounds checking) is desired template typename std::enable_if::value && std::is_signed::value, option>::type get_impl(const std::shared_ptr& elem) { if (auto v = elem->as()) { if (v->get() < (std::numeric_limits::min)()) throw std::underflow_error{ "T cannot represent the value requested in get"}; if (v->get() > (std::numeric_limits::max)()) throw std::overflow_error{ "T cannot represent the value requested in get"}; return {static_cast(v->get())}; } else { return {}; } } template typename std::enable_if::value && std::is_unsigned::value, option>::type get_impl(const std::shared_ptr& elem) { if (auto v = elem->as()) { if (v->get() < 0) throw std::underflow_error{"T cannot store negative value in get"}; if (static_cast(v->get()) > (std::numeric_limits::max)()) throw std::overflow_error{ "T cannot represent the value requested in get"}; return {static_cast(v->get())}; } else { return {}; } } template typename std::enable_if::value || std::is_same::value, option>::type get_impl(const std::shared_ptr& elem) { if (auto v = elem->as()) { return {v->get()}; } else { return {}; } } /** * Represents a TOML keytable. */ class table : public base { public: friend class table_array; friend std::shared_ptr
make_table(); std::shared_ptr clone() const override; /** * tables can be iterated over. */ using iterator = string_to_base_map::iterator; /** * tables can be iterated over. Const version. */ using const_iterator = string_to_base_map::const_iterator; iterator begin() { return map_.begin(); } const_iterator begin() const { return map_.begin(); } iterator end() { return map_.end(); } const_iterator end() const { return map_.end(); } bool is_table() const override { return true; } bool empty() const { return map_.empty(); } /** * Determines if this key table contains the given key. */ bool contains(const std::string& key) const { return map_.find(key) != map_.end(); } /** * Determines if this key table contains the given key. Will * resolve "qualified keys". Qualified keys are the full access * path separated with dots like "grandparent.parent.child". */ bool contains_qualified(const std::string& key) const { return resolve_qualified(key); } /** * Obtains the base for a given key. * @throw std::out_of_range if the key does not exist */ std::shared_ptr get(const std::string& key) const { return map_.at(key); } /** * Obtains the base for a given key. Will resolve "qualified * keys". Qualified keys are the full access path separated with * dots like "grandparent.parent.child". * * @throw std::out_of_range if the key does not exist */ std::shared_ptr get_qualified(const std::string& key) const { std::shared_ptr p; resolve_qualified(key, &p); return p; } /** * Obtains a table for a given key, if possible. */ std::shared_ptr
get_table(const std::string& key) const { if (contains(key) && get(key)->is_table()) return std::static_pointer_cast
(get(key)); return nullptr; } /** * Obtains a table for a given key, if possible. Will resolve * "qualified keys". */ std::shared_ptr
get_table_qualified(const std::string& key) const { if (contains_qualified(key) && get_qualified(key)->is_table()) return std::static_pointer_cast
(get_qualified(key)); return nullptr; } /** * Obtains an array for a given key. */ std::shared_ptr get_array(const std::string& key) const { if (!contains(key)) return nullptr; return get(key)->as_array(); } /** * Obtains an array for a given key. Will resolve "qualified keys". */ std::shared_ptr get_array_qualified(const std::string& key) const { if (!contains_qualified(key)) return nullptr; return get_qualified(key)->as_array(); } /** * Obtains a table_array for a given key, if possible. */ std::shared_ptr get_table_array(const std::string& key) const { if (!contains(key)) return nullptr; return get(key)->as_table_array(); } /** * Obtains a table_array for a given key, if possible. Will resolve * "qualified keys". */ std::shared_ptr get_table_array_qualified(const std::string& key) const { if (!contains_qualified(key)) return nullptr; return get_qualified(key)->as_table_array(); } /** * Helper function that attempts to get a value corresponding * to the template parameter from a given key. */ template option get_as(const std::string& key) const { try { return get_impl(get(key)); } catch (const std::out_of_range&) { return {}; } } /** * Helper function that attempts to get a value corresponding * to the template parameter from a given key. Will resolve "qualified * keys". */ template option get_qualified_as(const std::string& key) const { try { return get_impl(get_qualified(key)); } catch (const std::out_of_range&) { return {}; } } /** * Helper function that attempts to get an array of values of a given * type corresponding to the template parameter for a given key. * * If the key doesn't exist, doesn't exist as an array type, or one or * more keys inside the array type are not of type T, an empty option * is returned. Otherwise, an option containing a vector of the values * is returned. */ template inline typename array_of_trait::return_type get_array_of(const std::string& key) const { if (auto v = get_array(key)) { std::vector result; result.reserve(v->get().size()); for (const auto& b : v->get()) { if (auto val = b->as()) result.push_back(val->get()); else return {}; } return {std::move(result)}; } return {}; } /** * Helper function that attempts to get an array of values of a given * type corresponding to the template parameter for a given key. Will * resolve "qualified keys". * * If the key doesn't exist, doesn't exist as an array type, or one or * more keys inside the array type are not of type T, an empty option * is returned. Otherwise, an option containing a vector of the values * is returned. */ template inline typename array_of_trait::return_type get_qualified_array_of(const std::string& key) const { if (auto v = get_array_qualified(key)) { std::vector result; result.reserve(v->get().size()); for (const auto& b : v->get()) { if (auto val = b->as()) result.push_back(val->get()); else return {}; } return {std::move(result)}; } return {}; } /** * Adds an element to the keytable. */ void insert(const std::string& key, const std::shared_ptr& value) { map_[key] = value; } /** * Convenience shorthand for adding a simple element to the * keytable. */ template void insert(const std::string& key, T&& val, typename value_traits::type* = 0) { insert(key, make_value(std::forward(val))); } /** * Removes an element from the table. */ void erase(const std::string& key) { map_.erase(key); } private: #if defined(CPPTOML_NO_RTTI) table() : base(base_type::TABLE) { // nothing } #else table() { // nothing } #endif table(const table& obj) = delete; table& operator=(const table& rhs) = delete; std::vector split(const std::string& value, char separator) const { std::vector result; std::string::size_type p = 0; std::string::size_type q; while ((q = value.find(separator, p)) != std::string::npos) { result.emplace_back(value, p, q - p); p = q + 1; } result.emplace_back(value, p); return result; } // If output parameter p is specified, fill it with the pointer to the // specified entry and throw std::out_of_range if it couldn't be found. // // Otherwise, just return true if the entry could be found or false // otherwise and do not throw. bool resolve_qualified(const std::string& key, std::shared_ptr* p = nullptr) const { auto parts = split(key, '.'); auto last_key = parts.back(); parts.pop_back(); auto cur_table = this; for (const auto& part : parts) { cur_table = cur_table->get_table(part).get(); if (!cur_table) { if (!p) return false; throw std::out_of_range{key + " is not a valid key"}; } } if (!p) return cur_table->map_.count(last_key) != 0; *p = cur_table->map_.at(last_key); return true; } string_to_base_map map_; }; /** * Helper function that attempts to get an array of arrays for a given * key. * * If the key doesn't exist, doesn't exist as an array type, or one or * more keys inside the array type are not of type T, an empty option * is returned. Otherwise, an option containing a vector of the values * is returned. */ template <> inline typename array_of_trait::return_type table::get_array_of(const std::string& key) const { if (auto v = get_array(key)) { std::vector> result; result.reserve(v->get().size()); for (const auto& b : v->get()) { if (auto val = b->as_array()) result.push_back(val); else return {}; } return {std::move(result)}; } return {}; } /** * Helper function that attempts to get an array of arrays for a given * key. Will resolve "qualified keys". * * If the key doesn't exist, doesn't exist as an array type, or one or * more keys inside the array type are not of type T, an empty option * is returned. Otherwise, an option containing a vector of the values * is returned. */ template <> inline typename array_of_trait::return_type table::get_qualified_array_of(const std::string& key) const { if (auto v = get_array_qualified(key)) { std::vector> result; result.reserve(v->get().size()); for (const auto& b : v->get()) { if (auto val = b->as_array()) result.push_back(val); else return {}; } return {std::move(result)}; } return {}; } std::shared_ptr
make_table() { struct make_shared_enabler : public table { make_shared_enabler() { // nothing } }; return std::make_shared(); } namespace detail { template <> inline std::shared_ptr
make_element
() { return make_table(); } } // namespace detail template std::shared_ptr value::clone() const { return make_value(data_); } inline std::shared_ptr array::clone() const { auto result = make_array(); result->reserve(values_.size()); for (const auto& ptr : values_) result->values_.push_back(ptr->clone()); return result; } inline std::shared_ptr table_array::clone() const { auto result = make_table_array(is_inline()); result->reserve(array_.size()); for (const auto& ptr : array_) result->array_.push_back(ptr->clone()->as_table()); return result; } inline std::shared_ptr table::clone() const { auto result = make_table(); for (const auto& pr : map_) result->insert(pr.first, pr.second->clone()); return result; } /** * Exception class for all TOML parsing errors. */ class parse_exception : public std::runtime_error { public: parse_exception(const std::string& err) : std::runtime_error{err} { } parse_exception(const std::string& err, std::size_t line_number) : std::runtime_error{err + " at line " + std::to_string(line_number)} { } }; inline bool is_number(char c) { return c >= '0' && c <= '9'; } inline bool is_hex(char c) { return is_number(c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); } /** * Helper object for consuming expected characters. */ template class consumer { public: consumer(std::string::iterator& it, const std::string::iterator& end, OnError&& on_error) : it_(it), end_(end), on_error_(std::forward(on_error)) { // nothing } void operator()(char c) { if (it_ == end_ || *it_ != c) on_error_(); ++it_; } template void operator()(const char (&str)[N]) { std::for_each(std::begin(str), std::end(str) - 1, [&](char c) { (*this)(c); }); } void eat_or(char a, char b) { if (it_ == end_ || (*it_ != a && *it_ != b)) on_error_(); ++it_; } int eat_digits(int len) { int val = 0; for (int i = 0; i < len; ++i) { if (!is_number(*it_) || it_ == end_) on_error_(); val = 10 * val + (*it_++ - '0'); } return val; } void error() { on_error_(); } private: std::string::iterator& it_; const std::string::iterator& end_; OnError on_error_; }; template consumer make_consumer(std::string::iterator& it, const std::string::iterator& end, OnError&& on_error) { return consumer(it, end, std::forward(on_error)); } // replacement for std::getline to handle incorrectly line-ended files // https://stackoverflow.com/questions/6089231/getting-std-ifstream-to-handle-lf-cr-and-crlf namespace detail { inline std::istream& getline(std::istream& input, std::string& line) { line.clear(); std::istream::sentry sentry{input, true}; auto sb = input.rdbuf(); while (true) { auto c = sb->sbumpc(); if (c == '\r') { if (sb->sgetc() == '\n') c = sb->sbumpc(); } if (c == '\n') return input; if (c == std::istream::traits_type::eof()) { if (line.empty()) input.setstate(std::ios::eofbit); return input; } line.push_back(static_cast(c)); } } } // namespace detail /** * The parser class. */ class parser { public: /** * Parsers are constructed from streams. */ parser(std::istream& stream) : input_(stream) { // nothing } parser& operator=(const parser& parser) = delete; /** * Parses the stream this parser was created on until EOF. * @throw parse_exception if there are errors in parsing */ std::shared_ptr
parse() { std::shared_ptr
root = make_table(); table* curr_table = root.get(); while (detail::getline(input_, line_)) { line_number_++; auto it = line_.begin(); auto end = line_.end(); consume_whitespace(it, end); if (it == end || *it == '#') continue; if (*it == '[') { curr_table = root.get(); parse_table(it, end, curr_table); } else { parse_key_value(it, end, curr_table); consume_whitespace(it, end); eol_or_comment(it, end); } } return root; } private: #if defined _MSC_VER __declspec(noreturn) #elif defined __GNUC__ __attribute__((noreturn)) #endif void throw_parse_exception(const std::string& err) { throw parse_exception{err, line_number_}; } void parse_table(std::string::iterator& it, const std::string::iterator& end, table*& curr_table) { // remove the beginning keytable marker ++it; if (it == end) throw_parse_exception("Unexpected end of table"); if (*it == '[') parse_table_array(it, end, curr_table); else parse_single_table(it, end, curr_table); } void parse_single_table(std::string::iterator& it, const std::string::iterator& end, table*& curr_table) { if (it == end || *it == ']') throw_parse_exception("Table name cannot be empty"); std::string full_table_name; bool inserted = false; auto key_end = [](char c) { return c == ']'; }; auto key_part_handler = [&](const std::string& part) { if (part.empty()) throw_parse_exception("Empty component of table name"); if (!full_table_name.empty()) full_table_name += '.'; full_table_name += part; if (curr_table->contains(part)) { #if !defined(__PGI) auto b = curr_table->get(part); #else // Workaround for PGI compiler std::shared_ptr b = curr_table->get(part); #endif if (b->is_table()) curr_table = static_cast(b.get()); else if (b->is_table_array()) curr_table = std::static_pointer_cast(b) ->get() .back() .get(); else throw_parse_exception("Key " + full_table_name + "already exists as a value"); } else { inserted = true; curr_table->insert(part, make_table()); curr_table = static_cast(curr_table->get(part).get()); } }; key_part_handler(parse_key(it, end, key_end, key_part_handler)); if (it == end) throw_parse_exception( "Unterminated table declaration; did you forget a ']'?"); if (*it != ']') { std::string errmsg{"Unexpected character in table definition: "}; errmsg += '"'; errmsg += *it; errmsg += '"'; throw_parse_exception(errmsg); } // table already existed if (!inserted) { auto is_value = [](const std::pair&>& p) { return p.second->is_value(); }; // if there are any values, we can't add values to this table // since it has already been defined. If there aren't any // values, then it was implicitly created by something like // [a.b] if (curr_table->empty() || std::any_of(curr_table->begin(), curr_table->end(), is_value)) { throw_parse_exception("Redefinition of table " + full_table_name); } } ++it; consume_whitespace(it, end); eol_or_comment(it, end); } void parse_table_array(std::string::iterator& it, const std::string::iterator& end, table*& curr_table) { ++it; if (it == end || *it == ']') throw_parse_exception("Table array name cannot be empty"); auto key_end = [](char c) { return c == ']'; }; std::string full_ta_name; auto key_part_handler = [&](const std::string& part) { if (part.empty()) throw_parse_exception("Empty component of table array name"); if (!full_ta_name.empty()) full_ta_name += '.'; full_ta_name += part; if (curr_table->contains(part)) { #if !defined(__PGI) auto b = curr_table->get(part); #else // Workaround for PGI compiler std::shared_ptr b = curr_table->get(part); #endif // if this is the end of the table array name, add an // element to the table array that we just looked up, // provided it was not declared inline if (it != end && *it == ']') { if (!b->is_table_array()) { throw_parse_exception("Key " + full_ta_name + " is not a table array"); } auto v = b->as_table_array(); if (v->is_inline()) { throw_parse_exception("Static array " + full_ta_name + " cannot be appended to"); } v->get().push_back(make_table()); curr_table = v->get().back().get(); } // otherwise, just keep traversing down the key name else { if (b->is_table()) curr_table = static_cast(b.get()); else if (b->is_table_array()) curr_table = std::static_pointer_cast(b) ->get() .back() .get(); else throw_parse_exception("Key " + full_ta_name + " already exists as a value"); } } else { // if this is the end of the table array name, add a new // table array and a new table inside that array for us to // add keys to next if (it != end && *it == ']') { curr_table->insert(part, make_table_array()); auto arr = std::static_pointer_cast( curr_table->get(part)); arr->get().push_back(make_table()); curr_table = arr->get().back().get(); } // otherwise, create the implicitly defined table and move // down to it else { curr_table->insert(part, make_table()); curr_table = static_cast(curr_table->get(part).get()); } } }; key_part_handler(parse_key(it, end, key_end, key_part_handler)); // consume the last "]]" auto eat = make_consumer(it, end, [this]() { throw_parse_exception("Unterminated table array name"); }); eat(']'); eat(']'); consume_whitespace(it, end); eol_or_comment(it, end); } void parse_key_value(std::string::iterator& it, std::string::iterator& end, table* curr_table) { auto key_end = [](char c) { return c == '='; }; auto key_part_handler = [&](const std::string& part) { // two cases: this key part exists already, in which case it must // be a table, or it doesn't exist in which case we must create // an implicitly defined table if (curr_table->contains(part)) { auto val = curr_table->get(part); if (val->is_table()) { curr_table = static_cast(val.get()); } else { throw_parse_exception("Key " + part + " already exists as a value"); } } else { auto newtable = make_table(); curr_table->insert(part, newtable); curr_table = newtable.get(); } }; auto key = parse_key(it, end, key_end, key_part_handler); if (curr_table->contains(key)) throw_parse_exception("Key " + key + " already present"); if (it == end || *it != '=') throw_parse_exception("Value must follow after a '='"); ++it; consume_whitespace(it, end); curr_table->insert(key, parse_value(it, end)); consume_whitespace(it, end); } template std::string parse_key(std::string::iterator& it, const std::string::iterator& end, KeyEndFinder&& key_end, KeyPartHandler&& key_part_handler) { // parse the key as a series of one or more simple-keys joined with '.' while (it != end && !key_end(*it)) { auto part = parse_simple_key(it, end); consume_whitespace(it, end); if (it == end || key_end(*it)) { return part; } if (*it != '.') { std::string errmsg{"Unexpected character in key: "}; errmsg += '"'; errmsg += *it; errmsg += '"'; throw_parse_exception(errmsg); } key_part_handler(part); // consume the dot ++it; } throw_parse_exception("Unexpected end of key"); } std::string parse_simple_key(std::string::iterator& it, const std::string::iterator& end) { consume_whitespace(it, end); if (it == end) throw_parse_exception("Unexpected end of key (blank key?)"); if (*it == '"' || *it == '\'') { return string_literal(it, end, *it); } else { auto bke = std::find_if(it, end, [](char c) { return c == '.' || c == '=' || c == ']'; }); return parse_bare_key(it, bke); } } std::string parse_bare_key(std::string::iterator& it, const std::string::iterator& end) { if (it == end) { throw_parse_exception("Bare key missing name"); } auto key_end = end; --key_end; consume_backwards_whitespace(key_end, it); ++key_end; std::string key{it, key_end}; if (std::find(it, key_end, '#') != key_end) { throw_parse_exception("Bare key " + key + " cannot contain #"); } if (std::find_if(it, key_end, [](char c) { return c == ' ' || c == '\t'; }) != key_end) { throw_parse_exception("Bare key " + key + " cannot contain whitespace"); } if (std::find_if(it, key_end, [](char c) { return c == '[' || c == ']'; }) != key_end) { throw_parse_exception("Bare key " + key + " cannot contain '[' or ']'"); } it = end; return key; } enum class parse_type { STRING = 1, LOCAL_TIME, LOCAL_DATE, LOCAL_DATETIME, OFFSET_DATETIME, INT, FLOAT, BOOL, ARRAY, INLINE_TABLE }; std::shared_ptr parse_value(std::string::iterator& it, std::string::iterator& end) { parse_type type = determine_value_type(it, end); switch (type) { case parse_type::STRING: return parse_string(it, end); case parse_type::LOCAL_TIME: return parse_time(it, end); case parse_type::LOCAL_DATE: case parse_type::LOCAL_DATETIME: case parse_type::OFFSET_DATETIME: return parse_date(it, end); case parse_type::INT: case parse_type::FLOAT: return parse_number(it, end); case parse_type::BOOL: return parse_bool(it, end); case parse_type::ARRAY: return parse_array(it, end); case parse_type::INLINE_TABLE: return parse_inline_table(it, end); default: throw_parse_exception("Failed to parse value"); } } parse_type determine_value_type(const std::string::iterator& it, const std::string::iterator& end) { if (it == end) { throw_parse_exception("Failed to parse value type"); } if (*it == '"' || *it == '\'') { return parse_type::STRING; } else if (is_time(it, end)) { return parse_type::LOCAL_TIME; } else if (auto dtype = date_type(it, end)) { return *dtype; } else if (is_number(*it) || *it == '-' || *it == '+' || (*it == 'i' && it + 1 != end && it[1] == 'n' && it + 2 != end && it[2] == 'f') || (*it == 'n' && it + 1 != end && it[1] == 'a' && it + 2 != end && it[2] == 'n')) { return determine_number_type(it, end); } else if (*it == 't' || *it == 'f') { return parse_type::BOOL; } else if (*it == '[') { return parse_type::ARRAY; } else if (*it == '{') { return parse_type::INLINE_TABLE; } throw_parse_exception("Failed to parse value type"); } parse_type determine_number_type(const std::string::iterator& it, const std::string::iterator& end) { // determine if we are an integer or a float auto check_it = it; if (*check_it == '-' || *check_it == '+') ++check_it; if (check_it == end) throw_parse_exception("Malformed number"); if (*check_it == 'i' || *check_it == 'n') return parse_type::FLOAT; while (check_it != end && is_number(*check_it)) ++check_it; if (check_it != end && *check_it == '.') { ++check_it; while (check_it != end && is_number(*check_it)) ++check_it; return parse_type::FLOAT; } else { return parse_type::INT; } } std::shared_ptr> parse_string(std::string::iterator& it, std::string::iterator& end) { auto delim = *it; assert(delim == '"' || delim == '\''); // end is non-const here because we have to be able to potentially // parse multiple lines in a string, not just one auto check_it = it; ++check_it; if (check_it != end && *check_it == delim) { ++check_it; if (check_it != end && *check_it == delim) { it = ++check_it; return parse_multiline_string(it, end, delim); } } return make_value(string_literal(it, end, delim)); } std::shared_ptr> parse_multiline_string(std::string::iterator& it, std::string::iterator& end, char delim) { std::stringstream ss; auto is_ws = [](char c) { return c == ' ' || c == '\t'; }; bool consuming = false; std::shared_ptr> ret; auto handle_line = [&](std::string::iterator& local_it, std::string::iterator& local_end) { if (consuming) { local_it = std::find_if_not(local_it, local_end, is_ws); // whole line is whitespace if (local_it == local_end) return; } consuming = false; while (local_it != local_end) { // handle escaped characters if (delim == '"' && *local_it == '\\') { auto check = local_it; // check if this is an actual escape sequence or a // whitespace escaping backslash ++check; consume_whitespace(check, local_end); if (check == local_end) { consuming = true; break; } ss << parse_escape_code(local_it, local_end); continue; } // if we can end the string if (std::distance(local_it, local_end) >= 3) { auto check = local_it; // check for """ if (*check++ == delim && *check++ == delim && *check++ == delim) { local_it = check; ret = make_value(ss.str()); break; } } ss << *local_it++; } }; // handle the remainder of the current line handle_line(it, end); if (ret) return ret; // start eating lines while (detail::getline(input_, line_)) { ++line_number_; it = line_.begin(); end = line_.end(); handle_line(it, end); if (ret) return ret; if (!consuming) ss << std::endl; } throw_parse_exception("Unterminated multi-line basic string"); } std::string string_literal(std::string::iterator& it, const std::string::iterator& end, char delim) { ++it; std::string val; while (it != end) { // handle escaped characters if (delim == '"' && *it == '\\') { val += parse_escape_code(it, end); } else if (*it == delim) { ++it; consume_whitespace(it, end); return val; } else { val += *it++; } } throw_parse_exception("Unterminated string literal"); } std::string parse_escape_code(std::string::iterator& it, const std::string::iterator& end) { ++it; if (it == end) throw_parse_exception("Invalid escape sequence"); char value; if (*it == 'b') { value = '\b'; } else if (*it == 't') { value = '\t'; } else if (*it == 'n') { value = '\n'; } else if (*it == 'f') { value = '\f'; } else if (*it == 'r') { value = '\r'; } else if (*it == '"') { value = '"'; } else if (*it == '\\') { value = '\\'; } else if (*it == 'u' || *it == 'U') { return parse_unicode(it, end); } else { throw_parse_exception("Invalid escape sequence"); } ++it; return std::string(1, value); } std::string parse_unicode(std::string::iterator& it, const std::string::iterator& end) { bool large = *it++ == 'U'; auto codepoint = parse_hex(it, end, large ? 0x10000000 : 0x1000); if ((codepoint > 0xd7ff && codepoint < 0xe000) || codepoint > 0x10ffff) { throw_parse_exception( "Unicode escape sequence is not a Unicode scalar value"); } std::string result; // See Table 3-6 of the Unicode standard if (codepoint <= 0x7f) { // 1-byte codepoints: 00000000 0xxxxxxx // repr: 0xxxxxxx result += static_cast(codepoint & 0x7f); } else if (codepoint <= 0x7ff) { // 2-byte codepoints: 00000yyy yyxxxxxx // repr: 110yyyyy 10xxxxxx // // 0x1f = 00011111 // 0xc0 = 11000000 // result += static_cast(0xc0 | ((codepoint >> 6) & 0x1f)); // // 0x80 = 10000000 // 0x3f = 00111111 // result += static_cast(0x80 | (codepoint & 0x3f)); } else if (codepoint <= 0xffff) { // 3-byte codepoints: zzzzyyyy yyxxxxxx // repr: 1110zzzz 10yyyyyy 10xxxxxx // // 0xe0 = 11100000 // 0x0f = 00001111 // result += static_cast(0xe0 | ((codepoint >> 12) & 0x0f)); result += static_cast(0x80 | ((codepoint >> 6) & 0x1f)); result += static_cast(0x80 | (codepoint & 0x3f)); } else { // 4-byte codepoints: 000uuuuu zzzzyyyy yyxxxxxx // repr: 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx // // 0xf0 = 11110000 // 0x07 = 00000111 // result += static_cast(0xf0 | ((codepoint >> 18) & 0x07)); result += static_cast(0x80 | ((codepoint >> 12) & 0x3f)); result += static_cast(0x80 | ((codepoint >> 6) & 0x3f)); result += static_cast(0x80 | (codepoint & 0x3f)); } return result; } uint32_t parse_hex(std::string::iterator& it, const std::string::iterator& end, uint32_t place) { uint32_t value = 0; while (place > 0) { if (it == end) throw_parse_exception("Unexpected end of unicode sequence"); if (!is_hex(*it)) throw_parse_exception("Invalid unicode escape sequence"); value += place * hex_to_digit(*it++); place /= 16; } return value; } uint32_t hex_to_digit(char c) { if (is_number(c)) return static_cast(c - '0'); return 10 + static_cast(c - ((c >= 'a' && c <= 'f') ? 'a' : 'A')); } std::shared_ptr parse_number(std::string::iterator& it, const std::string::iterator& end) { auto check_it = it; auto check_end = find_end_of_number(it, end); auto eat_sign = [&]() { if (check_it != end && (*check_it == '-' || *check_it == '+')) ++check_it; }; auto check_no_leading_zero = [&]() { if (check_it != end && *check_it == '0' && check_it + 1 != check_end && check_it[1] != '.') { throw_parse_exception("Numbers may not have leading zeros"); } }; auto eat_digits = [&](bool (*check_char)(char)) { auto beg = check_it; while (check_it != end && check_char(*check_it)) { ++check_it; if (check_it != end && *check_it == '_') { ++check_it; if (check_it == end || !check_char(*check_it)) throw_parse_exception("Malformed number"); } } if (check_it == beg) throw_parse_exception("Malformed number"); }; auto eat_hex = [&]() { eat_digits(&is_hex); }; auto eat_numbers = [&]() { eat_digits(&is_number); }; if (check_it != end && *check_it == '0' && check_it + 1 != check_end && (check_it[1] == 'x' || check_it[1] == 'o' || check_it[1] == 'b')) { ++check_it; char base = *check_it; ++check_it; if (base == 'x') { eat_hex(); return parse_int(it, check_it, 16); } else if (base == 'o') { auto start = check_it; eat_numbers(); auto val = parse_int(start, check_it, 8, "0"); it = start; return val; } else // if (base == 'b') { auto start = check_it; eat_numbers(); auto val = parse_int(start, check_it, 2); it = start; return val; } } eat_sign(); check_no_leading_zero(); if (check_it != end && check_it + 1 != end && check_it + 2 != end) { if (check_it[0] == 'i' && check_it[1] == 'n' && check_it[2] == 'f') { auto val = std::numeric_limits::infinity(); if (*it == '-') val = -val; it = check_it + 3; return make_value(val); } else if (check_it[0] == 'n' && check_it[1] == 'a' && check_it[2] == 'n') { auto val = std::numeric_limits::quiet_NaN(); if (*it == '-') val = -val; it = check_it + 3; return make_value(val); } } eat_numbers(); if (check_it != end && (*check_it == '.' || *check_it == 'e' || *check_it == 'E')) { bool is_exp = *check_it == 'e' || *check_it == 'E'; ++check_it; if (check_it == end) throw_parse_exception("Floats must have trailing digits"); auto eat_exp = [&]() { eat_sign(); check_no_leading_zero(); eat_numbers(); }; if (is_exp) eat_exp(); else eat_numbers(); if (!is_exp && check_it != end && (*check_it == 'e' || *check_it == 'E')) { ++check_it; eat_exp(); } return parse_float(it, check_it); } else { return parse_int(it, check_it); } } std::shared_ptr> parse_int(std::string::iterator& it, const std::string::iterator& end, int base = 10, const char* prefix = "") { std::string v{it, end}; v = prefix + v; v.erase(std::remove(v.begin(), v.end(), '_'), v.end()); it = end; try { return make_value(std::stoll(v, nullptr, base)); } catch (const std::invalid_argument& ex) { throw_parse_exception("Malformed number (invalid argument: " + std::string{ex.what()} + ")"); } catch (const std::out_of_range& ex) { throw_parse_exception("Malformed number (out of range: " + std::string{ex.what()} + ")"); } } std::shared_ptr> parse_float(std::string::iterator& it, const std::string::iterator& end) { std::string v{it, end}; v.erase(std::remove(v.begin(), v.end(), '_'), v.end()); it = end; char decimal_point = std::localeconv()->decimal_point[0]; std::replace(v.begin(), v.end(), '.', decimal_point); try { return make_value(std::stod(v)); } catch (const std::invalid_argument& ex) { throw_parse_exception("Malformed number (invalid argument: " + std::string{ex.what()} + ")"); } catch (const std::out_of_range& ex) { throw_parse_exception("Malformed number (out of range: " + std::string{ex.what()} + ")"); } } std::shared_ptr> parse_bool(std::string::iterator& it, const std::string::iterator& end) { auto eat = make_consumer(it, end, [this]() { throw_parse_exception("Attempted to parse invalid boolean value"); }); if (*it == 't') { eat("true"); return make_value(true); } else if (*it == 'f') { eat("false"); return make_value(false); } eat.error(); return nullptr; } std::string::iterator find_end_of_number(std::string::iterator it, std::string::iterator end) { auto ret = std::find_if(it, end, [](char c) { return !is_number(c) && c != '_' && c != '.' && c != 'e' && c != 'E' && c != '-' && c != '+' && c != 'x' && c != 'o' && c != 'b'; }); if (ret != end && ret + 1 != end && ret + 2 != end) { if ((ret[0] == 'i' && ret[1] == 'n' && ret[2] == 'f') || (ret[0] == 'n' && ret[1] == 'a' && ret[2] == 'n')) { ret = ret + 3; } } return ret; } std::string::iterator find_end_of_date(std::string::iterator it, std::string::iterator end) { auto end_of_date = std::find_if(it, end, [](char c) { return !is_number(c) && c != '-'; }); if (end_of_date != end && *end_of_date == ' ' && end_of_date + 1 != end && is_number(end_of_date[1])) end_of_date++; return std::find_if(end_of_date, end, [](char c) { return !is_number(c) && c != 'T' && c != 'Z' && c != ':' && c != '-' && c != '+' && c != '.'; }); } std::string::iterator find_end_of_time(std::string::iterator it, std::string::iterator end) { return std::find_if(it, end, [](char c) { return !is_number(c) && c != ':' && c != '.'; }); } local_time read_time(std::string::iterator& it, const std::string::iterator& end) { auto time_end = find_end_of_time(it, end); auto eat = make_consumer( it, time_end, [&]() { throw_parse_exception("Malformed time"); }); local_time ltime; ltime.hour = eat.eat_digits(2); eat(':'); ltime.minute = eat.eat_digits(2); eat(':'); ltime.second = eat.eat_digits(2); int power = 100000; if (it != time_end && *it == '.') { ++it; while (it != time_end && is_number(*it)) { ltime.microsecond += power * (*it++ - '0'); power /= 10; } } if (it != time_end) throw_parse_exception("Malformed time"); return ltime; } std::shared_ptr> parse_time(std::string::iterator& it, const std::string::iterator& end) { return make_value(read_time(it, end)); } std::shared_ptr parse_date(std::string::iterator& it, const std::string::iterator& end) { auto date_end = find_end_of_date(it, end); auto eat = make_consumer( it, date_end, [&]() { throw_parse_exception("Malformed date"); }); local_date ldate; ldate.year = eat.eat_digits(4); eat('-'); ldate.month = eat.eat_digits(2); eat('-'); ldate.day = eat.eat_digits(2); if (it == date_end) return make_value(ldate); eat.eat_or('T', ' '); local_datetime ldt; static_cast(ldt) = ldate; static_cast(ldt) = read_time(it, date_end); if (it == date_end) return make_value(ldt); offset_datetime dt; static_cast(dt) = ldt; int hoff = 0; int moff = 0; if (*it == '+' || *it == '-') { auto plus = *it == '+'; ++it; hoff = eat.eat_digits(2); dt.hour_offset = (plus) ? hoff : -hoff; eat(':'); moff = eat.eat_digits(2); dt.minute_offset = (plus) ? moff : -moff; } else if (*it == 'Z') { ++it; } if (it != date_end) throw_parse_exception("Malformed date"); return make_value(dt); } std::shared_ptr parse_array(std::string::iterator& it, std::string::iterator& end) { // this gets ugly because of the "homogeneity" restriction: // arrays can either be of only one type, or contain arrays // (each of those arrays could be of different types, though) // // because of the latter portion, we don't really have a choice // but to represent them as arrays of base values... ++it; // ugh---have to read the first value to determine array type... skip_whitespace_and_comments(it, end); // edge case---empty array if (*it == ']') { ++it; return make_array(); } auto val_end = std::find_if( it, end, [](char c) { return c == ',' || c == ']' || c == '#'; }); parse_type type = determine_value_type(it, val_end); switch (type) { case parse_type::STRING: return parse_value_array(it, end); case parse_type::LOCAL_TIME: return parse_value_array(it, end); case parse_type::LOCAL_DATE: return parse_value_array(it, end); case parse_type::LOCAL_DATETIME: return parse_value_array(it, end); case parse_type::OFFSET_DATETIME: return parse_value_array(it, end); case parse_type::INT: return parse_value_array(it, end); case parse_type::FLOAT: return parse_value_array(it, end); case parse_type::BOOL: return parse_value_array(it, end); case parse_type::ARRAY: return parse_object_array(&parser::parse_array, '[', it, end); case parse_type::INLINE_TABLE: return parse_object_array( &parser::parse_inline_table, '{', it, end); default: throw_parse_exception("Unable to parse array"); } } template std::shared_ptr parse_value_array(std::string::iterator& it, std::string::iterator& end) { auto arr = make_array(); while (it != end && *it != ']') { auto val = parse_value(it, end); if (auto v = val->as()) arr->get().push_back(val); else throw_parse_exception("Arrays must be homogeneous"); skip_whitespace_and_comments(it, end); if (*it != ',') break; ++it; skip_whitespace_and_comments(it, end); } if (it != end) ++it; return arr; } template std::shared_ptr parse_object_array(Function&& fun, char delim, std::string::iterator& it, std::string::iterator& end) { auto arr = detail::make_element(); while (it != end && *it != ']') { if (*it != delim) throw_parse_exception("Unexpected character in array"); arr->get().push_back(((*this).*fun)(it, end)); skip_whitespace_and_comments(it, end); if (it == end || *it != ',') break; ++it; skip_whitespace_and_comments(it, end); } if (it == end || *it != ']') throw_parse_exception("Unterminated array"); ++it; return arr; } std::shared_ptr
parse_inline_table(std::string::iterator& it, std::string::iterator& end) { auto tbl = make_table(); do { ++it; if (it == end) throw_parse_exception("Unterminated inline table"); consume_whitespace(it, end); if (it != end && *it != '}') { parse_key_value(it, end, tbl.get()); consume_whitespace(it, end); } } while (*it == ','); if (it == end || *it != '}') throw_parse_exception("Unterminated inline table"); ++it; consume_whitespace(it, end); return tbl; } void skip_whitespace_and_comments(std::string::iterator& start, std::string::iterator& end) { consume_whitespace(start, end); while (start == end || *start == '#') { if (!detail::getline(input_, line_)) throw_parse_exception("Unclosed array"); line_number_++; start = line_.begin(); end = line_.end(); consume_whitespace(start, end); } } void consume_whitespace(std::string::iterator& it, const std::string::iterator& end) { while (it != end && (*it == ' ' || *it == '\t')) ++it; } void consume_backwards_whitespace(std::string::iterator& back, const std::string::iterator& front) { while (back != front && (*back == ' ' || *back == '\t')) --back; } void eol_or_comment(const std::string::iterator& it, const std::string::iterator& end) { if (it != end && *it != '#') throw_parse_exception("Unidentified trailing character '" + std::string{*it} + "'---did you forget a '#'?"); } bool is_time(const std::string::iterator& it, const std::string::iterator& end) { auto time_end = find_end_of_time(it, end); auto len = std::distance(it, time_end); if (len < 8) return false; if (it[2] != ':' || it[5] != ':') return false; if (len > 8) return it[8] == '.' && len > 9; return true; } option date_type(const std::string::iterator& it, const std::string::iterator& end) { auto date_end = find_end_of_date(it, end); auto len = std::distance(it, date_end); if (len < 10) return {}; if (it[4] != '-' || it[7] != '-') return {}; if (len >= 19 && (it[10] == 'T' || it[10] == ' ') && is_time(it + 11, date_end)) { // datetime type auto time_end = find_end_of_time(it + 11, date_end); if (time_end == date_end) return {parse_type::LOCAL_DATETIME}; else return {parse_type::OFFSET_DATETIME}; } else if (len == 10) { // just a regular date return {parse_type::LOCAL_DATE}; } return {}; } std::istream& input_; std::string line_; std::size_t line_number_ = 0; }; /** * Utility function to parse a file as a TOML file. Returns the root table. * Throws a parse_exception if the file cannot be opened. */ inline std::shared_ptr
parse_file(const std::string& filename) { #if defined(BOOST_NOWIDE_FSTREAM_INCLUDED_HPP) boost::nowide::ifstream file{filename.c_str()}; #elif defined(NOWIDE_FSTREAM_INCLUDED_HPP) nowide::ifstream file{filename.c_str()}; #else std::ifstream file{filename}; #endif if (!file.is_open()) throw parse_exception{filename + " could not be opened for parsing"}; parser p{file}; return p.parse(); } template struct value_accept; template <> struct value_accept<> { template static void accept(const base&, Visitor&&, Args&&...) { // nothing } }; template struct value_accept { template static void accept(const base& b, Visitor&& visitor, Args&&... args) { if (auto v = b.as()) { visitor.visit(*v, std::forward(args)...); } else { value_accept::accept(b, std::forward(visitor), std::forward(args)...); } } }; /** * base implementation of accept() that calls visitor.visit() on the concrete * class. */ template void base::accept(Visitor&& visitor, Args&&... args) const { if (is_value()) { using value_acceptor = value_accept; value_acceptor::accept(*this, std::forward(visitor), std::forward(args)...); } else if (is_table()) { visitor.visit(static_cast(*this), std::forward(args)...); } else if (is_array()) { visitor.visit(static_cast(*this), std::forward(args)...); } else if (is_table_array()) { visitor.visit(static_cast(*this), std::forward(args)...); } } /** * Writer that can be passed to accept() functions of cpptoml objects and * will output valid TOML to a stream. */ class toml_writer { public: /** * Construct a toml_writer that will write to the given stream */ toml_writer(std::ostream& s, const std::string& indent_space = "\t") : stream_(s), indent_(indent_space), has_naked_endline_(false) { // nothing } public: /** * Output a base value of the TOML tree. */ template void visit(const value& v, bool = false) { write(v); } /** * Output a table element of the TOML tree */ void visit(const table& t, bool in_array = false) { write_table_header(in_array); std::vector values; std::vector tables; for (const auto& i : t) { if (i.second->is_table() || i.second->is_table_array()) { tables.push_back(i.first); } else { values.push_back(i.first); } } for (unsigned int i = 0; i < values.size(); ++i) { path_.push_back(values[i]); if (i > 0) endline(); write_table_item_header(*t.get(values[i])); t.get(values[i])->accept(*this, false); path_.pop_back(); } for (unsigned int i = 0; i < tables.size(); ++i) { path_.push_back(tables[i]); if (values.size() > 0 || i > 0) endline(); write_table_item_header(*t.get(tables[i])); t.get(tables[i])->accept(*this, false); path_.pop_back(); } endline(); } /** * Output an array element of the TOML tree */ void visit(const array& a, bool = false) { write("["); for (unsigned int i = 0; i < a.get().size(); ++i) { if (i > 0) write(", "); if (a.get()[i]->is_array()) { a.get()[i]->as_array()->accept(*this, true); } else { a.get()[i]->accept(*this, true); } } write("]"); } /** * Output a table_array element of the TOML tree */ void visit(const table_array& t, bool = false) { for (unsigned int j = 0; j < t.get().size(); ++j) { if (j > 0) endline(); t.get()[j]->accept(*this, true); } endline(); } /** * Escape a string for output. */ static std::string escape_string(const std::string& str) { std::string res; for (auto it = str.begin(); it != str.end(); ++it) { if (*it == '\b') { res += "\\b"; } else if (*it == '\t') { res += "\\t"; } else if (*it == '\n') { res += "\\n"; } else if (*it == '\f') { res += "\\f"; } else if (*it == '\r') { res += "\\r"; } else if (*it == '"') { res += "\\\""; } else if (*it == '\\') { res += "\\\\"; } else if (static_cast(*it) <= UINT32_C(0x001f)) { res += "\\u"; std::stringstream ss; ss << std::hex << static_cast(*it); res += ss.str(); } else { res += *it; } } return res; } protected: /** * Write out a string. */ void write(const value& v) { write("\""); write(escape_string(v.get())); write("\""); } /** * Write out a double. */ void write(const value& v) { std::stringstream ss; ss << std::showpoint << std::setprecision(std::numeric_limits::max_digits10) << v.get(); auto double_str = ss.str(); auto pos = double_str.find("e0"); if (pos != std::string::npos) double_str.replace(pos, 2, "e"); pos = double_str.find("e-0"); if (pos != std::string::npos) double_str.replace(pos, 3, "e-"); stream_ << double_str; has_naked_endline_ = false; } /** * Write out an integer, local_date, local_time, local_datetime, or * offset_datetime. */ template typename std::enable_if< is_one_of::value>::type write(const value& v) { write(v.get()); } /** * Write out a boolean. */ void write(const value& v) { write((v.get() ? "true" : "false")); } /** * Write out the header of a table. */ void write_table_header(bool in_array = false) { if (!path_.empty()) { indent(); write("["); if (in_array) { write("["); } for (unsigned int i = 0; i < path_.size(); ++i) { if (i > 0) { write("."); } if (path_[i].find_first_not_of("ABCDEFGHIJKLMNOPQRSTUVWXYZabcde" "fghijklmnopqrstuvwxyz0123456789" "_-") == std::string::npos) { write(path_[i]); } else { write("\""); write(escape_string(path_[i])); write("\""); } } if (in_array) { write("]"); } write("]"); endline(); } } /** * Write out the identifier for an item in a table. */ void write_table_item_header(const base& b) { if (!b.is_table() && !b.is_table_array()) { indent(); if (path_.back().find_first_not_of("ABCDEFGHIJKLMNOPQRSTUVWXYZabcde" "fghijklmnopqrstuvwxyz0123456789" "_-") == std::string::npos) { write(path_.back()); } else { write("\""); write(escape_string(path_.back())); write("\""); } write(" = "); } } private: /** * Indent the proper number of tabs given the size of * the path. */ void indent() { for (std::size_t i = 1; i < path_.size(); ++i) write(indent_); } /** * Write a value out to the stream. */ template void write(const T& v) { stream_ << v; has_naked_endline_ = false; } /** * Write an endline out to the stream */ void endline() { if (!has_naked_endline_) { stream_ << "\n"; has_naked_endline_ = true; } } private: std::ostream& stream_; const std::string indent_; std::vector path_; bool has_naked_endline_; }; inline std::ostream& operator<<(std::ostream& stream, const base& b) { toml_writer writer{stream}; b.accept(writer); return stream; } template std::ostream& operator<<(std::ostream& stream, const value& v) { toml_writer writer{stream}; v.accept(writer); return stream; } inline std::ostream& operator<<(std::ostream& stream, const table& t) { toml_writer writer{stream}; t.accept(writer); return stream; } inline std::ostream& operator<<(std::ostream& stream, const table_array& t) { toml_writer writer{stream}; t.accept(writer); return stream; } inline std::ostream& operator<<(std::ostream& stream, const array& a) { toml_writer writer{stream}; a.accept(writer); return stream; } } // namespace cpptoml #endif // CPPTOML_H RcppTOML/inst/tinytest/0000755000176200001440000000000013504146047014516 5ustar liggesusersRcppTOML/inst/tinytest/strings.toml0000644000176200001440000000231413503466503017105 0ustar liggesusers################################################################################ ## String # There are four ways to express strings: basic, multi-line basic, literal, and # multi-line literal. All strings must contain only valid UTF-8 characters. [string.basic] #basic = "I'm a string. \"You can quote me\". Name\tJos\u00E9\nLocation\tSF." basic = "I'm a string. \"You can quote me\". Name\tJose\nLocation\tSF." [string.multiline] # The following strings are byte-for-byte equivalent: key1 = "One\nTwo" key2 = """One\nTwo""" key3 = """ One Two""" [string.multiline.continued] # The following strings are byte-for-byte equivalent: key1 = "The quick brown fox jumps over the lazy dog." key2 = """ The quick brown \ fox jumps over \ the lazy dog.""" key3 = """\ The quick brown \ fox jumps over \ the lazy dog.\ """ [string.literal] # What you see is what you get. winpath = 'C:\Users\nodejs\templates' winpath2 = '\\ServerX\admin$\system32\' quoted = 'Tom "Dubs" Preston-Werner' regex = '<\i\c*\s*>' [string.literal.multiline] regex2 = '''I [dw]on't need \d{2} apples''' lines = ''' The first newline is trimmed in raw strings. All other whitespace is preserved. ''' RcppTOML/inst/tinytest/toml_example.toml0000644000176200001440000000155313503466503020106 0ustar liggesusers# This is a TOML document. Boom. title = "TOML Example" [owner] name = "Tom Preston-Werner" organization = "GitHub" bio = "GitHub Cofounder & CEO\nLikes tater tots and beer." dob = 1979-05-27T07:32:00Z # First class dates? Why not? [database] server = "192.168.1.1" ports = [ 8001, 8001, 8002 ] connection_max = 5000 enabled = true [servers] # You can indent as you please. Tabs or spaces. TOML don't care. [servers.alpha] ip = "10.0.0.1" dc = "eqdc10" [servers.beta] ip = "10.0.0.2" dc = "eqdc10" country = "中国" # This should be parsed as UTF-8 [clients] data = [ ["gamma", "delta"], [1, 2] ] # just an update to make sure parsers support it # Line breaks are OK when inside arrays hosts = [ "alpha", "omega" ] # Products [[products]] name = "Hammer" sku = 738594937 [[products]] name = "Nail" sku = 284758393 color = "gray" RcppTOML/inst/tinytest/dates_and_times.toml0000644000176200001440000000055113503466503020540 0ustar liggesusers ## Offset Date-Time odt1 = 1979-05-27T07:32:00Z odt2 = 1979-05-27T00:32:00-07:00 odt3 = 1979-05-27T00:32:00.999999-07:00 ## also without T odt4 = 1979-05-27 07:32:00Z ## Local Date-Time ldt1 = 1979-05-27T07:32:00 ldt2 = 1979-05-27T00:32:00.999999 ## Local Date ld1 = 1979-05-27 ## Local Time -- no R type for this #lt1 = 07:32:00 #lt2 = 00:32:00.999999 RcppTOML/inst/tinytest/float.toml0000644000176200001440000000071013503466503016517 0ustar liggesusers################################################################################ ## Float # A float consists of an integer part (which may be prefixed with a plus or # minus sign) followed by a fractional part and/or an exponent part. [float.fractional] key1 = +1.0 key2 = 3.1415 key3 = -0.01 [float.exponent] key1 = 5e+22 key2 = 1e6 key3 = -2E-2 [float.both] key = 6.626e-34 [float.underscores] key1 = 9_224_617.445_991_228_313 #key2 = 1e1_000 RcppTOML/inst/tinytest/test_float.R0000644000176200001440000000106613503466503017011 0ustar liggesusers library(RcppTOML) toml <- parseToml("float.toml") expect_equal(names(toml), c("float")) expect_equal(names(toml$float), c("both", "exponent", "fractional", "underscores")) expect_equal(toml$float$both$key, 6.626e-34) expect_equal(toml$float$exponent$key1, 5e22) expect_equal(toml$float$exponent$key2, 1e+06) expect_equal(toml$float$exponent$key3, -0.02) expect_equal(toml$float$fractional$key1, 1) expect_equal(toml$float$fractional$key2, 3.1415) expect_equal(toml$float$fractional$key3, -0.01) expect_equal(toml$float$underscores$key1, 9224617.445991228313) RcppTOML/inst/tinytest/test_dates_times.R0000644000176200001440000000175213503526032020201 0ustar liggesusers isSolaris <- Sys.info()[["sysname"]] == "SunOS" library(RcppTOML) ## v0.5 brings more date and time supprt toml <- parseToml("dates_and_times.toml") ## reference results pt1 <- as.POSIXct("1979-05-27 07:32:00", tz="UTC", usetz=TRUE) pt2 <- as.POSIXct("1979-05-27 07:32:00.999999", tz="UTC", usetz=TRUE) pt3 <- as.POSIXct("1979-05-27 00:32:00.999999", tz="UTC", usetz=TRUE) if (!isSolaris) expect_equal(toml$odt1, pt1) expect_true(inherits(toml$odt1, "POSIXct")) if (!isSolaris) expect_equal(toml$odt2, pt1) expect_true(inherits(toml$odt2, "POSIXct")) if (!isSolaris) expect_equal(toml$odt3, pt2) expect_true(inherits(toml$odt3, "POSIXct")) if (!isSolaris) expect_equal(toml$odt4, pt1) expect_true(inherits(toml$odt4, "POSIXct")) if (!isSolaris) expect_equal(toml$ldt1, pt1) expect_true(inherits(toml$ldt1, "POSIXct")) if (!isSolaris) expect_equal(toml$ldt2, pt3) expect_true(inherits(toml$ldt1, "POSIXct")) expect_equal(class(toml$ld1), "Date") expect_equal(toml$ld1, as.Date("1979-05-27")) RcppTOML/inst/tinytest/integer.toml0000644000176200001440000000077313503466503017060 0ustar liggesusers################################################################################ ## Integer # Integers are whole numbers. Positive numbers may be prefixed with a plus sign. # Negative numbers are prefixed with a minus sign. [integer] key1 = +99 key2 = 42 key3 = 0 key4 = -17 [integer.underscores] # For large numbers, you may use underscores to enhance readability. Each # underscore must be surrounded by at least one digit. key1 = 1_000 key2 = 5_349_221 key3 = 1_2_3_4_5 # valid but inadvisable RcppTOML/inst/tinytest/toml_example-v0.4.0.toml0000644000176200001440000001230413503466503020725 0ustar liggesusers################################################################################ ## Comment # Speak your mind with the hash symbol. They go from the symbol to the end of # the line. ################################################################################ ## Table # Tables (also known as hash tables or dictionaries) are collections of # key/value pairs. They appear in square brackets on a line by themselves. [table] key = "value" # Yeah, you can do this. # Nested tables are denoted by table names with dots in them. Name your tables # whatever crap you please, just don't use #, ., [ or ]. [table.subtable] key = "another value" # You don't need to specify all the super-tables if you don't want to. TOML # knows how to do it for you. # [x] you # [x.y] don't # [x.y.z] need these [x.y.z.w] # for this to work ################################################################################ ## Inline Table # Inline tables provide a more compact syntax for expressing tables. They are # especially useful for grouped data that can otherwise quickly become verbose. # Inline tables are enclosed in curly braces `{` and `}`. No newlines are # allowed between the curly braces unless they are valid within a value. [table.inline] name = { first = "Tom", last = "Preston-Werner" } point = { x = 1, y = 2 } ################################################################################ ## String # There are four ways to express strings: basic, multi-line basic, literal, and # multi-line literal. All strings must contain only valid UTF-8 characters. [string.basic] #basic = "I'm a string. \"You can quote me\". Name\tJos\u00E9\nLocation\tSF." basic = "I'm a string. \"You can quote me\". Name\tJose\nLocation\tSF." [string.multiline] # The following strings are byte-for-byte equivalent: key1 = "One\nTwo" key2 = """One\nTwo""" key3 = """ One Two""" [string.multiline.continued] # The following strings are byte-for-byte equivalent: key1 = "The quick brown fox jumps over the lazy dog." key2 = """ The quick brown \ fox jumps over \ the lazy dog.""" key3 = """\ The quick brown \ fox jumps over \ the lazy dog.\ """ [string.literal] # What you see is what you get. winpath = 'C:\Users\nodejs\templates' winpath2 = '\\ServerX\admin$\system32\' quoted = 'Tom "Dubs" Preston-Werner' regex = '<\i\c*\s*>' [string.literal.multiline] regex2 = '''I [dw]on't need \d{2} apples''' lines = ''' The first newline is trimmed in raw strings. All other whitespace is preserved. ''' ################################################################################ ## Integer # Integers are whole numbers. Positive numbers may be prefixed with a plus sign. # Negative numbers are prefixed with a minus sign. [integer] key1 = +99 key2 = 42 key3 = 0 key4 = -17 [integer.underscores] # For large numbers, you may use underscores to enhance readability. Each # underscore must be surrounded by at least one digit. key1 = 1_000 key2 = 5_349_221 key3 = 1_2_3_4_5 # valid but inadvisable ################################################################################ ## Float # A float consists of an integer part (which may be prefixed with a plus or # minus sign) followed by a fractional part and/or an exponent part. [float.fractional] key1 = +1.0 key2 = 3.1415 key3 = -0.01 [float.exponent] key1 = 5e+22 key2 = 1e6 key3 = -2E-2 [float.both] key = 6.626e-34 [float.underscores] key1 = 9_224_617.445_991_228_313 #key2 = 1e1_000 ################################################################################ ## Boolean # Booleans are just the tokens you're used to. Always lowercase. [boolean] True = true False = false ################################################################################ ## Datetime # Datetimes are RFC 3339 dates. [datetime] key1 = 1979-05-27T07:32:00Z key2 = 1979-05-27T00:32:00-07:00 key3 = 1979-05-27T00:32:00.999999-07:00 ################################################################################ ## Array # Arrays are square brackets with other primitives inside. Whitespace is # ignored. Elements are separated by commas. Data types may not be mixed. [array] key1 = [ 1, 2, 3 ] key2 = [ "red", "yellow", "green" ] key3 = [ [ 1, 2 ], [3, 4, 5] ] key4 = [ [ 1, 2 ], ["a", "b", "c"] ] # this is ok # Arrays can also be multiline. So in addition to ignoring whitespace, arrays # also ignore newlines between the brackets. Terminating commas are ok before # the closing bracket. key5 = [ 1, 2, 3 ] key6 = [ 1, 2, # this is ok ] ################################################################################ ## Array of Tables # These can be expressed by using a table name in double brackets. Each table # with the same double bracketed name will be an element in the array. The # tables are inserted in the order encountered. [[products]] name = "Hammer" sku = 738594937 [[products]] [[products]] name = "Nail" sku = 284758393 color = "gray" # You can create nested arrays of tables as well. [[fruit]] name = "apple" [fruit.physical] color = "red" shape = "round" [[fruit.variety]] name = "red delicious" [[fruit.variety]] name = "granny smith" [[fruit]] name = "banana" [[fruit.variety]] name = "plantain" RcppTOML/inst/tinytest/tables.toml0000644000176200001440000000217013503466503016666 0ustar liggesusers################################################################################ ## Table # Tables (also known as hash tables or dictionaries) are collections of # key/value pairs. They appear in square brackets on a line by themselves. [table] key = "value" # Yeah, you can do this. # Nested tables are denoted by table names with dots in them. Name your tables # whatever crap you please, just don't use #, ., [ or ]. [table.subtable] key = "another value" # You don't need to specify all the super-tables if you don't want to. TOML # knows how to do it for you. # [x] you # [x.y] don't # [x.y.z] need these [x.y.z.w] # for this to work ################################################################################ ## Inline Table # Inline tables provide a more compact syntax for expressing tables. They are # especially useful for grouped data that can otherwise quickly become verbose. # Inline tables are enclosed in curly braces `{` and `}`. No newlines are # allowed between the curly braces unless they are valid within a value. [table.inline] name = { first = "Tom", last = "Preston-Werner" } point = { x = 1, y = 2 } RcppTOML/inst/tinytest/test_arrays.R0000644000176200001440000000213613503466503017204 0ustar liggesusers library(RcppTOML) toml <- parseToml("arrays.toml") expect_equal(names(toml), c("array", "fruit", "products")) expect_equal(names(toml$array), paste0("key", 1:6)) expect_equal(toml$array$key1, 1:3) expect_equal(class(toml$array$key1), "integer") expect_equal(toml$array$key2, c("red", "yellow", "green")) expect_equal(toml$array$key3[[1]], 1:2) expect_equal(toml$array$key3[[2]], 3:5) expect_equal(toml$array$key4[[1]], 1:2) expect_equal(toml$array$key4[[2]], letters[1:3]) expect_equal(toml$array$key5, 1:3) expect_equal(toml$array$key6, 1:2) expect_equal(toml$fruit[[1]]$name, "apple") expect_equal(toml$fruit[[1]]$physical, list(color="red", shape="round")) expect_equal(toml$fruit[[1]]$variety, list(list(name="red delicious"), list(name="granny smith"))) expect_equal(toml$fruit[[2]]$name, "banana") expect_equal(toml$fruit[[2]]$variety, list(list(name="plantain"))) expect_equal(toml$products[[1]], list(name="Hammer", sku=738594937L)) expect_equal(toml$products[[2]], list()) expect_equal(toml$products[[3]], list(color="gray", name="Nail", sku=284758393L)) RcppTOML/inst/tinytest/test_bool_datetime.R0000644000176200001440000000102113503525230020473 0ustar liggesusers library(RcppTOML) isSolaris <- Sys.info()[["sysname"]] == "SunOS" toml <- parseToml("bool_datetime.toml") expect_equal(names(toml), c("boolean", "datetime")) expect_true(toml$boolean$True) expect_false(toml$boolean$False) ref1 <- as.POSIXct("1979-05-27 07:32:00", tz="UTC", usetz=TRUE) ref2 <- as.POSIXct("1979-05-27 07:32:00.999999", tz="UTC", usetz=TRUE) if (!isSolaris) expect_equal(toml$datetime$key1, ref1) if (!isSolaris) expect_equal(toml$datetime$key2, ref1) if (!isSolaris) expect_equal(toml$datetime$key3, ref2) RcppTOML/inst/tinytest/toml_hard_example.toml0000644000176200001440000000260613503466503021104 0ustar liggesusers# Test file for TOML # Only this one tries to emulate a TOML file written by a user of the kind of parser writers probably hate # This part you'll really hate [the] test_string = "You'll hate me after this - #" # " Annoying, isn't it? [the.hard] test_array = [ "] ", " # "] # ] There you go, parse this! test_array2 = [ "Test #11 ]proved that", "Experiment #9 was a success" ] # You didn't think it'd as easy as chucking out the last #, did you? another_test_string = " Same thing, but with a string #" harder_test_string = " And when \"'s are in the string, along with # \"" # "and comments are there too" # Things will get harder [the.hard."bit#"] "what?" = "You don't think some user won't do that?" multi_line_array = [ "]", # ] Oh yes I did ] # Each of the following keygroups/key value pairs should produce an error. Uncomment to them to test #[error] if you didn't catch this, your parser is broken #string = "Anything other than tabs, spaces and newline after a keygroup or key value pair has ended should produce an error unless it is a comment" like this #array = [ # "This might most likely happen in multiline arrays", # Like here, # "or here, # and here" # ] End of array comment, forgot the # #number = 3.14 pi <--again forgot the # RcppTOML/inst/tinytest/test_misc.R0000644000176200001440000000160313503525501016626 0ustar liggesusers isSolaris <- Sys.info()[["sysname"]] == "SunOS" toml <- RcppTOML::parseToml(" title = \"TOML Example\" [owner] name = \"Tom Preston-Werner\" dob = 1979-05-27T07:32:00-08:00 # First class dates [database] server = \"192.168.1.1\" ports = [ 8001, 8001, 8002 ] connection_max = 5000 enabled = true ", fromFile=FALSE) expect_true(setequal(names(toml), c("title", "owner", "database"))) expect_true(setequal(names(toml$owner), c("name", "dob"))) expect_equal(toml$owner$name, "Tom Preston-Werner") if (!isSolaris) expect_equal(toml$owner$dob, as.POSIXct("1979-05-27 15:32:00", tz="UTC", usetz=TRUE)) expect_true(setequal(names(toml$database), c("server", "ports", "connection_max", "enabled"))) expect_equal(toml$database$server, "192.168.1.1") expect_equal(toml$database$ports, c(8001L, 8001L, 8002L)) expect_equal(toml$database$connection_max, 5000L) expect_equal(toml$database$enabled, TRUE) RcppTOML/inst/tinytest/test_strings.R0000644000176200001440000000324413503466503017375 0ustar liggesusers library(RcppTOML) toml <- parseToml("strings.toml") expect_equal(names(toml), "string") expect_true(setequal(names(toml$string), c("basic", "literal", "multiline"))) expect_equal(names(toml$string$basic), "basic") expect_equal(toml$string$basic$basic, "I'm a string. \\\"You can quote me\\\". Name\tJose\\nLocation\tSF.") expect_true(setequal(names(toml$string$multiline), c("key1", "key2", "key3", "continued"))) expect_equal(toml$string$multiline$key1, "One\\nTwo") expect_equal(toml$string$multiline$key2, "One\\nTwo") expect_equal(toml$string$multiline$key3, "One\\nTwo") expect_true(setequal(names(toml$string$multiline$continued), c("key1", "key2", "key3"))) expect_equal(toml$string$multiline$continued$key1, "The quick brown fox jumps over the lazy dog.") expect_equal(toml$string$multiline$continued$key2, "The quick brown fox jumps over the lazy dog.") expect_equal(toml$string$multiline$continued$key3, "The quick brown fox jumps over the lazy dog.") expect_true(setequal(names(toml$string$literal), c("winpath", "winpath2", "quoted", "regex", "multiline"))) expect_equal(toml$string$literal$winpath, "C:\\\\Users\\\\nodejs\\\\templates") expect_equal(toml$string$literal$winpath2, "\\\\\\\\ServerX\\\\admin$\\\\system32\\\\") expect_equal(toml$string$literal$quoted, "Tom \\\"Dubs\\\" Preston-Werner") expect_equal(toml$string$literal$regex, "<\\\\i\\\\c*\\\\s*>") expect_true(setequal(names(toml$string$literal$multiline), c("regex2", "lines"))) expect_equal(toml$string$literal$multiline$regex2, "I [dw]on't need \\\\d{2} apples") expect_equal(toml$string$literal$multiline$lines, "The first newline is\\ntrimmed in raw strings.\\n All other whitespace\\n is preserved.\\n") RcppTOML/inst/tinytest/bool_datetime.toml0000644000176200001440000000067013503466503020226 0ustar liggesusers################################################################################ ## Boolean # Booleans are just the tokens you're used to. Always lowercase. [boolean] True = true False = false ################################################################################ ## Datetime # Datetimes are RFC 3339 dates. [datetime] key1 = 1979-05-27T07:32:00Z key2 = 1979-05-27T00:32:00-07:00 key3 = 1979-05-27T00:32:00.999999-07:00 RcppTOML/inst/tinytest/test_integer.R0000644000176200001440000000074613503466503017345 0ustar liggesusers library(RcppTOML) toml <- parseToml("integer.toml") expect_equal(names(toml), c("integer")) expect_equal(names(toml$integer), c("key1", "key2", "key3", "key4", "underscores")) expect_equal(toml$integer$key1, 99L) expect_equal(toml$integer$key2, 42L) expect_equal(toml$integer$key3, 0L) expect_equal(toml$integer$key4, -17L) expect_equal(toml$integer$underscores$key1, 1000L) expect_equal(toml$integer$underscores$key2, 5349221L) expect_equal(toml$integer$underscores$key3, 12345L) RcppTOML/inst/tinytest/arrays.toml0000644000176200001440000000251113503466503016714 0ustar liggesusers ################################################################################ ## Array # Arrays are square brackets with other primitives inside. Whitespace is # ignored. Elements are separated by commas. Data types may not be mixed. [array] key1 = [ 1, 2, 3 ] key2 = [ "red", "yellow", "green" ] key3 = [ [ 1, 2 ], [3, 4, 5] ] key4 = [ [ 1, 2 ], ["a", "b", "c"] ] # this is ok # Arrays can also be multiline. So in addition to ignoring whitespace, arrays # also ignore newlines between the brackets. Terminating commas are ok before # the closing bracket. key5 = [ 1, 2, 3 ] key6 = [ 1, 2, # this is ok ] ################################################################################ ## Array of Tables # These can be expressed by using a table name in double brackets. Each table # with the same double bracketed name will be an element in the array. The # tables are inserted in the order encountered. [[products]] name = "Hammer" sku = 738594937 [[products]] [[products]] name = "Nail" sku = 284758393 color = "gray" # You can create nested arrays of tables as well. [[fruit]] name = "apple" [fruit.physical] color = "red" shape = "round" [[fruit.variety]] name = "red delicious" [[fruit.variety]] name = "granny smith" [[fruit]] name = "banana" [[fruit.variety]] name = "plantain" RcppTOML/inst/tinytest/test_examples.R0000644000176200001440000001546013504146047017524 0ustar liggesusers library(RcppTOML) isWindows <- Sys.info()[["sysname"]] == "Windows" isSolaris <- Sys.info()[["sysname"]] == "SunOS" ## basic toml-lang::tests/example.toml toml <- parseToml("toml_example.toml") expect_true(setequal(names(toml), c("title", "owner", "database", "servers", "clients", "products"))) expect_equal(toml$title, "TOML Example") expect_true(setequal(names(toml$owner), c("name", "organization", "bio", "dob"))) expect_equal(toml$owner$name, "Tom Preston-Werner") expect_equal(toml$owner$organization, "GitHub") expect_equal(toml$owner$bio, "GitHub Cofounder & CEO\\nLikes tater tots and beer.") if (!isSolaris) expect_equal(toml$owner$dob, as.POSIXct("1979-05-27 07:32:00", tz="UTC", usetz=TRUE)) expect_true(setequal(names(toml$database), c("server", "ports", "connection_max", "enabled"))) expect_equal(toml$database$server, "192.168.1.1") expect_equal(toml$database$ports, c(8001L, 8001L, 8002L)) expect_equal(toml$database$connection_max, 5000L) expect_equal(toml$database$enabled, TRUE) expect_true(setequal(names(toml$servers), c("alpha", "beta"))) expect_true(setequal(names(toml$servers$alpha), c("ip", "dc"))) expect_equal(toml$servers$alpha$ip, "10.0.0.1") expect_equal(toml$servers$alpha$dc, "eqdc10") expect_true(setequal(names(toml$servers$beta), c("ip", "dc", "country"))) expect_equal(toml$servers$beta$ip, "10.0.0.2") expect_equal(toml$servers$beta$dc, "eqdc10") expect_equal(toml$servers$beta$country, "\u4e2d\u56fd") expect_true(setequal(names(toml$clients), c("data", "hosts"))) expect_true(setequal(toml$clients$data, list(c("gamma", "delta"), c(1L, 2L)))) expect_true(setequal(toml$clients$hosts, c("alpha", "omega"))) expect_true(setequal(toml$products[[1]], list(name="Hammer", sku=738594937L))) expect_true(setequal(toml$products[[2]], list(color="gray", name="Nail", sku=284758393L))) ## harder toml-lang::tests/hard_example.toml toml <- parseToml("toml_hard_example.toml") expect_equal(names(toml), "the") expect_true(setequal(names(toml$the), c("test_string", "hard"))) expect_equal(toml$the$test_string, "You'll hate me after this - #") expect_true(setequal(names(toml$the$hard), c("test_array", "test_array2", "another_test_string", "harder_test_string", "bit#"))) expect_equal(toml$the$hard$test_array, c("] ", " # ")) expect_equal(toml$the$hard$test_array2, c("Test #11 ]proved that", "Experiment #9 was a success")) expect_equal(toml$the$hard$another_test_string, " Same thing, but with a string #") expect_equal(toml$the$hard$harder_test_string, " And when \\\"'s are in the string, along with # \\\"") expect_equal(toml$the$hard$`bit#`$`what?`, "You don't think some user won't do that?") expect_equal(toml$the$hard$`bit#`$multi_line_array, "]") ## example toml-lang::examples/example-v0.4.0.toml ## ## note that we edited line 56 which cannot be parsed by cpptoml ## ## also note that there is some redunancy as we had used these tests for the first ## iteration in tests/ which are now tests files here toml <- parseToml("toml_example-v0.4.0.toml") expect_true(setequal(names(toml), c("table", "string", "integer", "float", "boolean", "datetime", "array", "products", "fruit", "x"))) expect_equal(toml$table$key, "value") expect_equal(toml$table$subtable$key, "another value") expect_equal(toml$table$inline$name, list(first="Tom", last="Preston-Werner")) expect_equal(toml$table$inline$point, list(x=1L, y=2L)) expect_equal(toml$x$y$y$z$w, NULL) expect_equal(toml$string$basic$basic, "I'm a string. \\\"You can quote me\\\". Name\tJose\\nLocation\tSF.") expect_equal(toml$string$multiline$key1, "One\\nTwo") expect_equal(toml$string$multiline$key2, "One\\nTwo") expect_equal(toml$string$multiline$key3, "One\\nTwo") expect_equal(toml$string$multiline$continued$key1, "The quick brown fox jumps over the lazy dog.") expect_equal(toml$string$multiline$continued$key2, "The quick brown fox jumps over the lazy dog.") expect_equal(toml$string$multiline$continued$key3, "The quick brown fox jumps over the lazy dog.") expect_equal(toml$string$literal$winpath, "C:\\\\Users\\\\nodejs\\\\templates") expect_equal(toml$string$literal$winpath2, "\\\\\\\\ServerX\\\\admin$\\\\system32\\\\") expect_equal(toml$string$literal$quoted, "Tom \\\"Dubs\\\" Preston-Werner") expect_equal(toml$string$literal$regex, "<\\\\i\\\\c*\\\\s*>") expect_equal(toml$string$literal$multiline$regex2, "I [dw]on't need \\\\d{2} apples") expect_equal(toml$string$literal$multiline$lines, paste0("The first newline is\\ntrimmed in raw strings.\\n", " All other whitespace\\n is preserved.\\n")) expect_equal(names(toml$integer), c("key1", "key2", "key3", "key4", "underscores")) expect_equal(toml$integer$key1, 99L) expect_equal(toml$integer$key2, 42L) expect_equal(toml$integer$key3, 0L) expect_equal(toml$integer$key4, -17L) expect_equal(toml$integer$underscores$key1, 1000L) expect_equal(toml$integer$underscores$key2, 5349221L) expect_equal(toml$integer$underscores$key3, 12345L) expect_equal(names(toml$float), c("both", "exponent", "fractional", "underscores")) expect_equal(toml$float$both$key, 6.626e-34) expect_equal(toml$float$exponent$key1, 5e22) expect_equal(toml$float$exponent$key2, 1e+06) expect_equal(toml$float$exponent$key3, -0.02) expect_equal(toml$float$fractional$key1, 1) expect_equal(toml$float$fractional$key2, 3.1415) expect_equal(toml$float$fractional$key3, -0.01) expect_equal(toml$float$underscores$key1, 9224617.445991228313) expect_true(toml$boolean$True) expect_false(toml$boolean$False) ref1 <- as.POSIXct("1979-05-27 07:32:00", tz="UTC", usetz=TRUE) ref2 <- as.POSIXct("1979-05-27 07:32:00.999999", tz="UTC", usetz=TRUE) if (!isSolaris) expect_equal(toml$datetime$key1, ref1) if (!isSolaris) expect_equal(toml$datetime$key2, ref1) if (!isSolaris) expect_equal(toml$datetime$key3, ref2) expect_equal(names(toml$array), paste0("key", 1:6)) expect_equal(toml$array$key1, 1:3) expect_equal(class(toml$array$key1), "integer") expect_equal(toml$array$key2, c("red", "yellow", "green")) expect_equal(toml$array$key3[[1]], 1:2) expect_equal(toml$array$key3[[2]], 3:5) expect_equal(toml$array$key4[[1]], 1:2) expect_equal(toml$array$key4[[2]], letters[1:3]) expect_equal(toml$array$key5, 1:3) expect_equal(toml$array$key6, 1:2) expect_equal(toml$products[[1]], list(name="Hammer", sku=738594937L)) expect_equal(toml$products[[2]], list()) expect_equal(toml$products[[3]], list(color="gray", name="Nail", sku=284758393L)) expect_equal(toml$fruit[[1]]$name, "apple") expect_equal(toml$fruit[[1]]$physical, list(color="red", shape="round")) expect_equal(toml$fruit[[1]]$variety, list(list(name="red delicious"), list(name="granny smith"))) expect_equal(toml$fruit[[2]]$name, "banana") expect_equal(toml$fruit[[2]]$variety, list(list(name="plantain"))) RcppTOML/inst/tinytest/test_tables.R0000644000176200001440000000101413503466503017147 0ustar liggesusers library(RcppTOML) toml <- parseToml("tables.toml") expect_true(setequal(names(toml), c("table", "x"))) expect_true(setequal(names(toml$table), c("key", "subtable", "inline"))) expect_equal(toml$table$key, "value") expect_equal(toml$table$subtable$key, "another value") expect_equal(toml$table$x$y$z$w, NULL) # not list() expect_equal(names(toml$table$inline), c("name", "point")) expect_equal(toml$table$inline$name, list(first="Tom", last="Preston-Werner")) expect_equal(toml$table$inline$point, list(x=1L, y=2L)) RcppTOML/inst/NEWS.Rd0000644000176200001440000001066013761446654013715 0ustar liggesusers\name{NEWS} \title{News for Package \pkg{RcppTOML}} \newcommand{\ghpr}{\href{https://github.com/eddelbuettel/rcpptoml/pull/#1}{##1}} \newcommand{\ghit}{\href{https://github.com/eddelbuettel/rcpptoml/issues/#1}{##1}} \section{Changes in version 0.1.7 (2020-12-01)}{ \itemize{ \item Add \code{#include } to header file, also contributed upstream, to permit compilation under the (unreleased) `g++-11`. \item Switch the simple `cleanup` script to `bash`. \item Switch CI use to `r-ci` for focal and \pkg{bspm}. \item Update several TOML URLs to \code{https://toml.io/en/}. } } \section{Changes in version 0.1.6 (2019-06-25)}{ \itemize{ \item Propagate the \code{escape} switch to calls of \code{getTable()} and \code{getArray()} (Václav Hausenblas in \ghpr{32} completing \ghpr{26}). \item The \code{README.md} file now mentions TOML v0.5.0 support (Watal Iwasaki in \ghpr{35} addressing \ghit{33}). \item Encodings in arrays is to UTF-8 for character (Václav Hausenblas in \ghpr{36} completing \ghpr{28}) \item The package now uses \pkg{tinytest} (Dirk in \ghpr{38} fixing \ghit{37}, also Václav in \ghpr{39}). } } \section{Changes in version 0.1.5 (2018-10-31)}{ \itemize{ \item Escape characters treatment now has toggle (Václav Hausenblas in \ghpr{27} fixing \ghpr{26}) \item The TOML 0.5.0 'time' type is now supported (somewhat) by returning a formatted string (\ghpr{29}) \item Encodings are now supported by defaulting to UTF-8 (Václav Hausenblas in \ghpr{30} fixing \ghpr{28}) } } \section{Changes in version 0.1.4 (2018-10-23)}{ \itemize{ \item Spelling / grammar fixes to README (Jon Calder in \ghpr{18}) \item Cast from \code{StretchyList} to \code{List} ensures lists appear as \code{List} objects in R \item Support optional \code{includize} pre-processor for recursive includes by Dan Dillon as a header-only library (\ghpr{21} and \ghpr{22}) \item Support \code{includize} argument in R and C++ parser interface \item Added a few more \code{#nocov} tags for coverage (\ghpr{23}) \item Synchronized with new upstream \href{https://github.com/skystrife/cpptoml}{cpptoml} version supporting the \href{https://toml.io/en/v0.5.0}{TOML v0.5.0} specification. (\ghpr{25}) } } \section{Changes in version 0.1.3 (2017-04-25)}{ \itemize{ \item Nested TableArray types are now correctly handled (\ghit{16}) } } \section{Changes in version 0.1.2 (2017-03-26)}{ \itemize{ \item Dates and Datetimes in arrays in the input now preserve their types instead of converting to numeric vectors (\ghit{13}) \item Boolean vectors are also correctly handled (\ghit{14}) \item TableArray types are now stored as lists in a single named list (\ghit{15}) \item The README.md file was expanded with an example and screenshot. \item Added file \code{init.c} with calls to \code{R_registerRoutines()} \code{and R_useDynamicSymbols()}; also use \code{.registration=TRUE} in \code{useDynLib} in \code{NAMESPACE} \item Two example files were updated. } } \section{Changes in version 0.1.1 (2017-02-12)}{ \itemize{ \item Synchronized multiple times with ccptoml upstream adding support for local datetime and local date and more (PR \ghpr{9}, \ghpr{10}, PR \ghpr{11}) \item Dates are now first class types, some support for local versus UTC times was added (though it may be adviseable to stick with UTC) \item Parsing from (R) character variables is now supported as well \item Output from \code{print.toml} no longer prints extra newlines } } \section{Changes in version 0.1.0 (2017-01-05)}{ \itemize{ \item Added Windows support by relying on \code{Rcpp::mktime00()} (PR s\ghpr{6} and \ghpr{8} closing \ghit{5} and \ghit{3}) \item Synchronized with \code{cpptoml} upstream (\ghpr{9}) \item Updated Travis CI support via newer \code{run.sh} } } \section{Changes in version 0.0.5 (2015-12-19)}{ \itemize{ \item Synchronized with \code{cpptoml} upstream (PR \ghpr{4}) \item Improved and extended examples } } \section{Changes in version 0.0.4 (2015-07-16)}{ \itemize{ \item Minor update of upstream \code{cpptoml.h} \item More explicit call of \code{utils::str()} \item Properly cope with empty lists (\ghpr{2}) } } \section{Changes in version 0.0.3 (2015-04-27)}{ \itemize{ \item First CRAN release after four weeks of initial development } } RcppTOML/cleanup0000755000176200001440000000004213761446661013241 0ustar liggesusers#!/bin/sh rm -f src/*.o src/*.so