开发者

Bison input analyzer - basic question on optional grammar and input interpretation

开发者 https://www.devze.com 2023-01-01 10:22 出处:网络
I am very new to Flex/Bison, So it is very navie question. Pardon me if so.May look like homework question - but I need to implement project based on below concept.

I am very new to Flex/Bison, So it is very navie question.

Pardon me if so. May look like homework question - but I need to implement project based on below concept.

My question is related to two parts,

Question 1

In Bison parser, How do I provide rules for optional input.

Like, I need to parse the statment

Example :

-country='USA' -state='INDIANA' -population='100' -ratio='0.5' -comment='Census study for Indiana'

Here the ratio token can be optional. Similarly, If I have many tokens optional, then How do I provide the grammar in the parser for the same?

My code looks like,

%start program

program : TK_COUNTRY TK_IDENTIFIER TK_STATE TK_IDENTIFIER TK_POPULATION TK_IDENTIFIER ...

where all the tokens are defined in the lexer. Since there are many tokens which are optional, If I use "|" then there will be many different ways of input combination possible.

Question 2

There are good chance that the comment might have quotes as part of the input, so I have added a token -tag which user can provide to interpret the same,

Example :

-country='USA' -state='INDIANA' -population='100' -ratio='0.5' -开发者_如何学JAVAcomment='Census study for Indiana$'s population' -tag=$  

Now, I need to reinterpret Indiana$'s as Indiana's since -tag=$.

Please provide any input or related material for to understand these topic.


Q1: I am assuming we have 4 possible tokens: NAME , '-', '=' and VALUE

Then the grammar could look like this:

attrs: 
    attr attrs
    | attr
    ;

attr:
   '-' NAME '=' VALUE
   ;

Note that, unlike you make specific attribute names distinguished tokens, there is no way to say "We must have country, state and population, but ratio is optional." This would be the task of that part of the program that analyses the data produced by the parser.

Q2: I understand this so, that you think of changing the way lexical analysis works while the parser is running. This is not a good idea, at least not for a beginner. Have you even started to think about lexical analysis, as opposed to parsing?

0

精彩评论

暂无评论...
验证码 换一张
取 消