Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
Matthew Kramer
@matthewthekramer
@matozoid Got it, thanks for the response!
Ghost
@ghost~5f9bcab3d73408ce4ff2dae6
Hello, I have been playing with JavaParser serialization and DotPrinter (which are very cool tools). The JSON and Dot outputs are different in terms of child order. For example, JSON prints the children of BinaryExpr as (left, operator, right) while DotPrinter print (operator, left, right). I was wondering if there is a grammar that I can follow to make these consistent with each other? Thank you.
Chinese News Board
@ralphcnb_twitter
@ftomassetti ... Do you know anything about it? Do you know what I could 'null' so that an AST is cleared from memory (Java Heap) after I'm done with a CompilationUnit generated by StaticJavaParser ???
As I explained, I parse around 330 '.java' source-code files with JP - to extract source-code for code-hiliting in a JavaDoc HTML Extention Tool - it works fine - but memory heap grows and grows. @ftomassetti ...
jean pierre Lerbscher
@jlerbsc
@ralphcnb_twitter perhaps you can do a PhantomNodeLogic.cleanUpCache() to limit memory footprint.
Chinese News Board
@ralphcnb_twitter

Hey, thanks, just got back. I will try that. All I know is that after using an AST to retrieve stuff (String's), if I try to do something like ...

.forEach((Node nChild) -> 
            { try { nChild.removeForced(); ...

It starts throwing exceptions. It seems like this could be a trivial operation I'm trying to do, but I cannot figure it out. Thanks for the advice, will try later today. For System.gc() to actually do its magic, the references have to be null...

Chinese News Board
@ralphcnb_twitter

I read through it, and it looked like the light at the end of the tunnel for me! I wasn't aware that there was a cache in LexicalPreservingPrinter ... I get this exception:

Torello/HTML/Tools/JavaDoc/JavaSourceCodeFile.java:30: error: 
PhantomNodeLogic is not public in com.github.javaparser.printer.lexicalpreservation; cannot be accessed from outside package
import com.github.javaparser.printer.lexicalpreservation.PhantomNodeLogic;
                                                        ^
Torello/HTML/Tools/JavaDoc/JavaSourceCodeFile.java:449: error: 
PhantomNodeLogic is not public in com.github.javaparser.printer.lexicalpreservation; cannot be accessed from outside package
            PhantomNodeLogic.cleanUpCache();
            ^
2 errors

Is there any chance I'm using an "older" jar file? If that's the source of what "feels like" a memory-leak, is there a newer JP JAR File that I would need? I have been using (for almost a year now)
javaparser-core-3.14.159265359.jar This looks very promising...

Chinese News Board
@ralphcnb_twitter
According to this Java-Parser JavaDoc Site https://www.javadoc.io/doc/com.github.javaparser/javaparser-core/latest/index.html
It says that both PhantomNodeLogic is a public class, and that cleanUpCache() is a public static method, so I couldn't really be able to say why my JDK is reporting that it isn't public so... If anyone knows the answer... I don't have a GitHub account, and haven't ever built JP before, would I have to do that or something?
jean pierre Lerbscher
@jlerbsc
@ralphcnb_twitter you are using an old JP version. Try the lastest version 3.16.2.
Chinese News Board
@ralphcnb_twitter

Thanks!!! It worked... BTW, I wrote my own build tool for my library - it's not Maven or Gradle (It's this very large Java Package), so I just kept using the JP Jar I got off the Internet... It has always worked though... I got 3.16.2 (It's 6:50 AM right now, here in Dallas)...

**************************************************************************
Free Memory Available:             242,205,208
Total Memory Available:            255,524,864
Loading File:                      javadoc/Torello/Languages/Verbs.WebFiles.html
Fully-Qualified Name:              Torello.Languages.Verbs.WebFiles
Built from Source-File:            Torello/Languages/Verbs.java
Relative-URL String:               ../../
Parsed JavaDoc '.html':            Name [Verbs.WebFiles], Package [Torello.Languages], CIET [class]
Parsed Source '.java':             Name [Verbs.WebFiles], Package [Torello.Languages], CIET [class]
'.html' File Parser Found:         [000] Fields, [000] Constructors, [004] Methods
'.java' File, JavaParser Found:    [000] Fields, [001] Constructors, [004] Methods
**************************************************************************

The garbage collector seems to have got it all... Thanks Mr. Lerbscher ... I know you mentioned LexicalPreservingPrinter being the source of it, but I didn't quite get it...

This is what it used to look like.... At the end of the build...
Free Memory Available:             315,115,776
Total Memory Available:            709,603,328
It would get slower and slower
Chinese News Board
@ralphcnb_twitter
HEY!!! I took the train to Fort Worth (Texas) this morning. It's Halloween... I brought my laptop. I'm at Starbucks. Happy Halloween. Great stress relief after all the "Brain control" and staring at how to fix my Java Parser segment of my program! It worked! Fort Worth Water Gardens
Danny van Bruggen
@matozoid
Good to hear, nice pic!
Ashley
@ascopes

Hi!

I am trying to write a piece of code that removes useless empty if-else statements from code. For example...

foo();
if (true) { } else { }
bar();

but I seem to be running into an issue which I am not sure if it is just me missing something, or whether it is a bug.

My code is as follows:

class EmptyIfVisitor : VoidVisitorAdapter<Unit>() {
    override fun visit(ifStmt: IfStmt, arg: Unit?) {
        super.visit(ifStmt, arg)
        val condition = simplifyExpr(ifStmt.condition)
        val thenStmt = ifStmt.thenStmt
        val elseStmt = ifStmt.elseStmt.orElse(null)

        if (condition is BooleanLiteralExpr) {
            if (isEmptyStatement(thenStmt) && isEmptyStatement(elseStmt)) {
                // We can happily remove this block, as it is doing absolutely nothing useful whatsoever.
                logger.warn { "removing useless ${debugString(ifStmt, verbose = true)}" }
                ifStmt.remove()
            }
        }   
    }
}

however, the ifStmt.remove() is currently throwing a ConcurrentModificationException whenever it is hit, assumably because it is modifying the internal NodeList on the parent while iterating over it.

Is there some way to do what I want to do? The only other solution is to do ifStmt.replace(EmptyStmt()) but that really feels like a bodge to me.

Ashley
@ascopes
stack trace is
java.util.ConcurrentModificationException
    at java.util.ArrayList.forEach(ArrayList.java:1262)
    at com.github.javaparser.ast.NodeList.forEach(NodeList.java:290)
    at com.github.javaparser.ast.visitor.VoidVisitorAdapter.visit(VoidVisitorAdapter.java:109)
    at com.github.javaparser.ast.stmt.BlockStmt.accept(BlockStmt.java:76)
    at com.github.javaparser.ast.visitor.VoidVisitorAdapter.lambda$visit$104(VoidVisitorAdapter.java:369)
    at java.util.Optional.ifPresent(Optional.java:159)
    at com.github.javaparser.ast.visitor.VoidVisitorAdapter.visit(VoidVisitorAdapter.java:369)
    at com.github.javaparser.ast.body.MethodDeclaration.accept(MethodDeclaration.java:106)
    at com.github.javaparser.ast.visitor.VoidVisitorAdapter.lambda$visit$31(VoidVisitorAdapter.java:154)
    at java.util.ArrayList.forEach(ArrayList.java:1259)
    at com.github.javaparser.ast.NodeList.forEach(NodeList.java:290)
    at com.github.javaparser.ast.visitor.VoidVisitorAdapter.visit(VoidVisitorAdapter.java:154)
    at com.github.javaparser.ast.body.ClassOrInterfaceDeclaration.accept(ClassOrInterfaceDeclaration.java:100)
    at com.github.javaparser.ast.visitor.VoidVisitorAdapter.lambda$visit$43(VoidVisitorAdapter.java:175)
    at java.util.ArrayList.forEach(ArrayList.java:1259)
    at com.github.javaparser.ast.NodeList.forEach(NodeList.java:290)
    at com.github.javaparser.ast.visitor.VoidVisitorAdapter.visit(VoidVisitorAdapter.java:175)
    at com.github.javaparser.ast.CompilationUnit.accept(CompilationUnit.java:134)
    at <my unit test that calls CompilationUnit#accept(EmptyIfVisitor(), null)>
    at <other junit stuff>
jean pierre Lerbscher
@jlerbsc
hi @ascopes because you modify the AST you can use a ModifierVisitor like this
ModifierVisitor v = new ModifierVisitor<Void>() {
        @Override
        public Visitable visit(IfStmt ifs, Void arg) {
            return null;   
        }
    };
    v.visit(cu, null);
Ashley
@ascopes
ah awesome, thanks
Danny van Bruggen
@matozoid
Also the functional traversal style has protection built in against that: https://javaparser.org/functional-tree-traversal/
Amartya Vats
@amartya2969
Hi!
I am trying to write a piece of code through which I can print all the methods that have been called in a constructor. For a non contructor method it is easy to do with MethodCallExpr, how to do the same for a constructor?
and check the class it extends from.
Discotek.ca
@discotekdotca_twitter
Hello, I have been testing JavaParser against the JDK's own code and have some issues. What is the best way for me to report them?
Discotek.ca
@discotekdotca_twitter
Sorry - forget it. I found the info I needed.
Danny van Bruggen
@matozoid
Well, that's quick :-)
I'm curious what that info was though (setting the language level maybe?)
Cheikh Saadbouh
@cheikh-sadbouh

hello everyone i am new to javaParser and i need some help .

i want :

  • delete some method parameters
  • replace statement A with statement B
class MethodChangerVisitor extends VoidVisitorAdapter<Void> {
      @Override
    public   void visit(MethodDeclaration n, Void arg) {

          System.out.println(n.getParameters().get(0).getType());
          System.out.println(n.getParameters().get(0).getName());
          System.out.println(n.getParameters().remove(0));//remove parameter not working
          //replace statement with other statement ?
          System.out.println(n.getBody().get().getStatements().get(0).asExpressionStmt().setExpression("int a = 5;"));

        super.visit(n, arg);
    }
jean pierre Lerbscher
@jlerbsc
Hi @cheikh-sadbouh why do you say "n.getParameters().remove(0)" doesn't work? Do you have an exception?
12 replies
ovesh
@ovesh

Hello!

I have a question about chained method calls.
Given a chained invocation (builder pattern):

return new ThingBuilder().withA(a).withB(b).build();

How can I use JavaParser to add another chained invocation to end up with code like this:

return new ThingBuilder().withA(a).withB(b).withC(c).build();

Inserting it anywhere in the chain (before build()) is fine.

15 replies
mdproctor
@mdproctor
does anyone know of a Language Server Protocol impl, that can be driven from a JavaCC grammar?
3 replies
Yevgen Muntyan
@muntyan

Good morning. I am using LexicalPreservingPrinter to do some code modifications, and it works well, but I can't figure out how to insert whitespace where I need it. My goal is to replace code like

    function(new RuntimeException("abc"),
        anArgument,
        anotherArgument);

with

    new RuntimeException("abc",
        anArgument,
        anotherArgument);

But I can't get the newlines in the replacement, I can only get

    new RuntimeException("abc", anArgument, anotherArgument);

Is it possible to do what I want?

12 replies
Roger Howell
@MysterAitch
v3.17.0 released -- it'll be available as soon as bintray/sonatype/maven central do their thing!
Big shout out to @jlerbsc for another bumper release of bug fixes! 🥳🥳
Nicholas Smith
@SmiddyPence

I would like to translate the book "JavaParser: Visited" into Brazilian Portuguese, has anyone translated this book? do you know if it is allowed? who would i have to talk to? thank you.

Sure, no problem.

Devan-Kerman
@Devan-Kerman

hey, given a FieldDeclaration, how would I replace the initiailizer, so for example

public class Foo {
       public int a = Something.compute(3, 5);
}

to

public class Foo {
       public int a = Impl.init();
}

I have the FieldDeclaration instance already

Roger Howell
@MysterAitch
Iirc the field declaration has a list of variable initialisations -- that's where you can access the right hand side of the assignment operators
(it's a list because you can have int x, b, abc;)
Devan-Kerman
@Devan-Kerman
yea I think I got it
for (VariableDeclarator variable : n.getVariables()) {
variable.setInitializer("Impl.init()");
}
very nice api, thank you
Roger Howell
@MysterAitch
Brill! Glad you've got it! :)
For reference, in case you've not seen it, this article might be helpful :) https://javaparser.org/inspecting-an-ast/
MarcosCosmos
@MarcosCosmos
Hey has anyone got a generic method/solution for getting the position/range in the source for attributes, or at the least, their tokens?
48 replies
mdproctor
@mdproctor
We are back to developing our java language extensions. One problem we have, is backwards compatibility - we want to make this optional. In short how we handle newlines, we would like to make configurable on a property. Does JavaCC have anything to enable that?
23 replies
Roger Howell
@MysterAitch
Could I ask for some sets of eyes on #2886 please? Specifically, will these changes in Java need to be acted upon in javaparser? It's not a language change, but I don't understand nests and some of the other things it talks about... equally, it could end up being something that is handled transparently for us by javassist...

Assuming that hidden classes (#2886) don't affect anything (I don't think it does, but I don't entirely understand the JEP), we can then formally tick javaparser off as supporting java 15... which would be rather nice! :D

After that, it's just records to go for java 16 support :)

Danny van Bruggen
@matozoid
Looks like some way to support people who want to write code that generates classes at runtime, so it is user code, running on the JVM, that is generating byte code to run on the same JVM, which can then be used only with reflection. Symbol solving is all about static, compile-time analysis, so this JEP would only be of interest if JP also had a JVM implementation :-)
Don't forget about javaparser/javaparser#2512 which has half the record syntax already! Feel free to take over from me.
The private project I'm working on has a dependency on JP since a few days ago, so I now have a stake in the project again :-#