Parses a string containing JSONC to an AST with comments and tokens. # Example ``` use jsonc_parser::CollectOptions; use jsonc_parser::CommentCollectionStrategy; use jsonc_parser::parse_to_ast; use jsonc_parser::ParseOptions; let parse_result = parse_to_ast(r#"{ "test": 5 } // test"#, &CollectOptions { comments: CommentCollectionStrategy::Separate, // include comments in result tokens: true, //
( text: &'a str, collect_options: &CollectOptions, parse_options: &ParseOptions, )
| 242 | /// // ...inspect parse_result for value, tokens, and comments here... |
| 243 | /// ``` |
| 244 | pub fn parse_to_ast<'a>( |
| 245 | text: &'a str, |
| 246 | collect_options: &CollectOptions, |
| 247 | parse_options: &ParseOptions, |
| 248 | ) -> Result<ParseResult<'a>, ParseError> { |
| 249 | let mut context = Context { |
| 250 | scanner: Scanner::new( |
| 251 | text, |
| 252 | &ScannerOptions { |
| 253 | allow_single_quoted_strings: parse_options.allow_single_quoted_strings, |
| 254 | allow_hexadecimal_numbers: parse_options.allow_hexadecimal_numbers, |
| 255 | allow_unary_plus_numbers: parse_options.allow_unary_plus_numbers, |
| 256 | }, |
| 257 | ), |
| 258 | comments: match collect_options.comments { |
| 259 | CommentCollectionStrategy::Separate => Some(Default::default()), |
| 260 | CommentCollectionStrategy::Off | CommentCollectionStrategy::AsTokens => None, |
| 261 | }, |
| 262 | current_comments: None, |
| 263 | last_token_end: 0, |
| 264 | range_stack: Vec::new(), |
| 265 | tokens: if collect_options.tokens { Some(Vec::new()) } else { None }, |
| 266 | collect_comments_as_tokens: collect_options.comments == CommentCollectionStrategy::AsTokens, |
| 267 | allow_comments: parse_options.allow_comments, |
| 268 | allow_trailing_commas: parse_options.allow_trailing_commas, |
| 269 | allow_missing_commas: parse_options.allow_missing_commas, |
| 270 | allow_loose_object_property_names: parse_options.allow_loose_object_property_names, |
| 271 | maximum_nesting_depth: 512, |
| 272 | }; |
| 273 | context.scan()?; |
| 274 | let value = parse_value(&mut context)?; |
| 275 | |
| 276 | if context.scan()?.is_some() { |
| 277 | return Err(context.create_error(ParseErrorKind::MultipleRootJsonValues)); |
| 278 | } |
| 279 | |
| 280 | debug_assert!(context.range_stack.is_empty()); |
| 281 | |
| 282 | Ok(ParseResult { |
| 283 | comments: context.comments, |
| 284 | tokens: context.tokens, |
| 285 | value, |
| 286 | }) |
| 287 | } |
| 288 | |
| 289 | fn parse_value<'a>(context: &mut Context<'a>) -> Result<Option<Value<'a>>, ParseError> { |
| 290 | if context.range_stack.len() > context.maximum_nesting_depth { |
searching dependent graphs…