Skip to content

Commit

Permalink
parse ws
Browse files Browse the repository at this point in the history
  • Loading branch information
dhconnelly committed Dec 5, 2012
1 parent 96aab30 commit 92d53b5
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 0 deletions.
34 changes: 34 additions & 0 deletions prettybnf.js
Expand Up @@ -4,5 +4,39 @@
exports.version = '0.0.0';
exports.parse = function (g) {};
exports.stringify = function (ast) {};
exports.Parser = Parser;

// ---------------------------------------------------------------------------

function Parser(input) {
var o = (this !== exports) ? this : {};
o.input = input;
o.pos = 0;
o.line = 1;
}

Parser.EOF = -1;

Parser.prototype.peek = function () {
if (this.pos >= this.input.length) return Parser.EOF;
return this.input[this.pos];
};

Parser.prototype.eat = function () {
if (this.pos >= this.input.length) return Parser.EOF;
return this.input[this.pos++];
};

// <ws> ::= <space> <ws> | <empty>;
// <space> ::= " " | "\n" | "\t";
// <empty> ::= "";
Parser.prototype.ws = function () {
var ret = '', ch;
while (' \n\t'.indexOf(ch = this.peek()) >= 0) {
if (ch === '\n') this.line++;
ret += this.eat();
}
return ret;
};

}(typeof exports === 'undefined' ? this.prettybnf = {} : exports));
35 changes: 35 additions & 0 deletions test_prettybnf.js
@@ -1,6 +1,41 @@
/*jshint node: true */
'use strict';

var prettybnf = require('./prettybnf');

exports.testVersion = function (t) {
t.equal(prettybnf.version, '0.0.0');
t.done();
};

// ---------------------------------------------------------------------------

var Parser = prettybnf.Parser;

exports.testParser_peek = function (t) {
var p = new Parser('abc');
t.equal(p.peek(), 'a');
t.equal(p.peek(), 'a');
p.pos = 3;
t.equal(p.peek(), Parser.EOF);
t.equal(p.peek(), Parser.EOF);
t.done();
};

exports.testParser_eat = function (t) {
var p = new Parser('abc');
t.equal(p.eat(), 'a');
t.equal(p.eat(), 'b');
t.equal(p.eat(), 'c');
t.equal(p.eat(), Parser.EOF);
t.equal(p.eat(), Parser.EOF);
t.done();
};

exports.testParser_ws = function (t) {
var p = new Parser(' \n\n \t\n foo');
t.equal(p.ws(), ' \n\n \t\n ');
t.equal(p.peek(), 'f');
t.equal(p.ws(), '');
t.done();
};

0 comments on commit 92d53b5

Please sign in to comment.