Skip to content

Commit

Permalink
fix: improve throws formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
jtkiesel committed Jan 16, 2024
1 parent 983a09d commit ea90004
Show file tree
Hide file tree
Showing 29 changed files with 3,718 additions and 44 deletions.
55 changes: 55 additions & 0 deletions packages/prettier-plugin-java/dist/base-cst-printer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { BaseJavaCstVisitor } from "java-parser";
import { printNodeWithComments } from "./printers/comments/format-comments.js";
export class BaseCstPrettierPrinter extends BaseJavaCstVisitor {
constructor() {
super();
this.mapVisit = (elements, params) => {
if (elements === undefined) {
// TODO: can optimize this by returning an immutable empty array singleton.
return [];
}
return elements.map(element => this.visit(element, params));
};
this.getSingle = (ctx) => {
const ctxKeys = Object.keys(ctx);
if (ctxKeys.length !== 1) {
throw Error(`Expecting single key CST ctx but found: <${ctxKeys.length}> keys`);
}
const singleElementKey = ctxKeys[0];
const singleElementValues = ctx[singleElementKey];
if ((singleElementValues === null || singleElementValues === void 0 ? void 0 : singleElementValues.length) !== 1) {
throw Error(`Expecting single item in CST ctx key but found: <${singleElementValues === null || singleElementValues === void 0 ? void 0 : singleElementValues.length}> items`);
}
return singleElementValues[0];
};
// @ts-ignore
this.orgVisit = this.visit;
this.visit = function (ctx, inParam) {
if (ctx === undefined) {
// empty Doc
return "";
}
const node = Array.isArray(ctx) ? ctx[0] : ctx;
if (node.ignore) {
try {
const startOffset = node.leadingComments !== undefined
? node.leadingComments[0].startOffset
: node.location.startOffset;
const endOffset = (node.trailingComments !== undefined
? node.trailingComments[node.trailingComments.length - 1].endOffset
: node.location.endOffset);
return this.prettierOptions.originalText.substring(startOffset, endOffset + 1);
}
catch (e) {
throw Error(e +
"\nThere might be a problem with prettier-ignore, please report an issue on https://github.com/jhipster/prettier-java/issues");
}
}
return printNodeWithComments(node, this.orgVisit.call(this, node, inParam));
};
this.visitSingle = function (ctx, params) {
const singleElement = this.getSingle(ctx);
return this.visit(singleElement, params);
};
}
}
29 changes: 29 additions & 0 deletions packages/prettier-plugin-java/dist/cst-printer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { BaseCstPrettierPrinter } from "./base-cst-printer.js";
import { ArraysPrettierVisitor } from "./printers/arrays.js";
import { BlocksAndStatementPrettierVisitor } from "./printers/blocks-and-statements.js";
import { ClassesPrettierVisitor } from "./printers/classes.js";
import { ExpressionsPrettierVisitor } from "./printers/expressions.js";
import { InterfacesPrettierVisitor } from "./printers/interfaces.js";
import { LexicalStructurePrettierVisitor } from "./printers/lexical-structure.js";
import { NamesPrettierVisitor } from "./printers/names.js";
import { TypesValuesAndVariablesPrettierVisitor } from "./printers/types-values-and-variables.js";
import { PackagesAndModulesPrettierVisitor } from "./printers/packages-and-modules.js";
// Mixins for the win
mixInMethods(ArraysPrettierVisitor, BlocksAndStatementPrettierVisitor, ClassesPrettierVisitor, ExpressionsPrettierVisitor, InterfacesPrettierVisitor, LexicalStructurePrettierVisitor, NamesPrettierVisitor, TypesValuesAndVariablesPrettierVisitor, PackagesAndModulesPrettierVisitor);
function mixInMethods(...classesToMix) {
classesToMix.forEach(from => {
const fromMethodsNames = Object.getOwnPropertyNames(from.prototype);
const fromPureMethodsName = fromMethodsNames.filter(methodName => methodName !== "constructor");
fromPureMethodsName.forEach(methodName => {
// @ts-ignore
BaseCstPrettierPrinter.prototype[methodName] = from.prototype[methodName];
});
});
}
const prettyPrinter = new BaseCstPrettierPrinter();
// TODO: do we need the "path" and "print" arguments passed by prettier
// see https://github.com/prettier/prettier/issues/5747
export function createPrettierDoc(cstNode, options) {
prettyPrinter.prettierOptions = options;
return prettyPrinter.visit(cstNode);
}
66 changes: 66 additions & 0 deletions packages/prettier-plugin-java/dist/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import parse from "./parser.js";
import print from "./printer.js";
import options from "./options.js";
const languages = [
{
name: "Java",
parsers: ["java"],
group: "Java",
tmScope: "text.html.vue",
aceMode: "html",
codemirrorMode: "clike",
codemirrorMimeType: "text/x-java",
extensions: [".java"],
linguistLanguageId: 181,
vscodeLanguageIds: ["java"]
}
];
function locStart( /* node */) {
return -1;
}
function locEnd( /* node */) {
return -1;
}
function hasPragma(text) {
return /^\/\*\*[\n][\t\s]+\*\s@(prettier|format)[\n][\t\s]+\*\//.test(text);
}
const parsers = {
java: {
parse,
astFormat: "java",
locStart,
locEnd,
hasPragma
}
};
function canAttachComment(node) {
return node.ast_type && node.ast_type !== "comment";
}
function printComment(commentPath) {
const comment = commentPath.getValue();
switch (comment.ast_type) {
case "comment":
return comment.value;
default:
throw new Error("Not a comment: " + JSON.stringify(comment));
}
}
function clean(ast, newObj) {
delete newObj.lineno;
delete newObj.col_offset;
}
const printers = {
java: {
print,
// hasPrettierIgnore,
printComment,
canAttachComment,
massageAstNode: clean
}
};
export default {
languages,
printers,
parsers,
options
};
242 changes: 242 additions & 0 deletions packages/prettier-plugin-java/dist/options.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,242 @@
export default {
entrypoint: {
type: "choice",
category: "Global",
default: "compilationUnit",
// sed -nr 's/.*\.RULE\(([^,]+),.*/\1/p' $(ls path/to/java-parser/rules/folder/*)
choices: [
{ value: "arrayInitializer" },
{ value: "variableInitializerList" },
{ value: "block" },
{ value: "blockStatements" },
{ value: "blockStatement" },
{ value: "localVariableDeclarationStatement" },
{ value: "localVariableDeclaration" },
{ value: "localVariableType" },
{ value: "statement" },
{ value: "statementWithoutTrailingSubstatement" },
{ value: "emptyStatement" },
{ value: "labeledStatement" },
{ value: "expressionStatement" },
{ value: "statementExpression" },
{ value: "ifStatement" },
{ value: "assertStatement" },
{ value: "switchStatement" },
{ value: "switchBlock" },
{ value: "switchBlockStatementGroup" },
{ value: "switchLabel" },
{ value: "switchRule" },
{ value: "caseConstant" },
{ value: "whileStatement" },
{ value: "doStatement" },
{ value: "forStatement" },
{ value: "basicForStatement" },
{ value: "forInit" },
{ value: "forUpdate" },
{ value: "statementExpressionList" },
{ value: "enhancedForStatement" },
{ value: "breakStatement" },
{ value: "continueStatement" },
{ value: "returnStatement" },
{ value: "throwStatement" },
{ value: "synchronizedStatement" },
{ value: "tryStatement" },
{ value: "catches" },
{ value: "catchClause" },
{ value: "catchFormalParameter" },
{ value: "catchType" },
{ value: "finally" },
{ value: "tryWithResourcesStatement" },
{ value: "resourceSpecification" },
{ value: "resourceList" },
{ value: "resource" },
{ value: "yieldStatement" },
{ value: "variableAccess" },
{ value: "classDeclaration" },
{ value: "normalClassDeclaration" },
{ value: "classModifier" },
{ value: "typeParameters" },
{ value: "typeParameterList" },
{ value: "superclass" },
{ value: "superinterfaces" },
{ value: "interfaceTypeList" },
{ value: "classPermits" },
{ value: "classBody" },
{ value: "classBodyDeclaration" },
{ value: "classMemberDeclaration" },
{ value: "fieldDeclaration" },
{ value: "fieldModifier" },
{ value: "variableDeclaratorList" },
{ value: "variableDeclarator" },
{ value: "variableDeclaratorId" },
{ value: "variableInitializer" },
{ value: "unannType" },
{ value: "unannPrimitiveTypeWithOptionalDimsSuffix" },
{ value: "unannPrimitiveType" },
{ value: "unannReferenceType" },
{ value: "unannClassOrInterfaceType" },
{ value: "unannClassType" },
{ value: "unannInterfaceType" },
{ value: "unannTypeVariable" },
{ value: "methodDeclaration" },
{ value: "methodModifier" },
{ value: "methodHeader" },
{ value: "result" },
{ value: "methodDeclarator" },
{ value: "receiverParameter" },
{ value: "formalParameterList" },
{ value: "formalParameter" },
{ value: "variableParaRegularParameter" },
{ value: "variableArityParameter" },
{ value: "variableModifier" },
{ value: "throws" },
{ value: "exceptionTypeList" },
{ value: "exceptionType" },
{ value: "methodBody" },
{ value: "instanceInitializer" },
{ value: "staticInitializer" },
{ value: "constructorDeclaration" },
{ value: "constructorModifier" },
{ value: "constructorDeclarator" },
{ value: "simpleTypeName" },
{ value: "constructorBody" },
{ value: "explicitConstructorInvocation" },
{ value: "unqualifiedExplicitConstructorInvocation" },
{ value: "qualifiedExplicitConstructorInvocation" },
{ value: "enumDeclaration" },
{ value: "enumBody" },
{ value: "enumConstantList" },
{ value: "enumConstant" },
{ value: "enumConstantModifier" },
{ value: "enumBodyDeclarations" },
{ value: "recordDeclaration" },
{ value: "recordHeader" },
{ value: "recordComponentList" },
{ value: "recordComponent" },
{ value: "variableArityRecordComponent" },
{ value: "recordComponentModifier" },
{ value: "recordBody" },
{ value: "recordBodyDeclaration" },
{ value: "compactConstructorDeclaration" },
{ value: "isDims" },
{ value: "expression" },
{ value: "lambdaExpression" },
{ value: "lambdaParameters" },
{ value: "lambdaParametersWithBraces" },
{ value: "lambdaParameterList" },
{ value: "inferredLambdaParameterList" },
{ value: "explicitLambdaParameterList" },
{ value: "lambdaParameter" },
{ value: "regularLambdaParameter" },
{ value: "lambdaParameterType" },
{ value: "lambdaBody" },
{ value: "ternaryExpression" },
{ value: "binaryExpression" },
{ value: "unaryExpression" },
{ value: "unaryExpressionNotPlusMinus" },
{ value: "primary" },
{ value: "primaryPrefix" },
{ value: "primarySuffix" },
{ value: "fqnOrRefType" },
{ value: "fqnOrRefTypePartRest" },
{ value: "fqnOrRefTypePartCommon" },
{ value: "fqnOrRefTypePartFirst" },
{ value: "parenthesisExpression" },
{ value: "castExpression" },
{ value: "primitiveCastExpression" },
{ value: "referenceTypeCastExpression" },
{ value: "newExpression" },
{ value: "unqualifiedClassInstanceCreationExpression" },
{ value: "classOrInterfaceTypeToInstantiate" },
{ value: "typeArgumentsOrDiamond" },
{ value: "diamond" },
{ value: "methodInvocationSuffix" },
{ value: "argumentList" },
{ value: "arrayCreationExpression" },
{ value: "arrayCreationDefaultInitSuffix" },
{ value: "arrayCreationExplicitInitSuffix" },
{ value: "dimExprs" },
{ value: "dimExpr" },
{ value: "classLiteralSuffix" },
{ value: "arrayAccessSuffix" },
{ value: "methodReferenceSuffix" },
{ value: "pattern" },
{ value: "typePattern" },
{ value: "recordPattern" },
{ value: "componentPatternList" },
{ value: "componentPattern" },
{ value: "unnamedPattern" },
{ value: "guard" },
{ value: "isRefTypeInMethodRef" },
{ value: "interfaceDeclaration" },
{ value: "normalInterfaceDeclaration" },
{ value: "interfaceModifier" },
{ value: "extendsInterfaces" },
{ value: "interfacePermits" },
{ value: "interfaceBody" },
{ value: "interfaceMemberDeclaration" },
{ value: "constantDeclaration" },
{ value: "constantModifier" },
{ value: "interfaceMethodDeclaration" },
{ value: "interfaceMethodModifier" },
{ value: "annotationTypeDeclaration" },
{ value: "annotationTypeBody" },
{ value: "annotationTypeMemberDeclaration" },
{ value: "annotationTypeElementDeclaration" },
{ value: "annotationTypeElementModifier" },
{ value: "defaultValue" },
{ value: "annotation" },
{ value: "elementValuePairList" },
{ value: "elementValuePair" },
{ value: "elementValue" },
{ value: "elementValueArrayInitializer" },
{ value: "elementValueList" },
{ value: "literal" },
{ value: "integerLiteral" },
{ value: "floatingPointLiteral" },
{ value: "booleanLiteral" },
{ value: "moduleName" },
{ value: "packageName" },
{ value: "typeName" },
{ value: "expressionName" },
{ value: "methodName" },
{ value: "packageOrTypeName" },
{ value: "ambiguousName" },
{ value: "compilationUnit" },
{ value: "ordinaryCompilationUnit" },
{ value: "modularCompilationUnit" },
{ value: "packageDeclaration" },
{ value: "packageModifier" },
{ value: "importDeclaration" },
{ value: "typeDeclaration" },
{ value: "moduleDeclaration" },
{ value: "moduleDirective" },
{ value: "requiresModuleDirective" },
{ value: "exportsModuleDirective" },
{ value: "opensModuleDirective" },
{ value: "usesModuleDirective" },
{ value: "providesModuleDirective" },
{ value: "requiresModifier" },
{ value: "primitiveType" },
{ value: "numericType" },
{ value: "integralType" },
{ value: "floatingPointType" },
{ value: "referenceType" },
{ value: "classOrInterfaceType" },
{ value: "classType" },
{ value: "interfaceType" },
{ value: "typeVariable" },
{ value: "dims" },
{ value: "typeParameter" },
{ value: "typeParameterModifier" },
{ value: "typeBound" },
{ value: "additionalBound" },
{ value: "typeArguments" },
{ value: "typeArgumentList" },
{ value: "typeArgument" },
{ value: "wildcard" },
{ value: "wildcardBounds" }
],
description: "Prettify from the entrypoint, allowing to use prettier on snippet."
}
};
Loading

0 comments on commit ea90004

Please sign in to comment.