Checking the types of infix operators in the compiler

I am writing a compiler (in Haskell), and in the grammar of the language there are rules for adding infix operators (adding is used as an example):

EAdd . Expr ::= Expr "+" Expr

which means EAddan expression, it consists of an expression, a string, "+"and another expression.

Parser returns an abstract syntax tree (AST):

data Expr = ... | EAdd Expr Expr

I want to make typechecker if it checks that function calls are given with arguments of the correct types.

Note that โ€œ+โ€ is a function that takes two integers and returns an integer. Other operators are similar.

At the moment, I have come up with three approaches to typecheck EAdd, all of which include adding a "+" as a function to the initial character table:

  • Declare that infix plus is syntactic sugar for calling the + function with two arguments. Place a "desugarizer" that converts the AST from the parser to another data type (without EAdd) between the parser and typechecker.

  • (similar to the first) Declare that infix plus is syntactic sugar, but desugarizer uses the same AST data type. Typechecker returns an error if one is specified EAdd.

  • Inline "desugarizer" in typechecker. Similar to this:

    ...
    typecheck (EAdd a b) = typecheck (ECall infixPlus [a, b])
    ...
    

Note that all binary infix operators obey this (other arithmetic, Boolean operations, comparison operators).

, . , , , ECalls , ( - llvm) ( ). , codegen , , .

?

UPD

Haskell ( https://ghc.haskell.org/trac/ghc/wiki/Commentary/Compiler/Renamer):

... renamer :

  • . infix -, . , "a + b * c" "(a + b) * c". Renamer , , .
+4
1

LLVM ,

define void @f() alwaysinline { ... }

, + LLVM .

+1

Source: https://habr.com/ru/post/1584551/


All Articles