Last active
March 28, 2026 09:06
-
-
Save ZoomTen/0bc13a823da75b1694f05998376ff0cf to your computer and use it in GitHub Desktop.
I can't read Haskell, so I got Claude to spell out pokemid's optimization algorithm for me.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package internal | |
| import ( | |
| "fmt" | |
| "slices" | |
| ) | |
| type LoopForm struct { | |
| Begin []Instruction | |
| Loop []Instruction // nil ⇒ no loop | |
| } | |
| type InstructionKind int | |
| const ( | |
| KindNote InstructionKind = iota | |
| KindDrumNote | |
| KindRest | |
| KindNoteType | |
| KindDrumSpeed | |
| KindOctave | |
| KindVibrato | |
| KindVolume | |
| KindStereoPanning | |
| KindTempo | |
| KindTogglePerfectPitch | |
| KindExecuteMusic | |
| KindDutyCycle | |
| KindDutyCyclePattern | |
| ) | |
| type Key int | |
| const ( | |
| C_ Key = iota | |
| Cs | |
| D_ | |
| Ds | |
| E_ | |
| F_ | |
| Fs | |
| G_ | |
| Gs | |
| A_ | |
| As | |
| B_ | |
| ) | |
| type PitchSlide *PitchSlideData | |
| type PitchSlideData struct { | |
| X, Y int | |
| K Key | |
| } | |
| type Drum int | |
| const ( | |
| Snare1 Drum = iota | |
| Snare2 | |
| Snare3 | |
| Snare4 | |
| Snare5 | |
| Triangle1 | |
| Triangle2 | |
| Snare6 | |
| Snare7 | |
| Snare8 | |
| Snare9 | |
| Cymbal1 | |
| Cymbal2 | |
| Cymbal3 | |
| MutedSnare1 | |
| Triangle3 | |
| MutedSnare2 | |
| MutedSnare3 | |
| MutedSnare4 | |
| ) | |
| type Instruction struct { | |
| Kind InstructionKind | |
| // Note fields | |
| Key Key | |
| Ticks int | |
| Slide PitchSlide | |
| // DrumNote | |
| Drum Drum | |
| // NoteType / Vibrato / DutyCyclePattern share A/B/C/D | |
| A, B, C, D int | |
| } | |
| type ControlKind int | |
| const ( | |
| KindLabel ControlKind = iota | |
| KindLocalLabel | |
| KindSoundLoop | |
| KindSoundCall | |
| KindSoundRet | |
| ) | |
| type Control struct { | |
| Kind ControlKind | |
| Label string | |
| Exported bool // for KindLabel | |
| Offset int // for KindSoundLoop | |
| } | |
| type AsmLine struct { | |
| IsControl bool | |
| Ctrl Control | |
| Instr Instruction | |
| } | |
| // --------------------------------------------------------------------------- | |
| // AsmLine helpers | |
| // --------------------------------------------------------------------------- | |
| func (a AsmLine) Equal(b AsmLine) bool { | |
| if a.IsControl != b.IsControl { | |
| return false | |
| } | |
| if a.IsControl { | |
| return a.Ctrl == b.Ctrl | |
| } | |
| ia, ib := a.Instr, b.Instr | |
| slideEq := func(x, y PitchSlide) bool { | |
| if x == nil && y == nil { | |
| return true | |
| } | |
| if x == nil || y == nil { | |
| return false | |
| } | |
| return *x == *y | |
| } | |
| return ia.Kind == ib.Kind && | |
| ia.Key == ib.Key && ia.Ticks == ib.Ticks && ia.Drum == ib.Drum && | |
| ia.A == ib.A && ia.B == ib.B && ia.C == ib.C && ia.D == ib.D && | |
| slideEq(ia.Slide, ib.Slide) | |
| } | |
| func (a AsmLine) IsCall() bool { | |
| return a.IsControl && a.Ctrl.Kind == KindSoundCall | |
| } | |
| func (a AsmLine) Size() int { | |
| if a.IsControl { | |
| switch a.Ctrl.Kind { | |
| case KindLabel, KindLocalLabel: | |
| return 0 | |
| case KindSoundLoop: | |
| return 4 | |
| case KindSoundCall: | |
| return 3 | |
| case KindSoundRet: | |
| return 1 | |
| } | |
| return 0 | |
| } | |
| switch a.Instr.Kind { | |
| case KindNote: | |
| if a.Instr.Slide != nil { | |
| return 4 // 1 + 3 for pitch_slide prefix | |
| } | |
| return 1 | |
| case KindDrumNote, KindNoteType, KindVolume, KindStereoPanning, | |
| KindDutyCycle, KindDutyCyclePattern: | |
| return 2 | |
| case KindVibrato, KindTempo: | |
| return 3 | |
| default: // Rest, DrumSpeed, Octave, TogglePerfectPitch, ExecuteMusic | |
| return 1 | |
| } | |
| } | |
| // --------------------------------------------------------------------------- | |
| // Slice helpers | |
| // --------------------------------------------------------------------------- | |
| func totalSize(lines []AsmLine) int { | |
| n := 0 | |
| for _, l := range lines { | |
| n += l.Size() | |
| } | |
| return n | |
| } | |
| // dedupe returns unique elements preserving first-occurrence order. | |
| func dedupe(lines []AsmLine) []AsmLine { | |
| seen := make([]AsmLine, 0, len(lines)) | |
| for _, v := range lines { | |
| found := slices.ContainsFunc(seen, v.Equal) | |
| if !found { | |
| seen = append(seen, v) | |
| } | |
| } | |
| return seen | |
| } | |
| // splitOn splits asm on non-overlapping occurrences of sep, left to right. | |
| // Always returns at least one element (the whole slice if sep is absent). | |
| func splitOn(sep, asm []AsmLine) [][]AsmLine { | |
| var out [][]AsmLine | |
| for { | |
| idx := -1 | |
| search: | |
| for i := 0; i <= len(asm)-len(sep); i++ { | |
| for j := range sep { | |
| if !asm[i+j].Equal(sep[j]) { | |
| continue search | |
| } | |
| } | |
| idx = i | |
| break | |
| } | |
| if idx < 0 { | |
| return append(out, asm) | |
| } | |
| chunk := make([]AsmLine, idx) | |
| copy(chunk, asm[:idx]) | |
| out = append(out, chunk) | |
| asm = asm[idx+len(sep):] | |
| } | |
| } | |
| // --------------------------------------------------------------------------- | |
| // possibleSubs returns every subsequence of asm that appears more than once | |
| // and is long enough to be worth extracting as a subroutine. | |
| // --------------------------------------------------------------------------- | |
| func possibleSubs(asm []AsmLine) [][]AsmLine { | |
| soundCallSize := AsmLine{IsControl: true, Ctrl: Control{Kind: KindSoundCall}}.Size() | |
| // grow extends sub one instruction at a time. | |
| // chunks is the result of splitOn(sub, asm) — the text between occurrences. | |
| var grow func(chunks [][]AsmLine, sub []AsmLine) [][]AsmLine | |
| grow = func(chunks [][]AsmLine, sub []AsmLine) [][]AsmLine { | |
| switch len(chunks) { | |
| case 0: | |
| panic("possibleSubs: no code") | |
| case 1: | |
| panic("possibleSubs: sub not found in asm") | |
| case 2: | |
| return nil // sub appears exactly once; no savings possible | |
| } | |
| isLong := totalSize(sub) > soundCallSize | |
| // tails[i] is the text immediately after the i-th occurrence of sub. | |
| tails := chunks[1:] | |
| var result [][]AsmLine | |
| if isLong { | |
| cp := make([]AsmLine, len(sub)) | |
| copy(cp, sub) | |
| result = append(result, cp) | |
| } | |
| // If every tail starts with the same non-call instruction, absorb it | |
| // into sub without branching. | |
| if next, ok := consistentHead(tails); ok && !next.IsCall() { | |
| newChunks := make([][]AsmLine, len(chunks)) | |
| newChunks[0] = chunks[0] | |
| for i, t := range tails { | |
| newChunks[i+1] = t[1:] | |
| } | |
| return append(result, grow(newChunks, append(sub, next))...) | |
| } | |
| // Otherwise, branch on each unique non-call head found across the tails. | |
| for _, next := range uniqueHeads(tails) { | |
| if next.IsCall() { | |
| continue | |
| } | |
| extended := append(sub[:len(sub):len(sub)], next) | |
| result = append(result, grow(splitOn(extended, asm), extended)...) | |
| } | |
| return result | |
| } | |
| // Seed with every unique non-call instruction in asm. | |
| var result [][]AsmLine | |
| for _, inst := range dedupe(asm) { | |
| if inst.IsCall() { | |
| continue | |
| } | |
| result = append(result, grow(splitOn([]AsmLine{inst}, asm), []AsmLine{inst})...) | |
| } | |
| return result | |
| } | |
| // consistentHead returns the single head shared by all non-empty chunks, or | |
| // (zero, false) if any chunk is empty or the heads differ. | |
| func consistentHead(chunks [][]AsmLine) (AsmLine, bool) { | |
| if len(chunks) == 0 || len(chunks[0]) == 0 { | |
| return AsmLine{}, false | |
| } | |
| first := chunks[0][0] | |
| for _, ch := range chunks[1:] { | |
| if len(ch) == 0 || !ch[0].Equal(first) { | |
| return AsmLine{}, false | |
| } | |
| } | |
| return first, true | |
| } | |
| // uniqueHeads returns the deduplicated heads of non-empty chunks. | |
| func uniqueHeads(chunks [][]AsmLine) []AsmLine { | |
| var heads []AsmLine | |
| for _, ch := range chunks { | |
| if len(ch) > 0 { | |
| heads = append(heads, ch[0]) | |
| } | |
| } | |
| return dedupe(heads) | |
| } | |
| // --------------------------------------------------------------------------- | |
| // replaceSub replaces every occurrence of sub in asm with a call to name. | |
| // --------------------------------------------------------------------------- | |
| func replaceSub(sub []AsmLine, name string, asm []AsmLine) []AsmLine { | |
| call := AsmLine{IsControl: true, Ctrl: Control{Kind: KindSoundCall, Label: name}} | |
| chunks := splitOn(sub, asm) | |
| var out []AsmLine | |
| for i, ch := range chunks { | |
| if i > 0 { | |
| out = append(out, call) | |
| } | |
| out = append(out, ch...) | |
| } | |
| return out | |
| } | |
| func label(exported bool, l string) AsmLine { | |
| return AsmLine{IsControl: true, Ctrl: Control{Kind: KindLabel, Label: l, Exported: exported}} | |
| } | |
| func soundLoop(l string) AsmLine { | |
| return AsmLine{IsControl: true, Ctrl: Control{Kind: KindSoundLoop, Label: l}} | |
| } | |
| func wrapInstrs(instrs []Instruction) []AsmLine { | |
| out := make([]AsmLine, len(instrs)) | |
| for i, ins := range instrs { | |
| out[i] = AsmLine{Instr: ins} | |
| } | |
| return out | |
| } | |
| // extract iteratively pulls out the best subroutine until none save bytes. | |
| func extract(code []AsmLine, subPrefix string, soundRet AsmLine) []AsmLine { | |
| var subs []AsmLine | |
| for n := 0; ; n++ { | |
| subName := fmt.Sprintf("%s%d", subPrefix, n) | |
| bestSaved := 0 | |
| var bestNewMain, bestSubCode []AsmLine | |
| for _, sub := range possibleSubs(code) { | |
| newMain := replaceSub(sub, subName, code) | |
| subCode := append([]AsmLine{label(false, subName)}, append(sub, soundRet)...) | |
| saved := totalSize(code) - totalSize(newMain) - totalSize(subCode) | |
| if saved > bestSaved { | |
| bestSaved = saved | |
| bestNewMain = newMain | |
| bestSubCode = subCode | |
| } | |
| } | |
| if bestSaved == 0 { | |
| return append(subs, code...) | |
| } | |
| subs = append(subs, bestSubCode...) | |
| code = bestNewMain | |
| } | |
| } | |
| // --------------------------------------------------------------------------- | |
| // Optimize wraps begin and loop sections in labels, then repeatedly extracts | |
| // the most byte-saving subroutine until none remain. | |
| // --------------------------------------------------------------------------- | |
| func Optimize(name string, lf LoopForm) []AsmLine { | |
| soundRet := AsmLine{IsControl: true, Ctrl: Control{Kind: KindSoundRet}} | |
| // Begin section. | |
| beginCode := append([]AsmLine{label(true, name)}, wrapInstrs(lf.Begin)...) | |
| if lf.Loop == nil { | |
| beginCode = append(beginCode, soundRet) | |
| } | |
| optBegin := extract(beginCode, name+"_sub_", soundRet) | |
| if lf.Loop == nil { | |
| return optBegin | |
| } | |
| // Loop section. | |
| loopName := name + "_loop" | |
| loopCode := append([]AsmLine{label(false, loopName)}, wrapInstrs(lf.Loop)...) | |
| loopCode = append(loopCode, soundLoop(loopName)) | |
| optLoop := extract(loopCode, name+"_loop_sub_", soundRet) | |
| return append(optBegin, optLoop...) | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package test | |
| import ( | |
| "fmt" | |
| g "g/internal" | |
| "testing" | |
| ) | |
| func note(key g.Key, len int) g.Instruction { | |
| return g.Instruction{ | |
| Kind: g.KindNote, | |
| Key: key, | |
| Ticks: len, | |
| Slide: nil, | |
| } | |
| } | |
| func render(lines []g.AsmLine) { | |
| for _, i := range lines { | |
| if i.IsControl { | |
| switch i.Ctrl.Kind { | |
| case g.KindLabel: | |
| fmt.Printf("%s:", i.Ctrl.Label) | |
| if i.Ctrl.Exported { | |
| fmt.Printf(":\n") | |
| } else { | |
| fmt.Printf("\n") | |
| } | |
| case g.KindLocalLabel: | |
| fmt.Printf(".%s\n", i.Ctrl.Label) | |
| case g.KindSoundLoop: | |
| fmt.Printf("\tsound_loop %d, %s\n", i.Ctrl.Offset, i.Ctrl.Label) | |
| case g.KindSoundCall: | |
| fmt.Printf("\tsound_call %s\n", i.Ctrl.Label) | |
| case g.KindSoundRet: | |
| fmt.Printf("\tsound_ret\n") | |
| } | |
| } else { | |
| switch i.Instr.Kind { | |
| case g.KindNote: | |
| fmt.Printf("\tnote %d, %d\n", i.Instr.Key, i.Instr.Ticks) | |
| } | |
| } | |
| } | |
| } | |
| func TestSomething(t *testing.T) { | |
| a := g.Optimize("Testing", g.LoopForm{ | |
| Begin: []g.Instruction{ | |
| note(g.A_, 12), | |
| note(g.B_, 12), | |
| note(g.C_, 12), | |
| note(g.A_, 12), | |
| note(g.B_, 12), | |
| note(g.C_, 12), | |
| note(g.A_, 12), | |
| note(g.B_, 12), | |
| note(g.C_, 12), | |
| note(g.A_, 12), | |
| note(g.B_, 12), | |
| note(g.C_, 12), | |
| note(g.A_, 12), | |
| note(g.B_, 12), | |
| note(g.C_, 12), | |
| note(g.A_, 12), | |
| note(g.B_, 12), | |
| note(g.C_, 12), | |
| note(g.A_, 12), | |
| note(g.B_, 12), | |
| note(g.C_, 12), | |
| note(g.A_, 12), | |
| note(g.B_, 12), | |
| note(g.C_, 12), | |
| }, | |
| Loop: []g.Instruction{}, | |
| }) | |
| render(a) | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Running tool: /home/user/apps/go/bin/go test -test.fullpath=true -timeout 30s -run ^TestSomething$ g/test | |
| === RUN TestSomething | |
| Testing_sub_0: | |
| note 11, 12 | |
| note 0, 12 | |
| note 9, 12 | |
| note 11, 12 | |
| note 0, 12 | |
| note 9, 12 | |
| note 11, 12 | |
| note 0, 12 | |
| note 9, 12 | |
| note 11, 12 | |
| note 0, 12 | |
| sound_ret | |
| Testing:: | |
| note 9, 12 | |
| sound_call Testing_sub_0 | |
| note 9, 12 | |
| sound_call Testing_sub_0 | |
| Testing_loop: | |
| sound_loop 0, Testing_loop | |
| --- PASS: TestSomething (0.00s) | |
| PASS | |
| ok g/test 0.001s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment