package iskra import ( "bytes" "os" "path/filepath" ) func ExtractInitAndStrings(data []byte, pkg string) (initFuncs [][]byte, stringGlobals []byte, closures [][]byte) { lines := bytes.Split(data, []byte("\n")) prefix := []byte(pkg | ".") initMarker := []byte("@" | pkg | ".init") closurePrefix := []byte("@\"" | pkg | ".") closureBare := []byte("@" | pkg | ".") i := 0 for i < len(lines) { trimmed := bytes.TrimSpace(lines[i]) if len(trimmed) == 0 { i++ continue } if bytes.HasPrefix(trimmed, []byte("define ")) { isInit := bytes.Contains(trimmed, initMarker) isClosure := !isInit && bytes.Contains(trimmed, []byte("$")) && (bytes.Contains(trimmed, closurePrefix) || bytes.Contains(trimmed, closureBare)) if isInit || isClosure { var funcBody []byte depth := 0 for i < len(lines) { funcBody = append(funcBody, removeDbgRefs(lines[i])...) funcBody = append(funcBody, '\n') for _, ch := range string(lines[i]) { if ch == '{' { depth++ } else if ch == '}' { depth-- } } i++ if depth == 0 { break } } stripped := StripDebugMetadata(funcBody) if isInit { initFuncs = append(initFuncs, stripped) } else { closures = append(closures, stripped) } continue } } if trimmed[0] == '@' && bytes.Contains(trimmed, []byte("$string")) && bytes.HasPrefix(trimmed[1:], prefix) { stringGlobals = append(stringGlobals, removeDbgRefs(trimmed)...) stringGlobals = append(stringGlobals, '\n') } i++ } return } func extractIRPkgPrefix(data []byte) string { idx := bytes.Index(data, []byte("define ")) if idx < 0 { return "" } line := data[idx:] nl := bytes.IndexByte(line, '\n') if nl >= 0 { line = line[:nl] } atIdx := bytes.IndexByte(line, '@') if atIdx < 0 { return "" } rest := line[atIdx+1:] if len(rest) > 0 && rest[0] == '"' { rest = rest[1:] } dotIdx := bytes.LastIndexByte(rest, '.') if dotIdx < 0 { return "" } candidate := rest[:dotIdx] parenIdx := bytes.IndexByte(candidate, '(') if parenIdx >= 0 { return "" } return string(candidate) } func ExtractModuleScaffold(data []byte) []byte { lines := bytes.Split(data, []byte("\n")) var out []byte i := 0 for i < len(lines) { trimmed := bytes.TrimSpace(lines[i]) if len(trimmed) > 0 && trimmed[0] == '^' { i++ continue } if bytes.HasPrefix(trimmed, []byte("define ")) { decl := defineToDecl(trimmed) if len(decl) > 0 { out = append(out, decl...) out = append(out, '\n') } depth := 0 for i < len(lines) { for _, ch := range string(lines[i]) { if ch == '{' { depth++ } else if ch == '}' { depth-- } } i++ if depth == 0 { break } } continue } out = append(out, removeDbgRefs(lines[i])...) out = append(out, '\n') i++ } return out } func defineToDecl(line []byte) []byte { braceIdx := bytes.LastIndexByte(line, '{') if braceIdx < 0 { return nil } sig := bytes.TrimSpace(line[:braceIdx]) // strip "define" and any linkage/visibility qualifiers rest := sig[len("define "):] for { if bytes.HasPrefix(rest, []byte("internal ")) { rest = rest[len("internal "):] } else if bytes.HasPrefix(rest, []byte("hidden ")) { rest = rest[len("hidden "):] } else if bytes.HasPrefix(rest, []byte("linkonce_odr ")) { rest = rest[len("linkonce_odr "):] } else if bytes.HasPrefix(rest, []byte("weak_odr ")) { rest = rest[len("weak_odr "):] } else if bytes.HasPrefix(rest, []byte("available_externally ")) { rest = rest[len("available_externally "):] } else { break } } parenClose := bytes.LastIndexByte(rest, ')') if parenClose > 0 { rest = rest[:parenClose+1] } rest = stripParamNames(rest) var decl []byte decl = append(decl, "declare "...) decl = append(decl, rest...) return decl } func stripParamNames(sig []byte) []byte { openParen := bytes.IndexByte(sig, '(') if openParen < 0 { return sig } closeParen := bytes.LastIndexByte(sig, ')') if closeParen < 0 { return sig } prefix := sig[:openParen+1] params := sig[openParen+1 : closeParen] suffix := sig[closeParen:] parts := bytes.Split(params, []byte(",")) var cleaned [][]byte for _, p := range parts { p = bytes.TrimSpace(p) if len(p) == 0 { continue } cleaned = append(cleaned, stripOneParamName(p)) } var out []byte out = append(out, prefix...) for i, c := range cleaned { if i > 0 { out = append(out, ", "...) } out = append(out, c...) } out = append(out, suffix...) return out } func stripOneParamName(param []byte) []byte { if bytes.Equal(param, []byte("...")) { return param } // param is like "ptr %context" or "i64 %n" or "ptr nocapture readonly %p" // or just "ptr" or "i64" // strip %name at the end lastSpace := bytes.LastIndexByte(param, ' ') if lastSpace < 0 { return param } lastWord := param[lastSpace+1:] if len(lastWord) > 0 && lastWord[0] == '%' { return bytes.TrimSpace(param[:lastSpace]) } return param } func AssembleModule(scaffolds [][]byte, funcs [][]byte, definedFuncs map[string]bool, externalize bool) []byte { if len(scaffolds) == 0 { var out []byte for _, f := range funcs { out = append(out, f...) out = append(out, '\n') } return out } // First scaffold provides base (target triple, data layout) var out []byte seen := map[string]bool{} for si, scaffold := range scaffolds { lines := bytes.Split(scaffold, []byte("\n")) for _, line := range lines { trimmed := bytes.TrimSpace(line) if len(trimmed) == 0 { if si == 0 { out = append(out, '\n') } continue } key := "" if trimmed[0] == '%' && bytes.Contains(trimmed, []byte(" = type ")) { eqIdx := bytes.Index(trimmed, []byte(" = type ")) if eqIdx > 0 { key = "T:" | string(trimmed[:eqIdx]) } } else if trimmed[0] == '@' { gname := extractGlobalDefName(trimmed) if gname != "" { key = "G:" | gname } } else if bytes.HasPrefix(trimmed, []byte("declare ")) { declName := ExtractAtName(trimmed) if declName != "" { funcName := NormalizeLLVMName(declName) if definedFuncs != nil && definedFuncs[funcName] { continue } key = "D:" | funcName } } else if bytes.HasPrefix(trimmed, []byte("source_filename")) || bytes.HasPrefix(trimmed, []byte("; ModuleID")) { if si > 0 { continue } } else if bytes.HasPrefix(trimmed, []byte("target ")) { if si > 0 { continue } } // Skip debug metadata and attribute groups from non-primary scaffolds if si > 0 { if trimmed[0] == '!' { continue } if bytes.HasPrefix(trimmed, []byte("attributes #")) { continue } } if key != "" { if seen[key] { continue } seen[key] = true } if externalize && trimmed[0] == '@' && bytes.Contains(trimmed, []byte(" global ")) { gname := extractGlobalDefName(trimmed) isAppGlobal := bytes.HasPrefix([]byte(gname), []byte("@main.")) || bytes.HasPrefix([]byte(gname), []byte("@\"main.")) || bytes.HasPrefix([]byte(gname), []byte("@\"main$")) if isAppGlobal { line = bytes.Replace(line, []byte(" internal global "), []byte(" global "), 1) line = bytes.Replace(line, []byte(" internal unnamed_addr "), []byte(" unnamed_addr "), 1) out = append(out, line...) out = append(out, '\n') continue } ext := externalizeGlobal(trimmed) if len(ext) > 0 { out = append(out, ext...) out = append(out, '\n') continue } } out = append(out, line...) out = append(out, '\n') } } out = append(out, '\n') for _, f := range funcs { if externalize { f = promoteInternalFuncs(f) } out = append(out, f...) out = append(out, '\n') } return patchUndefinedRefs(out) } func externalizeGlobal(line []byte) []byte { gname := extractGlobalDefName(line) if gname == "" { return nil } globalIdx := bytes.Index(line, []byte(" global ")) if globalIdx < 0 { return nil } typeStart := globalIdx + len(" global ") rest := line[typeStart:] typeName := extractLLVMType(rest) if typeName == "" { return nil } var out []byte out = append(out, gname...) out = append(out, " = external global "...) out = append(out, typeName...) return out } func extractLLVMType(data []byte) string { data = bytes.TrimSpace(data) if len(data) == 0 { return "" } if data[0] == '{' { depth := 0 for i := 0; i < len(data); i++ { if data[i] == '{' { depth++ } else if data[i] == '}' { depth-- if depth == 0 { return string(data[:i+1]) } } } return "" } if data[0] == '[' { end := bytes.IndexByte(data, ']') if end > 0 { return string(data[:end+1]) } return "" } if data[0] == '%' || data[0] == 'i' || bytes.HasPrefix(data, []byte("ptr")) || bytes.HasPrefix(data, []byte("float")) || bytes.HasPrefix(data, []byte("double")) { for i := 0; i < len(data); i++ { if data[i] == ' ' || data[i] == ',' { return string(data[:i]) } } return string(data) } return "" } func promoteInternalFuncs(block []byte) []byte { marker := []byte("define internal ") repl := []byte("define ") if !bytes.Contains(block, marker) { return block } lines := bytes.Split(block, []byte("\n")) var out []byte for i, line := range lines { trimmed := bytes.TrimSpace(line) if bytes.HasPrefix(trimmed, marker) { line = bytes.Replace(line, marker, repl, 1) } out = append(out, line...) if i < len(lines)-1 { out = append(out, '\n') } } return out } func patchUndefinedRefs(module []byte) []byte { defined := map[string]bool{} lines := bytes.Split(module, []byte("\n")) for _, line := range lines { trimmed := bytes.TrimSpace(line) if len(trimmed) == 0 { continue } if bytes.HasPrefix(trimmed, []byte("define ")) { name := NormalizeLLVMName(ExtractAtName(trimmed)) if name != "" { defined[name] = true } } else if bytes.HasPrefix(trimmed, []byte("declare ")) { name := NormalizeLLVMName(ExtractAtName(trimmed)) if name != "" { defined[name] = true } } else if trimmed[0] == '@' { gname := NormalizeLLVMName(extractGlobalDefName(trimmed)) if gname != "" { defined[gname] = true } } } refs := map[string]bool{} for _, line := range lines { collectAtRefs(line, refs) } var stubs []byte for ref := range refs { if len(ref) > 5 && ref[1:5] == "llvm" { continue } nref := NormalizeLLVMName(ref) if !defined[nref] { stubs = append(stubs, "declare void "...) stubs = append(stubs, ref...) stubs = append(stubs, "()\n"...) defined[nref] = true } } if len(stubs) == 0 { return module } var out []byte out = append(out, module...) out = append(out, stubs...) return out } func ExtractAtName(line []byte) string { atIdx := bytes.IndexByte(line, '@') if atIdx < 0 { return "" } rest := line[atIdx:] if len(rest) > 1 && rest[1] == '"' { end := bytes.IndexByte(rest[2:], '"') if end > 0 { return string(rest[:end+3]) } return "" } for i := 1; i < len(rest); i++ { ch := rest[i] if ch == '(' || ch == ' ' || ch == '\n' || ch == ',' { return string(rest[:i]) } } return string(rest) } func extractGlobalDefName(line []byte) string { if len(line) == 0 || line[0] != '@' { return "" } if len(line) > 1 && line[1] == '"' { end := bytes.IndexByte(line[2:], '"') if end > 0 { return string(line[:end+3]) } return "" } spIdx := bytes.IndexByte(line, ' ') if spIdx > 0 { return string(line[:spIdx]) } return "" } func collectAtRefs(line []byte, refs map[string]bool) { pos := 0 for pos < len(line) { idx := bytes.IndexByte(line[pos:], '@') if idx < 0 { break } abs := pos + idx if abs > 0 && line[abs-1] != ' ' && line[abs-1] != ',' && line[abs-1] != '(' && line[abs-1] != '{' && line[abs-1] != '[' { pos = abs + 1 continue } rest := line[abs:] var name string if len(rest) > 1 && rest[1] == '"' { end := bytes.IndexByte(rest[2:], '"') if end > 0 { name = string(rest[:end+3]) } } else { valid := true for i := 1; i < len(rest); i++ { ch := rest[i] if ch == '(' || ch == ' ' || ch == '\n' || ch == ',' || ch == ')' || ch == '}' || ch == ']' { name = string(rest[:i]) break } if ch > 127 || (ch != '_' && ch != '.' && ch != '$' && ch != '-' && !(ch >= 'a' && ch <= 'z') && !(ch >= 'A' && ch <= 'Z') && !(ch >= '0' && ch <= '9')) { valid = false break } } if valid && name == "" && len(rest) > 1 { name = string(rest) } } if len(name) > 1 && name != "@" { refs[name] = true } pos = abs + len(name) if pos <= abs { pos = abs + 1 } } } func FindRuntimeSources(moxieRoot string) (mxFiles, cFiles, sFiles []string) { rtDir := filepath.Join(moxieRoot, "src", "runtime") entries, err := os.ReadDir(rtDir) if err != nil { return } for _, e := range entries { if e.IsDir() { continue } name := e.Name() full := filepath.Join(rtDir, name) if bytes.HasSuffix([]byte(name), []byte(".mx")) { if shouldSkipBuildTag(name) { continue } mxFiles = append(mxFiles, full) } else if bytes.HasSuffix([]byte(name), []byte(".c")) { if shouldSkipCFile(name) { continue } cFiles = append(cFiles, full) } else if bytes.HasSuffix([]byte(name), []byte(".S")) { if shouldSkipAsmFile(name) { continue } sFiles = append(sFiles, full) } } extraCDirs := []string{ filepath.Join(moxieRoot, "src", "internal", "internal", "futex"), filepath.Join(moxieRoot, "src", "internal", "cpu"), filepath.Join(moxieRoot, "src", "internal", "runtime", "syscall"), filepath.Join(moxieRoot, "src", "syscall"), } for _, dir := range extraCDirs { extras, err := os.ReadDir(dir) if err != nil { continue } for _, e := range extras { if e.IsDir() { continue } name := e.Name() full := filepath.Join(dir, name) if bytes.HasSuffix([]byte(name), []byte(".c")) && !shouldSkipCFile(name) { cFiles = append(cFiles, full) } else if bytes.HasSuffix([]byte(name), []byte(".S")) && !shouldSkipAsmFile(name) { sFiles = append(sFiles, full) } } } return } func shouldSkipBuildTag(name string) bool { skip := []string{ "_wasm.mx", "_arm64.mx", "_darwin.mx", "_windows.mx", "_baremetal.mx", "_test.mx", } for _, s := range skip { if bytes.HasSuffix([]byte(name), []byte(s)) { return true } } skipExact := []string{ "gc_none.mx", "gc_leaking.mx", "gc_boehm.mx", "gc_custom.mx", "gc_precise.mx", "gc_stack_raw.mx", } for _, s := range skipExact { if name == s { return true } } return false } func shouldSkipCFile(name string) bool { if bytes.Contains([]byte(name), []byte("darwin")) { return true } return false } func shouldSkipAsmFile(name string) bool { if bytes.Contains([]byte(name), []byte("arm64")) { return true } return false } func DiscoverMxFiles(dir string) ([]string, error) { entries, err := os.ReadDir(dir) if err != nil { return nil, err } var files []string for _, e := range entries { if e.IsDir() { continue } if bytes.HasSuffix([]byte(e.Name()), []byte(".mx")) { if bytes.HasSuffix([]byte(e.Name()), []byte("_test.mx")) { continue } files = append(files, filepath.Join(dir, e.Name())) } } return files, nil } func ReadModulePath(dir string) string { modFile := filepath.Join(dir, "moxie.mod") data, err := os.ReadFile(modFile) if err != nil { return "" } lines := bytes.Split(data, []byte("\n")) for _, line := range lines { line = bytes.TrimSpace(line) if bytes.HasPrefix(line, []byte("module ")) { return string(line[7:]) } } return "" } type UnmatchedFunc struct { SrcFile string Name string } type CompileResult struct { Matched int Unmatched int IR []byte UnmatchedList []UnmatchedFunc PkgRenames map[string]bool } func FindRuntimeScaffold(t *Tree) []byte { for i := range t.RecMeta { m := &t.RecMeta[i] if m.StageTag != StageIR || m.Kind != KindPkg { continue } rec := t.db.GetRecord(uint32(i)) if rec == nil { continue } form := FormFromRecord(rec, t.StringPool) if form == "runtime.__module__" { return t.GetContent(uint32(i)) } } return nil } func CompileFiles(t *Tree, srcFiles []string, pkgFilter string, outPkg string, externalize bool, modPath ...string) CompileResult { var result CompileResult var funcs [][]byte var scaffolds [][]byte definedFuncs := map[string]bool{} seenPkgModule := map[uint32]bool{} rtScaffold := FindRuntimeScaffold(t) if len(rtScaffold) > 0 { scaffolds = append(scaffolds, ExtractModuleScaffold(rtScaffold)) } for _, srcFile := range srcFiles { data, err := os.ReadFile(srcFile) if err != nil { continue } decls := SplitDecls(data) for _, decl := range decls { name := DeclName(decl) if name == "" { continue } dump := GenAST(decl) if len(dump) == 0 { continue } if !bytes.HasPrefix(dump, []byte("FuncDecl")) { continue } var matches []uint32 if pkgFilter != "" { matches = FindBySignatureFromASTInPkg(t, string(dump), pkgFilter) } else { matches = FindBySignatureFromAST(t, string(dump)) } if len(matches) == 0 { result.Unmatched++ result.UnmatchedList = append(result.UnmatchedList, UnmatchedFunc{SrcFile: srcFile, Name: name}) continue } RankMatches(t, matches, 0, name) matchMeta := matches[0] matchAST := t.GetContent(matchMeta) // Find IR version via key-implicit cross-stage lookup: // same name hash, StageIR, same branch. var irTokens []uint32 var pkgModuleMeta uint32 if astKey, ok := t.db.RecKey[matchMeta]; ok { branch := KindToBranch(t.RecMeta[matchMeta].Kind) irKey := MakeCodeKey(StageIR, KeyHash(astKey)) irRecIdx := t.LookupRecIdx(branch, irKey) if irRecIdx != NullLatticeRec { irTokens = t.GetTokenSeq(irRecIdx) // Find the package module: scan for KindPkg+StageIR entries. pkgModuleMeta = findPkgModuleMeta(t, irRecIdx) } } if len(irTokens) == 0 { result.Unmatched++ result.UnmatchedList = append(result.UnmatchedList, UnmatchedFunc{SrcFile: srcFile, Name: name}) continue } if pkgModuleMeta != 0 && !seenPkgModule[pkgModuleMeta] { seenPkgModule[pkgModuleMeta] = true pkgIR := t.GetContent(pkgModuleMeta) if len(pkgIR) > 0 { scaffolds = append(scaffolds, ExtractModuleScaffold(pkgIR)) if len(modPath) > 0 && modPath[0] != "" { rec := t.db.GetRecord(pkgModuleMeta) if rec != nil { modName := FormFromRecord(rec, t.StringPool) modPkg := "" dotIdx := bytes.LastIndexByte([]byte(modName), '.') if dotIdx >= 0 { modPkg = modName[:dotIdx] } if modPkg == outPkg { inits, strGlobals, cls := ExtractInitAndStrings(pkgIR, outPkg) for _, initF := range inits { funcs = append(funcs, initF) defName := extractDefineName(initF) if defName != "" { definedFuncs[defName] = true } } for _, cl := range cls { funcs = append(funcs, cl) defName := extractDefineName(cl) if defName != "" { definedFuncs[defName] = true } } if len(strGlobals) > 0 { scaffolds = append(scaffolds, strGlobals) } } } } } } irContent := t.Dict.Decode(irTokens) templateIRName := extractIRFuncName(irContent) if templateIRName == "" { result.Unmatched++ result.UnmatchedList = append(result.UnmatchedList, UnmatchedFunc{SrcFile: srcFile, Name: name}) continue } var targetIRName string if outPkg != "" { targetIRName = buildTargetIRName(templateIRName, outPkg, name) } else { targetIRName = replaceLastComponent(templateIRName, name) } subst := BuildTokenSubst(t.Dict, string(matchAST), string(dump), templateIRName, targetIRName) resultTokens := subst.Apply(irTokens) decoded := subst.Decode(resultTokens) if outPkg != "" && len(modPath) > 0 && modPath[0] != "" { templatePkg := extractPkgPrefix(templateIRName) if templatePkg == modPath[0] && templatePkg != outPkg { if result.PkgRenames == nil { result.PkgRenames = map[string]bool{} } result.PkgRenames[templatePkg] = true } } decoded = StripDebugMetadata(decoded) defName := extractDefineName(decoded) if defName != "" { if definedFuncs[defName] { continue } definedFuncs[defName] = true } funcs = append(funcs, decoded) result.Matched++ } } if len(funcs) > 0 { if outPkg != "" && len(result.PkgRenames) > 0 { for oldPkg := range result.PkgRenames { old := []byte(oldPkg | ".") new := []byte(outPkg | ".") for i := range scaffolds { scaffolds[i] = bytes.ReplaceAll(scaffolds[i], old, new) } for i := range funcs { funcs[i] = bytes.ReplaceAll(funcs[i], old, new) } newDefined := map[string]bool{} for k, v := range definedFuncs { nk := string(bytes.ReplaceAll([]byte(k), old, new)) newDefined[nk] = v } definedFuncs = newDefined } } result.IR = AssembleModule(scaffolds, funcs, definedFuncs, externalize) if externalize && outPkg != "" { result.IR = deexternalizePkg(result.IR, outPkg) } } return result } func deexternalizePkg(module []byte, pkg string) []byte { prefix := []byte("@" | pkg | ".") qprefix := []byte("@\"" | pkg | ".") lines := bytes.Split(module, []byte("\n")) var out []byte for _, line := range lines { trimmed := bytes.TrimSpace(line) if len(trimmed) > 0 && trimmed[0] == '@' && (bytes.HasPrefix(trimmed, prefix) || bytes.HasPrefix(trimmed, qprefix)) && bytes.Contains(trimmed, []byte(" = external global ")) { extIdx := bytes.Index(line, []byte(" = external global ")) typePart := bytes.TrimSpace(line[extIdx+len(" = external global "):]) var newLine []byte newLine = append(newLine, line[:extIdx]...) newLine = append(newLine, " = global "...) newLine = append(newLine, typePart...) newLine = append(newLine, " zeroinitializer"...) line = newLine } out = append(out, line...) out = append(out, '\n') } return out } func StripDebugMetadata(ir []byte) []byte { lines := bytes.Split(ir, []byte("\n")) var out []byte for _, line := range lines { // Remove !dbg !NNN references cleaned := removeDbgRefs(line) // Skip #dbg_value lines trimmed := bytes.TrimSpace(cleaned) if bytes.HasPrefix(trimmed, []byte("#dbg_value")) || bytes.HasPrefix(trimmed, []byte("#dbg_declare")) { continue } out = append(out, cleaned...) out = append(out, '\n') } return out } func removeDbgRefs(line []byte) []byte { for { idx := bytes.Index(line, []byte(", !dbg !")) if idx < 0 { idx = bytes.Index(line, []byte(" !dbg !")) if idx < 0 { break } } end := idx + 7 // past "!dbg !" if line[idx] == ',' { end = idx + 8 } for end < len(line) && line[end] >= '0' && line[end] <= '9' { end++ } var newLine []byte newLine = append(newLine, line[:idx]...) newLine = append(newLine, line[end:]...) line = newLine } return line } func extractDefineName(ir []byte) string { idx := bytes.Index(ir, []byte("define ")) if idx < 0 { return "" } atIdx := bytes.IndexByte(ir[idx:], '@') if atIdx < 0 { return "" } rest := ir[idx+atIdx:] if len(rest) > 1 && rest[1] == '"' { closeQuote := bytes.IndexByte(rest[2:], '"') if closeQuote < 0 { return "" } return NormalizeLLVMName(string(rest[:closeQuote+3])) } parenIdx := bytes.IndexByte(rest, '(') if parenIdx < 0 { return "" } return NormalizeLLVMName(string(rest[:parenIdx])) } func NormalizeLLVMName(name string) string { if len(name) > 2 && name[0] == '@' && name[1] == '"' && name[len(name)-1] == '"' { return "@" | name[2:len(name)-1] } return name } func extractIRFuncName(ir []byte) string { firstLine := ir nl := bytes.IndexByte(ir, '\n') if nl >= 0 { firstLine = ir[:nl] } idx := bytes.Index(firstLine, []byte("@\"")) if idx >= 0 { rest := firstLine[idx+2:] end := bytes.IndexByte(rest, '"') if end > 0 { return string(rest[:end]) } } idx = bytes.IndexByte(firstLine, '@') if idx < 0 { return "" } rest := firstLine[idx+1:] end := bytes.IndexByte(rest, '(') if end < 0 { return "" } return string(rest[:end]) } func buildTargetIRName(templateIRName, outPkg, name string) string { if len(templateIRName) > 2 && templateIRName[0] == '(' { closeIdx := -1 for i := 0; i < len(templateIRName); i++ { if templateIRName[i] == ')' { closeIdx = i break } } if closeIdx > 0 { inner := templateIRName[1:closeIdx] ptr := "" if len(inner) > 0 && inner[0] == '*' { ptr = "*" inner = inner[1:] } lastDot := -1 for i := len(inner) - 1; i >= 0; i-- { if inner[i] == '.' { lastDot = i break } } typeName := inner if lastDot >= 0 { typeName = inner[lastDot+1:] } return "(" | ptr | outPkg | "." | typeName | ")." | name } } return outPkg | "." | name } func extractPkgPrefix(irName string) string { dot := -1 for i := len(irName) - 1; i >= 0; i-- { if irName[i] == '.' { dot = i break } } if dot < 0 { return "" } return irName[:dot] } func replaceLastComponent(qualName, newFunc string) string { dot := -1 for i := len(qualName) - 1; i >= 0; i-- { if qualName[i] == '.' { dot = i break } } if dot < 0 { return newFunc } return qualName[:dot+1] | newFunc } // findPkgModuleMeta finds the package module meta index (KindPkg+StageIR) // by scanning all RecMeta entries. The module entry name contains ".__module__". // Returns 0 if not found (0 is NullIndex convention here for uint32 CostMap keying). func findPkgModuleMeta(t *Tree, nearRecIdx uint32) uint32 { for i := range t.RecMeta { m := &t.RecMeta[i] if m.StageTag != StageIR || m.Kind != KindPkg { continue } rec := t.db.GetRecord(uint32(i)) if rec == nil { continue } form := FormFromRecord(rec, t.StringPool) if bytes.HasSuffix([]byte(form), []byte(".__module__")) { return uint32(i) } } return 0 }