# ---------------------------------------------------------------------- # NAME : BibTeX/Structure.pm # CLASSES : Text::BibTeX::Structure, Text::BibTeX::StructuredEntry # RELATIONS : # DESCRIPTION: Provides the two base classes needed to implement # Text::BibTeX structure modules. # CREATED : in original form: Apr 1997 # completely redone: Oct 1997 # MODIFIED : # VERSION : $Id: Structure.pm 3033 2006-09-21 20:07:27Z ambs $ # COPYRIGHT : Copyright (c) 1997-2000 by Gregory P. Ward. All rights # reserved. # # This file is part of the Text::BibTeX library. This # library is free software; you may redistribute it and/or # modify it under the same terms as Perl itself. # ---------------------------------------------------------------------- package Text::BibTeX::Structure; require 5.004; # for 'isa' and 'can' use strict; use Carp; use Text::BibTeX ('check_class'); =head1 NAME Text::BibTeX::Structure - provides base classes for user structure modules =head1 SYNOPSIS # Define a 'Foo' structure for BibTeX databases: first, the # structure class: package Text::BibTeX::FooStructure; @ISA = ('Text::BibTeX::Structure'); sub known_option { my ($self, $option) = @_; ... } sub default_option { my ($self, $option) = @_; ... } sub describe_entry { my $self = shift; $self->set_fields ($type, \@required_fields, \@optional_fields, [$constraint_1, $constraint_2, ...]); ... } # Now, the structured entry class package Text::BibTeX::FooEntry; @ISA = ('Text::BibTeX::StructuredEntry'); # define whatever methods you like =head1 DESCRIPTION The module C provides two classes that form the basis of the B "structure module" system. This system is how database structures are defined and imposed on BibTeX files, and provides an elegant synthesis of object-oriented techniques with BibTeX-style database structures. Nothing described here is particularly deep or subtle; anyone familar with object-oriented programming should be able to follow it. However, a fair bit of jargon in invented and tossed around, so pay attention. A I, in B parlance, is just a set of allowed entry types and the rules for fields in each of those entry types. Currently, there are three kinds of rules that apply to fields: some fields are I, meaning they must be present in every entry for a given type; some are I, meaning they may be present, and will be used if they are; other fields are members of I, which are explained in L<"Field lists and constraint sets"> below. A B structure is implemented with two classes: the I and the I. The former defines everything that applies to the structure as a whole (allowed types and field rules). The latter provides methods that operate on individual entries which conform (or are supposed to conform) to the structure. The two classes provided by the C module are C and C; these serve as base classes for, respectively, all structure classes and all structured entry classes. One canonical structure is provided as an example with B: the C structure, which (via the C and C classes) provides the same functionality as the standard style files of BibTeX 0.99. It is hoped that other programmers will write new bibliography-related structures, possibly deriving from the C structure, to emulate some of the functionality that is available through third-party BibTeX style files. The purpose of this manual page is to describe the whole "structure module" system. It is mainly for programmers wishing to implement a new database structure for data files with BibTeX syntax; if you are interested in the particular rules for the BibTeX-emulating C structure, see L. Please note that the C prefix is dropped from most module and class names in this manual page, except where necessary. =head1 STRUCTURE CLASSES Structure classes have two roles: to define the list of allowed types and field rules, and to handle I. =head2 Field lists and constraint sets Field lists and constraint sets define the database structure for a particular entry type: that is, they specify the rules which an entry must follow to conform to the structure (assuming that entry is of an allowed type). There are three components to the field rules for each entry type: a list of required fields, a list of optional fields, and I. Required and optional fields should be obvious to anyone with BibTeX experience: all required fields must be present, and any optional fields that are present have some meaning to the structure. (One could conceive of a "strict" interpretation, where any field not mentioned in the official definition is disallowed; this would be contrary to the open spirit of BibTeX databases, but could be useful in certain applications where a stricter level of control is desired. Currently, B does not offer such an option.) Field constraints capture the "one or the other, but not both" type of relationships present for some entry types in the BibTeX standard style files. Most BibTeX documentation glosses over the distinction between mutually constrained fields and required/optional fields. For instance, one of the standard entry types is C, and "C or C" is given in the list of required fields for that type. The meaning of this is that an entry of type C must have I the C or C fields, but not both. Likewise, the "C or C" are listed under the "optional fields" heading for C entries; it would be more accurate to say that every C entry may have one or the other, or neither, of C or C---but not both. B attempts to clarify this situation by creating a third category of fields, those that are mutually constrained. For instance, neither C nor C appears in the list of required fields for the C type according to B; rather, a field constraint is created to express this relationship: [1, 1, ['author', 'editor']] That is, a field constraint is a reference to a three-element list. The last element is a reference to the I, the list of fields to which the constraint applies. (Calling this a set is a bit inaccurate, as there are conditions in which the order of fields matters---see the C method in L<"METHODS 2: BASE STRUCTURED ENTRY CLASS">.) The first two elements are the minimum and maximum number of fields from the constraint set that must be present for an entry to conform to the constraint. This constraint thus expresses that there must be exactly one (>= 1 and <= 1) of the fields C and C in a C entry. The "either one or neither, but not both" constraint that applies to the C and C fields for C entries is expressed slightly differently: [0, 1, ['volume', 'number']] That is, either 0 or 1, but not the full 2, of C and C may be present. It is important to note that checking and enforcing field constraints is based purely on counting which fields from a set are actually present; this mechanism can't capture "x must be present if y is" relationships. The requirements imposed on the actual structure class are simple: it must provide a method C which sets up a fancy data structure describing the allowed entry types and all the field rules for those types. The C class provides methods (inherited by a particular structure class) to help particular structure classes create this data structure in a consistent, controlled way. For instance, the C method in the BibTeX 0.99-emulating C class is quite simple: sub describe_entry { my $self = shift; # series of 13 calls to $self->set_fields (one for each standard # entry type) } One of those calls to the C method defines the rules for C entries: $self->set_fields ('book', [qw(title publisher year)], [qw(series address edition month note)], [1, 1, [qw(author editor)]], [0, 1, [qw(volume number)]]); The first field list is the list of required fields, and the second is the list of optional fields. Any number of field constraints may follow the list of optional fields; in this case, there are two, one for each of the constraints (C/C and C/C) described above. At no point is a list of allowed types explicitly supplied; rather, each call to C adds one more allowed type. New structure modules that derive from existing ones will probably use the C method (and possibly C) to augment an existing entry type. Adding new types should be done with C, though. =head2 Structure options The other responsibility of structure classes is to handle I. These are scalar values that let the user customize the behaviour of both the structure class and the structured entry class. For instance, one could have an option to enable "extended structure", which might add on a bunch of new entry types and new fields. (In this case, the C method would have to pay attention to this option and modify its behaviour accordingly.) Or, one could have options to control how the structured entry class sorts or formats entries (for bibliography structures such as C). The easy way to handle structure options is to provide two methods, C and C. These return, respectively, whether a given option is supported, and what its default value is. (If your structure doesn't support any options, you can just inherit these methods from the C class. The default C returns false for all options, and its companion C crashes with an "unknown option" error.) Once C and C are provided, the structure class can sit back and inherit the more visible C and C methods from the C class. These are the methods actually used to modify/query options, and will be used by application programs to customize the structure module's behaviour, and by the structure module itself to pay attention to the user's wishes. Options should generally have pure string values, so that the generic set_options method doesn't have to parse user-supplied strings into some complicated structure. However, C will take any scalar value, so if the structure module clearly documents its requirements, the application program could supply a structure that meets its needs. Keep in mind that this requires cooperation between the application and the structure module; the intermediary code in C knows nothing about the format or syntax of your structure's options, and whatever scalar the application passes via C will be stored for your module to retrieve via C. As an example, the C structure supports a number of "markup" options that allow applications to control the markup language used for formatting bibliographic entries. These options are naturally paired, as formatting commands in markup languages generally have to be turned on and off. The C structure thus expects references to two-element lists for markup options; to specify LaTeX 2e-style emphasis for book titles, an application such as C would set the C option as follows: $structure->set_options (btitle_mkup => ['\emph{', '}']); Other options for other structures might have a more complicated structure, but it's up to the structure class to document and enforce this. =head1 STRUCTURED ENTRY CLASSES A I defines the behaviour of individual entries under the regime of a particular database structure. This is the Itre> for any database structure: the structure class merely lays out the rules for entries to conform to the structure, but the structured entry class provides the methods that actually operate on individual entries. Because this is completely open-ended, the requirements of a structured entry class are much less rigid than for a structure class. In fact, all of the requirements of a structured entry class can be met simply by inheriting from C, the other class provided by the C module. (For the record, those requirements are: a structured entry class must provide the entry parse/query/manipulate methods of the C class, and it must provide the C, C, and C methods of the C class. Since C inherits from C, both of these requirements are met "for free" by structured entry classes that inherit from C, so naturally this is the recommended course of action!) There are deliberately no other methods required of structured entry classes. A particular application (eg. C for bibliography structures) will require certain methods, but it's up to the application and the structure module to work out the requirements through documentation. =head1 CLASS INTERACTIONS Imposing a database structure on your entries sets off a chain reaction of interactions between various classes in the C library that should be transparent when all goes well. It could prove confusing if things go wrong and you have to go wading through several levels of application program, core C classes, and some structure module. The justification for this complicated behaviour is that it allows you to write programs that will use a particular structured module without knowing the name of the structure when you write the program. Thus, the user can supply a database structure, and ultimately the entry objects you manipulate will be blessed into a class supplied by the structure module. A short example will illustrate this. Typically, a C-based program is based around a kernel of code like this: $bibfile = new Text::BibTeX::File "foo.bib"; while ($entry = new Text::BibTeX::Entry $bibfile) { # process $entry } In this case, nothing fancy is happening behind the scenes: the C<$bibfile> object is blessed into the C class, and C<$entry> is blessed into C. This is the conventional behaviour of Perl classes, but it is not the only possible behaviour. Let us now suppose that C<$bibfile> is expected to conform to a database structure specified by C<$structure> (presumably a user-supplied value, and thus unknown at compile-time): $bibfile = new Text::BibTeX::File "foo.bib"; $bibfile->set_structure ($structure); while ($entry = new Text::BibTeX::Entry $bibfile) { # process $entry } A lot happens behind the scenes with the call to C<$bibfile>'s C method. First, a new structure object is created from C<$structure>. The structure name implies the name of a Perl module---the structure module---which is C'd by the C constructor. (The main consequence of this is that any compile-time errors in your structure module will not be revealed until a C or C call attempts to load it.) Recall that the first responsibility of a structure module is to define a structure class. The "structure object" created by the C method call is actually an object of this class; this is the first bit of trickery---the structure object (buried behind the scenes) is blessed into a class whose name is not known until run-time. Now, the behaviour of the C constructor changes subtly: rather than returning an object blessed into the C class as you might expect from the code, the object is blessed into the structured entry class associated with C<$structure>. For example, if the value of C<$structure> is C<"Foo">, that means the user has supplied a module implementing the C structure. (Ordinarily, this module would be called C---but you can customize this.) Calling the C method on C<$bibfile> will attempt to create a new structure object via the C constructor, which loads the structure module C. Once this module is successfully loaded, the new object is blessed into its structure class, which will presumably be called C (again, this is customizable). The new object is supplied with the user's structure options via the C method (usually inherited), and then it is asked to describe the actual entry layout by calling its C method. This, in turn, will usually call the inherited C method for each entry type in the database structure. When the C constructor is finished, the new structure object is stored in the C object (remember, we started all this by calling C on a C object) for future reference. Then, when a new C object is created and parsed from that particular C object, some more trickery happens. Trivially, the structure object stored in the C object is also stored in the C object. (The idea is that entries could belong to a database structure independently of any file, but usually they will just get the structure that was assigned to their database file.) More importantly, the new C object is re-blessed into the structured entry class supplied by the structure module---presumably, in this case, C (also customizable). Once all this sleight-of-hand is accomplished, the application may treat its entry objects as objects of the structured entry class for the C structure---they may call the check/coerce methods inherited from C, and they may also call any methods specific to entries for this particular database structure. What these methods might be is up to the structure implementor to decide and document; thus, applications may be specific to one particular database structure, or they may work on all structures that supply certain methods. The choice is up to the application developer, and the range of options open to him depends on which methods structure implementors provide. =head1 EXAMPLE For example code, please refer to the source of the C module and the C, C, and C applications supplied with C. =head1 METHODS 1: BASE STRUCTURE CLASS The first class provided by the C module is C. This class is intended to provide methods that will be inherited by user-supplied structure classes; such classes should not override any of the methods described here (except C and C) without very good reason. Furthermore, overriding the C method would be useless, because in general applications won't know the name of your structure class---they can only call C (usually via C). Finally, there are three methods that structure classes should implement: C, C, and C. The first two are described in L<"Structure options"> above, the latter in L<"Field lists and constraint sets">. Note that C depends heavily on the C, C, and C methods described here. =head2 Constructor/simple query methods =over 4 =item new (STRUCTURE, [OPTION =E VALUE, ...]) Constructs a new structure object---I a C object, but rather an object blessed into the structure class associated with STRUCTURE. More precisely: =over 4 =item * Loads (with C) the module implementing STRUCTURE. In the absence of other information, the module name is derived by appending STRUCTURE to C<"Text::BibTeX::">---thus, the module C implements the C structure. Use the pseudo-option C to override this module name. For instance, if the structure C is implemented by the module C: $structure = new Text::BibTeX::Structure ('Foo', module => 'Foo'); This method Cs if there are any errors loading/compiling the structure module. =item * Verifies that the structure module provides a structure class and a structured entry class. The structure class is named by appending C<"Structure"> to the name of the module, and the structured entry class by appending C<"Entry">. Thus, in the absence of a C option, these two classes (for the C structure) would be named C and C. Either or both of the default class names may be overridden by having the structure module return a reference to a hash (as opposed to the traditional C<1> returned by modules). This hash could then supply a C element to name the structure class, and an C element to name the structured entry class. Apart from ensuring that the two classes actually exist, C verifies that they inherit correctly (from C and C respectively), and that the structure class provides the required C, C, and C methods. =item * Creates the new structure object, and blesses it into the structure class. Supplies it with options by passing all (OPTION, VALUE) pairs to its C method. Calls its C method, which should list the field requirements for all entry types recognized by this structure. C will most likely use some or all of the C, C, and C methods---described below---for this. =back =cut sub new { my ($type, $name, %options) = @_; # - $type is presumably "Text::BibTeX::Structure" (if called from # Text::BibTeX::File::set_structure), but shouldn't assume that # - $name is the name of the user-supplied structure; it also # determines the module we will attempt to load here, unless # a 'module' option is given in %options # - %options is a mix of options recognized here (in particular # 'module'), by Text::BibTeX::StructuredEntry (? 'check', 'coerce', # 'warn' flags), and by the user structure classes my $module = (delete $options{'module'}) || ('Text::BibTeX::' . $name); my $module_info = eval "require $module"; die "Text::BibTeX::Structure: unable to load module \"$module\" for " . "user structure \"$name\": $@\n" if $@; my ($structure_class, $entry_class); if (ref $module_info eq 'HASH') { $structure_class = $module_info->{'structure_class'}; $entry_class = $module_info->{'entry_class'}; } $structure_class ||= $module . 'Structure'; $entry_class ||= $module . 'Entry'; check_class ($structure_class, "user structure class", 'Text::BibTeX::Structure', ['known_option', 'default_option', 'describe_entry']); check_class ($entry_class, "user entry class", 'Text::BibTeX::StructuredEntry', []); my $self = bless {}, $structure_class; $self->{entry_class} = $entry_class; $self->{name} = $name; $self->set_options (%options); # these methods are both provided by $self->describe_entry; # the user structure class $self; } =item name () Returns the name of the structure described by the object. =item entry_class () Returns the name of the structured entry class associated with this structure. =back =cut sub name { shift->{'name'} } sub entry_class { shift->{'entry_class'} } =head2 Field structure description methods =over 4 =item add_constraints (TYPE, CONSTRAINT, ...) Adds one or more field constraints to the structure. A field constraint is specified as a reference to a three-element list; the last element is a reference to the list of fields affected, and the first two elements are the minimum and maximum number of fields from the constraint set allowed in an entry of type TYPE. See L<"Field lists and constraint sets"> for a full explanation of field constraints. =cut sub add_constraints { my ($self, $type, @constraints) = @_; my ($constraint); foreach $constraint (@constraints) { my ($min, $max, $fields) = @$constraint; croak "add_constraints: constraint record must be a 3-element " . "list, with the last element a list ref" unless (@$constraint == 3 && ref $fields eq 'ARRAY'); croak "add_constraints: constraint record must have 0 <= 'min' " . "<= 'max' <= length of field list" unless ($min >= 0 && $max >= $min && $max <= @$fields); map { $self->{fields}{$type}{$_} = $constraint } @$fields; } push (@{$self->{fieldgroups}{$type}{'constraints'}}, @constraints); } # add_constraints =item add_fields (TYPE, REQUIRED [, OPTIONAL [, CONSTRAINT, ...]]) Adds fields to the required/optional lists for entries of type TYPE. Can also add field constraints, but you can just as easily use C for that. REQUIRED and OPTIONAL, if defined, should be references to lists of fields to add to the respective field lists. The CONSTRAINTs, if given, are exactly as described for C above. =cut sub add_fields # add fields for a particular type { my ($self, $type, $required, $optional, @constraints) = @_; # to be really robust and inheritance-friendly, we should: # - check that no field is in > 1 list (just check $self->{fields} # before we start assigning stuff) # - allow sub-classes to delete fields or move them to another group if ($required) { push (@{$self->{fieldgroups}{$type}{'required'}}, @$required); map { $self->{fields}{$type}{$_} = 'required' } @$required; } if ($optional) { push (@{$self->{fieldgroups}{$type}{'optional'}}, @$optional); map { $self->{fields}{$type}{$_} = 'optional' } @$optional; } $self->add_constraints ($type, @constraints); } # add_fields =item set_fields (TYPE, REQUIRED [, OPTIONAL [, CONSTRAINTS, ...]]) Sets the lists of required/optional fields for entries of type TYPE. Identical to C, except that the field lists and list of constraints are set from scratch here, rather than being added to. =back =cut sub set_fields { my ($self, $type, $required, $optional, @constraints) = @_; my ($constraint, $field); undef %{$self->{fields}{$type}}; if ($required) { $self->{fieldgroups}{$type}{'required'} = $required; map { $self->{fields}{$type}{$_} = 'required' } @$required; } if ($optional) { $self->{fieldgroups}{$type}{'optional'} = $optional; map { $self->{fields}{$type}{$_} = 'optional' } @$optional; } undef @{$self->{fieldgroups}{$type}{'constraints'}}; $self->add_constraints ($type, @constraints); } # set_fields =head2 Field structure query methods =over 4 =item types () Returns the list of entry types supported by the structure. =item known_type (TYPE) Returns true if TYPE is a supported entry type. =item known_field (TYPE, FIELD) Returns true if FIELD is in the required list, optional list, or one of the constraint sets for entries of type TYPE. =item required_fields (TYPE) Returns the list of required fields for entries of type TYPE. =item optional_fields () Returns the list of optional fields for entries of type TYPE. =item field_constraints () Returns the list of field constraints (in the format supplied to C) for entries of type TYPE. =back =cut sub types { my $self = shift; keys %{$self->{'fieldgroups'}}; } sub known_type { my ($self, $type) = @_; exists $self->{'fieldgroups'}{$type}; } sub _check_type { my ($self, $type) = @_; croak "unknown entry type \"$type\" for $self->{'name'} structure" unless exists $self->{'fieldgroups'}{$type}; } sub known_field { my ($self, $type, $field) = @_; $self->_check_type ($type); $self->{'fields'}{$type}{$field}; # either 'required', 'optional', or } # a constraint record (or undef!) sub required_fields { my ($self, $type) = @_; $self->_check_type ($type); @{$self->{'fieldgroups'}{$type}{'required'}}; } sub optional_fields { my ($self, $type) = @_; $self->_check_type ($type); @{$self->{'fieldgroups'}{$type}{'optional'}}; } sub field_constraints { my ($self, $type) = @_; $self->_check_type ($type); @{$self->{'fieldgroups'}{$type}{'constraints'}}; } =head2 Option methods =over 4 =item known_option (OPTION) Returns false. This is mainly for the use of derived structures that don't have any options, and thus don't need to provide their own C method. Structures that actually offer options should override this method; it should return true if OPTION is a supported option. =cut sub known_option { return 0; } =item default_option (OPTION) Crashes with an "unknown option" message. Again, this is mainly for use by derived structure classes that don't actually offer any options. Structures that handle options should override this method; every option handled by C should have a default value (which might just be C) that is returned by C. Your C method should crash on an unknown option, perhaps by calling C (in order to ensure consistent error messages). For example: sub default_option { my ($self, $option) = @_; return $default_options{$option} if exists $default_options{$option}; $self->SUPER::default_option ($option); # crash } The default value for an option is returned by C when that options has not been explicitly set with C. =cut sub default_option { my ($self, $option) = @_; croak "unknown option \"$option\" for structure \"$self->{'name'}\""; } =item set_options (OPTION =E VALUE, ...) Sets one or more option values. (You can supply as many C