compiler-inservice-s22 / Discussion

MIT License
0 stars 0 forks source link

How to use container types defined in STL as the type of semantic values? #19

Open PlusoneWang opened 2 years ago

PlusoneWang commented 2 years ago

Hi TA,

I am new to c/c++. I've tried the following ways to use the container type as the type for the semantic value, but none of them worked.

  1. Declare the type in %union:

    // in parser.y
    #include <vector>
    
    %union {
       std::vector<int> *myVectorType;
    }

    Result of the make command: image

    For the above try, the error occurs whether myVectorType is used in %type or not.

  2. Use vector in %type or %nterm directly. I found a similar issue that asked by the past student and followed the official documentation to do this.

    // in parser.y
    #include <vector>
    %type <std::vector<int>> TerminalList; // or use %nterm
    
    TerminalList:
       Epsilon {
           // just empty
           // or $$ = { 1, 2, 3 };
       }
       |
       TerminalList Terminal {
           $$ = $1
           $$.push_back(1);
           // or $$.push_back($2);
           // or $$->push_back(1);
           // or $$->push_back($2);
       }
    ;

    Result of the make command: image

    For the above try, although the official documentation shows that it's necessary to add the %language="c++" to enable C++ in bison, but when I tried to add %language="c++" to my parser, I got lots of errors about the yy founctions and no way to debug by my self or do more things.

It would be great that if you could give me some hints. Thank you in advance!


Additional information:
To make sure the c++ STL works correctly in the general code block, I add the following code to the int main(int argc, const char *argv[]) in parser.y and confirmed it worked:

std::vector<int> intList;
intList = { 1, 2, 3 };
std::cout << "Size of intList: " << ints.size() << std::endl; // output: Size of intList: 3
std::cout << "CPP works!" << std::endl; // output: CPP works!
LittleLaGi commented 2 years ago

同學你好:

include 要放在 %code requires { } 裡面,如果要用 std namespace 的話也是放這裡, 其他的就跟標準的 C++ 一樣,我們作業在使用的標準是 C++17。


若以上回答有回答到同學的問題,請對助教的回覆加上 emoji 👍,助教會幫此 issue 加上「已解決」的標籤,感謝同學的配合。

PlusoneWang commented 2 years ago

It works! Thank you.