pax_global_header00006660000000000000000000000064147157306030014520gustar00rootroot0000000000000052 comment=965be8521d521796350be1b964954c6cc7de54ae rust-sexpr-out-965be8521d521796350be1b964954c6cc7de54ae/000077500000000000000000000000001471573060300213445ustar00rootroot00000000000000rust-sexpr-out-965be8521d521796350be1b964954c6cc7de54ae/.gitignore000066400000000000000000000014361471573060300233400ustar00rootroot00000000000000# -*- mode: gitignore; -*- ### Emacs ### *~ \#*\# /.emacs.desktop /.emacs.desktop.lock *.elc auto-save-list tramp .\#* # Org-mode .org-id-locations *_archive # flymake-mode *_flymake.* # eshell files /eshell/history /eshell/lastdir # elpa packages /elpa/ # reftex files *.rel # AUCTeX auto folder /auto/ # cask packages .cask/ dist/ # Flycheck flycheck_*.el # server auth directory /server/ # projectiles files .projectile # directory configuration .dir-locals.el # network security /network-security.data ### Rust ### # Generated by Cargo # will have compiled files and executables /target/ # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html Cargo.lock rust-sexpr-out-965be8521d521796350be1b964954c6cc7de54ae/Cargo.toml000066400000000000000000000007551471573060300233030ustar00rootroot00000000000000[package] name = "sexpr-out" description = "Tools for writing S-Expressions from Rust data." version = "0.1.0" authors = ["Simon Johnston "] repository = "https://github.com/johnstonskj/rust-sexpr-out.git" license-file = "LICENSE" readme = "README.md" edition = "2021" publish = true [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] all-features = true [dependencies] itertools = "0.13.0" objio = "0.1.1" [dev-dependencies] pretty_assertions = "1.4" rust-sexpr-out-965be8521d521796350be1b964954c6cc7de54ae/LICENSE000066400000000000000000000261361471573060300223610ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. rust-sexpr-out-965be8521d521796350be1b964954c6cc7de54ae/README.md000066400000000000000000000015211471573060300226220ustar00rootroot00000000000000# Package sexpr-out Tools for writing S-Expressions from Rust data. # Example ```rust use objio::{HasOptions, ObjectWriter}; use pretty_assertions::assert_eq; use sexpr_out::value::Value; use sexpr_out::writer::{LanguageStyle, Options, Writer}; let writer = Writer::default().pretty_printed(true).with_options( Options::default() .with_line_width(20) .with_style(LanguageStyle::Racket), ); let list = Value::from(vec![ Value::from("hello"), Value::from("this"), Value::from("is"), Value::from("a"), Value::from("lisp"), Value::from("list"), ]); // 1 2 3 // 0123456789012345678901234567890 // ("hello" "this" "is" // "a" "lisp" "list") assert_eq!( writer.write_to_string(&list).unwrap(), "(\"hello\" \"this\" \"is\"\n \"a\" \"lisp\" \"list\")".to_string() ); ``` rust-sexpr-out-965be8521d521796350be1b964954c6cc7de54ae/src/000077500000000000000000000000001471573060300221335ustar00rootroot00000000000000rust-sexpr-out-965be8521d521796350be1b964954c6cc7de54ae/src/error.rs000066400000000000000000000056201471573060300236350ustar00rootroot00000000000000/*! Provides the crate's Error and Result types as well as helper functions. */ /* Copyright 2024 Simon Johnston Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ use std::fmt::{Debug, Display}; // ------------------------------------------------------------------------------------------------ // Public Types // ------------------------------------------------------------------------------------------------ /// /// The Error type for this crate. /// #[derive(Debug)] pub enum Error { /// An error was signaled by the standard library I/O functions. IoError { source: std::io::Error, }, SymbolParserError { source: String, }, } /// /// A Result type that specifically uses this crate's Error. /// pub type Result = std::result::Result; // ------------------------------------------------------------------------------------------------ // Public Functions // ------------------------------------------------------------------------------------------------ /// Construct an Error from the provided source. #[inline] pub fn io_error(source: std::io::Error) -> Error { Error::IoError { source } } /// Construct an Error from the provided source. #[inline] pub fn symbol_parser_error(source: S) -> Error where S: Into, { Error::SymbolParserError { source: source.into(), } } // ------------------------------------------------------------------------------------------------ // Implementations // ------------------------------------------------------------------------------------------------ impl Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "{}", match self { Error::IoError { source } => format!("An I/O error occurred; source: {}", source), Error::SymbolParserError { source } => format!( "An error occurred parsing a symbol string; source: {}", source ), } ) } } impl std::error::Error for Error { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { #[allow(unreachable_patterns)] match self { Error::IoError { source } => Some(source), _ => None, } } } impl From for Error { fn from(source: std::io::Error) -> Self { io_error(source) } } rust-sexpr-out-965be8521d521796350be1b964954c6cc7de54ae/src/lib.rs000066400000000000000000000033331471573060300232510ustar00rootroot00000000000000/*! One-line description. More detailed description, with # Example TBD # Features */ /* Copyright 2024 Simon Johnston Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #![warn( unknown_lints, // ---------- Stylistic absolute_paths_not_starting_with_crate, elided_lifetimes_in_paths, explicit_outlives_requirements, macro_use_extern_crate, nonstandard_style, /* group */ noop_method_call, rust_2018_idioms, single_use_lifetimes, trivial_casts, trivial_numeric_casts, // ---------- Future future_incompatible, /* group */ rust_2021_compatibility, /* group */ // ---------- Public missing_debug_implementations, // missing_docs, unreachable_pub, // ---------- Unsafe unsafe_code, unsafe_op_in_unsafe_fn, // ---------- Unused unused, /* group */ )] #![deny( // ---------- Public exported_private_dependencies, // ---------- Deprecated anonymous_parameters, bare_trait_objects, ellipsis_inclusive_range_patterns, // ---------- Unsafe deref_nullptr, drop_bounds, dyn_drop, )] pub mod error; pub use error::Error; pub mod value; pub use value::{Number, Value}; pub mod writer; pub use writer::{Options, Writer}; rust-sexpr-out-965be8521d521796350be1b964954c6cc7de54ae/src/value.rs000066400000000000000000000210101471573060300236070ustar00rootroot00000000000000/*! This module provides the common [`Value`] enum for atomic values (bool, integer, float, character, string, symbol, and keyword) and lists of values. Similar in approach to crates such as `serde_json` the [`Value`] enum is the representation of data supported directly by the representation, in this case Lisp-like s-expressions. Values are independent of *style* (corresponding to common Lisp families) which is applied when written. */ /* Copyright 2024 Simon Johnston Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // ------------------------------------------------------------------------------------------------ // Public Types // ------------------------------------------------------------------------------------------------ #[derive(Clone, Copy, Debug)] pub enum Number { Integer(i64), Flonum(f64), } #[derive(Clone, Debug)] pub struct Symbol(String); #[derive(Clone, Debug)] pub struct Keyword(Symbol); #[derive(Clone, Debug)] pub enum Value { Bool(bool), Number(Number), Character(char), String(String), Symbol(Symbol), Keyword(Keyword), List(Vec), } // ------------------------------------------------------------------------------------------------ // Implementations ❱ Number // ------------------------------------------------------------------------------------------------ impl From for Number { fn from(value: i64) -> Self { Self::Integer(value) } } impl From<&i64> for Number { fn from(value: &i64) -> Self { Self::Integer(*value) } } impl From for Number { fn from(value: i32) -> Self { Self::Integer(value as i64) } } impl From<&i32> for Number { fn from(value: &i32) -> Self { Self::Integer(*value as i64) } } impl From for Number { fn from(value: i16) -> Self { Self::Integer(value as i64) } } impl From<&i16> for Number { fn from(value: &i16) -> Self { Self::Integer(*value as i64) } } impl From for Number { fn from(value: i8) -> Self { Self::Integer(value as i64) } } impl From<&i8> for Number { fn from(value: &i8) -> Self { Self::Integer(*value as i64) } } impl From for Number { fn from(value: f64) -> Self { Self::Flonum(value) } } impl From<&f64> for Number { fn from(value: &f64) -> Self { Self::Flonum(*value) } } impl From for Number { fn from(value: f32) -> Self { Self::Flonum(value as f64) } } impl From<&f32> for Number { fn from(value: &f32) -> Self { Self::Flonum(*value as f64) } } impl Number { pub fn is_integer(&self) -> bool { matches!(self, Self::Integer(_)) } pub fn as_integer(&self) -> Option { match self { Number::Integer(v) => Some(*v), _ => None, } } pub fn is_flonum(&self) -> bool { matches!(self, Self::Flonum(_)) } pub fn as_flonum(&self) -> Option { match self { Number::Flonum(v) => Some(*v), _ => None, } } } // ------------------------------------------------------------------------------------------------ // Implementations ❱ Symbol // ------------------------------------------------------------------------------------------------ impl AsRef for Symbol { fn as_ref(&self) -> &str { &self.0 } } impl From for String { fn from(value: Symbol) -> Self { value.0 } } impl Symbol { pub fn new(s: S) -> Self where S: Into, { Self(s.into()) } pub fn inner(&self) -> String { self.0.clone() } } // ------------------------------------------------------------------------------------------------ // Implementations ❱ Keyword // ------------------------------------------------------------------------------------------------ impl From for Keyword { fn from(value: Symbol) -> Self { Self(value) } } impl From for Symbol { fn from(value: Keyword) -> Self { value.0 } } impl From for String { fn from(value: Keyword) -> Self { value.0.into() } } impl Keyword { pub fn new(s: S) -> Self where S: Into, { Self(Symbol::new(s.into())) } pub fn inner(&self) -> Symbol { self.0.clone() } } // ------------------------------------------------------------------------------------------------ // Implementations ❱ Value::Bool // ------------------------------------------------------------------------------------------------ impl From for Value { fn from(value: bool) -> Self { Self::Bool(value) } } impl From<&bool> for Value { fn from(value: &bool) -> Self { Self::Bool(*value) } } // ------------------------------------------------------------------------------------------------ // Implementations ❱ Value::Number // ------------------------------------------------------------------------------------------------ impl> From for Value { fn from(value: N) -> Self { Self::Number(value.into()) } } // ------------------------------------------------------------------------------------------------ // Implementations ❱ Value::Character // ------------------------------------------------------------------------------------------------ impl From for Value { fn from(value: char) -> Self { Self::Character(value) } } impl From<&char> for Value { fn from(value: &char) -> Self { Self::Character(*value) } } // ------------------------------------------------------------------------------------------------ // Implementations ❱ Value::String // ------------------------------------------------------------------------------------------------ impl From for Value { fn from(value: String) -> Self { Self::String(value) } } impl From<&String> for Value { fn from(value: &String) -> Self { Self::String(value.clone()) } } impl From<&str> for Value { fn from(value: &str) -> Self { Self::String(value.to_string()) } } // ------------------------------------------------------------------------------------------------ // Implementations ❱ Value::Symbol // ------------------------------------------------------------------------------------------------ impl From for Value { fn from(value: Symbol) -> Self { Self::Symbol(value) } } impl From<&Symbol> for Value { fn from(value: &Symbol) -> Self { Self::Symbol(value.clone()) } } // ------------------------------------------------------------------------------------------------ // Implementations ❱ Value::Keyword // ------------------------------------------------------------------------------------------------ impl From for Value { fn from(value: Keyword) -> Self { Self::Keyword(value) } } impl From<&Keyword> for Value { fn from(value: &Keyword) -> Self { Self::Keyword(value.clone()) } } // ------------------------------------------------------------------------------------------------ // Implementations ❱ Value::List // ------------------------------------------------------------------------------------------------ impl From> for Value { fn from(value: Vec) -> Self { Self::List(value) } } impl From<&Vec> for Value { fn from(value: &Vec) -> Self { Self::List(value.clone()) } } impl From<&[Value]> for Value { fn from(value: &[Value]) -> Self { Self::List(value.to_vec()) } } impl FromIterator for Value { fn from_iter>(iter: T) -> Self { Self::List(Vec::from_iter(iter)) } } // ------------------------------------------------------------------------------------------------ // Implementations ❱ Value // ------------------------------------------------------------------------------------------------ impl Value { pub fn empty_list() -> Self { Self::List(Vec::default()) } } rust-sexpr-out-965be8521d521796350be1b964954c6cc7de54ae/src/writer.rs000066400000000000000000000650621471573060300240260ustar00rootroot00000000000000/*! This module provides the ability to write `Value`s in different language styles with an option to *pretty print* nested values. # Example ```rust use objio::{HasOptions, ObjectWriter}; use sexpr_out::{value::Value, writer::{LanguageStyle, Options, Writer}}; let writer = Writer::default().with_options( Options::default().with_style(LanguageStyle::Racket) ); assert_eq!( writer.write_to_string(&Value::from(true)).unwrap(), "#t".to_string() ); ``` */ /* Copyright 2024 Simon Johnston Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ use crate::{ value::{Keyword, Number, Symbol}, Error, Value, }; use itertools::{Itertools, Position}; use objio::{HasOptions, ObjectWriter}; use std::io::Write; // ------------------------------------------------------------------------------------------------ // Public Types // ------------------------------------------------------------------------------------------------ #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub enum LanguageStyle { #[default] Racket, TreeSitter, CommonLisp, Scheme, // as of R7RS EmacsLisp, } #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub enum QuoteStyle { #[default] None, All(bool), AsNeeded(bool), } #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub struct Options { line_width: usize, pair_kw_args: bool, wrap_in_define: bool, style: LanguageStyle, quote: QuoteStyle, } #[derive(Debug, Default)] pub struct Writer { options: Options, pretty_print: bool, } // ------------------------------------------------------------------------------------------------ // Private Types // ------------------------------------------------------------------------------------------------ pub(crate) trait Printable { fn stringify(&self, style: LanguageStyle) -> String; fn printed_length(&self, style: LanguageStyle) -> usize { self.stringify(style).len() } fn print(&self, w: &mut W, style: LanguageStyle) -> Result<(), Error> where W: Write, { Ok(w.write_all(self.stringify(style).as_bytes())?) } fn pretty_print( &self, w: &mut W, _current_indentation: usize, _line_width: usize, style: LanguageStyle, ) -> Result<(), Error> where W: Write, { self.print(w, style) } } // ------------------------------------------------------------------------------------------------ // Private Values // ------------------------------------------------------------------------------------------------ /// List Delimiters const CHAR_LIST_OPEN: char = '('; const CHAR_LIST_CLOSE: char = ')'; const LIST_OPEN: &[u8] = b"("; const LIST_CLOSE: &[u8] = b")"; const EMPTY_LIST: &[u8] = b"()"; const CHAR_SQLIST_OPEN: char = '['; const CHAR_SQLIST_CLOSE: char = ']'; /// Separators Separator const STR_EMPTY: &str = ""; const SPACE: &[u8] = b" "; const NEWLINE: &[u8] = b"\n"; const CHAR_NEWLINE: char = '\n'; /// Special Reader Syntax const CHAR_NUMBER_SIGN: char = '#'; const CHAR_COLON: char = ':'; const CHAR_SEMICOLON: char = ';'; const CHAR_PERIOD: char = '.'; /// Escaping const CHAR_BACKSLASH: char = '\\'; const CHAR_VERTICAL_BAR: char = '|'; const STR_VERTICAL_BAR: &str = "|"; /// Quoting const CHAR_QUOTE: char = '\''; const CHAR_QUASI_QUOTE: char = '`'; const CHAR_UNQUOTE: char = ','; const CHAR_OTHER_QUOTE: char = '‘'; const KEYWORD_FALSE: &str = "f"; const KEYWORD_FALSE_LONG: &str = "false"; const KEYWORD_TRUE: &str = "t"; const KEYWORD_TRUE_LONG: &str = "true"; const KEYWORD_NIL: &str = "nil"; const RACKET_SYMBOL_PREFIX: &str = "#%"; const CHAR_PREFIX: &str = "#\\"; const CHAR_PREFIX_UNICODE: &str = "#\\u"; const CHAR_PREFIX_UNICODE_LONG: &str = "#\\U"; const SCHEME_CHAR_PREFIX_UNICODE: &str = "#\\x"; const ELISP_CHAR_PREFIX: &str = "?"; const ELISP_CHAR_PREFIX_ESC: &str = "?\\"; const ELISP_CHAR_PREFIX_UNICODE: &str = "?\\u"; const ELISP_CHAR_PREFIX_UNICODE_LONG: &str = "?\\U"; // ------------------------------------------------------------------------------------------------ // Implementations ❱ QuoteStyle // ------------------------------------------------------------------------------------------------ impl QuoteStyle { pub fn is_long_form(&self) -> bool { match self { Self::None => false, Self::All(v) => *v, Self::AsNeeded(v) => *v, } } } // ------------------------------------------------------------------------------------------------ // Implementations ❱ Options // ------------------------------------------------------------------------------------------------ impl Options { pub fn with_line_width(self, line_width: usize) -> Self { let mut self_mut = self; self_mut.set_line_width(line_width); self_mut } pub fn line_width(&self) -> &usize { &self.line_width } pub fn set_line_width(&mut self, line_width: usize) { assert!(line_width >= 20); self.line_width = line_width; } // -------------------------------------------------------------------------------------------- pub fn with_style(self, style: LanguageStyle) -> Self { let mut self_mut = self; self_mut.set_style(style); self_mut } pub fn style(&self) -> &LanguageStyle { &self.style } pub fn set_style(&mut self, style: LanguageStyle) { self.style = style; } // -------------------------------------------------------------------------------------------- pub fn with_wrap_in_define(self, wrap_in_define: bool) -> Self { let mut self_mut = self; self_mut.set_wrap_in_define(wrap_in_define); self_mut } pub fn wrap_in_define(&self) -> &bool { &self.wrap_in_define } pub fn set_wrap_in_define(&mut self, wrap_in_define: bool) { self.wrap_in_define = wrap_in_define; } // -------------------------------------------------------------------------------------------- pub fn with_quote(self, quote: QuoteStyle) -> Self { let mut self_mut = self; self_mut.set_quote(quote); self_mut } pub fn quote(&self) -> &QuoteStyle { &self.quote } pub fn set_quote(&mut self, quote: QuoteStyle) { self.quote = quote; } } // ------------------------------------------------------------------------------------------------ // Implementations ❱ Writer // ------------------------------------------------------------------------------------------------ impl HasOptions for Writer { fn set_options(&mut self, options: Options) { self.options = options; } fn options(&self) -> &Options { &self.options } } impl ObjectWriter for Writer { type Error = Error; fn write(&self, w: &mut W, object: &Value) -> Result<(), Self::Error> where W: Write, { if self.pretty_print { object.pretty_print(w, 0, self.options.line_width, self.options.style)?; w.write_all(NEWLINE)?; Ok(()) } else { object.print(w, self.options.style) } } } impl Writer { pub fn pretty_printed(self, pretty_print: bool) -> Self { let mut self_mut = self; self_mut.set_pretty_print(pretty_print); self_mut } pub fn pretty_print(&self) -> bool { self.pretty_print } pub fn set_pretty_print(&mut self, pretty_print: bool) { self.pretty_print = pretty_print; } } // ------------------------------------------------------------------------------------------------ // Implementations ❱ Printables // ------------------------------------------------------------------------------------------------ macro_rules! display_to_printable { ($type:ty) => { impl Printable for $type { fn stringify(&self, _: LanguageStyle) -> String { self.to_string() } } }; } // ------------------------------------------------------------------------------------------------ display_to_printable!(i64); // ------------------------------------------------------------------------------------------------ display_to_printable!(f64); // ------------------------------------------------------------------------------------------------ impl Printable for Number { fn stringify(&self, style: LanguageStyle) -> String { match self { Number::Integer(v) => v.stringify(style), Number::Flonum(v) => v.stringify(style), } } } // ------------------------------------------------------------------------------------------------ /// /// From https://docs.racket-lang.org/guide/symbols.html /// /// Any string (i.e., any character sequence) can be supplied to string->symbol to obtain the /// corresponding symbol. For reader input, any character can appear directly in an identifier, /// except for whitespace and the following special characters: /// /// ( ) [ ] { } " , ' ` ; # | \ /// /// Actually, # is disallowed only at the beginning of a symbol, and then only if not followed by %; /// otherwise, # is allowed, too. Also, . by itself is not a symbol. /// /// Whitespace or special characters can be included in an identifier by quoting them with | or \. /// These quoting mechanisms are used in the printed form of identifiers that contain special /// characters or that might otherwise look like numbers. /// /// A #% also starts a symbol. (From https://docs.racket-lang.org/reference/reader.html#%28part._parse-symbol%29) /// impl Printable for Symbol { fn stringify(&self, style: LanguageStyle) -> String { fn inner(s: &str, style: LanguageStyle) -> String { let mut add_multi_escape = false; let new_s = s .chars() .tuple_windows() .map(|(c0, c1)| { if c1 == CHAR_VERTICAL_BAR && c0 != CHAR_BACKSLASH { add_multi_escape = true; format!("{c0}{CHAR_BACKSLASH}{CHAR_VERTICAL_BAR}") } else if is_char_nonprintable(c0) { add_multi_escape = true; format!("{}{c1}", string_escape_char(c0, style)) } else { format!("{c0}{c1}") } }) .collect::(); if add_multi_escape || new_s != s { format!("{CHAR_VERTICAL_BAR}{new_s}{CHAR_VERTICAL_BAR}") } else { new_s } } if style == LanguageStyle::TreeSitter { // a shame... self.inner() } else { let s = self.as_ref(); if style == LanguageStyle::Racket && s.starts_with(RACKET_SYMBOL_PREFIX) { inner(&s[2..], style) } else if s.starts_with(CHAR_VERTICAL_BAR) && s.ends_with(CHAR_VERTICAL_BAR) { let len = s.len() - 2; inner(&s[1..len], style) } else { inner(s, style) } } } fn printed_length(&self, style: LanguageStyle) -> usize { self.stringify(style).len() } fn print(&self, w: &mut W, style: LanguageStyle) -> Result<(), Error> where W: Write, { Ok(w.write_all(self.stringify(style).as_bytes())?) } fn pretty_print( &self, w: &mut W, _current_indentation: usize, _line_width: usize, style: LanguageStyle, ) -> Result<(), Error> where W: Write, { self.print(w, style) } } // ------------------------------------------------------------------------------------------------ impl Printable for Keyword { fn stringify(&self, style: LanguageStyle) -> String { let inner = self.inner().stringify(style); match style { LanguageStyle::Racket => format!("{CHAR_NUMBER_SIGN}{CHAR_COLON}{inner}"), LanguageStyle::TreeSitter => format!("{inner}{CHAR_COLON}"), LanguageStyle::CommonLisp => format!("{CHAR_COLON}{inner}"), LanguageStyle::Scheme => format!("{CHAR_COLON}{inner}"), LanguageStyle::EmacsLisp => format!("{CHAR_COLON}{inner}"), } } } // ------------------------------------------------------------------------------------------------ impl Printable for bool { fn stringify(&self, style: LanguageStyle) -> String { match (style, *self) { (LanguageStyle::Racket, true) => format!("{CHAR_NUMBER_SIGN}{KEYWORD_TRUE}"), (LanguageStyle::Racket, false) => format!("{CHAR_NUMBER_SIGN}{KEYWORD_FALSE}"), (LanguageStyle::TreeSitter, true) => KEYWORD_TRUE_LONG.to_string(), (LanguageStyle::TreeSitter, false) => KEYWORD_FALSE_LONG.to_string(), (LanguageStyle::CommonLisp, true) => KEYWORD_TRUE.to_string(), (LanguageStyle::CommonLisp, false) => KEYWORD_NIL.to_string(), (LanguageStyle::Scheme, true) => format!("{CHAR_NUMBER_SIGN}{KEYWORD_TRUE}"), (LanguageStyle::Scheme, false) => format!("{CHAR_NUMBER_SIGN}{KEYWORD_FALSE}"), (LanguageStyle::EmacsLisp, true) => KEYWORD_TRUE.to_string(), (LanguageStyle::EmacsLisp, false) => KEYWORD_NIL.to_string(), } } } // ------------------------------------------------------------------------------------------------ impl Printable for char { fn stringify(&self, style: LanguageStyle) -> String { fn escape( c: char, std_prefix: &str, esc_prefix: &str, long_esc_prefix: Option<&str>, ) -> String { println!("escape char {:06X}?", c as u32); match c { '\u{0000}'..'\u{0008}' | '\u{000B}'..'\u{001F}' | '\u{007F}'..'\u{009F}' | '\u{2000}'..'\u{200F}' | '\u{2028}'..'\u{202F}' | '\u{205F}'..'\u{206F}' | '\u{3000}'..'\u{FEFF}' => format!("{esc_prefix}{:04X}", c as u32), '\u{E0100}'..'\u{E01EF}' => { format!("{}{:06X}", long_esc_prefix.unwrap_or(esc_prefix), c as u32) } _ => format!("{std_prefix}{c}"), } } match (*self, style) { ('\u{00}', LanguageStyle::Racket) => format!("{CHAR_PREFIX}null"), ('\u{08}', LanguageStyle::Racket) => { format!("{CHAR_PREFIX}backspace") } ('\u{09}', LanguageStyle::Racket) => format!("{CHAR_PREFIX}tab"), ('\u{0A}', LanguageStyle::Racket) => { format!("{CHAR_PREFIX}newline") } ('\u{0B}', LanguageStyle::Racket) => format!("{CHAR_PREFIX}vtab"), ('\u{0C}', LanguageStyle::Racket) => format!("{CHAR_PREFIX}page"), ('\u{0D}', LanguageStyle::Racket) => { format!("{CHAR_PREFIX}return") } ('\u{20}', LanguageStyle::Racket) => format!("{CHAR_PREFIX}space"), ('\u{7F}', LanguageStyle::Racket) => { format!("{CHAR_PREFIX}rubout") } (c, LanguageStyle::Racket) => escape( c, CHAR_PREFIX, CHAR_PREFIX_UNICODE, Some(CHAR_PREFIX_UNICODE_LONG), ), (c, LanguageStyle::TreeSitter) => format!("{c:?}"), ('\u{08}', LanguageStyle::CommonLisp) => format!("{CHAR_PREFIX}Backspace"), ('\u{09}', LanguageStyle::CommonLisp) => format!("{CHAR_PREFIX}Tab"), ('\u{0A}', LanguageStyle::CommonLisp) => format!("{CHAR_PREFIX}Newline"), ('\u{0C}', LanguageStyle::CommonLisp) => format!("{CHAR_PREFIX}Page"), ('\u{0D}', LanguageStyle::CommonLisp) => format!("{CHAR_PREFIX}Return"), ('\u{20}', LanguageStyle::CommonLisp) => format!("{CHAR_PREFIX}Space"), ('\u{7F}', LanguageStyle::CommonLisp) => format!("{CHAR_PREFIX}Rubout"), (c, LanguageStyle::CommonLisp) => { escape(c, CHAR_PREFIX, CHAR_PREFIX_UNICODE_LONG, None) } ('\u{00}', LanguageStyle::Scheme) => format!("{CHAR_PREFIX}null"), ('\u{07}', LanguageStyle::Scheme) => format!("{CHAR_PREFIX}alarm"), ('\u{08}', LanguageStyle::Scheme) => format!("{CHAR_PREFIX}backspace"), ('\u{09}', LanguageStyle::Scheme) => format!("{CHAR_PREFIX}tab"), ('\u{0A}', LanguageStyle::Scheme) => format!("{CHAR_PREFIX}newline"), ('\u{0D}', LanguageStyle::Scheme) => format!("{CHAR_PREFIX}return"), ('\u{1B}', LanguageStyle::Scheme) => format!("{CHAR_PREFIX}escape"), ('\u{20}', LanguageStyle::Scheme) => format!("{CHAR_PREFIX}space"), ('\u{7F}', LanguageStyle::Scheme) => format!("{CHAR_PREFIX}delete"), (c, LanguageStyle::Scheme) => escape(c, CHAR_PREFIX, SCHEME_CHAR_PREFIX_UNICODE, None), ('\u{00}', LanguageStyle::EmacsLisp) => format!("{ELISP_CHAR_PREFIX_UNICODE}00"), ('\u{07}', LanguageStyle::EmacsLisp) => format!("{ELISP_CHAR_PREFIX_ESC}a"), ('\u{08}', LanguageStyle::EmacsLisp) => format!("{ELISP_CHAR_PREFIX_ESC}b"), ('\u{09}', LanguageStyle::EmacsLisp) => format!("{ELISP_CHAR_PREFIX_ESC}t"), ('\u{0A}', LanguageStyle::EmacsLisp) => format!("{ELISP_CHAR_PREFIX_ESC}n"), ('\u{0B}', LanguageStyle::EmacsLisp) => format!("{ELISP_CHAR_PREFIX_ESC}v"), ('\u{0C}', LanguageStyle::EmacsLisp) => format!("{ELISP_CHAR_PREFIX_ESC}f"), ('\u{0D}', LanguageStyle::EmacsLisp) => format!("{ELISP_CHAR_PREFIX_ESC}r"), ('\u{1B}', LanguageStyle::EmacsLisp) => format!("{ELISP_CHAR_PREFIX_ESC}e"), ('\u{20}', LanguageStyle::EmacsLisp) => format!("{ELISP_CHAR_PREFIX_ESC}s"), ('\u{7F}', LanguageStyle::EmacsLisp) => format!("{ELISP_CHAR_PREFIX_ESC}d"), ( c @ (CHAR_LIST_OPEN | CHAR_LIST_CLOSE | CHAR_SQLIST_OPEN | CHAR_SQLIST_CLOSE | CHAR_BACKSLASH | CHAR_SEMICOLON | CHAR_VERTICAL_BAR | CHAR_QUOTE | CHAR_QUASI_QUOTE | CHAR_NUMBER_SIGN | CHAR_PERIOD | CHAR_UNQUOTE | CHAR_OTHER_QUOTE), LanguageStyle::EmacsLisp, ) => format!("{ELISP_CHAR_PREFIX_ESC}{c}"), (c, LanguageStyle::EmacsLisp) => escape( c, ELISP_CHAR_PREFIX, ELISP_CHAR_PREFIX_UNICODE, Some(ELISP_CHAR_PREFIX_UNICODE_LONG), ), } } } // ------------------------------------------------------------------------------------------------ impl Printable for String { fn stringify(&self, style: LanguageStyle) -> String { format!( "{:?}", if self.len() == 1 { let c = self.chars().next().unwrap(); if is_char_nonprintable(c) { string_escape_char(c, style) } else { c.to_string() } } else { self.chars() .tuple_windows() .with_position() .map(|(p, (c0, c1))| { if c1 == CHAR_VERTICAL_BAR && c0 != CHAR_BACKSLASH { format!( "{c0}{CHAR_BACKSLASH}{}", if p == Position::Last { STR_VERTICAL_BAR } else { STR_EMPTY } ) } else { match (p, is_char_nonprintable(c0), is_char_nonprintable(c1)) { (Position::Last | Position::Only, true, true) => { format!( "{}{}", string_escape_char(c0, style), string_escape_char(c1, style) ) } (Position::Last | Position::Only, true, false) => { format!("{}{}", string_escape_char(c0, style), c1) } (Position::Last | Position::Only, false, true) => { format!("{}{}", c0, string_escape_char(c1, style)) } (Position::Last | Position::Only, false, false) => { format!("{}{}", c0, c1) } (_, true, _) => string_escape_char(c0, style), (_, false, _) => c0.to_string(), } } }) .collect::() } ) } } // ------------------------------------------------------------------------------------------------ impl Printable for Vec { fn stringify(&self, style: LanguageStyle) -> String { format!( "{}{}{}", CHAR_LIST_OPEN, self.iter() .map(|v| v.stringify(style)) .collect::>() .join(" "), CHAR_LIST_CLOSE, ) } fn printed_length(&self, style: LanguageStyle) -> usize { self.iter().fold(0, |t, v| t + v.printed_length(style)) // add inter-datum spaces + if self.len() < 2 { 0 } else { self.len() - 1 } } fn print(&self, w: &mut W, style: LanguageStyle) -> Result<(), crate::Error> where W: std::io::Write, { if self.is_empty() { w.write_all(EMPTY_LIST)?; } else { w.write_all(LIST_OPEN)?; for (value, is_last) in self .iter() .enumerate() .map(|(i, v)| (v, i == self.len() - 1)) { value.print(w, style)?; if !is_last { w.write_all(SPACE)?; } } w.write_all(LIST_CLOSE)?; } Ok(()) } fn pretty_print( &self, w: &mut W, current_indentation: usize, line_width: usize, style: LanguageStyle, ) -> Result<(), crate::Error> where W: std::io::Write, { let print_width = self.printed_length(style); if self.is_empty() { w.write_all(EMPTY_LIST)?; } else if current_indentation + print_width < line_width { self.print(w, style)?; } else { let current_indentation = current_indentation + 1; // one '(' let mut current_width = current_indentation; w.write_all(LIST_OPEN)?; let last_value_index: usize = self.len() - 1; for (i, v) in self.iter().enumerate() { current_width += v.printed_length(style); v.pretty_print(w, current_indentation, line_width, style)?; if i < last_value_index { let next_width = self.get(i + 1).unwrap().printed_length(style); if (current_width + next_width + 1) >= line_width { newline_and_indent(current_indentation, w)?; current_width = current_indentation; } else { w.write_all(SPACE)?; } } } w.write_all(LIST_CLOSE)?; } Ok(()) } } // ------------------------------------------------------------------------------------------------ impl Printable for Value { fn stringify(&self, style: LanguageStyle) -> String { match self { Value::Bool(v) => v.stringify(style), Value::Number(v) => v.stringify(style), Value::Character(v) => v.stringify(style), Value::String(v) => v.stringify(style), Value::Symbol(v) => v.stringify(style), Value::Keyword(v) => v.stringify(style), Value::List(v) => v.stringify(style), } } fn pretty_print( &self, w: &mut W, current_indentation: usize, line_width: usize, style: LanguageStyle, ) -> Result<(), Error> where W: Write, { match self { Value::Bool(v) => v.pretty_print(w, current_indentation, line_width, style), Value::Number(v) => v.pretty_print(w, current_indentation, line_width, style), Value::Character(v) => v.pretty_print(w, current_indentation, line_width, style), Value::String(v) => v.pretty_print(w, current_indentation, line_width, style), Value::Symbol(v) => v.pretty_print(w, current_indentation, line_width, style), Value::Keyword(v) => v.pretty_print(w, current_indentation, line_width, style), Value::List(v) => v.pretty_print(w, current_indentation, line_width, style), } } } // ------------------------------------------------------------------------------------------------ // Private Functions // ------------------------------------------------------------------------------------------------ #[inline(always)] fn is_char_nonprintable(c: char) -> bool { matches!(c, '\u{0000}'..'\u{0008}' | '\u{000B}'..'\u{001F}' | '\u{007F}'..'\u{009F}' | '\u{2000}'..'\u{200F}' | '\u{2028}'..'\u{202F}' | '\u{205F}'..'\u{206F}' | '\u{3000}'..'\u{FEFF}' | '\u{E0100}'..'\u{E01EF}') } #[inline(always)] fn newline_and_indent(indent: usize, writer: &mut W) -> Result<(), Error> where W: Write, { writer.write_all(format!("{CHAR_NEWLINE}{:indent$}", " ").as_bytes())?; Ok(()) } fn string_escape_char(c: char, style: LanguageStyle) -> String { match style { LanguageStyle::Racket => { if c.is_control() { format!("\\u{:04X}", c as u32) } else { c.to_string() } } LanguageStyle::TreeSitter => todo!(), LanguageStyle::CommonLisp => todo!(), LanguageStyle::Scheme => todo!(), LanguageStyle::EmacsLisp => todo!(), } } rust-sexpr-out-965be8521d521796350be1b964954c6cc7de54ae/tests/000077500000000000000000000000001471573060300225065ustar00rootroot00000000000000rust-sexpr-out-965be8521d521796350be1b964954c6cc7de54ae/tests/test_writer.rs000066400000000000000000000172651471573060300254420ustar00rootroot00000000000000use objio::{HasOptions, ObjectWriter}; use pretty_assertions::assert_eq; use sexpr_out::value::Value; use sexpr_out::writer::{LanguageStyle, Options, Writer}; #[test] fn test_print_single_boolean_racket() { let writer = Writer::default().with_options(Options::default().with_style(LanguageStyle::Racket)); assert_eq!( writer.write_to_string(&Value::from(true)).unwrap(), "#t".to_string() ); assert_eq!( writer.write_to_string(&Value::from(false)).unwrap(), "#f".to_string() ); } #[test] fn test_print_single_boolean_treesitter() { let writer = Writer::default().with_options(Options::default().with_style(LanguageStyle::TreeSitter)); assert_eq!( writer.write_to_string(&Value::from(true)).unwrap(), "true".to_string() ); assert_eq!( writer.write_to_string(&Value::from(false)).unwrap(), "false".to_string() ); } #[test] fn test_print_single_boolean_clisp() { let writer = Writer::default().with_options(Options::default().with_style(LanguageStyle::CommonLisp)); assert_eq!( writer.write_to_string(&Value::from(true)).unwrap(), "t".to_string() ); assert_eq!( writer.write_to_string(&Value::from(false)).unwrap(), "nil".to_string() ); } #[test] fn test_print_single_boolean_scheme() { let writer = Writer::default().with_options(Options::default().with_style(LanguageStyle::Scheme)); assert_eq!( writer.write_to_string(&Value::from(true)).unwrap(), "#t".to_string() ); assert_eq!( writer.write_to_string(&Value::from(false)).unwrap(), "#f".to_string() ); } #[test] fn test_print_single_boolean_elisp() { let writer = Writer::default().with_options(Options::default().with_style(LanguageStyle::EmacsLisp)); assert_eq!( writer.write_to_string(&Value::from(true)).unwrap(), "t".to_string() ); assert_eq!( writer.write_to_string(&Value::from(false)).unwrap(), "nil".to_string() ); } #[test] fn test_print_single_char_racket() { let writer = Writer::default().with_options(Options::default().with_style(LanguageStyle::Racket)); assert_eq!( writer.write_to_string(&Value::from('a')).unwrap(), r"#\a".to_string() ); assert_eq!( writer.write_to_string(&Value::from('\n')).unwrap(), r"#\newline".to_string() ); // assert_eq!('§'.to_string_for(LanguageStyle::Racket), r"#\§".to_string()); // assert_eq!( // '\u{3001}'.to_string_for(LanguageStyle::Racket), // r"#\u3001".to_string() // ); // assert_eq!( // '\u{E0101}'.to_string_for(LanguageStyle::Racket), // r"#\U0E0101".to_string() // ); } #[test] fn test_print_single_char_treesitter() { let writer = Writer::default().with_options(Options::default().with_style(LanguageStyle::TreeSitter)); assert_eq!( writer.write_to_string(&Value::from('a')).unwrap(), r"'a'".to_string() ); assert_eq!( writer.write_to_string(&Value::from('\n')).unwrap(), r"'\n'".to_string() ); // assert_eq!( // '§'.to_string_for(LanguageStyle::TreeSitter), // r"'§'".to_string() // ); // assert_eq!( // '\u{30F0}'.to_string_for(LanguageStyle::TreeSitter), // r"'ヰ'".to_string() // ); // assert_eq!( // '\u{E0101}'.to_string_for(LanguageStyle::TreeSitter), // r"'\u{e0101}'".to_string() // ); } #[test] fn test_print_single_char_clisp() { let writer = Writer::default().with_options(Options::default().with_style(LanguageStyle::CommonLisp)); assert_eq!( writer.write_to_string(&Value::from('a')).unwrap(), r"#\a".to_string() ); assert_eq!( writer.write_to_string(&Value::from('\n')).unwrap(), r"#\Newline".to_string() ); // assert_eq!( // '§'.to_string_for(LanguageStyle::CommonLisp), // r"#\§".to_string() // ); // assert_eq!( // '\u{3001}'.to_string_for(LanguageStyle::CommonLisp), // r"#\U3001".to_string() // ); // assert_eq!( // '\u{E0101}'.to_string_for(LanguageStyle::CommonLisp), // r"#\U0E0101".to_string() // ); } #[test] fn test_print_single_char_scheme() { let writer = Writer::default().with_options(Options::default().with_style(LanguageStyle::Scheme)); assert_eq!( writer.write_to_string(&Value::from('a')).unwrap(), r"#\a".to_string() ); assert_eq!( writer.write_to_string(&Value::from('\n')).unwrap(), r"#\newline".to_string() ); // assert_eq!('§'.to_string_for(LanguageStyle::Scheme), r"#\§".to_string()); // assert_eq!( // '\u{3001}'.to_string_for(LanguageStyle::Scheme), // r"#\x3001".to_string() // ); // assert_eq!( // '\u{E0101}'.to_string_for(LanguageStyle::Scheme), // r"#\x0E0101".to_string() // ); } #[test] fn test_print_single_char_elisp() { let writer = Writer::default().with_options(Options::default().with_style(LanguageStyle::EmacsLisp)); assert_eq!( writer.write_to_string(&Value::from('a')).unwrap(), r"?a".to_string() ); assert_eq!( writer.write_to_string(&Value::from('\n')).unwrap(), r"?\n".to_string() ); // assert_eq!( // '§'.to_string_for(LanguageStyle::EmacsLisp), // r"?§".to_string() // ); // assert_eq!( // ','.to_string_for(LanguageStyle::EmacsLisp), // r"?\,".to_string() // ); // assert_eq!( // '\u{3001}'.to_string_for(LanguageStyle::EmacsLisp), // r"?\u3001".to_string() // ); // assert_eq!( // '\u{E0101}'.to_string_for(LanguageStyle::EmacsLisp), // r"?\U0E0101".to_string() // ); } #[test] fn test_print_single_string_racket() { let writer = Writer::default().with_options(Options::default().with_style(LanguageStyle::Racket)); assert_eq!( writer.write_to_string(&Value::from("hello")).unwrap(), "\"hello\"".to_string() ); assert_eq!( writer.write_to_string(&Value::from("hel\tlo")).unwrap(), "\"hel\\tlo\"".to_string() ); assert_eq!( writer.write_to_string(&Value::from("hel\u{00}lo")).unwrap(), "\"hel\\\\u0000lo\"".to_string() ); } #[test] fn test_print_single_string_treesitter() {} #[test] fn test_print_single_string_clisp() {} #[test] fn test_print_single_string_scheme() {} #[test] fn test_print_single_string_elisp() {} #[test] fn test_print_short_list_racket() { let writer = Writer::default().with_options(Options::default().with_style(LanguageStyle::Racket)); let list = Value::from(vec![ Value::from("hello"), Value::from("this"), Value::from("is"), Value::from("a"), Value::from("lisp"), Value::from("list"), ]); assert_eq!( writer.write_to_string(&list).unwrap(), "(\"hello\" \"this\" \"is\" \"a\" \"lisp\" \"list\")".to_string() ); } #[test] fn test_print_empty_list() { for style in [ LanguageStyle::Racket, LanguageStyle::TreeSitter, LanguageStyle::CommonLisp, LanguageStyle::Scheme, LanguageStyle::EmacsLisp, ] { let writer = Writer::default().with_options(Options::default().with_style(style)); assert_eq!( writer .write_to_string(&Value::from(Vec::default())) .unwrap(), r"()".to_string() ); } } rust-sexpr-out-965be8521d521796350be1b964954c6cc7de54ae/tests/test_writer_pretty.rs000066400000000000000000000034331471573060300270410ustar00rootroot00000000000000use objio::{HasOptions, ObjectWriter}; use pretty_assertions::assert_eq; use sexpr_out::value::Value; use sexpr_out::writer::{LanguageStyle, Options, Writer}; #[test] fn test_pretty_print_short_list_racket() { let writer = Writer::default().pretty_printed(true).with_options( Options::default() .with_line_width(20) .with_style(LanguageStyle::Racket), ); let list = Value::from(vec![ Value::from("hello"), Value::from("this"), Value::from("is"), Value::from("a"), Value::from("lisp"), Value::from("list"), ]); // 1 2 3 // 0123456789012345678901234567890 // ("hello" "this" "is" // "a" "lisp" "list") assert_eq!( writer.write_to_string(&list).unwrap(), "(\"hello\" \"this\" \"is\"\n \"a\" \"lisp\" \"list\")\n".to_string() ); } #[test] fn test_pretty_print_short_nested_list_racket() { let writer = Writer::default().pretty_printed(true).with_options( Options::default() .with_line_width(20) .with_style(LanguageStyle::Racket), ); let list = Value::from(vec![ Value::from(1), Value::from(2), Value::from(3), Value::from(vec![ Value::from(4), Value::from(5), Value::from(vec![ Value::from(6), Value::from(7), Value::from(vec![Value::from(8)]), ]), ]), Value::from(9), Value::from(10), ]); // 1 2 3 // 0123456789012345678901234567890 // (1 2 3 // (4 5 (6 7 (8))) 9 // 10) assert_eq!( writer.write_to_string(&list).unwrap(), "(1 2 3\n (4 5 (6 7 (8))) 9\n 10)\n".to_string() ); }