Files
test-repo/src/parser-parse5.js
T
Joseph Frazier a78d1389f6 Use babylon.parseExpression for JSON (#2476)
* Add comments showing parser arguments

Since this is how they are invoked, the comments make it easier to maintain.

* Use babylon.parseExpression for JSON

See https://github.com/prettier/prettier/issues/2378#issuecomment-314600778

Note that this doesn't yet print comments:

    echo '{/*comment*/"K":"V"}' | ./bin/prettier.js --parser json

* Remove parser-json.js

This reduces duplicate code in the built package.
See https://github.com/prettier/prettier/pull/2476#pullrequestreview-50181398

* Add test with block comment in JSON

* Fix test with block comment in JSON

* Add test with line comment in JSON

* Don't build now-redundant parser-json.js
2017-07-24 11:43:49 +10:00

51 lines
1.2 KiB
JavaScript

"use strict";
// const createError = require("./parser-create-error");
function parse(text /*, parsers, opts*/) {
// Inline the require to avoid loading all the JS if we don't use it
const parse5 = require("parse5");
try {
const isFragment = !/^\s*<(!doctype|html|head|body)/i.test(text);
const ast = (isFragment ? parse5.parseFragment : parse5.parse)(text, {
treeAdapter: parse5.treeAdapters.htmlparser2,
locationInfo: true
});
return extendAst(ast);
} catch (error) {
// throw createError(error.message, {
// start: {
// line: error.locations[0].line,
// column: error.locations[0].column
// }
// } else {
throw error;
// }
}
}
function extendAst(ast) {
if (!ast || !ast.children) {
return ast;
}
for (const child of ast.children) {
extendAst(child);
if (child.attribs) {
child.attributes = convertAttribs(child.attribs);
}
}
return ast;
}
function convertAttribs(attribs) {
return Object.keys(attribs).map(attributeKey => {
return {
type: "attribute",
key: attributeKey,
value: attribs[attributeKey]
};
});
}
module.exports = parse;