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.
この問題ではJavaScriptの構文解析器のうち
JavaScriptの式を扱う部分を書きます
これはとても直接的で
前の問題でJavaScriptの規則を数えて
並べたように解くことができます
早速IDEに移りましょう
問題として与えられたコードがここにあります
よく見ると
構文解析の規則はどうするべきか
すでに書いてあります
ここには識別子、数字、
文字列、真偽値、
notキーワードをどのように扱うか
そして括弧つきの式です
さらに優先順位と結合性も
それぞれ与えられています
つまり行うべきことはすべて書きました
ご覧のとおり演算子の優先順位は
すでに書かれています
これはほとんど問題で与えられた
優先順位の一番低いものから
除算までのリストを書いた
コメントのとおりに書いたのです
この下にDIVIDEとありますね
さらにNOTも動くように加えています
規則を書いていきましょう
最初に扱う規則は括弧にします
対応する左右の括弧の式の値は
中身の式と同じで単純です
ここに4つの即値についての規則を書きました
数は“number”とその中身の文字列で
文字列は“string”と書き 同じようにします
TrueかFalseと一致したら
それを示すタプルを構文解析木にします
notが見つかったら構文解析木に
“not”とその中身を加えます
その後 10個ほどの二項演算子の規則が続きます
加算、減算、乗算、剰余、
除算、などなどです
そえぞれ別に書くこともできますが
時間の節約のために
ショートカットします
これらのうち どれかに一致すれば
それを二項演算子“binop”と呼んで
このタプルの最初の要素にそのように示し
二項演算の左辺となる始めの要素と
演算子そのままと
右辺となる最後の要素も入れます
さらに 以前の問題で行った関数宣言でなく
関数呼び出しの式もあります
関数呼び出しは省略可能な引数とともに
括弧で囲まれた識別子になります
そしてこの省略可能な引数を扱うためのコードは
関数宣言での省略可能な引数を扱う部分と
ほとんど同じです
おそらく完全に同じでしょう
これですべて終わりました
50行ほどのコードで完成です
Neste problema, vamos construir parte do nosso
parser para JavaScript, que trata expressões JavaScript.
Isso é muito fácil e direto, assim como
o último problema, onde essencialmente
enumeramos todas as regras que predefinimos
para nossa linguagem JavaScript. Então, vamos direto
ao IDE.
Aqui temos que fornecer o código para
o problema e, se olharmos mais de perto, veremos que
quase todas as regras do parser estão enumeradas,
exatamente como deveriam ser: temos "identifier",
"numbers", "strings", "true" e "false", como tratar a
palavra chave "not", e depois expressões.
Temos também a relação de precedência de
e de associatividade para cada uma
dessas operações.
Então, temos realmente tudo o que precisamos, na
descrição do problema, para este problema.
E, como você pode ver, eu já preenchi
a ordem de precedência das operações.
E isso é obtido diretamente do comentário
dado no problema, onde "or" é listado na
precedência mais baixa, e prosseguimos até
a divisão, aqui. Eu adicionei também o "not",
para fazer isso funcionar.
Então vamos começar a preencher as regras.
Minha primeira regra vai tratar parênteses: se temos um casamento de
parênteses à esquerda e à direita, a expressão correspondente
é simplesmente o conteúdo dos parênteses -- bem fácil.
E agora eu tenho 4 regras para
alguns dos nossos valores literais: temos "number" --
vamos dizer "number" e o conteúdo disso --
temos "string" -- simplesmente dizemos "string" -- e,
se casamos com "true" ou "false", vamos retornar
as tuplas especificadas. Se vemos um "not",
então simplesmente temos na nossa árvore do parser a palavra "not"
e então o conteúdo que está sendo negado.
Depois disso, temos mais ou menos uma dúzia de regras
para operadores binários: adição, subtração, multiplicação, módulo,
divisão etcetera etcetera. E, para economizar espaço --
eu poderia enumerar cada função, mas quero
um atalho -- eu digo que, se casamos com
qualquer dessas coisas, eu chamo uma operação binária,
sendo o primeiro elemento o operando à esquerda
da operação binária, a entrada seguinte
na tupla é a operação a ser usada,
e a última é
o operando à direita da operação binária.
E agora eu tenho expressões para chamada de funções,
não para declarações, que nós vimos no último problema.
Uma chamada de função será um
identificador, com argumentos opcionais, entre parênteses.
E o código para tratar argumentos opcionais
é quase exatamente o mesmo que
o código que usamos para tratar argumentos opcionais
na declaração de função. De fato, eu acho que é
exatamente o mesimo. E, com tiudo isso, terminamos.
São mais ou menos 50 linhas de codigo e estamos felizes.