Custom interpreter in java

Hello
I want to write a program to be able to parse and execute some files
The file consists of some user commands (I want to be able to define commands and corresponding methods, so when the program sees that the command should execute the corresponding method)
This grammar is not important to me; I just want to be able to define teams
Something like a simple and small translator written in java.
Is there a library for this purpose?
Or do I need to write by myself?

thanks

+4
source share
5 answers

Java 6 (and newer) has this in the standard library: see the javax.script package API documentation. You can use this to run scripts from your Java program (for example, to automate your program) using any scripting language for which the plug-in mechanism is available for the javax.script API. JavaScript is provided by default.

See the Java Scripting Programmer's Guide .

A simple example from this guide:

 import javax.script.*; public class EvalScript { public static void main(String[] args) throws Exception { // create a script engine manager ScriptEngineManager factory = new ScriptEngineManager(); // create a JavaScript engine ScriptEngine engine = factory.getEngineByName("JavaScript"); // evaluate JavaScript code from String engine.eval("print('Hello, World')"); } } 
+4
source

Have you looked at BeanShell?

Provides interpretation of fragments like Java at runtime.

If you need a little more than this then consider an attachment, for example. JPython or another small interpreter. Just select one that matches JSR-233 to get general debugging support.

+2
source

You can use ANTLR , but you will need to define a grammar (a parser will be created for you).

Check this example elevator expression , it looks like your problem, but instead of reading files, it reads from standard input.

If you choose ANTLR, take a look at ANTLRWorks , this is a graphical interface that will help in developing ANTLR (I think it is also available as an Eclipse plugin).

+1
source

What you need is called a "script engine." A quick search reveals Rhino . This is a good option because it is JavaScript, and many people know JavaScript, and there are a certain number of third-party extensions (libraries and code snippets) for it.

+1
source

I know this is an old thread, but some time ago I implemented a small interpreter for a language like JavaScript (with a lot of restrictions), the code was posted on Github at https://github.com/guilhermelabigalini/interpreter

But it supports IF / CASE / LOOPS / FUNCTIONs, see below:

 function factorial(n) { if (n == 1) return 1; return n * factorial(n - 1); } var x = factorial(6); 
0
source

All Articles