SlideShare ist ein Scribd-Unternehmen logo
1 von 30
Downloaden Sie, um offline zu lesen
JavaParser
A tool to generate, analyze, and refactor Java code
Federico Tomassetti founder of
Goal
JavaParser is evolving in a suite of libraries to support:
• Code generation
• Code analysis
• Code refactoring
It has a growing user-base but we are not sure on which usages
to focus:
Can you help us figure out
who could we serve better?
What JavaParser does?
JavaParser… parse Java code into a Java AST
package foo.bar;
class A {
int field;
}
CompilationUnit
PackageDecl ClassDecl
FieldDecl
PrimitiveType
What JavaParser does?
JavaParser unparse an AST into code
package foo.bar;
class A {
int field;
}
CompilationUnit
PackageDecl ClassDecl
FieldDecl
PrimitiveType
Why do you need symbol resolving?
int foo;
public void aMethod(int foo) {
foo = 1;
}
public void anotherMethod() {
foo = 1;
}
To JP these two statements looks the same: they produce the same
AST nodes.
It is the assignment of a thing named ”foo”, no idea what that thing is
public void print1(String foo) {
System.out.print(foo);
}
public void print2(int foo) {
System.out.print(foo);
}
To JP these two statements looks the same: they produce the same
AST nodes.
It is the call of a method named “print”, no idea which signature that
has
Why do you need symbol resolving?
class A { }
public void creator1() {
new A();
}
public void creator2() {
class A { }
new A();
}
To JP these two statements looks the same: they produce the same
AST nodes.
It is the instantiation of a class named “A”, no idea where it is defined
Why do you need symbol resolving?
What JavaSymbolSolver does?
JavaSymbolSolver resolves symbols in the JavaParser AST
package foo.bar;
class C {
D field;
}
package foo.bar;
class D {
}
CompilationUnit
PackageDecl ClassDecl
FieldDecl
ReferenceType
Relationship JP & JSS
Certain methods in the AST requires additional intelligence.
myCallExpression.calculateResolvedType();
myCallExpression.getName();
JSS not enabled JSS enabled
JSS not enabled JSS enabled
Configuring JavaSymbolSolver
A typical usage:
CombinedTypeSolver typeSolver = new CombinedTypeSolver(
new ReflectionTypeSolver(),
new JavaParserTypeSolver(new File("src/main/java")),
new JavaParserTypeSolver(new File("src/test/java")),
new JarTypeSolver("libs/guava.jar"),
new JarTypeSolver("libs/log4j.jar"));
Supporting code generation
We want to support people who has to generate code:
• Because they want to generate boilerplate code from
some source (e.g., a database schema)
• They want to build a transpiler targeting Java
JavaParser to generate code
CompilationUnit cu = new CompilationUnit();
cu.setPackageDeclaration("jpexample.model");
ClassOrInterfaceDeclaration book =
cu.addClass("Book");
book.addField("String", "title");
book.addField("Person", "author");
JavaParser to generate code
book.addConstructor(Modifier.PUBLIC)
.addParameter("String", "title")
.addParameter("Person", "author")
.setBody(new BlockStmt()
.addStatement(new ExpressionStmt(new AssignExpr(
new FieldAccessExpr(
new ThisExpr(), "title"),
new NameExpr("title"),
AssignExpr.Operator.ASSIGN)))
.addStatement(new ExpressionStmt(new AssignExpr(
new FieldAccessExpr(
new ThisExpr(), "author"),
new NameExpr("author"),
AssignExpr.Operator.ASSIGN))));
JavaParser to generate code
book.addMethod("getTitle", Modifier.PUBLIC).setBody(
new BlockStmt().addStatement(
new ReturnStmt(new NameExpr("title"))));
book.addMethod("getAuthor", Modifier.PUBLIC).setBody(
new BlockStmt().addStatement(
new ReturnStmt(new NameExpr("author"))));
System.out.println(cu.toString());
JavaParser to generate code
package jpexample.model;
public class Book {
String title;
Person author;
public Book(String title, Person author) {
this.title = title;
this.author = author;
}
public void getTitle() {
return title;
}
public void getAuthor() {
return author;
}
}
Supporting code analysis
We want to support people who have to analyse code:
• Because they want some metrics on code
• Because they want to ensure some quality standards are
met
• Because they want to write quick, one-off queries about
their codebase
JavaParser to run queries
Question: How many methods take more than 3 parameters?
long n = getNodes(allCus, MethodDeclaration.class)
.stream()
.filter(m -> m.getParameters().size() > 3)
.count();
System.out.println("N of methods with >3 params: "
+ n);
Answer: 11
JavaParser to run queries
Question: What are the three top classes with most methods?
Answer: CoreMatchers: 35 methods
BaseDescription: 13 methods
IsEqual: 9 methods
getNodes(allCus, ClassOrInterfaceDeclaration.class)
.stream()
.filter(c -> !c.isInterface())
.sorted(Comparator.comparingInt(o ->
-1 * o.getMethods().size()))
.limit(3)
.forEach(c ->
System.out.println(c.getNameAsString()
+ ": " + c.getMethods().size()
+ " methods"));
JavaParser to run queries
Question: What is the class with most ancestors?
Answer: org.hamcrest.core.StringContains: org.hamcrest.core.SubstringMatcher,
org.hamcrest.TypeSafeMatcher, org.hamcrest.BaseMatcher, org.hamcrest.Matcher,
org.hamcrest.SelfDescribing, java.lang.Object
ResolvedReferenceTypeDeclaration c = getNodes(allCus,
ClassOrInterfaceDeclaration.class)
.stream()
.filter(c -> !c.isInterface())
.map(c -> c.resolve())
.sorted(Comparator.comparingInt(o ->
-1 * o.getAllAncestors().size()))
.findFirst().get();
List<String> ancestorNames = c.getAllAncestors()
.stream()
.map(a -> a.getQualifiedName())
.collect(Collectors.toList());
System.out.println(c.getQualifiedName() + ": " +
String.join(", ", ancestorNames));
JSS at work here
Supporting code refactoring
We want to support people who has to refactor code:
• Because they have to modernize legacy code
• Because they want to update some dependencies and
the API of the libraries used changed
• Because they want to change some usage patterns
JavaParser for automated
refactoring
getNodes(allCus, MethodCallExpr.class)
.stream()
.filter(m -> m.resolveInvokedMethod()
.getQualifiedSignature()
.equals("foo.MyClass.oldMethod(java.lang.String,
int)"))
.forEach(m -> m.replace(replaceCallsToOldMethod(m)));
A new version of a library comes up and a deprecated method named
oldMethod is replaced by newMethod.
The new method takes 3 parameters: the first one as oldMethod but
inverted and the third one is a boolean, which we want to be always
true
JavaParser for automated
refactoring
public MethodCallExpr replaceCallsToOldMethod(
MethodCallExpr methodCall) {
MethodCallExpr newMethodCall = new MethodCallExpr(
methodCall.getScope().get(), "newMethod");
newMethodCall.addArgument(methodCall.getArgument(1));
newMethodCall.addArgument(methodCall.getArgument(0));
newMethodCall.addArgument(new BooleanLiteralExpr(true));
return newMethodCall;
}
Some other features
Comments attribution
void foo() {
// comment1
int a =
1 + 2; // comment2
}
// comment1
int a =
1 + 2;
CompilationUnit cu = JavaParser.parse(code);
ExpressionStmt expressionStmt =
cu.findFirst(ExpressionStmt.class).get() ;
System.out.println("Comment on the expression statement: "
+ expressionStmt.getComment().get().getContent());
Lexical preservation
Pretty printing is good for new code but for existing code users
want lexical preservation.
It is tricky because you need to know how to modify code
preserving the style and making the code correct.
Original code Change Final code
int a, b, c; remove b, adapt commas int a, c;
void foo() {
int a;
}
add new statement, indent
it as statement a previous
line
void foo() {
int a;
a = 0;
}
Things we are considering
JavaParser to identify patterns
We are working on the Matcher library to reduce the complexity, it is in the early
stages
This gives you a list of pairs name-type for all the properties in your bean.
Java templates
We are discussing the idea of Java templates.
We would like to have Java code with placeholders for variable parts
and be able to validate those templates.
class A extends ${BASE_CLASS:Id} {
private ${FIELD_TYPE:Type} myField;
}
class A extends ${BASE_CLASS:Id} {
${E:Expression} myField;
}
OK
KO
Making Java extensible
Researchers (but also a certain company…) would be interested in
writing extensions for Java based on JavaParser.
How can you add a new statement or expression to Java today? You
have to fork the parser. We have one user who forked JavaParser just
to change the grammar file.
We are looking for a better way.
Any suggestions?
JavaParser: Visited
Book on JavaParser and JavaSymbolSolver,
from the core committers.
Avalaible for 0+ $
Currently 1.000+ readers
https://leanpub.com/javaparservisited
Federico Tomassetti
See you on GitHub at
javaparser/javaparser

Weitere ähnliche Inhalte

Ähnlich wie JavaParser - A tool to generate, analyze and refactor Java code

JavaBasicsCore1.ppt
JavaBasicsCore1.pptJavaBasicsCore1.ppt
JavaBasicsCore1.pptbuvanabala
 
Java OOP Concepts 1st Slide
Java OOP Concepts 1st SlideJava OOP Concepts 1st Slide
Java OOP Concepts 1st Slidesunny khan
 
Topic2JavaBasics.ppt
Topic2JavaBasics.pptTopic2JavaBasics.ppt
Topic2JavaBasics.pptMENACE4
 
hallleuah_java.ppt
hallleuah_java.ppthallleuah_java.ppt
hallleuah_java.pptRahul201258
 
Introduction to Intermediate Java
Introduction to Intermediate JavaIntroduction to Intermediate Java
Introduction to Intermediate JavaPhilip Johnson
 
A Scala tutorial
A Scala tutorialA Scala tutorial
A Scala tutorialDima Statz
 
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsMahika Tutorials
 
Scala uma poderosa linguagem para a jvm
Scala   uma poderosa linguagem para a jvmScala   uma poderosa linguagem para a jvm
Scala uma poderosa linguagem para a jvmIsaias Barroso
 
Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)jeffz
 
Lab 1 Recursion  Introduction   Tracery (tracery.io.docx
Lab 1 Recursion  Introduction   Tracery (tracery.io.docxLab 1 Recursion  Introduction   Tracery (tracery.io.docx
Lab 1 Recursion  Introduction   Tracery (tracery.io.docxsmile790243
 
Cancer genomics big_datascience_meetup_july_14_2014
Cancer genomics big_datascience_meetup_july_14_2014Cancer genomics big_datascience_meetup_july_14_2014
Cancer genomics big_datascience_meetup_july_14_2014Shyam Sarkar
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Martin Odersky
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionGanesh Samarthyam
 
Android Training (Java Review)
Android Training (Java Review)Android Training (Java Review)
Android Training (Java Review)Khaled Anaqwa
 
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building BlocksOCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building Blocksİbrahim Kürce
 

Ähnlich wie JavaParser - A tool to generate, analyze and refactor Java code (20)

JavaBasicsCore1.ppt
JavaBasicsCore1.pptJavaBasicsCore1.ppt
JavaBasicsCore1.ppt
 
Java OOP Concepts 1st Slide
Java OOP Concepts 1st SlideJava OOP Concepts 1st Slide
Java OOP Concepts 1st Slide
 
Topic2JavaBasics.ppt
Topic2JavaBasics.pptTopic2JavaBasics.ppt
Topic2JavaBasics.ppt
 
hallleuah_java.ppt
hallleuah_java.ppthallleuah_java.ppt
hallleuah_java.ppt
 
2.ppt
2.ppt2.ppt
2.ppt
 
Slides
SlidesSlides
Slides
 
Introduction to Intermediate Java
Introduction to Intermediate JavaIntroduction to Intermediate Java
Introduction to Intermediate Java
 
Java SE 8 & EE 7 Launch
Java SE 8 & EE 7 LaunchJava SE 8 & EE 7 Launch
Java SE 8 & EE 7 Launch
 
Scala presentationjune112011
Scala presentationjune112011Scala presentationjune112011
Scala presentationjune112011
 
A Scala tutorial
A Scala tutorialA Scala tutorial
A Scala tutorial
 
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika Tutorials
 
Scala uma poderosa linguagem para a jvm
Scala   uma poderosa linguagem para a jvmScala   uma poderosa linguagem para a jvm
Scala uma poderosa linguagem para a jvm
 
Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)
 
Lab 1 Recursion  Introduction   Tracery (tracery.io.docx
Lab 1 Recursion  Introduction   Tracery (tracery.io.docxLab 1 Recursion  Introduction   Tracery (tracery.io.docx
Lab 1 Recursion  Introduction   Tracery (tracery.io.docx
 
Cancer genomics big_datascience_meetup_july_14_2014
Cancer genomics big_datascience_meetup_july_14_2014Cancer genomics big_datascience_meetup_july_14_2014
Cancer genomics big_datascience_meetup_july_14_2014
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - Description
 
Android Training (Java Review)
Android Training (Java Review)Android Training (Java Review)
Android Training (Java Review)
 
Synapse India Reviews
Synapse India ReviewsSynapse India Reviews
Synapse India Reviews
 
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building BlocksOCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
 

Mehr von Federico Tomassetti

Jariko - A JVM interpreter for RPG written in kotlin
Jariko - A JVM interpreter for RPG written in kotlinJariko - A JVM interpreter for RPG written in kotlin
Jariko - A JVM interpreter for RPG written in kotlinFederico Tomassetti
 
How do you create a programming language for the JVM?
How do you create a programming language for the JVM?How do you create a programming language for the JVM?
How do you create a programming language for the JVM?Federico Tomassetti
 
Automatically Spotting Cross-language Relations
Automatically Spotting Cross-language RelationsAutomatically Spotting Cross-language Relations
Automatically Spotting Cross-language RelationsFederico Tomassetti
 
Lifting variability from C to mbeddr-C
Lifting variability from C to mbeddr-CLifting variability from C to mbeddr-C
Lifting variability from C to mbeddr-CFederico Tomassetti
 
Maturity of Software Modelling and Model Driven Engineering: a Survey in the ...
Maturity of Software Modelling and Model Driven Engineering: a Survey in the ...Maturity of Software Modelling and Model Driven Engineering: a Survey in the ...
Maturity of Software Modelling and Model Driven Engineering: a Survey in the ...Federico Tomassetti
 
Eclipse Florence Day: Modeling in the Italian Industry
Eclipse Florence Day: Modeling in the Italian IndustryEclipse Florence Day: Modeling in the Italian Industry
Eclipse Florence Day: Modeling in the Italian IndustryFederico Tomassetti
 
Estendere Java con il Meta Programming System di JetBrains
Estendere Java con il Meta Programming System di JetBrains Estendere Java con il Meta Programming System di JetBrains
Estendere Java con il Meta Programming System di JetBrains Federico Tomassetti
 
Xtext Un Framework Per La Creazione Di Dsl
Xtext   Un Framework Per La Creazione Di DslXtext   Un Framework Per La Creazione Di Dsl
Xtext Un Framework Per La Creazione Di DslFederico Tomassetti
 
Model Driven Web Development Solutions
Model Driven Web Development SolutionsModel Driven Web Development Solutions
Model Driven Web Development SolutionsFederico Tomassetti
 

Mehr von Federico Tomassetti (12)

Jariko - A JVM interpreter for RPG written in kotlin
Jariko - A JVM interpreter for RPG written in kotlinJariko - A JVM interpreter for RPG written in kotlin
Jariko - A JVM interpreter for RPG written in kotlin
 
How do you create a programming language for the JVM?
How do you create a programming language for the JVM?How do you create a programming language for the JVM?
How do you create a programming language for the JVM?
 
Building languages with Kotlin
Building languages with KotlinBuilding languages with Kotlin
Building languages with Kotlin
 
Building languages with Kotlin
Building languages with KotlinBuilding languages with Kotlin
Building languages with Kotlin
 
Automatically Spotting Cross-language Relations
Automatically Spotting Cross-language RelationsAutomatically Spotting Cross-language Relations
Automatically Spotting Cross-language Relations
 
Lifting variability from C to mbeddr-C
Lifting variability from C to mbeddr-CLifting variability from C to mbeddr-C
Lifting variability from C to mbeddr-C
 
Maturity of Software Modelling and Model Driven Engineering: a Survey in the ...
Maturity of Software Modelling and Model Driven Engineering: a Survey in the ...Maturity of Software Modelling and Model Driven Engineering: a Survey in the ...
Maturity of Software Modelling and Model Driven Engineering: a Survey in the ...
 
Eclipse Florence Day: Modeling in the Italian Industry
Eclipse Florence Day: Modeling in the Italian IndustryEclipse Florence Day: Modeling in the Italian Industry
Eclipse Florence Day: Modeling in the Italian Industry
 
Estendere Java con il Meta Programming System di JetBrains
Estendere Java con il Meta Programming System di JetBrains Estendere Java con il Meta Programming System di JetBrains
Estendere Java con il Meta Programming System di JetBrains
 
What is Federico doing?
What is Federico doing?What is Federico doing?
What is Federico doing?
 
Xtext Un Framework Per La Creazione Di Dsl
Xtext   Un Framework Per La Creazione Di DslXtext   Un Framework Per La Creazione Di Dsl
Xtext Un Framework Per La Creazione Di Dsl
 
Model Driven Web Development Solutions
Model Driven Web Development SolutionsModel Driven Web Development Solutions
Model Driven Web Development Solutions
 

Kürzlich hochgeladen

CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....ShaimaaMohamedGalal
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 

Kürzlich hochgeladen (20)

CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 

JavaParser - A tool to generate, analyze and refactor Java code

  • 1. JavaParser A tool to generate, analyze, and refactor Java code Federico Tomassetti founder of
  • 2. Goal JavaParser is evolving in a suite of libraries to support: • Code generation • Code analysis • Code refactoring It has a growing user-base but we are not sure on which usages to focus: Can you help us figure out who could we serve better?
  • 3. What JavaParser does? JavaParser… parse Java code into a Java AST package foo.bar; class A { int field; } CompilationUnit PackageDecl ClassDecl FieldDecl PrimitiveType
  • 4. What JavaParser does? JavaParser unparse an AST into code package foo.bar; class A { int field; } CompilationUnit PackageDecl ClassDecl FieldDecl PrimitiveType
  • 5. Why do you need symbol resolving? int foo; public void aMethod(int foo) { foo = 1; } public void anotherMethod() { foo = 1; } To JP these two statements looks the same: they produce the same AST nodes. It is the assignment of a thing named ”foo”, no idea what that thing is
  • 6. public void print1(String foo) { System.out.print(foo); } public void print2(int foo) { System.out.print(foo); } To JP these two statements looks the same: they produce the same AST nodes. It is the call of a method named “print”, no idea which signature that has Why do you need symbol resolving?
  • 7. class A { } public void creator1() { new A(); } public void creator2() { class A { } new A(); } To JP these two statements looks the same: they produce the same AST nodes. It is the instantiation of a class named “A”, no idea where it is defined Why do you need symbol resolving?
  • 8. What JavaSymbolSolver does? JavaSymbolSolver resolves symbols in the JavaParser AST package foo.bar; class C { D field; } package foo.bar; class D { } CompilationUnit PackageDecl ClassDecl FieldDecl ReferenceType
  • 9. Relationship JP & JSS Certain methods in the AST requires additional intelligence. myCallExpression.calculateResolvedType(); myCallExpression.getName(); JSS not enabled JSS enabled JSS not enabled JSS enabled
  • 10. Configuring JavaSymbolSolver A typical usage: CombinedTypeSolver typeSolver = new CombinedTypeSolver( new ReflectionTypeSolver(), new JavaParserTypeSolver(new File("src/main/java")), new JavaParserTypeSolver(new File("src/test/java")), new JarTypeSolver("libs/guava.jar"), new JarTypeSolver("libs/log4j.jar"));
  • 11. Supporting code generation We want to support people who has to generate code: • Because they want to generate boilerplate code from some source (e.g., a database schema) • They want to build a transpiler targeting Java
  • 12. JavaParser to generate code CompilationUnit cu = new CompilationUnit(); cu.setPackageDeclaration("jpexample.model"); ClassOrInterfaceDeclaration book = cu.addClass("Book"); book.addField("String", "title"); book.addField("Person", "author");
  • 13. JavaParser to generate code book.addConstructor(Modifier.PUBLIC) .addParameter("String", "title") .addParameter("Person", "author") .setBody(new BlockStmt() .addStatement(new ExpressionStmt(new AssignExpr( new FieldAccessExpr( new ThisExpr(), "title"), new NameExpr("title"), AssignExpr.Operator.ASSIGN))) .addStatement(new ExpressionStmt(new AssignExpr( new FieldAccessExpr( new ThisExpr(), "author"), new NameExpr("author"), AssignExpr.Operator.ASSIGN))));
  • 14. JavaParser to generate code book.addMethod("getTitle", Modifier.PUBLIC).setBody( new BlockStmt().addStatement( new ReturnStmt(new NameExpr("title")))); book.addMethod("getAuthor", Modifier.PUBLIC).setBody( new BlockStmt().addStatement( new ReturnStmt(new NameExpr("author")))); System.out.println(cu.toString());
  • 15. JavaParser to generate code package jpexample.model; public class Book { String title; Person author; public Book(String title, Person author) { this.title = title; this.author = author; } public void getTitle() { return title; } public void getAuthor() { return author; } }
  • 16. Supporting code analysis We want to support people who have to analyse code: • Because they want some metrics on code • Because they want to ensure some quality standards are met • Because they want to write quick, one-off queries about their codebase
  • 17. JavaParser to run queries Question: How many methods take more than 3 parameters? long n = getNodes(allCus, MethodDeclaration.class) .stream() .filter(m -> m.getParameters().size() > 3) .count(); System.out.println("N of methods with >3 params: " + n); Answer: 11
  • 18. JavaParser to run queries Question: What are the three top classes with most methods? Answer: CoreMatchers: 35 methods BaseDescription: 13 methods IsEqual: 9 methods getNodes(allCus, ClassOrInterfaceDeclaration.class) .stream() .filter(c -> !c.isInterface()) .sorted(Comparator.comparingInt(o -> -1 * o.getMethods().size())) .limit(3) .forEach(c -> System.out.println(c.getNameAsString() + ": " + c.getMethods().size() + " methods"));
  • 19. JavaParser to run queries Question: What is the class with most ancestors? Answer: org.hamcrest.core.StringContains: org.hamcrest.core.SubstringMatcher, org.hamcrest.TypeSafeMatcher, org.hamcrest.BaseMatcher, org.hamcrest.Matcher, org.hamcrest.SelfDescribing, java.lang.Object ResolvedReferenceTypeDeclaration c = getNodes(allCus, ClassOrInterfaceDeclaration.class) .stream() .filter(c -> !c.isInterface()) .map(c -> c.resolve()) .sorted(Comparator.comparingInt(o -> -1 * o.getAllAncestors().size())) .findFirst().get(); List<String> ancestorNames = c.getAllAncestors() .stream() .map(a -> a.getQualifiedName()) .collect(Collectors.toList()); System.out.println(c.getQualifiedName() + ": " + String.join(", ", ancestorNames)); JSS at work here
  • 20. Supporting code refactoring We want to support people who has to refactor code: • Because they have to modernize legacy code • Because they want to update some dependencies and the API of the libraries used changed • Because they want to change some usage patterns
  • 21. JavaParser for automated refactoring getNodes(allCus, MethodCallExpr.class) .stream() .filter(m -> m.resolveInvokedMethod() .getQualifiedSignature() .equals("foo.MyClass.oldMethod(java.lang.String, int)")) .forEach(m -> m.replace(replaceCallsToOldMethod(m))); A new version of a library comes up and a deprecated method named oldMethod is replaced by newMethod. The new method takes 3 parameters: the first one as oldMethod but inverted and the third one is a boolean, which we want to be always true
  • 22. JavaParser for automated refactoring public MethodCallExpr replaceCallsToOldMethod( MethodCallExpr methodCall) { MethodCallExpr newMethodCall = new MethodCallExpr( methodCall.getScope().get(), "newMethod"); newMethodCall.addArgument(methodCall.getArgument(1)); newMethodCall.addArgument(methodCall.getArgument(0)); newMethodCall.addArgument(new BooleanLiteralExpr(true)); return newMethodCall; }
  • 24. Comments attribution void foo() { // comment1 int a = 1 + 2; // comment2 } // comment1 int a = 1 + 2; CompilationUnit cu = JavaParser.parse(code); ExpressionStmt expressionStmt = cu.findFirst(ExpressionStmt.class).get() ; System.out.println("Comment on the expression statement: " + expressionStmt.getComment().get().getContent());
  • 25. Lexical preservation Pretty printing is good for new code but for existing code users want lexical preservation. It is tricky because you need to know how to modify code preserving the style and making the code correct. Original code Change Final code int a, b, c; remove b, adapt commas int a, c; void foo() { int a; } add new statement, indent it as statement a previous line void foo() { int a; a = 0; }
  • 26. Things we are considering
  • 27. JavaParser to identify patterns We are working on the Matcher library to reduce the complexity, it is in the early stages This gives you a list of pairs name-type for all the properties in your bean.
  • 28. Java templates We are discussing the idea of Java templates. We would like to have Java code with placeholders for variable parts and be able to validate those templates. class A extends ${BASE_CLASS:Id} { private ${FIELD_TYPE:Type} myField; } class A extends ${BASE_CLASS:Id} { ${E:Expression} myField; } OK KO
  • 29. Making Java extensible Researchers (but also a certain company…) would be interested in writing extensions for Java based on JavaParser. How can you add a new statement or expression to Java today? You have to fork the parser. We have one user who forked JavaParser just to change the grammar file. We are looking for a better way. Any suggestions?
  • 30. JavaParser: Visited Book on JavaParser and JavaSymbolSolver, from the core committers. Avalaible for 0+ $ Currently 1.000+ readers https://leanpub.com/javaparservisited Federico Tomassetti See you on GitHub at javaparser/javaparser