-
Title:
Parsing Javascript Expressions Solution - Programming Languages
-
Description:
-
In this problem we’re going to build the part of
-
our javascript parser that handles javascript
-
expressions. This is pretty straightforward, just
-
like the last problem where we’re essentially
-
numerating all the rules that we’ve predefined
-
for our javascript language. So let’s go right
-
through the I, the E.
-
So here we have the supply code for the
-
problem and if we look closely, we see that
-
almost all the parse float are numerated to
-
exactly what they should be. We have Identifier,
-
numbers, strings, true and false, how to handle a
-
not keyword do the opposite and then for
-
expressions. We are also given an enumeration
-
of the precedence and the associativity for each
-
of these operations.
-
So really we have everything we need in the
-
problem description to do this problem. And as
-
you can see here, I’ve already filled in the
-
precedence ordering for the operations. And this
-
has simply taken almost exactly right from the
-
comment given in the problem where or is listed
-
at the lowest precedence and we go all the way
-
up to division, right here. I’ve also added not
-
just to make it work.
-
So let’s start filling in the rules. My first rule is
-
going to handle. If we add a matching left and
-
right parenthesis, the expression that is equal to
-
is simply the contents of the parenthesis, pretty
-
straightforward. And now I have four rules for
-
some of our literal values. We have a number,
-
we’re going to say number and then the contents
-
of that string, just simply say the word string,
-
we’ve matched true or false, we’re going to
-
return the specified tuples. If we see a notch,
-
then we simply have in our Pastry that we’re not
-
and then the contents that are being.
-
Afterwards, we have about a dozen or so binary
-
rules. Addition, subtraction, times, modulus
-
division etcetera, etcetera and to save some time
-
I could enumerate each function, but I want to
-
take a short cut. So here I’ve said if we match
-
any of these things, I’m calling it a binary
-
operation. For the first element is new left,
-
upper end of the binary operation. The next
-
entry in our tuple is going to be the operation
-
being used and the last one its going to be the
-
right upper hand of the binary operation.
-
And now I have the expressions for function
-
calls, not just decorations, which we had in the
-
last problem. A function call is going to be
-
identifier, with optional argument in between
-
parenthesis. And the code for handling optional
-
arguments is almost exactly the same as the
-
code we use to handle, optional arguments in
-
the function decoration. In fact, I think it is
-
exactly the same. And with all that, we’ve done
-
it. It’s about 50 lines a code and we are happy.