We want to design a simple domain specific language for writing test scripts to automatically test a XML-based interface of one of our applications. A sample test would be:
Get an input XML file from network shared folder or subversion repository
Import the XML file using the interface
Check if the import result message was successfull
Export the XML corresponding to the object that was just imported using the interface and check if it correct.
If the domain specific language can be declarative and its statements look as close as my sentences in the sample above as possible, it will be awesome because people won't necessarily have to be programmers to understand/write/maintain the tests. Something like:
newObject = GET FILE "http://svn/repos/template1.xml"
reponseMessage = IMPORT newObject
newObjectID = GET PROPERTY '/object/id/' FROM responseMessage
(..)
But then I'm not sure how to implement a simple parser for that languange in Java. Back in school, 10 years ago, I coded a language parser using Lex and Yacc for the C language. Maybe an approach would be to use some equivalent for Java?
Or, I could give up the idea of having a declarative language and choose an XML-based language instead, which would possibly be easier to create a parser for? What approach would you recommend?
You could try JavaCC or Antlr for creating a parser for your domain specific language. If the editors of that file are not programmers, I would prefer this approach over XML.
Take a look at Xtext - it will take a grammar definition and generate a parser as well as a fully-featured eclipse editor pluging with syntax highlighting and -checking.
ANTLR should suffice
ANTLR, ANother Tool for Language Recognition, is a language tool that provides a framework for constructing recognizers, interpreters, compilers, and translators from grammatical descriptions containing actions in a variety of target languages. ANTLR provides excellent support for tree construction, tree walking, translation, error recovery, and error reporting.
Look at Antlr library. You'll have to use EBNF grammatic to describe your language and then use Antlr to make java classes from your grammatic.
Have a look at how Cucumber defines its test cases:
(source: cukes.info)
http://cukes.info/ - can run in JRuby.
Or, I could give up the idea of having a declarative language and
choose an XML-based language instead,
which would possibly be easier to
create a parser for? What approach
would you recommend?
This could be easily done using XML to describe your test scenarios.
< GETFILE object="newObject" file="http://svn/repos/template1.xml"/ >
Since your example of syntax is quite simple, it should also be possible to simply use StringTokenizer to tokenize and parse these kind of scripts.
If you want to introduce more complex expressions or control structures you probably better choose ANTLR
I realize this thread is 3 years old but still feel prompted to offer my take on it. The questioner asked if Java could be used for a DSL to look as closely as possible like
Get an input XML file from network shared folder or subversion repository
Import the XML file using the interface
Check if the import result message was successfull
Export the XML corresponding to the object that was just imported
using the interface and check if it correct.
The answer is yes it can be done, and has been done for similar needs. Many years ago I built a Java DSL framework that - with simple customization - could allow the following syntax to be used for compilable, runnable code:
file InputFile
message Message
get InputFile from http://<....>
import Message from InputFile
if validate Message export Message
else
begin
! Signal an error
end
In the above, the keywords file, message, get, import, validate and export are all custom keywords, each one requiring two simple classes of less than a page of code to implement their compiler and runtime functions. As each piece of functionality is completed it is dropped into the framework, where it is immediately available to do its job.
Note that this is just one possible form; the exact syntax can be freely chosen by the implementor. The system is effectively a DIY high-level assembly language, using pre-written Java classes to perform all the functional blocks, both for compiling and for the runtime. The framework defines where these bits of functionality have to be placed, and provides the necessary abstract classes and interfaces to be implemented.
The system meets the primary need of clarity, where non-programmers can easily see what's happening. Changes can be made quickly and run immediately as compilation is almost instantaneous.
Complete (open) source code is available on request. There's a generic Java version and also one for Android.
Related
This page describes how I can use the code generator in javac to generate code given that I can build an AST (using a separate parser which I wrote). The technique involves editing javac's source code to basically bypass the Java parser, so that one could supply his/her own AST to the code generator. This could work, but I was hoping to do it in a slightly cleaner way. I want to include the code generating part of javac as a library in my project so I can use it to generate code, without bringing with it the rest of javac's source.
Is there a way to do this with javac, or is there perhaps a better library?
Also, feel free to change the question's title. I couldn't think of a better one, but it's a little ambiguous. If you suggest an edit for a better title, I'll accept it.
I think what you might be interested in is a java library like BCEL(ByteCode Engineering Library)
I played around with it back when I took a class on compiler construction, basically, it has a nice wrapper for generating the constant pool, inserting named bytecode instructions into a method and whatnot, then when you are done, you can either load the class at runtime with a custom classloader, or write it out to a file in the normal way.
With BCEL, it should be relatively easy to go from the syntax tree to the java bytecodes, albeit a bit tedious, but you may want to just use BCEL to generate the raw bytecode without building the tree as well in some cases.
Another cool framework is ASM, a bytecode analysis and manipulation framework.
In case you do not want to use a framework, as of now (2014), it is not possible to generate bytecode from a tree using the arbitrary representations of com.sun.source.tree.* as said here.
The application I am working inputs lot of data from file import and updates the database column accordingly. I need to come up with a custom Rule engine that would process all the input values based on validation and perform transformation of data accordingly. E.x.
One of the fields in our application is Product Name. So one of the rules we need to implement is to convert Product name from lower case to upper case, if the input value from the file is in lower case. Similarly, there are many text/mathematical transformations that need to be done. For these reasons, we need to come up with custom rule engine where we define the rules for each attribute, parse them and then apply the rules.
I do know that ANTLR is one of the parser generators around for Java. I am seeking advice on following queries:
1> General information on working of a parser generator and best practices for implementing grammar.
2> Since I need to design this rule engine completely, can anyone point me to a sample rule engine out there that I can refer to? right from UI to database design. I am using GWT for UI, Java for core logic and oracle for database
3> Are there any other parser generators around for Java
4> Though I do want to follow the path of defining my own grammar and using parser generator to build this rule engine, is there any other approach I should consider?
You might want to consider just using JbossRules (formerly Drools) which is a Java based rules engine. Alternatively, a scripting engine may be another way to implement your rules (e.g. Apache Rhino (Javascript in Java)).
Writing your own in this situation seems like overkill, but it may allow you to provide better security guarantees if end users are going to be creating the rules / scripts.
EDIT to address questions in comments:
I suggest using an existing rules engine (ala JbossRules/Drools) instead of writing your own parser and grammar (for the rule component). Take a look here for instance: Drools.
For specialized logic that rules may need to use (db access or computation libraries) you should write a single Java API used by your rules (so that rules are not deeply accessing your other code since that can lead to bugs if/when you refactor). This advice applies regardless of which rules engine you use (your own or an existing one).
I assume that you already have the data format of your data input files solved and that you are only looking for a solution to the rule format and rule parsing.
There is JavaCC, which is a Parser generator and there is groovy for evaluating rules. If you are going to use a script engine or not depends on the grammar. If the rules can't be expressed in javascript, java, python, etc, and you want to write them in a new language, well then you have to use a parser generator. But you can always do anything you want inside methods that you create and then call them from the rules. The rules will be evaluated by the script engine.
I want to use a math-expression parser of java code. In particular I would like to convert a math-expression given as String to an abstract syntax tree consisted of separate nodes.
Is there anyone to recommend me a relevant open source tool?
If no, how do you reckon the possibility to exploit Intellij source code to do this work?
Which classes are responsible for code parsing and analysis?
Are they included in idea.jar? How can I easily infiltrate their functionality (methods etc)?
I am speaking exclusively for Intellij.
Take a look at MVEL library.
If you only want the results of the math-expression you should revise the question and the answer i selected months ago:
Java 1.5: mathematical formula parser
Brieff description: use the java integration with dinamyc languajes like javascript to let them do the work for you
I would not use IntelliJ, as much as I love it.
If you need an AST, look no further than ANTLR. If you can write a grammar for your equations, ANTLR can generate a lexer/parser to create it for you.
I'm parsing Java source files and I need to extract type information to guess at signatures of called methods.
e.g. I have foo.x(bar) and I need to figure out the type of foo and bar.
I'm using a java parser that gives me a complete AST, but I'm running into problems with scoping. Is there a different parser I could use that resolves this?
This can't be resolved perfectly because of reflection, but I'm hoping a good parser can deal with scoping and casting issues in the least.
edit: I can't assume that other source files will be present, so I can't simply follow the method call to its source and read the signature from the method declaration
Java's Pluggable Annotation Processing Framework (and its associated APIs) are designed to model Java code in the way you're talking about. You can invoke the Java compiler at runtime, giving you access to the model of the source using the APIs in the javax.lang.model packages. An introductory article is available here.
Basically getting types of identifier would require you to run a big part of a Java compiler yourself. In Java there is a long way from parsing to resolving types, so implementing this is a challenging task even for good programmers.
Perhaps your best way through this would be to take the Java Compiler from OpenJDK, run the relevant compiler phases and extract the types from that.
What you need is all the name and type resolution machinery. As another poster observed, one way you can get that is to abuse the Java compiler.
But you likely have some goal in mind other than compiling java; once you have those names, you want to do something with them. The Java compiler is unlikely to help you here.
What you really want is a foundation for building a tool that processes the Java language, including name and type resolution, that will help you do the rest of your task.
Our DMS Software Reengineering Toolkit is generalized program analysis and transformation machinery. It parses code, builds ASTs, manages symbol tables, provides generic flow analysis mechnisms, supports AST modification (or construction) both procedurally and in terms of surface syntax pattens, including (re)generation of compilable text from the ASTs including any comments.
DMS has a Java Front End that enables DMS to process Java, build Java ASTs, do all that name and type resolution you want. Yes, that's a lot of machinery, equivalent to what the Java compiler has, go read your latest Java reference manual. You can build whatever custom tool you need on top of that foundation.
What you won't be able to do as a practical issue is full, accurate name and type resolution without the rest of the Java source files (or corresponding class files), no matter how you tackle it. You might be able to produce some heuristic guess, but that's all it would be.
I'm looking for a way to automatically generate source code for new methods within an existing Java source code file, based on the fields defined within the class.
In essence, I'm looking to execute the following steps:
Read and parse SomeClass.java
Iterate through all fields defined in the source code
Add source code method someMethod()
Save SomeClass.java (Ideally, preserving the formatting of the existing code)
What tools and techniques are best suited to accomplish this?
EDIT
I don't want to generate code at runtime; I want to augment existing Java source code
What you want is a Program Transformation system.
Good ones have parsers for the language you care about, build ASTs representing the program for the parsed code, provide you with access to the AST for analaysis and modification, and can regenerate source text from the AST. Your remark about "scanning the fields" is just a kind of traversal of the AST representing the program. For each interesting analysis result you produce, you want to make a change to the AST, perhaps somewhere else, but nonetheless in the AST.
And after all the chagnes are made, you want to regenerate text with comments (as originally entered, or as you have constructed in your new code).
There are several tools that do this specifically for Java.
Jackpot provides a parser, builds ASTs, and lets you code Java procedures to do what you want with the trees. Upside: easy conceptually. Downside: you write a lot more Java code to climb around/hack at trees than you'd expect. Jackpot only works with Java.
Stratego and TXL parse your code, build ASTs, and let you write "surce-to-source" transformations (using the syntax of the target language, e.g., Java in this case) to express patterns and fixes. Additional good news: you can define any programming language you like, as the target language to be processed, and both of these have Java definitions.
But they are weak on analysis: often you need symbol tables, and data flow analysis, to really make analyses and changes you need. And they insist that everything is a rewrite rule, whether that helps you or not; this is a little like insisting you only need a hammer in toolbox; after all, everything can be treated like a nail, right?
Our DMS Software Reengineering Toolkit allows the definition of an abitrary target language (and has many predefined langauges including Java), includes all the source-to-source transformation capabilities of Stratego, TXL, the procedural capability of Jackpot,
and additionally provides symbol tables, control and data flow analysis information. The compiler guys taught us these things were necessary to build strong compilers (= "analysis + optimizations + refinement") and it is true of code generation systems too, for exactly the same reasons. Using this approach you can generate code and optimize it to the extent you have the knowledge to do so. One example, similar to your serialization ideas, is to generate fast XML readers and writers for specified XML DTDs; we've done that with DMS for Java and COBOL.
DMS has been used to read/modify/write many kinds of source files. A nice example that will make the ideas clear can be found in this technical paper, which shows how to modify code to insert instrumentation probes: Branch Coverage Made Easy.
A simpler, but more complete example of defining an arbitrary lanauges and transformations to apply to it can be found at How to transform Algebra using the same ideas.
Have a look at Java Emitter Templates. They allow you to create java source files by using a mark up language. It is similar to how you can use a scripting language to spit out HTML except you spit out compilable source code. The syntax for JET is very similar to JSP and so isn't too tricky to pick up. However this may be an overkill for what you're trying to accomplish. Here are some resources if you decide to go down that path:
http://www.eclipse.org/articles/Article-JET/jet_tutorial1.html
http://www.ibm.com/developerworks/library/os-ecemf2
http://www.vogella.de/articles/EclipseJET/article.html
Modifying the same java source file with auto-generated code is maintenance nightmare. Consider generating a new class that extends you current class and adds the desired method. Use reflection to read from user-defined class and create velocity templates for the auto-generating classes. Then for each user-defined class generate its extending class. Integrate the code generation phase in your build lifecycle.
Or you may use 'bytecode enhancement' techniques to enhance the classes without having to modify the source code.
Updates:
mixing auto-generated code always pose a risk of someone modifying it in future to just to tweak a small behavior. It's just the matter of next build, when this changes will be lost.
you will have to solely rely on the comments on top of auto-generated source to prevent developers from doing so.
version-controlling - Lets say you update the template of someMethod(), now all of your source file's version will be updated, even if the source updates is auto-generated. you will see redundant history.
You can use cglib to generate code at runtime.
Iterating through the fields and defining someMethod is a pretty vague problem statement, so it's hard to give you a very useful answer, but Eclipse's refactoring support provides some excellent tools. It'll give you constructors which initialize a selected set of the defined members, and it'll also define a toString method for you.
I don't know what other someMethod()'s you'd want to consider, but there's a start for you.
I'd be very wary of injecting generated code into files containing hand-written code. Hand-written code should be checked into revision control, but generated code should not be; the code generation should be done as part of the build process. You'd have to structure your build process so that for each file you make a temporary copy, inject the generated source code into it, and compile the result, without touching the original source file that the developers work on.
Antlr is really a great tool that can be used very easily for transforming Java source code to Java source code.