Improved Go Syntax (transpiler)

Overview

Improved Go (igo) GoDoc

Everyone knows that Go is a very verbose language. It takes numerous lines of code to do what a few lines of code can do in other languages. This is a deliberate design decision by the Go Authors.

The igo project provides various syntactical sugar to make your code simpler and easier to read. It works by allowing you to program in *.igo files with the fancy new syntax. You then run igo build to transpile your igo files to standard go files which you can then build as per normal.

  1. Address Operator (&)
    • Constants and Functions
  2. Defers for for-loops
    • fordefer guarantees to run prior to the loop's current iteration exiting.
  3. Defer go
    • Run defer statements in a goroutine
  4. must function
    • Converts a multi-return value function into a single-return function.
    • See #32219
  5. Negative slice indices

NOTE: igo is pronounced ee-gohr

the project to show your appreciation.

What is included

  • igofmt (auto format code)
  • igo transpiler (generate standard go code)

Installation

Transpiler

go get -u github.com/rocketlaunchr/igo

Use go install to install the executable.

Formatter

go get -u github.com/rocketlaunchr/igo/igofmt

Inspiration

Most professional front-end developers are fed up with standard JavaScript. They program using Typescript and then transpile the code to standard ES5 JavaScript. igo adds the same step to the build process.

Examples

Address Operator

The Address Operator allows you to use more visually pleasing syntax. There is no need for a temporary variable. It can be used with string, bool, int, float64 and function calls where the function returns 1 return value.

func main() {

	message := &"igo is so convenient"
	display(message)

	display(&`inline string`)

	display(&defaultMessage())

}

func display(m *string) {
	if m == nil {
		fmt.Print("no message")
	} else {
		fmt.Print(*m)
	}

}

func defaultMessage() string {
	return "default message"
}

Fordefer

See Blog post on why this is an improvement. It can be especially helpful in unit tests.

for {
	row, err := db.Query("SELECT ...")
	if err != nil {
		panic(err)
	}

	fordefer row.Close()
}

Defer go

This feature makes Go's language syntax more internally consistent. There is no reason why defer and go should not work together.

mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
	start := time.Now()
	// Transmit how long the request took to serve without delaying response to client.
	defer go transmitRequestStats(start)

	fmt.Fprintf(w, "Welcome to the home page!")
})

Must builtin function

must is a "builtin" function that converts a multi-return value function ("fn") into a single-return value function. fn's final return value is expected to be of type error. must will panic upon fn returning an error.

It is useful in scenarios where you know that no error will actually be returned by fn and you just want to use the function inline. Alternatively, you may want to catch the error during local development because no error should be produced in production.

must also accepts an optional second argument of type func(error) error.

See #32219

import "database/sql"

db := must(sql.Open("mysql", "host"))

LIMITATIONS

  • Currently, it only works when fn returns two return values.
  • It doesn't work when used outside of functions (i.e. initializing package variables).
  • It works perfectly in simple cases. For more complex cases, peruse the generated code.
  • A PR would be appreciated by an expert in the go/types package. It is possible to create a truly generics-compatible must that resolves the limitations above.
  • Unlike real "builtin" functions, must is a reserved keyword.

Negative slice indices

You can use negative indices to refer to items in a slice starting from the back. It only works with constants and not variables.

x := []int{0, 1, 2, 3, 4}

x[-3] // x[len(x)-3]

x[-3:-1] // x[len(x)-3:len(x)-1]

How to use

Transpile

igo can accept numerous directories or igo files. The generated go files are saved alongside the igo files.

igo build [igo files...]

Format Code

igofmt will format your code to the standard form. It understands igo syntax.

igofmt [-s] [igo files...]

Configure your IDE to run igofmt upon saving a *.igo file. -s will attempt to simplify the code by running gofmt -s.

Design Decisions and Limitations

Pull-Requests are requested for the below deficiencies.

  • For fordefer: goto statements inside a for-loop that jump outside the for-loop is not implemented. Use github.com/rocketlaunchr/igo/stack package manually in such cases.
  • goimports equivalent has not been made.
  • Address Operator for constants currently only supports string, bool, float64 and int. The other int types are not supported. This can be fixed by using go/types package.
  • Address Operator feature assumes you have not attempted to redefine true and false to something/anything else.

Tips & Advice

  • Store the igo and generated go files in your git repository.
  • Configure your IDE to run igofmt upon saving a *.igo file.

Legal Information

The license is a modified MIT license. Refer to the LICENSE file for more details.

© 2018-20 PJ Engineering and Business Solutions Pty. Ltd.

Final Notes

Feel free to enhance features by issuing pull-requests.

You might also like...
Go Cheat Sheet - An overview of Go syntax and features.

Go Cheat Sheet - An overview of Go syntax and features.

Tool that can parse Go files into an abstract syntax tree and translate it to several programming languages.
Tool that can parse Go files into an abstract syntax tree and translate it to several programming languages.

GoDMT GoDMT, the one and only Go Data Model Translator. The goal of this project is to provide a tool that can parse Go files that include var, const,

The Slick programming language is an s-expression surface syntax for Go.

The Slick programming language The Slick programming language is a Lisp/Scheme-style s-expression surface syntax for the Go programming language, with

An online book focusing on Go syntax/semantics and runtime related things

Go 101 is a book focusing on Go syntax/semantics and all kinds of runtime related things. It tries to help gophers gain a deep and thorough understanding of Go. This book also collects many details of Go and in Go programming. The book is expected to be helpful for both beginner and experienced Go programmers.

An interesting go struct tag expression syntax for field validation, etc.

go-tagexpr An interesting go struct tag expression syntax for field validation, etc. Usage Validator: A powerful validator that supports struct tag ex

Easy JSON Query Processor with a Lispy syntax in Go

jql Hey there! You're probably here cause you're fed up with other json query processors being too complicated to use for anything surpassing simple s

A general purpose syntax highlighter in pure Go

Chroma — A general purpose syntax highlighter in pure Go NOTE: As Chroma has just been released, its API is still in flux. That said, the high-level i

Go package for syntax highlighting of code

syntaxhighlight Package syntaxhighlight provides syntax highlighting for code. It currently uses a language-independent lexer and performs decently on

Search for Go code using syntax trees

gogrep GO111MODULE=on go get mvdan.cc/gogrep Search for Go code using syntax trees. Work in progress. gogrep -x 'if $x != nil { return $x, $*_ }' In

Decorated Syntax Tree - manipulate Go source with perfect fidelity.

Decorated Syntax Tree The dst package enables manipulation of a Go syntax tree with high fidelity. Decorations (e.g. comments and line spacing) remain

Assembly syntax that makes you feel like you're writing code in a high-level language.

shasm Assembly syntax that makes you feel like you're writing code in a high-level language. Shasm is not an Assembler. Shasm simply compiles Shasm sy

A convenient syntax to generate JSON (or YAML) for commandline

clon A convenient syntax to generate JSON (or YAML) for commandline "mumbo-jumbo". Syntax Overview Syntax resembles that of JSON with a few caveats: a

An alternative syntax to generate YAML (or JSON) from commandline

yo An alternative syntax to generate YAML (or JSON) from commandline. The ultimate commanline YAML (or JSON) generator! ... I'm kidding of course! but

Syntax-aware grep for PHP code.

phpgrep Syntax-aware grep for PHP code. This repository is used for the library and command-line tool development. A good source for additional utilit

An interesting go struct tag expression syntax for field validation, etc.

An interesting go struct tag expression syntax for field validation, etc.

CLI shorthand syntax for Go

CLI Shorthand Syntax CLI shorthand syntax is a contextual shorthand syntax for passing structured data into commands that require e.g. JSON/YAML. Whil

A languge based on LISP syntax, NOT strictly lisp

Lisp-Interpreter A languge based on LISP syntax, NOT strictly lisp, I changed some things that in my opinion make the language more useable, this was

Go-based search engine URL collector , support Google, Bing, can be based on Google syntax batch collection URL
Go-based search engine URL collector , support Google, Bing, can be based on Google syntax batch collection URL

Go-based search engine URL collector , support Google, Bing, can be based on Google syntax batch collection URL

To run a .go file use below syntax

To run a .go file use below syntax

Comments
  • Weird

    Weird

    Having this in an igo file:

    func (db *DB) BeginTx(ctx context.Context, opts *stdSql.TxOptions) (*stdSql.Tx, error)
    func (c *Conn) BeginTx(ctx context.Context, opts *stdSql.TxOptions) (*Tx, error)
    

    generates this error during build state:

    panic: runtime error: invalid memory address or nil pointer dereference
    [signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x119f041]
    
    goroutine 1 [running]:
    github.com/rocketlaunchr/igo/common.RemoveComments.func1(0x12604e0, 0xc0003d2d20, 0x1260b01)
    	/Users/pj/GOPATH/src/github.com/rocketlaunchr/igo/common/comments.go:36 +0x71
    go/ast.inspector.Visit(0xc0002ded50, 0x12604e0, 0xc0003d2d20, 0x125f220, 0xc0002ded50)
    	/usr/local/Cellar/go/1.12.6/libexec/src/go/ast/walk.go:373 +0x3a
    go/ast.Walk(0x125f220, 0xc0002ded50, 0x12604e0, 0xc0003d2d20)
    	/usr/local/Cellar/go/1.12.6/libexec/src/go/ast/walk.go:52 +0x66
    go/ast.walkDeclList(0x125f220, 0xc0002ded50, 0xc000179e00, 0xb, 0x10)
    	/usr/local/Cellar/go/1.12.6/libexec/src/go/ast/walk.go:38 +0x9e
    go/ast.Walk(0x125f220, 0xc0002ded50, 0x1260460, 0xc0003caa80)
    	/usr/local/Cellar/go/1.12.6/libexec/src/go/ast/walk.go:353 +0x2659
    go/ast.Inspect(...)
    	/usr/local/Cellar/go/1.12.6/libexec/src/go/ast/walk.go:385
    github.com/rocketlaunchr/igo/common.RemoveComments(0xc000291770, 0x27, 0x13e8ea8, 0x0)
    	/Users/pj/GOPATH/src/github.com/rocketlaunchr/igo/common/comments.go:33 +0x15e
    github.com/rocketlaunchr/igo/cmds.processFile(0xc0003c8080, 0x9, 0x0, 0x0)
    	/Users/pj/GOPATH/src/github.com/rocketlaunchr/igo/cmds/build.go:102 +0x22f
    github.com/rocketlaunchr/igo/cmds.BuildCmd(0xc0000dc500, 0xc000094720, 0x1, 0x1)
    	/Users/pj/GOPATH/src/github.com/rocketlaunchr/igo/cmds/build.go:40 +0x472
    github.com/spf13/cobra.(*Command).execute(0xc0000dc500, 0xc0000946f0, 0x1, 0x1, 0xc0000dc500, 0xc0000946f0)
    	/Users/pj/GOPATH/src/github.com/spf13/cobra/command.go:830 +0x2ae
    github.com/spf13/cobra.(*Command).ExecuteC(0xc0000dc000, 0xc000040f78, 0x2, 0x2)
    	/Users/pj/GOPATH/src/github.com/spf13/cobra/command.go:914 +0x2fc
    github.com/spf13/cobra.(*Command).Execute(...)
    	/Users/pj/GOPATH/src/github.com/spf13/cobra/command.go:864
    main.main()
    	/Users/pj/GOPATH/src/github.com/rocketlaunchr/igo/main.go:43 +0x173
    
    
    opened by pjebs 1
  • TODO:

    TODO:

    1. ~~Update copyright~~
    2. ~~Implement negative indexing~~
    3. ~~Implement fordefer go~~
    4. ~~Fix: must will panic upon encountering an error. to fn returning an error~~
    5. ~~igofmt -s=> Run gofmt -s after transpiling~~
    6. fancy range functionality
    7. -f flash to go build to auto format
    opened by pjebs 0
Releases(v1.0.3)
Owner
null
A languge based on LISP syntax, NOT strictly lisp

Lisp-Interpreter A languge based on LISP syntax, NOT strictly lisp, I changed some things that in my opinion make the language more useable, this was

Leo De Silva 1 Jan 2, 2023
Improved go doc with terminal syntax highlighting

GopherDoc Improved go doc with terminal syntax highlighting. This is a modification of the original go doc command that adds terminal syntax highlight

Raven Ravener 16 Nov 22, 2022
Golang->Haxe->CPP/CSharp/Java/JavaScript transpiler

TARDIS Go -> Haxe transpiler Haxe -> C++ / C# / Java / JavaScript Project status: a non-working curiosity, development currently on-ice The advent of

TARDIS Go 423 Dec 30, 2022
NoiseGo - Implementation of Improved Perlin Noise in Golang

NoiseGo Implementation of Improved Perlin Noise in Golang. NoiseGo is written on

Tada Teruki (多田 瑛貴) 1 Jan 24, 2022
argv - Go library to split command line string as arguments array using the bash syntax.

Argv Argv is a library for Go to split command line string into arguments array. Documentation Documentation can be found at Godoc Example func TestAr

null 37 Nov 19, 2022
pongo2 is a Django-syntax like templating-language

Django-syntax like template-engine for Go

Florian Schlachter 2.4k Dec 27, 2022
igor is an abstraction layer for PostgreSQL with a gorm like syntax.

igor igor is an abstraction layer for PostgreSQL, written in Go. Igor syntax is (almost) compatible with GORM. When to use igor You should use igor wh

Paolo Galeone 90 Jan 1, 2023
Go package for syntax highlighting of code

syntaxhighlight Package syntaxhighlight provides syntax highlighting for code. It currently uses a language-independent lexer and performs decently on

Sourcegraph 253 Nov 18, 2022
Generate High Level Cloud Architecture diagrams using YAML syntax.

A commandline tool that generate High Level microservice & serverless Architecture diagrams using a declarative syntax defined in a YAML file.

Luca Sepe 557 Dec 24, 2022
Article spinning and spintax/spinning syntax engine written in Go, useful for A/B, testing pieces of text/articles and creating more natural conversations

GoSpin Article spinning and spintax/spinning syntax engine written in Go, useful for A/B, testing pieces of text/articles and creating more natural co

Miles Croxford 44 Dec 22, 2022