[script] Add some statisticts tracking

Track the statistics of used instructions for the script.
This commit is contained in:
Zorchenhimer 2025-09-06 22:53:33 -04:00
parent b3312a8500
commit 4bd0027c70
Signed by: Zorchenhimer
GPG Key ID: 70A1AB767AAB9C20
3 changed files with 102 additions and 1 deletions

View File

@ -17,6 +17,7 @@ type Arguments struct {
Input string `arg:"positional,required"`
Output string `arg:"positional"`
StartAddr string `arg:"--start" default:"0x6000" help:"base address for the start of the script"`
StatsFile string `arg:"--stats" help:"file to write some statistics to"`
LabelFile string `arg:"--labels" help:"file containing address/label pairs"`
start int
@ -78,6 +79,20 @@ func run(args *Arguments) error {
fmt.Fprintln(outfile, token.String(scr.Labels))
}
if args.StatsFile != "" {
statfile, err := os.Create(args.StatsFile)
if err != nil {
return fmt.Errorf("Unable to create stats file: %w", err)
}
defer statfile.Close()
//err = scr.WriteStats(statfile)
_, err = scr.Stats().WriteTo(statfile)
if err != nil {
return fmt.Errorf("Error writing stats: %w", err)
}
}
return nil
}

View File

@ -1,6 +1,7 @@
package script
import (
"fmt"
)
type Script struct {
@ -10,6 +11,35 @@ type Script struct {
StartAddress int
StackAddress int
//Labels map[int]string
Labels map[int]*Label
}
type InstrStat struct {
Instr *Instruction
Count int
}
func (is InstrStat) String() string {
return fmt.Sprintf("0x%02X %3d %s", is.Instr.Opcode, is.Count, is.Instr.String())
}
func (s *Script) Stats() Stats {
st := make(Stats)
for _, t := range s.Tokens {
if t.Instruction == nil {
continue
}
op := t.Instruction.Opcode
if _, ok := st[op]; !ok {
st[op] = &InstrStat{
Instr: t.Instruction,
Count: 0,
}
}
st[op].Count++
}
return st
}

56
script/stats.go Normal file
View File

@ -0,0 +1,56 @@
package script
import (
"io"
"slices"
"maps"
"fmt"
)
type Stats map[byte]*InstrStat
func (this Stats) Add(that Stats) {
for _, st := range that {
op := st.Instr.Opcode
if _, ok := this[op]; !ok {
this[op] = st
} else {
this[op].Count += that[op].Count
}
}
}
func (s Stats) WriteTo(w io.Writer) (int64, error) {
count := int64(0)
keys := slices.Sorted(maps.Keys(s))
unknownInstr := 0
unknownUses := 0
for _, key := range keys {
n, err := fmt.Fprintln(w, s[key])
count += int64(n)
if err != nil {
return count, err
}
if s[key].Instr.Name == "" {
unknownInstr++
unknownUses += s[key].Count
}
}
n, err := fmt.Fprintln(w, "\nUnknown uses:", unknownUses)
count += int64(n)
if err != nil {
return count, err
}
n, err = fmt.Fprintln(w, "Unknown instructions:", unknownInstr)
count += int64(n)
if err != nil {
return count, err
}
return count, nil
}