in reply to Re: Parsing and converting Fortran expression
in thread Parsing and converting Fortran expression [solved]
Alternate version without intermediate parse tree, just building the C code directly.
#!/usr/bin/perl # http://perlmonks.org/?node_id=1139915 use strict; # recursive descent parser using /\G/gc and C generator use warnings; my $had = $_ = @ARGV ? "@ARGV" : '.not.foo(1,bar(2)+1,3).and.baz(4,5)' +; my $want = '! foo[2][bar[1]][0] && baz[4][3]'; my $answer = expr(); /\G\s* \z /gcx or error(); # verify complete parse print "had $had\nwant $want\ngot $answer\n"; sub expr # left associative => term (.and. term)* { my $left = term(); $left = "(($left) && (" . term() . '))' while /\G\s* \.and\. /gcx; return $left; } sub term # left associative => item ([+] item)* { my $left = item(); $left = "(($left)+(" . item() . '))' while /\G\s* \+ /gcx; return $left; } sub list { my $left = '[(' . expr() . ')-1]'; $left = '[(' . expr() . ")-1]$left" while /\G\s* , /gcx; return $left; } sub item # number, .not. minus, array, or (expr) { /\G\s* (\d+) /gcx and return $1; /\G\s* \.not\. /gcx and return '!(' . item() . ')'; /\G\s* (\w+) \s* \( /gcx and do{ # array my $arr = $1; my $value = list(); /\G\s* \) /gcx or error(); return $arr . $value; }; /\G\s* \( /gcx and # parens do{ my $value = expr(); /\G\s* \) /gcx or error(); return $value } +; error(); } sub error { die s/\G/ SYNTAX ERROR->/r, "\n" }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: Parsing and converting Fortran expression
by Anonymous Monk on Aug 26, 2015 at 15:02 UTC |