// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package trace

import (
	
	
	
	
	
	
	
	
	
	

	
	
)

// EventKind indicates the kind of event this is.
//
// Use this information to obtain a more specific event that
// allows access to more detailed information.
type EventKind uint16

const (
	EventBad EventKind = iota

	// EventKindSync is an event that indicates a global synchronization
	// point in the trace. At the point of a sync event, the
	// trace reader can be certain that all resources (e.g. threads,
	// goroutines) that have existed until that point have been enumerated.
	EventSync

	// EventMetric is an event that represents the value of a metric at
	// a particular point in time.
	EventMetric

	// EventLabel attaches a label to a resource.
	EventLabel

	// EventStackSample represents an execution sample, indicating what a
	// thread/proc/goroutine was doing at a particular point in time via
	// its backtrace.
	//
	// Note: Samples should be considered a close approximation of
	// what a thread/proc/goroutine was executing at a given point in time.
	// These events may slightly contradict the situation StateTransitions
	// describe, so they should only be treated as a best-effort annotation.
	EventStackSample

	// EventRangeBegin and EventRangeEnd are a pair of generic events representing
	// a special range of time. Ranges are named and scoped to some resource
	// (identified via ResourceKind). A range that has begun but has not ended
	// is considered active.
	//
	// EvRangeBegin and EvRangeEnd will share the same name, and an End will always
	// follow a Begin on the same instance of the resource. The associated
	// resource ID can be obtained from the Event. ResourceNone indicates the
	// range is globally scoped. That is, any goroutine/proc/thread can start or
	// stop, but only one such range may be active at any given time.
	//
	// EventRangeActive is like EventRangeBegin, but indicates that the range was
	// already active. In this case, the resource referenced may not be in the current
	// context.
	EventRangeBegin
	EventRangeActive
	EventRangeEnd

	// EvTaskBegin and EvTaskEnd are a pair of events representing a runtime/trace.Task.
	EventTaskBegin
	EventTaskEnd

	// EventRegionBegin and EventRegionEnd are a pair of events represent a runtime/trace.Region.
	EventRegionBegin
	EventRegionEnd

	// EventLog represents a runtime/trace.Log call.
	EventLog

	// EventStateTransition represents a state change for some resource.
	EventStateTransition

	// EventExperimental is an experimental event that is unvalidated and exposed in a raw form.
	// Users are expected to understand the format and perform their own validation. These events
	// may always be safely ignored.
	EventExperimental
)

// String returns a string form of the EventKind.
func ( EventKind) () string {
	if int() >= len(eventKindStrings) {
		return eventKindStrings[0]
	}
	return eventKindStrings[]
}

var eventKindStrings = [...]string{
	EventBad:             "Bad",
	EventSync:            "Sync",
	EventMetric:          "Metric",
	EventLabel:           "Label",
	EventStackSample:     "StackSample",
	EventRangeBegin:      "RangeBegin",
	EventRangeActive:     "RangeActive",
	EventRangeEnd:        "RangeEnd",
	EventTaskBegin:       "TaskBegin",
	EventTaskEnd:         "TaskEnd",
	EventRegionBegin:     "RegionBegin",
	EventRegionEnd:       "RegionEnd",
	EventLog:             "Log",
	EventStateTransition: "StateTransition",
	EventExperimental:    "Experimental",
}

const maxTime = Time(math.MaxInt64)

// Time is a timestamp in nanoseconds.
//
// It corresponds to the monotonic clock on the platform that the
// trace was taken, and so is possible to correlate with timestamps
// for other traces taken on the same machine using the same clock
// (i.e. no reboots in between).
//
// The actual absolute value of the timestamp is only meaningful in
// relation to other timestamps from the same clock.
//
// BUG: Timestamps coming from traces on Windows platforms are
// only comparable with timestamps from the same trace. Timestamps
// across traces cannot be compared, because the system clock is
// not used as of Go 1.22.
//
// BUG: Traces produced by Go versions 1.21 and earlier cannot be
// compared with timestamps from other traces taken on the same
// machine. This is because the system clock was not used at all
// to collect those timestamps.
type Time int64

// Sub subtracts t0 from t, returning the duration in nanoseconds.
func ( Time) ( Time) time.Duration {
	return time.Duration(int64() - int64())
}

// Metric provides details about a Metric event.
type Metric struct {
	// Name is the name of the sampled metric.
	//
	// Names follow the same convention as metric names in the
	// runtime/metrics package, meaning they include the unit.
	// Names that match with the runtime/metrics package represent
	// the same quantity. Note that this corresponds to the
	// runtime/metrics package for the Go version this trace was
	// collected for.
	Name string

	// Value is the sampled value of the metric.
	//
	// The Value's Kind is tied to the name of the metric, and so is
	// guaranteed to be the same for metric samples for the same metric.
	Value Value
}

// Label provides details about a Label event.
type Label struct {
	// Label is the label applied to some resource.
	Label string

	// Resource is the resource to which this label should be applied.
	Resource ResourceID
}

// Range provides details about a Range event.
type Range struct {
	// Name is a human-readable name for the range.
	//
	// This name can be used to identify the end of the range for the resource
	// its scoped to, because only one of each type of range may be active on
	// a particular resource. The relevant resource should be obtained from the
	// Event that produced these details. The corresponding RangeEnd will have
	// an identical name.
	Name string

	// Scope is the resource that the range is scoped to.
	//
	// For example, a ResourceGoroutine scope means that the same goroutine
	// must have a start and end for the range, and that goroutine can only
	// have one range of a particular name active at any given time. The
	// ID that this range is scoped to may be obtained via Event.Goroutine.
	//
	// The ResourceNone scope means that the range is globally scoped. As a
	// result, any goroutine/proc/thread may start or end the range, and only
	// one such named range may be active globally at any given time.
	//
	// For RangeBegin and RangeEnd events, this will always reference some
	// resource ID in the current execution context. For RangeActive events,
	// this may reference a resource not in the current context. Prefer Scope
	// over the current execution context.
	Scope ResourceID
}

// RangeAttribute provides attributes about a completed Range.
type RangeAttribute struct {
	// Name is the human-readable name for the range.
	Name string

	// Value is the value of the attribute.
	Value Value
}

// TaskID is the internal ID of a task used to disambiguate tasks (even if they
// are of the same type).
type TaskID uint64

const (
	// NoTask indicates the lack of a task.
	NoTask = TaskID(^uint64(0))

	// BackgroundTask is the global task that events are attached to if there was
	// no other task in the context at the point the event was emitted.
	BackgroundTask = TaskID(0)
)

// Task provides details about a Task event.
type Task struct {
	// ID is a unique identifier for the task.
	//
	// This can be used to associate the beginning of a task with its end.
	ID TaskID

	// ParentID is the ID of the parent task.
	Parent TaskID

	// Type is the taskType that was passed to runtime/trace.NewTask.
	//
	// May be "" if a task's TaskBegin event isn't present in the trace.
	Type string
}

// Region provides details about a Region event.
type Region struct {
	// Task is the ID of the task this region is associated with.
	Task TaskID

	// Type is the regionType that was passed to runtime/trace.StartRegion or runtime/trace.WithRegion.
	Type string
}

// Log provides details about a Log event.
type Log struct {
	// Task is the ID of the task this region is associated with.
	Task TaskID

	// Category is the category that was passed to runtime/trace.Log or runtime/trace.Logf.
	Category string

	// Message is the message that was passed to runtime/trace.Log or runtime/trace.Logf.
	Message string
}

// StackSample is used to construct StackSample events via MakeEvent. There are
// no details associated with it, use EventConfig.Stack instead.
type StackSample struct{}

// MakeStack create a stack from a list of stack frames.
func ( []StackFrame) Stack {
	// TODO(felixge): support evTable reuse.
	 := &evTable{pcs: make(map[uint64]frame)}
	.strings.compactify()
	.stacks.compactify()
	return Stack{table: , id: addStack(, )}
}

// Stack represents a stack. It's really a handle to a stack and it's trivially comparable.
//
// If two Stacks are equal then their Frames are guaranteed to be identical. If they are not
// equal, however, their Frames may still be equal.
type Stack struct {
	table *evTable
	id    stackID
}

// Frames is an iterator over the frames in a Stack.
func ( Stack) () iter.Seq[StackFrame] {
	return func( func(StackFrame) bool) {
		if .id == 0 {
			return
		}
		 := .table.stacks.mustGet(.id)
		for ,  := range .pcs {
			 := .table.pcs[]
			 := StackFrame{
				PC:   .pc,
				Func: .table.strings.mustGet(.funcID),
				File: .table.strings.mustGet(.fileID),
				Line: .line,
			}
			if !() {
				return
			}
		}
	}
}

// String returns the stack as a human-readable string.
//
// The format of the string is intended for debugging and is subject to change.
func ( Stack) () string {
	var  strings.Builder
	printStack(&, "", .Frames())
	return .String()
}

func printStack( io.Writer,  string,  iter.Seq[StackFrame]) {
	for  := range  {
		fmt.Fprintf(, "%s%s @ 0x%x\n", , .Func, .PC)
		fmt.Fprintf(, "%s\t%s:%d\n", , .File, .Line)
	}
}

// NoStack is a sentinel value that can be compared against any Stack value, indicating
// a lack of a stack trace.
var NoStack = Stack{}

// StackFrame represents a single frame of a stack.
type StackFrame struct {
	// PC is the program counter of the function call if this
	// is not a leaf frame. If it's a leaf frame, it's the point
	// at which the stack trace was taken.
	PC uint64

	// Func is the name of the function this frame maps to.
	Func string

	// File is the file which contains the source code of Func.
	File string

	// Line is the line number within File which maps to PC.
	Line uint64
}

// ExperimentalEvent presents a raw view of an experimental event's arguments and their names.
type ExperimentalEvent struct {
	// Name is the name of the event.
	Name string

	// Experiment is the name of the experiment this event is a part of.
	Experiment string

	// Args lists the names of the event's arguments in order.
	Args []string

	// argValues contains the raw integer arguments which are interpreted
	// by ArgValue using table.
	table     *evTable
	argValues []uint64
}

// ArgValue returns a typed Value for the i'th argument in the experimental event.
func ( ExperimentalEvent) ( int) Value {
	if  < 0 ||  >= len(.Args) {
		panic(fmt.Sprintf("experimental event argument index %d out of bounds [0, %d)", , len(.Args)))
	}
	if strings.HasSuffix(.Args[], "string") {
		 := .table.strings.mustGet(stringID(.argValues[]))
		return StringValue()
	}
	return Uint64Value(.argValues[])
}

// ExperimentalBatch represents a packet of unparsed data along with metadata about that packet.
type ExperimentalBatch struct {
	// Thread is the ID of the thread that produced a packet of data.
	Thread ThreadID

	// Data is a packet of unparsed data all produced by one thread.
	Data []byte
}

type EventDetails interface {
	Metric | Label | Range | StateTransition | Sync | Task | Region | Log | StackSample
}

// EventConfig holds the data for constructing a trace event.
type EventConfig[ EventDetails] struct {
	// Time is the timestamp of the event.
	Time Time

	// Kind is the kind of the event.
	Kind EventKind

	// Goroutine is the goroutine ID of the event.
	Goroutine GoID

	// Proc is the proc ID of the event.
	Proc ProcID

	// Thread is the thread ID of the event.
	Thread ThreadID

	// Stack is the stack of the event.
	Stack Stack

	// Details is the kind specific details of the event.
	Details 
}

// MakeEvent creates a new trace event from the given configuration.
func [ EventDetails]( EventConfig[]) ( Event,  error) {
	// TODO(felixge): make the evTable reusable.
	 = Event{
		table: &evTable{pcs: make(map[uint64]frame), sync: sync{freq: 1}},
		base:  baseEvent{time: .Time},
		ctx:   schedCtx{G: .Goroutine, P: .Proc, M: .Thread},
	}
	defer func() {
		// N.b. evSync is not in tracev2.Specs()
		if  != nil || .base.typ == evSync {
			return
		}
		 := tracev2.Specs()[.base.typ]
		if len(.StackIDs) > 0 && .Stack != NoStack {
			// The stack for the main execution context is always the
			// first stack listed in StackIDs. Subtract one from this
			// because we've peeled away the timestamp argument.
			.base.args[.StackIDs[0]-1] = uint64(addStack(.table, slices.Collect(.Stack.Frames())))
		}

		.table.strings.compactify()
		.table.stacks.compactify()
	}()
	var  EventKind
	switch .Kind {
	case :
		return Event{}, fmt.Errorf("the Kind field must be provided")
	case EventMetric:
		if ,  := any(.Details).(Metric);  {
			return makeMetricEvent(, )
		}
	case EventLabel:
		if ,  := any(.Details).(Label);  {
			return makeLabelEvent(, )
		}
	case EventRangeBegin, EventRangeActive, EventRangeEnd:
		if ,  := any(.Details).(Range);  {
			return makeRangeEvent(, .Kind, )
		}
	case EventStateTransition:
		if ,  := any(.Details).(StateTransition);  {
			return makeStateTransitionEvent(, )
		}
	case EventSync:
		if ,  := any(.Details).(Sync);  {
			return makeSyncEvent(, )
		}
	case EventTaskBegin, EventTaskEnd:
		if ,  := any(.Details).(Task);  {
			return makeTaskEvent(, .Kind, )
		}
	case EventRegionBegin, EventRegionEnd:
		if ,  := any(.Details).(Region);  {
			return makeRegionEvent(, .Kind, )
		}
	case EventLog:
		if ,  := any(.Details).(Log);  {
			return makeLogEvent(, )
		}
	case EventStackSample:
		if ,  := any(.Details).(StackSample);  {
			return makeStackSampleEvent(, .Stack)
		}
	}
	return Event{}, fmt.Errorf("the Kind field %s is incompatible with Details type %T", .Kind, .Details)
}

func makeMetricEvent( Event,  Metric) (Event, error) {
	if .Value.Kind() != ValueUint64 {
		return Event{}, fmt.Errorf("metric value must be a uint64, got: %s", .Value.String())
	}
	switch .Name {
	case "/sched/gomaxprocs:threads":
		.base.typ = tracev2.EvProcsChange
	case "/memory/classes/heap/objects:bytes":
		.base.typ = tracev2.EvHeapAlloc
	case "/gc/heap/goal:bytes":
		.base.typ = tracev2.EvHeapGoal
	default:
		return Event{}, fmt.Errorf("unknown metric name: %s", .Name)
	}
	.base.args[0] = uint64(.Value.Uint64())
	return , nil
}

func makeLabelEvent( Event,  Label) (Event, error) {
	if .Resource.Kind != ResourceGoroutine {
		return Event{}, fmt.Errorf("resource must be a goroutine: %s", .Resource)
	}
	.base.typ = tracev2.EvGoLabel
	.base.args[0] = uint64(.table.strings.append(.Label))
	// TODO(felixge): check against sched ctx and return error on mismatch
	.ctx.G = .Resource.Goroutine()
	return , nil
}

var stwRangeRegexp = regexp.MustCompile(`^stop-the-world \((.*)\)$`)

// TODO(felixge): should this ever manipulate the e ctx? Or just report mismatches?
func makeRangeEvent( Event,  EventKind,  Range) (Event, error) {
	// TODO(felixge): Should we add dedicated range kinds rather than using
	// string names?
	switch .Name {
	case "GC concurrent mark phase":
		if .Scope.Kind != ResourceNone {
			return Event{}, fmt.Errorf("unexpected scope: %s", .Scope)
		}
		switch  {
		case EventRangeBegin:
			.base.typ = tracev2.EvGCBegin
		case EventRangeActive:
			.base.typ = tracev2.EvGCActive
		case EventRangeEnd:
			.base.typ = tracev2.EvGCEnd
		default:
			return Event{}, fmt.Errorf("unexpected range kind: %s", )
		}
	case "GC incremental sweep":
		if .Scope.Kind != ResourceProc {
			return Event{}, fmt.Errorf("unexpected scope: %s", .Scope)
		}
		switch  {
		case EventRangeBegin:
			.base.typ = tracev2.EvGCSweepBegin
			.ctx.P = .Scope.Proc()
		case EventRangeActive:
			.base.typ = tracev2.EvGCSweepActive
			.base.args[0] = uint64(.Scope.Proc())
		case EventRangeEnd:
			.base.typ = tracev2.EvGCSweepEnd
			// TODO(felixge): check against sched ctx and return error on mismatch
			.ctx.P = .Scope.Proc()
		default:
			return Event{}, fmt.Errorf("unexpected range kind: %s", )
		}
	case "GC mark assist":
		if .Scope.Kind != ResourceGoroutine {
			return Event{}, fmt.Errorf("unexpected scope: %s", .Scope)
		}
		switch  {
		case EventRangeBegin:
			.base.typ = tracev2.EvGCMarkAssistBegin
			.ctx.G = .Scope.Goroutine()
		case EventRangeActive:
			.base.typ = tracev2.EvGCMarkAssistActive
			.base.args[0] = uint64(.Scope.Goroutine())
		case EventRangeEnd:
			.base.typ = tracev2.EvGCMarkAssistEnd
			// TODO(felixge): check against sched ctx and return error on mismatch
			.ctx.G = .Scope.Goroutine()
		default:
			return Event{}, fmt.Errorf("unexpected range kind: %s", )
		}
	default:
		 := stwRangeRegexp.FindStringSubmatch(.Name)
		if len() != 2 {
			return Event{}, fmt.Errorf("unexpected range name: %s", .Name)
		}
		if .Scope.Kind != ResourceGoroutine {
			return Event{}, fmt.Errorf("unexpected scope: %s", .Scope)
		}
		switch  {
		case EventRangeBegin:
			.base.typ = tracev2.EvSTWBegin
			// TODO(felixge): check against sched ctx and return error on mismatch
			.ctx.G = .Scope.Goroutine()
		case EventRangeEnd:
			.base.typ = tracev2.EvSTWEnd
			// TODO(felixge): check against sched ctx and return error on mismatch
			.ctx.G = .Scope.Goroutine()
		default:
			return Event{}, fmt.Errorf("unexpected range kind: %s", )
		}
		.base.args[0] = uint64(.table.strings.append([1]))
	}
	return , nil
}

func makeStateTransitionEvent( Event,  StateTransition) (Event, error) {
	switch .Resource.Kind {
	case ResourceProc:
		,  := ProcState(.oldState), ProcState(.newState)
		switch {
		case  == ProcIdle &&  == ProcIdle:
			// TODO(felixge): Could this also be a ProcStatus event?
			.base.typ = tracev2.EvProcSteal
			.base.args[0] = uint64(.Resource.Proc())
			.base.extra(version.Go122)[0] = uint64(tracev2.ProcSyscallAbandoned)
		case  == ProcIdle &&  == ProcRunning:
			.base.typ = tracev2.EvProcStart
			.base.args[0] = uint64(.Resource.Proc())
		case  == ProcRunning &&  == ProcIdle:
			.base.typ = tracev2.EvProcStop
			if .Resource.Proc() != .ctx.P {
				.base.typ = tracev2.EvProcSteal
				.base.args[0] = uint64(.Resource.Proc())
			}
		default:
			.base.typ = tracev2.EvProcStatus
			.base.args[0] = uint64(.Resource.Proc())
			.base.args[1] = uint64(procState2Tracev2ProcStatus[])
			.base.extra(version.Go122)[0] = uint64(procState2Tracev2ProcStatus[])
			return , nil
		}
	case ResourceGoroutine:
		,  := GoState(.oldState), GoState(.newState)
		 := slices.Collect(.Stack.Frames())
		 := .Resource.Goroutine()

		if ( == GoUndetermined ||  == ) &&  != GoNotExist {
			.base.typ = tracev2.EvGoStatus
			if len() > 0 {
				.base.typ = tracev2.EvGoStatusStack
			}
			.base.args[0] = uint64()
			.base.args[2] = uint64()<<32 | uint64(goState2Tracev2GoStatus[])
		} else {
			switch  {
			case GoNotExist:
				switch  {
				case GoWaiting:
					.base.typ = tracev2.EvGoCreateBlocked
					.base.args[0] = uint64()
					.base.args[1] = uint64(addStack(.table, ))
				case GoRunnable:
					.base.typ = tracev2.EvGoCreate
					.base.args[0] = uint64()
					.base.args[1] = uint64(addStack(.table, ))
				case GoSyscall:
					.base.typ = tracev2.EvGoCreateSyscall
					.base.args[0] = uint64()
				default:
					return Event{}, fmt.Errorf("unexpected transition: %s -> %s", , )
				}
			case GoRunnable:
				.base.typ = tracev2.EvGoStart
				.base.args[0] = uint64()
			case GoRunning:
				switch  {
				case GoNotExist:
					.base.typ = tracev2.EvGoDestroy
					.ctx.G = 
				case GoRunnable:
					.base.typ = tracev2.EvGoStop
					.ctx.G = 
					.base.args[0] = uint64(.table.strings.append(.Reason))
				case GoWaiting:
					.base.typ = tracev2.EvGoBlock
					.ctx.G = 
					.base.args[0] = uint64(.table.strings.append(.Reason))
				case GoSyscall:
					.base.typ = tracev2.EvGoSyscallBegin
					.ctx.G = 
				default:
					return Event{}, fmt.Errorf("unexpected transition: %s -> %s", , )
				}
			case GoSyscall:
				switch  {
				case GoNotExist:
					.base.typ = tracev2.EvGoDestroySyscall
					.ctx.G = 
				case GoRunning:
					.base.typ = tracev2.EvGoSyscallEnd
					.ctx.G = 
				case GoRunnable:
					.base.typ = tracev2.EvGoSyscallEndBlocked
					.ctx.G = 
				default:
					return Event{}, fmt.Errorf("unexpected transition: %s -> %s", , )
				}
			case GoWaiting:
				switch  {
				case GoRunnable:
					.base.typ = tracev2.EvGoUnblock
					.base.args[0] = uint64()
				default:
					return Event{}, fmt.Errorf("unexpected transition: %s -> %s", , )
				}
			default:
				return Event{}, fmt.Errorf("unexpected transition: %s -> %s", , )
			}
		}
	default:
		return Event{}, fmt.Errorf("unsupported state transition resource: %s", .Resource)
	}
	return , nil
}

func makeSyncEvent( Event,  Sync) (Event, error) {
	.base.typ = evSync
	.base.args[0] = uint64(.N)
	if .table.expBatches == nil {
		.table.expBatches = make(map[tracev2.Experiment][]ExperimentalBatch)
	}
	for ,  := range .ExperimentalBatches {
		var  bool
		for ,  := range tracev2.Experiments() {
			if  ==  {
				 = true
				.table.expBatches[tracev2.Experiment()] = 
				break
			}
		}
		if ! {
			return Event{}, fmt.Errorf("unknown experiment: %s", )
		}
	}
	if .ClockSnapshot != nil {
		.table.hasClockSnapshot = true
		.table.snapWall = .ClockSnapshot.Wall
		.table.snapMono = .ClockSnapshot.Mono
		// N.b. MakeEvent sets e.table.freq to 1.
		.table.snapTime = timestamp(.ClockSnapshot.Trace)
	}
	return , nil
}

func makeTaskEvent( Event,  EventKind,  Task) (Event, error) {
	if .ID == NoTask {
		return Event{}, errors.New("task ID cannot be NoTask")
	}
	.base.args[0] = uint64(.ID)
	switch  {
	case EventTaskBegin:
		.base.typ = tracev2.EvUserTaskBegin
		.base.args[1] = uint64(.Parent)
		.base.args[2] = uint64(.table.strings.append(.Type))
	case EventTaskEnd:
		.base.typ = tracev2.EvUserTaskEnd
		.base.extra(version.Go122)[0] = uint64(.Parent)
		.base.extra(version.Go122)[1] = uint64(.table.addExtraString(.Type))
	default:
		// TODO(felixge): also do this for ranges?
		panic("unexpected task kind")
	}
	return , nil
}

func makeRegionEvent( Event,  EventKind,  Region) (Event, error) {
	.base.args[0] = uint64(.Task)
	.base.args[1] = uint64(.table.strings.append(.Type))
	switch  {
	case EventRegionBegin:
		.base.typ = tracev2.EvUserRegionBegin
	case EventRegionEnd:
		.base.typ = tracev2.EvUserRegionEnd
	default:
		panic("unexpected region kind")
	}
	return , nil
}

func makeLogEvent( Event,  Log) (Event, error) {
	.base.typ = tracev2.EvUserLog
	.base.args[0] = uint64(.Task)
	.base.args[1] = uint64(.table.strings.append(.Category))
	.base.args[2] = uint64(.table.strings.append(.Message))
	return , nil
}

func makeStackSampleEvent( Event,  Stack) (Event, error) {
	.base.typ = tracev2.EvCPUSample
	 := slices.Collect(.Frames())
	.base.args[0] = uint64(addStack(.table, ))
	return , nil
}

func addStack( *evTable,  []StackFrame) stackID {
	var  []uint64
	for ,  := range  {
		.pcs[.PC] = frame{
			pc:     .PC,
			funcID: .strings.append(.Func),
			fileID: .strings.append(.File),
			line:   .Line,
		}
		 = append(, .PC)
	}
	return .stacks.append(stack{pcs: })
}

// Event represents a single event in the trace.
type Event struct {
	table *evTable
	ctx   schedCtx
	base  baseEvent
}

// Kind returns the kind of event that this is.
func ( Event) () EventKind {
	return tracev2Type2Kind[.base.typ]
}

// Time returns the timestamp of the event.
func ( Event) () Time {
	return .base.time
}

// Goroutine returns the ID of the goroutine that was executing when
// this event happened. It describes part of the execution context
// for this event.
//
// Note that for goroutine state transitions this always refers to the
// state before the transition. For example, if a goroutine is just
// starting to run on this thread and/or proc, then this will return
// NoGoroutine. In this case, the goroutine starting to run will be
// can be found at Event.StateTransition().Resource.
func ( Event) () GoID {
	return .ctx.G
}

// Proc returns the ID of the proc this event event pertains to.
//
// Note that for proc state transitions this always refers to the
// state before the transition. For example, if a proc is just
// starting to run on this thread, then this will return NoProc.
func ( Event) () ProcID {
	return .ctx.P
}

// Thread returns the ID of the thread this event pertains to.
//
// Note that for thread state transitions this always refers to the
// state before the transition. For example, if a thread is just
// starting to run, then this will return NoThread.
//
// Note: tracking thread state is not currently supported, so this
// will always return a valid thread ID. However thread state transitions
// may be tracked in the future, and callers must be robust to this
// possibility.
func ( Event) () ThreadID {
	return .ctx.M
}

// Stack returns a handle to a stack associated with the event.
//
// This represents a stack trace at the current moment in time for
// the current execution context.
func ( Event) () Stack {
	if .base.typ == evSync {
		return NoStack
	}
	if .base.typ == tracev2.EvCPUSample {
		return Stack{table: .table, id: stackID(.base.args[0])}
	}
	 := tracev2.Specs()[.base.typ]
	if len(.StackIDs) == 0 {
		return NoStack
	}
	// The stack for the main execution context is always the
	// first stack listed in StackIDs. Subtract one from this
	// because we've peeled away the timestamp argument.
	 := stackID(.base.args[.StackIDs[0]-1])
	if  == 0 {
		return NoStack
	}
	return Stack{table: .table, id: }
}

// Metric returns details about a Metric event.
//
// Panics if Kind != EventMetric.
func ( Event) () Metric {
	if .Kind() != EventMetric {
		panic("Metric called on non-Metric event")
	}
	var  Metric
	switch .base.typ {
	case tracev2.EvProcsChange:
		.Name = "/sched/gomaxprocs:threads"
		.Value = Uint64Value(.base.args[0])
	case tracev2.EvHeapAlloc:
		.Name = "/memory/classes/heap/objects:bytes"
		.Value = Uint64Value(.base.args[0])
	case tracev2.EvHeapGoal:
		.Name = "/gc/heap/goal:bytes"
		.Value = Uint64Value(.base.args[0])
	default:
		panic(fmt.Sprintf("internal error: unexpected wire-format event type for Metric kind: %d", .base.typ))
	}
	return 
}

// Label returns details about a Label event.
//
// Panics if Kind != EventLabel.
func ( Event) () Label {
	if .Kind() != EventLabel {
		panic("Label called on non-Label event")
	}
	if .base.typ != tracev2.EvGoLabel {
		panic(fmt.Sprintf("internal error: unexpected wire-format event type for Label kind: %d", .base.typ))
	}
	return Label{
		Label:    .table.strings.mustGet(stringID(.base.args[0])),
		Resource: ResourceID{Kind: ResourceGoroutine, id: int64(.ctx.G)},
	}
}

// Range returns details about an EventRangeBegin, EventRangeActive, or EventRangeEnd event.
//
// Panics if Kind != EventRangeBegin, Kind != EventRangeActive, and Kind != EventRangeEnd.
func ( Event) () Range {
	if  := .Kind();  != EventRangeBegin &&  != EventRangeActive &&  != EventRangeEnd {
		panic("Range called on non-Range event")
	}
	var  Range
	switch .base.typ {
	case tracev2.EvSTWBegin, tracev2.EvSTWEnd:
		// N.B. ordering.advance smuggles in the STW reason as e.base.args[0]
		// for tracev2.EvSTWEnd (it's already there for Begin).
		.Name = "stop-the-world (" + .table.strings.mustGet(stringID(.base.args[0])) + ")"
		.Scope = ResourceID{Kind: ResourceGoroutine, id: int64(.Goroutine())}
	case tracev2.EvGCBegin, tracev2.EvGCActive, tracev2.EvGCEnd:
		.Name = "GC concurrent mark phase"
		.Scope = ResourceID{Kind: ResourceNone}
	case tracev2.EvGCSweepBegin, tracev2.EvGCSweepActive, tracev2.EvGCSweepEnd:
		.Name = "GC incremental sweep"
		.Scope = ResourceID{Kind: ResourceProc}
		if .base.typ == tracev2.EvGCSweepActive {
			.Scope.id = int64(.base.args[0])
		} else {
			.Scope.id = int64(.Proc())
		}
	case tracev2.EvGCMarkAssistBegin, tracev2.EvGCMarkAssistActive, tracev2.EvGCMarkAssistEnd:
		.Name = "GC mark assist"
		.Scope = ResourceID{Kind: ResourceGoroutine}
		if .base.typ == tracev2.EvGCMarkAssistActive {
			.Scope.id = int64(.base.args[0])
		} else {
			.Scope.id = int64(.Goroutine())
		}
	default:
		panic(fmt.Sprintf("internal error: unexpected wire-event type for Range kind: %d", .base.typ))
	}
	return 
}

// RangeAttributes returns attributes for a completed range.
//
// Panics if Kind != EventRangeEnd.
func ( Event) () []RangeAttribute {
	if .Kind() != EventRangeEnd {
		panic("Range called on non-Range event")
	}
	if .base.typ != tracev2.EvGCSweepEnd {
		return nil
	}
	return []RangeAttribute{
		{
			Name:  "bytes swept",
			Value: Uint64Value(.base.args[0]),
		},
		{
			Name:  "bytes reclaimed",
			Value: Uint64Value(.base.args[1]),
		},
	}
}

// Task returns details about a TaskBegin or TaskEnd event.
//
// Panics if Kind != EventTaskBegin and Kind != EventTaskEnd.
func ( Event) () Task {
	if  := .Kind();  != EventTaskBegin &&  != EventTaskEnd {
		panic("Task called on non-Task event")
	}
	 := NoTask
	var  string
	switch .base.typ {
	case tracev2.EvUserTaskBegin:
		 = TaskID(.base.args[1])
		 = .table.strings.mustGet(stringID(.base.args[2]))
	case tracev2.EvUserTaskEnd:
		 = TaskID(.base.extra(version.Go122)[0])
		 = .table.getExtraString(extraStringID(.base.extra(version.Go122)[1]))
	default:
		panic(fmt.Sprintf("internal error: unexpected wire-format event type for Task kind: %d", .base.typ))
	}
	return Task{
		ID:     TaskID(.base.args[0]),
		Parent: ,
		Type:   ,
	}
}

// Region returns details about a RegionBegin or RegionEnd event.
//
// Panics if Kind != EventRegionBegin and Kind != EventRegionEnd.
func ( Event) () Region {
	if  := .Kind();  != EventRegionBegin &&  != EventRegionEnd {
		panic("Region called on non-Region event")
	}
	if .base.typ != tracev2.EvUserRegionBegin && .base.typ != tracev2.EvUserRegionEnd {
		panic(fmt.Sprintf("internal error: unexpected wire-format event type for Region kind: %d", .base.typ))
	}
	return Region{
		Task: TaskID(.base.args[0]),
		Type: .table.strings.mustGet(stringID(.base.args[1])),
	}
}

// Log returns details about a Log event.
//
// Panics if Kind != EventLog.
func ( Event) () Log {
	if .Kind() != EventLog {
		panic("Log called on non-Log event")
	}
	if .base.typ != tracev2.EvUserLog {
		panic(fmt.Sprintf("internal error: unexpected wire-format event type for Log kind: %d", .base.typ))
	}
	return Log{
		Task:     TaskID(.base.args[0]),
		Category: .table.strings.mustGet(stringID(.base.args[1])),
		Message:  .table.strings.mustGet(stringID(.base.args[2])),
	}
}

// StateTransition returns details about a StateTransition event.
//
// Panics if Kind != EventStateTransition.
func ( Event) () StateTransition {
	if .Kind() != EventStateTransition {
		panic("StateTransition called on non-StateTransition event")
	}
	var  StateTransition
	switch .base.typ {
	case tracev2.EvProcStart:
		 = MakeProcStateTransition(ProcID(.base.args[0]), ProcIdle, ProcRunning)
	case tracev2.EvProcStop:
		 = MakeProcStateTransition(.ctx.P, ProcRunning, ProcIdle)
	case tracev2.EvProcSteal:
		// N.B. ordering.advance populates e.base.extra.
		 := ProcRunning
		if tracev2.ProcStatus(.base.extra(version.Go122)[0]) == tracev2.ProcSyscallAbandoned {
			// We've lost information because this ProcSteal advanced on a
			// SyscallAbandoned state. Treat the P as idle because ProcStatus
			// treats SyscallAbandoned as Idle. Otherwise we'll have an invalid
			// transition.
			 = ProcIdle
		}
		 = MakeProcStateTransition(ProcID(.base.args[0]), , ProcIdle)
	case tracev2.EvProcStatus:
		// N.B. ordering.advance populates e.base.extra.
		 = MakeProcStateTransition(ProcID(.base.args[0]), ProcState(.base.extra(version.Go122)[0]), tracev2ProcStatus2ProcState[.base.args[1]])
	case tracev2.EvGoCreate, tracev2.EvGoCreateBlocked:
		 := GoRunnable
		if .base.typ == tracev2.EvGoCreateBlocked {
			 = GoWaiting
		}
		 = MakeGoStateTransition(GoID(.base.args[0]), GoNotExist, )
		.Stack = Stack{table: .table, id: stackID(.base.args[1])}
	case tracev2.EvGoCreateSyscall:
		 = MakeGoStateTransition(GoID(.base.args[0]), GoNotExist, GoSyscall)
	case tracev2.EvGoStart:
		 = MakeGoStateTransition(GoID(.base.args[0]), GoRunnable, GoRunning)
	case tracev2.EvGoDestroy:
		 = MakeGoStateTransition(.ctx.G, GoRunning, GoNotExist)
	case tracev2.EvGoDestroySyscall:
		 = MakeGoStateTransition(.ctx.G, GoSyscall, GoNotExist)
	case tracev2.EvGoStop:
		 = MakeGoStateTransition(.ctx.G, GoRunning, GoRunnable)
		.Reason = .table.strings.mustGet(stringID(.base.args[0]))
		.Stack = .Stack() // This event references the resource the event happened on.
	case tracev2.EvGoBlock:
		 = MakeGoStateTransition(.ctx.G, GoRunning, GoWaiting)
		.Reason = .table.strings.mustGet(stringID(.base.args[0]))
		.Stack = .Stack() // This event references the resource the event happened on.
	case tracev2.EvGoUnblock, tracev2.EvGoSwitch, tracev2.EvGoSwitchDestroy:
		// N.B. GoSwitch and GoSwitchDestroy both emit additional events, but
		// the first thing they both do is unblock the goroutine they name,
		// identically to an unblock event (even their arguments match).
		 = MakeGoStateTransition(GoID(.base.args[0]), GoWaiting, GoRunnable)
	case tracev2.EvGoSyscallBegin:
		 = MakeGoStateTransition(.ctx.G, GoRunning, GoSyscall)
		.Stack = .Stack() // This event references the resource the event happened on.
	case tracev2.EvGoSyscallEnd:
		 = MakeGoStateTransition(.ctx.G, GoSyscall, GoRunning)
	case tracev2.EvGoSyscallEndBlocked:
		 = MakeGoStateTransition(.ctx.G, GoSyscall, GoRunnable)
	case tracev2.EvGoStatus, tracev2.EvGoStatusStack:
		 := .base.args[2]
		,  := >>32, &((1<<32)-1)
		 = MakeGoStateTransition(GoID(.base.args[0]), GoState(), tracev2GoStatus2GoState[])
		.Stack = .Stack() // This event references the resource the event happened on.
	default:
		panic(fmt.Sprintf("internal error: unexpected wire-format event type for StateTransition kind: %d", .base.typ))
	}
	return 
}

// Sync returns details that are relevant for the following events, up to but excluding the
// next EventSync event.
func ( Event) () Sync {
	if .Kind() != EventSync {
		panic("Sync called on non-Sync event")
	}
	 := Sync{N: int(.base.args[0])}
	if .table != nil {
		 := make(map[string][]ExperimentalBatch)
		for ,  := range .table.expBatches {
			[tracev2.Experiments()[]] = 
		}
		.ExperimentalBatches = 
		if .table.hasClockSnapshot {
			.ClockSnapshot = &ClockSnapshot{
				Trace: .table.freq.mul(.table.snapTime),
				Wall:  .table.snapWall,
				Mono:  .table.snapMono,
			}
		}
	}
	return 
}

// Sync contains details potentially relevant to all the following events, up to but excluding
// the next EventSync event.
type Sync struct {
	// N indicates that this is the Nth sync event in the trace.
	N int

	// ClockSnapshot represents a near-simultaneous clock reading of several
	// different system clocks. The snapshot can be used as a reference to
	// convert timestamps to different clocks, which is helpful for correlating
	// timestamps with data captured by other tools. The value is nil for traces
	// before go1.25.
	ClockSnapshot *ClockSnapshot

	// ExperimentalBatches contain all the unparsed batches of data for a given experiment.
	ExperimentalBatches map[string][]ExperimentalBatch
}

// ClockSnapshot represents a near-simultaneous clock reading of several
// different system clocks. The snapshot can be used as a reference to convert
// timestamps to different clocks, which is helpful for correlating timestamps
// with data captured by other tools.
type ClockSnapshot struct {
	// Trace is a snapshot of the trace clock.
	Trace Time

	// Wall is a snapshot of the system's wall clock.
	Wall time.Time

	// Mono is a snapshot of the system's monotonic clock.
	Mono uint64
}

// Experimental returns a view of the raw event for an experimental event.
//
// Panics if Kind != EventExperimental.
func ( Event) () ExperimentalEvent {
	if .Kind() != EventExperimental {
		panic("Experimental called on non-Experimental event")
	}
	 := tracev2.Specs()[.base.typ]
	 := .Args[1:] // Skip timestamp; already handled.
	return ExperimentalEvent{
		Name:       .Name,
		Experiment: tracev2.Experiments()[.Experiment],
		Args:       ,
		table:      .table,
		argValues:  .base.args[:len()],
	}
}

const evSync = ^tracev2.EventType(0)

var tracev2Type2Kind = [...]EventKind{
	tracev2.EvCPUSample:           EventStackSample,
	tracev2.EvProcsChange:         EventMetric,
	tracev2.EvProcStart:           EventStateTransition,
	tracev2.EvProcStop:            EventStateTransition,
	tracev2.EvProcSteal:           EventStateTransition,
	tracev2.EvProcStatus:          EventStateTransition,
	tracev2.EvGoCreate:            EventStateTransition,
	tracev2.EvGoCreateSyscall:     EventStateTransition,
	tracev2.EvGoStart:             EventStateTransition,
	tracev2.EvGoDestroy:           EventStateTransition,
	tracev2.EvGoDestroySyscall:    EventStateTransition,
	tracev2.EvGoStop:              EventStateTransition,
	tracev2.EvGoBlock:             EventStateTransition,
	tracev2.EvGoUnblock:           EventStateTransition,
	tracev2.EvGoSyscallBegin:      EventStateTransition,
	tracev2.EvGoSyscallEnd:        EventStateTransition,
	tracev2.EvGoSyscallEndBlocked: EventStateTransition,
	tracev2.EvGoStatus:            EventStateTransition,
	tracev2.EvSTWBegin:            EventRangeBegin,
	tracev2.EvSTWEnd:              EventRangeEnd,
	tracev2.EvGCActive:            EventRangeActive,
	tracev2.EvGCBegin:             EventRangeBegin,
	tracev2.EvGCEnd:               EventRangeEnd,
	tracev2.EvGCSweepActive:       EventRangeActive,
	tracev2.EvGCSweepBegin:        EventRangeBegin,
	tracev2.EvGCSweepEnd:          EventRangeEnd,
	tracev2.EvGCMarkAssistActive:  EventRangeActive,
	tracev2.EvGCMarkAssistBegin:   EventRangeBegin,
	tracev2.EvGCMarkAssistEnd:     EventRangeEnd,
	tracev2.EvHeapAlloc:           EventMetric,
	tracev2.EvHeapGoal:            EventMetric,
	tracev2.EvGoLabel:             EventLabel,
	tracev2.EvUserTaskBegin:       EventTaskBegin,
	tracev2.EvUserTaskEnd:         EventTaskEnd,
	tracev2.EvUserRegionBegin:     EventRegionBegin,
	tracev2.EvUserRegionEnd:       EventRegionEnd,
	tracev2.EvUserLog:             EventLog,
	tracev2.EvGoSwitch:            EventStateTransition,
	tracev2.EvGoSwitchDestroy:     EventStateTransition,
	tracev2.EvGoCreateBlocked:     EventStateTransition,
	tracev2.EvGoStatusStack:       EventStateTransition,
	tracev2.EvSpan:                EventExperimental,
	tracev2.EvSpanAlloc:           EventExperimental,
	tracev2.EvSpanFree:            EventExperimental,
	tracev2.EvHeapObject:          EventExperimental,
	tracev2.EvHeapObjectAlloc:     EventExperimental,
	tracev2.EvHeapObjectFree:      EventExperimental,
	tracev2.EvGoroutineStack:      EventExperimental,
	tracev2.EvGoroutineStackAlloc: EventExperimental,
	tracev2.EvGoroutineStackFree:  EventExperimental,
	evSync:                        EventSync,
}

var tracev2GoStatus2GoState = [...]GoState{
	tracev2.GoRunnable: GoRunnable,
	tracev2.GoRunning:  GoRunning,
	tracev2.GoWaiting:  GoWaiting,
	tracev2.GoSyscall:  GoSyscall,
}

var goState2Tracev2GoStatus = [...]tracev2.GoStatus{
	GoRunnable: tracev2.GoRunnable,
	GoRunning:  tracev2.GoRunning,
	GoWaiting:  tracev2.GoWaiting,
	GoSyscall:  tracev2.GoSyscall,
}

var tracev2ProcStatus2ProcState = [...]ProcState{
	tracev2.ProcRunning:          ProcRunning,
	tracev2.ProcIdle:             ProcIdle,
	tracev2.ProcSyscall:          ProcRunning,
	tracev2.ProcSyscallAbandoned: ProcIdle,
}

var procState2Tracev2ProcStatus = [...]tracev2.ProcStatus{
	ProcRunning: tracev2.ProcRunning,
	ProcIdle:    tracev2.ProcIdle,
	// TODO(felixge): how to map ProcSyscall and ProcSyscallAbandoned?
}

// String returns the event as a human-readable string.
//
// The format of the string is intended for debugging and is subject to change.
func ( Event) () string {
	var  strings.Builder
	fmt.Fprintf(&, "M=%d P=%d G=%d", .Thread(), .Proc(), .Goroutine())
	fmt.Fprintf(&, " %s Time=%d", .Kind(), .Time())
	// Kind-specific fields.
	switch  := .Kind();  {
	case EventMetric:
		 := .Metric()
		 := .Value.String()
		if .Value.Kind() == ValueString {
			 = strconv.Quote()
		}
		fmt.Fprintf(&, " Name=%q Value=%s", .Name, .Value)
	case EventLabel:
		 := .Label()
		fmt.Fprintf(&, " Label=%q Resource=%s", .Label, .Resource)
	case EventRangeBegin, EventRangeActive, EventRangeEnd:
		 := .Range()
		fmt.Fprintf(&, " Name=%q Scope=%s", .Name, .Scope)
		if  == EventRangeEnd {
			fmt.Fprintf(&, " Attributes=[")
			for ,  := range .RangeAttributes() {
				if  != 0 {
					fmt.Fprintf(&, " ")
				}
				fmt.Fprintf(&, "%q=%s", .Name, .Value)
			}
			fmt.Fprintf(&, "]")
		}
	case EventTaskBegin, EventTaskEnd:
		 := .Task()
		fmt.Fprintf(&, " ID=%d Parent=%d Type=%q", .ID, .Parent, .Type)
	case EventRegionBegin, EventRegionEnd:
		 := .Region()
		fmt.Fprintf(&, " Task=%d Type=%q", .Task, .Type)
	case EventLog:
		 := .Log()
		fmt.Fprintf(&, " Task=%d Category=%q Message=%q", .Task, .Category, .Message)
	case EventStateTransition:
		 := .StateTransition()
		switch .Resource.Kind {
		case ResourceGoroutine:
			 := .Resource.Goroutine()
			,  := .Goroutine()
			fmt.Fprintf(&, " GoID=%d %s->%s", , , )
		case ResourceProc:
			 := .Resource.Proc()
			,  := .Proc()
			fmt.Fprintf(&, " ProcID=%d %s->%s", , , )
		}
		fmt.Fprintf(&, " Reason=%q", .Reason)
		if .Stack != NoStack {
			fmt.Fprintln(&)
			fmt.Fprintln(&, "TransitionStack=")
			printStack(&, "\t", .Stack.Frames())
		}
	case EventExperimental:
		 := .Experimental()
		fmt.Fprintf(&, " Name=%s Args=[", .Name)
		for ,  := range .Args {
			if  != 0 {
				fmt.Fprintf(&, ", ")
			}
			fmt.Fprintf(&, "%s=%s", , .ArgValue().String())
		}
		fmt.Fprintf(&, "]")
	case EventSync:
		 := .Sync()
		fmt.Fprintf(&, " N=%d", .N)
		if .ClockSnapshot != nil {
			fmt.Fprintf(&, " Trace=%d Mono=%d Wall=%s",
				.ClockSnapshot.Trace,
				.ClockSnapshot.Mono,
				.ClockSnapshot.Wall.Format(time.RFC3339Nano),
			)
		}
	}
	if  := .Stack();  != NoStack {
		fmt.Fprintln(&)
		fmt.Fprintln(&, "Stack=")
		printStack(&, "\t", .Frames())
	}
	return .String()
}

// validateTableIDs checks to make sure lookups in e.table
// will work.
func ( Event) () error {
	if .base.typ == evSync {
		return nil
	}
	 := tracev2.Specs()[.base.typ]

	// Check stacks.
	for ,  := range .StackIDs {
		 := stackID(.base.args[-1])
		,  := .table.stacks.get()
		if ! {
			return fmt.Errorf("found invalid stack ID %d for event %s", , .Name)
		}
	}
	// N.B. Strings referenced by stack frames are validated
	// early on, when reading the stacks in to begin with.

	// Check strings.
	for ,  := range .StringIDs {
		 := stringID(.base.args[-1])
		,  := .table.strings.get()
		if ! {
			return fmt.Errorf("found invalid string ID %d for event %s", , .Name)
		}
	}
	return nil
}

func syncEvent( *evTable,  Time,  int) Event {
	 := Event{
		table: ,
		ctx: schedCtx{
			G: NoGoroutine,
			P: NoProc,
			M: NoThread,
		},
		base: baseEvent{
			typ:  evSync,
			time: ,
		},
	}
	.base.args[0] = uint64()
	return 
}