use of org.codehaus.groovy.ast.CodeVisitorSupport in project groovy by apache.
the class AstBuilder method visitCompactConstructorDeclaration.
@Override
public MethodNode visitCompactConstructorDeclaration(CompactConstructorDeclarationContext ctx) {
ClassNode classNode = ctx.getNodeMetaData(CLASS_DECLARATION_CLASS_NODE);
Objects.requireNonNull(classNode, "classNode should not be null");
if (!AnnotatedNodeUtils.hasAnnotation(classNode, RECORD_TYPE_CLASS)) {
createParsingFailedException("Only `record` can have compact constructor", ctx);
}
List<ModifierNode> modifierNodeList = ctx.getNodeMetaData(COMPACT_CONSTRUCTOR_DECLARATION_MODIFIERS);
Objects.requireNonNull(modifierNodeList, "modifierNodeList should not be null");
ModifierManager modifierManager = new ModifierManager(this, modifierNodeList);
if (modifierManager.containsAny(VAR)) {
throw createParsingFailedException("var cannot be used for compact constructor declaration", ctx);
}
String methodName = this.visitMethodName(ctx.methodName());
String className = classNode.getNodeMetaData(CLASS_NAME);
if (!methodName.equals(className)) {
createParsingFailedException("Compact constructor should have the same name with record: " + className, ctx.methodName());
}
Parameter[] header = classNode.getNodeMetaData(RECORD_HEADER);
Objects.requireNonNull(header, "record header should not be null");
final Parameter[] parameters = cloneParams(header);
Statement code = this.visitMethodBody(ctx.methodBody());
code.visit(new CodeVisitorSupport() {
@Override
public void visitPropertyExpression(PropertyExpression expression) {
final String propertyName = expression.getPropertyAsString();
if (THIS_STR.equals(expression.getObjectExpression().getText()) && Arrays.stream(parameters).anyMatch(p -> p.getName().equals(propertyName))) {
createParsingFailedException("Cannot assign a value to final variable `" + propertyName + "`", expression.getProperty());
}
super.visitPropertyExpression(expression);
}
});
attachTupleConstructorAnnotationToRecord(classNode, parameters, code);
return null;
}
Aggregations