Skip to main content

saola_schema_ast/
lib.rs

1//! The Prisma Schema AST.
2
3#![deny(rust_2018_idioms, unsafe_code)]
4#![allow(clippy::derive_partial_eq_without_eq)]
5
6pub use self::{parser::parse_schema, reformat::reformat, source_file::SourceFile};
7
8/// The AST data structure. It aims to faithfully represent the syntax of a Prisma Schema, with
9/// source span information.
10pub mod ast;
11
12mod parser;
13mod reformat;
14mod renderer;
15mod source_file;
16
17/// Transform the input string into a valid (quoted and escaped) PSL string literal.
18///
19/// PSL string literals have the exact same grammar as [JSON string
20/// literals](https://datatracker.ietf.org/doc/html/rfc8259#section-7).
21///
22/// ```
23/// # use schema_ast::string_literal;
24///let input = r#"oh
25///hi"#;
26///assert_eq!(r#""oh\nhi""#, &string_literal(input).to_string());
27/// ```
28pub fn string_literal(s: &str) -> impl std::fmt::Display + '_ {
29    struct StringLiteral<'a>(&'a str);
30
31    impl std::fmt::Display for StringLiteral<'_> {
32        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
33            f.write_str("\"")?;
34            for c in self.0.char_indices() {
35                match c {
36                    (_, '\t') => f.write_str("\\t")?,
37                    (_, '\n') => f.write_str("\\n")?,
38                    (_, '"') => f.write_str("\\\"")?,
39                    (_, '\r') => f.write_str("\\r")?,
40                    (_, '\\') => f.write_str("\\\\")?,
41                    // Control characters
42                    (_, c) if c.is_ascii_control() => {
43                        let mut b = [0];
44                        c.encode_utf8(&mut b);
45                        f.write_fmt(format_args!("\\u{:04x}", b[0]))?;
46                    }
47                    (start, other) => f.write_str(&self.0[start..(start + other.len_utf8())])?,
48                }
49            }
50            f.write_str("\"")
51        }
52    }
53
54    StringLiteral(s)
55}