#nested #format #block #print #code

codize

Simple, language-agnostic library that pretty-prints code for your code-generation tool

8 releases

new 0.3.3 May 23, 2024
0.3.2 May 23, 2024
0.2.0 May 4, 2024
0.1.2 Jun 13, 2023
0.1.0 Apr 19, 2023

#62 in Value formatting

Download history 3/week @ 2024-02-16 15/week @ 2024-02-23 5/week @ 2024-03-01 9/week @ 2024-03-08 10/week @ 2024-03-15 19/week @ 2024-03-22 33/week @ 2024-03-29 11/week @ 2024-04-05 3/week @ 2024-04-19 12/week @ 2024-04-26 456/week @ 2024-05-03 26/week @ 2024-05-10

497 downloads per month
Used in regen-lang

Unlicense

34KB
842 lines

codize

Build Badge Version Badge License Badge Issue Badge

Simple, language-agnostic library that pretty-prints code for your code-generation tool.

First, create a Code enum with the code structure with one of the ways listed below. Then, the Format struct can be used to format the output. Or you can simply use to_string for a quick formatting with the default parameters

Code Examples

The Code enum stores all of the code structures. You can create it in one of the following ways:

  • Create a single line from a String or &str with into()
  • A block of code with an indented body with the cblock! macro
  • A list of code segments with a separator with the clist! macro
  • A concatenation of multiple code segments, either converted from an iterator with into(), or with the cconcat! macro which allows for mixing different types of code segments

Usually, the macros will automatically convert the input to Code by calling Code::from.

use codize::{cblock, clist, cconcat};

let code = cconcat![
    "",
    "/// This block is auto-generated",
    "",
    cblock!("fn main() {", [
        cblock!("println!(", [
            clist!("," => [r#""{}, {}!""#, r#""Hello""#, r#""world!""#])
        ], ");")
    ], "}"),
];

let expected = r#"
/// This block is auto-generated

fn main() {
    println!(
        "{}, {}!",
        "Hello",
        "world!",
    );
}"#;

assert_eq!(expected, code.to_string());

Format Examples

You can use the FormatCode trait along with the Format struct to change global formatting options

use codize::{cblock, Format, FormatCode};
let code = cblock!("fn main() {", ["println!(\"Hello, world!\");"], "}");

let indent_2 = 
r#"fn main() {
  println!("Hello, world!");
}"#;
assert_eq!(indent_2, code.format_with(&Format::indent(2)));

let indent_tab =
"fn main() {
\tprintln!(\"Hello, world!\");
}";
assert_eq!(indent_tab, code.format_with(&Format::indent_tab()));

Dependencies

~1.5MB
~34K SLoC