Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
jean pierre Lerbscher
@jlerbsc
Hi @marcosvasousa What you have represented in your example is an internal stack trace of the class but i think you want to extend it to all the classes of a project. I don't have time to implement your algorithm but what I recommend at first glance is to use the plain capacity of the visitor pattern and use the second argument to propagate an execution context which keep track of current class declaration, method declaration, method call expression for each class and use graph to modelize each relationship... Personnally i use this technique to implement a java class/package/module relationship in 3D representation (example http://www.jperf.com/jp/). Unfortunately i can't help you more without spending a lot more time on it, but I think you need to look further into these solutions or even study others if this one does not allow you to achieve your objective.
makbro
@makbro
Good evening, everyone! If someone would be so kind as to help me setup javaparser into NetBeans I would appreciate it. I want Netbeans to playback some feedback sounds whenever the parser detects an error as the user types code. How would I go about to do that? If there is already a video or resource explaining how to do that let me know.
And if there is someone I can contact directly that can help me, please let me know.
Danny van Bruggen
@matozoid
@makbro I think you want to look into creating Netbeans plugins for that - Netbeans already parses the code and shows the errors, so there must be a parser and some handling in there that you might be able to plug into. This project, JavaParser, is not in use in Netbeans.
makbro
@makbro
@matozoid I will do that. Thank you!
Chinese News Board
@ralphcnb_twitter
@matozoid !!! How do I garbage collect an AST after I am done with it? I have nary a clue where to start looking for that. I load AST's by asking the class StaticJavaParser for a CompilationUnit cu, and then have a straightforward VoidVisitor retrieve several String's from the AST... Is there any simple way to clear the AST out of the Java Heap ("memory") after my build code moves on from one source file to the next source-file ? Would you like to help ?? (Specifically, I mean System.gc() doesn't get the AST's out of memory !!
Danny van Bruggen
@matozoid
@ralphcnb_twitter --> https://visualvm.github.io/ :+1:
Chinese News Board
@ralphcnb_twitter
I know about the Memory Analyzer (you brought it up, before)... Umm... Do you know how in C/C++ you have to say free(ptr) or dealloc(ptr) (I haven't done C/C++ in 20 years)... But in Java as long as you say objReference = null you are guaranteed that the Object objReference (whatever it was) will be cleared from the Heap by an invokation of System.gc()(because there are no references to it) ... How in the world can I make sure the AST pointers that are being retained by ether LexicalPreservingPrinter or StaticJavaParser are set to null, so that System.gc() will clean the heap out after my code is through with an AST? I've got to clean that out in my build process - when the build moves from one source-file AST and one to the next source-file AST
Danny van Bruggen
@matozoid
Hey @ralphcnb_twitter, I'm not active on this project anymore. It looks like the problem (if any, GC is something that is best left to do its thing most of the time) is in your code, and I don't have time to look at that. The few times the GC was failing to do its job was always because a reference to the object to collect was accidentally still in a map or list somewhere.
If you are not running out of memory, there should be no reason to worry. If you depend on finalize() or so, then stop doing so.
Chinese News Board
@ralphcnb_twitter

You quit Java Parser ... for real? Haven't you been doing this for years and years? I mean, I almost bought your book, but I'm trying not to get into the internals of the JP Code - I used it, and it (Java Parser) worked great. It gets used on hundreds of source-files every time I do a build... I just don't want to memorize the whole JP GitHub Build - I want to concentrate on my build instead... Does that make sense? (Use the API, rather than becoming a JP Developer) I know I mentioned that the JP Jar I use is javaparser-core-3.14.159265359.jar and I literally got it from http://jar-downloader.com

Yeah, you said the right thing, and I have tried to explain that I extract (a bunch / a lot) of java.lang.String using a VoidVisitor -- but after the Visitor completes there is a bunch of stuff in memory, and I'm not keeping any references to the JavaParser classes at all - only java.lang.String ... But OK... If you have quit this project, that's fine... It's been real.... Take care...

Matthew Kramer
@matthewthekramer
Hey all, sorry if this is a silly question, but I've recently been investigating if javaparser would be a good substitute for a dependency in a project I'm working on. I would like to traverse an AST and save context to certain nodes (i.e. saving names of variables in the same scope to a statement node) for later visitor operations. Currently, the only way I see this would be possible is creating subclasses for some nodes, and replacing the nodes with the subclass during a visit. However, this seems a bit messy to me as you would then have to cast the node later to see its context. Is there a better way of doing this? Am I missing something obvious? I've looked a bit around the javadocs and read the book but it doesn't seem obvious to me. Thanks
Danny van Bruggen
@matozoid
Hi @matthewthekramer - you can annotate the nodes with any kind of information you like using the setData/getData methods.
Lucas Gontijo
@gontijolucas
Hi.
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.
Danny van Bruggen
@matozoid
@SmiddyPence is/was the book guy.
Luca Molteni
@lucamolteni
Hi guys, I haven't been checking this channel for a while
so @matozoid aren't you on the project anymore? woah that's big news
I hope there's still someone then :D
Little trivia: what is the difference between the twos? (without looking at the source code
     StringLiteralExpr a = new StringLiteralExpr("String with \"");
     StringLiteralExpr b = new StringLiteralExpr().setString("String with \"");
Cameron Braid
@cameronbraid
I have a method call chain like the following, a.b().c() and I want to insert an extra method call in the chain to make it like a.b().d().c(). How do I do that ? I tried using new MethodCallExpr making d's scope be b and c's scope be d but when printing I get
Exception in thread "main" java.util.NoSuchElementException: No value present
        at java.base/java.util.Optional.get(Optional.java:148)
        at com.github.javaparser.printer.lexicalpreservation.PhantomNodeLogic.isPhantomNode(PhantomNodeLogic.java:58)
        at com.github.javaparser.printer.lexicalpreservation.LexicalPreservingPrinter.findNodeForToken(LexicalPreservingPrinter.java:364)
        at com.github.javaparser.printer.lexicalpreservation.LexicalPreservingPrinter.findNodeForToken(LexicalPreservingPrinter.java:375)
        at com.github.javaparser.printer.lexicalpreservation.LexicalPreservingPrinter.findNodeForToken(LexicalPreservingPrinter.java:375)
My actualy code is :
          MethodCallExpr nameMethod = cu.findAll(MethodCallExpr.class)
          .stream()
          .filter(mc->
            mc.getNameAsString().equals("name") &&
            mc.getArguments().size() == 1 &&
            mc.getArgument(0).isLiteralStringValueExpr() && 
            mc.getArgument(0).asLiteralStringValueExpr().getValue().equals(propertyName)
          ).findFirst().get();
          MethodCallExpr wireClassMethod = nameMethod.findAncestor(MethodCallExpr.class, a->a.getNameAsString().equals("wireClass")).get();
          MethodCallExpr wireTypeRef = new MethodCallExpr(wireClassMethod.getScope().get(), "wireTypeReference", NodeList.nodeList(new StringLiteralExpr("test")));
          wireClassMethod.setScope(wireTypeRef);
It works when using PrettyPrinter but that really messes up my code so I need to preserve the lexical structure
Cameron Braid
@cameronbraid
Found it.. need to run LexicalPreservingPrinter.setup(cu) BEFORE doing mutations on the compilation unit
jean pierre Lerbscher
@jlerbsc
Hi @cameronbraid we can't help you with so little information. The least thing would be to provide a minimalist test case.
Danny van Bruggen
@matozoid
@gontijolucas - no response from @SmiddyPence, so I say go ahead! I'm not aware of translations. @ftomassetti is author #3 but I doubt he will protest.
@lucamolteni - I'm in the background, supporting the new team :-) --> @maartenc @jlerbsc @MysterAitch <--
@lucamolteni I bet the answer to your riddle is something about how helpful JavaParser is trying to be with literals, and how it is failing to be consistent :-)
Danny van Bruggen
@matozoid
@maartenc @jlerbsc @mysteraitch, @lucamolteni works on RedHat's Drools (https://www.drools.org/) which was prototyped with JavaParser, and if I'm not mistaken it is still based on it. Pretty cool if you ask me.
Federico Tomassetti
@ftomassetti
I confirm I will not protest 🙂
Damn the issue was commented 7 years ago. I feel oooold
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/