Skip to content

Commit

Permalink
Catch wrong attribute usage in a regex.
Browse files Browse the repository at this point in the history
Regexes are methods on Cursor (or some subclass of it), meaning that
an attribute access inside of them is relative to that. Rather than
failing silently or exploding noisily at runtime, catch the problem at
compile time. The typed exception's message explains the issue and
offers a suggestion; wording tweaks welcome.
  • Loading branch information
jnthn committed Mar 11, 2015
1 parent 7b153f5 commit 858ac4e
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 2 deletions.
26 changes: 24 additions & 2 deletions src/Perl6/Grammar.nqp
Expand Up @@ -4923,7 +4923,25 @@ grammar Perl6::QGrammar is HLL::Grammar does STD {
}
}

grammar Perl6::RegexGrammar is QRegex::P6Regex::Grammar does STD {
my role CursorPackageNibbler {
method nibble-in-cursor($parent) {
my $*PACKAGE := $*W.find_symbol(['Cursor']);
my %*ATTR_USAGES;
my $cur := nqp::findmethod($parent, 'nibbler')(self);
for %*ATTR_USAGES {
my $name := $_.key;
my $node := $_.value[0].node;
$node.CURSOR.typed_sorry('X::Attribute::Regex', symbol => $name);
}
$cur
}
}

grammar Perl6::RegexGrammar is QRegex::P6Regex::Grammar does STD does CursorPackageNibbler {
method nibbler() {
self.nibble-in-cursor(QRegex::P6Regex::Grammar)
}

method throw_unrecognized_metachar ($metachar) {
self.typed_sorry('X::Syntax::Regex::UnrecognizedMetachar', :$metachar);
}
Expand Down Expand Up @@ -5016,7 +5034,11 @@ grammar Perl6::RegexGrammar is QRegex::P6Regex::Grammar does STD {
}
}

grammar Perl6::P5RegexGrammar is QRegex::P5Regex::Grammar does STD {
grammar Perl6::P5RegexGrammar is QRegex::P5Regex::Grammar does STD does CursorPackageNibbler {
method nibbler() {
self.nibble-in-cursor(QRegex::P5Regex::Grammar)
}

token rxstopper { <stopper> }

token p5metachar:sym<(?{ })> {
Expand Down
7 changes: 7 additions & 0 deletions src/core/Exception.pm
Expand Up @@ -583,6 +583,13 @@ my class X::Attribute::Undeclared is X::Undeclared {
}
}

my class X::Attribute::Regex is X::Undeclared {
method message() {
"Attribute $.symbol not available inside of a regex, since regexes are methods on Cursor.\n" ~
"Consider storing the attribute in a lexical, and using that in the regex.";
}
}

my class X::Undeclared::Symbols does X::Comp {
has %.post_types;
has %.unk_types;
Expand Down
1 change: 1 addition & 0 deletions src/core/core_prologue.pm
Expand Up @@ -5,6 +5,7 @@ my class Pair { ... }
my class Whatever { ... }
my class HyperWhatever { ... }
my class WhateverCode { ... }
my class Cursor { ... }

# Stub these or we can't use any sigil other than $.
my role Positional { ... }
Expand Down

0 comments on commit 858ac4e

Please sign in to comment.