START-INFO-DIR-ENTRY
* Gperf: (gperf). Perfect hash function generator.
END-INFO-DIR-ENTRY
Introduction
************
'Gperf' is a perfect hash function generator written in C ++. It uses a perfect hash function f to convert
For a set of user-specific keywords containing nelements to the unique. Ing keyword W. f In the set to the 0. k range of W,
In K> = n if k = N, F is the perfect minimum hash function. 'gperf' generates a static query of 0. k elements.
Queries a table and a pair of C functions. These functions determine whether a given string S is in the set w by searching only once.
'Gperf' is generally used to generate a lexical analyzer for multiple commercial compilers, research compilers, and language processing tools.
Keyword identifiers. These compilers include gnu c, gnu c ++, GNU Pascal, GNU modula 3,
And GNU indent. Complete 'gperf' C ++Source codeYou can use anonymous FTP 'ics .uci.edu 'and 'ftp.
Obtained by santafe.edu. 'gperf' has been released with GNU libg ++ for several years. It is highly similar and has equivalent functions.
The K & r c version of 'gperf' has been archived in Comp. Sources. UNIX, Volume 20. Finally, an article about
The detailed design and implementation of 'gperf' can be found in the second usenix C ++ conference.
'Gperf' static search structure and GNU 'gperf'
****************************************
A "static search structure" is an abstract data type with some basic operations, such as initialization, insertion,
And Retrieval concept, all inserts occur before the search. In reality, 'gperf' generates a 'static 'array, which
Is a query set that contains keywords and user-specified related attributes. In this way, basically no insertion time is spent (pre-release
In the array). This is a useful data structure used to represent "static lookup set ".
Application discovery. Generally, static lookup sets contain compiler keywords and Assembly commands.Code, And built-in shell commands. Find the set
A member, called a keyword, is inserted only once in the structure.ProgramIt is not modified during initialization and real-time running.
There are many ways to implement static search structures, such as arrays, linked lists, binary search trees, numeric search tuples, and hash tables.
The method provides a balance between space utilization and search efficiency. For example, a sorted array of n elements is space-effective, although
The average time complexity of searching is the opposite to that of log n. Hash Tables are usually able to locate a table at constant time.
But usually requires additional memory overhead and presentation of low performance in the worst case.
"Minimal perfect hash function" provides an ideal solution for a special static lookup set.
The Greek function is defined to have the following two properties:
* It allows you to identify a keyword in a static lookup set as long as a "one-time" test is performed in the hash table.
Nature represents "perfect" Nature
* The actual memory allocation is used to save the keyword precisely enough to save the key set, and is not "larger". This is"
Minimize "nature.
It is easier to generate a "perfect" hash function for many applications than to generate a "minimum perfect" hash function. Moreover, in practice
Smaller perfect hash functions tend to execute faster than the "minimum perfect" hash function because of sparse search.
The keyword table adds the probability of locating a "null" record. Therefore, the default value of 'gperf' is to reduce the string comparison.
Key character set generation "approximate minimization" perfect hash function. However, 'gpref' provides many options to allow user control Minimization
And the degree of perfection
Static lookup sets are usually relatively stable in time. For example, Ada's 63 reserved words (that is, static lookup set) are kept constant.
For nearly ten years. Therefore, if we need to repeat implementation every time, we will spend a one-time effort to build an optimal search structure.
It is worth noting that 'gperf' is a tough task to manually implement a time-balanced search set.
Utility tools are used in various programming projects. 'gpref' outputs are generally used in multiple commercial compilers, research compilers, including
Gnu c, gnu c ++, GNU Pascal, and GNU modula 3. The last two compilers have not yet become official GNU releases.
The compiler uses 'gperf' to automatically generate static search structures to effectively identify their reserved words.
'Gperf' GNU 'gperf' High-level description
*************************************
The perfect hash function generator 'gperf' reads a keyword set from a key file ("Keyfile" or a tacit standard input ).
In combination, it tries to obtain a perfect hash function to identify "static keywords" members by detecting at most one query table. If 'gperf'
If such a function is successfully generated, it will generate a pair of C-source code routines to execute hash and table search and identification. All generated C-generation
Code-oriented to standard output. The following command line option description allows you to modify the input/output format of 'gperf'
By default, 'gperf' attempts to generate more time-efficient code by reducing the amount of space that emphasizes effectiveness. However, several options exist.
Allows the execution time in exchange for space storage. In particular, extended table size generation generates a sparse search structure, which generally produces faster searches.
On the contrary, you can instruct 'gperf' to use C's 'Switch 'statement to arrange the minimum data space storage size. In addition, you can use C switch
In fact, it improves the search time of keywords to some extent. Of course, this is also related to your C compiler.
Generally, 'gperf' assigns a value to a letter for hashes until each keyword in the final set corresponds to a unique value. A very
The larger the hash value range, the easier 'gperf' is to generate a perfect hash function. Experiments show that this is 'gperf'
Most importantly.
'Gperf' input format
======================================
You can control the input file format by changing specific command line parameters, especially the '-t' option. The input format is similar to the GNU utility.
'Flex 'and 'bison' (or Unix 'lex 'and 'yacc') Here are general format outlines:
Declarations
%
Keywords
%
Functions
If it is not used for 'flex 'or 'bison', all parts of the 'gperf' input are optional. Next, each section describes each part of the input format.
The 'struct 'statement and C Code contain
------------------------------------------
Key input files include optional parts used to include arbitrary C statements and definitions, and user-defined 'struct '. If the'-t' option is valid, you must
A C' struct 'must be provided to the input file as the final component of the declaration part. The first field of this struct must be of the 'Char *' type,
The identifier named 'name', although you can use the '-k' option described later to modify the domain name.
Here is a simple example, using the month of a year and their attributes as input:
Struct months {char * Name; int number; int days; int leap_days ;};
%
January, 1, 31, 31
February, 2, 28, 29
March, 3, 31, 31
10000l, 4, 30, 30
May, 5, 31, 31
June, 6, 30, 30
July, 7, 31, 31
August, 8, 31, 31
September, 9, 30, 30
October, 10, 31, 31
November, 11, 30, 30
December, 12, 31, 31
Separate the 'struct 'Declaration and keyword list with a consecutive percent sign' % ', which appears in the first leftmost column, as shown in
UNIX utility 'lex'
The syntax is similar to the GNU utility 'flex 'and 'bison'. It may directly contain C source code and comments, and directly output
To the output file, it is enclosed by the left-aligned '% {',' %} 'pairs. Here an input segment is based on the previous example, used to describe
This feature:
% {
# Include <assert. h>
/* This section of code is inserted directly into the output .*/
Int return_month_days (struct months * months, int is_leap_year );
%}
Struct months {char * Name; int number; int days; int leap_days ;};
%
January, 1, 31, 31
February, 2, 28, 29
March, 3, 31, 31
...
The declaration part may be completely ignored. In this case, the key file begins with the direct first line keyword definition, for example:
January, 1, 31, 31
February, 2, 28, 29
March, 3, 31, 31
10000l, 4, 30, 30
...
Keyword record format
--------------------------
The second part of the key file contains the keywords of a row and any associated attributes you provide. Start with '#' in the first column of each row.
Represents a line of comment.
The initial field of a non-Annotated row is a keyword. It is given by a simple name. For example, it is not identified by string quotation marks,
It can be left aligned. In the context, a "Domain" is considered to be extended, and does not contain spaces, commas, or line breaks.
Here is a simple example listing some reserved C words:
# These are a few C reserved words, see the c. 'gperf' File
# For a complete list of ansi c reserved words.
Unsigned
Sizeof
Switch
Signed
If
Default
For
While
Return
Note: Unlike 'flex 'or 'bison', if the declared part is null, the '%' identifier can be omitted.
The field after the leading keyword is optional. The fields should be separated by commas and end with the end of the line. The meanings of these fields are fully defined by you;
They are used to initialize the element User-Defined 'struct '(defined in the Declaration). If the'-t' option is not selected, these fields will be simply
Ignore. All previous examples, except the last one, contain the keyword attribute.
Include additional c Functions
--------------------------------
The third part is also very similar to the definitions in 'flex 'and 'bison'. All content in this part starts with the last '%'
At the end of the input file, the content will be directly copied to the output file. Of course, it is your responsibility to ensure that the included code is valid C code.
C code output format generated by 'gperf'
========================================================== ========
Several options control how to generate C code in the standard output. Two C functions will be generated. Their names are 'hash', 'in _ word_set ',
Although you can modify the 'in _ word_set name through a command line option, all functions require two parameters, one string, 'Char * 'Str
And a length parameter, 'int' Len. Their default function prototype is as follows:
Static int Hash (char * STR, int Len );
Int in_word_set (char * STR, int Len );
By default, the generated 'hash' function returns an integer value by adding the length to several user-specified key STR locations.
As an index of a static array. The associated value table is constructed inside 'gperf' and is followed
The output is a static local array named hash_table. Its meaning and nature will be described later. Note the implementation :.
You can specify it by running the '-k' option of 'gperf'. This will be described in the 'options' section below. Note the options ::.
Two options: '-G' (assuming you are compiling with gnuc and related 'inline' features) and'-A' (assuming the ansi c style prototype,
The generated 'hash' and 'in _ word_set 'routines will be changed. However, the 'in _ word_set' function can be modified more.
The options that affect the structure of 'in _ word_set 'are as follows:
'-T'
Use User-Defined 'struct'
-S all use switch statements
Generate one or more C' switches, instead of using a large (possibly sparse) Static array.
The exact time space saved by this method greatly depends on your C Compiler Optimization. This method is often used
Resulting in smaller and faster code.
If the '-t' and'-S' options are omitted, the default behavior is to generate an array of 'Char * ', including keywords, and additional fill numbers
The 'null' string of the group is determined by testing different input and output options and timing the result produced for C.
Choose the best option.
'Gperf' practical options
******************************
There are a lot of 'gperf' options here. It is more convenient to add and use programs in real applications. "On-line" is easy to help.
The '-H' option is obtained. Here is a complete list of options.
Option that affects the interpretation of input files
========================================================== ================
-E keyword separator list
Allows you to provide a string containing delimiters to separate keywords and their attributes. The default value is ", \ n"
The essence of this option is to use-e "tab" if you want to use keywords embedded with commas or line breaks"
Here, tab is a constant of the Tab character.
'-T'
Allow you to include a 'struct 'type declaration to generate code. Any content before a pair of continuous %
Part of the declared type. The following are keywords and extra-field fields. A group of fields is one row. A group generates a perfect hash table.
And function examples, the reserved words about Ada, C, and g ++, Pascal, and modula 2 and 3 are released along with the program.
Specifies the language in which the output code is generated.
========================================================== ==============
'-L generate language name'
Indicates 'gperf' to generate code by specifying the option parameter specified by the language. Currently, Supported languages include:
'Kr-C'
The old K & r c. language can be recognized by the old C compiler and ansic compiler.
The ansi c compiler may mark warnings (or even errors) because the 'const' mark is missing ).
'C'
C. This language can be recognized by the ansi c compiler for the old C compiler,
If the compiler cannot recognize keywords, you can use "# define const'
Empty to support
'Ansi-C'
Ansi c. This language can be recognized by ansi c and C ++ compilers.
'C ++'
C ++ can be identified by the C ++ compiler.
The default value is C.
'-'
This option is compatible with the previous 'gperf' and does not work.
'-G'
This option is compatible with the previous 'gperf' and does not work.
Detailed options used to adjust code output
========================================================== ============
'-K keyword name'
This option is valid only when the '-t' option is valid. By default, the program assumes that the variable for the keyword in the structure is 'name '.
This option allows any keyword to be selected. Of course, this option is only specified in the first field in the 'struct 'you provide.
'-H hash function name'
You can specify the name of the generated hash function. The default name is 'hash'. This option allows
Use two hash tables.
'-N find function name'
Allow you to specify the name of the query function to be generated. The default name is 'in _ word_set '. This option allows
Automatically generate perfect function functions, especially when multiple generated hash functions are used in the same application.
'-Z class name'
This option is valid only when option '-l c ++' is set. It allows you to specify the generated C ++ class name. The default name is
'Perfect _ hash'
'-7'
This option specifies that each character of all the hash functions passed to and the query function strings is 7 characters
(The character range is 0 .. 127). (Note that the functions 'isalnum' and 'isgraph' in ansi c are not guaranteed.
The parameter is in this range. Only obvious tests such as 'C> = 'A' & C <= 'Z' ensure this) in
In earlier 'gperf' versions, This is the default option. Note that the current default option is assumed to be 8 bits.
'-C'
The generated C Code uses the 'strcmp 'function to execute string comparison. The default value is 'strcmp '.
'-C'
Make sure that all the content in the query table is not changed, for example, "read-only". At this point, many compilers can ensure that
More effective code: Put the table into the read-only memory.
'-E'
When defining a constant value, use a local enumeration volume in the lookup function instead of # define.
This also means that different search functions can exist in the same file at the same time. Thanks to James Clark.
'<Jjc@ai.mit.edu>'
'-I'
Include necessary system header files at the beginning of the Code, '<string, h>'. This is not the default.
The compile code user must personally include this header file
'-G'
Generate a keyword static table as a static global variable instead of encapsulating it in the search function integer.
(Encapsulation is the default action in the search function ).
'-W hash table array name'
You can specify the name of the array containing the hash table generated. The default name is 'wordlist'. This option
Allows users to use two hash tables in the same file, even when the '-G' option is set
'-S full switch statement'
The generated C Code uses a 'Switch 'statement to replace an array query table.
This produces better time space efficiency. The option parameter determines how many switch statements are generated. 1 indicates that one
The 'Switch 'statement contains all elements. 2 indicates that two tables are generated. Each table uses a 'Switch' statement, which contains
1/2 elements. And so on. This is valid because many c compilers cannot correctly generate many large 'switch' statements.
This option was inspired by Keith Bostic's original C program design.
'-T'
Block the type from being converted to the output file. Use this option when the type has been defined somewhere.
'-P'
This option is compatible with the previous version 'gperf' and does not accomplish anything.
Used to select 'gperf'AlgorithmOptions
========================================================== ====================
'-K keys'
Allowed option character key locations are used in the hash function of the keyword. The allowed range is between 1-126 (including 1,126). These locations
Separated by commas (,), for example, '-K 9, 4, 13, 14'. intervals can be used. For example, all positions of '-K 2-7' can appear in any order.
In addition, the meta sign '*' causes the generated hash function to consider the positions of all characters for each key, while '$' indicates that
"One character" as a key (by the way, this is the only way to use a character location greater than 126)
For example, if '-K,-10,' $ ''is used to generate a hash function, consider
Location 1, 2, 4, 6, 7, 8, 9, 10, and the last character (obviously it can be different from any key). Key Length
Smaller than the indicated Key location is appropriate, because selecting a key location beyond its length will simply not be referenced in the hash function.
'-L'
The length of the comparison key when you try to compare strings. This may reduce the number of matching characters in the search, because
If the key length is different, 'strcmp 'will never be used for comparison.
The switch option '-S' is not set). Using'-l' may cause the size of the generated C code to increase.
A table with a record length contains as many elements as the number of records in the query table.
'-D'
When the key position distribution column has a duplicate value, the duplicate value occurs for the following two reasons:
* Because 'gperf' cannot be traced back, it cannot be found when the first word of the unique ing is not found.
Keyword you entered. However, a small number of duplicate values often occur, and most of them need
Perform a test in the table.
* Sometimes the keywords of a set can have the same name but different related attributes. Use the-D option.
'Gperf' regards all these keys as part of an equivalence class and ensures a perfect hash function.
When the same key value is used, the comparison is performed multiple times until you modify the generated C code to eliminate ambiguity. However, 'gperf'
Help you organize these outputs
The '-d' option is extremely useful for keyword sets that are very large or highly redundant, such as the Assembly script set.
Using this option usually means that the generated hash function is no longer perfect. On the other hand, it allows 'gperf'
Work in these key sets, otherwise it cannot be processed.
'-F iteration qty'
The perfect hash function generated by "quick" can reduce the running time of 'gperf' and minimize the size of the child table.
The number of iterations indicates the number of iterations when a collision occurs. '0' indicates the number of iterations as the number of keywords. When a large keyword set is encountered, this
Options '-d' or/and'-S' may be very useful.
'-I initiator'
Provide an initialization value for the key array value. The default value is 0. Increasing the actual starting value may lead to an increase in the size of the final table and more time searches.
Note that this option is not particularly used when the '-S' option is used. The'-I 'option is also ignored when the'-R' option is used.
'-J jump value'
The "Jump value" is affected. For example, when a collision occurs, how far must it go before it reaches the relevant character. The jump value is an odd value and the default value is 5.
If the jump value is 0, 'gperf' is redirected to a random number.
'-N'
Indicates that the generator does not contain the length of the keyword when calculating its hash value. This can be used when a search table is generated.
Saves a lot of assembly instructions
'-O'
Key Sets are reordered by keywords, and the key locations that often occur appear at the beginning. A rearrangement is followed,
The "key with a fixed value" is placed at the top of the key table. This reduces the time required to generate a perfect hash function.
And generates more minimal perfect hash functions. The result is that the re-arrangement reduces the search time when the search encounters a collision.
On the other hand, when the keyword set is very large, using '-O' may increase the execution time of 'gperf', because the collision will start earliest and
It will continue in the next processing.
For more information, see the January 1980 communications of the ACM paper by cichelli.
'-R'
Use a random value to initialize the associated value table. initialize the table with a fixed value (starts to initialize all associated values to 0)
This will often generate results faster. In addition, using the Randomization option will usually increase the table size. If a key set is determined
If you have difficulty, try '-R' or'-d'
'-S size-multiple'
The number parameter that affects the size of the hash table generated. The value range of this option is "How many times greater than or less ".
If size-multiple is a negative number, the calculation method of the maximum associated value is to divide it by the total number of keys. For example, if the value is 3, "the maximum allowed
The maximum join value is 3 times the number of input keys"
Conversely, a value of-3 means "the maximum allowed join value is 1/3 of the number of input keys. A negative value is very useful for limiting hash table generation,
This will increase the duplicate hash value.
If the 'generate switch' option '-S' is not valid, the maximum associated value affects the size of the static array table,
In addition, a larger table should reduce the time for unsuccessful searches.
The default value is 1, so the default maximum join value is the number of keywords (to be more effective, the maximum join value is usually the power of 2)
The actual table size can be changed, because this technology is essentially a heuristic method. In particular, setting this value too high will lead
The running time of 'gperf' is slow because it must be searched in a very large range value. The '-F' option is used wisely.
This can reduce the total overhead.
Information output
============================
'-H'
Print a brief summary about each program option. The program will be interrupted when an exception occurs.
'-V'
Print the current version number
'-D'
Enable debugging options. This will generate a detailed "standard error" diagnosis when 'gperf' is executed. This will be used to manipulate the program and determine whether a given option is available
It can accelerate the discovery of a solution. Some useful information will be discarded at the end of the program when the '-d' option is valid
Transferred from
Http://blog.csdn.net/wenfengmtd/archive/2006/06/12/792692.aspx