How to use the pegjs.buildParser function in pegjs

To help you get started, we’ve selected a few pegjs examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github homizu / js-macro / ex-js / make_exjs_tree.js View on Github external
path.exists(parserFile, function(file) {
                        if (file) {
                            if (debug) console.log('Find a parser');
                            parser = require(parserFile);
                        } else {
                            // re-generate a parser
                            try {
                                if (debug) console.log('Re-building a parser ...');
                                grammar = grammar + macro;
                                start = new Date();
                                parser = PEG.buildParser(grammar, { cache: true, trackLineAndColumn: true });
                                end = new Date();
                                if (debug) console.log('Done.\nTime: %ds.\n', (end.getTime() - start.getTime()) / 1000);
                            } catch (e) {
//                                console.log("Line " + e.line + ", column " + e.column + ": " + e.message + "\n");
                                printErrorMessage(e);
                                process.exit(1);
                            }
                        }

                        // make a parse tree
                        try {
                            if (debug) console.log('Parsing a JavaScript code ...');
                            start = new Date();
                            tree = parser.parse(jsCode, 'start');
                            end = new Date();
                            if (debug) console.log('Done.\nTime: %ds.\n%s', (end.getTime() - start.getTime()) / 1000, JSON.stringify(tree, null, 2));
github vvakame / review.js / benchmark / index.js View on Github external
// RESULT peg.js master/HEAD
// parse0 x 26.06 ops/sec ±5.00% (49 runs sampled)
// parse1 x 123 ops/sec ±1.32% (81 runs sampled)
// parse2 x 121 ops/sec ±1.08% (80 runs sampled)
// Fastest is parse1

var fs = require("fs");
var content = fs.readFileSync("./vvakame.re", {encoding: "utf8"});

var PEG = require("pegjs");

var reviewParser = require("../resources/grammar").PEG;

var baseGrammar = fs.readFileSync("../resources/grammar.pegjs", {encoding: "utf8"});
var base1 = PEG.buildParser(baseGrammar);
fs.writeFileSync("./base1.js", base1.parse.toString() + "\n module.exports = peg$parse;");
var base1parser = require("./base1");

var base2 = PEG.buildParser(baseGrammar, {cache: true});
fs.writeFileSync("./base2.js", base2.parse.toString() + "\n module.exports = peg$parse;");
var base2parser = require("./base2");

var benchmark = require('benchmark');
var suite = new benchmark.Suite();
suite
	.add("parse0", function() {
		reviewParser.parse(content);
	})
	.add("parse1", function() {
		base1parser(content);
	})
github sergi / abcnode / test / test_parser.js View on Github external
var fs = require("fs");
var PEG = require("pegjs");

var parser = PEG.buildParser(fs.readFileSync("parser.pegjs", "utf8"));
var tunes = fs.readFileSync("test/tunes.txt", "utf8").split("\n\n");
var mistakes = 0;

tunes.forEach(function(p) {
    try {
        var parsed = parser.parse(p + "\n");
        console.log("\x1B[0;32m:)\x1B[0m " + parsed.header.title)
        //console.log(JSON.stringify(parsed, null, 2))
    }
    catch (error) {
        console.log("\x1B[0;31m\nSyntax Error:");
        console.log(error.message);
        console.log("line: " + error.line);
        console.log("column: " + error.column);

        var debugLine = Array(error.column).join("-") + "^";
github IdeaBlade / Breeze / _Internal / Mongo / ExpressDemo / parse.js View on Github external
var fs = require("fs");

console.log("reading file...");

var filename = "odata.pegjs1";
if (!fs.existsSync(filename)) {
    throw new Error("Unable to locate file: " + filename);
}
var pegdef = fs.readFileSync(filename, 'utf8');

console.log("reading file completed");

var t0;
var parser;
try {
    parser = PEG.buildParser(pegdef);
} catch (e) {
    throw e
}

t0 = tryParse("$filter='xxx'");

t0 = tryParse("$filter=Name/foo")


parseAndCompare("$filter","$filter=Name eq 'John'",
    { type: "op_bool", op: "eq",
        p1: { type: "member", value: "Name" },
        p2: { type: "lit_string", value: "John"}
    });
github medic / L7 / definitions / query.js View on Github external
var fs = require('fs'),
    path = require('path'),
    definition,
    pegjs = require('pegjs');

definition = fs.readFileSync(path.join(__dirname, 'query.pegjs'), 'utf8');

module.exports = pegjs.buildParser(definition);
github Seikho / node-chess / src / engine / parsers / stringParsers / fen.ts View on Github external
import { StringParser } from '../../../types';
const PEG = require("pegjs");

const parser: StringParser = PEG.buildParser(`
	Start
	= WS r:RankList WS t:Turn WS c:Castling WS Enpassant WS h:HalfMove WS m:Move WS
	{ return {
	ranks: r,
	turn: t,
	castling: c,
	halfMove: h,
	fullMove: t };
	}
	RankList
	= head:Rank "/" tail:RankList { return [].concat(head,tail); }
	/ Rank

	Rank
	= rank:[a-zA-Z0-9]+ { return rank.join(''); }
github elastic / kibana / src / core_plugins / timelion / server / handlers / lib / parse_sheet.js View on Github external
*
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

import { i18n } from '@kbn/i18n';
import fs from 'fs';
import path from 'path';
import _ from 'lodash';
const grammar = fs.readFileSync(path.resolve(__dirname, '../../../public/chain.peg'), 'utf8');
import PEG from 'pegjs';
const Parser = PEG.buildParser(grammar);

export default function parseSheet(sheet) {
  return _.map(sheet, function (plot) {
    try {
      return Parser.parse(plot).tree;
    } catch (e) {
      if (e.expected) {
        throw new Error(
          i18n.translate('timelion.serverSideErrors.sheetParseErrorMessage', {
            defaultMessage: 'Expected: {expectedDescription} @ character {column}',
            values: {
              expectedDescription: e.expected[0].description,
              column: e.column,
            },
          })
        );
github atom / atom / script / lib / transpile-peg-js-paths.js View on Github external
function transpilePegJsPath(pegJsPath) {
  const inputCode = fs.readFileSync(pegJsPath, 'utf8');
  const jsPath = pegJsPath.replace(/pegjs$/g, 'js');
  const outputCode =
    'module.exports = ' + peg.buildParser(inputCode, { output: 'source' });
  fs.writeFileSync(jsPath, outputCode);
  fs.unlinkSync(pegJsPath);
}
github grncdr / js-shell-parse / build.js View on Github external
function getSource () {
  delete require.cache[require.resolve('./overrides')]
  var grammar = fs.readFileSync(input, 'utf8')
  var parserSource = pegjs.buildParser(grammar, {
    output: "source",
    allowedStartRules: [
      'script',
      'command',
      'argument',
      'continuationStart'
    ],
    plugins: [overrideAction],
    overrideActionPlugin: require('./overrides')
  })
  return 'module.exports = parse\n\n' +
         parse + '\n' +
         'var parser=' + parserSource + '\n' +
         'module.exports.SyntaxError = parser.SyntaxError\n';

}
github tmcnab / Hyperglot / js / app.grammar.js View on Github external
function buildParser() {
		var input = localStorage.getItem('app.grammar.text') || "";
		try {
			var preamble = "{\n var ast = require('ast-types').builders;\n}\n";
			var opts = {
 							 cache: self.options.cache(),
				trackLineAndColumn: true//self.options.trackLineAndColumn()
			};

			self.parser = require("pegjs").buildParser(preamble + input, opts);
			app.nav.info('[PEGjs] Parser constructed.')
		}
		catch (ex) {
			self.parser = null;
			app.nav.error('[PEGjs] ' + ex.message);
		}
	}