Syntax directed definition (count number of pairs of parentheses)

1.3k views Asked by At

given the following grammar I have to find the appropriate semantic actions to calculate, for each string of the language, the number of pairs of parentheses in the string.

S -> (L)

S -> a

L -> L, S

L -> S

Usually, to perform this type of exercise, I build a derivation tree of a sample string and then I add the attributes. After that it is easier to find the semantic rules.

So I built this derivation tree for the string "((a, (a), a))", but I can't proceed with the resolution of the exercise. How do I count the pairs of parentheses? I'am not able to do that...

enter image description here

I do't want the solution but I'd like someone to help me with the reasoning to be made in these cases.

(I'm sorry for the bad tree...)

2

There are 2 answers

1
Brian Tompsett - 汤莱恩 On

The OP wrote:

These might be the correct semantic actions for this grammar?

S -> (L) {S.p = counter + 1}

S -> a {do nothing}

L -> L, S {L.p = S.p}

L -> S {L.p = S.p}

.p is a synthesized attribute.

0
Praveen Karmakar On
S-> (S)     { S.count =S.count + 1} 
S-> SS{ S.count  = S.count + S.count}
S-> ϵ{S.count = 0}

This should make things clear