Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- grammar VarDeclare {
- token TOP { <type> <array>? \s+ <name> \s* <value>? }
- proto token type {*}
- token type:sym<int> { 'int' }
- token type:sym<float> { 'float' }
- token type:sym<string> { 'string' }
- token array { '[]' }
- token name { <[A..Za..z]>+ }
- proto token value {*}
- token value:sym<int> { '=' \s* <[0..9]>+ }
- token value:sym<float> { '=' \s* <[0..9]>* '.' <[0..9]>+ }
- token value:sym<string> { '=' \s* '"' <[A..Za..z]>+ '"' }
- }
- class Variable {
- has Str $.type is required;
- has Str $.name is required;
- has $.value;
- has @.arrayValue;
- has Bool $.isArray is rw = False;
- method declareAsArr() {
- $.isArray = True;
- }
- multi method new(Str $type, Str $name, $value) {
- self.bless(:$type, :$name, :$value);
- }
- multi method new(Str $type, Str $name, *@arrayValue) {
- self.bless(:$type, :$name, :@arrayValue);
- self.declareAsArr();
- }
- method gist(Variable:D:){
- if $.isArray {
- return "$.type[] $.name = " ~ @.arrayValue.join(', ');
- } else {
- return "$.type $.name = " ~ ($.value // 'undefined');
- }
- }
- }
- sub parseCode(Str $input) {
- my $parsed = VarDeclare.parse($input);
- if $parsed {
- my $type = $parsed<type>.Str;
- my $name = $parsed<name>.Str;
- my $isArray = $parsed<array>:exists;
- my $valueMatch = $parsed<value>;
- if $isArray {
- my @values = $valueMatch ?? $valueMatch.Str.subst('=', '').split(',').map(*.trim) !! ();
- =begin pod
- say $type;
- say $name;
- say $isArray;
- say @values;
- =end pod
- return Variable.new($type, $name, |@values);
- } else {
- my $value = $valueMatch ?? $valueMatch.Str.subst('=', '').trim !! Nil;
- =begin pod
- say $type;
- say $name;
- say $isArray;
- say $value;
- =end pod
- return Variable.new($type, $name, $value);
- }
- } else {
- say "Parsing failed for input: $input";
- return Nil;
- }
- }
- #TODO make arrays work with multiple value declaration
- #=begin pod
- my $input = "int a = 100";
- my $output1 = parseCode($input);
- my $input2 = 'string[] animal = "cat,dog"';
- my $output2 = parseCode($input2);
- my $input3 = "float Hb";
- my $output3 = parseCode($input3);
- my $input4 = 'string hhh = "hope"';
- my $output4 = parseCode($input4);
- say $output1;
- say $output2;
- say $output3;
- say $output4;
- #=end pod
Advertisement
Comments
-
- currently output would be
- Parsing failed for input: string[] animal = "cat,dog"
- int a = 100
- (Any)
- float Hb = undefined
- string hhh = "hope"
Add Comment
Please, Sign In to add comment