Can not resolve JavaParser - antlr

JavaParser.CallContext and JavaParser.FunctionDeclContext do not seem to be able to resolve. This is modeled after page 139 in the definitive antlr reference.
Am I missing a Lib?
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.misc.MultiMap;
import org.antlr.v4.runtime.misc.OrderedHashSet;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.tree.*;
import org.stringtemplate.v4.ST;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Set;
static class FunctionListener extends JavaBaseListener {
Graph graph = new Graph();
String currentFunctionName = null;
public void enterFunctionDecl(JavaParser.FunctionDeclContext ctx) {
currentFunctionName = ctx.ID().getText();
graph.nodes.add(currentFunctionName);
}
public void exitCall(JavaParser.CallContext ctx) {
String funcName = ctx.ID().getText();
// map current function to the callee
graph.edge(currentFunctionName, funcName);
}
}

I think I have seen this one, and I dont have enough points to "comment", but let me ask a question first; It looks like you are trying to produce an external version of the AST on page 137, You took the examples and renamed them to the grammar you had generated already. I'm going to assume that the rest of it is working or you would have had a lot more errors than this one ! Is that the goal ? Are you after just the calling methods/classes or are you after the full homogeneous AST ?
This depends on the grammar entry points. That's not as obvious in the book as it seems. You referenced functionDecl, which looks to be an entry in the Cymbol.g4, but doesn't exist in Java.g4 So rather than JavaParser.FunctionDeclContext I suggest JavaParser.classOrInterfaceDeclarationContext. It should should pull up the right method. I will also confess that I don't know what the exitCall would map to. I could use the illumination on that myself.
Were you after the whole AST or only the call graph ? If the whole AST, I think you can use enterEveryRule or ExitEveryRule for that as well, but confirmation would be good.
So start by regenerating your grammar, change your program to reference the rule entry point in the .g4 files, then see if it all works.
Thanks

Related

Selenium (Java): the method dndScript() is undefined

I'm trying to verify that a former colleague's old demo Selenium script still works, but have run into a curious error. The colleague is no longer around to consult, unfortunately. First, here's the script in question, which is supposed to drag and drop one element over another on a page:
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Supplier;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
public class DragNDrop {
#Test
public void testDragAndDropWithCheck() throws InterruptedException {
System.setProperty("webdriver.gecko.driver","D:\\WebDriver\\geckodriver.exe");
WebDriver driver=new FirefoxDriver();
driver.get("https://the-internet.herokuapp.com/drag_and_drop");
By css = By.cssSelector("div[id^=\"column-\"]");
WebDriverWait wait = new WebDriverWait(driver, 10);
Supplier<List<WebElement>> fetchComponents = () -> wait
.until(ExpectedConditions.presenceOfAllElementsLocatedBy(css));
/**
* Starting check for element position
*/
List<WebElement> startingCheck = fetchComponents.get();
Assert.assertEquals("Starting - Draggable number does not match!", 2, startingCheck.size());
Assert.assertEquals("Starting - A position does not match!", "A", startingCheck.get(0).getText());
Assert.assertEquals("Starting - B position does not match!", "B", startingCheck.get(1).getText());
int index = ThreadLocalRandom.current().nextInt(startingCheck.size());
WebElement from = startingCheck.get(index);
WebElement to = startingCheck.get(1 - index);
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript(
dndScript() + "simulateDragAndDrop(arguments[0], arguments[1])",
from,
to);
/**
* Ending check for element position
*/
List<WebElement> endingCheck = fetchComponents.get();
Assert.assertEquals("Ending - Draggable number does not match!", 2, endingCheck.size());
Assert.assertEquals("Ending - A position does not match!", "A", endingCheck.get(1).getText());
Assert.assertEquals("Ending - B position does not match!", "B", endingCheck.get(0).getText());
}
}
The problem is with this part:
jse.executeScript(
dndScript() + "simulateDragAndDrop(arguments[0], arguments[1])",
from,
to);
Eclipse highlighted dndScript() and threw the message:
The method dndScript() is undefined for the type DragNDrop
I first figured this was due to a missing import, so I got to googling, but I can't find any information on it. The most I could find was some references to something called "RichFaces", but I couldn't find any further clarification (may be my own fault -- I'm by no means a Selenium/Java expert).
Any idea on what the story is with this function and how to properly implement it in this script?
It is unlikely related to the missing import (probably the static one). Since this is just a method name there could be three cases:
This is a static method in scope of some different classand used to be imported with static import
This is the method that has to be implemented in the scope of your current class
This is the method that has to be implemented in scope of parent classes
The reason of you currently have is that the code of your current class changed since that time. You need to check revision history if you take this code from version control.
There are few possible stories which seem possible:
There was a method in scope of current class and then it was moved so some parent class. In some reason someone forgot to add extends keyword to current class.
There was a method in scope of parent class. After that someone decided to break relationship between the classes and forgot to move that method to your current class.
There was static method in some different class. It was imported to the current class as static import. Then someone loaded that class to IDE and didn't add that "different class" to project's class path. Then they applied "organize imports" feature which removed that broken import from your current class.

Having trouble with Random ore generation for minecraft 1.15.2

So I am trying to make a minecraft mod that has a randomly generated ore. I have run into a problem in this part of the code.
import net.minecraft.world.biome.Biome;
import net.minecraft.world.biome.Biomes;
import net.minecraft.world.gen.GenerationStage;
import net.minecraft.world.gen.feature.Feature;
import net.minecraft.world.gen.feature.OreFeatureConfig;
import net.minecraft.world.gen.placement.ConfiguredPlacement;
import net.minecraft.world.gen.placement.CountRangeConfig;
import net.minecraft.world.gen.placement.Placement;
import net.minecraftforge.registries.ForgeRegistries;
public class ModOreGen {
public static void generateOre() {
for (Biome biome : ForgeRegistries.BIOMES) {
if (biome == Biomes.BAMBOO_JUNGLE) {
ConfiguredPlacement<CountRangeConfig> customConfig = Placement.COUNT_RANGE
.func_227446_a_(new CountRangeConfig(9, 10, 10, 0));
biome.addFeature(GenerationStage.Decoration.UNDERGROUND_ORES,Feature.ORE.withConfiguration(new OreFeatureConfig(OreFeatureConfig.FillerBlockType.NATURAL_STONE, blockinit.chocolate_ore.getDefaultState(), 10)).withPlacement(customConfig));
}
}
}
}
Where it says .withConfiguration it gives me the error:
The method withConfiguration(OreFeatureConfig) is undefined for the type Feature<OreFeatureConfig>
I have already tried updating my mappings and such, but nothing helped. This has been a problem that has really irritated me for days now. What is happening?
I just had this same problem with my code and finally fixed it. Try this out!
import net.minecraft.world.biome.Biome;
import net.minecraft.world.biome.Biomes;
import net.minecraft.world.gen.GenerationStage;
import net.minecraft.world.gen.feature.Feature;
import net.minecraft.world.gen.feature.OreFeatureConfig;
import net.minecraft.world.gen.placement.ConfiguredPlacement;
import net.minecraft.world.gen.placement.CountRangeConfig;
import net.minecraft.world.gen.placement.Placement;
import net.minecraftforge.registries.ForgeRegistries;
public class ModOreGen {
public static void generateOre() {
for (Biome biome : ForgeRegistries.BIOMES) {
if(biome == Biomes.BAMBOO_JUNGLE) {
ConfiguredPlacement<?> customConfig = Placement.COUNT_RANGE
.configure(new CountRangeConfig(9, 10, 10, 0));
biome.addFeature(GenerationStage.Decoration.UNDERGROUND_ORES, Feature.ORE.withConfiguration(newOreFeatureConfig(OreFeatureConfig.FillerBlockType.NATURAL_STONE,BlockInit.chocolate_ore.getDefaultState(), 10)).withPlacement(customConfig));
}
}
}
}
The obvious thing Sammerson did was to remove the strong typing for CountRangeConfig:
ConfiguredPlacement<?> , but that doesn't matter.
What you can't see is updating Forge to 1.15.2.
This is most likely your best fix. In your build.gradle, somewhere near the top (mine is line 28) you've probably already updated your mappings to:
mappings channel: 'snapshot', version: '20200409-1.15.1'
But you also want to go down and update the Forge version also (this is around line 90 for me).
dependencies {
minecraft 'net.minecraftforge:forge:1.15.2-31.1.0'
}
You need to do the same
gradlew genEclipseRuns
gradlew eclipse
just like updating the mappings.
(You can check the Forge page, there may be a newer version than 1.15.2 by the time someone else reads this. And I hope anyone using IntelliJ can figure out how to update your own mappings/forge.))

Why is close() method highlighted as redundant in Intellij, when using CSVPrinter from apcache.commons?

I am using CSVPrinter class from apache.commons.csv, and I am trying to print some lines in a csv file. As I know, we need to call close() method on a FileWriter, after the writing is done. And based on that assumption, I tried to call CSVPrinter.close().However, IntelliJ IDEA warns me that this method is redundant. Besides, examples in https://www.callicoder.com/java-read-write-csv-file-apache-commons-csv/ does not include this method, either. I want to know why is that method redundant and if I just use .flush() everything will be alright?
Here is an example copied from website mentioned above.
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
public class CSVWriter {
private static final String SAMPLE_CSV_FILE = "./sample.csv";
public static void main(String[] args) throws IOException {
try (
BufferedWriter writer = Files.newBufferedWriter(Paths.get(SAMPLE_CSV_FILE));
CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT
.withHeader("ID", "Name", "Designation", "Company"));
) {
csvPrinter.printRecord("1", "Sundar Pichai ♥", "CEO", "Google");
csvPrinter.printRecord("2", "Satya Nadella", "CEO", "Microsoft");
csvPrinter.printRecord("3", "Tim cook", "CEO", "Apple");
csvPrinter.printRecord(Arrays.asList("4", "Mark Zuckerberg", "CEO", "Facebook"));
csvPrinter.flush();
// I added the following line
csvPrinter.close();
}
}
}
As #user207421 explained in the comments.
First: The try-with-resources statement provides an automatic close at the end of its scope.
Second: Flush is redundant before close.

import cycle in golang with test packages

I am trying to refactor some test code and in two packages I need to do the same thing (connect to a DB). I am getting an import cycle. I get why I can't do it, but am wondering what the best way around it is.
Some specifics, I have three packages: testutils, client, engine.
In engine I define an interface & implementation (both exported).
package engine
type interface QueryEngine {
// ...
}
type struct MagicEngine {
// ...
}
And then in the testutils package I will create a MagicEngine and try and return it.
package testutils
func CreateAndConnect() (*engine.MagicEngine, error) {
// ....
}
Now in the test code (using a TestMain) I need to do something like
package engine
func TestMain(m *testing.M) {
e, err := testutils.CreateAndConnect()
// ....
os.Exit(m.Run())
}
This is of course a cycle. I want to do this so that I can in the client package also use this testutils.CreateAndConnect() method. I don't want to repeat the code in both packages. I don't want it in the main code of the engine package, it is very specific to the tests.
I tried adding it as an exported method on the engine test class (engine/engine_test.go) and using it in the client/client_test.go. No dice. :/
I feel I have done this in other languages, but could be crazy. What is the best way to structure this code for reusability?
You could use black-box style testing because the components of engine are exported. Change your tests to be in package engine_test:
package engine_test
import "engine"
import "testutils"
func TestMain(m *testing.M) {
e, err := testutils.CreateAndConnect()
// ....
os.Exit(m.Run())
}

toolprovider.getsystemjavacompiler() returns null

First, I am seeing a lot of questions about the use of the JavaCompilerAPI, I want to clarify that I am creating an on-line simulation builder that takes too many inputs from the user to precreate classes. That is why I am using a java compiler in order to write the classes using the user's inputs.
As for my problem, I have tested with some basic compiler programs, and am presently working of code found here: Dynamic Compiling Without Create Physical File
The compilation of the code is successful, however when I run the code,
ToolProvider.getSystemJavaCompiler();
returns null.
From other entries I understand one cause might be that the default java.home is JRE, so I added the line where I set java home to my JDK version:
System.setProperty("java.home", "C:\\Program Files (x86)\\Java\\jdk1.7.0_51;");
I have also added tools.jar to the folder with my program, and called the program specifying tools.jar in the classpath like so:
java -cp ".;tools.jar" Compiler
These approaches have not changed anything. Any ideas about what might be the problem?
import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.*;
public class Compiler {
static final Logger logger = Logger.getLogger(Compiler.class.getName());
static String sourceCode = "class HelloWorld{"
+ "public static void main (String args[]){"
+ "System.out.println (\"Hello, dynamic compilation world!\");"
+ "}"
+ "}";
public void doCompilation() {
System.out.println(System.getProperty("java.home"));
System.setProperty("java.home", "C:\\Program Files (x86)\\Java\\jdk1.7.0_51;");
System.out.println(System.getProperty("java.home"));
SimpleJavaFileObject fileObject = new DynamicJavaSourceCodeObject("HelloWorld",sourceCode);
JavaFileObject javaFileObjects[] = new JavaFileObject[]{fileObject};
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
System.out.println(compiler);
StandardJavaFileManager stdFileManager = compiler.getStandardFileManager(null, Locale.getDefault(), null);
...