IUCompilerCourse / Essentials-of-Compilation

A book about compiling Racket and Python to x86-64 assembly
1.27k stars 137 forks source link

Print for non-integer args (Python Version) #159

Closed waynee95 closed 1 year ago

waynee95 commented 1 year ago

The book doesn't talk about how to compile print for non-integer arguments. Nor does it say, that print is restricted to only integer arguments.

The language grammar would allow to print non-integers and the TypeChecker in Fig. 2.3 doesn't rule out non-integers args.

However, the type checker in type_check_Lvar.py from the python-support-code doesn't allow print to be invoked for non-integer arguments, although the runtime.c kinda has specialized print functions for non-integers.

jsiek commented 1 year ago

In the Lvar language (Chapter 2), there are only integers, so there is nothing else to rule out regarding print.

In the Lif language (Chapter 5), there are integers and booleans, so the type checker for Lif needs to rule out non-integers for print, and indeed it does in Figure 5.5:

      case Expr(Call(Name('print'), [arg])):
        t = self.type_check_exp(arg, env)
        check_type_equal(t, int, arg)
        return self.type_check_stmts(ss[1:], env)

I hope that clarifies the issue for you!

waynee95 commented 1 year ago

@jsiek So printing anything else other than integers is not in the scope of the book, right?

EDIT: At least up to chapter 7.

jsiek commented 1 year ago

That is correct.

Yes, when the book gets to dynamic typing, then the type checker can't rule out non-integers, and it felt weird to me to rule them out at runtime. However, now that I think more about it, ruling them out at runtime would be a reasonable shortcut, as learning about printing is a non-goal for the book.

waynee95 commented 1 year ago

Thanks!