Skip to content

Commit ad166ad

Browse files
committed
finally finished this lesson, however, homework is not done yet
1 parent 7b32477 commit ad166ad

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

nathansununiversity_03.js

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,3 +138,77 @@ space =
138138
spaceatom =
139139
space natom:atom
140140
{ return natom; }
141+
142+
143+
// Page 7
144+
// a very ... chicky implementation, guess it is not the original purpose
145+
// of author, will re-visit when have time
146+
// hint of page:
147+
// I added a new rule comma at the top then modified the start and primary rules.
148+
start =
149+
additive
150+
151+
symbol =
152+
"+"
153+
/ ","
154+
155+
additive =
156+
left:multiplicative symbol:symbol right:additive
157+
{ return {tag: symbol, left:left, right:right}; }
158+
/ multiplicative
159+
160+
multiplicative =
161+
left:primary "*" right:multiplicative
162+
{ return {tag: "*", left:left, right:right}; }
163+
/ primary
164+
165+
primary =
166+
integer
167+
/ "(" additive:additive ")"
168+
{ return additive; }
169+
170+
integer =
171+
digits:[0-9]+
172+
{ return parseInt(digits.join(""), 10); }
173+
174+
// test for above on the page
175+
var parse = wrapExceptions(PEG.buildParser(answer).parse);
176+
177+
assert_eq(parse("1+2"),
178+
{tag:"+", left:1, right:2},
179+
"parse 1+2");
180+
assert_eq(parse("1+2*3"),
181+
{tag:"+", left:1, right:{tag:"*", left:2, right:3}},
182+
"parse 1+2*3");
183+
assert_eq(parse("1,2"),
184+
{tag:",", left:1, right:2},
185+
"parse 1,2");
186+
assert_eq(parse("1,2+3"),
187+
{tag:",", left:1, right:{tag:"+", left:2, right:3}},
188+
"parse 1,2+3");
189+
assert_eq(parse("1*2,3"),
190+
{tag:",", left:{tag:"*", left:1, right:2}, right:3},
191+
"parse 1*2,3");
192+
193+
194+
195+
// Page 8, howto write simple test case in node.js
196+
var PEG = require('pegjs');
197+
var assert = require('assert');
198+
var fs = require('fs'); // for loading files
199+
200+
// Read file contents
201+
var data = fs.readFileSync('my.peg', 'utf-8');
202+
// Show the PEG grammar file
203+
console.log(data);
204+
// Create my parser
205+
var parse = PEG.buildParser(data).parse;
206+
// Do a test
207+
assert.deepEqual( parse("(a b c)"), ["a", "b", "c"] );
208+
209+
// One trick that might be helpful is that the PEG parsers
210+
// you generate can be started from rules other than start.
211+
assert.deepEqual(parse("a4[100]", "note"),
212+
{tag:"note", pitch:"a4", dur:100});
213+
214+
// TODO: Homework

0 commit comments

Comments
 (0)