#!perl6 # # test-grammar.pl6: # # Attempted to specify a grammar with a string evaluated during the script execution # at run-time depending on input from another process. Below was written to show # how and why it doesn't yet do what you mean. # # Short-term strategy is: write a parsing dispatch table which determines # which type of known grammars are being used and parses against the # specified grammar. (Not listed in this example.) # # WARNING: the below is meant to show Perl6 code which is a BAD EXAMPLE. # our grammar Example::Grammar; # Grammar to be evaluated our Match $match; # Match object our Str $grammar; # Str containing grammar our Str $string = "parse me fully"; # Str to parse ## PASS:{ # Works - but only due to the string being declared versus eval ## # 0. Literal string encapsulation of grammar $grammar = "grammar Example::Grammar { rule TOP { } token wordlist { [ \s*]+ } regex word {\w+} }"; say "# Grammar:\n|$grammar|"; eval($grammar); ## <-- Not required.. since Perl6 gets it from string above - ## No wonder it cannot be passed from the other process in a string: ## Well duh. (say returns interpreted rules in the grammar, rather than ## delaring the Grammar block) finding an interpolated code block in ## the double-quoted String, not the original Str of $grammar ## ## Change above to single quotes, fails. ## ## } ## ## FAILS:{ # Seemingly Dubious ## our $grams = q/ rule TOP { } token wordlist { [ \s*]+ } regex word {\w+} /; # ## 1. Basic string concat to nest target rules inside grammar block: #our Str $gram_1 = 'grammar Example::Grammar {'; #$gram_1 ~= $grams; #$gram_1 ~= '}'; #say "# Grammar 1:\n|$gram_1|"; #eval($gram_1); # FAIL_1 # ## 2. Basic string interpolation to nest target rules inside grammar block: ##our Str $gram_2 = "grammar Example::Grammar {$grams}"; #our Str $gram_2 = "grammar Example::Grammar \{$grams\}"; #say "# Grammar 2:\n|$gram_2|"; #eval($gram_2); # FAIL_2 - still fails # ## 3. Inclusion in grammar statement: #our grammar Example::Grammar { # <$grams> #}; # FAIL_3 - either with :: or with-out inside <> or outside, doesn't matter # ## } ## # # @eval(Str $string, Str $grammar --> Match $match): # #eval(q% say "TEST: "; $match = Example::Grammar.parse($string); say " 1. perl: ",$match.perl; say " 2. string map: "; # # Match and print a wordlist using test grammar: # #say map{~$_},$word; for ($match) -> @w { for (@w) -> $W { say "|" ~ $W ~ "|"; } } #%); ## ## TODO: OK then, how do you eval a grammar? ##