Skip to main content

oak_json/
lib.rs

1#![doc = include_str!("readme.md")]
2#![feature(new_range_api)]
3#![feature(portable_simd)]
4#![warn(missing_docs)]
5#![doc(html_logo_url = "https://raw.githubusercontent.com/ygg-lang/oaks/refs/heads/dev/documents/logo.svg")]
6#![doc(html_favicon_url = "https://raw.githubusercontent.com/ygg-lang/oaks/refs/heads/dev/documents/logo.svg")]
7
8/// AST module.
9pub mod ast;
10/// Builder module.
11pub mod builder;
12
13// pub mod formatter;
14
15/// Type definitions module.
16/// Language configuration module.
17pub mod language;
18/// Lexer module.
19pub mod lexer;
20/// LSP module.
21#[cfg(any(feature = "lsp", feature = "oak-highlight", feature = "oak-pretty-print"))]
22pub mod lsp;
23/// MCP module.
24#[cfg(feature = "mcp")]
25pub mod mcp;
26
27/// Parser module.
28pub mod parser;
29
30pub use crate::{
31    ast::{JsonRoot, JsonValue},
32    builder::JsonBuilder,
33    language::JsonLanguage,
34    lexer::JsonLexer,
35    parser::JsonParser,
36};
37
38/// Highlighter implementation.
39#[cfg(feature = "oak-highlight")]
40pub use crate::lsp::highlighter::JsonHighlighter;
41
42#[cfg(feature = "serde")]
43pub use crate::language::serde_impl::{from_value, to_value};
44
45#[cfg(feature = "serde")]
46/// Serializes the given value to a JSON string.
47pub fn to_string<T: ::serde::Serialize>(value: &T) -> Result<String, String> {
48    let json_value = to_value(value).map_err(|e| e.to_string())?;
49    Ok(json_value.to_string())
50}
51
52#[cfg(feature = "serde")]
53/// Deserializes a value of type `T` from a JSON string.
54pub fn from_str<T: ::serde::de::DeserializeOwned>(s: &str) -> Result<T, String> {
55    let json_value = parse(s)?;
56    from_value(json_value).map_err(|e| e.to_string())
57}
58
59/// Parses a JSON string into a `JsonValue` AST.
60pub fn parse(json: &str) -> Result<crate::ast::JsonValue, String> {
61    use oak_core::{Builder, parser::session::ParseSession, source::SourceText};
62    let language = JsonLanguage::default();
63    let builder = JsonBuilder::new(&language);
64    let source = SourceText::new(json.to_string());
65    let mut cache = ParseSession::default();
66    let result = builder.build(&source, &[], &mut cache);
67    result.result.map(|root| root.value).map_err(|e| format!("{:?}", e))
68}
69
70pub use oak_macros::json;
71
72/// LSP implementation.
73#[cfg(feature = "lsp")]
74pub use crate::lsp::JsonLanguageService;
75// #[cfg(feature = "oak-pretty-print")]
76// pub use crate::lsp::formatter::JsonFormatter;
77
78/// MCP service implementation.
79#[cfg(feature = "mcp")]
80pub use crate::mcp::serve_json_mcp;
81pub use lexer::token_type::JsonTokenType;
82pub use parser::element_type::JsonElementType;