简体   繁体   English

词法分析器输出问题

[英]Lexical analyzer output issue

This is my lexical analyzer code when I enter as an input the following : 当我输入以下内容时,这是我的词法分析器代码:

/*This is an example */

program
        var a,b:integer;

begin

        a =2;

        b =a+5;

        write(a);

        if b==1 then write(a);

end

the output must be like this : 输出必须是这样的:

<res,program>
<res,var> <id,a>,<id,b>:<res,integer>;
<res,begin>
<id,a> <assign,=><num,2>;
<id,b> <assign,=><id,a><addop,+><num,5>;
<res,write>(<id,a>);
<res,if> <id,b><relop,==><num,1> <res,then> <res,write>(<id,a>);
<res,end>

but I my output is : 但我的输出是:

Lexical Error~/hedor1>exampler < input\ .txt 
<res,program><res,var><id,a>,<id,b>:<res,integer>;<res,begin><id,a><assign,=><num,2>;<id,b><assign,=><id,a><addop,+><num,5>;<res,write>(<id,a>);<res,if><id,b><relop,==><num,1><res,then><res,write>(<id,a>);<res,end>

I don't know why it just avoids the newline and doesnot print it to the output although I have defined that in my patterns section \\n printf("\\n"); 我不知道为什么它只避免换行并且不将其打印到输出中,尽管我在模式部分\\n printf("\\n");定义了它\\n printf("\\n"); what is the problem? 问题是什么?

Nowhere in your input do you have a single newline by itself. 输入中的任何地方都没有单独的换行符。 All you have are sequences of one or more whitespace characters (spaces, tabs and newlines). 您所拥有的只是一个或多个空格字符(空格,制表符和换行符)的序列。 Since you have a rule that matches that, Flex uses the longest match. 由于您有匹配的规则,因此Flex使用最长的匹配项。

Flex generates a greedy parser, which tries to match as much of the input as possible. Flex生成一个贪婪的解析器,该解析器尝试匹配尽可能多的输入。 For example, if it sees the input reality , it doesn't stop after matching real and then go on and match ity as a separate token. 例如,如果它看到输入现实中 ,它并不真正匹配后停止,然后去和匹配,两者均作为一个单独的令牌。 Instead, it matches all of reality . 相反,它符合所有现实

In the same way, in your input after the starting comment you have not one but two newlines (since there is an empty line there), and this will be matched by your {whitespace}+ rule, instead of twice by the \\n rule. 以同样的方式,在开始注释之后的输入中,您没有一个,而是两个换行符(因为那里有一个空行),这将由您的{whitespace} +规则匹配,而不是由\\ n规则匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM