GPP for Visual Studio Code
Editor support for GPP, an independent superset of Go that compiles to ordinary Go. GPP keeps Go's familiar syntax and ecosystem while adding features such as classes, anonymous structs, enums, annotations, string interpolation, extension methods, safe access, and exception handling.
This extension adds language-aware editing for .gpp and .gpp.tpl files. Syntax highlighting and snippets work on their own; install the GPP CLI to enable the language server, formatting, and project commands.
GPP website · Getting started · Documentation · Examples · Compiler repository
Language overview
GPP source looks familiar to Go developers, with additional syntax for higher-level language features. A standalone program can omit its package declaration; without one, GPP treats the file as part of main:
func main() {
println("Hello, GPP!")
}
The compiler translates GPP into Go, so Go packages and tools remain part of the workflow. Explore the language guides and working examples for more syntax and complete programs.
Whirlwind tour
GPP starts with familiar Go code, then adds richer ways to model data and behavior. The tour follows the feature sequence in the language guides.
Packages
Package names may include dots, and source files do not need to live in matching nested directories. These two files can sit side by side even though one declares demo.people:
// people.gpp
package demo.people
func Greet(name string) string {
return "Hello, " + name
}
// main.gpp
import demo.people
func main() {
println(people.Greet("Ada"))
}
The imported function starts with an uppercase letter so it can be used from another package. See the package guide and multi-file package example.
Classes and structs
Classes bring fields and methods together. Existing Go structs remain supported, and GPP adds class features on top:
class Person {
Name string
func Greeting() string {
return "Hello, " + this.Name
}
}
func main() {
person := Person(Name: "Ada")
println(person.Greeting())
}
The init() hook runs after construction, so a class can validate or normalize its fields:
class Person {
Name string
func init() {
this.Name = this.Name.TrimSpace()
}
}
person := Person(Name: " Ada ")
println(person.Name)
Static methods are called on the class itself. A factory can provide a named way to construct a common instance:
class User {
Name string
Active bool
static func Guest() *User {
return User(Name: "Guest", Active: true)
}
}
guest := User.Guest()
println(guest.Name, guest.Active)
Classes can inherit fields and methods from a parent. Uppercase method names are public, so a child can inherit and override them; calls through a base-typed value still use the child's implementation:
class Animal {
func Sound() string {
return "animal"
}
}
class Dog : Animal {
func Sound() string {
return "woof"
}
}
func describe(animal Animal) string {
return animal.Sound()
}
func main() {
dog := Dog()
println(describe(dog))
}
GPP supports named struct types with named-field construction, as well as anonymous structs made with struct(...):
struct Point {
X int
Y int
}
func main() {
point := Point(X: 3, Y: 4)
anonymous := struct(X: point.X, Y: point.Y)
println(anonymous.X, anonymous.Y)
}
Ordinary Go struct declarations and literals also remain supported.
See the structs guide and struct examples for more patterns.
Classes also support static methods and factories, polymorphism, and multiple inheritance.
Functions and arguments
Function overloading lets the same name handle different parameter types:
func formatValue(value int) string {
return "int"
}
func formatValue(value string) string {
return "string"
}
formatValue(42) // selects the int overload
formatValue("hello") // selects the string overload
Default values and named calls let you omit optional arguments or make a call explicit:
func greet(name string, punctuation string = "!") string {
return name + punctuation
}
greet(name: "Ada")
greet(name: "Ada", punctuation: "?")
See the full overloading example for methods, typed overloads, named calls, and defaults.
Slices
Write the element type before a bracketed list to create a slice. Empty slices use Type[]; nested slices and fixed-size arrays are supported too:
numbers := int[3, 1, 2]
empty := int[]
matrix := []int[[1, 2], [3, 4]]
fixed := [3]int[10, 20, 30]
Slices support Go indexing and slice expressions. The prelude adds methods such as Append, Find, DeleteBy, Sort, and Take:
moreNumbers := numbers.Append(4, 5)
window := moreNumbers[1:4]
withoutTwo := numbers.DeleteBy(value => value == 2)
found, ok := numbers.Find(value => value == 2)
numbers.Sort()
firstThree := numbers.Take(3)
Go brace literals remain available for keyed or indexed elements. See the slice example, slice and array guide, and prelude guide for more details.
Class slices use the same compact literal form. Each parenthesized group constructs one object, using either named or positional constructor arguments:
class Message {
Text string
func init(text string) {
this.Text = text
}
}
messages := Message[(text: "hello"), ("welcome")]
Operators
GPP supports Go's arithmetic, comparison, logical, bitwise, and shift operators, plus compound assignments. Increment and decrement are standalone statements:
count := 1
count += 2
count++
count--
enabled := count > 0 && count != 2
label := enabled ? "on" : "off"
Compound assignments include +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=, and &^=. GPP also adds safe access ?. and lazy fallback ??, shown in the expression examples and error fallback example. See assignments.gpp for more compound assignment examples.
Enums
Enums define a closed set of named values. Members are namespaced under the enum, so different enum types remain distinct even when they use the same backing type:
enum Status string {
Draft
Published
}
status := Status.Published
Use Status.From(value) to validate an external string or integer before converting it to an enum. See the enum guide and enum example.
Generics
Type parameters let a class or function work with different types while keeping field, parameter, and return types checked by the compiler. Declare parameters in square brackets, then supply concrete types when creating a generic class value:
class Box[T] {
Value T
func get() T {
return this.Value
}
}
numberBox := Box[int](https://github.com/telgatech/gpp-vscode/blob/HEAD/Value: 42)
wordBox := Box[string](https://github.com/telgatech/gpp-vscode/blob/HEAD/Value: "GPP")
println(numberBox.get(), wordBox.get())
Methods can declare their own type parameters even when their class is not generic. GPP can infer the method type from the argument, or you can provide it explicitly:
class Client {
func echo[T any](https://github.com/telgatech/gpp-vscode/blob/HEAD/value T) T {
return value
}
}
client := Client()
word := client.echo("GPP")
number := client.echo[int](https://github.com/telgatech/gpp-vscode/blob/HEAD/42)
println(word, number)
Constraints narrow which types can be used for a parameter. For example, a type used as a Go map key must be comparable:
class Index[K comparable, V] {
Entries map[K]V
}
ages := Index[string, int](https://github.com/telgatech/gpp-vscode/blob/HEAD/Entries: map[string]int{})
Generic free functions and methods are supported too. See the generics example for stacks, constrained maps, pairs, and generic functions.
Lambdas
Pass a lambda to .Each to run an action for every value in a slice.
names := []string{"Ada", "Lin"}
names.Each(name => println(name))
See the lambda examples and prelude examples.
Extension methods
Extension methods add method-style operations to existing Go or GPP types without changing those types or wrapping them. The compiler resolves each call and emits ordinary Go code. A single extend block can target multiple types when the same operation applies to each:
extend string, []byte, []rune {
func size() int {
return len(this)
}
}
text := "GPP"
bytes := []byte("GPP")
runes := []rune("GPP")
println(text.size(), bytes.size(), runes.size())
See the extension methods example and multi-type extension example.
Prelude helpers
The prelude is available without an import and adds useful operations directly to ordinary Go slices, maps, and strings. Chain helpers to filter and transform values without writing the same loops and temporary slices by hand:
names := []string{" Ada ", "Lin", " "}
cleanNames := names.Filter(name => !name.IsBlank()).Map(name => name.TrimSpace())
cleanNames.Each(name => println(name))
Map helpers provide lookup with an optional fallback:
config := map(port: "8080")
port := config.Get("port", "3000")
See the prelude guide and prelude example for more collection, map, and string helpers.
Strings and expressions
Only double-quoted strings interpolate. Backtick strings stay literal. In double-quoted strings, escape an opener with a backslash or double the braces to keep them as text:
message := "Hello, {{name}}!"
literalTemplate := `<h1>{{.Name}}</h1>`
escaped := "Write \{{name}} to show the braces literally"
escapedBraces := "Use {{{{name}}}} literally"
Conditional expressions use condition ? whenTrue : whenFalse; only the selected branch is evaluated:
label := enabled ? "on" : "off"
Safe access with ?. avoids repeating nil checks on nullable class values, and lazy fallback with ?? evaluates a default only when the value on the left is absent or erroneous. See the interpolation, conditional expression, safe access, and error fallback examples.
Regular expressions
regexp(pattern) returns Go's native regular-expression value. Use it directly for matching or as a pattern in a tagged string switch; string.CompileRegex() is the error-returning alternative:
re := regexp(`^[a-z]+$`)
valid := re.MatchString(username)
switch path {
case "/", regexp(`^/users/[0-9]+$`):
println("home or user route")
case regexp(`^/health$`):
println("health route")
}
See the regex example for direct compilation, matching, switch cases, and the CompileRegex() extension.
Errors and Exception Handling
GPP keeps Go's error values and adds try/catch for structured recovery. If a call's trailing error result is left uncaptured, a non-nil error is automatically raised and propagates through callers until the nearest matching catch; a nil error lets execution continue. Assign the error explicitly (value, err := call()) when you want to handle it as an ordinary value.
func readConfig(path string) []byte {
return os.ReadFile(path) // trailing error propagates automatically
}
func main() {
try {
data := readConfig("config.json")
println(len(data))
} catch os.PathError pathErr {
println("could not read config:", pathErr)
} catch ValidationError, PermissionError err {
println("config was rejected:", err)
} catch err {
println("unexpected error:", err)
} finally {
println("config load finished")
}
}
Catch clauses are checked in order. A clause can match one type, several types, or any error; finally runs whether the protected work succeeds or unwinds through an error. See the exception handling example for more cases.
Annotations and introspection
Declare typed metadata, restrict where it can be used, and attach it to a declaration:
annotation Label(value string) on class
@{Label("example")}
class User {
Name string
}
Annotations can be validated against their targets and inspected at runtime. See the annotations example for field, method, and class metadata.
Applications
The standard packages build on these features with serialization, HTTP routing, OpenAPI and Swagger, ORM and SQL, typed templates, cron scheduling, and suite-based tests.
Override Handle(ctx) for procedural request handling, then start the app with Listen:
package main
import http "gpp/http"
class App : http.Server {
func Handle(ctx *http.Context) error {
if ctx.Request.URL.Path == "/healthz" {
return ctx.Text("ok")
}
return nil
}
}
func main() {
App().Listen(8080)
}
See the HTTP server example.
Typed SQL queries return the result shape you request:
func loadPeople(db *sql.DB) {
person := db.Get[Person](https://github.com/telgatech/gpp-vscode/blob/HEAD/"SELECT id, name FROM people WHERE id = $1", int64(1))
people := db.Select[Person](https://github.com/telgatech/gpp-vscode/blob/HEAD/"SELECT id, name FROM people")
println(person.Name, len(people))
}
See the typed SQL example.
ORM models provide persistence methods from their declaration:
class Employee : orm.Model {
Id int64
Name string
}
func saveEmployee(db *sql.DB) {
employee := Employee(Id: 1, Name: "Ada")
employee.Insert(db)
}
See the ORM example.
Annotate a function to schedule it as a cron job:
func refreshCache(ctx context.Context) error @{cron.Every(time.Minute)} {
return nil
}
func main() {
cron.Start()
}
See the cron example.
Typed templates render HTML with Go's template actions:
template welcome(data any) {
<h1>Welcome</h1>
}
See the template example for rendering details.
Use ordinary Go imports, compile Go and GPP together, and emit ordinary Go. The CLI provides project creation, building, running, testing, formatting, source documentation, and a language server.
import "fmt"
func main() {
fmt.Println("Using a Go package from GPP")
}
See mixed-language examples for Go and GPP in the same build.
The examples directory has complete programs for these features, including enums, error fallback, and mixed Go/GPP projects.
Extension features
- Syntax highlighting for Go syntax and GPP additions, including classes, enums, anonymous structs, annotations, lambdas, safe access, error fallback, string interpolation, and Go template actions
- Language configuration for brackets, auto-closing pairs, indentation, and folding
- Snippets for declarations, control flow, annotations, structs, templates, expressions, and imports
- Optional GPP language-server support for diagnostics, completion, hover, navigation, references, rename, symbols, inlay hints, code actions, and more
- Formatting through
gpp fmt --stdout, including unsaved editor contents
- Commands to run, build, and test a GPP project
- Workspace watching so edits to GPP and Go files can refresh language-server diagnostics and indexes
Setup
Open any .gpp or .gpp.tpl file to use syntax highlighting. No compiler installation is required for syntax-only support.
To enable language-server features, formatting, and project commands, install the GPP CLI using the instructions in the Getting Started guide. The extension starts gpp lsp when a GPP file is opened and, by default, looks for the executable at ~/go/bin/gpp.
If gpp is installed elsewhere, set its path in VS Code settings:
{
"gpp.lsp.command": "/path/to/gpp",
"gpp.lsp.enabled": true
}
Set gpp.lsp.enabled to false to use syntax highlighting without starting the language server. Language-server startup errors and capability messages appear in View → Output → GPP.
Commands
Open the Command Palette and search for GPP to run these commands:
- GPP: Format Document
- GPP: Run Project
- GPP: Build Project
- GPP: Test Project
- GPP: Show Output
- GPP: Organize Imports
- GPP: Refresh Diagnostics
Formatting uses the compiler's gpp fmt --stdout command. Run, build, and test use the corresponding GPP CLI commands in the current workspace.
Links
Development
To run this extension from the source repository:
- Open the repository folder in VS Code.
- Open Run and Debug, choose Run GPP Extension, or press
F5.
- In the Extension Development Host window, open a
.gpp or .gpp.tpl file.
The repository includes a launch configuration for the Extension Development Host. The grammar, language configuration, snippets, and language-server bridge are plain source files.