FortranPEG is an online parser generator that uses a PEG grammar and generates a Fortran module with a recursive descent parser.
First, you have to write the parsing expression grammar, for example, a simple calculator:
s = e
e = t "+" e
/ t "-" e
/ t
t = f "*" t
/ f "/" t
/f
f = "(" e ")"
/ _ [0..9]+ _
_ = [ \t\n\r]*
Next, semantic actions can be added to the end of each rule in Fortran code within brackets.
To access the values within the body of the rule, a label can be defined. For example, in the rule:
f = _ [0..9]+ _
It could be:
f = _ num:[0..9]+ _
Where "num" will be automatically declared in the rule function.
Note
By default, these labels are declared as strings. It is the user's responsibility to return a desired type.
Important
By convention, in each rule function, a value and return type can be defined with the name "res".
For example, to return an integer from the rule:
f = _ num:[0..9]+ _
It would be:
f = _ num:[0-9]+ _ {
integer :: res
read(num, *) res
}
The complete grammar can be found at this link:
Now that you have the grammar, use the online generator to download the parser. It will be downloaded as parser.f90.
To use the parser, you will need a Fortran program that makes calls to the parse(input) function with the string to be evaluated.
Here is an example program for testing:
To start using the program, it must be compiled as follows:
gfortran -c parser.f90
gfortran -c test.f90
gfortran parser.o test.o -o test
./test
Tip
Alternatively, you can use a bash with these lines: # bash exec
Congratulations 👏! You can now use the built program!