File: Signatures.pm

package info (click to toggle)
libparse-method-signatures-perl 1.003019-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 276 kB
  • sloc: perl: 3,081; makefile: 2
file content (1064 lines) | stat: -rw-r--r-- 24,606 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
package Parse::Method::Signatures;

use Moose;
use MooseX::Types::Moose qw/
  ArrayRef HashRef ScalarRef CodeRef Int Str ClassName
/;

use Class::Load qw(load_class);
use PPI;
use Moose::Util::TypeConstraints;
use Parse::Method::Signatures::ParamCollection;
use Parse::Method::Signatures::Types qw/
  PositionalParam NamedParam UnpackedParam
/;

use Carp qw/croak/;

use namespace::clean -except => 'meta';
our $VERSION = '1.003019';
$VERSION = eval $VERSION;
our $ERROR_LEVEL = 0;
our %LEXTABLE;
our $DEBUG = $ENV{PMS_DEBUG} || 0;

# Setup what we need for specific PPI subclasses
@PPI::Token::EOF::ISA = 'PPI::Token';

class_type "PPI::Document";
class_type "PPI::Element";

has 'input' => (
    is       => 'ro',
    isa      => Str,
    required => 1
);

has 'offset' => (
    is      => 'rw',
    isa     => Int,
    default => 0,
);

has 'signature_class' => (
    is      => 'ro',
    isa     => Str,
    default => 'Parse::Method::Signatures::Sig',
);

has 'param_class' => (
    is      => 'ro',
    isa     => Str,
    default => 'Parse::Method::Signatures::Param',
);

has 'type_constraint_class' => (
    is      => 'ro',
    isa     => Str,
    default => 'Parse::Method::Signatures::TypeConstraint',
);

has 'type_constraint_callback' => (
    is        => 'ro',
    isa       => CodeRef,
    predicate => 'has_type_constraint_callback',
);

has 'from_namespace' => (
    is        => 'rw',
    isa       => ClassName,
    predicate => 'has_from_namespace'
);

has 'ppi_doc' => (
    is => 'ro',
    isa => 'PPI::Document',
    lazy_build => 1,
    builder => 'parse',
);

# A bit dirty, but we set this with local most of the time
has 'ppi' => (
    is => 'ro',
    isa => 'PPI::Element',
    lazy_build => 1,
    writer => '_set_ppi'
);

sub BUILD {
    my ($self) = @_;

    load_class($_)
        for map { $self->$_ } qw/
            signature_class
            param_class
            type_constraint_class
        /;

    my $ppi = $self->ppi;

    # Skip leading whitespace
    $self->consume_token
      unless $ppi->significant;
}

sub create_param {
    my ($self, $args) = @_;

    my @traits;
    push @traits, $args->{ variable_name } ? 'Bindable' : 'Placeholder'
        if !exists $args->{unpacking};
    push @traits, $args->{ named         } ? 'Named'    : 'Positional';
    push @traits, 'Unpacked::' . $args->{unpacking}
        if exists $args->{unpacking};

    return $self->param_class->new_with_traits(traits => \@traits, %{ $args });
}

override BUILDARGS => sub {
  my $class = shift;

  return { input => $_[0] } if @_ == 1 and !ref $_[0];

  return super();
};

sub parse {
  my ($self) = @_;
  
  my $input = substr($self->input, $self->offset);
  my $doc = PPI::Document->new(\$input);

  # Append the magic EOF Token
  $doc->add_element(PPI::Token::EOF->new(""));

  # Annoyingly "m($x)" gets treated as a regex operator. This isn't what we 
  # want. so replace it with a Word, then a list. The way we do this is by
  # taking the operator off the front, then reparsing the rest of the content
  # This will look the same (so wont affect anything in a code block) but is
  # just store different token wise.
  $self->_replace_regexps($doc);

  # ($, $x) parses the $, as a single var. not what we want. FIX UP
  # While we're att it lets fixup $: $? and $!
  $self->_replace_magic($doc);

  # (Str :$x) yields a label of "Str :"
  # (Foo Bar :$x) yields a label of "Bar :"
  $self->_replace_labels($doc);

  # This one is actually a bug in PPI, rather than just an oddity
  # (Str $x = 0xfF) parses as "Oxf" and a word of "F"
  $self->_fixup_hex($doc);

  return $doc;
}

sub _replace_regexps {
  my ($self, $doc) = @_;

  REGEXP:
  foreach my $node ( @{ $doc->find('Token::Regexp') || [] } ) {
    my $str = $node->content;

    next REGEXP unless defined $node->{operator};

    # Rather annoyingly, there are *no* methods on Token::Regexp;
    my ($word, $rest) = $str =~ /^(\Q@{[$node->{operator}]}\E)(.*)$/s;

    my $subdoc = PPI::Document->new(\$rest);
    my @to_add = reverse map { $_->remove } $subdoc->children;
    push @to_add, new PPI::Token::Word($word);
    # insert_after restricts what you can insert.
    # $node->insert_after($_) for @to_add;
    $node->__insert_after($_) for @to_add;

    $node->delete;
  }
}


sub _replace_magic {
  my ($self, $doc) = @_;

  foreach my $node ( @{ $doc->find('Token::Magic') || [] } ) {
    my ($op) = $node->content =~ /^\$([,?:!)])$/ or next;

    $node->insert_after(new PPI::Token::Operator($op));
    $node->insert_after(new PPI::Token::Cast('$'));
    $node->delete;
  }
}

sub _replace_labels {
  my ($self, $doc) = @_;

  foreach my $node ( @{ $doc->find('Token::Label') || [] } ) {
    my ($word, $ws) = $node->content =~ /^(.*?)(\s+)?:$/s or next;

    $node->insert_after(new PPI::Token::Operator(':'));
    $node->insert_after(new PPI::Token::Whitespace($ws)) if defined $ws;
    $node->insert_after(new PPI::Token::Word($word));
    $node->delete;
  }
}

sub _fixup_hex {
  my ($self, $doc) = @_;

  foreach my $node ( @{ $doc->find('Token::Number::Hex') || [] } ) {
    my $next = $node->next_token;
    next unless $next->isa('PPI::Token::Word') 
             && $next->content =~ /^[0-9a-f]+$/i;

    $node->add_content($next->content);
    $next->delete;
  }
}

sub _build_ppi {
  my ($self) = @_;
  my $ppi = $self->ppi_doc->first_token;

  if ($ppi->class eq 'PPI::Token::Word' && exists $LEXTABLE{"$ppi"}) {
    bless $ppi, "PPI::Token::LexSymbol";
    $ppi->{lex} = $LEXTABLE{"$ppi"};
  }
  return $ppi;
}

# signature: O_PAREN
#            invocant
#            params
#            C_PAREN
#
# invocant: param ':'
#
# params: param COMMA params
#       | param
#       | /* NUL */
sub signature {
  my $self = shift;

  $self = $self->new(@_) unless blessed($self);

  $self->assert_token('(');

  my $args = {};
  my $params = [];

  my $param = $self->param;

  if ($param && $self->ppi->content eq ':') {
    # That param was actually the invocant
    $args->{invocant} = $param;
    croak "Invocant cannot be named"
      if NamedParam->check($param);
    croak "Invocant cannot be optional"
      if !$param->required;
    croak "Invocant cannot have a default value"
      if $param->has_default_value;

    croak "Invocant must be a simple scalar"
      if UnpackedParam->check($param) || $param->sigil ne '$';

    $self->consume_token;
    $param = $self->param;

  }

  if ($param) {
    push @$params, $param;

    my $greedy = $param->sigil ne '$' ? $param : undef;
    my $opt_pos_param = !$param->required;

    while ($self->ppi->content eq ',') {
      $self->consume_token;

      my $err_ctx = $self->ppi;
      $param = $self->param;
      $self->error($err_ctx, "Parameter expected")
        if !$param;

      my $is_named = NamedParam->check($param);
      if (!$is_named) {
        if ($param->required && $opt_pos_param) {
          $self->error($err_ctx, "Invalid: Required positional param " .
            " found after optional one");
        }
        if ($greedy) {
          croak "Invalid: Un-named parameter '" . $param->variable_name
            . "' after greedy '" 
            . $greedy->variable_name . "'\n";
        }
      }

      push @$params, $param;
      $opt_pos_param = $opt_pos_param || !$param->required;
      $greedy = $param->sigil ne '$' ? $param : undef;
    }
  }

  $self->assert_token(')');
  $args->{params} = $params;

  my $sig = $self->signature_class->new($args);

  return $sig;
}


# param: tc?
#        var
#        (OPTIONAL|REQUIRED)?
#        default?
#        where*
#        trait*
#
# where: WHERE <code block>
#
# trait: TRAIT class
#
# var : COLON label '(' var_or_unpack ')' # label is classish, with only /a-z0-9_/i allowed
#     | COLON VAR
#     | var_or_unpack
#
# var_or_unpack : '[' param* ']' # should all be required + un-named
#               | '{' param* '}' # Should all be named
#               | VAR
#
# OPTIONAL: '?'
# REQUIRED: '!'
sub param {
  my $self = shift;
  my $class_meth;
  unless (blessed($self)) {
    $self = $self->new(@_) unless blessed($self);
    $class_meth = 1;
  }

  # Also used to check if a anything has been consumed
  my $err_ctx = $self->ppi;

  my $param = {
    required => 1,
  };

  $self->_param_typed($param);

  $self->_param_opt_or_req(
    $self->_param_labeled($param)
      || $self->_param_named($param)
      || $self->_param_variable($param)
      || $self->_unpacked_param($param)
  ) or ($err_ctx == $self->ppi and return)
    or $self->error($err_ctx);

  $self->_param_default($param);
  $self->_param_constraint_or_traits($param);

  $param = $self->create_param($param);

  return !$class_meth
      ? $param
      : wantarray
      ? ($param, $self->remaining_input)
      : $param;
}

sub _param_opt_or_req {
  my ($self, $param) = @_;

  return unless $param;

  if ($self->ppi->class eq 'PPI::Token::Operator') {
    my $c = $self->ppi->content;
    if ($c eq '?') {
      $param->{required} = 0;
      $self->consume_token;
    } elsif ($c eq '!') {
      $param->{required} = 1;
      $self->consume_token;
    }
  }
  return $param;

}

sub _param_constraint_or_traits {
  my ($self, $param) = @_;

  while ($self->_param_where($param) ||
         $self->_param_traits($param) ) {
    # No op;

  }
  return $param;
}

sub _param_where {
  my ($self, $param) = @_;

  return unless $self->ppi->isa('PPI::Token::LexSymbol')
             && $self->ppi->lex eq 'WHERE';

  $self->consume_token;

  $param->{constraints} ||= [];

  my $ppi = $self->ppi;

  $self->error($ppi, "Block expected after where")
    unless $ppi->class eq 'PPI::Token::Structure'
        && $ppi->content eq '{';

  # Go from token to block
  $ppi = $ppi->parent;

  $ppi->finish or $self->error($ppi, 
    "Runaway '" . $ppi->braces . "' in " . $self->_parsing_area(1), 1);

  push @{$param->{constraints}}, $ppi->content;

  $self->_set_ppi($ppi->finish);
  $self->consume_token;
  return $param;
}

sub _param_traits {
  my ($self, $param) = @_;
  return unless $self->ppi->isa('PPI::Token::LexSymbol')
             && $self->ppi->lex eq 'TRAIT';

  my $op = $self->consume_token->content;

  $self->error($self->ppi, "Error parsing parameter trait")
    unless $self->ppi->isa('PPI::Token::Word');

  $param->{param_traits} ||= [];

  push @{$param->{param_traits}}, [$op, $self->consume_token->content];
  return $param;
}

sub _param_labeled {
  my ($self, $param) = @_;

  return unless 
    $self->ppi->content eq ':' &&
    $self->ppi->next_token->isa('PPI::Token::Word');

  $self->consume_token;

  $self->error($self->ppi, "Invalid label")
    if $self->ppi->content =~ /[^-\w]/;

  $param->{named} = 1;
  $param->{required} = 0;
  $param->{label} = $self->consume_token->content;

  $self->assert_token('(');
  $self->_unpacked_param($param) 
    || $self->_param_variable($param)
    || $self->error($self->ppi);

  $self->assert_token(')');

  return $param;
}

sub _unpacked_param {
  my ($self, $param) = @_;

  return $self->bracketed('[', \&unpacked_array, $param) ||
         $self->bracketed('{', \&unpacked_hash, $param);
}

sub _param_named {
  my ($self, $param) = @_;

  return unless
    $self->ppi->content eq ':' &&
    $self->ppi->next_token->isa('PPI::Token::Symbol');

  $param->{required} = 0;
  $param->{named} = 1;
  $self->consume_token;

  my $err_ctx = $self->ppi;
  $param = $self->_param_variable($param);

  $self->error($err_ctx, "Arrays or hashes cannot be named")
    if $param->{sigil} ne '$';

  return $param;
}

sub _param_typed {
  my ($self, $param) = @_;

  my $tc = $self->tc
    or return;


  $tc = $self->type_constraint_class->new(
    ppi  => $tc,
    ( $self->has_type_constraint_callback
      ? (tc_callback => $self->type_constraint_callback)
      : ()
    ),
    ( $self->has_from_namespace
      ? ( from_namespace => $self->from_namespace )
      : ()
    ),
  );
  $param->{type_constraints} = $tc;

  return $param;
}
 
sub _param_default {
  my ($self, $param) = @_;

  return unless $self->ppi->content eq '=';

  $self->consume_token;

  $param->{default_value} =
    $self->_consume_if_isa(qw/
      PPI::Token::QuoteLike
      PPI::Token::Number
      PPI::Token::Quote
      PPI::Token::Symbol
      PPI::Token::Magic
      PPI::Token::ArrayIndex
    /) ||
    $self->bracketed('[') ||
    $self->bracketed('{') 
  or $self->error($self->ppi);
    
  $param->{default_value} = $param->{default_value}->content;
}


sub _param_variable {
  my ($self, $param) = @_;

  my $ppi = $self->ppi;
  my $class = $ppi->class;
  return unless $class eq 'PPI::Token::Symbol'
             || $class eq 'PPI::Token::Cast';

  if ($class eq 'PPI::Token::Symbol') {
    $ppi->symbol_type eq $ppi->raw_type or $self->error($ppi);

    $param->{sigil} = $ppi->raw_type;
    $param->{variable_name} = $self->consume_token->content;
  } else {
    $param->{sigil} = $self->consume_token->content;
  }

  return $param;
}

sub unpacked_hash {
  my ($self, $list, $param) = @_;

  my $params = [];
  while ($self->ppi->content ne '}') {
    my $errctx = $self->ppi;
    my $p = $self->param
      or $self->error($self->ppi);

    $self->error($errctx, "Cannot have positional parameters in an unpacked-array")
      if $p->sigil eq '$' && PositionalParam->check($p);
    push @$params, $p;

    last if $self->ppi->content eq '}';
    $self->assert_token(',');
  }
  $param->{params} = $params;
  $param->{sigil} = '$';
  $param->{unpacking} = 'Hash';
  return $param;
}

sub unpacked_array {
  my ($self, $list, $param) = @_;

  my $params = [];
  while ($self->ppi->content ne ']') {
    my $watermark = $self->ppi;
    my $param = $self->param
      or $self->error($self->ppi);

    $self->error($watermark, "Cannot have named parameters in an unpacked-array")
      if NamedParam->check($param);

    $self->error($watermark, "Cannot have optional parameters in an unpacked-array")
      unless $param->required;

    push @$params, $param;

    last if $self->ppi->content eq ']';
    $self->assert_token(',');
  }
  $param->{params} = $params;
  $param->{sigil} = '$';
  $param->{unpacking} = 'Array';
  return $param;
}

sub tc {
  my ($self, $required) = @_;

  my $ident = $self->_ident;

  $ident or ($required and $self->error($self->ppi)) or return;

  return $self->_tc_union(
    $self->bracketed('[', \&_tc_params, $ident)
      || $ident->clone
  );
}

# Handle parameterized TCs. e.g.:
# ArrayRef[Str]
# Dict[Str => Str]
# Dict["foo bar", Baz]
sub _tc_params {
  my ($self, $list, $tc) = @_;

  my $new = PPI::Statement::Expression::TCParams->new($tc->clone);

  return $new if $self->ppi->content eq ']';

  $new->add_element($self->_tc_param);

  while ($self->ppi->content =~ /^,|=>$/ ) {

    my $op = $self->consume_token;
    $self->_stringify_last($new) if $op->content eq '=>';

    $new->add_element($self->tc(1));
  }

  return $new;
}

# Valid token for individual component of parameterized TC
sub _tc_param {
  my ($self) = @_;

  (my $class = $self->ppi->class) =~ s/^PPI:://;
  return $self->consume_token->clone
      if $class eq 'Token::Number' ||
         $class =~ /^Token::Quote::(?:Single|Double|Literal|Interpolate)/;

  return $self->tc(1);
}

sub _tc_union {
  my ($self, $tc) = @_;
  
  return $tc unless $self->ppi->content eq '|';

  my $union = PPI::Statement::Expression::TCUnion->new;
  $union->add_element($tc);
  while ( $self->ppi->content eq '|' ) {
   
    $self->consume_token;
    $union->add_element($self->tc(1));
  }

  return $union;
}

# Stringify LHS of fat comma
sub _stringify_last {
  my ($self, $list) = @_;
  my $last = $list->last_token;
  return unless $last->isa('PPI::Token::Word');

  # Is this conditional on the content of the word?
  bless $last, "PPI::Token::StringifiedWord";
  return $list;
}

# Handle the boring bits of bracketed product, then call $code->($self, ...) 
sub bracketed {
  my ($self, $type, $code, @args) = @_;

  local $ERROR_LEVEL = $ERROR_LEVEL + 1;
  my $ppi = $self->ppi;
  return unless $ppi->content eq $type;

  $self->consume_token; # consume '[';

  # Get from the '[' token the to Strucure::Constructor 
  $ppi = $ppi->parent;

  $ppi->finish or $self->error($ppi, 
    "Runaway '" . $ppi->braces . "' in " . $self->_parsing_area(1), 1);


  my $ret;
  if ($code) {
    my $list = PPI::Structure::Constructor->new($ppi->start->clone);
    $ret = $code->($self, $list, @args);

    $self->error($self->ppi)
      if $self->ppi != $ppi->finish;

    # There is no public way to do this as of PPI 1.204_06. I'll add one to the
    # next release, 1.205 (or so)
    $list->{finish} = $self->consume_token->clone;
  } else {
    # Just clone the entire [] or {}
    $ret = $ppi->clone;
    $self->_set_ppi($ppi->finish);
    $self->consume_token;
  }

  return $ret;
}

# Work out what sort of production we are in for sane default error messages
sub _parsing_area { 
  shift;
  my $height = shift || 0;
  my (undef, undef, undef, $sub) = caller($height+$ERROR_LEVEL);

  return "type constraint" if $sub =~ /(?:\b|_)tc(?:\b|_)/;
  return "unpacked parameter"      
                           if $sub =~ /(?:\b|_)unpacked(?:\b|_)/;
  return "parameter"       if $sub =~ /(?:\b|_)param(?:\b|_)/;
  return "signature"       if $sub =~ /(?:\b|_)signature(?:\b|_)/;

  " unknown production ($sub)";
}

# error(PPI::Token $token, Str $msg?, Bool $no_in = 0)
sub error {
  my ($self, $token, $msg, $no_in) = @_;

  $msg = "Error parsing " . $self->_parsing_area(2)
    unless ($msg);


  $msg = $msg . " near '$token'" . 
        ($no_in ? ""
                : " in '" . $token->statement . "'" 
        );

  if ($DEBUG) {
    Carp::confess($msg);
  } else {
    Carp::croak($msg);
  }
}

sub assert_token {
  my ($self, $need, $msg) = @_;

  if ($self->ppi->content ne $need) {
    $self->error($self->ppi, "'$need' expected whilst parsing " . $self->_parsing_area(2));
  }
  return $self->consume_token;
}


%LEXTABLE = (
  where => 'WHERE',
  is    => 'TRAIT',
  does  => 'TRAIT',
);

sub _ident {
  my ($self) = @_;

  my $ppi = $self->ppi;
  return $self->consume_token
    if $ppi->class eq 'PPI::Token::Word';
  return undef;
}

sub _consume_if_isa {
  my ($self, @classes) = @_;

  for (@classes) {
    return $self->consume_token
      if $self->ppi->isa($_);
  }

}

sub consume_token {
  my ($self) = @_;

  my $ppi = $self->ppi;
  my $ret = $ppi;

  while (!$ppi->isa('PPI::Token::EOF') ) {
    $ppi = $ppi->next_token;
    last if $ppi->significant;
  }

  if ($ppi->class eq 'PPI::Token::Word' && exists $LEXTABLE{"$ppi"}) {
    bless $ppi, "PPI::Token::LexSymbol";
    $ppi->{lex} = $LEXTABLE{"$ppi"};
  }
  $self->_set_ppi( $ppi );
  return $ret;
}

sub remaining_input {
  my $tok = $_[0]->ppi;
  my $buff;

  while ( !$tok->isa('PPI::Token::EOF') ) {
    $buff .= $tok->content;
    $tok = $tok->next_token;
  }
  return $buff;
}

__PACKAGE__->meta->make_immutable;


# Extra PPI classes to represent what we want.
{ package 
    PPI::Statement::Expression::TCUnion;
  use base 'PPI::Statement::Expression';

  sub content {
    join('|', $_[0]->children );
  }
}

{ package 
    PPI::Statement::Expression::TCParams;
    
  use base 'PPI::Statement::Expression';
  use Moose;

  # $self->children stores everything so PPI can track parents
  # params just contains the keywords (not commas) inside the []
  has type => ( is => 'ro');
  has params => ( 
    is => 'ro',
    default => sub { [] },
  );

  sub new {
    my ($class, $type) = @_;

    return $class->meta->new_object(
      __INSTANCE__ => $class->SUPER::new($type),
      type => $type
    );
  };

  override add_element => sub {
    my ($self, $ele) = @_;
    super();
    push @{$self->params}, $ele;
  };

  sub content { 
    $_[0]->type->content . '[' . join(',', @{$_[0]->params}) . ']'
  }

  no Moose;
}

{ package 
    PPI::Token::LexSymbol;
  use base 'PPI::Token::Word';

  sub lex {
    my ($self) = @_;
    return $self->{lex}
  }
}

# Used for LHS of fat comma
{ package
    PPI::Token::StringifiedWord;
  use base 'PPI::Token::Word'; 

  use Moose;
  override content => sub {
    return '"' . super() . '"';
  };

  sub string {
    return $_[0]->PPI::Token::Word::content();
  }
  no Moose;
}

1;

__END__

=head1 NAME

Parse::Method::Signatures - Perl6 like method signature parser

=head1 DESCRIPTION

Inspired by L<Perl6::Signature> but streamlined to just support the subset
deemed useful for L<TryCatch> and L<MooseX::Method::Signatures>.

=head1 TODO

=over

=item * Document the parameter return types.

=item * Probably lots of other things

=back

=head1 METHODS

There are only two public methods to this module, both of which should be
called as class methods. Both methods accept  either a single (non-ref) scalar
as the value for the L</input> attribute, or normal new style arguments (hash
or hash-ref).

=head2 signature

 my $sig = Parse::Method::Signatures->signature( '(Str $foo)' )

Attempts to parse the (bracketed) method signature. Returns a value or croaks
on error.

=head2 param

  my $param = Parse::Method::Signatures->param( 'Str $foo where { length($_) < 10 }')

Attempts to parse the specification for a single parameter. Returns value or
croaks on error.

=head1 ATTRIBUTES

All the attributes on this class are read-only.

=head2 input

B<Type:> Str

The string to parse.

=head2 offset

B<Type:> Int

Offset into L</input> at which to start parsing. Useful for using with
Devel::Declare linestring

=head2 signature_class

B<Default:> Parse::Method::Signatures::Sig

B<Type:> Str (loaded on demand class name)

=head2 param_class

B<Default:> Parse::Method::Signatures::Param

B<Type:> Str (loaded on demand class name)

=head2 type_constraint_class

B<Default:> L<Parse::Method::Signatures::TypeConstraint>

B<Type:> Str (loaded on demand class name)

Class that is used to turn the parsed type constraint into an actual
L<Moose::Meta::TypeConstraint> object.

=head2 from_namespace

B<Type:> ClassName

Let this module know which package it is parsing signatures form. This is
entirely optional, and the only effect is has is on parsing type constraints.

If this attribute is set it is passed to L</type_constraint_class> which can
use it to introspect the package (commonly for L<MooseX::Types> exported
types). See
L<Parse::Method::Signature::TypeConstraints/find_registered_constraint> for
more details.

=head2 type_constraint_callback

B<Type:> CodeRef

Passed to the constructor of L</type_constraint_class>. Default implementation
of this callback asks Moose for a type constrain matching the name passed in.
If you have more complex requirements, such as parsing types created by
L<MooseX::Types> then you will want a callback similar to this:

 # my $target_package defined elsewhere.
 my $tc_cb = sub {
   my ($pms_tc, $name) = @_;
   my $code = $target_package->can($name);
   $code ? eval { $code->() } 
         : $pms_tc->find_registered_constraint($name);
 }

Note that the above example is better provided by providing the
L</from_namespace> attribute.

=head1 CAVEATS

Like Perl6::Signature, the parsing of certain constructs is currently only a
'best effort' - specifically default values and where code blocks might not
successfully for certain complex cases. Patches/Failing tests welcome.

Additionally, default value specifications are not evaluated which means that
no such lexical or similar errors will not be produced by this module.
Constant folding will also not be performed.

There are certain constructs that are simply too much hassle to avoid when the
work around is simple. Currently the only cases that are known to parse wrong
are when using anonymous variables (i.e. just sigils) in unpacked arrays. Take
the following example:

 method foo (ArrayRef [$, $], $some_value_we_care_about) {

In this case the C<$]> is treated as one of perl's magic variables
(specifically, the patch level of the Perl interpreter) rather than a C<$>
followed by a C<]> as was almost certainly intended. The work around for this
is simple: introduce a space between the characters:

 method foo (ArrayRef [ $, $ ], $some_value_we_care_about) {

The same applies

=head1 AUTHOR

Ash Berlin <ash@cpan.org>.

Thanks to Florian Ragwitz <rafl@debian.org>.

Many thanks to Piers Cawley to showing me the way to refactor my spaghetti
code into something more manageable.

=head1 SEE ALSO

L<Devel::Declare> which is used by most modules that use this (currently by
all modules known to the author.)

L<http://github.com/ashb/trycatch/tree>.

=head1 LICENSE

Licensed under the same terms as Perl itself.

This distribution copyright 2008-2009, Ash Berlin <ash@cpan.org>