/gala:gala-lintfrom gala
Lints GALA code for best practices and coding standards. Scans .gala files for violations including bare Go builtins, style issues, and pattern problems.
Ships in gala. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Verify that all GALA code in the codebase follows GALA best practices and coding standards.
Argument: $ARGUMENTS - Optional path to a specific .gala file or directory to lint (default: scan all .gala files in the project)
Search for .gala files in the target path (or entire project), excluding build outputs and generated files.
For each .gala file, check all linting rules below and collect violations. Run the mechanical grep passes given in each rule's Check line (especially rule 7c, which requires every for to be classified) rather than relying on reading alone. Most greps list candidates to read; a Check marked verdict is different — every hit it reports outside a comment or string literal is a finding, never dismissed by judgment.
Present findings in the output format specified at the end.
GALA-E0035)Bare Go builtins are not part of GALA's surface — calling one is a hard
transpile error (GALA-E0035), not merely "prefer GALA". This applies to
append, make, new, cap, copy, delete, close, complex, real,
imag, panic, recover, and len. Code that still calls them will not
compile, so treat any occurrence as a must-fix. The check is resolver-aware: a
user-defined function that happens to share one of these names (e.g. a local
func delete(...)) is fine — only the builtin is forbidden.
| Forbidden builtin | Sanctioned replacement |
|---|---|
len(x) | x.Size() — logical size (characters for strings, element count for slices/maps/collections). x.ByteSize() — a string's raw byte count. |
append(s, v) | go_interop.SliceAppend(s, v) / SliceAppendAll(s, more) at a Go-slice boundary; otherwise Array.Append / List.Prepend |
cap(x) | go_interop.SliceCap(x) |
make([]T, n) | go_interop.SliceWithSize / SliceWithCapacity; MapEmpty for maps; or an empty Array/HashMap |
new(T) | go_interop.New[T]() (pointer), or a zero value / Option[T] |
delete(m, k) | go_interop.MapDelete(m, k), or HashMap.Remove(k) |
copy(dst, src) | go_interop.SliceCopy(...), or copy an Array |
close(ch) | go_interop.CloseChan(ch), or go_interop.CloseSignal(s) for a signal channel |
complex/real/imag | go_interop.Complex / Real / Imag |
panic(v) | go_builtins.Panic(v) — only where a panic is genuinely intended (see rule 11); prefer Option/Try/Either |
recover() | not available — Try captures panics (Try(() => …) / TryApply) |
.Size()also fixes a footgun: Go'slen(string)returns bytes, so non-ASCII text mis-counts..Size()is logical size ("héllo".Size() == 5);.ByteSize()is the raw byte count (== 6).
The rows below (rule 4a Go-slices, rule 11 error handling) reference these
replacements; a bare builtin is always the higher-severity GALA-E0035 finding.
GALA-E0036)The Go statement keywords defer, go, goto, fallthrough, select, and
chan are not part of GALA's grammar. A bare use is a hard transpile error
(GALA-E0036), not merely "prefer GALA". They only ever appeared to work as an
accident of the final gofmt pass (which glued the following statement onto the
keyword), so treat any occurrence as a must-fix. Like rule 0, the check is
resolver-aware — a symbol the program itself declared is left alone.
| Forbidden statement | Sanctioned replacement |
|---|---|
defer x.Close() | a use x = acquire binding (closes at block exit, LIFO), or a resource combinator — Using / Bracket / WithLock from martianoff/gala/resource |
go f() | prefer concurrent.Future (its captures are checked, see GALA-E0037); go_interop.Spawn(() => f()) is the unchecked escape hatch |
goto, fallthrough | structured control flow — pattern matching (match), recursion, or a for loop |
select, chan | the go_interop channel helpers |
use — the RAII scoped-resource idiom (preferred defer replacement)use x = acquire binds x for the rest of the enclosing block and guarantees
x.Close() runs when the function returns, on every path (normal or panic).
Multiple use bindings release LIFO (last acquired closes first). It lowers
to Go x := acquire; defer x.Close() in the generated code — so Go's defer
survives only as this sanctioned internal lowering, never on the GALA surface.
The resource must satisfy Close() error; no import is needed.
| Issue | Pattern to Flag | Recommended Fix |
|---|---|---|
Bare defer for cleanup | defer f.Close() — a hard error (GALA-E0036) | use f = open(path) — closes at block exit |
Nested Using pyramid for sequential resources | Using(a, (x) => Using(b, (y) => …)) | flatten to top-to-bottom use bindings |
| Manual close on every exit path | val f = open(); …; f.Close() (forgettable, skipped on panic) | use f = open() — release is guaranteed |
Bad pattern — Go-style defer:
func readAll(path string) string {
val f = OpenFile(path)
defer f.Close() // GALA-E0036: not a GALA statement
f.ReadString()
}
Good pattern — use binding (or a resource combinator):
// use: closes at block exit, guaranteed on every path
func copyFile(src string, dst string) Try[Int] = Try(() => {
use in = OpenFile(src) // in.Close() runs last
use out = CreateFile(dst) // out.Close() runs first (LIFO)
out.Write(in.ReadString())
})
// resource combinators — for resources without Close() (a mutex, a temp dir),
// or when the close error must be surfaced (Using discards it):
val next = WithLock(mu, () => sharedCounter + 1)
val text = Using(OpenFile(path), (f) => f.ReadString())
For a non-Closeable cleanup (e.g. os.RemoveAll(dir)), use
Bracket(resource, release, body) — it runs release after body on every
exit path.
These Go habits are also rejected by the compiler. Any occurrence is a must-fix;
each code has a page with the full explanation (gala explain GALA-Exxxx).
| Code | Pattern to Flag | Fix |
|---|---|---|
GALA-E0007 | Slice literal []int{1, 2, 3} | ArrayOf(1, 2, 3); go_interop.SliceOf(...) only for a raw Go slice at an interop boundary |
GALA-E0008 | Map literal map[string]int{"a": 1} | HashMapOf(("a", 1)); go_interop.MapPut(go_interop.MapEmpty[K, V](), ...) only at a Go boundary |
GALA-E0013 | Defaulted parameter before a required one | Move defaulted parameters to the end |
GALA-E0034 | Untyped / grouped parameters: func add(a, b int), struct Point(X, Y int) | One type per parameter: func add(a int, b int) |
GALA-E0037 | A Future closure capturing mutable or unshareable state | Snapshot into a val before the boundary; prefer immutable collections |
GALA-E0039 | Bare variant name in a pattern: case Circle => | case Circle(_) => |
GALA-E0040 | Go slice or map type inside an expression: EmptyHashMap[string, []byte]() | Name a GALA type: Array[T] / HashMap[K, V]; text is string, not []byte |
GALA-E0041 | Importing another tree's internal/ package | Use the parent package's public API, or move the importer into the tree |
GALA-E0042 | Unparenthesised lambda parameter: x => x * 2 | (x) => x * 2 |
GALA-E0043 | Type name called as a constructor: Array(1, 2, 3) | ArrayOf(1, 2, 3) |
GALA-E0045 | Struct constructed without a required field | Pass the field, or give it a default in the struct declaration |
GALA-E0047 | if with an initializer: if v, err := f(); err == nil { ... } | Try(f()) match { case Success(v) => ...; case Failure(_) => ... } |
GALA-E0052 | Named func declared inside a function body: func main() { func helper(x int) int = x + 1 } | A lambda bound to a val: val helper = (x int) int => x + 1; generic helpers stay at the top level |
| Issue | Pattern to Flag | Recommended Fix |
|---|---|---|
Unnecessary var | var x = <literal> where x is never reassigned | Use val x = <literal> |
| Mutable loop counter | var i = 0; for { i++ } when FoldLeft works | Use FoldLeft or ForEach |
| Mutation instead of copy | person.age = 31 | Use person.Copy(age = 31) |
| Nil for optional fields | var next *Node = nil (mutable just to allow nil) | Use val next Option[Node] or val next func() Option[Node] |
| Mutable pointer for optional | var data *T assigned once then read | Use val data Option[T] |
Redundant val parameter or receiver (LOW) | func f(val s string), (val x) => …, func (val p Point) M() — parameters, lambda parameters and receivers are immutable by default, so val changes nothing | Drop it: func f(s string) |
Unnecessary var parameter | func f(var n int) or (var n) => … where n is never reassigned | Drop var: func f(n int) |
Check: Search for var declarations and verify each is reassigned later in the same scope.
Acceptable var uses: loop counters, accumulators in Fold-like operations, stream traversal cursors. A counter being acceptable does not make its loop acceptable — every for is still checked against rule 7c.
| Issue | Pattern to Flag | Recommended Fix |
|---|---|---|
| If-else on Option | if opt.IsDefined() { opt.Get() } | opt match { case Some(x) => ... } |
| If-else on Either | if either.IsRight() { either.Right() } | either match { case Right(x) => ... } |
| Type assertion chains | if _, ok := x.(T); ok { } — an if initializer is a hard error (GALA-E0047) | x match { case t: T => ... } |
| Long if-else chains | 3+ else-if branches | Use match expression |
| If-else on isEmpty/NonEmpty | if x.IsEmpty() { ... } else { ... } | Pattern match: case Array(h, tail...) / case _ for an Array; case Cons(h, t) / case Nil() for a List |
| Head/Tail after empty check | if !list.IsEmpty() { list.Head(); list.Tail() } | list match { case Cons(h, t) => ... } |
| Unused extractors | Defining Unapply extractors but using if-else internally | Use your own extractors! |
| Get(0) after length check | if x.Length() > 0 { x.Get(0) } | x.HeadOption() or pattern match |
| Unnecessary default on sealed | case _ => when all sealed variants are covered | Remove case _ =>; exhaustive match is verified by the transpiler |
| IsXxx() chains on sealed type | if s.IsCircle() { ... } else if s.IsRectangle() { ... } | s match { case Circle(r) => ... case Rectangle(w, h) => ... } |
| If-err-nil on Go error return | val x, err = f(); if err == nil { ... } | Wrap with Try(f) (if f takes no args) or Try(f(args)) then use .Map, .GetOrElse, or match |
| Sequential if-err-nil fallback | Multiple val x, err = f(); if err == nil { return x } in sequence | Try(f1).OrElse(Try(f2)) chain (or Try(f1(args)).OrElse(Try(f2(args))) if args needed) |
| Lambda wrapper for zero-arg func | Try(() => f()) where f takes no arguments | Try(f) — pass function reference directly (for any other single-expression body, drop () => instead — see rule 11d) |
| Issue | Pattern to Flag | Recommended Fix |
|---|---|---|
| Manual discriminator | Struct with kind int or _variant uint8 field + iota constants + switch/if-else on kind | Use sealed type declaration |
| Interface for closed variants | Interface with a small, fixed set of implementations that are all in the same package | Use sealed type instead |
| Iota enum without data | const ( Red = iota; Green; Blue ) for a fixed set of values | sealed type Color { case Red() case Green() case Blue() } |
| Iota enum with data | Iota constants + separate struct fields per variant | sealed type with fields on each case |
| Struct union pattern | A struct with fields for multiple variants where only some are used at a time | sealed type with variant-specific fields |
{}.Apply() on zero-arg case | TeamLead{}.Apply(), Idle{}.Apply(), None[string]{}.Apply() | TeamLead(), Idle(), None[string]() — call the case constructor directly |
Check: Search for iota declarations that represent a fixed set of categories/kinds/variants. Search for struct fields named kind, type, tag, variant of integer type paired with constants. Grep \{\}\.Apply\(\) (and \][a-z_, 0-9]*\{\}\.Apply\(\) for the parameterized form like None[string]{}.Apply()) — every hit is a leftover workaround from an early transpiler bug where bare zero-arg sealed-case constructors didn't lower correctly. The bug has been fixed; the {}.Apply() form should be replaced with the direct call. Pervasive in test files and any code that predates the fix.
Bad pattern — {}.Apply() boilerplate:
// BAD: leftover workaround
val msg = TeamLead{}.Apply()
val state = Idle{}.Apply()
val maybe = None[string]{}.Apply()
val s = Transition(Idle{}.Apply(), UserPrompted{}.Apply(), ctx)
Good pattern — direct case construction:
val msg = TeamLead()
val state = Idle()
val maybe = None[string]()
val s = Transition(Idle(), UserPrompted(), ctx)
Good pattern - sealed type with exhaustive match:
sealed type Shape {
case Circle(Radius float64)
case Rectangle(Width float64, Height float64)
case Point()
}
// No case _ needed - all variants covered
func describe(s Shape) string = s match {
case Circle(r) => f"radius=$r%.2f"
case Rectangle(w, h) => s"${w}x${h}"
case Point() => "point"
}
Bad pattern - manual discriminator:
// BAD: Manual variant encoding
type Shape struct {
kind int
var radius float64
var width float64
var height float64
}
val circleKind = 0
val rectKind = 1
Principle: GALA prefers its own standard data structures over Go native types. Go native types should only be used at interop boundaries (calling Go APIs, receiving Go returns). Internal logic should use GALA types for immutability, pattern matching, and functional operations.
Before flagging a Go slice or map, determine whether it sits at a true interop boundary. A value is "at a boundary" only if every use of it is one of:
f.Write(buf), strings.Join(parts, ","), http.DefaultClient.Do(req)(*bytes.Buffer).Read(buf), (*sql.Rows).Scan(dst...)http.Request(Body = body, Header = hdr)log.Printf(fmt, args...)If the value is also:
xs[i]), iterated (for _, x := range xs), appended to, measured (len(xs)), or returned from a GALA-internal function — it has leaked past the boundary and should be a GALA collection.The "scratch buffer" exception: go_interop.SliceWithSize[byte](n) created solely to be filled by a Go .Read(buf) / .Write(buf) / .Scan(buf) call on the next few lines is acceptable (bare make([]byte, n) is a hard error — use SliceWithSize) — this is the canonical I/O buffer pattern and has no GALA equivalent. Flag only if the buffer is subsequently inspected with manual index loops, appended to, or stored as a field of a GALA struct for later GALA-side use.
Smell signals (strong indicators the Go type has leaked internally):
[]T or map[K]V (not a Go-interop shim)var xs []T / var m map[K]V that is only read and written inside GALA code (no Go call consumes it)for _, x := range xs over a Go slice when xs.ForEach(f) would work on an Array[T]collection_immutable already imported in the same file but a Go slice/map is used anyway for similar workmapOf, sliceOf, indexBy that build Go maps/slices — usually a sign Array.GroupBy / Array.FoldLeft were overlookedApply these heuristics before flagging; record the inferred boundary/internal classification in the issue so the user can contest borderline cases.
| Issue | Pattern to Flag | Recommended Fix |
|---|---|---|
| SliceOf for general use | val items = SliceOf(1, 2, 3) when not passing to Go API | val items = ArrayOf(1, 2, 3) or ListOf(1, 2, 3) |
| SliceEmpty for general use | val items = SliceEmpty[int]() | val items = EmptyArray[int]() or EmptyList[int]() |
| Go slice type in struct | type Foo struct { Items []int } when functional ops needed | Use Array[int] or List[int] |
Bare len for length | len(x) — a hard error (GALA-E0035) | x.Size() (logical size; characters for strings) or x.ByteSize() (string bytes) — see rule 0 |
| Manual loop on slice | for i := 0; i < slice.Size(); i++ { ... } | Use GALA collection with .ForEach, .Map, .Filter |
Bare append on slice | result = append(result, item) — a hard error (GALA-E0035) | Array.Append() / List.Prepend() / FoldLeft; go_interop.SliceAppend/SliceAppendAll only at a Go boundary |
| SliceOf import confusion | import . "martianoff/gala/std" expecting SliceOf | SliceOf is in go_interop, but prefer ArrayOf/ListOf from collection_immutable |
| Missing functional ops | Using []T then writing manual Map/Filter loops | Switch to Array[T] or List[T] which have .Map(), .Filter(), .FoldLeft() |
| Manual loop on variadic args | for i := 0; i < len(args); i++ on variadic []T | Convert with ArrayOf(args...) then use functional methods |
| Variadic accumulation loop | var acc; for { acc = f(acc, args[i]) } on variadic | ArrayOf(args...).FoldLeft(init, f) or .FoldRight(init, f) |
Internal function returning []T | func groupBy(xs Array[T]) []Group — GALA-private helper returning Go slice | Return Array[Group] / List[Group] so the caller keeps functional ops |
Internal function taking []T | Non-interop helper with []T param | Take Array[T] / List[T] and let the Go boundary do the conversion |
Local var xs []T inspected in GALA code | var xs []T; ...; for _, x := range xs / xs[i] / len(xs) with no Go call consuming xs | Rebuild with Array[T] / List[T]; use .Size() / .Get(i) / .ForEach |
| Scratch buffer used beyond the Go read | val dst = SliceWithSize[byte](n); lr.Read(dst); for _, b := range dst { ... } | Read into a scratch buffer, then ArrayFromSlice(go_interop.SliceTo(dst, n)) before further processing |
Check: Search for SliceOf, SliceEmpty, SliceWithCapacity, SliceWithSize, []T declarations, append( calls, and manual loops over variadic parameters. Apply the §4.0 boundary heuristics. Only flag when the slice is observed internally (index, range, len, returned from a GALA-internal function) rather than exclusively at a Go call site.
Acceptable Go slice uses:
strings.Join, sort.Slice, etc.)SliceWithSize[byte](n) immediately passed to .Read / .Write / .Scan (and not inspected afterward — see §4.0 exception)other(args...))[]Tcollection.ToGoSlice() when needed| Issue | Pattern to Flag | Recommended Fix |
|---|---|---|
| Go map for general use | val m = map[string]int{} (map literal, a hard error GALA-E0008) or make(map[K]V) (GALA-E0035) | EmptyHashMap[string, int]() from collection_immutable |
| Go map literal | map[K]V{"a": 1, "b": 2} — a hard error (GALA-E0008) | HashMapOf(("a", 1), ("b", 2)); go_interop.MapPut(go_interop.MapEmpty[K, V](), ...) only at a Go boundary |
| Manual map iteration | for k, v := range m { ... } for transform/filter | Use HashMap.MapValues(), .Filter(), .ForEachKV(), .FoldLeftKV(), .Collect() |
| Go map in struct field | type Cache struct { data map[string]Entry } | Use HashMap[string, Entry] for immutability + functional ops |
| Manual map lookup with default | val v, ok = m[key]; if !ok { v = defaultVal } | hashMap.GetOrElse(key, defaultVal) |
| Manual map existence check | val _, ok = m[key]; if ok { ... } | hashMap.Contains(key) or hashMap.Get(key) match { case Some(v) => ... } |
| MapForEach from go_interop | MapForEach(goMap, func) for internal processing | Convert to HashMap first: HashMapFromGoMap(goMap).ForEachKV(...) |
| Mutable map accumulation | var m = map[K]V{}; for { m[k] = v } | Use FoldLeft to build HashMap, or use collection_mutable.HashMap |
Internal function returning map[K]V | func countBy(xs Array[T]) map[K]int — GALA-private helper returning Go map | Return HashMap[K, int] so the caller keeps functional ops |
Internal function taking map[K]V | Non-interop helper with map[K]V param | Take HashMap[K, V] and convert at the Go boundary |
| Index-by-build-up pattern | var m = map[K]V{}; xs.ForEach((x) => m[f(x)] = g(x)) | xs.FoldLeft(EmptyHashMap[K, V](), (m, x) => m.Put(f(x), g(x))); for grouping, HashMapFromGoMap(xs.GroupBy(f)) (GroupBy returns a Go map) |
Check: Apply the §4.0 boundary heuristics. Search for map[, make(map, MapEmpty, MapForEach, MapPut from go_interop. Flag when the map is observed internally (range-loop, indexed assignment, passed to another GALA function) rather than exclusively at a Go call site.
Acceptable Go map uses:
map[K]Vmap[string]any is unavoidableGood pattern — GALA HashMap:
import . "martianoff/gala/collection_immutable"
val config = EmptyHashMap[string, string]()
.Put("host", "localhost")
.Put("port", "8080")
val upper = config.MapValues((v) => strings.ToUpper(v))
val port = config.Get("port").GetOrElse("3000")
Bad pattern — Go map for internal logic:
// BAD: Go map with manual iteration (the map literal is also GALA-E0008)
var config = map[string]string{}
config["host"] = "localhost"
config["port"] = "8080"
for k, v := range config {
Println(s"$k=$v")
}
| Issue | Pattern to Flag | Recommended Fix |
|---|---|---|
| Channel for single async result | ch := make(chan T, 1); go func() { ch <- f() }(); <-ch — make, go, and chan are hard errors (GALA-E0035 / GALA-E0036) | Future(f()) then .Await() or .Map() |
| Channel for timeout | select { case r := <-ch: ... case <-time.After(d): ... } — select is a hard error (GALA-E0036) | future.WithTimeout(d) or FirstCompletedOf |
| Channel for fan-out | Spawning goroutines writing to shared channel | Sequence(futures) or Traverse(items, f) (top-level functions in concurrent) |
| Signal channel from a Go API | <-ctx.Done() (accepted, but the helper reads better); holding one in a type argument such as Some(ctx.Done()), or a lambda that returns one, is a hard error because it writes the struct{} element type (GALA-E0090) | go_interop.WaitDone(ctx) / IsDone(ctx) / WaitDoneTimeout(ctx, d); for any <-chan struct{}, WaitClosed(ch) / IsClosed(ch) / WaitClosedTimeout(ch, d); own signals are a go_interop.Signal (NewSignal()) |
| WaitGroup for completion | sync.WaitGroup + goroutines | Sequence(ArrayOf(futures...)) |
| Mutex for shared state | sync.Mutex protecting shared map/counter | Use immutable data + Future composition, or WithLock(mu, () => ...) from resource with a go_interop.Mutex |
Check: Search for make(chan, go func(), select { (hard errors, rules 0 and 0b) and sync.WaitGroup, sync.Mutex in non-interop code. A closure passed to Future must not capture unshareable state (GALA-E0037).
Acceptable Go concurrency uses:
Stream[T] insteadVariadic args pattern — convert to Array for functional processing:
// BAD: manual loop over variadic Go slice
func applyAll(handler Handler, filters ...Filter) Handler {
var h = handler
for i := filters.Size() - 1; i >= 0; i-- {
val f = filters[i]
val inner = h
h = (req) => f(req, inner)
}
return h
}
// GOOD: convert variadic to Array, use FoldRight
func applyAll(handler Handler, filters ...Filter) Handler =
ArrayOf(filters...).FoldRight(handler, (f, inner) => (req) => f(req, inner))
Good pattern - GALA collections:
import . "martianoff/gala/collection_immutable"
val nums = ArrayOf(1, 2, 3, 4, 5)
val evenDoubled = nums.Collect({ case n if n % 2 == 0 => n * 2 })
val sum = nums.FoldLeft(0, (acc, x) => acc + x)
Bad pattern - Go slices with manual loops:
import . "martianoff/gala/go_interop"
val nums = SliceOf(1, 2, 3, 4, 5)
var evens = SliceEmpty[int]()
for _, x := range nums {
if x % 2 == 0 {
evens = append(evens, x)
}
}
| Issue | Pattern to Flag | Recommended Fix |
|---|---|---|
fmt.Sprintf for simple formatting | fmt.Sprintf("Hello %s", name) | s"Hello $name" |
fmt.Sprintf with expressions | fmt.Sprintf("sum=%d", a + b) | s"sum=${a + b}" |
fmt.Println | fmt.Println("result:", x) | Println("result:", x) |
fmt.Print | fmt.Print("hello") | Print("hello") |
fmt.Sprintf with explicit format | fmt.Sprintf("%.2f", price) | f"$price%.2f" |
Unnecessary import "fmt" | import "fmt" used only for Println/Sprintf | Remove import, use s"..." / Println |
| String concatenation for formatting | "Hello " + name + ", age " + fmt.Sprintf("%d", age) | s"Hello $name, age $age" |
Check: Search for fmt.Sprintf, fmt.Println, fmt.Print, fmt.Printf, and import "fmt". For each:
fmt.Sprintf → replace with s"..." (auto-inferred verbs) or f"..." (explicit format specs)fmt.Println / fmt.Print → replace with Println / Printimport "fmt" → remove if only used for Sprintf/Println/Print (keep for fmt.Errorf, fmt.Fprintf, etc.)Acceptable fmt uses: fmt.Errorf, fmt.Fprintf, fmt.Fscan*, fmt.Stringer interface implementation, and any fmt function not covered by interpolation.
| Issue | Pattern to Flag | Recommended Fix |
|---|---|---|
| Long parameter list on single line | func f(a string, b string, c string, d string) T (>100 chars) | Use multi-line with trailing commas |
| Long struct declaration on single line | struct Foo(a string, b string, c string, d string) (>100 chars) | Use multi-line with trailing commas |
| Missing trailing comma in multi-line | Multi-line params without trailing comma | Add trailing comma for consistency |
Check: Search for func declarations and struct shorthand declarations with lines exceeding ~100 characters. These benefit from multi-line formatting with trailing commas.
Good pattern — multi-line with trailing commas:
func createServer(
host string,
port int = 8080,
tls bool = true,
maxConnections int = 100,
) Server = ...
struct Cookie(
Name string,
Value string,
Path string,
MaxAge int,
)
Bad pattern — long single line:
func createServer(host string, port int = 8080, tls bool = true, maxConnections int = 100) Server = ...
| Issue | Pattern to Flag | Recommended Fix |
|---|---|---|
| Options pattern instead of defaults | Struct with WithPort, WithTimeout option functions | Use default parameter values: func connect(host string, port int = 8080) |
| Multiple wrapper functions | func NewFoo(), func NewFooWithBar(), func NewFooWithBarAndBaz() | Single function with defaults: func NewFoo(bar int = 0, baz string = "") |
| Boolean flag parameter without name | connect("localhost", 8080, true) where true is ambiguous | Use named arg: connect("localhost", tls = true) |
| Positional args reducing readability | createUser("Alice", 30, "admin", true, false) | Use named args for clarity: createUser(name = "Alice", age = 30, role = "admin") |
| Default before a required parameter | func f(a int = 1, b int, c string = "x") — a hard error (GALA-E0013) | Defaults must be contiguous at end: func f(b int, a int = 1, c string = "x") |
Check: Search for the functional options pattern (structs named *Option or *Config with With* functions), multiple function overloads with incremental parameters, and call sites with 3+ positional boolean/int literal arguments where named args would clarify intent.
Acceptable patterns: Go interop functions that must match Go signatures cannot use defaults.
| Issue | Pattern to Flag | Recommended Fix |
|---|---|---|
| Redundant variable type | val x int = 42 | val x = 42 |
| Redundant generic params on helpers | Some[int](42) | Some(42) |
Redundant type arg on None[T]() in inferable context | func parse() Option[int] = None[int]() | func parse() Option[int] = None() (type pinned by the return type) |
| Redundant collection types | ListOf[int](1, 2, 3) | ListOf(1, 2, 3) |
| Redundant single-param struct constructor | Box[int](Value = 42) | Box(Value = 42) (type inferred from named field value) |
| Redundant generic function call type params | Try[int](() => { return 1 }) | Try(() => { return 1 }) (type inferred from lambda return) |
| Unnecessary lambda for zero-arg func | Try(() => os.TempDir()) | Try(os.TempDir) — pass function reference directly when func takes no args; for any other single-expression body drop () => (see rule 11d) |
| Redundant generic function call type params | NewCons[int](head, tail) | NewCons(head, tail) (type inferred from arguments) |
| Redundant lambda param type | list.Map((x int) => x * 2) | list.Map((x) => x * 2) (type inferred from method signature) |
| Redundant method type param | list.Map[int]((x) => x * 2) | list.Map((x) => x * 2) (Go infers from lambda) |
| Redundant FoldLeft type param | list.FoldLeft[int](0, (acc int, x int) => acc + x) | list.FoldLeft(0, (acc, x) => acc + x) (accumulator type inferred from zero value) |
| Redundant wrapper method lambda types | str.Filter((r rune) => r == 'a') | str.Filter((r) => r == 'a') (type inferred from non-generic method signature) |
Check: Search for the pattern Name[ConcreteTypes](args) — any call where [...] contains concrete types (not type parameter declarations like [T any]) and the arguments already provide enough information for Go to infer the type parameters. This includes:
Single-type-param generic struct constructors: Box[int](Value = 42) → Box(Value = 42) — Go infers the single type param from the named field value
Single-type-param generic function calls: Try[int](f), NewCons[int](head, tail) — argument types determine the type param
Helper constructors: Some[int](42), ListOf[int](1, 2, 3) — element values determine type params
Zero-arg sealed-variant constructors when the context pins a CONCRETE type: None[int]() (and other zero-field cases of a generic sealed type) when the surrounding context supplies a concrete type argument. A zero-field variant has no argument to infer from, but the transpiler propagates an expected type downward and injects the type arg, so the explicit […] is redundant. Flag None[Concrete]() → None() when it appears as any of:
return whose declared return type is a concrete Option[Concrete] — func parse() Option[int] = None[int]() → None()val/var with an explicit concrete Option[Concrete] type — val x Option[string] = None[string]() → None()Option[Concrete]ArrayOf[Option[int]](None[int]()) → ArrayOf[Option[int]](None())match arm whose result type is externally pinned to a concrete Option[Concrete] (e.g. the match is the body of a function returning Option[int])if/else branch whose sibling branch is a Some(...) of known concrete type — if (c) Some(x) else None[int]()Do NOT flag (explicit typing is still REQUIRED) when:
func (a Array[T]) HeadOption() Option[T] = … None[T]() or func (o Option[T]) OrElse(...) = … None[T](). A bare None() does compile here (the declaration's own and receiver type parameters count as known types), but the explicit None[T]() is common in the collection/std library and is not worth churning — do not flag it.None[int]() inside a lambda whose result type is unconstrained, e.g. arr.Map((x) => None[int]()): removing [int] makes the type undeterminable (GALA-E0018). Keep it.Rule of thumb: only flag when the type argument you would remove is a concrete type (int, string, Array[JField], …), never when it is an in-scope abstract type parameter.
Exception: Explicit types ARE required for:
Left[L, R](), Right[L, R]() — no value arguments to infer from (and Either carries two params)EmptyArray[T](), EmptyList[T](), EmptyHashMap[K, V](), Empty[T]() — no elements to infer fromPair[string, int]("a", 1) — Go cannot infer when there are 2+ type params on struct instantiationPair[C, B](First = ...) — abstract type params from enclosing method must be explicitUnfold[A, S](seed, f) — Go often cannot infer all params when multiple are involvedval f = (x int) => x * 2)| Issue | Pattern to Flag | Recommended Fix |
|---|---|---|
| Manual accumulation | var acc; for { acc = f(acc, x) } | list.FoldLeft(init, (acc, x) => f(acc, x)) |
| Manual filter | for { if cond { append } } | list.Filter(predicate) |
| Manual map | for { result = append(result, f(x)) } | list.Map(f) |
| Filter then Map | list.Filter(p).Map(f) | list.Collect({ case x if p(x) => f(x) }) |
| Map then Filter (flatMap pattern) | list.Map(f).Filter(p) when f returns Option-like | list.Collect({ case x if p(x) => f(x) }) |
| FlatMap + Option for filter+transform | list.FlatMap((x) => if p(x) { Some(f(x)) } else { None }) | list.Collect({ case x if p(x) => f(x) }) |
| Index-based iteration | for i := 0; i < x.Size(); i++ | x.ForEach(f), or x.ZipWithIndex() when the index is needed |
| Option side effects | if opt.IsDefined() { f(opt.Get()) } | opt.ForEach(f) |
| Reimplementing collection methods | Defining Map, Filter, Fold etc. with manual loops when wrapping a collection | Delegate to underlying collection's method |
| Manual ForAll pattern | for { if !p(x) { return false } }; return true | collection.ForAll(p) |
| Manual Exists pattern | for { if p(x) { return true } }; return false | collection.Exists(p) |
| Manual Find pattern | for { if p(x) { return Some(x) } }; return None | collection.Find(p) |
| Manual Reverse | for i := len-1; i >= 0; i-- { append } | collection.Reverse() |
| Manual ZipWithIndex | for i := 0; ...; result.Append((elem, i)) | collection.ZipWithIndex() |
| Manual IndexOf | for i := 0; ...; if elem == target { return i } | collection.IndexOf(target); for a predicate, collection.Find(p) or ZipWithIndex().Find(...) |
Check: Also search for .Filter( followed by .Map( on the same collection (chained or via intermediate val). These should use .Collect with a partial function instead.
Bad pattern — Filter + Map chain:
// BAD: Two passes over the collection
val evenDoubled = numbers.Filter((x) => x % 2 == 0).Map((x) => x * 2)
// BAD: Filter + Map with intermediate val
val adults = people.Filter((p) => p.Age >= 18)
val names = adults.Map((p) => p.Name)
// BAD: FlatMap with Option for conditional transform
val results = items.FlatMap((x) => if x.IsValid() { Some(x.Transform()) } else { None[Output]() })
Good pattern — Collect with partial function:
// GOOD: Single pass, filter and transform together
val evenDoubled = numbers.Collect({ case n if n % 2 == 0 => n * 2 })
// GOOD: Collect with extractor
val names = people.Collect({ case p if p.Age >= 18 => p.Name })
// GOOD: Collect replaces FlatMap + Option
val results = items.Collect({ case x if x.IsValid() => x.Transform() })
// GOOD: Collect with sealed type extractor
val values = options.Collect({ case Some(v) => v * 2 })
for must justify itself (HIGH priority)The table rows in rule 7b are written in C-style for i := 0; i < n; i++ form,
but GALA code almost always writes the counter loop while-style, which
those rows do not visibly match:
var i = 0
for i < n {
...
i = i + 1
}
Treat every while-style loop exactly like the C-style form. Rule 1's
"loop counters are an acceptable var" excuses the counter; it does not
excuse the loop. The question for every for is whether a combinator — or a
function that already exists — already says it.
Mechanical pass (run it; do not rely on reading). Enumerate every loop and classify each hit — none may be left unclassified in the report:
FILES=$(find . -type f -name '*.gala' -not -path './bazel-*' -not -path './.claude/*' -not -path './.gala/*' -not -path './.git/*' -not -path '*/node_modules/*' -not -path '*/vendor/*')
grep -nE '^\s*for\b' $FILES
Every hit is either a finding or an Accepted loop with its reason number
written in the report (see "Acceptable loops" below). A report that does not
account for each for is incomplete. Tests, demos, examples and tools are
scanned too.
Before recommending a replacement, check behaviour parity. Hand-rolled
helpers often differ from the library at the edges: a split that drops a
trailing "", ASCII-only case mapping, rune count vs. display width, an early
exit a Fold would lose. State the difference in
the finding when there is one; the fix must keep the behaviour the call sites
rely on (or the finding must say the change is intended).
Recommendations must compile. These were checked against the stdlib source;
do not invent others (stream.Range(...).Count(p), Str.HeadOption,
Array.IndexWhere do not exist).
| Receiver | Available |
|---|---|
Array[T] | ArrayTabulate(n, f), ArrayFill(n, v), Map, FlatMap, Filter, Collect, FoldLeft, FoldRight, Reduce, ReduceOption, ForEach, ForAll, Exists, Find, FindLast, Count(p), Contains, IndexOf(elem), LastIndexOf(elem), Distinct, Zip, ZipWithIndex, Sliding, Grouped, Take, Drop, TakeWhile, DropWhile, Span, Partition, GroupBy, Slice, Reverse, HeadOption, LastOption, Init, Updated, MkString(sep), Sorted, SortWith, SortBy |
stream (import "martianoff/gala/stream") | stream.Range(lo, hi), stream.RangeStep(lo, hi, step), stream.Iterate(seed, f), stream.Unfold(seed, f), stream.FromArray(xs); methods Map, Filter, Find, Exists, ForAll, ForEach, Fold, Scan (emits the seed first), IndexWhere, IndexOf, TakeWhile, DropWhile, Take, Drop, Zip, ZipWithIndex, Intersperse, MkString, Count() (no predicate — use .Filter(p).Count()), ToArray |
Str via S(s) (import . "martianoff/gala/strings") | ToChars(), ToString() (not .String()), Length, Take, Drop, TakeRight, DropRight, Substring(lo, hi), SplitAt(i) (returns Tuple[Str, Str]), Lines(), Split, Words, Contains, ContainsAny, Count(sub), IndexOf(sub) (returns Option[int]), IndexOfChar, LastIndexOf, StartsWith, EndsWith, CharAt, Trim*, PadLeft/PadRight(n, r), Center, Repeat, Replace*, ToLower/ToUpper, Map, Filter, Exists, ForAll, Fold, Find, Reverse, ZipWithIndex |
GALA strings free functions | Contains, HasPrefix, HasSuffix, EqualFold, LastIndex, Trim*, ToLower, ToUpper, Repeat, Replace, ReplaceAll, Split / SplitN / Fields (return Array[string]), Join(Array[string], sep) — there is no free Count/Index (use S(s).Count, or Go strings where that is the import) |
string | s.Size() — characters (runes), not bytes; s.ByteSize() for bytes |
| Go stdlib | strconv.Itoa / Atoi, strings.NewReplacer, strings.IndexRune, strings.LastIndexAny, unicode/utf8, math.Mod, slices.EqualFunc — fine to call |
Sorted / SortWith / SortBy are stable (ties keep their input order), so
they replace a hand-written stable sort directly.
Array values are not ==-comparable; compare windows with
w.Zip(needle).ForAll((t) => t.V1 == t.V2).
The table lists the non-obvious methods; the core accessors (Get, Length,
Size, Append, AppendAll, Head, Last, IsEmpty, NonEmpty,
ToGoSlice, ArrayFromSlice(goSlice)) exist too. Verified edge behaviour:
| Call | Behaviour |
|---|---|
Array[rune] → string | string(rs.ToGoSlice()). Not rs.MkString("") — that prints code points (104233…) |
string → runes | S(s).ToChars(). []rune(s) is not GALA syntax |
stream.….IndexWhere(p), .IndexOf(x) on Array | int, -1 when absent |
S(s).IndexOf(sub), S(s).IndexOfChar(r) | Option[int] |
S(s).Lines(), strings.Split(s, "\n") | keep a trailing "" ("a\nb\n" → 3 items); Split("", sep) → one "". A helper that drops them is not a drop-in match |
S(s).Fold(z, f) | returns the accumulator type U |
Go []rune / []byte parameters | ArrayFromSlice(rs) to get combinators; string(rs[a:b]) to measure a range with a string helper |
| Loop shape | Replacement |
|---|---|
var out = EmptyArray[T](); var i = 0; for i < n { out = out.Append(f(i)); i = i + 1 } | ArrayTabulate(n, f) |
for i < n { out = out.Append(v) } (same value) | ArrayFill(n, v) |
for i < n { g(xs.Get(i)); i = i + 1 } | xs.ForEach(g) |
for i < n { g(xs.Get(i), i) } | xs.ZipWithIndex().ForEach((t) => g(t.V1, t.V2)) |
Parallel arrays: for i < n { g(a.Get(i), b.Get(i)) } | a.Zip(b).ForEach(...) (or .Map) |
Consecutive pairs: for i < n-1 { g(xs.Get(i), xs.Get(i+1)) } | xs.Zip(xs.Drop(1)) or xs.Sliding(2) |
Running total emitted per step: for { out = out.Append(pos); pos = pos + d(i) } | stream.FromArray(ds).Scan(start, (p, d) => p + d).Take(n).ToArray() (Scan emits the seed first, so this yields the n start positions), or FoldLeft over a (pos, out) tuple |
Accumulator carried in several vars: var acc; var given; var out; for {...} | FoldLeft over a tuple (acc, given, out) |
Repeat a state update N times: for i < N { m = Update(m, X); i = i + 1 } | stream.Range(0, N).Fold(m, (m, _) => Update(m, X)) |
Search: for i < n { if p(i) { return i }; i = i + 1 }; return n | stream.Range(start, n).Find(p).GetOrElse(n) / .IndexWhere(p) |
Last match: loop keeping the latest index/element that satisfies p | xs.FindLast(p); for an index, xs.ZipWithIndex().FindLast((t) => p(t.V1)).Map((t) => t.V2) |
Cyclic search from sel (next/prev enabled item) | stream.Range(1, n + 1).Map((k) => (sel + k) % n).Find(p).GetOrElse(sel) |
Count: var c = 0; for ... { if p(x) { c = c + 1 } } | xs.Count(p); over a range, stream.Range(a, b).Filter(p).Count() |
Max/min tracking: if cur > best { best = cur } inside a loop | xs.Map(f).FoldLeft(0, (a, b) => if (a > b) a else b) / ReduceOption |
Sum: total = total + f(x) | xs.FoldLeft(0, (t, x) => t + f(x)) |
Join with a separator (manual if i > 0 { out = out + sep }) | strings.Join(xs, sep) / xs.MkString(sep) |
| Separator between items (intersperse) | stream.FromArray(xs).Intersperse(sep) or FlatMap over ZipWithIndex |
Run-length grouping into runs (run, runKey, started) | FoldLeft over (out, current) seeded from the head — the run-length step is the fold body |
Non-unit or geometric step: for w < 40 { ...; w = w + 4 }, for c <= 256 { c = c * 2 } | stream.RangeStep(12, 41, 4); stream.Iterate(1, (c) => c * 2).TakeWhile((c) => c <= 256) |
Fixed-step loop over a range: for y < yEnd { ...; y = y + 1 } | stream.Range(y0, yEnd).ForEach(...) |
| Worklist that grows while processed, or an early-exit fold (stop when a pure step reports it is done) | a tail-recursive helper over the state tuple; FoldLeft cannot stop early, so do not force it |
Test assertion sweep threading T: for { t = Eq(t, got(i), want(i)) } | cases.FoldLeft(t, (t, c) => Eq(t, got(c), want(c))) / stream.Range(a, b).Fold(t, ...) — keeps the per-case message, which ForAll would lose |
Two combinator passes (e.g. first and last index) are an acceptable price for removing a loop — unless the loop is on a documented hot path (reason 1).
| Issue | Pattern to Flag | Recommended Fix |
|---|---|---|
| Break-by-assignment | i = n, j = nn, k = -1, i = xs.Length() used only to end the loop — including inline forms { ok = false; j = nn }, { i = n; continue } | Prefer the combinator the loop is hiding (Exists, ForAll, Find, IndexWhere, TakeWhile); if the loop is genuinely justified, use break or return |
| Sentinel in the loop condition | for i < n && !found, for i < n && idx < 0, for !done — set in the body, even if also read after the loop | the combinator that returns that value (Exists / Find / IndexWhere), or break at the point the flag is set |
Flag checked by a break at the loop head | if done { break } at the top, done = true further down | break where done is set |
Counter assignment inside a range loop | for _, c := range s { ...; i = end } — this does not exit a range loop; it silently keeps iterating | always a bug: break, or the combinator |
| Flag + inner loop for substring/sequence match | var ok = true; for j < nn { if a.Get(i+j) != b.Get(j) { ok = false; j = nn } } | strings.Contains / S(h).Contains for text; xs.Sliding(nn).Exists((w) => w.Zip(needle).ForAll((t) => t.V1 == t.V2)) for arrays |
| One flag stopping nested loops | fits = false ending both an inner and an outer loop | extract the loops into a function and return, or precompute the stop point (Scan + TakeWhile) before the side effects |
break and continue are valid GALA. A counter set to its bound is not an
idiom; it is a missing break — and usually a missing combinator.
Check:
# counter/flag clobbers, standalone or inline
grep -nE '\b[a-z]\w* = (n|nn|hn|pn|k|end|total|count|size|[a-z]+\.(Length|Size)\(\))\s*($|;|\})' $FILES | grep -vE '\b(val|var) '
grep -nE '\b(ok|found|done|fits|hit|matched|stop)\w* = (true|false)' $FILES
# sentinels in loop conditions
grep -nE '^\s*for .*&& *(!\w+|\w+ *[<>]=? *-?[0-9]+)' $FILES
Discard clamps (if end > n { end = n }) — they are not exits.
for _, c := range s that builds a new string with out = out + string(c) is
quadratic as well as imperative. Any +-concatenation of a string inside a
loop is a finding: use the library call below, slicing, or a
strings.Builder (a Builder-backed loop may then qualify for reason 1).
| Loop shape | Replacement |
|---|---|
Append every rune to an Array[rune] | S(s).ToChars() |
Count runes: var n = 0; for _ = range s { n = n + 1 } | s.Size() (characters, not bytes) |
Count a rune: for _, c := range s { if c == '\n' { n = n + 1 } } | S(s).Count("\n") |
Split on a rune, accumulating cur and out | strings.Split(s, "\n") (GALA strings returns Array[string]) / S(s).Lines() — check the trailing-"" behaviour |
| Join lines back | strings.Join(lines, "\n") |
Keep all but the last rune (seen < total - 1) | S(s).DropRight(1).ToString() |
Split at a rune column (if i < col { lhs } else { rhs }) | S(s).SplitAt(col) |
Take / drop the first k runes, or a rune range | S(s).Take(k) / S(s).Drop(k) / S(s).Substring(lo, hi) |
| First / last rune | S(s).ToChars().HeadOption() / .LastOption() |
Leading run (TakeWhile) / leading count | S(s).ToChars().TakeWhile(p); leading spaces: s.Size() - strings.TrimLeft(s, " ").Size() |
| Trim trailing spaces | strings.TrimRight(s, " ") |
Case-map by arithmetic (c + 32 for 'A'..'Z') | strings.ToLower / strings.ToUpper — ASCII arithmetic is also wrong for non-ASCII |
for _, c := range s { return c == '.' } (first-rune test) | strings.HasPrefix(s, ".") |
| Contains a rune | S(s).Exists((c) => c == r) / Go strings.ContainsRune |
| Find a rune from an index | strings.IndexRune / S(s).IndexOfChar(r); over Array[rune], stream.FromArray(rs).Drop(start).IndexWhere(p) + start |
Widest line: if current > width { width = current } on '\n' | strings.Split(s, "\n").Map((l) => l.Size()).FoldLeft(0, (a, b) => if (a > b) a else b) — use a display-width function instead of Size() if display columns, not runes, are meant |
| Digit parse / int → string | strconv.Atoi / strconv.Itoa / s"$n" |
| Escape / multi-replace | strings.NewReplacer(...).Replace(s) / ReplaceAll |
| Per-rune transform / filter / predicate / fold | S(s).Map(f), S(s).Filter(p), S(s).Exists(p), S(s).ForAll(p), S(s).Fold(z, f) |
Check: grep -nE 'for _?,? ?\w* ?:?= range ' $FILES and
grep -nE '= \w+ \+ (string\(|\w+\b)' $FILES inside loop bodies.
Before accepting any small helper, check whether its body is a hand-rolled version of something that already exists in:
strings, strconv, unicode/utf8, math, slices);martianoff/gala/strings (Str), collection_immutable, stream;Fill/Set
method, summing per-element widths when a width function exists, a test
helper copying a function the package already exports, a private
contains/lower-case pair re-implementing an exported matcher. Grep the
package's exported functions and compare.Flag it regardless of how the loop is written, and whether or not it has a loop at all. Signals:
strContains, xToLower, xSplitLines, xDropLast, stringRunes,
xRunes, RuneCount, intToStr, xTrim, xEscape, indexOfX, …Join…,
…Contains…, …Repeat….(string) string,
(string) int, (int) string, (string) Array[string], (string) Array[rune],
(string, string) bool, (string, int) string, (string, int) Tuple[…],
(Array[rune], int, int) string, (Array[rune], int, …) bool|int,
(Array[T], T) bool|int, (Array[string], string) string, (*T, …) string.for t < 0 { t += 2π } style reduction (math.Mod), or hand-rolled
sin/cos/sqrt.| Hand-written helper | Library call |
|---|---|
| substring search | strings.Contains(h, n) / S(h).Contains(n) |
| lower/upper-case | strings.ToLower / strings.ToUpper |
| split / join lines | strings.Split(s, "\n") / S(s).Lines(); strings.Join(xs, "\n") / xs.MkString("\n") |
| string → runes | S(s).ToChars() |
| rune count | s.Size() (utf8.RuneCountInString(s) at a Go boundary) |
| prefix / suffix test | strings.HasPrefix / strings.HasSuffix |
| occurrence count | S(s).Count(sub) / xs.Count(p) |
| repeat / pad | strings.Repeat, S(s).PadLeft(n, ' '), S(s).PadRight(n, ' ') |
| trim | strings.TrimRight/TrimLeft/TrimSpace |
| int ↔ string | strconv.Itoa / strconv.Atoi / s"$n" |
| last separator | strings.LastIndex / strings.LastIndexAny(path, "/\\") |
| escape | strings.NewReplacer(...) |
| membership / position in an array | xs.Contains(x) / xs.Exists(p) / xs.IndexOf(x) |
| reverse / distinct / sort | xs.Reverse(), xs.Distinct(), xs.SortBy(f) (stable) |
| element-wise equality of Go slices | slices.EqualFunc(a, b, eq) |
| angle reduction | math.Mod |
| fill a region with one value | the container's own bulk primitive (Fill, SetRange, …) |
A thin exported wrapper kept for API stability (e.g. a public RuneCount
or XContains) is fine — but its body must be the library call, not a loop.
The same helper body copied under a different name (stringRunes, strRunes,
parserRunes, … one per file; a "join rows into text" helper in every test
file), or the same loop body repeated inside one file (the same dispatch block
pasted four times; a function whose body is another function's inner loop), is
a finding on every copy. Report the group together — including copies in files outside
the requested scope — and recommend one helper, or, usually, deleting all of
them for the library call.
Check: compare private function bodies that are identical after renaming,
for any parameter list, not just (s string):
# helpers grouped by signature shape; read bodies within each group
grep -nE '^func [a-z]\w*\(' $FILES | sed -E 's/^([^:]+:[0-9]+):func ([a-z]\w*)(\(.*)$/\3 \2 \1/' | sort
Also compare test helpers against the package's exported functions (a test copy of an exported function is a duplicate), and look for repeated multi-line blocks within a file.
A for may stay when it does one of these, and the report must say which:
Fill, its serializer, its diff), a strings.Builder or Go scratch slice
that is the output, or a read/write loop on a per-request / per-event /
per-frame path whose comment says why (no allocation, early exit). This does
not cover calling code that loops x.Set over a region — call the
primitive — nor a Go slice used as an intermediate that a Map would build.Scan +
TakeWhile, or recurse.Println per
line is not this case: ForEach.T-threading row
in 7c-1.break/return, and slice or use a
Builder instead of +-concatenating.Even an accepted loop gets 7c-2 and 7c-3 applied. Report such a loop as
ACCEPTED-WITH-FIX file:line | reason # | the 7c-2/7c-3 fix — the loop stays,
its body changes.
Find / IndexWhere / TakeWhile.i = end that
moves to the next token is the loop's step; the clobber grep will list it —
discard it along with clamps. A candidate from the sentinel grep is a finding
only if the body sets the tested value; a pure predicate or data bound in
the condition (!isClosingLine(l), depth < max) is a TakeWhile/search, not a
flag. The greps are candidate lists, not verdicts, and compound conditions
(a || b, x < n && f(x) == y) must still be read.stream.Range(...).ForEach is not a fix:
report ACCEPTED 1 and suggest adding the primitive.FoldLeft(s, (c, m) => if (c.Done) c else step(c, m))) is fine when the
skipped steps cost nothing; use recursion when step is expensive or the
work list grows while processing.X/Width vs Y/Height) — are duplicates. Variants whose
semantics differ (breadth-first vs depth-first processing) are not, unless
they can be unified without changing behaviour; say which.Folds; they are not fixtures.BUG line — a replacement that
fixes one is an intended behaviour change and the report must say so.| Issue | Pattern to Flag | Recommended Fix |
|---|---|---|
| If-else for conditional Option | if (cond) Some(v) else None[T]() | When(cond, v) |
| Negated condition for Option | if (!cond) Some(v) else None[T]() | Unless(cond, v) |
| Custom helper for conditional Option | func optionFromBool[T](cond bool, v T) Option[T] | Remove custom helper, use When(cond, v) from std |
| Nil map lookup boilerplate | val v = m[key]; if v == nil { None() } else { Some(v) } | OptionFromMap(m, key) from go_interop |
| Double nil check on Go map | if m == nil { return empty }; val v = m[k]; if v == nil { ... } | OptionFromMap(m, k) handles both nil map and missing key |
| Range over possibly-nil slice | if s != nil { for _, x := range s } | for _, x := range SliceFromNil(s) from go_interop |
Check: Search for if.*Some.*else.*None patterns, custom optionFrom* helper functions, double nil-check patterns on Go maps, and nil guards before range loops.
Good patterns:
import . "martianoff/gala/std"
import . "martianoff/gala/go_interop"
// Conditional Option creation
val name = When(s != "", s)
val deadline = When(ok, t)
val fallback = Unless(isDisabled, defaultValue)
// Nil-safe Go map lookup
val params = OptionFromMap(queryMap, "page")
.FlatMap((v) => Try(strconv.Atoi(v)).ToOption())
.GetOrElse(1)
// Nil-safe Go slice iteration
for _, item := range SliceFromNil(maybeNilSlice) {
process(item)
}
Bad patterns:
// BAD: verbose conditional Option
val name = if (s != "") Some(s) else None[string]()
// BAD: double nil check
val qp = r.bridge.AllQueryParams()
if qp == nil { return EmptyArray[string]() }
val values = qp[name]
if values == nil { return EmptyArray[string]() }
| Issue | Pattern to Flag | Recommended Fix |
|---|---|---|
| Go colon syntax for bridge structs | pkg.GoStruct{Field: value} | pkg.GoStruct(Field = value) — GALA named-arg syntax |
| Mixed construction styles | GALA structs use =, Go structs use : in same file | Use = syntax consistently for both |
Check: Search for composite literal syntax (Type{Field: value}) on Go-imported types. If the type comes from a non-GALA import, suggest GALA named-arg syntax.
Acceptable Go literal uses: When constructing Go types that require specific field ordering or embedding, or when the composite literal includes non-named elements.
Good pattern:
// Consistent GALA syntax for both GALA and Go structs
val cookie = Cookie(Name = "session", Value = "abc")
val goCookie = http.Cookie(Name = "session", Value = "abc", Path = "/")
Bad pattern:
// Inconsistent: GALA uses =, Go uses :
val cookie = Cookie(Name = "session", Value = "abc")
val goCookie = http.Cookie{Name: "session", Value: "abc", Path: "/"}
| Issue | Pattern to Flag | Recommended Fix |
|---|---|---|
| Imperative retry loop | var attempts = 0; for attempts < max { ... attempts++ } | Retry(max, backoff, action) from concurrent |
| Manual backoff calculation | var delay = initial; delay = delay * 2; if delay > max { delay = max } | ExponentialBackoff(initial, max) |
| Manual constant delay | time.Sleep(fixedDuration) inside retry loop | ConstantBackoff(fixedDuration) |
| Retry without backoff | Retry loop with no sleep between attempts | Retry(max, NoBackoff(), action) |
Check: Search for var attempts or var retries paired with for loops and time.Sleep. These are retry patterns that should use the Retry combinator.
Good pattern:
import . "martianoff/gala/concurrent"
val result = Retry(3, ExponentialBackoff(100 * time.Millisecond, 5 * time.Second), (attempt) => {
val resp = callService()
if resp.Code() < 500 { return Success(resp) }
return Failure[Response](fmt.Errorf("attempt %d: status %d", attempt, resp.Code()))
})
Bad pattern:
// BAD: imperative retry with manual backoff
var lastResp = InternalError("no attempts")
var attempts = 0
var backoff = 100 * time.Millisecond
for attempts < 3 {
val resp = callService()
lastResp = resp
if resp.Code() < 500 { return resp }
time.Sleep(backoff)
backoff = backoff * 2
attempts = attempts + 1
}
return lastResp
| Issue | Pattern to Flag | Recommended Fix |
|---|---|---|
| Block body for single expr | func f() T { return expr } | func f() T = expr |
| Lambda block for single expr | (x) => { return x * 2 } | (x) => x * 2 |
| Block lambda with no typed context | val f = (x int) => { val y = x * 2; y } — a standalone block lambda is treated as void, so the trailing y is rejected as evaluated but not used | Add return y, or use an expression body. When the lambda is passed where a value is expected (e.g. xs.Map(...)), the trailing expression is already the result; no return needed |
| Multi-line when one-liner works | if cond { return a } else { return b } | Use if-expression: if (cond) a else b |
| Issue | Pattern to Flag | Recommended Fix |
|---|---|---|
| Mutable var + if-statement for val | var x = a; if (cond) { x = b } | val x = if (cond) b else a |
| If-statement with return in both branches | if cond { return a } else { return b } | return if (cond) a else b |
| Ternary workaround with var | var result; if c { result = x } else { result = y }; use(result) | val result = if (c) x else y |
| Block if-expression when one-liner works | val x = if (c) { a } else { b } where a, b are simple | val x = if (c) a else b |
Check: Search for var declarations immediately followed by if/else that assign different values. These should use if-expressions.
Good patterns:
// Simple if-expression
val status = if (score > 50) "pass" else "fail"
// Block branches for complex logic
val url = if (query != "") {
val encoded = encode(query)
s"$base?$encoded"
} else {
base
}
// Mixed: one block, one expression
val label = if (count > 1) {
val suffix = "s"
s"$count item$suffix"
} else "1 item"
return (LOW priority)A block-bodied function or method with a result type returns its trailing
expression, as a block lambda passed where a value is expected and a match arm
do. A return on the last statement is therefore redundant: prefer the
implicit trailing value. This is a style preference — an explicit trailing
return is still valid GALA and compiles to the same Go.
| Issue | Pattern to Flag | Recommended Fix |
|---|---|---|
Trailing return in a block function or method | the final statement of a func ... T { ... } body is return <expr> | drop the return: end the body in <expr> |
Trailing return in both branches of a final if/else | the body ends in if (c) { ...; return a } else { ...; return b } | drop both returns: the branches carry the value |
Trailing return in a value-typed block lambda | xs.Map((x) => { val y = x * 2; return y + 1 }) — the lambda is passed where a value is expected | xs.Map((x) => { val y = x * 2; y + 1 }) |
Prefer rule 8d when it applies. If the body is a single return <expr>
(or can become one), the stronger fix is an expression body —
func f() T = expr, (x) => expr — not a block that ends in expr.
Do NOT flag:
return that is not the body's final statement, or one
inside a guard branch that exits before the end (if (n < 0) { return None() }
followed by more statements; a return inside a for loop or a match arm
that is not the tail).return in a function with no result type — it carries no value.val f = (x int) => { ...; return y }.
Such a lambda is treated as void unless it returns explicitly, so the return
is required there (see rule 8d).Check: For each block-bodied func with a result type, and each block
lambda passed as an argument, look at the last statement before the closing
brace; flag it when it is return <expr> (or a final if/else whose every
branch ends in return <expr>).
Bad pattern — redundant trailing return:
func describe(u User) string {
val name = u.Name.Trim()
return s"$name (${u.Age})"
}
Good pattern — implicit trailing value, return kept for the early exit:
func describe(u User) string {
if (u.Name == "") {
return "anonymous" // early exit: keep `return`
}
val name = u.Name.Trim()
s"$name (${u.Age})" // trailing value is the result
}
| Issue | Pattern to Flag | Recommended Fix |
|---|---|---|
| Single-use intermediate val | val x = f(); g(x) where x used once | g(f()) inline directly |
| Verbose tuple creation | Tuple[A, B](V1 = a, V2 = b) | (a, b) |
| Chained val assignments | val a = x; val b = f(a); val c = g(b); c | g(f(x)) or method chaining |
| Val for simple field access | val x = obj.field; use(x) once | use(obj.field) |
| Intermediate collection | val arr = toX(); arr.Method() | toX().Method() chain directly |
Exception: Keep intermediate vals for:
When creating wrapper types around collections (like Str wrapping string as Array[rune]), delegate to the underlying collection's methods instead of reimplementing.
| Issue | Pattern to Flag | Recommended Fix |
|---|---|---|
| Reimplementing Map | func (w Wrapper) Map(f) { for i := 0; ... } | toCollection(w).Map(f) then rewrap |
| Reimplementing Filter | func (w Wrapper) Filter(p) { for ... if p(x) { append } } | toCollection(w).Filter(p) |
| Reimplementing Fold | func (w Wrapper) Fold(z, f) { var acc = z; for ... } | Delegate to toCollection(w).FoldLeft(z, f) |
| Reimplementing ForAll | for { if !p(x) { return false } }; return true | toCollection(w).ForAll(p) |
| Reimplementing Exists | for { if p(x) { return true } }; return false | toCollection(w).Exists(p) |
| Reimplementing Find | for { if p(x) { return Some(x) } }; return None | toCollection(w).Find(p) |
| Reimplementing Reverse | for i := len-1; i >= 0; i-- | toCollection(w).Reverse() |
| Reimplementing ZipWithIndex | for i := 0; ...; append((x, i)) | toCollection(w).ZipWithIndex() |
| Reimplementing ForEach | for i := 0; ...; f(x) | toCollection(w).ForEach(f) |
Good pattern:
// Illustrative: a string wrapper that delegates to Array[rune] operations
func (s Str) Map(f func(rune) rune) Str =
Str(value = runesToString(toRunes(s.value).Map(f)))
func (s Str) Filter(p func(rune) bool) Str =
Str(value = runesToString(toRunes(s.value).Filter(p)))
func (s Str) ForAll(p func(rune) bool) bool =
s.NonEmpty() && toRunes(s.value).ForAll(p)
func (s Str) IsAlpha() bool = s.NonEmpty() && toRunes(s.value).ForAll(unicode.IsLetter)
| Issue | Pattern to Flag | Recommended Fix |
|---|---|---|
| Nullable without Option | func f() *T returning nil | func f() Option[T] |
Bare panic for errors | panic("error message") — a hard error (GALA-E0035) | Return Try[T] or Either[E, T] |
go_builtins.Panic to propagate an error | val x, err = f(); if err != nil { go_builtins.Panic(err) } (or the same inside a Try block) | Use the (T, error) call as a value: f(args) already is a Try[T] (the error is the Failure); compose with .Map/.FlatMap/bind and return the Try — do not .Get() it inside a function that returns Try (rule 11e) |
A Go (T, error) call's value used as T | val data = os.ReadFile(p) then count(data) / string(data) / data.Size() — the val is a Try[[]byte] (GALA-E0049) | Compose the Try (os.ReadFile(p).Map(...), match, .GetOrElse(...)), or val data, err = os.ReadFile(p) when the raw results go back to Go; .Get() only at a genuine edge |
.Get() inside an enclosing Try(() => {...}) | Try[T](() => { val x = Try(call()).Get(); return f(x) }) — the inner .Get() re-raises a Failure as a panic the outer Try re-catches | Compose with the monadic API: Try(call()).Map((x) => f(x)) (or .FlatMap / bind). Nesting .Get() inside an outer Try defeats Try's purpose — it round-trips a value through a panic |
| Ignored error | result, _ := fallibleOp() | Handle with Try or check error |
| Sentinel return value | Returning "", 0, -1, or nil to signal "not found" / failure | Return Option[T] or Try[T] instead |
| Go-style if-err-nil | val x, err = f(); if err == nil { use(x) } | Try(f) (or Try(f(args))) then .Map, .GetOrElse, or match |
| Sequential if-err-nil fallback | Multiple val x, err = f(); if err == nil { return x } blocks trying alternatives | Try(f1).OrElse(Try(f2)) chain |
| FlatMap vs OrElse confusion | Using FlatMap when fallback calls are independent | OrElse for independent fallbacks; FlatMap only when second call depends on first result |
Check: Search for patterns like val x, err = ...; if err == nil or if err != nil. Multiple such blocks in sequence (trying alternatives and returning the first success) should use Try + OrElse. Single error checks should use Try + Map/GetOrElse/match.
Bad pattern — Go-style sequential error fallback:
// BAD: imperative if-err-nil chain with sentinel return
func findBinary() string {
val p, err = exec.LookPath("gala")
if err == nil {
return p
}
val p2, err2 = exec.LookPath("gala.exe")
if err2 == nil {
return p2
}
return ""
}
Good pattern — Try + OrElse with Option return:
// GOOD: functional fallback chain, no sentinel value
func findBinary() Option[string] =
Try(exec.LookPath("gala"))
.OrElse(Try(exec.LookPath("gala.exe")))
.ToOption()
Best pattern — function reference when zero-arg:
// BEST: pass zero-arg function references directly (no lambda wrapper)
val dir = Try(os.TempDir) // same as Try(() => os.TempDir())
val answer = Try(getAnswer) // works with GALA functions too
When to use FlatMap vs OrElse:
// OrElse: independent fallbacks (second doesn't need first's result)
Try(lookupInCache(key)).OrElse(Try(lookupInDB(key)))
// FlatMap: dependent chain (second uses first's result)
Try(findConfig).FlatMap((path) => Try(readFile(path)))
go_builtins.Panic(err) to propagate an error is the same anti-pattern as bare
panic for errors. A (T, error) call whose error you turn into a panic
should be a Try — Try wraps the call and turns the error into a Failure,
which the caller (or an enclosing Try) composes with. Reserve
go_builtins.Panic for a genuinely intended panic: an unrecoverable invariant
(a broken RNG), a programmer error (out-of-bounds, Option.Get on None), or a
recursive parser that panics out to the caller's surrounding Try.
Bad pattern — mechanical if-err-nil that panics the error:
// BAD: os.OpenFile's error is turned into a panic by hand
func openConfig(p string) *os.File {
val f, err = os.OpenFile(p, os.O_RDONLY, 0)
if err != nil {
go_builtins.Panic(err)
}
return f
}
// BAD: same shape inside a Try block
func Abs(p string) Try[string] = Try[string](() => {
val resolved, err = filepath.Abs(p)
if err != nil { go_builtins.Panic(err) }
return resolved
})
Good pattern — Try turns the Go error into a Failure:
// GOOD: return a Try; the caller decides how to handle the failure
func openConfig(p string) Try[*os.File] = Try(os.OpenFile(p, os.O_RDONLY, 0))
// GOOD: the whole manual Try-block + if-err-nil collapses
func Abs(p string) Try[string] = Try(filepath.Abs(p))
// GOOD: a function that returns Try composes and returns it — never unwraps.
// `.Get()` re-raises a Failure as a panic, so reserve it for a genuine edge
// (a test, `io.UnsafeRun`, or truly terminal code), NEVER inside a function
// that returns Try:
func DecodeHex(s string) Try[Array[byte]] =
Try(hex.DecodeString(s)).Map((b) => ArrayFromSlice(b))
A Go call's value is already a Try (or a Tuple). Choose by the Go
function's return shape — and either way compose and return the Try, don't
.Get() it (see the unsafe-.Get() rule below):
(T, error) (os.ReadFile, os.Open,
os.MkdirTemp, io.Copy, strconv.Atoi, hex.DecodeString, …) → the call
used as a value IS a Try[T]; compose it with .Map/.FlatMap/bind or
match on it directly. Try(call) is the same Try[T] (it additionally
catches a panic inside the call) — flag it only as redundant noise.
(A, B, error) is a Try[Tuple[A, B]]; (A, B) / (A, B, C) without an
error are a Tuple / Tuple3 — destructure with val (a, b, c) = call.error (os.Rename, os.WriteFile, os.MkdirAll,
os.Remove/RemoveAll, os.Mkdir, os.Chdir/Chmod/Symlink/Truncate/Setenv,
(*File).Close, .Sync, scanner.Err, encoder.Encode, filepath.WalkDir, …)
→ the call is a plain error value. FromError(call) or Try(call) turn it
into a Try[Void] that fails on a non-nil error.val x = goCall() followed by using x as the plain T — that is
GALA-E0049. Fix with .Get() only at a genuine edge; otherwise compose the
Try, or bind Go-style val x, err = goCall() when the raw results go back to
Go code.// GOOD: value + error → the call is a Try; compose with Map (NOT .Get()):
func ReadText(p string) Try[string] = os.ReadFile(p).Map((b) => decode(b))
// GOOD: error-only → FromError (or Try) returns Try[Void]; return/compose it:
func Rename(src string, dst string) Try[Void] = FromError(os.Rename(src, dst))
func WriteFileString(p string, s string, mode int) Try[Void] =
FromError(os.WriteFile(p, ToBytes(s), os.FileMode(mode)))
// BAD (unsafe unwrap — re-panics; caught only by an enclosing Try):
val data = os.ReadFile(p).Get()
FromError(os.Rename(a, b)).Get()
.Get() on a Try/FromError result is an unsafe unwrap (panics on
Failure) — use it ONLY at a genuine edge (a test, io.UnsafeRun, or truly
terminal code), NEVER inside a function that returns Try (compose with
.Map/.FlatMap/bind and return the Try). Consistent with the
unsafe-.Get() rule (11e) below.
Verify by exercising an error path — assert IsFailure on a deliberately
bad call (os.Rename of a missing source, os.WriteFile into a missing dir).
.Get() inside an enclosing Try(() => {...}) defeats Try. Calling
.Get() on a Try re-raises a Failure as a panic; when that .Get() sits
inside another Try(() => {...}) block, the outer Try merely re-catches the
panic it just raised — a value laundered through a panic round-trip that ignores
the monadic API entirely. Compose instead:
Try(call()).Map((x) => f(x)) (or .Map(f) for a
plain function).Try(call()) directly (drop the wrapper).FromError(call()).Map((_) => true).bind notation or a
.FlatMap(...).Map(...) chain — never .Get() inside the outer Try.// BAD: inner .Get() re-raises as a panic that the outer Try re-catches
func Stat(path string) Try[FileInfo] = Try[FileInfo](() => {
val fi = Try(os.Stat(path)).Get()
return fromGoFileInfo(fi)
})
// GOOD: compose with Map — the failure flows as a Failure, no panic round-trip
func Stat(path string) Try[FileInfo] =
Try(os.Stat(path)).Map(fromGoFileInfo)
// GOOD: error-only call to a constant result
func RemoveAll(path string) Try[bool] =
FromError(os.RemoveAll(path)).Map((_) => true)
.Get() is safe only at the genuine edges enumerated in rule 11e (a test,
io.UnsafeRun, a guarded unwrap, an Immutable field). It is NOT made safe by
sitting in a non-Try function that "must abort": a library function that
produces a value from a fallible call should return Try[T] and let its caller
decide — compose with .Map/.FlatMap/bind, don't .Get()-and-panic.
Array.Grouped / Array.Sliding over Index Loops (HIGH priority)| Issue | Pattern to Flag | Recommended Fix |
|---|---|---|
| Index-stepping loop by 2 | var i = 0; for i < x.Size() - 1 { use(x[i], x[i+1]); i += 2 } | ArrayOf(x...).Grouped(2).FoldLeft(...) |
| Sliding window loop | Manual index loop with window | ArrayOf(x...).Sliding(n) |
val _ = is a compile error — use a bare statement (HIGH priority)val _ = <expr> — and var _ = <expr>, either one typed (val _ T = <expr>), and _ := <expr> — is a compiler error, GALA-E0060 (gala explain GALA-E0060); code that still has it does not build on current GALA. Flag it anyway when reviewing code pinned to an older release, and whenever the compiler output is not at hand. Whatever the right-hand side is, it should stand on its own as a statement. _ among several names (val n, _ = f(), val (_, b) = pair) is fine.
| Issue | Pattern to Flag | Recommended Fix |
|---|---|---|
| Discard call result | val _ = fs.WriteFileString(p, s, mode) | fs.WriteFileString(p, s, mode) — bare call |
| Discard match result | val _ = x match { ... } | x match { ... } — bare match |
Discard error-returning call | val _ = file.Close() | file.Close() — bare call (function-body), or FromError(file.Close()) if inside a void lambda |
| ForEach when match fits | opt.ForEach((v) => ...) when multiple cases needed | opt match { case Some(v) => ...; case None() => ... } |
Rationale: val _ = ... adds noise without expressing any intent the bare expression doesn't already express. If the result genuinely matters, bind it to a real name and use it (e.g. assert .IsSuccess() in tests). If it doesn't, the call/match should stand alone.
Void-lambda exception. Inside a lambda whose body is func() (no return), the analyzer rejects bare calls returning only an error, Go or GALA — error GALA-E0101: "cannot discard error return from X in void lambda" (hint: "use FromError(X(...)) to handle the error"). Use FromError(call()) from std: it returns Try[Void] and can itself stand as a bare statement (or chain .OnFailure((err) => ...)). Function-body bare calls are unaffected.
If bare-statement form does not transpile elsewhere — that is a transpiler bug, not a license to keep val _ =. Open a repro test against the transpiler and fix the bug. Never work around a transpiler bug: report it with a minimal reproduction.
Check (verdict; $FILES as built in rule 7c):
grep -nE '\b(val|var)[[:space:]]+_([[:space:]]+[[:alpha:]*[][^=]*)?[[:space:]]*=|(^|[>{;(]|\bfor)[[:space:]]*_[[:space:]]*:=' $FILES
Every hit, typed (val _ T =) or not, is a HIGH 11c finding, fixed per the table
and the void-lambda exception above. Tuple patterns (val (_, b) = t) do not match.
When a parameter's expected type is a zero-arg function type (func() T, or
void func()), a bare expression can be passed instead of an explicit () => expr
lambda — the transpiler lifts it into a thunk automatically (f(expr) means
f(() => expr)). Prefer the bare-expression form; it strips ceremony from the
most common Try and Future call sites while preserving the lazy, panic/error-
catching semantics.
| Issue | Pattern to Flag | Recommended Fix |
|---|---|---|
| Zero-arg lambda wrapping a single expression | Try(() => strconv.Atoi(s)) | Try(strconv.Atoi(s)) |
| Zero-arg lambda for a Future body | Future(() => compute()) / Future[int](() => compute()) | Future(compute()) / Future[int](compute()) |
Wrapper around a Go (T, error) call | Try(() => os.ReadFile(p)) / Try(os.ReadFile(p)) | os.ReadFile(p) — the call already is a Try[[]byte]; keep Try(...) only to also catch a panic inside the call |
| Zero-arg lambda in any thunk param | FutureOn(() => compute(), pool) | FutureOn(compute(), pool) |
Preferred forms, most concise first:
Try(() => os.TempDir()) → Try(os.TempDir).() =>: Try(() => f(x)) → Try(f(x)), Future(() => a * b) →
Future(a * b).Check: Grep for (() => — an open paren immediately followed by a zero-arg
lambda (empty parameter list). When the lambda body is a single expression
(the char after => is not {), flag it and remove the () => . Applies to
Try, Future, FutureOn, and any call whose argument is a zero-parameter
lambda.
Do NOT flag (keep the explicit lambda):
Future(() => { setup(); compute() }) cannot be desugared;
only single-expression lambdas convert.xs.Map((x) => x * 2) is a func(T) U, not a
zero-arg thunk. This rule is strictly about () => (empty parameter list).schedule(() => makeHandler())
where makeHandler() returns a func(). Dropping () => would pass the inner
function through directly (the sugar never re-wraps an existing function value),
changing meaning. Keep the lambda when the body's own type is a zero-arg function.Good pattern:
val parsed = Try(strconv.Atoi(input)) // was Try(() => strconv.Atoi(input))
val result = Try(riskyDivide(10, 2)) // was Try(() => riskyDivide(10, 2))
val async = Future(loadFromDB(id)) // was Future(() => loadFromDB(id))
val onPool = FutureOn(compute(), pool) // was FutureOn(() => compute(), pool)
Bad pattern — redundant zero-arg lambda wrapper:
val parsed = Try(() => strconv.Atoi(input))
val async = Future(() => loadFromDB(id))
.Get() unwrap (HIGH priority).Get() on a Try/Option/Either panics on the empty/failure case. It
throws away the type system's proof obligation instead of discharging it — the
hallmark of "unsafe code that looks functional." Prefer match / .GetOrElse /
.Map / .FlatMap / bind / sequence patterns; reserve .Get() for a guarded
or genuinely-terminal edge.
FLAG (unsafe):
| Pattern to Flag | Recommended Fix |
|---|---|
Try(...).Get() — wrap-then-unwrap | Compose: .Map/.FlatMap/bind, and return the Try |
.Get() on a Try inside an enclosing Try(() => {...}) | Compose (rule 11 above) — the inner .Get() re-raises a panic the outer Try re-catches |
opt.Get() on an unguarded Option | match { case Some(x) => …; case None() => … }, .GetOrElse(default), or .Map(...) |
coll.Head().Get() / coll.HeadOption().Get() on an unguarded collection | Sequence pattern match { case Cons(h, t) => … }, or .HeadOption().GetOrElse(default) |
coll.Find(pred).Get() / map.Get(k).Get() | match the Option, or .GetOrElse(default) / .Map(...) |
either.GetLeft() / .GetRight() without a preceding IsLeft()/match | match { case Left(l) => …; case Right(r) => … } and bind the value |
try.GetError() on a value not known to be Failure | Guard with IsFailure() or match first |
DO NOT FLAG (safe — leave these):
Immutable[T].Get() — unwrapping a val-field's Immutable wrapper; always
succeeds (it's how val fields are read, not a fallible unwrap)..Get() guarded by a preceding check in the same scope:
if opt.IsDefined() { opt.Get() }, for coll.NonEmpty() { coll.Head().Get() },
if e.IsLeft() { e.GetLeft() }.io.UnsafeRun() and other explicitly-named terminal/edge unwrap points.scratchDir helper that must abort the test on setup failure).// BAD: unguarded Option unwrap — panics on None
val first = xs.Find((x) => x > 10).Get()
// GOOD: match (or .GetOrElse / .Map)
val first = xs.Find((x) => x > 10) match {
case Some(x) => x
case None() => 0
}
// BAD: wrap-then-unwrap
func Head(xs Array[int]) int = Try(xs[0]).Get()
// GOOD: sequence pattern, no panic
func headOpt(xs Array[int]) Option[int] = xs match {
case Cons(h, _) => Some(h)
case Nil() => None()
}
// SAFE (do not flag): guarded, and an Immutable val-field read
if opt.IsDefined() { use(opt.Get()) } // guarded
val name = self.name.Get() // Immutable[string] field unwrap
The three .Get()-related rules are mutually consistent — none recommends a bare
.Get() as the fix: the Try-vs-FromError rule returns/composes the Try, the
.Get()-inside-Try rule composes with .Map/.FlatMap/bind, and this rule
prefers match/.GetOrElse/composition, reserving .Get() for guarded or
terminal edges.
| Issue | Pattern to Flag | Recommended Fix |
|---|---|---|
| Non-PascalCase type | type myType struct | type MyType struct |
| Non-PascalCase export | func myPublicFunc() | func MyPublicFunc() |
| Verbose lambda params | (element int) => in simple collection ops | (x) => -- prefer short names with implicit types |
| Issue | Pattern to Flag | Recommended Fix |
|---|---|---|
| Missing blank line after imports | import (...)\nfunc | Add blank line after import block |
| Unused import | Import not referenced | Remove unused import |
| Area | Pattern to Flag | Recommended Fix |
|---|---|---|
| Byte vs character size | .Size() used as the bound of a byte loop or byte offset on a string (it counts characters, so multibyte input is truncated) | .ByteSize() when you mean bytes; .Size() when you mean characters |
| Safe indexing | arr.Get(i) after a manual bounds check | arr.GetOption(i) |
Nested FlatMap pyramids | FlatMap nested more than once, or a later step reusing an earlier value | a bind / also block |
| Trivial lambdas | nums.Map((x) => x * 2), people.Map((p) => p.Name) | underscore shorthand: nums.Map(_ * 2), people.Map(_.Name) |
| Verbose tuples | Tuple[int, string](V1 = 1, V2 = "a") | (1, "a"); destructure with val (x, y) = t or case (a, b) => |
| Go conversions | []byte(s), string(bytes) | ToBytes(s), ToString(bytes), ToRunes(s) from go_interop |
| Callback signatures | any in a public callback parameter (forces callers to annotate lambdas) | a named function type with concrete params: type Handler func(Request) Response |
| Struct declaration form | block type Cfg struct { ... } for a GALA-native type | shorthand struct Cfg(Name string, Tries int = 3); keep the block form for Go-shaped types |
| New field on a published struct | added without a default | give it a default so existing call sites stay correct |
| Undocumented export | an exported declaration with no // comment directly above it, a comment not starting with the name, or a blank line between comment and declaration | // Name does ... directly above; parameters as name: description lines |
| Go-style tests | testing.T / testify in _test.gala files | martianoff/gala/test: func TestXxx(t T) T with Eq, IsTrue, ...; table-driven with RunCases |
opaque type (MEDIUM priority)A typed ID or unit (UserID, Millis, Cents) is an opaque type UserID int64:
a distinct type with the underlying type's operators, a generated Hash /
Compare (so it is a HashMap key and sorts), and the bare value on the wire.
Two other spellings of the same intent each lose something. Both rules below are
about scalars: bool, string, the integer and floating-point kinds, rune,
byte, an alias of one of those, or a Go named scalar such as time.Duration.
Rule prefer-opaque. Flag a shorthand struct when ALL of these hold:
= value);Millis(Value = n),
m.Value, case Millis(v)), never as a name with meaning of its own.Never flag a struct whose field is private (lowercase): struct Email(v string)
plus a ParseEmail constructor is the encapsulation tool. Only its own package can
build one, which is exactly what an opaque type gives up (Email("junk") compiles
in every package). Also leave it alone when the type is decoded from a wire format
already in use: the struct encodes as {"Value":1500}, the opaque type as 1500,
so the fix changes the wire shape and needs a migration, not a lint fix. Say so in
the report instead of suggesting the rewrite.
// FLAG — one exported scalar field, no default: boxes the value, loses `+` and `<`,
// needs hand-written Hash/Compare to be a HashMap key, encodes as an object
struct Millis(Value int64)
func (m Millis) Plus(other Millis) Millis = Millis(m.Value + other.Value)
// FIX
opaque type Millis int64
func (m Millis) Plus(other Millis) Millis = m + other
// NOT FLAGGED — private field: only this package can build an Email
struct Email(v string)
func ParseEmail(s string) Try[Email] = ...
// NOT FLAGGED — a default, a second field, or a non-scalar field
struct Retry(Tries int = 3)
struct Money(Amount int64, Currency string)
struct Tags(Values Array[string])
Check: grep -nE '^struct [A-Z][A-Za-z0-9]*\([A-Z][A-Za-z0-9]* [A-Za-z0-9_.]+\)' -r --include='*.gala' .
lists the candidates (one exported field, no default); keep those whose field type
is a scalar, then read how the field name is used.
Rule alias-as-identity. Flag type X Y where Y is a scalar and X appears
in two or more function or method signatures that also mention Y (as a
parameter or result). That is an alias standing in for an identity: an alias is
its target, so an int64 passes wherever a UserID is expected and the two
parameters can be swapped silently. Suggest opaque type X Y, with explicit
conversions (UserID(n), int64(id)) at the boundaries.
type UserID int64
// FLAG — UserID and int64 side by side in two signatures: Charge(42, userID)
// compiles, with the arguments the wrong way round
func Charge(user UserID, cents int64) Try[Receipt] = ...
func Refund(user UserID, cents int64) Try[Receipt] = ...
// FIX
opaque type UserID int64
Check: grep -nE '^type [A-Z][A-Za-z0-9]* (bool|string|rune|byte|u?int(8|16|32|64)?|float(32|64)|[a-z_]+\.[A-Z][A-Za-z0-9]*)$' -r --include='*.gala' .
lists the scalar aliases (add any alias of an alias); for each, count the
func signatures that mention both the alias and its target.
Do not flag:
type Handler func(Request) Response, type Row Array[string]): it names a shape, which is what an alias is for;Ptr[T] and OptionPtr[T] (MEDIUM priority)&x is a Ptr[T], a pointer that is never nil; OptionPtr[T] is a pointer that
may be absent; a plain *T is for Go interop.
Rule option-ptr-field. Flag a struct or sealed-case field of type
Option[Ptr[T]]. Suggest OptionPtr[T]: the same meaning in one pointer, where
Option adds a tag (a 16-byte slot instead of 8), and a field left out of a brace
literal is already empty.
Rule nullable-internal-pointer. Flag a *T parameter, result or field of a
non-exported GALA function or type whose values are only ever &x addresses
(no Go call produces them, no nil is passed or stored). Suggest Ptr[T]. A
*T that does take nil to mean "absent" is an OptionPtr[T].
// FLAG — Option adds a tag to every node; OptionPtr is one pointer
struct Node(Value int, Next Option[Ptr[Node]])
// FIX
struct Node(Value int, Next OptionPtr[Node])
Do not flag a *T at the Go boundary (an exported function Go calls, a field a
Go library fills, a Go callback's parameter); there RequirePtr(p) or
OptionPtrOf(p) converts it once, where it enters GALA code.
Rule option-ptr-to-option-match (LOW). Flag p.ToOption() match { ... }
on an OptionPtr. Match it directly — p match { case Some(x) => ...; case None() => ... }
— since its MatchView() gives it the sealed view Option[Ptr[T]]; the match is
the same and exhaustiveness-checked.
Check: grep -nE 'Option\[(std\.)?Ptr\[' -r --include='*.gala' . and
grep -nE '\.ToOption\(\) match' -r --include='*.gala' . (keep only hits on an
OptionPtr).
bazel-* (build outputs)node_modulesvendor// Code generated comment)GALA-Exxxx hard error (rules 0, 0b, 0c, and rows marked as hard errors elsewhere). Must be fixed; the file does not compile.Generate a report in this format:
# GALA Lint Report
**Files scanned**: X
**Issues found**: Y
## Summary
| Severity | Count |
|----------|-------|
| ERROR | W |
| HIGH | X |
| MEDIUM | Y |
| LOW | Z |
## Issues by File
### `path/to/file.gala`
| Line | Severity | Rule | Issue | Suggestion |
|------|----------|------|-------|------------|
| 15 | HIGH | Immutability | `var x = 10` never reassigned | Use `val x = 10` |
| 42 | MEDIUM | Pattern Matching | If-else chain on Option | Use `match` expression |
### `path/to/another.gala`
...
## Files with No Issues
- `path/to/clean.gala`
- `path/to/good.gala`
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
npx claudepluginhub martianoff/gala --plugin gala2 skills in this plugin
Other plugins' skills for the same job