Skip to content

Instantly share code, notes, and snippets.

@cimi
Created February 4, 2012 16:30
Show Gist options
  • Save cimi/1738814 to your computer and use it in GitHub Desktop.
Save cimi/1738814 to your computer and use it in GitHub Desktop.
Grammar Hack Example for Digua
// intialization section
grammar CSS21;
options
{
backtrack=true;
memoize=true;
superClass=DiguaParser;
}
@lexer::header {
package net.sf.digua;
}
@parser::header {
package net.sf.digua;
}
@parser::members {
private CSS21Processor getCSSProcessor() {
return (CSS21Processor)getProcessor();
}
}
// additional stuff here
term
: unaryOperator?
(
NUMBER
| PERCENTAGE
| LENGTH
| EMS
| EXS
| ANGLE
| TIME
| FREQ
)
| possibleColor=STRING
{
$possibleColor.setText(getCSSProcessor()
.minimizeColor($possibleColor.text));
}
| IDENT ( // Function
LPAREN expr RPAREN
)?
| URI
| hexColor
;
hexColor
: hexColorName=HASH
{
$hexColorName.setText(getCSSProcessor()
.minimizeColor($hexColorName.text));
}
;
protected String minimizeColor(String value) {
if (minimizeColors) {
try {
return HTMLColor.getMinHTML(value);
} catch (IllegalArgumentException exc) {
}
}
return value;
}
/** Given an HTML color returns the minimum size string
* representing that color.
* @throws IllegalArgumentException if the color name is
* not recognized or the value contains invalid digits or
* the number of digits is not 3 or 6.
*/
public static String getMinHTML(String value) {
if (value.length() <= 3)
return value;
Color c = forName(value);
HTMLColor hc = valueOf(c);
if (hc != null && hc.name().length()
< value.length())
value = hc.name();
if (value.length() <= 3)
return value;
String rgb = toHex(c.getRed()) + toHex(c.getGreen())
+ toHex(c.getBlue());
if (rgb.charAt(0) == rgb.charAt(1) &&
rgb.charAt(2) == rgb.charAt(3) &&
rgb.charAt(4) == rgb.charAt(5)) {
rgb = new StringBuilder().append(rgb.charAt(0))
.append(rgb.charAt(2))
.append(rgb.charAt(4)).toString();
}
if (rgb.length() < value.length())
value = "#" + rgb;
return value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment