- 
        Couldn't load subscription status. 
- Fork 70
Java 21: Pattern Matching + StringTemplate JEP-430 + Unnamed JEP-445 #935
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
          
     Open
      
      
            npeters
  wants to merge
  1
  commit into
  palantir:develop
  
    
      
        
          
  
    
      Choose a base branch
      
     
    
      
        
      
      
        
          
          
        
        
          
            
              
              
              
  
           
        
        
          
            
              
              
           
        
       
     
  
        
          
            
          
            
          
        
       
    
      
from
npeters:feature/java-21
  
      
      
   
  
    
  
  
  
 
  
      
    base: develop
Could not load branches
            
              
  
    Branch not found: {{ refName }}
  
            
                
      Loading
              
            Could not load tags
            
            
              Nothing to show
            
              
  
            
                
      Loading
              
            Are you sure you want to change the base?
            Some commits from the old base branch may be removed from the timeline,
            and old review comments may become outdated.
          
          
  
     Open
                    Changes from all commits
      Commits
    
    
  File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
        
          
          
            170 changes: 170 additions & 0 deletions
          
          170 
        
  ...ava-format/src/java21/java/com/palantir/javaformat/java/java21/Java21InputAstVisitor.java
  
  
      
      
   
        
      
      
    
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,170 @@ | ||
| /* | ||
| * (c) Copyright 2024 Palantir Technologies Inc. All rights reserved. | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|  | ||
| package com.palantir.javaformat.java.java21; | ||
|  | ||
| import com.google.common.collect.Iterables; | ||
| import com.palantir.javaformat.OpsBuilder; | ||
| import com.palantir.javaformat.java.JavaInputAstVisitor; | ||
| import com.palantir.javaformat.java.java14.Java14InputAstVisitor; | ||
| import com.sun.source.tree.BlockTree; | ||
| import com.sun.source.tree.CaseTree; | ||
| import com.sun.source.tree.ConstantCaseLabelTree; | ||
| import com.sun.source.tree.DeconstructionPatternTree; | ||
| import com.sun.source.tree.ParenthesizedTree; | ||
| import com.sun.source.tree.PatternCaseLabelTree; | ||
| import com.sun.source.tree.PatternTree; | ||
| import com.sun.source.tree.Tree; | ||
| import com.sun.source.tree.Tree.Kind; | ||
| import java.lang.reflect.Method; | ||
| import java.util.List; | ||
|  | ||
| /** | ||
| * Extends {@link Java14InputAstVisitor} with support for AST nodes that were added or modified for Java 14. | ||
| */ | ||
| public class Java21InputAstVisitor extends Java14InputAstVisitor { | ||
| private static final Method CASE_TREE_GET_LABELS2 = maybeGetMethodPrivate(CaseTree.class, "getLabels"); | ||
|  | ||
| private static Method maybeGetMethodPrivate(Class<?> c, String name) { | ||
| try { | ||
| return c.getMethod(name); | ||
| } catch (ReflectiveOperationException e) { | ||
| return null; | ||
| } | ||
| } | ||
|  | ||
| private static Object invokePrivate(Method m, Object target) { | ||
| try { | ||
| return m.invoke(target); | ||
| } catch (ReflectiveOperationException e) { | ||
| throw new RuntimeException(e.getMessage(), e); | ||
| } | ||
| } | ||
|  | ||
| public Java21InputAstVisitor(OpsBuilder builder, int indentMultiplier) { | ||
| super(builder, indentMultiplier); | ||
| } | ||
|  | ||
| @Override | ||
| public Void visitParenthesized(ParenthesizedTree node, Void unused) { | ||
| token("("); | ||
| Void v = scan(node.getExpression(), unused); | ||
| token(")"); | ||
| return v; | ||
| } | ||
|  | ||
| @Override | ||
| public Void visitDeconstructionPattern(DeconstructionPatternTree node, Void unused) { | ||
|  | ||
| Void r = scan(node.getDeconstructor(), unused); | ||
| token("("); | ||
| boolean firstInRow = true; | ||
| for (PatternTree item : node.getNestedPatterns()) { | ||
| if (!firstInRow) { | ||
| token(","); | ||
| builder.breakToFill(" "); | ||
| } | ||
| scan(item, null); | ||
| firstInRow = false; | ||
| } | ||
| token(")"); | ||
| return r; | ||
| } | ||
|  | ||
| @Override | ||
| public Void visitConstantCaseLabel(ConstantCaseLabelTree node, Void unused) { | ||
| return scan(node.getConstantExpression(), unused); | ||
| } | ||
|  | ||
| @Override | ||
| public Void visitCase(CaseTree node, Void unused) { | ||
| sync(node); | ||
| markForPartialFormat(); | ||
| builder.forcedBreak(); | ||
| List<? extends Tree> labels; | ||
| boolean isDefault; | ||
| if (CASE_TREE_GET_LABELS2 != null) { | ||
| labels = (List<? extends Tree>) invokePrivate(CASE_TREE_GET_LABELS2, node); | ||
| isDefault = labels.size() == 1 | ||
| && Iterables.getOnlyElement(labels).getKind().name().equals("DEFAULT_CASE_LABEL"); | ||
| } else { | ||
| labels = node.getExpressions(); | ||
| isDefault = labels.isEmpty(); | ||
| } | ||
| if (isDefault) { | ||
| token("default", plusTwo); | ||
| } else { | ||
| token("case", plusTwo); | ||
| builder.space(); | ||
| builder.open(labels.size() > 1 ? plusFour : JavaInputAstVisitor.ZERO); | ||
| boolean first = true; | ||
| for (Tree expression : labels) { | ||
| if (!first) { | ||
| token(","); | ||
| builder.breakOp(" "); | ||
| } | ||
| scan(expression, null); | ||
| first = false; | ||
| } | ||
| builder.close(); | ||
| } | ||
| switch (node.getCaseKind()) { | ||
| case STATEMENT: | ||
| token(":"); | ||
| boolean isBlock = node.getStatements().size() == 1 | ||
| && node.getStatements().get(0).getKind() == Kind.BLOCK; | ||
| builder.open(isBlock ? JavaInputAstVisitor.ZERO : plusTwo); | ||
| if (isBlock) { | ||
| builder.space(); | ||
| } | ||
| visitStatements(node.getStatements(), isBlock); | ||
| builder.close(); | ||
| break; | ||
| case RULE: | ||
| if (node.getGuard() != null) { | ||
| builder.space(); | ||
| token("when"); | ||
| builder.space(); | ||
| scan(node.getGuard(), null); | ||
| } | ||
|  | ||
| builder.space(); | ||
| token("-"); | ||
| token(">"); | ||
|  | ||
| builder.space(); | ||
| if (node.getBody().getKind() == Kind.BLOCK) { | ||
| // Explicit call with {@link CollapseEmptyOrNot.YES} to handle empty case blocks. | ||
| visitBlock( | ||
| (BlockTree) node.getBody(), | ||
| CollapseEmptyOrNot.YES, | ||
| AllowLeadingBlankLine.NO, | ||
| AllowTrailingBlankLine.NO); | ||
| } else { | ||
| scan(node.getBody(), null); | ||
| } | ||
| builder.guessToken(";"); | ||
| break; | ||
| default: | ||
| throw new IllegalArgumentException(node.getCaseKind().name()); | ||
| } | ||
| return null; | ||
| } | ||
|  | ||
| public Void visitPatternCaseLabel(PatternCaseLabelTree node, Void p) { | ||
| return scan(node.getPattern(), p); | ||
| } | ||
| } | 
        
          
          
            31 changes: 31 additions & 0 deletions
          
          31 
        
  .../java21Preview/java/com/palantir/javaformat/java/java21/Java21PreviewInputAstVisitor.java
  
  
      
      
   
        
      
      
    
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| /* | ||
| * (c) Copyright 2024 Palantir Technologies Inc. All rights reserved. | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
| package com.palantir.javaformat.java.java21; | ||
|  | ||
| import com.palantir.javaformat.OpsBuilder; | ||
| import com.sun.source.tree.AnyPatternTree; | ||
|  | ||
| public class Java21PreviewInputAstVisitor extends Java21InputAstVisitor { | ||
|  | ||
| public Java21PreviewInputAstVisitor(OpsBuilder builder, int indentMultiplier) { | ||
| super(builder, indentMultiplier); | ||
| } | ||
|  | ||
| public Void visitAnyPattern(AnyPatternTree node, Void p) { | ||
| token("_"); | ||
| return p; | ||
| } | ||
| } | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
|  | @@ -45,6 +45,7 @@ | |
| import com.sun.tools.javac.util.Log; | ||
| import com.sun.tools.javac.util.Options; | ||
| import java.io.IOException; | ||
| import java.lang.management.ManagementFactory; | ||
| import java.net.URI; | ||
| import java.util.Collection; | ||
| import javax.tools.Diagnostic; | ||
|  | @@ -131,7 +132,26 @@ static JavaOutput format( | |
| OpsBuilder opsBuilder = new OpsBuilder(javaInput); | ||
|  | ||
| JavaInputAstVisitor visitor; | ||
| if (getRuntimeVersion() >= 14) { | ||
|  | ||
| There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Remove that empty line | ||
| if (getRuntimeVersion() >= 21 && isEnabledPriew()) { | ||
| try { | ||
| visitor = Class.forName("com.palantir.javaformat.java.java21.Java21PreviewInputAstVisitor") | ||
| .asSubclass(JavaInputAstVisitor.class) | ||
| .getConstructor(OpsBuilder.class, int.class) | ||
| .newInstance(opsBuilder, options.indentationMultiplier()); | ||
| } catch (ReflectiveOperationException e) { | ||
| throw new RuntimeException(e.getMessage(), e); | ||
| } | ||
| } else if (getRuntimeVersion() >= 21) { | ||
| try { | ||
| visitor = Class.forName("com.palantir.javaformat.java.java21.Java21InputAstVisitor") | ||
| .asSubclass(JavaInputAstVisitor.class) | ||
| .getConstructor(OpsBuilder.class, int.class) | ||
| .newInstance(opsBuilder, options.indentationMultiplier()); | ||
| } catch (ReflectiveOperationException e) { | ||
| throw new RuntimeException(e.getMessage(), e); | ||
| } | ||
| } else if (getRuntimeVersion() >= 14) { | ||
| try { | ||
| visitor = Class.forName("com.palantir.javaformat.java.java14.Java14InputAstVisitor") | ||
| .asSubclass(JavaInputAstVisitor.class) | ||
|  | @@ -206,6 +226,11 @@ static int getRuntimeVersion() { | |
| return Runtime.version().feature(); | ||
| } | ||
|  | ||
| @VisibleForTesting | ||
| static boolean isEnabledPriew() { | ||
| return ManagementFactory.getRuntimeMXBean().getInputArguments().contains("--enable-preview"); | ||
| } | ||
|  | ||
| static boolean errorDiagnostic(Diagnostic<?> input) { | ||
| if (input.getKind() != Diagnostic.Kind.ERROR) { | ||
| return false; | ||
|  | ||
      
      Oops, something went wrong.
        
    
  
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I would remove this empty line