dsl language pegjs code example
Example: simple dsl language in peg.js
/**********
Starting rule, our entry point to the parser.
The first part of the PEG extracts the entity name as a string,
and makes the "entity" accessible in the JS below, allowing us to the AST and return it.
It matches certain expected keywords, eg. "has", but does nothing with them.
Finally it extracts the values, which have already been turned into a Values AST.
You'll see the "_" rule used here, this means "accept/skip whitespace", it's defined below.
**********/
Command = entity:Var "." command:Var _ "has" _ "nothing"* _ values:Values* _
{
// Handle case that there are no values
values = values.length === 0 ? [] : values[0];
// Return the matched results with this object structure
return {
entity: entity,
command: command,
values: values
}
}
/**********
Matches a collection of inputs, 0 to many, that are wrapped in parentheses
**********/
Values = "{" _ values:(CompositeValue/Value)* _ "}"
{
return values;
}
/**********
Value and CompositeValues always have the same initial shape, so I extracted
this into a partial result that is extended by both Value and Composite
**********/
ValuePartial = _ "a" [n]? _ cls:Var _ name:Var _
{
return {
class: cls,
param: name
}
}
Value = value:ValuePartial alias:(Alias)? _
{
value.requestParam = (alias) ? alias: value.param;
value.type = 'value';
return value;
}
/**********
Extract the alias value, ignore the "from" string
**********/
Alias = _ "from" _ alias:Var
{
return alias;
}
CompositeValue = value:ValuePartial "from" _ values:Values
{
value.type = 'composite';
value.values = values;
return value;
}
Var = name:[A-Za-z0-9_]*
{
return name.join("");
}
/**********
Match any sequence of "whitespace" characters
**********/
_ = [ \t\n\r]*