Giter VIP home page Giter VIP logo

javaparser's Introduction

JavaParser

Maven Central Build Status Coverage Status Join the chat at https://gitter.im/javaparser/javaparser License LGPL-3/Apache-2.0 DOI

This project contains a set of libraries implementing a Java 1.0 - Java 18 Parser with advanced analysis functionalities.

Our main site is at JavaParser.org

Sponsors

Support this project by becoming a sponsor! Become a sponsor. Your donation will help the project live and grow successfully.

Javaparser uses OpenCollective to gather money.

Thank you to our sponsors!

Setup

The project binaries are available in Maven Central.

We strongly advise users to adopt Maven, Gradle or another build system for their projects. If you are not familiar with them we suggest taking a look at the maven quickstart projects (javaparser-maven-sample, javasymbolsolver-maven-sample).

Just add the following to your maven configuration or tailor to your own dependency management system.

Please refer to the Migration Guide when upgrading from 2.5.1 to 3.0.0+

Maven:

<dependency>
    <groupId>com.github.javaparser</groupId>
    <artifactId>javaparser-symbol-solver-core</artifactId>
    <version>3.25.10</version>
</dependency>

Gradle:

implementation 'com.github.javaparser:javaparser-symbol-solver-core:3.25.10'

Since Version 3.5.10, the JavaParser project includes the JavaSymbolSolver. While JavaParser generates an Abstract Syntax Tree, JavaSymbolSolver analyzes that AST and is able to find the relation between an element and its declaration (e.g. for a variable name it could be a parameter of a method, providing information about its type, position in the AST, ect).

Using the dependency above will add both JavaParser and JavaSymbolSolver to your project. If you only need the core functionality of parsing Java source code in order to traverse and manipulate the generated AST, you can reduce your projects boilerplate by only including JavaParser to your project:

Maven:

<dependency>
    <groupId>com.github.javaparser</groupId>
    <artifactId>javaparser-core</artifactId>
    <version>3.25.10</version>
</dependency>

Gradle:

implementation 'com.github.javaparser:javaparser-core:3.25.10'

Since version 3.6.17 the AST can be serialized to JSON. There is a separate module for this:

Maven:

<dependency>
    <groupId>com.github.javaparser</groupId>
    <artifactId>javaparser-core-serialization</artifactId>
    <version>3.25.10</version>
</dependency>

Gradle:

implementation 'com.github.javaparser:javaparser-core-serialization:3.25.10'

How To Compile Sources

If you checked out the project's source code from GitHub, you can build the project with maven using:

./mvnw clean install

If you want to generate the packaged jar files from the source files, you run the following maven command:

./mvnw package

NOTE the jar files for the two modules can be found in:

  • javaparser/javaparser-core/target/javaparser-core-\<version\>.jar
  • javaparser-symbol-solver-core/target/javaparser-symbol-solver-core-\<version\>.jar

If you checkout the sources and want to view the project in an IDE, it is best to first generate some of the source files; otherwise you will get many compilation complaints in the IDE. (./mvnw clean install already does this for you.)

./mvnw javacc:javacc

If you modify the code of the AST nodes, specifically if you add or remove fields or node classes, the code generators will update a lot of code for you. The run_metamodel_generator.sh script will rebuild the metamodel, which is used by the code generators which are run by run_core_generators.sh Make sure that javaparser-core at least compiles before you run these.

Note: for Eclipse IDE follow the steps described in the wiki: https://github.com/javaparser/javaparser/wiki/Eclipse-Project-Setup-Guide

More information

JavaParser.org is the main information site or see the wiki page https://github.com/javaparser/javaparser/wiki.

License

JavaParser is available either under the terms of the LGPL License or the Apache License. You as the user are entitled to choose the terms under which adopt JavaParser.

For details about the LGPL License please refer to LICENSE.LGPL.

For details about the Apache License please refer to LICENSE.APACHE.

javaparser's People

Contributors

4evertheone avatar arouel avatar arturbosch avatar daanschipper avatar deepsnowneel avatar dependabot[bot] avatar edefazio avatar ftomassetti avatar hazendaz avatar itakeshi avatar jlerbsc avatar johannescoetzee avatar koppor avatar maartenc avatar malteskoruppa avatar mathiponds avatar matozoid avatar mernst avatar mlangkabel avatar mysteraitch avatar renovate-bot avatar renovate[bot] avatar ryan-beckett avatar sebastiankirsch avatar signed avatar simonbaars avatar smiddypence avatar thleu avatar wimtibackx avatar xdrop avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

javaparser's Issues

CommentsParser encoding problem

I was trying to parse java sources that was written by other encoding(Not UTF-8)
but unexpected error occured.

Because CommentsParser.parse() using fixed encoding value(UTF-8) like below.
and JavaParser is using this method.

public CommentsCollection parse(final String source) throws IOException, UnsupportedEncodingException {
        InputStream in = new ByteArrayInputStream(source.getBytes());
        return parse(in,"UTF-8");
}

Using javaparser for refactoring

To do that all the comments should be preserved (see #2 ), at least. Possibly also the layout should be kept as-is.

Any thoughts about that? I would like to take a look at that and I would appreciate suggestions, help, advices, etc.

Cleaning up

When running deadode4j version 2.0.0, I stumbled over these classes that probably should be removed:

  • japa.parser.Position
  • japa.parser.ast.TreeVisitor

They were both introduced in late 2013, but are no longer used.

Also, I'd suggest moving class japa.parser.ASTHelper to the test source, as it is only used in that context. Then one could remove lots of methods which are not used.

Now I'll happily create a patch for this, I just wanted to ask what the policy is regarding downgrade compatibility - as there could be some people out there using those classes. So you might want to deprecate those classes now and remove them with the 2.0.0 release. Please indicate what your intentions are.

Warnings in JavaDocs

There are 100+ warning during the JavaDoc generation. javadoc:jar goal

Things like a @param is documented, but no description is provided.

We can come back to that after the 2.0.0 release. I will just fix the errors #80 before that.

Lazy initialized lists should be used everywhere

We did that for comments in issue #3 but it applies everywhere.

I could do that in this way, if you agree:

    public List<Parameter> getParameters() {
        if (null == parameters) {
            parameters = new ArrayList<Parameter>();
        }
        return parameters;
    }

Thoughts?

Parsing Related Tests to JBehave

So I would estimate that the existing comment related tests made up about 50% of the test capital.

Does anyone else want to have a crack at these?

I'm happy to do it, but don't want to hog all the fun! Although I will be on holiday from next week so will take a little while to get around to.

Problem while retrieving field value using VariableDeclarator

I'm using VariableDeclarator for retrieving field's init value

List<VariableDeclarator> variables = fieldDeclaration.getVariables();
for (VariableDeclarator variableDeclarator : variables) {                   
    VariableDeclaratorId fieldName = variableDeclarator.getId();
    Expression fieldValue = variableDeclarator.getInit();
    ...

There is a problem.
See the code below. First Case is No problem.
But In second Case, "variableDeclarator.getInit()" returns "//field2 null"
In other word, "variableDeclarator.getInit()" returns value include line comment

//Case 1
private String field1 = null; //field1

//Case 2
private String field2 
                    = null; //field2

How Can I retrieve or parse only field value without comment?

new HashSet<> gives exception?

may line contains "<>" gives an exception ? Parsing can not be done. it gives;
japa.parser.ParseException: Encountered " "<" "< ""

1.0.9-SNAPSHOT is 2x slower than 1.0.8

I'm switching my project from 1.0.8 to the latest version (my project indexes Java sources with lucene). I found my indexer is 2x slower and consuming more memory.

I tried to run bisect. and found the bug was introduced in 6f070b8.

Since it is a huge commit (17K lines change), it will take me more time to investigate. Let me know if you have any clue.

com.github.javaparser.ast.body.Parameter.getType() can be null since 2.0.0

I assume a parameter's type being null only occurs for lambda expressions, thus why it didn't pop up until now.

This causes NullPointerExceptions at least for

  • com.github.javaparser.ast.visitor.GenericVisitorAdapter
  • com.github.javaparser.ast.visitor.ModifierVisitorAdapter
  • com.github.javaparser.ast.visitor.VoidVisitorAdapter

The other adapters seem to be unaffected, one of them was explicitly adapted to it. I'd appreciate a double-check of this.

Before introducing a mere if (parameter.getType() != null) everywhere, I wanted to discuss how this should be approached. Does it make sense to introduce a new class representing lambda parameters? Although lambda parameters can have a type too, it seems that it's the only instance a paramater can have no type. Or am I missing something?

Minor JavaDoc Comment

Line 233 of ASTHelperJavadoc comment for

    public static ReferenceType createReferenceType(PrimitiveType type, int arrayCount) {
...
    }
 *            number <b>os</b> arrays or 0 if is not a array.

==>
* number of arrays or 0 if is not a array.

Need exact position information of "xxx" in "class xxx { ... }"

I'm developing a program like grepcode.com (https://github.com/stepinto/polaris). It uses JavaParser. I need position information about class name in a TypeDeclaration i.e. "xxx" in "class xxx {...}". Currently the position of a TypeDeclaration is the whole class body.

I think we can use NameExpr instead of String for its name. For backward compatibility, we need to add another field "NameExpr nameExpr". I can prepare a patch if you think my idea is right.

MethodDeclaration has the same problem.

Javadoc is put below annotation then could not get comment!

I try to use javaparser to get the comment from this method but it's always null. It's will be ok if the comment first then annotations.

@GET
@Path("/original")
/**
 * Return the original user.
 */
public User getOriginalUser(String userName) {
    return userService.getOriginalUser(userName);
}

Annotation visitors does not seem to work

Here is my test class

public class Annot {
  @Test
  public void myTest() {
  }
}

Here is my annotation visitor

public class AnnotationPrinter {

    public static void main(String[] args) throws Exception {
        System.err.println("Parsing " + args[0]);
        FileInputStream in = new FileInputStream(args[0]);
        CompilationUnit cu;
        try {
            cu = JavaParser.parse(in);
        } finally {
            in.close();
        }
        new AnnotationVisitor().visit(cu, null);
    }
    private static class AnnotationVisitor extends VoidVisitorAdapter {
        @Override
        public void visit(AnnotationDeclaration n, Object arg) {
            System.out.println("Annotations:");
            System.out.println(n);
            System.out.println(arg);
            System.out.println(n.getName());
        }
    }
}

Expectation: The annotation Test should have been picked up by the annotation visitor.

Maven repository

Hello,

Is there the library (the current version 1.0.9) deployed on any maven repository?
If not, is there any schedule about it?

Thanks.

Regards
Chema.

Bug while parsing comments

Here is example code

public class ClassWithBlockComments {

    /* comment to a method */
    void foo(){};

    /*// comment put randomly in class: <==This is a Problem

    another orphan.
    It spans over more lines */

}

Of course it's not normal coding style.
But Unfortunately this kind of source exist.

Here is where the problem occurred.(CommentParser:line 82)
In that case, the value of "currentContent" is empty.
So "currentContent.toString().length()-1" make StringIndexOutOfBoundException

case IN_BLOCK_COMMENT:
    if (prevChar=='*' && c=='/'){
        // delete last character
        String content = currentContent.deleteCharAt(currentContent.toString().length()-1).toString();
        ...

Comparing a not-Node object with a Node causes an Exception

See Node.java, line 225:

@Override public boolean equals(final Object obj) {
    return EqualsVisitor.equals(this, (Node) obj);
}

This is a violation of the expected behavior of Equals, going to fix it and write a test for it.

Example of code causing the exception:

        Node n = new CompilationUnit();
        assertFalse(n.equals("anObjectWhichIsNotANode, it is a String"));

Generating Javadoc documentation

We could generate the Javadoc documentation and provide it as github pages.

I think it is technically possible but it would require maven skills far superior to mine. Volunteers are really welcome :D

Bug while parsing annotations with String literals containing ':'

I was trying to parse the following class:

public class Test {
    public static @interface SomeAnnotation {
        String value();
    }

    // Parser bug: the type of this field
    @SomeAnnotation("http://someURL.org/")
    protected Test test;
}

getType() on the FieldDeclaration of test returns a ReferenceType with:

//someURL.org/")
Test

It looks like the parser is treating the ':' character as some kind of separator, regardless of being inside a String literal...

(Tested on the latest version 1.0.12-SNAPSHOT as of this writing)

Allow to keep comments in memory

In commit a27c8a8 ASTParser has been changed to don't store comments in memory.

In some cases, as our case (Parse Compilation units, make some changes after a process and replace the original file) this can cause to loose comments (that was one main problem in original library version).

We need some way to configure this behaviour.

Thanks in advance.

Calculating code coverage

Given we are getting better tests, it could be nice to calculate also code coverage.
I am not familiar with anything for Java.
Do you know something we could use?

Maven Modules

I propose splitting the project into three modules:

core - Main module with all the libraries code
grammar - Contains grammar and generated sources
acceptance-tests - All the JBehave bases testing

Rational - Not plainly obvious what code is generated and that you have to run javacc:javacc initially from the command line. The IDE can get pissy while referencing src files from the target directory.

Any other suggestions logical divisions, names there of...

Setup continuos integration

Maybe we could have continuos integration using travis, to ensure all tests keep passing.

I can take care of that if it is ok for you.

Casting a lambda expression causes a parsing failure

I failed to parse some Java 8 files with lambda expressions; my stack trace was something like this

java.lang.NullPointerException
    at com.github.javaparser.ast.Node.setAsParentNodeOf(Node.java:331)
    at com.github.javaparser.ast.expr.MethodCallExpr.setArgs(MethodCallExpr.java:96)
    at com.github.javaparser.ast.expr.MethodCallExpr.<init>(MethodCallExpr.java:63)
    at com.github.javaparser.ASTParser.PrimarySuffixWithoutSuper(ASTParser.java:3180)

Obviously, the provided arguments was a list containing a null value. I boiled it down to a simple statement that cannot be parsed:

Stream<CharSequence> stream = Stream.generate((Supplier<CharSequence>) () -> "Fail");

Removing the cast makes the problem go away.

As this is certainly to be fixed within the java_1_8.jj file, I won't come up with a fix (this stuff is just beyond me). I can however set up a branch with a test case or something.

Tidying up tests

This issue came up from a comment in #50.
I copy the description from there.

The two files "TestCommentsParser" and "TestCommentsParsing" seem just to be two buckets with slightly different names.

Some tests use Hamcrest matchers other don't.

What I assume is legacy test code, that uses main rather than JUnit.

1.0.11 Release

It would be good to get the additional comment support into a release version on maven central.

A chap called before seems to have done this previously. Anyone else offer advice on how to do this?

Errors in JavaDocs

Nothing like documentation, especially when it is wrong!

Need to tidy up several items that come out of the javadoc:jar goal. Documenting exceptions that aren't thrown etc.

Could execute with <maven.javadoc.failOnError>false</maven.javadoc.failOnError>, but wrong is wrong at the end of the day.

I'll sort today,

Unable to build?

Hi guys,
I'm wondering if there are build instructions? Currently I've cloned the repo and imported it to eclipse but there are a few errors and the structure is strange. Are there special steps that need to be taken?

--Chris

Improve sorting algorithms

A rather horrible sort was found here: #75

Fix it by using built in JDK sorting algorithms, and search around for more of these bubble sorts.

Document the build process

We should write a few lines on how to build the project and how to include it as a dependency.

We should either doing that in the README.md or add a reference there.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.