translate.mx raw

   1  package transdb
   2  
   3  import (
   4  	"git.smesh.lol/iskradb/lattice"
   5  	"git.smesh.lol/transdb/fuzzy"
   6  )
   7  
   8  // FormFromInline extracts the surface form stored in Record.Inline.
   9  // Byte 23 holds the inline length (0 = overflow, data in pool).
  10  func FormFromInline(rec *lattice.Record, pool []byte) string {
  11  	n := int32(rec.Inline[23])
  12  	if n > 0 && n <= 23 {
  13  		return string(rec.Inline[:n])
  14  	}
  15  	if rec.DataFile == 1 && rec.DataLen > 0 {
  16  		end := rec.DataOff + rec.DataLen
  17  		if int32(end) <= len(pool) {
  18  			return string(pool[rec.DataOff:end])
  19  		}
  20  	}
  21  	return ""
  22  }
  23  
  24  // SetFormOnRecord stores the surface form in Record.Inline (up to 23 bytes)
  25  // or overflows into pool when longer.
  26  func SetFormOnRecord(rec *lattice.Record, form string, pool *[]byte) {
  27  	b := []byte(form)
  28  	if len(b) <= 23 {
  29  		copy(rec.Inline[:], b)
  30  		rec.Inline[23] = byte(len(b))
  31  		rec.DataFile = 0
  32  	} else {
  33  		copy(rec.Inline[:23], b[:23])
  34  		rec.Inline[23] = 0
  35  		rec.DataFile = 1
  36  		rec.DataOff = uint32(len(*pool))
  37  		rec.DataLen = uint32(len(b))
  38  		*pool = append(*pool, b...)
  39  	}
  40  }
  41  
  42  // defaultBranchOrder uses actual branch indices (Bnoun=1, Bverb=3, Bmodifier=4).
  43  var defaultBranchOrder [3]uint8
  44  
  45  // lookupByKey finds all translation candidates for a pre-computed key,
  46  // searching branches in the given order.
  47  func lookupByKey(tree *lattice.Tree, pool []byte, key lattice.Key, order [3]uint8) []string {
  48  	var results []string
  49  	for _, b := range order {
  50  		ri := tree.LookupRecIdx(lattice.Branch(b), key)
  51  		if ri == lattice.NullRec {
  52  			continue
  53  		}
  54  		rec := tree.GetRecord(ri)
  55  		if rec == nil {
  56  			continue
  57  		}
  58  		if rec.Link[0] != lattice.NullRec {
  59  			if dst := tree.GetRecord(rec.Link[0]); dst != nil {
  60  				if form := FormFromInline(dst, pool); form != "" {
  61  					results = appendUniq(results, form)
  62  				}
  63  			}
  64  		}
  65  		if rec.Link[1] != lattice.NullRec {
  66  			if dst := tree.GetRecord(rec.Link[1]); dst != nil {
  67  				if form := FormFromInline(dst, pool); form != "" {
  68  					results = appendUniq(results, form)
  69  				}
  70  			}
  71  		}
  72  		break
  73  	}
  74  	return results
  75  }
  76  
  77  // jaRecordBranch returns the branch of the coord=0 JA record for tok, or 255 if not found.
  78  func jaRecordBranch(tree *lattice.Tree, tok string) uint8 {
  79  	key := MakeKey(LangJA, 0, tok)
  80  	for _, b := range ActiveBranches {
  81  		if tree.LookupRecIdx(b, key) != lattice.NullRec {
  82  			return uint8(b)
  83  		}
  84  	}
  85  	return 255
  86  }
  87  
  88  // LookupWord finds all translation candidates for a single word token (coord=0).
  89  func LookupWord(tree *lattice.Tree, pool []byte, word string, srcLang uint8) []string {
  90  	translateInitOnce()
  91  	return lookupByKey(tree, pool, MakeKey(srcLang, 0, word), defaultBranchOrder)
  92  }
  93  
  94  // LookupWordCtx finds translations using the 22-bit coordinate.
  95  // Tries each coordinate in the relaxation sequence (most specific → least specific).
  96  // For JA source, branch order is derived from the cooccurrence axis.
  97  func LookupWordCtx(tree *lattice.Tree, pool []byte, word string, srcLang uint8, coord uint64) []string {
  98  	translateInitOnce()
  99  	order := defaultBranchOrder
 100  	if srcLang == LangJA {
 101  		order = branchOrderJA(coord)
 102  	}
 103  	for _, c := range RelaxCoord(coord) {
 104  		if results := lookupByKey(tree, pool, MakeKey(srcLang, c, word), order); len(results) > 0 {
 105  			return results
 106  		}
 107  	}
 108  	return nil
 109  }
 110  
 111  // jaRole constants for syntactic role assignment.
 112  const (
 113  	jaRoleNone = uint8(0)
 114  	jaRoleSubj = uint8(1) // は が
 115  	jaRoleObj  = uint8(2) // を
 116  	jaRoleVerb = uint8(3)
 117  	jaRoleMisc = uint8(4) // everything else
 118  )
 119  
 120  // jaRoleParticle maps particle strings to syntactic roles.
 121  // Only subject (は/が) and object (を) get specific roles;
 122  // other particles collapse to misc.
 123  var jaRoleParticle map[string]uint8
 124  
 125  // Translate tokenizes text in srcLang and translates each token to dstLang.
 126  // For JA→EN, applies particle-based role assignment and SOV→SVO reordering.
 127  // Tokens with no translation are passed through unchanged.
 128  func Translate(tree *lattice.Tree, pool []byte, idx *fuzzy.DualIndex,
 129  	text string, srcLang, dstLang uint8, verbose bool) string {
 130  
 131  	translateInitOnce()
 132  	KeyInitOnce()
 133  	var tokens []string
 134  	switch srcLang {
 135  	case LangEN:
 136  		tokens = TokenizeEN(text)
 137  	case LangJA:
 138  		tokens = TokenizeJA(text, tree, verbose)
 139  	default:
 140  		tokens = TokenizeEN(text)
 141  	}
 142  
 143  	if srcLang == LangJA && dstLang == LangEN {
 144  		return translateJAToEN(tree, pool, idx, tokens, verbose)
 145  	}
 146  	return translateTokens(tree, pool, idx, tokens, srcLang, dstLang, verbose)
 147  }
 148  
 149  // translateJAToEN handles JA→EN with two-zone SOV→SVO reordering.
 150  //
 151  // Zone split: は/が divides the sentence into subject zone and predicate zone.
 152  // Within the predicate zone, verb tokens are pulled to the front:
 153  //   SUBJ_ZONE + VERB(s) + REST_OF_PRED_ZONE
 154  //
 155  // This preserves modifier attachment (天皇の歴史的責任感 stays together as the
 156  // subject) while achieving SVO word order for the core clause.
 157  func translateJAToEN(tree *lattice.Tree, pool []byte, idx *fuzzy.DualIndex,
 158  	tokens []string, verbose bool) string {
 159  
 160  	n := len(tokens)
 161  
 162  	// isSkipToken: pure-hiragana particles and copulae get no EN output.
 163  	isSkip := func(tok string) bool {
 164  		if !isPureHiragana(tok) {
 165  			return false
 166  		}
 167  		jaKey := MakeKey(LangJA, 0, tok)
 168  		return tree.LookupRecIdx(lattice.Bmodifier, jaKey) != lattice.NullRec || jaFunctionWord[tok]
 169  	}
 170  
 171  	// lookupMorph returns the translation and MorphState for a JA token.
 172  	// Uses RelaxCoord: tries most-specific coord first, falls back toward coord=0.
 173  	lookupMorph := func(tok string, coord uint64) (string, uint8) {
 174  		order := branchOrderJA(coord)
 175  		for _, c := range RelaxCoord(coord) {
 176  			key := MakeKey(LangJA, c, tok)
 177  			for _, b := range order {
 178  				ri := tree.LookupRecIdx(lattice.Branch(b), key)
 179  				if ri == lattice.NullRec {
 180  					continue
 181  				}
 182  				rec := tree.GetRecord(ri)
 183  				if rec == nil {
 184  					continue
 185  				}
 186  				state := GetMorphState(rec)
 187  				if rec.Link[0] != lattice.NullRec {
 188  					if dst := tree.GetRecord(rec.Link[0]); dst != nil {
 189  						if form := FormFromInline(dst, pool); form != "" {
 190  							return form, state
 191  						}
 192  					}
 193  				}
 194  				break
 195  			}
 196  		}
 197  		return "", 0
 198  	}
 199  
 200  	// translateTok: translate a single JA token using the 22-bit coordinate.
 201  	// The coord encodes both cooccurrence context (prev/next word types) and
 202  	// the morphological state inferred from the token's surface form.
 203  	translateTok := func(i int32, tok string) string {
 204  		var prevType, nextType uint8
 205  		if i > 0 {
 206  			prevType = POSTypeFor(POSForWord(tree, LangJA, tokens[i-1]))
 207  		}
 208  		if i+1 < n {
 209  			nextType = POSTypeFor(POSForWord(tree, LangJA, tokens[i+1]))
 210  		}
 211  		morphState := uint64(inferMorphState(tok))
 212  		coord := PackCoord(0, 0, CoordCooccur(prevType, nextType), morphState, 0, 0, 0)
 213  
 214  		if en, state := lookupMorph(tok, coord); en != "" {
 215  			return applyMorphEN(en, state)
 216  		}
 217  
 218  		// Fuzzy fallback.
 219  		if idx != nil {
 220  			var corrected string
 221  			var wasCorrected bool
 222  			var candidates []string
 223  			candidates, corrected, wasCorrected = FuzzyLookupWord(tree, pool, idx, tok, LangJA, 2)
 224  			if verbose && wasCorrected {
 225  				println("fuzzy:", tok, "→", corrected)
 226  			}
 227  			for _, c := range candidates {
 228  				return applyMorphEN(c, 0)
 229  			}
 230  			_ = corrected
 231  		}
 232  
 233  		// verbStems fallback for forms not in lattice.
 234  		if stems := verbStems(tok); len(stems) > 0 {
 235  			for _, stem := range stems {
 236  				stemCoord := PackCoord(0, 0, CoordCooccur(prevType, nextType), morphState, 0, 0, 0)
 237  				if en, _ := lookupMorph(stem, stemCoord); en != "" {
 238  					return applyMorphEN(en, uint8(morphState))
 239  				}
 240  			}
 241  		}
 242  		return tok
 243  	}
 244  
 245  	// Find the first は/が boundary to split subject zone from predicate zone.
 246  	// subjEnd is the index of the は/が particle itself.
 247  	subjEnd := -1
 248  	for i, tok := range tokens {
 249  		if tok == "は" || tok == "が" {
 250  			if isPureHiragana(tok) {
 251  				subjEnd = i
 252  				break
 253  			}
 254  		}
 255  	}
 256  
 257  	// Translate all tokens in JA order, tagging each as subj/verb/pred.
 258  	type word struct {
 259  		en   string
 260  		isV  bool
 261  	}
 262  	var subjWords, predVerbs, predRest []word
 263  
 264  	for i, tok := range tokens {
 265  		if isSkip(tok) {
 266  			continue
 267  		}
 268  		en := translateTok(i, tok)
 269  		if en == "" {
 270  			continue
 271  		}
 272  		w := word{en, isJAVerb(tree, tok)}
 273  		if subjEnd >= 0 && i < subjEnd {
 274  			subjWords = append(subjWords, w)
 275  		} else if w.isV {
 276  			predVerbs = append(predVerbs, w)
 277  		} else {
 278  			predRest = append(predRest, w)
 279  		}
 280  	}
 281  
 282  	// Emit: SUBJ + VERB + REST_OF_PRED (preserves modifier order within each zone).
 283  	var out []byte
 284  	first := true
 285  	emit := func(en string) {
 286  		if !first {
 287  			out = append(out, ' ')
 288  		}
 289  		out = append(out, []byte(en)...)
 290  		first = false
 291  	}
 292  	for _, w := range subjWords {
 293  		emit(w.en)
 294  	}
 295  	for _, w := range predVerbs {
 296  		emit(w.en)
 297  	}
 298  	for _, w := range predRest {
 299  		emit(w.en)
 300  	}
 301  	return string(out)
 302  }
 303  
 304  // translateTokens handles EN→JA and same-language translation (no reordering).
 305  // For EN→JA: operator tokens ("did", "not", "apparently" etc.) accumulate
 306  // morphstate bits and are consumed without output; the next verb is looked up
 307  // at the resulting morphstate in the JA cluster.
 308  func translateTokens(tree *lattice.Tree, pool []byte, idx *fuzzy.DualIndex,
 309  	tokens []string, srcLang, dstLang uint8, verbose bool) string {
 310  
 311  	var out []byte
 312  	pendingMorph := uint8(0)       // accumulated operator bits waiting for a verb
 313  	progressiveAux := uint8(0xFF)  // 0xFF = none; otherwise tense bits from is/was/were
 314  	subjectSemFlags := uint64(0)   // semantic flags from subject nouns seen so far
 315  
 316  	for i, tok := range tokens {
 317  		// EN→JA: detect operator tokens (morphstate walk instructions).
 318  		if srcLang == LangEN && dstLang == LangJA {
 319  			if bits, ok := enOperators[tok]; ok {
 320  				pendingMorph |= bits
 321  				continue // operator consumed, no output
 322  			}
 323  			// Progressive auxiliary: "is/am/are/was/were" before a verb+ing.
 324  			if tenseBits, ok := enProgressiveAux[tok]; ok {
 325  				progressiveAux = tenseBits
 326  				continue
 327  			}
 328  			// Detect "-ing" suffix on a verb when progressive aux is pending.
 329  			if progressiveAux != 0xFF && len(tok) > 3 && tok[len(tok)-3:] == "ing" {
 330  				pendingMorph |= (1 << 3) | progressiveAux // aspect + tense
 331  				progressiveAux = 0xFF
 332  				// Strip "ing" to get base verb for lookup.
 333  				tok = tok[:len(tok)-3]
 334  			}
 335  		}
 336  
 337  		var candidates []string
 338  		corrected := tok
 339  
 340  		var prevType, nextType uint8
 341  		if i > 0 {
 342  			prevType = POSTypeFor(POSForWord(tree, srcLang, tokens[i-1]))
 343  		}
 344  		if i+1 < len(tokens) {
 345  			nextType = POSTypeFor(POSForWord(tree, srcLang, tokens[i+1]))
 346  		}
 347  
 348  		// Accumulate semantic flags from subject nouns for verb disambiguation.
 349  		// Read flags from the noun's base record DataFile (O(1), no coord scan).
 350  		if srcLang == LangEN && dstLang == LangJA {
 351  			curType := POSTypeFor(POSForWord(tree, srcLang, tok))
 352  			if curType == CooccurNominal { // it's a noun in the EN lattice
 353  				key := MakeKey(LangEN, 0, tok)
 354  				for _, b := range ActiveBranches {
 355  					if ri := tree.LookupRecIdx(b, key); ri != lattice.NullRec {
 356  						if rec := tree.GetRecord(ri); rec != nil {
 357  							subjectSemFlags |= GetSemanticFromDataFile(rec)
 358  						}
 359  						break
 360  					}
 361  				}
 362  			}
 363  		}
 364  
 365  		coord := PackCoord(subjectSemFlags, 0, CoordCooccur(prevType, nextType), 0, 0, 0, 0)
 366  
 367  		if idx != nil {
 368  			var wasCorrected bool
 369  			candidates, corrected, wasCorrected = FuzzyLookupWord(tree, pool, idx, tok, srcLang, 2)
 370  			if verbose && wasCorrected {
 371  				println("fuzzy: corrected", tok, "→", corrected)
 372  			}
 373  			if len(candidates) > 0 && coord != 0 {
 374  				if ctxCands := LookupWordCtx(tree, pool, corrected, srcLang, coord); len(ctxCands) > 0 {
 375  					candidates = ctxCands
 376  				}
 377  			}
 378  		} else {
 379  			candidates = LookupWordCtx(tree, pool, tok, srcLang, coord)
 380  		}
 381  
 382  		var translated string
 383  
 384  		// EN→JA: use lookupENToJA to get JA base + EN record's own MorphState.
 385  		// Combine with pendingMorph (accumulated operator bits) for the target state.
 386  		// Handles both synthetic ("sang" has MorphState=16) and analytical ("did"+"sing").
 387  		if srcLang == LangEN && dstLang == LangJA {
 388  			jaBase, enMorphState := lookupENToJA(tree, pool, corrected, coord)
 389  			targetState := pendingMorph | enMorphState
 390  			if jaBase != "" && targetState != 0 {
 391  				if targetForm := lookupJAAtMorphState(tree, pool, jaBase, targetState); targetForm != "" {
 392  					translated = targetForm
 393  				} else {
 394  					translated = jaBase
 395  				}
 396  				pendingMorph = 0
 397  			} else if jaBase != "" {
 398  				translated = jaBase
 399  				pendingMorph = 0
 400  			}
 401  		}
 402  
 403  		if translated == "" {
 404  			for _, c := range candidates {
 405  				translated = c
 406  				break
 407  			}
 408  		}
 409  		if translated == "" {
 410  			translated = tok
 411  		}
 412  		if len(out) > 0 && dstLang == LangEN {
 413  			out = append(out, ' ')
 414  		}
 415  		out = append(out, []byte(translated)...)
 416  	}
 417  	return string(out)
 418  }
 419  
 420  // lookupENToJA finds the JA base form and the EN record's MorphState for a
 421  // given EN token. Tries the word as-is, then with "to " prefix (JMdict gloss
 422  // format). The MorphState on the EN record drives JA cluster navigation:
 423  // "sang" has MorphState=16 pointing to 歌う, so we navigate to 歌った.
 424  func lookupENToJA(tree *lattice.Tree, pool []byte, word string, coord uint64) (jaBase string, morphState uint8) {
 425  	order := defaultBranchOrder
 426  	for _, tryWord := range []string{word, "to " | word} {
 427  		for _, c := range RelaxCoord(coord) {
 428  			key := MakeKey(LangEN, c, tryWord)
 429  			for _, b := range order {
 430  				ri := tree.LookupRecIdx(lattice.Branch(b), key)
 431  				if ri == lattice.NullRec {
 432  					continue
 433  				}
 434  				rec := tree.GetRecord(ri)
 435  				if rec == nil {
 436  					continue
 437  				}
 438  				state := GetMorphState(rec)
 439  				if rec.Link[0] == lattice.NullRec {
 440  					break
 441  				}
 442  				dst := tree.GetRecord(rec.Link[0])
 443  				if dst == nil {
 444  					break
 445  				}
 446  				if form := FormFromInline(dst, pool); form != "" {
 447  					return form, state
 448  				}
 449  				break
 450  			}
 451  		}
 452  	}
 453  	return "", 0
 454  }
 455  
 456  // enToJABase is the legacy wrapper used by the operator path.
 457  func enToJABase(tree *lattice.Tree, pool []byte, enWord string) string {
 458  	base, _ := lookupENToJA(tree, pool, enWord, 0)
 459  	return base
 460  }
 461  
 462  // lookupJAAtMorphState finds the surface form of jaBase at the given morphstate.
 463  // Uses stored verb class from Bcooccur (O(1)) when available; falls back to
 464  // trying each conjugation class in priority order (O(classes)).
 465  func lookupJAAtMorphState(tree *lattice.Tree, pool []byte, jaBase string, targetState uint8) string {
 466  	tryForm := func(targetForm string) bool {
 467  		if targetForm == "" {
 468  			return false
 469  		}
 470  		key := MakeKey(LangJA, 0, targetForm)
 471  		for _, b := range ActiveBranches {
 472  			if tree.LookupRecIdx(lattice.Branch(b), key) != lattice.NullRec {
 473  				return true
 474  			}
 475  		}
 476  		return false
 477  	}
 478  
 479  	// Fast path: stored verb class from inflect.mx registration.
 480  	// When the class is known, the computed form is authoritative — return it
 481  	// even if not pre-stored in the lattice.
 482  	if class, ok := GetVerbClass(tree, LangJA, jaBase); ok {
 483  		if f := InflectJA(jaBase, class, targetState); f != "" {
 484  			return f
 485  		}
 486  	}
 487  
 488  	// Fallback: try each class in priority order (pre-inflect data or unknown class)
 489  	classOrder := []string{
 490  		"v1", "v5k", "v5s", "v5m", "v5b", "v5r", "v5t", "v5u", "v5g", "v5n", "vs", "vk",
 491  	}
 492  	for _, class := range classOrder {
 493  		forms := BuildVerbForms(jaBase, class)
 494  		if len(forms) == 0 {
 495  			continue
 496  		}
 497  		targetForm, ok := forms[targetState]
 498  		if !ok || targetForm == "" {
 499  			continue
 500  		}
 501  		if tryForm(targetForm) {
 502  			return targetForm
 503  		}
 504  	}
 505  	return ""
 506  }
 507  
 508  // TranslateWithClusters uses the five-stage cluster pipeline instead of
 509  // token-by-token translation. Falls back to Translate if lang descriptors
 510  // are not registered (lang-init not yet run).
 511  func TranslateWithClusters(tree *lattice.Tree, pool []byte, text string, srcLang, dstLang uint8, verbose bool) string {
 512  	translateInitOnce()
 513  	KeyInitOnce()
 514  	srcDesc, hasSrc := GetLangDesc(tree, srcLang)
 515  	dstDesc, hasDst := GetLangDesc(tree, dstLang)
 516  	if !hasSrc || !hasDst {
 517  		if verbose {
 518  			println("cluster: lang descriptors not registered, using token-by-token")
 519  		}
 520  		return Translate(tree, pool, nil, text, srcLang, dstLang, verbose)
 521  	}
 522  
 523  	var tokens []string
 524  	switch srcLang {
 525  	case LangEN:
 526  		tokens = TokenizeEN(text)
 527  	case LangJA:
 528  		tokens = TokenizeJA(text, tree, verbose)
 529  	default:
 530  		tokens = TokenizeEN(text)
 531  	}
 532  
 533  	clusters := ParseClusters(tokens, tree, srcLang)
 534  	for _, c := range clusters {
 535  		TranslateCluster(c, tree, pool, srcLang, dstLang)
 536  	}
 537  	reordered := ReorderClusters(clusters, srcDesc.Order, dstDesc.Order)
 538  	return InsertMarkers(reordered, dstDesc, dstLang)
 539  }
 540  
 541  // BuildWordIndex extracts all words from the lattice and builds BK-trees
 542  // for fuzzy matching. Call once after loading the DB.
 543  // Returns a *fuzzy.DualIndex with EN words in A and JA words in B.
 544  func BuildWordIndex(tree *lattice.Tree, pool []byte) *fuzzy.DualIndex {
 545  	var enWords, jaWords []string
 546  	for recIdx := range tree.RecKey {
 547  		rec := tree.GetRecord(recIdx)
 548  		if rec == nil {
 549  			continue
 550  		}
 551  		form := FormFromInline(rec, pool)
 552  		if form == "" {
 553  			continue
 554  		}
 555  		switch Detect(form) {
 556  		case LangEN:
 557  			enWords = append(enWords, form)
 558  		case LangJA:
 559  			jaWords = append(jaWords, form)
 560  		}
 561  	}
 562  	return fuzzy.NewDualIndex(fuzzy.Build(enWords), fuzzy.Build(jaWords))
 563  }
 564  
 565  // FuzzyLookupWord attempts a translation with fuzzy fallback on exact miss.
 566  // Returns (translations, correctedForm, wasCorrected).
 567  func FuzzyLookupWord(tree *lattice.Tree, pool []byte, idx *fuzzy.DualIndex,
 568  	word string, srcLang uint8, maxDist int32) ([]string, string, bool) {
 569  
 570  	results := LookupWord(tree, pool, word, srcLang)
 571  	if len(results) > 0 {
 572  		return results, word, false
 573  	}
 574  	if idx == nil {
 575  		return nil, word, false
 576  	}
 577  
 578  	var matches []fuzzy.Match
 579  	switch srcLang {
 580  	case LangEN:
 581  		matches = idx.SuggestA(word, maxDist, 3)
 582  	case LangJA:
 583  		matches = idx.SuggestB(word, maxDist, 3)
 584  	}
 585  	if len(matches) == 0 {
 586  		return nil, word, false
 587  	}
 588  
 589  	best := matches[0].Word
 590  	results = LookupWord(tree, pool, best, srcLang)
 591  	if len(results) > 0 {
 592  		return results, best, true
 593  	}
 594  	return nil, word, false
 595  }
 596  
 597  // stripTo removes a leading "to " from a JMdict verb gloss ("to eat" → "eat").
 598  func stripTo(s string) string {
 599  	if len(s) > 3 && s[:3] == "to " {
 600  		return s[3:]
 601  	}
 602  	return s
 603  }
 604  
 605  // applyMorphEN maps a 5-bit MorphState onto EN tense/aspect/polarity markers.
 606  // Formality (bit1) has no EN grammatical effect. Evidentiality (bit0) → "apparently".
 607  // Strips JMdict "to " prefix before applying operators.
 608  func applyMorphEN(base string, state uint8) string {
 609  	v := stripTo(base) // "to eat" → "eat"
 610  	if state == 0 {
 611  		return v
 612  	}
 613  	past   := (state>>4)&1 == 1 // bit 4
 614  	prog   := (state>>3)&1 == 1 // bit 3
 615  	neg    := (state>>2)&1 == 1 // bit 2
 616  	evid   := state&1 == 1      // bit 0
 617  
 618  	prefix := ""
 619  	if evid {
 620  		prefix = "apparently "
 621  	}
 622  	switch {
 623  	case past && prog && neg:
 624  		return prefix | "wasn't " | v | "ing"
 625  	case past && prog:
 626  		return prefix | "was " | v | "ing"
 627  	case past && neg:
 628  		return prefix | "didn't " | v
 629  	case past:
 630  		return prefix | "did " | v
 631  	case prog && neg:
 632  		return prefix | "isn't " | v | "ing"
 633  	case prog:
 634  		return prefix | "is " | v | "ing"
 635  	case neg:
 636  		return prefix | "don't " | v
 637  	default:
 638  		return prefix | v // polite present, no EN marker
 639  	}
 640  }
 641  
 642  // enOperators maps EN words to the morphstate bits they set.
 643  // These are not content words — they are lattice walk operators.
 644  // bit 4 = tense(past), bit 3 = aspect(progressive), bit 2 = polarity(negative),
 645  // bit 0 = evidentiality(reported).
 646  var enOperators map[string]uint8
 647  
 648  // enProgressiveAuxiliary maps "is/are/am/was/were" to their tense bits.
 649  // Combined with an -ing verb, they set the aspect bit.
 650  var enProgressiveAux map[string]uint8
 651  
 652  // isJAVerb returns true if tok is a verb in the lattice, either as a dictionary
 653  // IsJAVerb exports isJAVerb for use by the propagation command.
 654  func IsJAVerb(tree *lattice.Tree, tok string) bool { return isJAVerb(tree, tok) }
 655  
 656  // form (Bverb) or as a conjugated form whose stem is a Bverb record.
 657  func isJAVerb(tree *lattice.Tree, tok string) bool {
 658  	if jaRecordBranch(tree, tok) == uint8(lattice.Bverb) {
 659  		return true
 660  	}
 661  	for _, stem := range verbStems(tok) {
 662  		if tree.LookupRecIdx(lattice.Bverb, MakeKey(LangJA, 0, stem)) != lattice.NullRec {
 663  			return true
 664  		}
 665  	}
 666  	return false
 667  }
 668  
 669  // inferMorphState estimates the MorphState from a conjugated JA token's suffix.
 670  // Used as fallback when the form isn't in the lattice (verbStems path).
 671  func inferMorphState(tok string) uint8 {
 672  	hs := func(suf string) bool {
 673  		return len(tok) >= len(suf) && tok[len(tok)-len(suf):] == suf
 674  	}
 675  	// Progressive past
 676  	if hs("ていなかった") || hs("でいなかった") { return MorphPastProgNeg }
 677  	if hs("ていました") || hs("でいました") { return MorphPastProgPolite }
 678  	if hs("ていた") || hs("でいた") { return MorphPastProgPlain }
 679  	// Progressive present
 680  	if hs("ていない") || hs("でいない") { return MorphPresProgNeg }
 681  	if hs("ています") || hs("でいます") { return MorphPresProgPolite }
 682  	if hs("ている") || hs("でいる") { return MorphPresProgPlain }
 683  	// Past
 684  	if hs("ませんでした") { return MorphPastNegPolite }
 685  	if hs("なかった") { return MorphPastNegPlain }
 686  	if hs("ました") { return MorphPastAffPolite }
 687  	if hs("そうだ") {
 688  		// reported: check if stem is past
 689  		inner := tok[:len(tok)-len("そうだ")]
 690  		if len(inner) > 0 {
 691  			last := inner[len(inner)-3:]
 692  			if last == "た" || last == "だ" { return MorphPastReported }
 693  		}
 694  		return MorphPresReported
 695  	}
 696  	if hs("た") || hs("だ") { return MorphPastAffPlain }
 697  	// Present negative
 698  	if hs("ません") { return MorphPresNegPolite }
 699  	if hs("ない") { return MorphPresNegPlain }
 700  	// Present polite
 701  	if hs("ます") { return MorphPresAffPolite }
 702  	return MorphPresAffPlain
 703  }
 704  
 705  // verbStems strips common Japanese conjugation suffixes and returns dictionary-
 706  // form candidates to try against the lattice. Longer suffixes checked first.
 707  // Returns nil if no suffix pattern recognized.
 708  func verbStems(tok string) []string {
 709  	if len(tok) == 0 {
 710  		return nil
 711  	}
 712  	hs := func(suf string) bool {
 713  		return len(tok) > len(suf) && tok[len(tok)-len(suf):] == suf
 714  	}
 715  	st := func(suf string) string {
 716  		return tok[:len(tok)-len(suf)]
 717  	}
 718  	// 9-byte (3-char) patterns
 719  	if hs("ている") {
 720  		s := st("ている")
 721  		return []string{s | "る", s | "く"}
 722  	}
 723  	// 6-byte (2-char) patterns — godan sound changes
 724  	if hs("いた") { return []string{st("いた") | "く"} }
 725  	if hs("いだ") { return []string{st("いだ") | "ぐ"} }
 726  	if hs("した") { s := st("した"); return []string{s | "す", s | "する"} }
 727  	if hs("んだ") { s := st("んだ"); return []string{s | "む", s | "ぬ", s | "ぶ"} }
 728  	if hs("った") { s := st("った"); return []string{s | "つ", s | "う", s | "る"} }
 729  	if hs("いて") { return []string{st("いて") | "く"} }
 730  	if hs("いで") { return []string{st("いで") | "ぐ"} }
 731  	if hs("して") { s := st("して"); return []string{s | "す", s | "する"} }
 732  	if hs("んで") { s := st("んで"); return []string{s | "む", s | "ぬ", s | "ぶ"} }
 733  	if hs("って") { s := st("って"); return []string{s | "つ", s | "う", s | "る"} }
 734  	if hs("ない") { s := st("ない"); return []string{s | "る", s | "う"} }
 735  	// 3-byte (1-char) — ichidan plain past only.
 736  	// bare て is a connective te-form (食べて+いる), NOT a standalone verb form;
 737  	// including it causes the tokenizer to split 食べていた as 食べて+い+た.
 738  	if hs("た") { return []string{st("た") | "る"} }
 739  	return nil
 740  }
 741  
 742  // isPureHiragana returns true if every codepoint in s is in U+3040-U+309F (hiragana).
 743  // Particles are always pure hiragana; kanji-containing words are content words.
 744  func isPureHiragana(s string) bool {
 745  	if len(s) == 0 {
 746  		return false
 747  	}
 748  	for i := 0; i < len(s); {
 749  		if i+2 >= len(s) {
 750  			return false
 751  		}
 752  		// Hiragana block: U+3040-U+309F = E3 81 80 – E3 82 9F
 753  		if s[i] != 0xE3 {
 754  			return false
 755  		}
 756  		b1 := s[i+1]
 757  		b2 := s[i+2]
 758  		if b1 == 0x81 && b2 >= 0x80 {
 759  			// U+3040-U+307F ✓
 760  		} else if b1 == 0x82 && b2 <= 0x9F {
 761  			// U+3080-U+309F ✓
 762  		} else {
 763  			return false
 764  		}
 765  		i += 3
 766  	}
 767  	return true
 768  }
 769  
 770  // jaFunctionWord: particles, copulae, and auxiliaries that are structural
 771  // fork labels, not content. Includes entries removed from the lattice by the
 772  // IsFunction() filter at ingest (prt/cop/aux POS codes).
 773  var jaFunctionWord map[string]bool
 774  
 775  var _translateInitDone bool
 776  
 777  func translateInitOnce() {
 778  	if _translateInitDone {
 779  		return
 780  	}
 781  	_translateInitDone = true
 782  
 783  	defaultBranchOrder = [3]uint8{uint8(lattice.Bnoun), uint8(lattice.Bverb), uint8(lattice.Bmodifier)}
 784  
 785  	jaRoleParticle = map[string]uint8{
 786  		"は": jaRoleSubj, "が": jaRoleSubj,
 787  		"を": jaRoleObj,
 788  	}
 789  
 790  	enOperators = map[string]uint8{
 791  		"did":         1 << 4,
 792  		"didn't":      (1 << 4) | (1 << 2),
 793  		"not":         1 << 2,
 794  		"don't":       1 << 2,
 795  		"doesn't":     1 << 2,
 796  		"wasn't":      (1 << 4) | (1 << 3) | (1 << 2),
 797  		"weren't":     (1 << 4) | (1 << 3) | (1 << 2),
 798  		"apparently":  1 << 0,
 799  		"reportedly":  1 << 0,
 800  		"supposedly":  1 << 0,
 801  		"allegedly":   1 << 0,
 802  	}
 803  
 804  	enProgressiveAux = map[string]uint8{
 805  		"is": 0, "are": 0, "am": 0,
 806  		"was": 1 << 4, "were": 1 << 4,
 807  	}
 808  
 809  	jaFunctionWord = map[string]bool{
 810  		"だ": true, "です": true, "でした": true,
 811  		"ない": true, "ぬ": true, "ん": true,
 812  		"ます": true, "ません": true, "ました": true,
 813  		"は": true, "が": true, "を": true,
 814  		"に": true, "で": true, "と": true,
 815  		"も": true, "や": true, "か": true,
 816  		"の": true, "から": true, "まで": true,
 817  		"より": true, "など": true, "ね": true,
 818  		"よ": true, "さ": true, "な": true,
 819  		"わ": true, "ぞ": true, "ぜ": true,
 820  		"て": true, "た": true,
 821  	}
 822  }
 823  
 824  // VerbLemma returns a single-step approximation of the dictionary form for
 825  // a JA verb surface form via verbStems. Used for morph-stats grouping.
 826  func VerbLemma(form string) string {
 827  	stems := verbStems(form)
 828  	if len(stems) > 0 {
 829  		return stems[0]
 830  	}
 831  	return form
 832  }
 833  
 834  func appendUniq(s []string, v string) []string {
 835  	for _, x := range s {
 836  		if x == v {
 837  			return s
 838  		}
 839  	}
 840  	return append(s, v)
 841  }
 842