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