Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
17 changes: 12 additions & 5 deletions scripts/generate-node-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,18 +110,25 @@ ${
? `${Object.entries(fields as unknown as Record<string, NodeTypeChildren>)
.map(([field, children]) => {
let fieldName = `${field}Node`;
let type = children.types.length
? children.types.map(t => getTypeExprFromRef(t)).join(" | ")
let fieldType = children.types.length
? children.types
.map(fieldType =>
fieldType.type === "primary_expression"
? { type: "expression", named: true }
: fieldType
)
.map(getTypeExprFromRef)
.join(" | ")
: "UnnamedNode";
if (children.multiple) {
if (children.types.length > 1) {
type = `(${type})`;
fieldType = `(${fieldType})`;
}
type += "[]";
fieldType += "[]";
fieldName += "s";
}
const opt = children.required || children.multiple ? "" : "?";
return ` ${fieldName}${opt}: ${type};`;
return ` ${fieldName}${opt}: ${fieldType};`;
})
.join("\n")}
}`
Expand Down
10 changes: 1 addition & 9 deletions src/comments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import parser from "./parser.ts";
import printer from "./printer.ts";
import {
hasChild,
isMember,
printComment,
type JavaParserOptions,
type NamedNodePath
Expand Down Expand Up @@ -243,7 +244,6 @@ function handleMemberChainComments(commentNode: CommentNode) {
util.addLeadingComment(enclosingNode, commentNode);
return true;
} else if (
followingNode &&
isMember(followingNode) &&
(!precedingNode ||
(precedingNode !== getMemberObject(followingNode) &&
Expand Down Expand Up @@ -329,14 +329,6 @@ function handleTryStatementComments(commentNode: CommentNode) {
return false;
}

function isMember(node: SyntaxNode) {
return (
node.type === SyntaxType.ArrayAccess ||
node.type === SyntaxType.FieldAccess ||
node.type === SyntaxType.MethodInvocation
);
}

function getMemberObject(
node: ArrayAccessNode | FieldAccessNode | MethodInvocationNode
) {
Expand Down
10 changes: 5 additions & 5 deletions src/node-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -740,7 +740,7 @@ export interface ArgumentListNode extends NamedNodeBase {

export interface ArrayAccessNode extends NamedNodeBase {
type: SyntaxType.ArrayAccess;
arrayNode: PrimaryExpressionNode;
arrayNode: ExpressionNode;
indexNode: ExpressionNode;
}

Expand Down Expand Up @@ -952,7 +952,7 @@ export interface ExplicitConstructorInvocationNode extends NamedNodeBase {
type: SyntaxType.ExplicitConstructorInvocation;
argumentsNode: ArgumentListNode;
constructorNode: SuperNode | ThisNode;
objectNode?: PrimaryExpressionNode;
objectNode?: ExpressionNode;
type_argumentsNode?: TypeArgumentsNode;
}

Expand All @@ -973,7 +973,7 @@ export interface ExtendsInterfacesNode extends NamedNodeBase {
export interface FieldAccessNode extends NamedNodeBase {
type: SyntaxType.FieldAccess;
fieldNode: IdentifierNode | ThisNode;
objectNode: PrimaryExpressionNode | SuperNode;
objectNode: ExpressionNode | SuperNode;
}

export interface FieldDeclarationNode extends NamedNodeBase {
Expand Down Expand Up @@ -1094,7 +1094,7 @@ export interface MethodInvocationNode extends NamedNodeBase {
type: SyntaxType.MethodInvocation;
argumentsNode: ArgumentListNode;
nameNode: IdentifierNode;
objectNode?: PrimaryExpressionNode | SuperNode;
objectNode?: ExpressionNode | SuperNode;
type_argumentsNode?: TypeArgumentsNode;
}

Expand Down Expand Up @@ -1281,7 +1281,7 @@ export interface SynchronizedStatementNode extends NamedNodeBase {
export interface TemplateExpressionNode extends NamedNodeBase {
type: SyntaxType.TemplateExpression;
template_argumentNode: StringLiteralNode;
template_processorNode: PrimaryExpressionNode;
template_processorNode: ExpressionNode;
}

export interface TernaryExpressionNode extends NamedNodeBase {
Expand Down
88 changes: 53 additions & 35 deletions src/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
type CommentNode,
type SyntaxNode
} from "./node-types.ts";
import { createTypeCheckFunction } from "./printers/helpers.ts";

export default {
async parse(text) {
Expand Down Expand Up @@ -48,6 +49,16 @@ const parser = (async () => {
return parser;
})();

const isParenthesizedParent = createTypeCheckFunction([
SyntaxType.DoStatement,
SyntaxType.IfStatement,
SyntaxType.SwitchExpression,
SyntaxType.SynchronizedStatement,
SyntaxType.TryStatement,
SyntaxType.TryWithResourcesStatement,
SyntaxType.WhileStatement
]);

function processTree(
node: Node,
fieldName: string | null = null,
Expand Down Expand Up @@ -89,44 +100,51 @@ function processTree(
Object.keys(multiFields).forEach(name => (javaNode[`${name}Nodes`] = []));
}

node.children.forEach((child, index) => {
const { type, text: value, startPosition, endPosition } = child;
if (type === SyntaxType.BlockComment || type === SyntaxType.LineComment) {
comments.push({
type,
value,
start: {
index: child.startIndex,
row: startPosition.row,
column: startPosition.column
},
end: {
index: child.endIndex,
row: endPosition.row,
column: endPosition.column
},
leading: false,
trailing: false,
printed: false
});
} else {
const fieldName = node.fieldNameForChild(index);
const javaChild = processTree(child, fieldName, comments);

javaNode.children.push(javaChild);
if (javaChild.isNamed) {
javaNode.namedChildren.push(javaChild);
}
node.children
.flatMap(child =>
child.type === SyntaxType.ParenthesizedExpression &&
!isParenthesizedParent(javaNode)
? child.namedChildren
: [child]
)
.forEach((child, index) => {
const { type, text: value, startPosition, endPosition } = child;
if (type === SyntaxType.BlockComment || type === SyntaxType.LineComment) {
comments.push({
type,
value,
start: {
index: child.startIndex,
row: startPosition.row,
column: startPosition.column
},
end: {
index: child.endIndex,
row: endPosition.row,
column: endPosition.column
},
leading: false,
trailing: false,
printed: false
});
} else {
const fieldName = node.fieldNameForChild(index);
const javaChild = processTree(child, fieldName, comments);

javaNode.children.push(javaChild);
if (javaChild.isNamed) {
javaNode.namedChildren.push(javaChild);
}

if (fieldName) {
if (multiFields?.[fieldName]) {
javaNode[`${fieldName}Nodes`].push(javaChild);
} else {
javaNode[`${fieldName}Node`] = javaChild;
if (fieldName) {
if (multiFields?.[fieldName]) {
javaNode[`${fieldName}Nodes`].push(javaChild);
} else {
javaNode[`${fieldName}Node`] = javaChild;
}
}
}
}
});
});

return javaNode;
}
13 changes: 9 additions & 4 deletions src/printer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { SyntaxType, type CommentNode, type SyntaxNode } from "./node-types.ts";
import {
embedTextBlock,
hasType,
needsParentheses,
printComment,
printValue,
type NamedNodePath
Expand All @@ -19,9 +20,13 @@ import { printerForNodeType } from "./printers/index.ts";

export default {
print(path, options, print, args) {
return hasJavaNode(path)
? printerForNodeType(path.node.type)(path, print, options, args)
: printValue(path);
if (!hasNamedNode(path)) {
return printValue(path);
}

const doc = printerForNodeType(path.node.type)(path, print, options, args);

return needsParentheses(path) ? ["(", doc, ")"] : doc;
},
embed(path) {
return hasType(path, SyntaxType.StringLiteral)
Expand Down Expand Up @@ -56,6 +61,6 @@ export default {
}
} satisfies Printer<SyntaxNode>;

function hasJavaNode(path: AstPath<SyntaxNode>): path is NamedNodePath {
function hasNamedNode(path: AstPath<SyntaxNode>): path is NamedNodePath {
return path.node.isNamed;
}
82 changes: 53 additions & 29 deletions src/printers/blocks-and-statements.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import type { Doc } from "prettier";
import type { AstPath, Doc } from "prettier";
import { builders } from "prettier/doc";
import { SyntaxType } from "../node-types.ts";
import {
SyntaxType,
type ReturnStatementNode,
type ThrowStatementNode
} from "../node-types.ts";
import {
hasChild,
hasLeadingComments,
Expand All @@ -10,7 +14,10 @@ import {
printDanglingComments,
printModifiers,
printVariableDeclaration,
type NamedNodePrinters
returnArgumentHasLeadingComment,
type NamedNodePath,
type NamedNodePrinters,
type PrintFunction
} from "./helpers.ts";

const {
Expand Down Expand Up @@ -291,32 +298,8 @@ export default {
: "continue;";
},

return_statement(path, print) {
const statement: Doc[] = ["return"];

if (path.node.namedChildren.length) {
statement.push(" ");
const expression = path.call(print, "namedChildren", 0);
if (path.node.namedChildren[0].type === SyntaxType.BinaryExpression) {
statement.push(
group([
ifBreak("("),
indent([softline, expression]),
softline,
ifBreak(")")
])
);
} else {
statement.push(expression);
}
}
statement.push(";");
return statement;
},

throw_statement(path, print) {
return ["throw ", path.call(print, "namedChildren", 0), ";"];
},
return_statement: printReturnOrThrowStatement,
throw_statement: printReturnOrThrowStatement,

synchronized_statement(path, print) {
const parenthesizedExpressionIndex = path.node.namedChildren.findIndex(
Expand Down Expand Up @@ -483,3 +466,44 @@ function printExpressionList(expressions: Doc[]) {
)
);
}

function printReturnOrThrowArgument(path: NamedNodePath, print: PrintFunction) {
const { node } = path;
const argumentDoc = print(path);

if (returnArgumentHasLeadingComment(node)) {
return ["(", indent([hardline, argumentDoc]), hardline, ")"];
}

if (node.type === SyntaxType.BinaryExpression) {
return group([
ifBreak("("),
indent([softline, argumentDoc]),
softline,
ifBreak(")")
]);
}

return argumentDoc;
}

function printReturnOrThrowStatement(
path: AstPath<ReturnStatementNode | ThrowStatementNode>,
print: PrintFunction
) {
const { node } = path;
return [
node.type === SyntaxType.ThrowStatement ? "throw" : "return",
node.namedChildren.length
? [
" ",
path.call(
() => printReturnOrThrowArgument(path, print),
"namedChildren",
0
)
]
: "",
";"
];
}
Loading