question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Passing variables to grammar for contextual post-processing

See original GitHub issue

I have a nearley grammar set up to produce a different value depending on the context in which it’s parsed. I’ve got this working using require() but it’s super complicated as I need to keep track of everything that is calling the parser and must make sure the grammar knows which is the correct context to reference. It would be significantly easier if I could just pass a context variable to the grammar. I can do this by editing the output of nearleyc like so:

const parser = new nearley.Parser(nearley.Grammar.fromCompiled(grammar(context)))
(function (context) {
    var grammar = {
        Lexer: undefined,
        ParserRules: [
             ...,
             {"name": "localVar", "symbols": [{"literal":"$"}, "string"], "postprocess": d => context[d[1]]},
             ...
        ]
      , ParserStart: "value"
    }
    if (typeof module !== 'undefined'&& typeof module.exports !== 'undefined') {
       module.exports = grammar;
    } else {
       window.grammar = grammar;
    }
});

However, every time I rerun nearleyc the modifications get overwritten. Is there a way to write the grammar.ne file so it can be passed a variable for contextual postprocessing?

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:13 (3 by maintainers)

github_iconTop GitHub Comments

12reactions
marthoffcommented, Jul 19, 2020

Hi ryanking1809,

I had a similar problem, but found a much easier solution maybe this helps someone.

I passed a variable to the grammar object when using it like this: grammar.lookup = (name) => { return map[name]; }

Then I can use this in my postprocessors like that: variable -> [A-Z]:+ {% d => grammar.lookup(d[0]) %}

No need to change the generated code or other hacks.

Hope this helps.

Cheers, Martin

4reactions
ryanking1809commented, Sep 9, 2019

I’ll leave this here in case anyone is looking for a solution in the future. It’s a bit of a hacky find and replace function, but it does the job. Just dump the following in a generate.js file and run node generate.js

var exec = require("child_process").exec;
var fs = require("fs");

var inputFile = "grammar.ne";
var outputFile = "grammar.js";
var args = ["context"];

// execute nearleyc to produce generated js file
// then update the generated file to acepts args
exec(`nearleyc ${inputFile} -o ${outputFile}`, function(err, stdout, stderr) {
	if (err) return console.error(err);
	fs.readFile(outputFile, "utf8", function(err, data) {
		if (err) return console.log(err);
		var result = data
			// replace initial function def to accept args
			// and export - could use module.exports later
			.replace(
				`(function () {`,
				`export default function (${args.join(",")}) {`
			)
			// we need to return grammar from the function - could be cleaner
			.replace(`module.exports =`, `return`)
			.replace(`window.grammar =`, `return`)
			// then ensure function isn't executed until later
			.replace(`})();`, `};`);
		fs.writeFile(outputFile, result, "utf8", function(err) {
			if (err) return console.error(err);
		});
	});
});

This makes the grammar file a function that needs to be called with the introduced arguments.

new nearley.Parser(nearley.Grammar.fromCompiled(grammar(context)))
Read more comments on GitHub >

github_iconTop Results From Across the Web

Writing Custom Effects | Post Processing | 2.2.2 - Unity - Manual
This context holds useful data that you can use and is passed around effects when they are rendered. Look into /PostProcessing/Runtime/PostProcessRenderContext.
Read more >
Writing custom effects | Post Processing | 3.2.2
The PostProcessRenderContext context holds data that Unity passes around effects when it renders them. You can find out what data is ...
Read more >
Template post-processing fields - ServiceNow Docs
The list displays execution results and the variables you passed into the activity on the Inputs form. All activity variables added in the ......
Read more >
Using the ggmcmc package
ggplot2 , based on the grammar of graphics (Wilkinson et al. ... all parameters that contain the character string sigma will be passed...
Read more >
Writing a parser - Nearley - JS.ORG
This section describes the nearley grammar language, in which you can describe ... Macros are dynamically scoped, which means they see arguments passed...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found