简体   繁体   中英

Wrap function instructions by some ASM code

I'm making a simple C compiler as an homework. I have the following grammar rule:

function_definition
: type_name declarator compound_statement

My semantic rules should transform it into:

declarator:
  push %ebp
  mov %esp %ebp

  // compound_statement (function instructions)

  pop %ebp
  ret

As the compound_statement rule will be called before function_definition , I can't fprintf() function instructions directly in its semantic rules. However, I can't define any streamstring in Yacc types neither (see: my previous question ).

So how should I do to put function instructions in a string (easily, not using strcat which would be a mess on a memory-allocation side) and then wrap them by the previous ASM instructions ?

You can probably write that rule as:

function_definition:
    type_name declarator
        { fprintf(..function prefix code..); }
    compound_statement
        { fprintf(..function suffix code..); }
;

and continue to have the rules for compound_statement output code directly. The problem is that depending on the rest of your grammar, this might introduce shift/reduce or reduce/reduce conflicts, as the embedded action introduces an extra null reduction (to run the action code) before parsing the compound_statement.

There are two ways:

  • you can either build an object that contains a representation of the function body inside the code for the compound_statement rule, which is then passed as an argument to the function_definition rule's code, or
  • you can use the GNU extension for mid-rule code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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