diff --git a/README.md b/README.md index e890da4..f19d242 100644 --- a/README.md +++ b/README.md @@ -38,10 +38,18 @@ start = grammar ``` -When you ```@import``` another grammar, that grammar's topmost rule becomes accessible in the context of the current grammar under one of two possible rule names: +When you ```@import``` another grammar, that grammar's topmost rule becomes accessible in the context of the current grammar under one of two possible rule names: - A name you provide explicitly through the use of the optional "as" parameter - The basename of the file, corrected to be a valid Javascript identifier (so if the file were called /foo/bar/my-grammar.peg, the rule name would be my_grammar). +pegjs-import will cache rules it has parsed. You can clear this local cache by calling `clearCache`: +```javascript + var pegimport = require('pegjs-import'); + + pegimport.clearCache(); +``` + + ## Changes from stock PEG.js behavior * You cannot supply ```options.allowedStartRules``` anymore. The only allowed start rule is always the first rule in the grammar. diff --git a/index.js b/index.js index b3115da..e35ca62 100644 --- a/index.js +++ b/index.js @@ -102,4 +102,9 @@ function buildParser(filename, options) { return newParser; }; -module.exports = { buildParser: buildParser }; + +function clearCache() { + parsers = {}; +} + +module.exports = { buildParser: buildParser, clearCache: clearCache }; diff --git a/package.json b/package.json index 9e0a60b..a6901a7 100644 --- a/package.json +++ b/package.json @@ -19,7 +19,8 @@ }, "devDependencies": { "chai": "^1.9.2", - "mocha": "^1.21.5" + "mocha": "^1.21.5", + "mock-fs": "^3.8.0" }, "author": "Harry Schmidt", "license": "MIT", diff --git a/test/spec/core.js b/test/spec/core.js index ac7ec6a..eeb45c5 100644 --- a/test/spec/core.js +++ b/test/spec/core.js @@ -1,8 +1,9 @@ - 'use strict'; var pegimport = require('../../index'), - peg = require('pegjs'); + peg = require('pegjs'), + path = require('path'), + mockFs = require('mock-fs'); describe('peg-import', function() { @@ -66,4 +67,43 @@ describe('peg-import', function() { }); + describe('caching', function() { + var absoluteFilename = path.resolve('test/fixtures/import.peg') + + afterEach(function() { + mockFs.restore(); + }); + + function enableMock() { + var stubbedFixture = 'start = a:.* { return "abc" }'; + + mockFs({ + 'test/fixtures': { + 'import.peg': stubbedFixture + } + }); + } + + function result() { + return pegimport.buildParser(absoluteFilename).parse('123'); + } + + it('works with absolute filenames', function() { + expect(result()).to.deep.equal(['1', '2', '3']); + + enableMock(); + + expect(result()).to.not.equal('abc'); + }); + + it('can be cleared', function() { + expect(result()).to.deep.equal(['1', '2', '3']); + + enableMock(); + pegimport.clearCache(); + + expect(result()).to.equal('abc'); + }); + + }); });