Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(rome_json_parser): support allowTrailingCommas option #326

Merged
merged 10 commits into from
Sep 22, 2023
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,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
}
}
}
```
nissy-dev marked this conversation as resolved.
Show resolved Hide resolved

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
8 changes: 7 additions & 1 deletion crates/biome_json_parser/src/syntax.rs
Original file line number Diff line number Diff line change
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
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, I actually meant having a json file that contains

true

(same for the rests)

They all are valid JSON files 😄

Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"a": [
"a",
],
"b": {
"c": true,
},
"d": [
null,
],
"e": {
"f": {},
},
"g": 0,
}
Loading
Loading