Skip to content

Instantly share code, notes, and snippets.

@asford
Last active January 1, 2016 08:49
Show Gist options
  • Save asford/8121304 to your computer and use it in GitHub Desktop.
Save asford/8121304 to your computer and use it in GitHub Desktop.
PEG.js selection grammar.
// Property based selections
{
function SelectionPredicate(selectionname)
{
this.selectionname = selectionname;
}
function ClassPredicate(classname)
{
this.classname = classname;
}
function Predicate(property, selector)
{
this.property = property;
this.selector = selector;
}
function Integer(digits) {
return parseInt(digits.join(""), 10);
}
function Range(start, end) {
this.start = start;
this.end = end;
}
function Selector (value) {
if (value instanceof Range)
{
this.values = {};
this.ranges = [value];
}
else
{
this.values = {}
this.values[value] = true;
this.ranges = [];
}
this.join = function(other) {
for (var attrname in other.values) { this.values[attrname] = other.values[attrname]; }
for (var li in other.ranges) {this.ranges.push(other.ranges[li]);}
}
}
}
selection =
selection:(chaini_selection / chain_selection / residue_selection / element_selection / atom_selection / class_selection/ named_selection)
{
console.log(selection);
return selection;
}
chaini_selection "chain selection" =
"chain" "i"? " " selector:integer_selector
{
return new Predicate("chaini", selector);
}
chain_selection "chain selection" =
"chain" "i"? " " selector:identifier_selector
{
return new Predicate("chain", selector);
}
residue_selection "residue_selection" =
"res" ("i" "due"?)? " " selector:integer_selector
{
return new Predicate("residue", selector);
}
element_selection "element selection" =
"elem" "ent"? " " selector:identifier_selector
{
return new Predicate("element", selector);
}
atom_selection "atom selection" =
"atom" ("n" "ame"?)? " " selector:identifier_selector
{
return new Predicate("atomn", selector);
}
class_selection "class name" =
name:("bb" / "sc")
{
return new ClassPredicate(name);
}
named_selection "selection name" =
selectionname:identifier
{
return new SelectionPredicate(selectionname);
}
// Basic identifier parsers
identifier_selector
= value:identifier next:("," identifier_selector)*
{
s = new Selector(value);
if(next.length > 0)
{
next_selector = next[0][1];
s.join(next_selector);
}
return s;
}
identifier =
id:[a-zA-Z_]+
{
return id.join("");
}
integer_selector =
value:(integer_range / integer) next:("," integer_selector)*
{
s = new Selector(value);
if(next.length > 0)
{
next_selector = next[0][1];
s.join(next_selector);
}
return s;
}
integer_range "range"
= start:integer "-" end:integer { return new Range(start, end); }
integer "integer"
= digits:([0-9]+) { return Integer(digits); }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment