How to use nearley - 10 common examples

To help you get started, we’ve selected a few nearley 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 vpdb / vpx-js / test / script.helper.ts View on Github external
export function vbsToAst(vbs: string): Program {
	const parser = new Parser(Grammar.fromCompiled(vbsGrammar));
	parser.feed(vbs.trim() + '\n');
	/* istanbul ignore if */
	if (parser.results.length === 0) {
		throw new Error('Parser returned no results.');
	}
	return parser.results[0] as Program;
}
github tjvr / tosh2 / editor / index.js View on Github external
compile() {
    const source = this.cm.getValue()
    // TODO cache compiled-ness
    const model = this._model
    const parser = new nearley.Parser(grammar)
    try {
      parser.feed(source)
    } catch (e) {
      console.error(e)
      model.scripts = { error: e }
      return
    }
    const results = parser.results
    if (results.length > 1) throw new Error("Ambiguous!")
    const scripts = []
    const x = 10
    var y = 10
    for (let script of results[0]) {
      scripts.push([x, y, script])
      y += measure(script) + 10
    }
github mimic-sussex / sema / src / language / nearley.worker.js View on Github external
import * as nearley from 'nearley/lib/nearley.js';
import * as grammar from './livelang.js';
import IRToJavascript from '../IR/IR.js'

var parserStartPoint;
let processor = nearley.Grammar.fromCompiled(grammar);
let parser = new nearley.Parser(processor);
parserStartPoint = parser.save();
console.log('Nearley parser loaded')

var ts = 0;
onmessage = (m) => {
  // console.log(m.data);
  if (m.data !== undefined) {
    try {
      parser.feed(m.data);
      // console.log(parser.results)
      postMessage({
        "treeTS": 1
      });
      console.log(JSON.stringify(parser.results));
      let jscode = IRToJavascript.treeToCode(parser.results);
github mimic-sussex / sema / src / language / nearley.worker.js View on Github external
import * as nearley from 'nearley/lib/nearley.js';
import * as grammar from './livelang.js';
import IRToJavascript from '../IR/IR.js'

var parserStartPoint;
let processor = nearley.Grammar.fromCompiled(grammar);
let parser = new nearley.Parser(processor);
parserStartPoint = parser.save();
console.log('Nearley parser loaded')

var ts = 0;
onmessage = (m) => {
  // console.log(m.data);
  if (m.data !== undefined) {
    try {
      parser.feed(m.data);
      // console.log(parser.results)
      postMessage({
        "treeTS": 1
      });
      console.log(JSON.stringify(parser.results));
      let jscode = IRToJavascript.treeToCode(parser.results);
      jscode.paramMarkers = JSON.stringify(jscode.paramMarkers);
github vpdb / vpx-js / lib / scripting / transpiler.ts View on Github external
private parse(vbs: string): Program {

		const parser = new Parser(Grammar.fromCompiled(vbsGrammar));
		parser.feed(vbs);
		/* istanbul ignore if */
		if (parser.results.length === 0) {
			throw new Error('Parser returned no results.');
		}
		return parser.results[0];
	}
github accordproject / cicero / packages / cicero-core / src / parsermanager.js View on Github external
static compileGrammar(sourceCode) {

        try {
            // Parse the grammar source into an AST
            const grammarParser = new nearley.Parser(nearleyGrammar);
            grammarParser.feed(sourceCode);
            const grammarAst = grammarParser.results[0]; // TODO check for errors

            // Compile the AST into a set of rules
            const grammarInfoObject = compile(grammarAst, {});
            // Generate JavaScript code from the rules
            const grammarJs = generate(grammarInfoObject, 'grammar');

            // Pretend this is a CommonJS environment to catch exports from the grammar.
            const module = {
                exports: {}
            };
            eval(grammarJs);
            return module.exports;
        } catch (err) {
            Logger.error(err);
github alyssarosenzweig / uPresent / browser / IDE / browser.publish.js View on Github external
function publish(input, shouldMinify, useFS, filePrefix) {
    var parser = new nearley.Parser(grammar.ParserRules, grammar.ParserStart);
    
    if(!filePrefix) filePrefix = "";

    var cssFile = filePrefix + "common.css";
    var themeFile = filePrefix + "themes/modern.dark.css";
    var jsFile = filePrefix + "scripts.js";

    if(useFS) {
        fs = require("fs"); // intentional lack of var keyword
    }

    parser.current = 0;
    parser.feed(input);

    var res = parser.results[0];
    var code = "";
github tridactyl / tridactyl / src / background / nearley_utils.ts View on Github external
constructor(grammar) {
        this.parser = new nearley.Parser(nearley.Grammar.fromCompiled(grammar))
        this.initial_state = this.parser.save()
        /* this.results = this.parser.results */
    }
github bijection / nearley-playground / src / client / compile.js View on Github external
}
            if (opts.alreadycompiled.indexOf(path) === -1) {
                opts.alreadycompiled.push(path)
                if (path === 'postprocessors.ne') {
                    var f = require('nearley/builtin/postprocessors.ne')
                } else if (path === 'whitespace.ne') {
                    var f = require('nearley/builtin/whitespace.ne')
                } else if (path === 'string.ne') {
                    var f = require('nearley/builtin/string.ne')
                } else if (path === 'number.ne') {
                    var f = require('nearley/builtin/number.ne')
                } else if (path === 'cow.ne') {
                    var f = require('nearley/builtin/cow.ne')
                }

                var parserGrammar = nearley.Grammar.fromCompiled(bootstraped)
                var parser = new nearley.Parser(parserGrammar)
                parser.feed(f)
                var c = Compile(parser.results[0], {
                    file: path,
                    __proto__: opts
                })

                result.rules = result.rules.concat(c.rules)
                result.body = result.body.concat(c.body)
                // result.customTokens = result.customTokens.concat(c.customTokens);
                Object.keys(c.config).forEach(function(k) {
                    result.config[k] = c.config[k]
                })
                Object.keys(c.macros).forEach(function(k) {
                    result.macros[k] = c.macros[k]
                })
github mahirshah / css-property-parser / src / expandShorthandProperty.js View on Github external
throw new UnsupportedPropertyError(propertyName);
  } else if (CSS_CONSTANTS.globalValues.includes(propertyValue)) {
    return getShorthandComputedProperties(propertyName).reduce((propertyMap, computedPropertyName) => (
      Object.assign({ [computedPropertyName]: propertyValue }, propertyMap)
    ), {});
  }

  // get the compiled grammar file for this property
  const grammar = grammars[propertyName];
  // remove any block style comments and extra whitespace
  const formattedPropertyValue = propertyValue.replace(R_BLOCK_COMMENT, ' ').replace(/\s+/g, ' ').trim();
  let parser;

  // attempt to parse the css value, using the property specific parser
  try {
    parser = new nearley.Parser(nearley.Grammar.fromCompiled(grammar)).feed(formattedPropertyValue);
  } catch (parseError) {
    throw new ParseError(`Error parsing shorthand property ${propertyName}: ${propertyValue}. ${parseError.message}`);
  }

  // get the first parsing and use the formatter for the specific shorthand type for this property
  const { shorthandType } = shorthandProperties[propertyName];
  const [rootNode] = parser.results;
  LocationIndexTracker.reset();
  let propertyExpansion = shorthandPropertyTypeToActionDictionaryFactoryMap[shorthandType]
    .format(propertyName, rootNode, formattedPropertyValue);

  if (recursivelyResolve) {
    Object.keys(propertyExpansion).forEach((prop) => {
      if (shorthandProperties[prop]) {
        Object.assign(
          propertyExpansion,