'Counting the number of specific type of variables in Yacc

I've just started to learn how to use Lex and Yacc. I'm using the grammar described in these sites(http://www.quut.com/c/ANSI-C-grammar-l-2011.html, http://www.quut.com/c/ANSI-C-grammar-y-2011.html).

I'm currently trying to apply the Yacc grammar to the code I'm working on: Counting specific type of variables(e.g. counting number of int variables) or count how many arrays have been declared.

In definition section, I additionally wrote like this:

%{
#include<stdio.h>
int num;
%}

For yacc to recognize such variable as int, I want to change the code below in rule section:

declaration 
    : declaration_specifiers ';'
    | declaration_specifiers init_declarator_list ';'
    ; 

like this:

declaration
    : type_specifier init_declarator_list ';'
    | type_specifier IDENTIFIER '[' primary_expression ']' ';'
    ;

or to be specific, if I were to count INT variables or array consisted of int, the code might be written like this:

declaration
    : INT init_declarator_list ';' {num++;}
    | INT IDENTIFIER '[' primary_expression ']' ';' {num++;}
    ;

and apparently this code will cause syntax error if I just edit like that. Moreover, it would not be able to count variables if C code was like this:

int a,b;

Only to count once. What move should I make in order to make it work? Thank you in advance.



Solution 1:[1]

You can't do this (correctly) with just a parser, because the following is a completely legal way of declaring an int variable:

typedef int MyType;
MyType x;

(Typedefs in C are aliases, not new types. So there is no difference between MyType and int after the above.)

It may well be the case that int32_t is a type alias for int, on a particular platform. So that's not just theoretical.

Even leaving that aside, trying to modify the grammar is probably a lot more work than using the grammar. My suggestion is that you create some kind of representation of types (something like an AST) and then use the semantic action for the variable declaration to see if the type being declared is a simple int or something else.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 rici