This module demonstrates how to deal with the phrases matched to the SABNF syntax rule names.
Rule names are similar to named groupings in regex
expressions. They associate a name with a phrase.
apg-exp
provides a little more information about the rule phrases than does the JavaScript RegExp
object.
Firstly, the JavaScript RegExp
object does not provide for naming the grouped phrases, although other flavors
of regex
engines do. Secondly, the JavaScript RegExp
object only gives the last match to the group and doesn’t
provide the character index where it was found. apg-exp
retains all phrases matched by any rule name and provides
character index where it was found.
The result
object retains an array of all of the phrases found for each rule name.
It is an array of phrase objects, each object having the phrase and index in the form
{phrase: string, index : number}.
By default, all rule names in the grammar are retained in the result object
but, as will be demonstrated here, uninteresting rules or phrases can be ignored.
The MDN
description of the RegExp
object also indicates that it retains “last match” information.
Although most of that information seems to be missing in the node.js
implementation, all of it,
including the aliases, are defined and retained by the apg-exp
object.
This will also be demonstrated here.
We will pick a grammar and string that will have several named-rules, some with zero, one and more matching phrases.
This is a simplified ini file
format.
It simply consists of a single, optional section name line and one required key/pair line.
Because of the many line end characters, we will use HTML display of the results.
The line end characters leave many confusing gaps in the console output.
(function rules() {
try {
const apgJs = require('apg-js');
const writeHtml = require('../writeHtml');
const grammar = new (require('./grammars/ini'))();
const { apgExp } = apgJs;
const { apgLib } = apgJs;
let exp;
let result;
let str;
let html;
let page;
let htmlName;
const flags = '';
exp = new apgExp(grammar, flags);
console.log();
console.log('Demonstrate named matched phrases.');
console.log();
console.log('SABNF grammar:');
console.log(exp.sourceToText());
str = '';
str += '; comment\n';
str += 'input = 1000\n';
result = exp.exec(str);