Am 09.02.2011 10:28, schrieb Gerd Pokorra:
In a presentation I saw a little calculator written in NQP that read
from and write to the commandline. How can I parse (compile) a string
and assign the result from the grammar action to a variable with a
NQP-program. Is it possible?


# parser
grammar ABC::Grammar {
     rule TOP {<expr>  }
     rule expr {<integer>  <addop>  <integer>  };
     token addop { '+' | '-' }
     token integer { \d+ }
}

# transform to ast
class ABC::Actions {
     method TOP($/) {
         make PAST::Block.new( $<expr>.ast );
     }

     method expr($/) {
         my $pirop := $<addop>  eq '-' ?? 'sub' !! 'add';
         make PAST::Op.new( :pirop($pirop),
                  +$<integer>[0], +$<integer>[1]);
     }
}


# compiler object (HLL::Compiler is base class for compilers)
class ABC::Compiler is HLL::Compiler {
     ABC::Compiler.language('abc');
     ABC::Compiler.parsegrammar(ABC::Grammar);
     ABC::Compiler.parseactions(ABC::Actions);
}

# invoke the compiler
my @ARGS := (pir::getinterp__p)[2];     # args from Parrot
ABC::Compiler.command_line(@ARGS);

#my $result := ....( '3+4' ) ???

my $result := ABC::Grammar.parse('3+4', :actions(ABC::Actions.new));
my $past   := $result.ast;

(haven't tested it though)

Cheers,
Moritz
_______________________________________________
http://lists.parrot.org/mailman/listinfo/parrot-dev

Reply via email to