コンパイラ作成(97) return文での型変換

今回の目標

int型→double型の型変換。

// int型→double型
double func(void)
{
    return 5;
}

int main()
{
    double x;
    x = func();
    printf("x = %f\n", x);
}

最近、return文のとこばかりだな。

statement

return文の処理を修正。

    if kind == TK::RESERVE && str == "return" then
      # return文の処理
      f = @functions[@funcname]
      kind, str = @lex.gettoken
      if kind != TK::SYMBOL && str != ";" then
        kind, str, type = expr kind, str
        if f[0] == "double" && type == "int" then
          codegen "  cvtsi2sd xmm0, eax"
          type = f[0]
        elsif f[0] == "double" then
          codegen "  movsd  xmm0, xmm8"
        end
        if f[0] != type then
          if f[0] == "void" then
            perror "return a value at void function"
          else
            perror "return with incompatible result type"
          end
        end
      else
        if f[0] != "void" then
          perror "return no value at non-void function"
        end
      end
      codegen "  jmp  .RET_" + @funcname
      if kind != TK::SYMBOL || str != ";" then
        perror "expected ';' after return statement"
      end

int型以外からの変換も入れちゃおうかと思ったけど、中途半端になるかなと思ってやめちゃった。

動作テスト
~/myc$ myc p28.myc
~/myc$ ./p28
x = 5.000000
~/myc$

ちゃんと変換されてる。これでint型→double型の変換は終わったよな。さて次回は何やろうかな。char型からの変換とかもやんなきゃいけないんだけど、ちょっと飽きてきたんで違うことやろうかな。