N
N
Nikolai Petrenko2015-04-08 13:38:25
JavaScript
Nikolai Petrenko, 2015-04-08 13:38:25

JavaScript - How to write your own lexer \ parser?

Please help me with such a thing, I don't know what to call it.
There is a Textarea in which there will be some code
, it will be converted into normal javascript code
. Example:
if(1 NOT 2)
{
alert = "1 is not equal to 2"
}
else
{
alert = "1 equals 2"
}
Which translates to
if(1 != 2)
{
alert("1 is not equal to 2");
}
else
{
alert("1 equals 2");
}
There are some sketches, but this is something not right, it seems to be what is required, but it works anyhow, but in principle it is written the same way, anyhow.
$("[name=in]").keyup(function()
{
var value = $("[name=in]").val();
value = value.replace("not", "!=");
$("[name=out]").val(value);
$("[name=out]").val($("[name=out]").val().replace(/not/g,"!="));
$("[name=out]").val($("[name=out]").val().replace(/is/g,"=="));
$("[name=out]").val($("[name=out]").val().replace(/yes/g,"true"));

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander Rulev, 2015-04-08
@Kingleonide

For javascript, I advise you to look at PEG.js . It is mastered in an hour or two, plus PEG grammars are extremely powerful, capable of describing even context-sensitive grammars in places (usually only context-free ones are used).
Plus there is an online version that you can poke (although be careful with it, if you enter something that does an eternal loop in parsing, then the page will freeze tightly and most likely lose all your grammar).

N
Nikolai Petrenko, 2015-04-08
@Kingleonide

But thanks for the way, but as I said above, this is something wrong.
I want to achieve the result as let's say in cofeeScript
//cofeeScript
if happy and knowsIt
clapsHands()
chaChaCha()
//JavaScript
if (happy && knowsIt)
{
clapsHands();
chaChaCha();
}
I mean about brackets after if (...){...} how to expose them when writing
if param and param2
if(param && param2)
That is, how to make a wrapper?

K
Konstantin Kitmanov, 2015-04-08
@k12th

You need a parser generator . If you manage to write a grammar, you will get everything you want, even if your coffeescript is even better.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question