Development of the toml
crate has moved to https://github.com/toml-rs/toml/tree/master/crates/toml.
This repo is now archived.
A TOML encoding/decoding library for Rust
Home Page: https://docs.rs/toml
License: Apache License 2.0
Development of the toml
crate has moved to https://github.com/toml-rs/toml/tree/master/crates/toml.
This repo is now archived.
Is that intentional? It caught me by surprise. I couldn't find enough info about the purpose and/or expected results of this trait method in https://doc.rust-lang.org/std/string/trait.ToString.html.
It seems it isn't being done across implementers.
println!("quoted? {}", 1.to_string());
println!("quoted? {}", "hello".to_string());
outputs:
quoted? 1
quoted? hello
rustc --version --verbose
rustc 1.8.0
binary: rustc
commit-hash: unknown
commit-date: unknown
host: x86_64-unknown-linux-gnu
release: 1.8.0
toml-rs does not compile on current rust master:
toml-rs/src/serialization.rs:580:5: 585:6 error: method `read_tuple` has 2 parameters but the declaration in trait `serialize::serialize::Decoder::read_tuple` has 3 [E0050]
toml-rs/src/serialization.rs:580 fn read_tuple<T>(&mut self,
toml-rs/src/serialization.rs:581 f: |&mut Decoder, uint| -> Result<T, DecodeError>)
toml-rs/src/serialization.rs:582 -> Result<T, DecodeError>
toml-rs/src/serialization.rs:583 {
toml-rs/src/serialization.rs:584 self.read_seq(f)
toml-rs/src/serialization.rs:585 }
toml-rs/src/serialization.rs:593:5: 599:6 error: method `read_tuple_struct` has 3 parameters but the declaration in trait `serialize::serialize::Decoder::read_tuple_struct` has 4 [E0050]
toml-rs/src/serialization.rs:593 fn read_tuple_struct<T>(&mut self,
toml-rs/src/serialization.rs:594 _s_name: &str,
toml-rs/src/serialization.rs:595 _f: |&mut Decoder, uint| -> Result<T, DecodeError>)
toml-rs/src/serialization.rs:596 -> Result<T, DecodeError>
toml-rs/src/serialization.rs:597 {
toml-rs/src/serialization.rs:598 panic!()
...
error: aborting due to 2 previous errors
The change was introduced by rust-lang/rust#17595
The Parser to_linecol() fn returns zero-based lines.
It should be one-based:
$ git diff
diff --git a/src/parser.rs b/src/parser.rs
index 377da24..bec7cd8 100644
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -79,7 +79,7 @@ impl<'a> Parser<'a> {
let mut cur = 0;
for (i, line) in self.input.lines().enumerate() {
if cur + line.len() > offset {
- return (i, offset - cur)
+ return (i + 1, offset - cur)
}
cur += line.len() + 1;
}
Page: http://alexcrichton.com/toml-rs/toml/enum.Value.html
Code: let value: toml::Value = toml.parse().unwrap();
The types are wrong, and it won't compile.
parse() returns a BTreeMap<String, Value>
I like what the docs are saying. It would be great if I could parse and use lookup() on the result.
Currently you have to:
It'd be nice to bump the serde support to 0.7
Two things are missing that have caused me issues:
chrono should be able to handle it fairly easily and help clean up the parsing method.
The current TOML parser uses Rust enums as a way to get "variable type" fields. That is, if you have an enum like this
enum MyEnum {
One(uint),
Two(f64)
}
The corresponding TOML is that a floating-point value is interpreted as a Two(num)
while an integer is interpreted as a One(num)
.
However, this does not interact well with C-like enums at all: with the current code, if you have an enum like
enum MyEnum {
One,
Two
}
then any TOML at all will decode to One
, since the decoder code just runs through the enum variants until one parses successfully. For C-like enums, the first one always will.
What would be nice (and more importantly, expected) is if I could use C-like enums as keys in a HashMap and have the values under [One]
go to one HashMap value while the values under [Two]
go to another.
I was trying to use quoted keys, but am finding that while quoted key values can be parsed into a rust data structure just fine, when we go in the other direction, the keys don't get quoted (and so then any subsequent parsing of such a value will fail).
Here's an example. Is this expected?
#[test]
fn round_trip_key_special_chars() {
let raw = include_str!("valid/key-special-chars.toml");
let mut parser = toml::Parser::new(raw);
let v = parser.parse().unwrap();
let the_str = format!("{}", toml::Value::Table(v));
let mut rt_parser = toml::Parser::new(&the_str);
match rt_parser.parse() {
Some(x) => (), // we don't get here
None => {
// parsing failed because when we serialized to a string
// we didn't quote the key
println!("parsing failed");
}
};
assert_eq!(the_str, raw);
}
test unicode_literal ... ok
test example3 ... ok
failures:
---- round_trip_key_special_chars stdout ----
parsing failed
thread 'round_trip_key_special_chars' panicked at 'assertion failed: `(left == right) && (right == left)` (left: `"~!@#$^&*()_+-`1234567890[]\\|/?><.,;:\' = 1\n"`, right: `"\"~!@#$^&*()_+-`1234567890[]\\\\|/?><.,;:\'\" = 1\n"`)', tests/valid.rs:188
failures:
round_trip_key_special_chars
test result: FAILED. 36 passed; 1 failed; 0 ignored; 0 measured
The version on crates.io is failing:
/home/travis/.cargo/registry/src/github.com-1ecc6299db9ec823/toml-0.1.3/src/lib.rs:80:1: 80:33 error: missing documentation for a type alias
/home/travis/.cargo/registry/src/github.com-1ecc6299db9ec823/toml-0.1.3/src/lib.rs:80 pub type TomlArray = Vec<Value>;
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/travis/.cargo/registry/src/github.com-1ecc6299db9ec823/toml-0.1.3/src/lib.rs:42:9: 42:21 note: lint level defined here
/home/travis/.cargo/registry/src/github.com-1ecc6299db9ec823/toml-0.1.3/src/lib.rs:42 #![deny(missing_docs)]
^~~~~~~~~~~~
It looks like this has been fixed on master. Thank you!
Not sure who maintains the documentation for the project, but the documentation indicates the follow line is valid:
let value = toml::Parser::new(toml).parse().unwrap();
If you get a moment to fix this it will be appreciated.
Here's some of the examples my automated testing with afl-fuzz spat out - these are all accepted as valid by toml-rs and rejected as invalid by pytoml:
0=0r=false
0=""o=""m=""r=""00="0"q="""0"""e="""0"""
[[0000l0]]
0="0"[[0000l0]]
0="0"[[0000l0]]
0="0"l="0"
0=[0]00=[0,0,0]t=["0","0","0"]s=[1000-00-00T00:00:00Z,2000-00-00T00:00:00Z]
0=0r0=0r=false
0=0r0=0r=falsefal=false
I've included a representative set of examples in case there's multiple bugs here.
I have a program that uses Serde to serialize/deserialize some types using this crate's encoder/decoder and Serde's custom derive annotations. The program compiles successfully, but when I run it and execute the serialization code path, the serialization call (my_type.serialize(&mut encoder)
) returns Error::InvalidMapKeyLocation
("a map cannot be at this location") with no other information. This seems like a bug in this crate since it seems like it should be able to work with any type that Serde can automatically implement traits for. How should I go about determining why this is happening? I can try to create a reduced test case if that'd be useful.
Decoding a struct that contains a sequence Vec<f64>
field fails for input that contains mixed integers / floats. Decoding a sequence of all floats works though
extern crate toml;
extern crate rustc_serialize;
#[derive(Debug, RustcDecodable)]
struct Config {
coefs: Vec<f64>,
}
let bad_test = r#"
coefs = [1, 2, 0.18530022764383866]
"#;
let good_test = r#"
coefs = [1.2, 2.2, 0.18530022764383866]
"#;
let config: Config = toml::decode_str(bad_test).unwrap(); // FAIL HERE
println!("value: {:?}", config);
Thanks in advance if you can help!
Here is a reproduction (pretend I'm actually doing something useful with the map).
extern crate toml;
#[test]
fn test() {
let config = r#"
[target]
[[target.Notifiers]]
url = "http://second.com"
[[target.notifiers]]
url = "http://first.com"
"#;
match toml::Parser::new(config).parse() {
Some(toml) => {
for (key, value) in toml.into_iter() {
match value.as_table() {
Some(node) => match node.get("notifiers") {
Some(notifiers) => {
match notifiers.as_slice() {
Some(notifiers) => {
notifiers.map(|x| println!("{:?}", x))
},
_ => ()
}
},
_ => ()
},
_ => ()
}
}
},
_ => ()
};
}
As an example:
extern crate toml;
extern crate serialize;
#[deriving(Decodable, Show)]
pub struct Food {
fruits: Vec<Fruit>
}
#[deriving(Decodable, Show)]
struct Fruit;
fn main() {
// This works fine, of course
let demo1: Option<Food> = toml::decode_str("[[fruits]]");
println!("demo1: {}", demo1);
// However this fails to decode and should result in an empty fruits Vec instead
let demo2: Option<Food> = toml::decode_str("");
println!("demo2: {}", demo2);
}
Output:
demo1: Some(Food { fruits: [Fruit] })
demo2: None
Expected output:
demo1: Some(Food { fruits: [Fruit] })
demo2: Some(Food { fruits: [] })
I'm not sure whether this is possible, feasible or in scope of this crate.
It would be nice to have a TOML <-> JSON translation (or more generic translation via serde to JSON, XML, YAML, whatever works). I care mostely about JSON, though.
How can I convince you? 😄
The spec has recently changed, we should update!
Spec changed in toml-lang/toml@5af8145
I've just categorized all the implementations in the TOML spec by version compliance, and I'd love to bump toml-rs up, as I know it's one of the most robust parsers. Think you can you address that in the Readme? Thanks!
... or there should be some obvious way to display a ParserError that includes display of a source location.
toml file:
[[values]]
foo = "baz"
[[values]]
foo = "qux"
code:
14 let values = value.lookup("values").unwrap();
15 println!("values: {}", values);
16 println!("########");
17 let value_0 = values.lookup("0").unwrap();
18 println!("0: {}", value_0);
output:
values: invalid toml array of tables[foo = "baz"
, foo = "qux"
]
########
0: foo = "baz"
Output first line contain "invalid toml array of tables". I think that the error in the file show.rs, string 41. Because it is valid toml file.
fails to build rust 1.0.0 alpha
Compiling toml v0.1.15 (https://github.com/alexcrichton/toml-rs#0a6a1cab)
/Users/mossplix/.cargo/git/checkouts/toml-rs-73fb57c92ca3f82c/master/src/parser.rs:31:10: 31:15 error: unknown derive
trait: Debug
/Users/mossplix/.cargo/git/checkouts/toml-rs-73fb57c92ca3f82c/master/src/parser.rs:31 #[derive(Debug)]
^~~~~
/Users/mossplix/.cargo/git/checkouts/toml-rs-73fb57c92ca3f82c/master/src/serialization.rs:69:10: 69:15 error: unknown derive
trait: Debug
/Users/mossplix/.cargo/git/checkouts/toml-rs-73fb57c92ca3f82c/master/src/serialization.rs:69 #[derive(Debug)]
^~~~~
/Users/mossplix/.cargo/git/checkouts/toml-rs-73fb57c92ca3f82c/master/src/serialization.rs:85:21: 85:26 error: unknown derive
trait: Debug
/Users/mossplix/.cargo/git/checkouts/toml-rs-73fb57c92ca3f82c/master/src/serialization.rs:85 #[derive(PartialEq, Debug)]
^~~~~
/Users/mossplix/.cargo/git/checkouts/toml-rs-73fb57c92ca3f82c/master/src/serialization.rs:94:21: 94:26 error: unknown derive
trait: Debug
/Users/mossplix/.cargo/git/checkouts/toml-rs-73fb57c92ca3f82c/master/src/serialization.rs:94 #[derive(PartialEq, Debug)]
^~~~~
error: aborting due to 4 previous errors
Could not compile toml
.
For example this input is accepted as valid:
foo=1000-00-00T00:00:00Z
My reading of RFC 3339 is that this is not valid, both day and month should be >= 1.
I can take a swing at fixing this but I'm not sure what the right approach would be. Maybe to add in a date time parsing library and offload the work onto that?
https://github.com/toml-lang/toml#string
Probably will be useful for cargo at a minimum
Maybe im missing it, but im looking for a mechanism to leave part of the toml unparsed, which allows rust to accept dynamic input. For instance, something akin to labeling a struct field type as interface{}
in go's json parser.
For example, you cant do something like:
#[derive(RustcDecodable)]
struct A {
v: Value,
}
and then decode the toml::Value manually afterwards because Value
is not Decodable
is there an easy mechanism to delay parsing?
If the enum
is unit-like it is not serialized by toml. At least I keep getting error.
If I try the same with rustc-serialize json
it is serialized without complaints.
A very-non-minimal test example is:
extern crate rustc_serialize;
extern crate toml;
use toml::{Encoder, Value};
use rustc_serialize::Encodable;
#[derive(RustcEncodable)]
enum Yolo { One, Two, Three }
#[derive(RustcEncodable)]
struct MyStruct { foo: isize, bar: String, baz: Yolo }
fn main() {
let my_struct = MyStruct { foo: 4, bar: "hello!".to_string(), baz: Yolo::One };
let mut e = Encoder::new();
my_struct.encode(&mut e).unwrap();
assert_eq!(e.toml.get(&"foo".to_string()), Some(&Value::Integer(4)))
}
This fails to run with
thread '<main>' panicked at 'called `Result::unwrap()` on an `Err` value: NoValue', ../src/libcore/result.rs:731.
Hi Alex,
I'm getting:
Compiling toml v0.1.3
/home/dan/.cargo/registry/src/github.com-1ecc6299db9ec823/toml-0.1.3/src/lib.rs:80:1: 80:33 error: missing documentation for a type alias
/home/dan/.cargo/registry/src/github.com-1ecc6299db9ec823/toml-0.1.3/src/lib.rs:80 pub type TomlArray = Vec<Value>;
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/dan/.cargo/registry/src/github.com-1ecc6299db9ec823/toml-0.1.3/src/lib.rs:42:9: 42:21 note: lint level defined here
/home/dan/.cargo/registry/src/github.com-1ecc6299db9ec823/toml-0.1.3/src/lib.rs:42 #![deny(missing_docs)]
^~~~~~~~~~~~
/home/dan/.cargo/registry/src/github.com-1ecc6299db9ec823/toml-0.1.3/src/lib.rs:81:1: 81:53 error: missing documentation for a type alias
/home/dan/.cargo/registry/src/github.com-1ecc6299db9ec823/toml-0.1.3/src/lib.rs:81 pub type TomlTable = TreeMap<string::String, Value>;
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/dan/.cargo/registry/src/github.com-1ecc6299db9ec823/toml-0.1.3/src/lib.rs:42:9: 42:21 note: lint level defined here
/home/dan/.cargo/registry/src/github.com-1ecc6299db9ec823/toml-0.1.3/src/lib.rs:42 #![deny(missing_docs)]
with:
rustc 0.13.0-nightly (6f4c11be3 2014-12-05 20:23:10 +0000)
Greetings,
Daniel
Hi. I'm playing with decode example and added channels
member to the struct and
This doesn't work
#[derive(Debug, RustcDecodable)]
struct Config {
global_string: Option<String>,
global_integer: Option<u64>,
server: Option<ServerConfig>,
peers: Option<Vec<PeerConfig>>,
channels: Vec<u8>,
}
http://play.integer32.com/?gist=1b59aed1fff3d968b3e705a60b0d2e24
while this works,
#[derive(Debug, RustcDecodable)]
struct Config {
global_string: Option<String>,
global_integer: Option<u64>,
channels: Vec<u8>,
server: Option<ServerConfig>,
peers: Option<Vec<PeerConfig>>,
}
http://play.integer32.com/?gist=e6758110c7793b90e8e7a6d287b87dba
Is this behaviour correct?
Good morning! toml
seems to have been broken by the closure updates and the changes to Encoder
and Decoder
:
toml-0.1.4/src/serialization.rs:222:5: 228:6 error: method
emit_enum_struct_variant
has 0 type parameters but its trait declaration has 1 type parameter [E0049]
I'm trying to fix this in one of my own libraries, and it's trickier than I expected.
The latest release notes:
* Don't emit leading spaces in the serialization of tables or arrays.
But leading newline characters are removed as well.. Is this intended?
I assume this is already on your radar, but I think it's important that this gets implemented soon: this parser currently rejects literal strings in key names, but people might want to use this syntax in Cargo in the not so distant future. That means people with an old version of Cargo (built with an old version of toml-rs) will not be able to parse those newer crate manifests. The only way to prevent this is to start shipping an updated parser soon.
I want to manipulate the contents of an existing TOML file. I started with something like this:
// The contents of the file. Let's pretend I read them from disk.
let toml = "
[test]
key = \"value\"
otherkey = \"othervalue\"
";
let mut table = toml::Parser::new(toml).parse().unwrap();
// Remove the "key" Item from the "test" Table.
table.get_mut("test").unwrap().as_table().unwrap().remove("key").unwrap();
// Turn the modified Table back into a String, ready to write back to the file.
let modified = toml::encode_str(&toml::Value::Table(table));
However, according to the documentation and the following error message, the Value struct's as_*()
methods can only return immutable structs. Am I missing something? Is there another, easier way to go about this? If not, I seriously recommend manipulating Values/Tables as a feature.
Thanks in advance.
Current signature: pub fn lookup<'a>(&'a self, path: &'a str) -> Option<&'a Value>
A better signature: pub fn lookup<'a, 'b>(&'a self, path: &'b str) -> Option<&'a Value>
Rationale:
The current signature is a problem because:
I can't even create a path to use lookup() because of the lifetime restriction. Example:
pub fn get_config_string<'a, 'b>(config: &'a Value, key: &'b str) -> Result<&'a str, MyError> {
let path = format!("init.{}", &key);
config.lookup(&path) <-- fails
Obviously it is "impossible" to create path with the required lifetime 'a.
(I need to limit lookups to subsets of a Value)
I've created my own branch with the 'better signature' and it works fine.
I can't see any downsides. Can you?
Thanks!
Unless I'm misunderstanding how I'm supposed to handle DecodeErrors, the c-tors for error kinds should be exported publicly, so I could handle them individually and write something like this:
fn foo_from_toml(toml_text: &str) -> Result<Foo, String> {
let mut parser = toml::Parser::new(toml_text);
match parser.parse() {
Some(value) => serialize::Decodable::decode(
&mut toml::Decoder::new(toml::Table(value))
).map_err(|e| show_decode_err(e)),
None => Err(format!("Error parsing TOML: {}", parser.errors))
}
}
fn show_decode_err(err: DecodeError) -> String {
format!("Error decoding Foo: in field '{}': {}",
err.field.unwrap_or("none".to_string()),
match err.kind {
ApplicationError(msg) => msg,
ExpectedField(e) => format!("expected field '{}'", e),
ExpectedType(e, f) => format!("expected a '{}', found a '{}'", e, f),
ExpectedMapKey(e) => format!("map key '{}' expected", e),
ExpectedMapElement(e) => format!("map value '{}' expected", e),
NoEnumVariants => format!("no enum variants"),
NilTooLong => format!("non-empty string for nil type")
})
}
There's a number of pain points with the current parser:
Cow
to slice back to the original source and only unescape when necessary. Arrays and maps may be able to be based on an iterator?toml::Value
but instead some form of AST. This AST may not have validation like no duplicate keys, no redefinitions, or arrays are homogneous. That kind of verification can perhaps be delayed to another step.Result
with an opaque error type which contains source information directly.While implemented, I'm not sure that I ever heavily scrutinized the implementation.
Got following traceback:
$ cargo build --verbose
Compiling toml v0.1.20
Running `rustc /home/seprich/.cargo/registry/src/github.com-1ecc6299db9ec823/toml-0.1.20/src/lib.rs --crate-name toml --crate-type lib -g -C metadata=e4d393d734aaa578 -C extra-filename=-e4d393d734aaa578 --out-dir /home/seprich/rust/manadochess/target/debug/deps --emit=dep-info,link -L dependency=/home/seprich/rust/manadochess/target/debug/deps -L dependency=/home/seprich/rust/manadochess/target/debug/deps --extern rustc_serialize=/home/seprich/rust/manadochess/target/debug/deps/librustc_serialize-2f8fcd98dcac2934.rlib -Awarnings`
Fresh rustc-serialize v0.3.10
/home/seprich/.cargo/registry/src/github.com-1ecc6299db9ec823/toml-0.1.20/src/parser.rs:394:27: 394:46 error: type `u32` does not implement any method in scope named `from_str_radix`
/home/seprich/.cargo/registry/src/github.com-1ecc6299db9ec823/toml-0.1.20/src/parser.rs:394 match u32::from_str_radix(num, 16).ok() {
^~~~~~~~~~~~~~~~~~~
/home/seprich/.cargo/registry/src/github.com-1ecc6299db9ec823/toml-0.1.20/src/parser.rs:394:46: 394:46 help: methods from traits can only be called if the trait is in scope; the following trait is implemented but not in scope, perhaps add a `use` for it:
/home/seprich/.cargo/registry/src/github.com-1ecc6299db9ec823/toml-0.1.20/src/parser.rs:394:46: 394:46 help: candidate #1: use `core::num::FromStrRadix`
error: aborting due to previous error
Could not compile `toml`.
Caused by:
Process didn't exit successfully: `rustc /home/seprich/.cargo/registry/src/github.com-1ecc6299db9ec823/toml-0.1.20/src/lib.rs --crate-name toml --crate-type lib -g -C metadata=e4d393d734aaa578 -C extra-filename=-e4d393d734aaa578 --out-dir /home/seprich/rust/manadochess/target/debug/deps --emit=dep-info,link -L dependency=/home/seprich/rust/manadochess/target/debug/deps -L dependency=/home/seprich/rust/manadochess/target/debug/deps --extern rustc_serialize=/home/seprich/rust/manadochess/target/debug/deps/librustc_serialize-2f8fcd98dcac2934.rlib -Awarnings` (exit code: 101)
my rustc version:
$ rustc --version
rustc 1.0.0-nightly (6cf3b0b74 2015-03-30) (built 2015-03-31)
It seems that from_str_radix
has been deprecated: https://doc.rust-lang.org/core/num/fn.from_str_radix.html
extern crate toml;
fn main() {
let args = std::os::args();
let mut parser = toml::Parser::new(args[1].as_slice());
let value = parser.parse();
println!("{}", value);
println!("{}", parser.errors);
}
$ ./foo 'value = "x"'
Some({value: "x"})
[]
$ ./foo 'value = ""'
None
[Error { lo: 10, hi: 10, desc: expected `"`, but found eof }]
The floating point tests fail on my system. I'm using:
cargo 0.0.1-pre-nightly (537b43c 2014-11-06 00:02:30 +0000)
rustc 0.13.0-nightly (45cbdec41 2014-11-07 00:02:18 +0000)
Linux 3.16.0-24-generic #32-Ubuntu SMP Tue Oct 28 13:07:32 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux
Intel(R) Core(TM) i7 CPU L 640
I guess floating point is hard but I'm seeing an out-by-ten error. I'm just starting rust so I'm not sure how to track down the issue.
toml-rs> cargo test
...
failures:
---- test::valid::float stdout ----
task 'test::valid::float' panicked at 'expected
{
"negpi": {
"type": "float",
"value": "-3.14"
},
"pi": {
"type": "float",
"value": "3.14"
}
}
got
{
"negpi": {
"type": "float",
"value": "-13.139999999999999"
},
"pi": {
"type": "float",
"value": "3.14"
}
}
', toml-rs/src/test/valid.rs:57
---- test::valid::long_float stdout ----
task 'test::valid::long_float' panicked at 'expected
{
"longpi": {
"type": "float",
"value": "3.141592653589793"
},
"neglongpi": {
"type": "float",
"value": "-3.141592653589793"
}
}
got
{
"longpi": {
"type": "float",
"value": "3.141592653589793"
},
"neglongpi": {
"type": "float",
"value": "-13.141592653589795"
}
}
', toml-rs/src/test/valid.rs:57
failures:
test::valid::float
test::valid::long_float
test result: FAILED. 89 passed; 2 failed; 0 ignored; 0 measured
Given:
#[derive(Debug, Clone, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)]
struct User {
pub name: String,
pub surname: String,
}
#[derive(Debug, Clone, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)]
struct Users {
pub user: Vec<User>,
}
encode_str(&Users {
user: vec![
User {
name: "John".to_string(),
surname: "Doe".to_string(),
},
User {
name: "Jane".to_string(),
surname: "Dough".to_string(),
},
],
))
One'd expect the result to be
[[user]]
name = "John"
surname = "Doe"
[[user]]
name = "Jane"
surname = "Dough"
But the output actually is
# Empty line
[[user]]
name = "John"
surname = "Doe"
[[user]]
name = "Jane"
surname = "Dough"
Which is rather ugly
#[derive(RustcEncodable, RustcDecodable, Debug)]
struct AA {
a: Vec<(i32,i32)>,
}
#[derive(RustcEncodable, RustcDecodable, Debug)]
struct BB {
b: Vec<(String, i32)>,
}
fn main() {
let a = AA { a: vec![(1, 2)] };
let a1 = toml::encode_str(&a);
println!("{:?}", a1);
let a2 = toml::decode_str::<AA>(&a1);
println!("{:?}", a2);
let b = BB { b: vec![("1".to_owned(), 2)] };
let b1 = toml::encode_str(&b);
println!("{:?}", b1);
let b2 = toml::decode_str::<BB>(&b1);
println!("{:?}", b2);
}
This print:
"a = [[1, 2]]
"
Some(AA { a: [(1, 2)] })
"b = [["1", 2]]
"
None
I am getting a failure when attempting to print successfully parsed TOML. If we use the below program as our src/main.rs
:
extern crate toml;
fn main() {
/* Exactly the example from the docs, with Cargo.lock TOML directly from the Cargo site */
let toml = r#"
[root]
name = "hello_world"
version = "0.0.1"
dependencies = [
"color 0.0.1 (git+https://github.com/bjz/color-rs.git#bf739419e2d31050615c1ba1a395b474269a4b98)",
]
[[package]]
name = "color"
version = "0.0.1"
source = "git+https://github.com/bjz/color-rs.git#bf739419e2d31050615c1ba1a395b474269a4b98"
"#;
let value = toml::Parser::new(toml).parse().unwrap();
println!("{}", value);
}
and we use the below as our Cargo.toml
:
[project]
name = "failing-show"
version = "0.0.0"
authors = []
[[bin]]
name = "failing-show"
[dependencies.toml]
git = "https://github.com/alexcrichton/toml-rs"
It results in:
task '<main>' failed at 'invalid toml array of tables', /Users/jroesch/.cargo/git/checkouts/toml-rs-73fb57c92ca3f82c/master/src/show.rs:39 {package: %
The exception is being throw here whenever one attempts to print an Array
of Table
s. The error message seems to suggest that this is an invalid state for a TOML value to be in, but it is not apparent to me why that would be (esp. since both Cargo and the TOML spec use examples like this). Any clarification would be great and I would happily author a PR if it is unintended behavior.
It would be nice for error reporting to be able to get the position (the span) of a specific TOML value in the file.
For example, I am parsing a configuration file for my project, and the user entered a string where an integer is needed. I would like to report the position of the error in addition with the usual "this key must be an integer"
message.
I do not know how hard this would be to implement, and how the API could look like. Having something like
struct Span {
file: Path,
line_start: usize,
line_end: usize,
col_start: usize,
col_end: usize,
}
enum Value {
String(String, Span),
Integer(i64, Span),
Float(f64, Span),
Boolean(bool, Span),
Datetime(String, Span),
Array(Array, Span),
Table(Table, Span),
}
would be rather inconvenient to use. Maybe something like that, with a duplication of methods on Value
and Entry
.
struct Entry {
value: Value,
span: Span
}
If you think this is not too hard, I can give it a try.
spec changed in toml-lang/toml#264
Parsing something like this:
[[foo]]
#…
[foo.bar]
#…
[[foo]]
#…
[foo.bar]
#...
results in:
ParserError { lo: 54, hi: 61, desc: redefinition of table `foo.bar` }
tomlv however accepts it happily:
$ tomlv -types /tmp/demo.toml
foo ArrayHash
foo.bar Hash
foo ArrayHash
foo.bar Hash
This is while building cargo:
"/usr/bin/rustc" -v
rustc 0.12.0-pre (1fb838d99 2014-09-21 05:45:31 +0000)
target/snapshot/bin/cargo build --target x86_64-unknown-linux-gnu
Updating git repository `https://github.com/alexcrichton/libssh2-static-sys`
Updating git repository `https://github.com/rust-lang/glob`
Updating git repository `https://github.com/alexcrichton/link-config`
Updating git repository `https://github.com/docopt/docopt.rs`
Updating git repository `https://github.com/alexcrichton/git2-rs`
Updating git repository `https://github.com/alexcrichton/curl-rust`
Updating git repository `https://github.com/rust-lang/semver`
Updating git repository `https://github.com/servo/rust-url`
Updating git repository `https://github.com/carllerche/hamcrest-rust.git`
Updating git repository `https://github.com/alexcrichton/openssl-static-sys`
Updating git repository `https://github.com/alexcrichton/flate2-rs`
Updating git repository `https://github.com/lifthrasiir/rust-encoding`
Updating git repository `https://github.com/alexcrichton/tar-rs`
Updating git repository `https://github.com/alexcrichton/toml-rs`
Compiling encoding v0.1.0 (https://github.com/lifthrasiir/rust-encoding#35f0d70f)
Compiling docopt v0.6.3 (https://github.com/docopt/docopt.rs#ee384409)
Compiling toml v0.1.0 (https://github.com/alexcrichton/toml-rs#5f5bd932)
Build failed, waiting for other jobs to finish...
Could not compile `toml`.
--- stderr
/home/mceier/.cargo/git/checkouts/toml-rs-73fb57c92ca3f82c/master/src/lib.rs:73:1: 73:29 error: duplicate definition of type or module `Array`
/home/mceier/.cargo/git/checkouts/toml-rs-73fb57c92ca3f82c/master/src/lib.rs:73 pub type Array = Vec<Value>;
^~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/mceier/.cargo/git/checkouts/toml-rs-73fb57c92ca3f82c/master/src/lib.rs:69:5: 69:17 note: first definition of type or module `Array` here
/home/mceier/.cargo/git/checkouts/toml-rs-73fb57c92ca3f82c/master/src/lib.rs:69 Array(Array),
^~~~~~~~~~~~
/home/mceier/.cargo/git/checkouts/toml-rs-73fb57c92ca3f82c/master/src/lib.rs:74:1: 74:41 error: duplicate definition of type or module `Table`
/home/mceier/.cargo/git/checkouts/toml-rs-73fb57c92ca3f82c/master/src/lib.rs:74 pub type Table = TreeMap<String, Value>;
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/mceier/.cargo/git/checkouts/toml-rs-73fb57c92ca3f82c/master/src/lib.rs:70:5: 70:17 note: first definition of type or module `Table` here
/home/mceier/.cargo/git/checkouts/toml-rs-73fb57c92ca3f82c/master/src/lib.rs:70 Table(Table),
^~~~~~~~~~~~
error: aborting due to 2 previous errors
To learn more, run the command again with --verbose.
Makefile:77: polecenia dla obiektu 'cargo-x86_64-unknown-linux-gnu' nie powiodły się
make: *** [cargo-x86_64-unknown-linux-gnu] Błąd 101
The same error is when using latest git versions of toml-rs, so it's not yet fixed:
"/usr/bin/rustc" -v
rustc 0.12.0-pre (1fb838d99 2014-09-21 05:45:31 +0000)
target/snapshot/bin/cargo build --target x86_64-unknown-linux-gnu
Updating git repository `https://github.com/alexcrichton/link-config`
Updating git repository `https://github.com/lifthrasiir/rust-encoding`
Updating git repository `https://github.com/servo/rust-url`
Updating git repository `https://github.com/alexcrichton/toml-rs`
Updating git repository `https://github.com/alexcrichton/curl-rust`
Updating git repository `https://github.com/rust-lang/glob`
Updating git repository `https://github.com/docopt/docopt.rs`
Updating git repository `https://github.com/alexcrichton/git2-rs`
Updating git repository `https://github.com/alexcrichton/flate2-rs`
Updating git repository `https://github.com/carllerche/hamcrest-rust.git`
Updating git repository `https://github.com/alexcrichton/tar-rs`
Updating git repository `https://github.com/alexcrichton/libssh2-static-sys`
Updating git repository `https://github.com/rust-lang/semver`
Updating git repository `https://github.com/alexcrichton/openssl-static-sys`
Compiling docopt v0.6.3 (https://github.com/docopt/docopt.rs#ee384409)
Compiling encoding v0.1.0 (https://github.com/lifthrasiir/rust-encoding#35f0d70f)
Compiling toml v0.1.0 (https://github.com/alexcrichton/toml-rs#1ca52c5e)
Compiling libgit2 v0.0.1 (https://github.com/alexcrichton/git2-rs#05276ae6)
Build failed, waiting for other jobs to finish...
Could not compile `toml`.
--- stderr
/home/mceier/.cargo/git/checkouts/toml-rs-73fb57c92ca3f82c/master/src/lib.rs:73:1: 73:29 error: duplicate definition of type or module `Array`
/home/mceier/.cargo/git/checkouts/toml-rs-73fb57c92ca3f82c/master/src/lib.rs:73 pub type Array = Vec<Value>;
^~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/mceier/.cargo/git/checkouts/toml-rs-73fb57c92ca3f82c/master/src/lib.rs:69:5: 69:17 note: first definition of type or module `Array` here
/home/mceier/.cargo/git/checkouts/toml-rs-73fb57c92ca3f82c/master/src/lib.rs:69 Array(Array),
^~~~~~~~~~~~
/home/mceier/.cargo/git/checkouts/toml-rs-73fb57c92ca3f82c/master/src/lib.rs:74:1: 74:41 error: duplicate definition of type or module `Table`
/home/mceier/.cargo/git/checkouts/toml-rs-73fb57c92ca3f82c/master/src/lib.rs:74 pub type Table = TreeMap<String, Value>;
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/mceier/.cargo/git/checkouts/toml-rs-73fb57c92ca3f82c/master/src/lib.rs:70:5: 70:17 note: first definition of type or module `Table` here
/home/mceier/.cargo/git/checkouts/toml-rs-73fb57c92ca3f82c/master/src/lib.rs:70 Table(Table),
^~~~~~~~~~~~
error: aborting due to 2 previous errors
To learn more, run the command again with --verbose.
Makefile:77: polecenia dla obiektu 'cargo-x86_64-unknown-linux-gnu' nie powiodły się
make: *** [cargo-x86_64-unknown-linux-gnu] Błąd 101
It seems like it would be much more convenient if Parser.parse
returned a result that includes the error if there's a failure. Any specific reason why it's an option? Would you be open to a pull to change this?
The toml 0.0.1 package on crates.io appears to be out of date, and I'd like to use to parse the exclude
list in my Cargo.toml
from a build script. Would it be possible to release an updated package at some point in the future?
Thank you again! (For approximately the 5th time today, I think—your help has been greatly appreciated.)
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.