eliben / pycparser

:snake: Complete C99 parser in pure Python
Other
3.24k stars 608 forks source link

Prefab implicit declaration types #489

Closed deangelisdf closed 1 year ago

deangelisdf commented 1 year ago

Hi everyone, In my use case I need to parse many small functions and generally each function requires a large number of typedefs to parse. Looking at the source code there is no direct way to implicitly import those types, but you can modify the method _is_type_in_scope

The test code I wrote is followed: import pycparser from pycparser import c_ast, c_generator from typing import List class PrefabParser(pycparser.c_parser.CParser): _prefab_types: List[str] = ['Type_t'] def _is_type_in_scope(self, name:str)->bool: if not name in self._prefab_types: return super()._is_type_in_scope(name) return True fstub = "void stub(){\n Type_t a = (Type_t)0;\n}" parser = PrefabParser() ast = parser.parse(fstub) generator = c_generator.CGenerator() stubline = generator.visit(ast) print(stubline)

Do you know whether this solution may have unexpected issues?

Thanks

eliben commented 1 year ago

It's a hack, but if it works for you I don't see a huge issue here. I'd prefer to just define the typedefs in text and pass it to the parser prepended to your code in some way, but this way can work too. Take a look at _lex_type_lookup_func and how it's used by the lexer for something similar.