使用递归下降解析器编写带有嵌套if条件的代码。

huangapple 未分类评论42阅读模式
英文:

Writing a recursive descent parser with nested if-conditions

问题

// if <cond> <statement>
else if (token.equals("if")) {
    token = getToken();
    cond1 = (parseCond(token));
    cond = (cond1) && (cond);

    token = getToken();
    execute = (cond) && (execute);
    parseStmt(cond, token);
    token = getToken();

    if (token.equals("else")) {
        if (cond) {
            execute = false;
            token = getToken();
            parseStmt(cond, token);
        } else {
            execute = (cond) && (execute);
            token = getToken();
            parseStmt(cond, token);
            cond = true;
            execute = true;
            token = getToken();
        }
    } else {
        line = token + line;
    }
}
英文:

I am writing a recursive descent parser for parsing a specific grammar, and I have to do the nested if/else in that grammar.

The grammar is as follows:

&lt;statement&gt; ::= if &lt;cond&gt; &lt;statement&gt; 

In the parseStmt we have to do the following: basically the getToken() method will remove blanks and grab the token.

// if &lt;cond&gt; &lt;statement&gt;
else if (token.equals(&quot;if&quot;)) {
	token = getToken();
	cond1 = (parseCond(token));
	cond = (cond1) &amp;&amp; (cond);

	token = getToken();
	execute = (cond) &amp;&amp; (execute);
	parseStmt(cond, token);
	token = getToken();

	if (token.equals(&quot;else&quot;)) {
		if (cond) {
			execute = false;
			token = getToken();
			parseStmt(cond, token);
		} else {
			execute = (cond) &amp;&amp; (execute);
			token = getToken();
			parseStmt(cond, token);
			cond = true;
			execute = true;
			token = getToken();
		}
	} else {
		line = token + line;
	}
}

huangapple
  • 本文由 发表于 2020年4月8日 21:33:44
  • 转载请务必保留本文链接:https://java.coder-hub.com/61101962.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定