Search code examples
c++regexragel

Compiling errors with Ragel and C++


I am trying to learn Ragel for the past 2 days and have been facing some issues related to the Ragel Syntax. My goal is to write a parser that recognizes Regex commands with C++ as host language. For now I am trying to recognize the following command with parser - :LoadSdf [0-9]+

Below is the following code I am trying:

#include <iostream>
#include <string.h>
#include <stdio.h>

%%{
action done {
printf("done\n");
}

machine ldf;    
main := (':'.'LoadSdf'.[0-9])@done;

}%%

%%write data;
int main(int argc, char** argv)
{
int cs;
if(argc > 1) {
    char *p = argv[1];
    char *pe = p+strlen(p) + 1;
    %%write init;
    %%write exec;
}
 return 0;
}

When I try to compile with the command ragel ldf.cpp - I get the following error:

ldf.cpp:10:1: this specification has no name, nor does any previous specification
ldf.cpp:16:31: action lookup of "done" failed

However if I write directly the code as

 main := (':'.'LoadSdf'.[0-9])@{printf("done\n");} //this compiles.

The second issue I have is when I try to write the following for my state machine -

main := (':'.'LoadSdf'.[0-9])@{printf("done\n");} $err{printf("error : %c",fc);};

I want to print an error when the commands are not matching as expected. The above code compiles in with the ragel command. However when I try compiling with g++ ldf.c -o ldf - this gives the following compiler error:

ldf.c: In function ‘int main(int, char**)’:
ldf.c:171:12: error: ‘eof’ was not declared in this scope
if ( p == eof )
          ′         

Any suggestions are welcomed.


Solution

  • machine should appear at the first line. This is what the "this specification has no name" error is about.

    %%{
    
    machine ldf;    // put it here.
    
    action done {
        printf("done\n");
    }
    
    main := (':'.'LoadSdf'.[0-9])@done;
    
    }%%
    

    For your second error, you should define the eof variable.

    char *p = argv[1];
    char *pe = p+strlen(p) + 1;
    char *eof = pe;               // <-- add this.