DEV Community

Cover image for Creating a Target (Pogo Pt: 2)
Chig Beef
Chig Beef

Posted on

Creating a Target (Pogo Pt: 2)

Intro

If you didn't read part one I am creating a Python to Golang transpiler called Pogo. From part one we used type annotations to construct the basis of the Go type system within Python.

Current Work

Now that we have our source better described, we can now move on to our target. We will be doing this by creating some Python code, and creating the result we would like.

To do this we will have to create our input to compile. A great test I like to use for compilers is searching for prime numbers, here is the code in Python.

from GoType import *

# Code
for i in range(2, 100):
    prime: bool = True

    for j in range(2, i):
        if i%j == 0:
            prime = False

    if prime:
        print(i)
Enter fullscreen mode Exit fullscreen mode

If you remember from the last post GoType is a Python file that defines each GoType we need, so that they come up for inference. This includes types such as uint8 that aren't in Python.
Next, we have a comment, which is very important because we don't want to get rid of these, we want to keep them for the final output.
For loops in Python and Go look very different, which may make them hard to work with in the long run.
You can see in the creation of prime we are using type annotations, which will be useful for Go to figure out which type prime should be.

Here is the equivalent Go code.

package main

import (
    "fmt"
)

func main() {
    // Code
    for i := 2; i < 100; i++ {
        var prime bool = true

        for j := 2; j < i; j++ {
            if i%j == 0 {
                prime = false
            }
        }

        if prime {
            fmt.Println(i)
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

This is probably the simplest way to find prime numbers, and is no way optimized, but it already shows some interesting things we will have to do in compilation.
Firstly, we can see that whenever we print we will inevitably need to import fmt. Furthermore, everything that was run in a global scope is set into the main function. Something useful, however, is that neither language uses type annotations on variables used in loops, such as i. This could make that compilation easier, or end up making it harder.

Next

In the next job we will start with the compiler, specifically defining what a token is and what can be a token, which will lead to the lexing process.

Top comments (2)

Collapse
 
soulsbane profile image
Paul Crane

Cool project. Keep it up! I know I will enjoy reading it.

Collapse
 
chigbeef_77 profile image
Chig Beef

Thanks, that means a lot! I'll try my best to keep to this project, and do call me out if I start not making sense (':