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

WIP: Refactor handling of code blocks with just comments #513

Closed
Closed
Show file tree
Hide file tree
Changes from 2 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
18 changes: 6 additions & 12 deletions src/comments.js
Original file line number Diff line number Diff line change
Expand Up @@ -293,17 +293,9 @@ const handleInlineComments = comment => {
return false;
};

function handleOnlyComments(enclosingNode, ast, comment, isLastComment) {
if (
enclosingNode &&
enclosingNode.kind === "program" &&
enclosingNode.children.length === 0
) {
if (isLastComment) {
addDanglingComment(enclosingNode, comment);
} else {
addLeadingComment(enclosingNode, comment);
}
function handleOnlyComments(enclosingNode, ast, comment) {
if (enclosingNode && enclosingNode.kind === "lonelyComment") {
addDanglingComment(enclosingNode, comment);
return true;
}
return false;
Expand Down Expand Up @@ -359,8 +351,10 @@ function printComments(comments, options) {
const parts = [];
comments.forEach((comment, index, comments) => {
comment.printed = true;
if (index > 0) {
parts.push(hardline);
}
parts.push(comment.value);
parts.push(hardline);
if (
isNextLineEmpty(options.originalText, comment, options) &&
comments.length > index + 1
Expand Down
98 changes: 98 additions & 0 deletions src/parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,104 @@ function parse(text) {

const ast = parser.parseCode(text);

function addLonelyCommentsToAst() {
const codeBlocks = [];
let start;
ast.tokens.forEach((token, index) => {
if (token[0] === "T_OPEN_TAG") {
start = index;
} else if (token[0] === "T_CLOSE_TAG") {
codeBlocks.push({ start, end: index });
}
});

const lonelyCommentBlocks = codeBlocks
.map(({ start, end }) => {
return ast.tokens.slice(start, end + 1);
})
.filter(tokens => {
return (
tokens.filter(
token =>
![
"T_COMMENT",
"T_DOC_COMMENT",
"T_WHITESPACE",
"T_OPEN_TAG",
"T_CLOSE_TAG"
].includes(token[0])
).length === 0
);
});

let astIndices = [];

if (!lonelyCommentBlocks) {
return;
}
const pushTokens = (tokens, index, arr) => {
arr.push({
index,
loc: {
start: {
line: tokens[0][2],
offset: tokens[0][3]
},
end: {
line: tokens[tokens.length - 1][2],
offset: tokens[tokens.length - 1][4]
}
}
});
};

if (!ast.children.length) {
lonelyCommentBlocks.forEach(tokens => pushTokens(tokens, 0, astIndices));
} else {
const [firstLonelyTokens] = lonelyCommentBlocks;
if (
firstLonelyTokens &&
ast.children.length > 0 &&
ast.children[0].loc.start.line >=
firstLonelyTokens[firstLonelyTokens.length - 1][2]
) {
pushTokens(firstLonelyTokens, 0, astIndices);
}

const lastLonelyTokens =
lonelyCommentBlocks[lonelyCommentBlocks.length - 1];
if (
lastLonelyTokens &&
ast.children.length > 0 &&
ast.children[ast.children.length - 1].loc.end.line <=
lastLonelyTokens[lastLonelyTokens.length - 1][2]
) {
pushTokens(lastLonelyTokens, ast.children.length, astIndices);
}

astIndices = ast.children.reduce((acc, child, index, children) => {
const fittingTokens = lonelyCommentBlocks.find(tokens =>
inBetweenLines(tokens[0][2], child, children[index + 1])
);
if (fittingTokens) {
pushTokens(fittingTokens, index + 1, acc);
}
return acc;
}, astIndices);
}

astIndices.forEach(({ index, loc }, j) => {
ast.children.splice(index + j, 0, {
kind: "lonelyComment",
raw: "",
value: "",
loc
});
});
}

addLonelyCommentsToAst();

// parser doesn't create `inline` node between `?>\n<?`, so we add them manually
const missingLinebreaks = ast.tokens.filter((token, index, tokens) => {
return (
Expand Down
58 changes: 25 additions & 33 deletions src/printer.js
Original file line number Diff line number Diff line change
Expand Up @@ -1340,27 +1340,11 @@ function printLines(path, options, print, childrenAttribute = "children") {
? "<?="
: "<?php";
const beforeInline =
childNode.leadingComments && childNode.leadingComments.length
? concat([
isFirstNode ? openTag : "",
hardline,
comments.printComments(childNode.leadingComments, options),
"?>"
])
: isProgramLikeNode(node) && isFirstNode
? ""
: concat([beforeCloseTagInlineNode, "?>"]);
isProgramLikeNode(node) && isFirstNode
? ""
: concat([beforeCloseTagInlineNode, "?>"]);
const afterInline =
childNode.comments && childNode.comments.length
? concat([
openTag,
hardline,
comments.printComments(childNode.comments, options),
"?>"
])
: isProgramLikeNode(node) && isLastNode
? ""
: concat([openTag, " "]);
isProgramLikeNode(node) && isLastNode ? "" : concat([openTag, " "]);

printed = concat([beforeInline, printed, afterInline]);
}
Expand All @@ -1371,12 +1355,6 @@ function printLines(path, options, print, childrenAttribute = "children") {
const wrappedParts = wrapPartsIntoGroups(parts, groupIndexes);

if (node.kind === "program") {
if (!wrappedParts.length && node.comments) {
wrappedParts.push(
hardline,
comments.printComments(node.comments, options)
);
}
const originalText = node.loc.source;
const firstNestedChildNode = getFirstNestedChildNode(node);
const lastNestedChildNode = getLastNestedChildNode(node);
Expand All @@ -1394,20 +1372,26 @@ function printLines(path, options, print, childrenAttribute = "children") {
const between = originalText.trim().match(/^<\?(php|=)(\s+)?\S/);

if (between && between[2]) {
afterOpenTag = between[2].includes("\n")
? concat([
hardline,
between[2].split("\n").length > 2 ? hardline : ""
])
: " ";
afterOpenTag =
between[2].includes("\n") &&
firstNestedChildNode.kind !== "lonelyComment"
Copy link
Member

Choose a reason for hiding this comment

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

Bug with extra here

? concat([
hardline,
between[2].split("\n").length > 2 ? hardline : ""
])
: " ";
}
}

if (hasEndTag) {
const between = originalText.trim().match(/\S(\s*)?\?>$/);

beforeCloseTag =
between && between[1] && between[1].includes("\n") ? hardline : " ";
lastNestedChildNode.kind === "lonelyComment"
? ""
: between && between[1] && between[1].includes("\n")
? hardline
: " ";
}

return concat([
Expand Down Expand Up @@ -2482,6 +2466,14 @@ function printNode(path, options, print) {
]);
case "label":
return concat([node.name, ":"]);
case "lonelyComment": {
const isMultiline = node.loc.start.line < node.loc.end.line;
return concat([
isMultiline ? hardline : "",
comments.printComments(node.comments, options),
isMultiline ? hardline : ""
]);
}
case "error":
default:
return `Have not implemented kind ${node.kind} yet.`;
Expand Down
37 changes: 26 additions & 11 deletions tests/comments/__snapshots__/jsfmt.spec.js.snap
Original file line number Diff line number Diff line change
Expand Up @@ -184,15 +184,11 @@ exports[`blank_lines.php 1`] = `

// Other comment
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<?php
// The first line of a comment
<?php // The first line of a comment
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

// The second line of a comment

// A third line which has a blank line before it

// Other comment


`;

exports[`break.php 1`] = `
Expand Down Expand Up @@ -1231,7 +1227,7 @@ exports[`inline2.php 1`] = `
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<?php
// test
?>
?>
<h1>Test</h1>

`;
Expand All @@ -1246,6 +1242,7 @@ exports[`inline3.php 1`] = `
<?php
// test
?>

`;

exports[`inline4.php 1`] = `
Expand All @@ -1272,7 +1269,7 @@ exports[`inline4.php 1`] = `
/**
* C
*/
?>
?>
<h1>Test</h1>

`;
Expand All @@ -1287,7 +1284,7 @@ exports[`inline5.php 1`] = `
<h1>Test</h1>
<?php
// test
?>
?>
<h1>Test</h1>

`;
Expand All @@ -1308,7 +1305,7 @@ exports[`inline6.php 1`] = `
/**
* test
*/
?>
?>
<h1>Test</h1>

`;
Expand All @@ -1320,6 +1317,26 @@ exports[`inline7.php 1`] = `

`;

exports[`inline8.php 1`] = `
<?php //test ?>
<?php echo 1; ?>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<?php //test ?>
<?php echo 1; ?>

`;

exports[`inline9.php 1`] = `
<?php //test ?>
<?php echo 1; ?>
<?php echo 2; ?>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<?php //test ?>
<?php echo 1; ?>
<?php echo 2; ?>

`;

exports[`isset.php 1`] = `
<?php

Expand Down Expand Up @@ -1425,15 +1442,13 @@ exports[`no_code.php 1`] = `
?>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<?php

/**
* Product Loop Start
*
* @author WooThemes
* @package WooCommerce/Templates
* @version 2.0.0
*/

?>

`;
Expand Down
2 changes: 2 additions & 0 deletions tests/comments/inline8.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
<?php //test ?>
<?php echo 1; ?>
3 changes: 3 additions & 0 deletions tests/comments/inline9.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<?php //test ?>
<?php echo 1; ?>
<?php echo 2; ?>