The main purpose is to try javacc and use the idea of compiling principles to construct your own language :)
First download javacc from your hometown of https://javacc.dev.java.net/javacc
Our goal today is to convert from teacher to select * from teacher
First, write the. JJ file.
1. Define the separator to be empty
SKIP:
{
""
| "/T"
| "/N"
| "/R"
| "/F"
}
2. Define keywords. From is the hql keyword. Teacher is the class name entered by the user. It should be any word consisting of letters and numbers. We can use a regular expression: ["a"-"Z", "a"-"Z", "0"-"9.
Token:/* Reserved tokens for uql */
{
<From: "from">
| <From_object :( ["a"-"Z", "a"-"Z", "0"-"9"]) +>
}
3. Define the input sequence and specifications.
Void expression ():
{
Token tTable;
}
{
(
<From>
TTable = <from_object>
)
{
Sqlsb. append ("select *");
Sqlsb. append ("from"). append (tTable. Image );
}
}
Finally, write the parsing code to generate the Java code.
Parser_begin (hqlparser)
Import java. Lang. stringbuffer;
Import java. Io. stringreader;
Import java. Io. reader;
Public class hqlparser {
Private Static stringbuffer sqlsb;
/**
A string based constructor for example of use.
**/
Public hqlparser (string S)
{
This (Reader) (new stringreader (s )));
Sqlsb = new stringbuffer ();
}
Public String getsql ()
{
Return sqlsb. tostring ();
}
Public static void main (string ARGs [])
{
Try
{
String query = ARGs [0];
Hqlparser parser = new hqlparser (query );
Parser. parse ();
System. Out. println ("SQL:" + parser. getsql ());
}
Catch (exception E)
{
E. printstacktrace ();
}
}
Public void parse ()
{
Try
{
Expression ();
}
Catch (exception E)
{
E. printstacktrace ();
}
}
}
Parser_end (hqlparser)
Enter the following in DOS:
Javacc-debug_parser test. jj
-Debug_parser: Used to output the syntax tree
At this time, seven java files will be generated. The functions of each file will be described in detail later.
At this time, you only need
Javac *. Java can compile all java files
Then execute Java hqlparser "from teacher"
At this time, the screen will show "select * from teacher"
Code details will be sent out tomorrow.