@calystral/prettier-plugin-solidity
Version:
prettier plugin for solidity
44 lines (39 loc) • 1.41 kB
JavaScript
const {
doc: {
builders: { group, line, concat, indent }
}
} = require('prettier/standalone');
const groupIfNecessaryBuilder = (path) => (doc) =>
path.getParentNode().type === 'BinaryOperation' ? doc : group(doc);
const indentIfNecessaryBuilder = (path) => (doc) => {
let node = path.getNode();
for (let i = 0; ; i += 1) {
const parentNode = path.getParentNode(i);
if (parentNode.type === 'ReturnStatement') return doc;
if (parentNode.type === 'IfStatement') return doc;
if (parentNode.type === 'WhileStatement') return doc;
if (parentNode.type !== 'BinaryOperation') return indent(doc);
if (node === parentNode.right) return doc;
node = parentNode;
}
};
module.exports = {
match: (op) => ['&&', '||'].includes(op),
print: (node, path, print) => {
const groupIfNecessary = groupIfNecessaryBuilder(path);
const indentIfNecessary = indentIfNecessaryBuilder(path);
const right = concat([node.operator, line, path.call(print, 'right')]);
// If it's a single binary operation, avoid having a small right
// operand like - 1 on its own line
const shouldGroup =
node.left.type !== 'BinaryOperation' &&
path.getParentNode().type !== 'BinaryOperation';
return groupIfNecessary(
concat([
path.call(print, 'left'),
' ',
indentIfNecessary(shouldGroup ? group(right) : right)
])
);
}
};