Skip to content

Commit

Permalink
Add JSON5 support
Browse files Browse the repository at this point in the history
  • Loading branch information
DavidArchibald committed Mar 21, 2021
1 parent 019397d commit 642fbc6
Show file tree
Hide file tree
Showing 6 changed files with 624 additions and 127 deletions.
17 changes: 5 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,19 +1,13 @@

JSON-ASTy
JSON5-ASTy
=========

Lossless JSON-to-AST Parser and AST-to-JSON Generator

<p/>
<img src="https://nodei.co/npm/json-asty.png?downloads=true&stars=true" alt=""/>

<p/>
<img src="https://david-dm.org/rse/json-asty.png" alt=""/>
Lossless JSON5-to-AST Parser and AST-to-JSON5 Generator forked from JSON-ASTy. The rest of the description is copied verbatim except to replace the name.

About
-----

JSON-ASTy is a JavaScript library providing a lossless JavaScript Object
JSON5-ASTy is a JavaScript library providing a lossless JavaScript Object
Notation (JSON) to Abstract Syntax Tree (AST) parser and a corresponding
AST to JSON generator. It is intended for cases where one has to read
JSON into an AST, manipulate the AST and generate JSON from the AST
Expand All @@ -26,14 +20,14 @@ Installation
------------

```shell
$ npm install json-asty
$ npm install json5-asty
```

Usage
-----

```js
const JsonAsty = require("json-asty")
const JsonAsty = require("json5-asty")

/* the JSON input */
let json = `{
Expand Down Expand Up @@ -157,4 +151,3 @@ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

11 changes: 9 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,16 @@
"email": "[email protected]",
"url": "http://engelschall.com"
},
"contributors": [
{
"name": "LukeAbby",
"email": "[email protected]",
"url": "http://gitlab.com/LukeAbby/"
}
],
"license": "MIT",
"homepage": "https://github.com/rse/json-asty",
"bugs": "https://github.com/rse/json-asty/issues",
"homepage": "https://github.com/DavidArchibald/json5-asty",
"bugs": "https://github.com/DavidArchibald/json5-astyissues",
"dependencies": {
"asty-astq": "1.13.4",
"pegjs-otf": "1.2.18",
Expand Down
65 changes: 32 additions & 33 deletions src/json-asty.d.ts
Original file line number Diff line number Diff line change
@@ -1,38 +1,37 @@
/*!
** JSON-ASTy -- Lossless JSON-to-AST Parser and AST-to-JSON Generator
** Copyright (c) 2018-2021 Dr. Ralf S. Engelschall <[email protected]>
**
** Permission is hereby granted, free of charge, to any person obtaining
** a copy of this software and associated documentation files (the
** "Software"), to deal in the Software without restriction, including
** without limitation the rights to use, copy, modify, merge, publish,
** distribute, sublicense, and/or sell copies of the Software, and to
** permit persons to whom the Software is furnished to do so, subject to
** the following conditions:
**
** The above copyright notice and this permission notice shall be included
** in all copies or substantial portions of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
** SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
** JSON-ASTy -- Lossless JSON-to-AST Parser and AST-to-JSON Generator
** Copyright (c) 2018-2021 Dr. Ralf S. Engelschall <[email protected]>
**
** Permission is hereby granted, free of charge, to any person obtaining
** a copy of this software and associated documentation files (the
** "Software"), to deal in the Software without restriction, including
** without limitation the rights to use, copy, modify, merge, publish,
** distribute, sublicense, and/or sell copies of the Software, and to
** permit persons to whom the Software is furnished to do so, subject to
** the following conditions:
**
** The above copyright notice and this permission notice shall be included
** in all copies or substantial portions of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
** SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

declare module "JsonAsty" {
class JsonAsty {
/* parse JSON into AST */
static parse(json: string): object;
declare module 'JsonAsty' {
class JsonAsty {
/* parse JSON into AST */
static parse(json: string): object;

/* dump AST */
static dump(ast: object, options?: { colors?: boolean }): string;
/* dump AST */
static dump(ast: object, options?: { colors?: boolean }): string;

/* unparse AST into JSON */
static unparse(ast: object): string;
}
export = JsonAsty
/* unparse AST into JSON */
static unparse(ast: object): string;
}
export = JsonAsty;
}

177 changes: 98 additions & 79 deletions src/json-asty.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,97 +23,116 @@
*/

/* external requirements */
const ASTY = require("asty-astq")
const PEG = require("pegjs-otf")
const PEGUtil = require("pegjs-util")
const chalk = require("chalk")
const ASTY = require("asty-astq");
const PEG = require("pegjs-otf");
const PEGUtil = require("pegjs-util");
const chalk = require("chalk");

/* pre-parse PEG grammar (replaced by browserify) */
const PEGparser = PEG.generateFromFile(`${__dirname}/json-asty.pegjs`, {
optimize: "size",
trace: false
})
const jsonParser = PEG.generateFromFile(`${__dirname}/json-asty.pegjs`, {
optimize: "size",
trace: false,
});

const json5Parser = PEG.generateFromFile(`${__dirname}/json5-asty.pegjs`, {
optimize: "size",
trace: false,
});

/* the API class */
class JsonAsty {
/* parse JSON into AST */
static parse (json) {
/* sanity check argument */
if (typeof json !== "string")
throw new Error("invalid JSON argument (expected type string)")
/* parse JSON into AST */
static parse(json, json5=true) {
/* sanity check argument */
if (typeof json !== "string")
throw new Error("invalid JSON argument (expected type string)");

/* parse specification into Abstract Syntax Tree (AST) */
const asty = new ASTY()
const result = PEGUtil.parse(PEGparser, json, {
startRule: "json",
makeAST: (line, column, offset, args) => {
return asty.create.apply(asty, args).pos(line, column, offset)
}
})
if (result.error !== null)
throw new Error("parse: JSON parsing failure:\n" +
PEGUtil.errorMessage(result.error, true).replace(/^/mg, "ERROR: ") + "\n")
return result.ast
let parser;
if (json5) {
parser = json5Parser;
} else {
parser = jsonParser;
}

/* dump AST (with optional colorization) */
static dump (ast, options = {}) {
/* determine options */
options = Object.assign({}, {
colors: false
}, options)
/* parse specification into Abstract Syntax Tree (AST) */
const asty = new ASTY();
const result = PEGUtil.parse(parser, json, {
startRule: "json",
makeAST: (line, column, offset, args) => {
return asty.create.apply(asty, args).pos(line, column, offset);
},
});
if (result.error !== null)
throw new Error(
"parse: JSON parsing failure:\n" +
PEGUtil.errorMessage(result.error, true).replace(/^/gm, "ERROR: ") +
"\n",
);
return result.ast;
}

/* dump AST (with optional colorization) */
static dump(ast, options = {}) {
/* determine options */
options = Object.assign(
{},
{
colors: false,
},
options,
);

/* eslint no-console: off */
let output
if (options.colors) {
output = ast.dump(Infinity, (type, text) => {
switch (type) {
case "tree": text = chalk.grey(text); break
case "type": text = chalk.blue(text); break
case "value": text = chalk.yellow(text); break
case "position": text = chalk.grey(text); break
default:
}
return text
})
/* eslint no-console: off */
let output;
if (options.colors) {
output = ast.dump(Infinity, (type, text) => {
switch (type) {
case "tree":
text = chalk.grey(text);
break;
case "type":
text = chalk.blue(text);
break;
case "value":
text = chalk.yellow(text);
break;
case "position":
text = chalk.grey(text);
break;
default:
}
else
output = ast.dump(Infinity)
return output
}
return text;
});
} else output = ast.dump(Infinity);
return output;
}

/* unparse AST into JSON */
static unparse (ast) {
/* sanity check arguments */
if (typeof ast !== "object")
throw new Error("generate: invalid AST argument (expected type object)")
/* unparse AST into JSON */
static unparse(ast) {
/* sanity check arguments */
if (typeof ast !== "object")
throw new Error("generate: invalid AST argument (expected type object)");

/* walk the AST */
let json = ""
ast.walk((node, depth, parent, when) => {
if (when === "downward") {
const prolog = node.get("prolog")
if (prolog !== undefined)
json += prolog
const body = node.get("body")
if (body !== undefined)
json += body
else {
const value = node.get("value")
if (value !== undefined)
json += JSON.stringify(value)
}
}
else if (when === "upward") {
const epilog = node.get("epilog")
if (epilog !== undefined)
json += epilog
}
}, "both")
return json
}
/* walk the AST */
let json = "";
ast.walk((node, depth, parent, when) => {
if (when === "downward") {
const prolog = node.get("prolog");
if (prolog !== undefined) json += prolog;
const body = node.get("body");
if (body !== undefined) json += body;
else {
const value = node.get("value");
if (value !== undefined) json += JSON.stringify(value);
}
} else if (when === "upward") {
const epilog = node.get("epilog");
if (epilog !== undefined) json += epilog;
}
}, "both");
return json;
}
}

/* export the API class */
module.exports = JsonAsty

module.exports = JsonAsty;
4 changes: 3 additions & 1 deletion src/json-asty.pegjs
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,9 @@ valueString "quoted string literal value"
}
)*
'"' {
if (text() === "" || text() == null) {
return ast("string").set({ body: '""', value: ""})
}
return ast("string").set({ body: text(), value: chars.join("") })
}

Expand All @@ -147,4 +150,3 @@ ws "whitespace"

eof "end of file"
= !.

Loading

0 comments on commit 642fbc6

Please sign in to comment.