Perl Moose TypeDecorator错误。如何调试?

3
最近我遇到了一个问题,非常感谢你提供任何洞察力。我之前在PerlMonks上发过类似的问题,并得到反馈建议更换MooseX :: Declare([http://www.perlmonks.org/?node_id=877703][1])。现在,我已经将代码切换到使用Moose和MooseX :: Types以及MooseX :: Params :: Validate。然而,在相同的位置发生了同样的错误。这并不奇怪,因为它看起来与MooseX :: Types有关。
我收到了以下错误消息(为了易读性尝试进行了间距处理,并截断了堆栈底部):
plxc16479> tmp10.pl

Argument cannot be 'name' at /nfs/pdx/disks/nehalem.pde.077/perl/lib64/site_perl/MooseX/Types/TypeDecorator.pm line 88

MooseX::Types::TypeDecorator::new('MooseX::Types::TypeDecorator=HASH(0x1620c58)', 'name', 'g1145114N5582201_16161616a2x_FU02xxT_2bxc2e3_6x0xxxp0fx0xxx0x...', 'mask_data', '', 'tags', 0) called at /nfs/pdx/disks/nehalem.pde.077/projects/lib/Program-Plist-Pl/lib/Program/Plist/Pl.pm line 61

Program::Plist::Pl::_create_pattern_obj(undef, 'name', 'g1145114N5582201_16161616a2x_FU02xxT_2bxc2e3_6x0xxxp0fx0xxx0x...', 'mask_data', '', 'tag_data', '') called at /nfs/pdx/disks/nehalem.pde.077/projects/lib/Program-Plist-Pl/lib/Program/Plist/Pl.pm line 77

Program::Plist::Pl::BUILD('Program::Plist::Pl=HASH(0x162d6c0)', 'HASH(0x162d648)') called at generated method (unknown origin) line 101

Program::Plist::Pl::new('Program::Plist::Pl', 'name', 'bist_hfmmin_16161616_list', 'parents', 'HASH(0xccf040)', 'fh', 'GLOB(0xccc928)', 'external_pl_code', 'CODE(0x14910b0)', ...) called at /nfs/pdx/disks/nehalem.pde.077/projects/lib/Program-Roles-PlHandler/lib/Program/Roles/PlHandler.pm line 52

Program::Roles::PlHandler::_create_global_pl_obj(undef, 'name', 'bist_hfmmin_16161616_list', 'parents', 'HASH(0xccf040)', 'fh', 'GLOB(0xccc928)') called at /nfs/pdx/disks/nehalem.pde.077/projects/lib/Program-Plist-Pl/lib/Program/Plist/Pl.pm line 77

Program::Plist::Pl::BUILD('Program::Plist::Pl=HASH(0xccd300)', 'HASH(0xccc628)') called at generated method (unknown origin) line 101

Program::Plist::Pl::new('Program::Plist::Pl', 'name', 'bist_list', 'parents', 'HASH(0xccce80)', 'fh', 'GLOB(0xccc928)', 'external_pl_code', 'CODE(0x14910b0)', ...) called at /nfs/pdx/disks/nehalem.pde.077/projects/lib/Program-Roles-PlHandler/lib/Program/Roles/PlHandler.pm line 52

问题似乎出在TypeDecorator::new的顶层调用上。TypeDecorator构造函数似乎期望两个参数,即类/自身参数和对TypeDecorator或TypeConstraint对象的引用。但实际上,它以某种方式接收了来自我的创建模式对象调用的参数。我已经验证了传入_create_pattern_obj函数的参数是正确的,并且传入Pattern->new调用的参数也是正确的(通过堆栈跟踪的参数证明)。_create_pattern_obj函数如下:
sub _create_pattern_obj {
    my ($self, $name, $mask_data, $tag_data) = validated_list(\@_,
                                                              name => {isa => Str},
                                                              mask_data => {isa => Str, optional => 1},
                                                              tag_data => {isa => Str, optional => 1});

    $mask_data = '' if !defined $mask_data;

    my $tags = defined $tag_data ? map {$_ => 1} split(',', $tag_data) : {};

    my $pattern_obj = Program::Plist::Pl::Pattern->new(name => $name,
                                                       mask_data => $mask_data,
                                                       tags => $tags);
    $self->_add_pattern($pattern_obj);
}

这个函数在调用Program::Plist::Pl::Pattern->new时出现了错误,这行代码在Pl.pm文件中的第61行,在上面的调用栈中引用了TypeDecorator::new。

Pattern类是:

package Program::Plist::Pl::Pattern;

use 5.012002;
our $VERSION = sprintf "2.%03d", q($Revision: 473 $) =~ /: (\d+)/;

use Moose;
use namespace::autoclean;

use MooseX::Types::Moose qw(Str Num Int HashRef);
use MooseX::Params::Validate;

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

has 'tuple' => (isa => Int,
                is => 'ro');

has 'tid' => (isa => Int,
              is => 'ro');

has 'weight' => (isa => Num,
                 is => 'ro');

has 'tags' => (isa => HashRef[Str],
               is => 'ro',
               default => sub {{}});

has 'mask_data' => (isa => Str,
                    is => 'rw',
                    default => '',
                    writer => '_set_mask_data');

sub has_tag {
    my ($self, $tag) = (shift,
                        pos_validated_list(\@_, {isa => Str}));

    exists $self->{tags}->{$tag} ? return 1 : return 0;
}

sub _add_tag {
    my ($self, $tag) = (shift,
                        pos_validated_list(\@_, {isa => Str}));
    $self->{tags}->{$tag} = 1;
}

sub BUILDARGS {
    print STDERR 'CALLED '.__PACKAGE__."BUILDARGS\n";
    print STDERR 'ARGUMENTS:'.join(',', @_)."\n";
}

sub BUILD {
    my ($self) = @_;
    print STDERR 'CALLED '.__PACKAGE__."::BUILD\n";
}

__PACKAGE__->meta->make_immutable;

1;

一些迹象表明,从调用堆栈的参数来看,我的 Pattern->new 调用的参数最终被传递到 TypeDecorator::new 调用中,并且它卡在了这些参数上。我已经验证了对此子例程的良好调用(从较早的堆栈跟踪中),如下所示(请注意两个参数):
DB <1> T $ = MooseX :: Types :: TypeDecorator :: new('MooseX :: Types :: TypeDecorator',ref(Moose :: Meta :: TypeConstraint))从文件 `/nfs/pdx/disks/nehalem.pde.077/perl/lib64/site_perl/MooseX/Types.pm' 第 464 行调用
问题在于我无法弄清楚发生了什么。当通过代码进行步进时,执行直接从 Pattern->new 调用传递到 TypeDecorator 代码。这发生在任何我的类代码执行之前。我知道 Moose 正在为我创建新方法,但我无法调试我无法查看的代码。
我查阅了 Moose 的文档,但那都是关于如何使用它而不是底层发生了什么的。我确实阅读了 Class::MOP 的文档,但我不清楚这段代码究竟在哪里创建以及何时创建。虽然我从所有研究中学到了很多东西,但没有一件事可以直接帮助我解决问题 :)
首先,如果您有任何想法,请告诉我发生了什么。其次,我该如何调试此问题?我的所有常规调试工具都让我失望了!执行直接从我的 new 调用跳转到问题代码,我似乎无法追踪 TypeDecorator::new 参数实际上是从哪里传递过来的。最后,是否有任何关于 Moose 如何做到这一点的好文章?或 Class::MOP?
编辑-以下是我的类型定义。我可能会补充说,这是我第一次涉足 Moose,因此,如果您发现我做的事情有些奇怪,请随时指出。
package Program::Types;

use 5.012002;
use strict;
use warnings;

our $VERSION = sprintf "2.%03d", q($Revision: 473 $) =~ /: (\d+)/;

# predeclare types
use MooseX::Types
-declare => [qw(NonemptyStr FilePath DirectoryPath FilePathThatExists DirectoryPathThatExists
                TwoDigNum Pl LocalPl Pattern Program_Env Program_Whichload Program_Tpl
                Program_Plist Program_Bmfc Program_Tpl_Test Program_Tpl_Flow
                Program_Tpl_Flow_Item Program_Tpl_Flow_Item_Result Word)];

# import some MooseX builtin types that will be built on
use MooseX::Types::Moose qw(Str Int Object);

# types base on some objects that I use
class_type Pl, {class => 'Program::Plist::Pl'};

class_type LocalPl, {class => 'Program::Plist::LocalPl'};

class_type Pattern, {class => 'Program::Plist::Pl::Pattern'};

class_type Program_Env, {class => 'Program::Env'};

class_type Program_Whichload, {class => 'Program::Whichload'};

class_type Program_Tpl, {class => 'Program::Tpl'};

class_type Program_Tpl_Test, {class => 'Program::Tpl::Test'};

class_type Program_Tpl_Flow, {class => 'Program::Tpl::Flow'};

class_type Program_Tpl_Flow_Item, {class => 'Program::Tpl::Flow::Item'};

class_type Program_Tpl_Flow_Item_Result, {class => 'Program::Tpl::Flow::Item::Result'};

class_type Program_Plist, {class => 'Program::Plist'};

class_type Program_Bmfc, {class => 'Program::Bmfc'};

subtype Word,
    as Str,
    where {$_ =~ /^\w*$/};

coerce Word,
    from Str,
    via {$_};

subtype NonemptyStr,
  as Str,
  where {$_ ne ''};

coerce NonemptyStr,
  from Str,
  via {$_};

subtype TwoDigNum,
  as Int,
  where {$_ =~ /^\d\d\z/},
  message {'TwoDigNum must be made of two digits.'};

coerce TwoDigNum,
  from Int,
  via {$_};

subtype FilePath,
  as Str,
  where {!($_ =~ /\0/)},
  message {'FilePath cannot contain a null character'};

coerce FilePath,
  from Str,
  via {$_};

subtype DirectoryPath,
  as Str,
  where {!($_ =~ /\0/)},
  message {'DirectoryPath cannot contain a null character'};

coerce DirectoryPath,
  from Str,
  via {$_};

subtype FilePathThatExists,
  as Str,
  where {(!($_ =~ /\0/) and -e $_)},
  message {'FilePathThatExists must reference a path to a valid existing file.'.
           "Path ($_)"};

coerce FilePathThatExists,
  from Str,
  via {$_};

coerce FilePathThatExists,
  from FilePath,
  via {$_};

subtype DirectoryPathThatExists,
  as FilePath,
  where {(!($_ =~ /\0/) and -d $_)},
  message {'DirectoryPathThatExists must reference a path to a valid existing '.
           "directory.  Path ($_)"};

coerce DirectoryPathThatExists,
  from Str,
  via {$_};

coerce DirectoryPathThatExists,
  from DirectoryPath,
  via {$_};

1;

编辑2--由于明显的操作错误而删除:)请注意,我在Pattern类中使用BUILDARGS而没有返回参数列表。在当前代码中,我已将其删除,但错误未更改。

Phaylon,这是Program::Plist::Pl类。

package Program::Plist::Pl;

use 5.012002;
our $VERSION = sprintf "2.%03d", q($Revision: 473 $) =~ /: (\d+)/;

use Moose;
use namespace::autoclean;

use Program::Plist::Pl::Pattern;
use Program::Types qw(Pl LocalPl TwoDigNum Pattern);
use Program::Utils qw(rchomp);

use MooseX::Types::Moose qw(HashRef GlobRef Str);
use MooseX::Params::Validate;

with 'Program::Roles::PlHandler';

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

has 'parents' => (isa => HashRef[Pl|LocalPl],
                  is => 'ro',
                  required => 1);

has 'children' => (isa => HashRef[Pl|LocalPl],
                   is => 'ro');

has 'prefixes' => (isa => HashRef[TwoDigNum],
                   is => 'ro',
                   default => sub{{}});

has 'patterns' => (isa => HashRef[Pattern],
                   is => 'ro',
                   default => sub{{}});

sub _add_child {
    my ($self, $obj) = (shift,
                        pos_validated_list(\@_, {isa => Pl|LocalPl}));
    $self->{children}->{$obj->name} = $obj;
}

sub _add_pattern {
    my ($self, $obj) = (shift,
                        pos_validated_list(\@_, {isa => Pattern}));
    $self->{patterns}->{$obj->name} = $obj;
}

sub _create_pattern_obj {
    $DB::single = 1;
    my ($self, $name, $mask_data, $tag_data) = validated_list(\@_,
                                                              name => {isa => Str},
                                                              mask_data => {isa => Str, optional => 1},
                                                              tag_data => {isa => Str, optional => 1});

    $mask_data = '' if !defined $mask_data;

    my $tags = defined $tag_data ? map {$_ => 1} split(',', $tag_data) : {};

    $DB::single = 1;
    my $pattern_obj = Program::Plist::Pl::Pattern->new(name => $name,
                                                       mask_data => $mask_data,
                                                       tags => $tags);
    $self->_add_pattern($pattern_obj);
}

sub BUILD {
    my ($self, $fh) = (shift,
                       pos_validated_list([$_[0]->{fh}], {isa => GlobRef}));

    while (<$fh>) {
        # skip empty or commented lines
        rchomp;
        next if ((/^\s*#/) or (/^\s*$/));

        # handle global plist declarations
        if (my @m = /^\s*GlobalPList\s+(\w+)/) {
            # creating new object and adding it to our data print STDERR
            #                    "SELF($self)\n".join("\n",sort keys
            #                    %Program::Plist::Pl::)."\n"; 
            $self->_create_global_pl_obj(name => $m[0],
                                         parents => {%{$self->parents},
                                                     $self->name => $self},
                                         fh => $fh);
        }

        # handle local referenced plist declarations
        elsif (@m = /^\s*PList\s+(\w+):(\w+)/) {
            $self->_create_local_pl_obj(file => $m[0],
                                        name => $m[1]);
        }
        # handling pattern lines
        elsif (@m = /^\s*Pat\s+(\w+)\s*(\[.*\])?\s*;\s*(#([\w,])#)?\s*$/) {
            $self->_create_pattern_obj(name => $m[0],
                                       mask_data => do {defined $m[1] ? $m[1] : ''},
                                       tag_data => do {defined $m[2] ? $m[2] : ''});
        }
        # handling our patlist closure
        elsif (/^\s*\}/) {
            last;
        }
    }

    # need to populate our hash of child plists
    for (@{$self->data}) {
        if (($_->isa('Pl')) or ($_->isa('LocalPl'))) {
            $self->_add_child($_);
        }
    }
}

__PACKAGE__->meta->make_immutable;

1;

你尝试过移除MooseX::Types的使用吗?这里所做的一切都可以使用普通的Moose类型来完成。这可能解决不了任何问题,但至少值得一试。 - Stevan Little
1
你的 'Program::Plist::Pl' 中是否有已导出的 'Pattern'?能展示一下那个文件吗? - phaylon
我可以移除MooseX::Types,但是还有很多其他文件需要逐个修改。我也不想绕过我不理解的问题。我发现这通常会导致在以后的路上重新创建类似或新的问题。我宁愿花费额外的时间进行调试并确定问题所在。Phaylon - 我已经在原始帖子的末尾添加了文件内容。 - TJ Thompson
跳过 make_immutable 可以帮助使构造函数周围的控制流更加易懂。 - jrockway
很好的想法。我看到了一些更多的东西,我们会看看它是否有帮助 :) - TJ Thompson
没这么幸运。还在深入挖掘 Moose 的内部。 - TJ Thompson
1个回答

3
问题出在我认为这里。
use Program::Types qw(Pl LocalPl TwoDigNum Pattern);

你正在将名为Pattern的函数导入到你的Program::Plist::Pl类中。然后在这里(无意中)调用了这个函数:
    my $pattern_obj = Program::Plist::Pl::Pattern->new(name => $name,
                                                   mask_data => $mask_data,
                                                   tags => $tags);

具体来说,Program::Plist::Pl::Pattern 解析为您完全限定的函数名称,而不是您期望的类(技术上的包名称)。该函数返回一个TypeObject对象,然后您可以在其上调用new()
注意:这正是上面评论中phaylon建议的内容。
实际上没有办法进行调试,除非知道您始终可以使用函数的完全限定名称来调用它,因此MooseX::Type和有效的类名永远不会冲突。
如果是我,我会编写一个非常简单的测试用例,并添加代码以复制原始文件,直到出现故障。我可能会从调用new开始。然后缓慢地添加回假设,直到找到导致错误的假设。希望您在该过程中尽早调用MooseX::Types,以便触发“噢,显然就是这个”的时刻。

1
你(和Phaylon)是完全正确的。我在另一个问题线程中解决了这个问题,但忘记在这里放置!由于某种原因,我没有意识到我使用Program :: Types库导入的类型定义实际上是子例程。糟糕的部分是常用于类型定义的命名约定(首字母大写无下划线)与包使用的相同命名约定相同。现在我已经弄清楚了,我有了一种新的命名约定,可以确保它们不会意外地与包名称冲突。 - TJ Thompson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接