-
Hi all 👋 Using // test.mjs
import { format } from 'prettier';
import { builders } from 'prettier/doc';
const { join, hardline } = builders;
const languages = [
{
name: 'escript',
parsers: ['escript'],
extensions: ['.src', '.inc']
},
];
const parsers = {
escript: {
astFormat: 'escript',
parse: (text, options) => {
// returning a static AST for simplicity for this example
return {
type: 'file',
start: { line_number: 1, character_column: 1, token_index: 0 },
end: { line_number: 4, character_column: 28, token_index: 9 },
body: [
{
type: 'use-declaration',
start: { line_number: 1, character_column: 1, token_index: 0 },
end: { line_number: 1, character_column: 8, token_index: 3 },
specifier: {
type: 'identifier',
start: { line_number: 1, character_column: 5, token_index: 2 },
end: { line_number: 1, character_column: 7, token_index: 2 },
id: 'uo'
}
},
{
type: 'include-declaration',
start: { line_number: 4, character_column: 9, token_index: 5 },
end: { line_number: 4, character_column: 23, token_index: 8 },
specifier: {
type: 'string-literal',
start: { line_number: 4, character_column: 17, token_index: 7 },
end: { line_number: 4, character_column: 22, token_index: 7 },
value: 'foo',
raw: '"foo"'
}
}
],
module: false
};
},
locStart: (node) => {
debugger;
throw new Error('Not used?');
return node ? node.start.token_index : NaN;
},
locEnd: (node) => {
debugger;
throw new Error('Not used?');
return node ? node.end.token_index : NaN;
}
},
};
const printers = {
escript: {
print(path, options, print) {
const { node } = path;
if (node === null) {
return [];
}
switch (node.type) {
case 'file':
return [
join(hardline, path.map(print, 'body'))
];
case 'string-literal':
return [node.raw];
case 'identifier':
return [node.id];
case 'include-declaration':
return ['include', ' ', path.call(print, 'specifier'), ';'];
case 'use-declaration':
return ['use', ' ', path.call(print, 'specifier'), ';'];
default:
throw new Error(`Unhandled node type ${node.type}`);
}
},
},
};
const plugin = { languages, printers, parsers };
const source = `use uo;
include "foo";`;
const formatted = await format(source, {
parser: 'escript',
plugins: [plugin]
});
console.log(formatted);
I'm not sure how the line breaks are supposed to be preserved? I read here that:
... but it appears that none of the breaks are preserved at all? Furthermore, I see that my parser's Thanks for reading, Kevin |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Figured it out: hardlines are added manually, see graphql's printer. |
Beta Was this translation helpful? Give feedback.
Figured it out: hardlines are added manually, see graphql's printer.