Skip to content

Commit

Permalink
feat(rome_json_parser): support allowTrailingCommas option (#326)
Browse files Browse the repository at this point in the history
  • Loading branch information
nissy-dev authored Sep 22, 2023
1 parent 481f926 commit 04de818
Show file tree
Hide file tree
Showing 45 changed files with 658 additions and 58 deletions.
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,19 @@ Read our [guidelines for writing a good changelog entry](https://github.com/biom
### Parser

- Enhance diagnostic for infer type handling in the parser. The 'infer' keyword can only be utilized within the 'extends' clause of a conditional type. Using it outside of this context will result in an error. Ensure that any type declarations using 'infer' are correctly placed within the conditional type structure to avoid parsing issues. Contributed by @denbezrukov
- Add support for parsing trailing commas inside JSON files:

```json
{
"json": {
"parser": {
"allowTrailingCommas": true
}
}
}
```

Contributed by @nissy-dev

### VSCode

Expand Down
41 changes: 39 additions & 2 deletions crates/biome_cli/tests/commands/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1856,13 +1856,13 @@ fn ignore_comments_error_when_allow_comments() {
}
"#;
let rome_config = "biome.json";
let biome_config = "biome.json";
let code = r#"
/*test*/ [1, 2, 3]
"#;
let file_path = Path::new("tsconfig.json");
fs.insert(file_path.into(), code.as_bytes());
fs.insert(rome_config.into(), config_json);
fs.insert(biome_config.into(), config_json);

let result = run_cli(
DynRef::Borrowed(&mut fs),
Expand Down Expand Up @@ -1911,6 +1911,43 @@ fn format_jsonc_files() {
));
}

#[test]
fn format_json_when_allow_trailing_commas() {
let mut fs = MemoryFileSystem::default();
let mut console = BufferConsole::default();

let config_json = r#"{
"json": {
"parser": { "allowTrailingCommas": true }
}
}"#;
let biome_config = "biome.json";
let code = r#"{
"array": [
1,
],
}"#;
let file_path = Path::new("file.json");
fs.insert(file_path.into(), code.as_bytes());
fs.insert(biome_config.into(), config_json);

let result = run_cli(
DynRef::Borrowed(&mut fs),
&mut console,
Args::from([("format"), file_path.as_os_str().to_str().unwrap()].as_slice()),
);

assert!(result.is_ok(), "run_cli returned {result:?}");

assert_cli_snapshot(SnapshotPayload::new(
module_path!(),
"format_json_when_allow_trailing_commas",
fs,
console,
result,
));
}

#[test]
fn treat_known_json_files_as_jsonc_files() {
let mut fs = MemoryFileSystem::default();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
---
source: crates/biome_cli/tests/snap_test.rs
expression: content
---
## `biome.json`

```json
{
"json": {
"parser": { "allowTrailingCommas": true }
}
}
```

## `file.json`

```json
{
"array": [
1,
],
}
```

# Emitted Messages

```block
file.json format ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
i Formatter would have printed the following content:
3 3 │ 1,
4 4 │ ],
5 │ - }
5 │ + }
6 │ +
```

```block
Compared 1 file(s) in <TIME>
```


4 changes: 2 additions & 2 deletions crates/biome_json_factory/src/generated/syntax_factory.rs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 6 additions & 6 deletions crates/biome_json_parser/src/lexer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ pub(crate) struct Lexer<'src> {
position: usize,

diagnostics: Vec<ParseDiagnostic>,
config: JsonParserOptions,
options: JsonParserOptions,
}

impl<'src> Lexer<'src> {
Expand All @@ -46,7 +46,7 @@ impl<'src> Lexer<'src> {
source: string,
position: 0,
diagnostics: vec![],
config: JsonParserOptions::default(),
options: JsonParserOptions::default(),
}
}

Expand Down Expand Up @@ -699,7 +699,7 @@ impl<'src> Lexer<'src> {
b'*' if self.peek_byte() == Some(b'/') => {
self.advance(2);

if !self.config.allow_comments {
if !self.options.allow_comments {
self.diagnostics.push(ParseDiagnostic::new(
"JSON standard does not allow comments.",
start..self.text_position(),
Expand Down Expand Up @@ -745,7 +745,7 @@ impl<'src> Lexer<'src> {
}
}

if !self.config.allow_comments {
if !self.options.allow_comments {
self.diagnostics.push(ParseDiagnostic::new(
"JSON standard does not allow comments.",
start..self.text_position(),
Expand All @@ -758,8 +758,8 @@ impl<'src> Lexer<'src> {
}
}

pub(crate) fn with_config(mut self, config: JsonParserOptions) -> Self {
self.config = config;
pub(crate) fn with_options(mut self, options: JsonParserOptions) -> Self {
self.options = options;
self
}
}
Expand Down
16 changes: 14 additions & 2 deletions crates/biome_json_parser/src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,25 +9,33 @@ use biome_parser::ParserContext;
pub(crate) struct JsonParser<'source> {
context: ParserContext<JsonSyntaxKind>,
source: JsonTokenSource<'source>,
options: JsonParserOptions,
}

#[derive(Default, Debug, Clone, Copy)]
pub struct JsonParserOptions {
pub allow_comments: bool,
pub allow_trailing_commas: bool,
}

impl JsonParserOptions {
pub fn with_allow_comments(mut self) -> Self {
self.allow_comments = true;
self
}

pub fn with_allow_trailing_commas(mut self) -> Self {
self.allow_trailing_commas = true;
self
}
}

impl<'source> JsonParser<'source> {
pub fn new(source: &'source str, config: JsonParserOptions) -> Self {
pub fn new(source: &'source str, options: JsonParserOptions) -> Self {
Self {
context: ParserContext::default(),
source: JsonTokenSource::from_str(source, config),
source: JsonTokenSource::from_str(source, options),
options,
}
}

Expand All @@ -45,6 +53,10 @@ impl<'source> JsonParser<'source> {

(events, diagnostics, trivia)
}

pub fn options(&self) -> &JsonParserOptions {
&self.options
}
}

impl<'source> Parser for JsonParser<'source> {
Expand Down
10 changes: 8 additions & 2 deletions crates/biome_json_parser/src/syntax.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ pub(crate) fn parse_root(p: &mut JsonParser) {
};

// Process the file to the end, e.g. in cases where there have been multiple values
if !p.at(EOF) {
if !(p.at(EOF)) {
parse_rest(p, value);
}

Expand Down Expand Up @@ -181,6 +181,10 @@ fn parse_sequence(p: &mut JsonParser, root_kind: SequenceKind) -> ParsedSyntax {

match current.parse_item(p) {
SequenceItem::Parsed(Absent) => {
if p.options().allow_trailing_commas && p.last() == Some(T![,]) {
break;
}

let range = if p.at(T![,]) {
p.cur_range()
} else {
Expand Down Expand Up @@ -249,7 +253,9 @@ fn parse_object_member(p: &mut JsonParser) -> SequenceItem {
let m = p.start();

if parse_member_name(p).is_absent() {
p.error(expected_property(p, p.cur_range()));
if !(p.options().allow_trailing_commas && p.last() == Some(T![,])) {
p.error(expected_property(p, p.cur_range()));
}

if !p.at(T![:]) && !p.at_ts(VALUE_START) {
m.abandon(p);
Expand Down
10 changes: 5 additions & 5 deletions crates/biome_json_parser/src/token_source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,20 +13,20 @@ pub(crate) struct JsonTokenSource<'source> {
current: JsonSyntaxKind,
current_range: TextRange,
preceding_line_break: bool,
config: JsonParserOptions,
options: JsonParserOptions,
}

impl<'source> JsonTokenSource<'source> {
pub fn from_str(source: &'source str, config: JsonParserOptions) -> Self {
let lexer = Lexer::from_str(source).with_config(config);
pub fn from_str(source: &'source str, options: JsonParserOptions) -> Self {
let lexer = Lexer::from_str(source).with_options(options);

let mut source = Self {
lexer,
trivia: Vec::new(),
current: TOMBSTONE,
current_range: TextRange::default(),
preceding_line_break: false,
config,
options,
};

source.next_non_trivia_token(true);
Expand All @@ -46,7 +46,7 @@ impl<'source> JsonTokenSource<'source> {
// Not trivia
break;
}
Ok(trivia_kind) if trivia_kind.is_comment() && !self.config.allow_comments => {
Ok(trivia_kind) if trivia_kind.is_comment() && !self.options.allow_comments => {
self.set_current_token(token);

// Not trivia
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
null,
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
---
source: crates/biome_json_parser/tests/spec_test.rs
expression: snapshot
---

## Input

```json
null,
```


## AST

```
JsonRoot {
value: JsonArrayValue {
l_brack_token: missing (required),
elements: JsonArrayElementList [
JsonNullValue {
value_token: NULL_KW@0..4 "null" [] [],
},
missing separator,
JsonBogusValue {
items: [
COMMA@4..5 "," [] [],
],
},
],
r_brack_token: missing (required),
},
eof_token: EOF@5..6 "" [Newline("\n")] [],
}
```

## CST

```
0: [email protected]
0: [email protected]
0: (empty)
1: [email protected]
0: [email protected]
0: [email protected] "null" [] []
1: (empty)
2: [email protected]
0: [email protected] "," [] []
2: (empty)
1: [email protected] "" [Newline("\n")] []
```

## Diagnostics

```
null.json:1:5 parse ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
× End of file expected
> 1 │ null,
│ ^
2 │
i Use an array for a sequence of values: `[1, 2]`
```


Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{},
Loading

0 comments on commit 04de818

Please sign in to comment.