The following sample file is formatted as a Windows INI configuration file. It is named my.ini.
[mysqld] basedir=C:/nsh/mysql [WinMySQLAdmin] Server=C:/nsh/bin/mysqld-nt.exe
The two sections in the file are:
mysqld
WinMySQLAdmin
The two key-value pairs in the file are:
basedir=C:/nsh/mysql
Server=C:/nsh/bin/mysqld-nt.exe
This structure requires two parsing rules, one to parse sections and the other to parse key-value pairs. Correspondingly, the grammar file needs two add-rules, one to add a section and another to add a key-value pair.
The following is the full ini.gm grammar file used to parse INI files:
TEMP temp VAR_L_BRACKET [ VAR_R_BRACKET ] VAR_EQUAL = VAR_NL \n %% WS [\t\n ]* SECTION [^]]+ KEY [^=]+ VAL .* COMMENT [#;].* EQUAL = LEFT_BRACKET \\[ RIGHT_BRACKET \\] CCOMMENT //.* %% ccomment CCOMMENT $save_as_comment $0 comment COMMENT $save_as_comment $0 section LEFT_BRACKET WS SECTION WS RIGHT_BRACKET $new_field $2 \ $save_var $TEMP $2 $set_as_nonleaf $save_record $2 $set_add_rule $0 key_val KEY WS EQUAL WS VAL $set_parent $TEMP \ $new_field $0 $new_field $4 $save_record $0 $set_add_rule $1 %% add_section $write_var $VAR_L_BRACKET $write_field $0 $write_var $VAR_R_BRACKET add_key_val $write_field $0 $write_var $VAR_EQUAL $write_field $1
The sample uses the TEMP
variable as a temporary variable to store the section name, which is referenced while parsing the key-value pair.
The sample uses the VAR_L_BRACKET
, VAR_R_BRACKET
, and VAR_EQUAL
variables to create new sections and key-value pairs.
The WS
token is used to match white spaces \t
, \n
and " "
.
The KEY
token is described in an example in Tokens section of a grammar file.
The other tokens follow the syntax used to create regular expressions. Note that the characters " /[]
are meta characters used in defining regular expressions and must be escaped when defining tokens if they are part of token values to be matched. Recall that in regular expressions, "." matches with any character, "" matches with zero or more characters preceding "", and "" matches with one or more characters preceding "". Note that "[" and "]" are used for grouping and "^" is used to indicate a complement.
In the rules section, the sample uses the rule named section
to parse section lines. Note the use of the $new_field
, $save_var
, $set_as_nonleaf
, $save_record
and $set_add_rule
actions. The sample uses the rule named key_val1
to match key-value pairs.