Mainly to try Javacc, use the idea of compilation principle to construct your own language :)
First of all, https://javacc.dev.java.net/?javacc download Javacc
Our goal is to convert from? Teacher to SELECT? *? From? Teacher
First write .jj files
1. Define separator to open
Skip ?:
{
?? "?"
|? "/ t"
|? "/ n"
|? "/ r"
|? "/ f"
}
2. Define the keyword. From? For the keyword of HQL, Teacher is the class name entered by the user. It should be a word that consists of letters and numbers. We can use regular expressions: ["A" - "z", "a" - "Z "0" - "9"].
Token:? / * Reserved? Tokens? For? Uql? * /
{
????
??? |?
}
?
3. Next define the order and specification of the input
Void? Expression () ?:
{
? TOKEN? TTABLE;
}
{
(
??
?? Ttable? =?
?)
? {
?? SQLSB.Append ("SELECT? *");
?? SQLSB.Append ("? from?"). Append (TTable.Image);
?
}
?
Finally, write parsing code to generate Java code.
Parser_Begin (HQLParser)
Import? java.lang.stringbuffer;
Import? java.io.stringreader;
IMPORT? Java.io.Reader;
PUBLIC? Class? HQLPARSER? {
?????????? STRINGBUFFER? SQLSB;
/ ** ??
?? a? String? Based? Constructor? For? Ease? Of? Us.
?? ** /
???? 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 ());
????????}
???????? caratch (Exception? E)
???????? {
?????????????? E.PrintStackTrace ();
????????}
????}
???? public? void? PARSE ()
???? {
? Try
? {
????? expression ();
?
? catch (Exception? E)
???????? {
???????????? E.PrintStackTrace ();
????????}
????}
}
Parser_END (HQLPARSER)
Next to DOS Enter:
Javacc? -debug_parser? Test.jj-debug_parser: Used to output syntax tree
At this time, seven Java files will be generated, and the role of each file will be described in detail later.
Time only needs
Javac? *. Java can compile all Java files
Then execute java? HqlParser? "From? Teacher"
At this time, "SELECT® *? From? Teacher" is displayed on the screen.