babygo

command module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 24, 2023 License: MIT Imports: 5 Imported by: 0

README

Babygo, a go compiler made from scratch

Test

Babygo is a small and simple go compiler. (Smallest and simplest in the world, I believe.) It is made from scratch and can compile itself.

  • No dependency to any libraries. Standard libraries and calling of system calls are home made.
  • Lexer, parser and code generator are handwritten.
  • Emit assemble code which results in a single static binary.

It depends only on as as an assembler and ld as a linker.

It is composed of only a few files.

  • main.go - the main compiler
  • parser.go - parser
  • scanner.go - scanner(or lexer)
  • src/ - standard packages
  • lib/ - libraries

Design

Lexer, Parser and AST

The design and logic of ast, lexer and parser are borrowed (or should I say "stolen") from go/ast, go/scanner and go/parser.

Code generator

The design of code generator is borrowed from chibicc , a C compiler.

Remaining parts (Semantic analysis, Type management etc.)

This is purely my design :)

Environment

It supports x86-64 Linux only.

If you are not using Linux, you can use a dedicated docker image for this project.

$ docker pull dqneo/ubuntu-compiler-go
$ ./docker-run

Usage

Hello world

# Build babygo
$ go build -o babygo

# Compile the hello world program by babygo
$ ./babygo example/hello.go

# Assemble and link
$ as -o hello.o /tmp/*.s
$ ld -o hello hello.o

# Run hello world
$ ./hello
hello world!

How to do self hosting

# Build babygo (1st generation)
$ go build -o babygo

# Build babygo by babygo (2nd generation)
$ rm /tmp/*.s
$ ./babygo *.go
$ as -o babygo2.o /tmp/*.s
$ ld -o babygo2 babygo2.o # 2nd generation compiler

# You can generate babygo3 (3rd generation), babygo4, and so on...
$ rm /tmp/*.s
$ ./babygo2 *.go
$ as -o babygo3.o /tmp/*.s
$ ld -o babygo3 babygo3.o # 3rd generation compiler

Test

$ make test

Reference

License

MIT

Author

@DQNEO

Documentation

The Go Gopher

There is no documentation for this package.

Directories

Path Synopsis
How to compile: go tool compile -N -S -l sample.go > sample.s
How to compile: go tool compile -N -S -l sample.go > sample.s
internal
ir
lib
ast
fmt
src
os
runtime
runtime for 2nd generation compiler
runtime for 2nd generation compiler
t

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL