[newbie] parsing CSS style

Mat| delgad... at caramail.com
Thu Oct 18 08:12:47 UTC 2007


I am just discovering ragel and I after some time trying to
understand how I could use it for my needs, I would like to
write a CSS style parser as an exercise and I come up
with some questions.

The input string is in the following form :

min-width: 100px; background: green;

for example.

Here is some code from my .rl file :

      machine CSSStyle;
      alphtype char;

      action token { free(tk); tk = (char *) calloc(fpc-tk_start+1,
sizeof(char)); std::strncpy(tk, tk_start, fpc-tk_start); }
      action style_item_value { free(tk2); tk2 = (char *) calloc(fpc-
tk_start+1, sizeof(char)); std::strncpy(tk2, tk_start, fpc-tk_start);
listener.style_item_value(tk2); }
      action unit { free(tk2); tk2=(char *) calloc(fpc-tk_start+1,
sizeof(char)); std::strncpy(tk2, tk_start, fpc-tk_start); }
      action style_item { style_item = (char *) calloc(fpc-tk_start+1,
sizeof(char)); std::strncpy(style_item, tk_start, fpc-tk_start);
listener.style_item(style_item); free(style_item); }
      action style_item_size { listener.style_item_size(std::atoi(tk),
tk2); }

      number =  digit+ >{tk_start = fpc;} %token;
      style_item = (alpha | '-')+ >{tk_start=fpc;} %style_item;
      style_item_value = (alpha)+ >{tk_start=fpc;} %style_item_value;
      unit = ("em"|"px") >{tk_start=fpc;} %unit;
      size = number unit %style_item_size;
      style = space* style_item space* ":" space* (size |
style_item_value) space* ";";

      main := style+;

My questions are :

- knowing that my target language is C++, is there a way to do
something simpler in my actions ? For the moment I use some
variables like tk and tk2 in a class and I have to reallocate them
with "calloc"...

- I have got a problem (maybe more than one but I could only
detect one !) with my machines, indeed in my expressions I always
have a terminating ";" character but for some reason the style_item
action is executed even if there is no terminating ";". For example,
if I use "background: green" as an input string, the style_item is
going to be executed but it should not because there is no ";" at
the end.

Can someone help ?

Thanks in advance!!!

More information about the ragel-users mailing list