edu.mines.jtk.util.UnitsParser.jj Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of edu-mines-jtk Show documentation
Show all versions of edu-mines-jtk Show documentation
Java packages for science and engineering
The newest version!
options {
STATIC=true;
}
PARSER_BEGIN(UnitsParser)
package edu.mines.jtk.util;
import java.io.*;
/**
* Parser (generated from UnitsParser.jj via JavaCC) to create Units
* from a string that conforms to the following (extended BNF) grammar:
*
* unit -> expr EOF
* expr -> term ( ("+" | "-") (DOUBLE|INTEGER) )?
* term -> factor ( ("*")? factor | "/" factor )*
* factor -> primary ("^" INTEGER)?
* primary -> NAME | (DOUBLE|INTEGER) | "(" expr ")"
*
*
* @author Dave Hale
* @version 1998.07.06
*/
final class UnitsParser {
/**
* Parse a String containing a unit definition.
* @param the unit definition, as in "coulomb/volt".
* @exception ParseException if the definition is not valid.
*/
static synchronized Units parse(String definition) throws ParseException {
ReInit(new StringReader(definition));
return units();
}
}
PARSER_END(UnitsParser)
SKIP : {
" "
| "\t"
}
TOKEN : {
< PLUS: "+" >
| < MINUS: "-" >
| < MUL: ("*"|".") >
| < DIV: ("/"|"per"|"PER") >
| < POW: ("^"|"**") >
| < LP: "(" >
| < RP: ")" >
| < NAME: "%" | ()*(()+()+)* >
| < INTEGER: ("-")?()+ >
| < DOUBLE: ("-")?(["e","E"](["-","+"])?)? >
| < #ALPHA: | "_" >
| < #LETTER: ["a"-"z","A"-"Z"] >
| < #FLOAT: | (".")? | "." >
| < #DIGIT: ["0"-"9"] >
}
Units units() : {
Units e;
} {
e=expr() {
return e;
}
}
Units expr() : {
Units t;
Token n;
} {
t=term() (
(n=|n=) {
t.shift(Double.valueOf(n.image).doubleValue());
} | (n=|n=) {
t.shift(-Double.valueOf(n.image).doubleValue());
}
)? {
return t;
}
}
Units term() : {
Units f,fb;
} {
f=factor() (
()? fb=factor() {
f.mul(fb);
} | fb=factor() {
f.div(fb);
}
)* {
return f;
}
}
Units factor() : {
Units p;
Token n;
} {
p=primary() (
n= {
p.pow(Integer.valueOf(n.image).intValue());
}
)? {
return p;
}
}
Units primary() : {
Units e,p;
Token n;
} {
n= {
p = Units.unitsFromName(n.image);
if (p==null) throw new ParseException("Units \""+n.image+"\" are undefined.");
return p;
} | (n=|n=) {
double d = (new Double(n.image)).doubleValue();
return (new Units()).scale(d);
} | e=expr()
© 2015 - 2025 Weber Informatics LLC | Privacy Policy