render_en.go raw
1 // Package iskra renderer.
2 package iskra
3
4 // Port of render_en.mx: Set to EN text, and Discourse to EN text.
5 //
6 // Where moxie joins strings with `|` this port joins with `+`. The irregular
7 // table is a direct transcription of enIrregular in lemma_en.mx.
8
9 // RenderENDiscourse renders a full multi-clause Discourse to EN text.
10 // Single-clause case renders identically to RenderEN(d[0].Set).
11 //
12 // Subordinating relations (ClauseIf, ClauseBecause) are emitted as prefixes
13 // on the subordinate clause itself ("if X, Y" - "if" attaches to X). Peer
14 // relations (ClauseAnd, ClauseOr, ClauseBut) emit between adjacent clauses.
15 func RenderENDiscourse(d []Clause) string {
16 if len(d) == 0 {
17 return ""
18 }
19 out := ""
20 for i, c := range d {
21 if i > 0 {
22 // Peer connective derived from THIS clause's Relation (the one
23 // joining it to the prior clause). For subordinators, the prefix
24 // is emitted below instead of here.
25 switch c.Relation {
26 case ClauseAnd:
27 out = out + " and "
28 case ClauseOr:
29 out = out + " or "
30 case ClauseBut:
31 out = out + " but "
32 case ClauseIf, ClauseBecause:
33 out = out + " "
34 default:
35 out = out + " "
36 }
37 }
38 // Subordinating prefix attached to this clause itself.
39 switch c.Relation {
40 case ClauseIf:
41 out = out + "if "
42 case ClauseBecause:
43 out = out + "because "
44 }
45 out = out + RenderEN(c.Set)
46 }
47 return out
48 }
49
50 // RenderEN converts a Set to EN text using SVO order with modifier-aware traversal.
51 //
52 // Two-pass walk:
53 // 1. Classify top-level entries (Head=-1) by Role into SVO groups.
54 // 2. For each emitted top-level entry, prepend its modifiers (entries whose
55 // Head points at this entry's index).
56 //
57 // EN modifier surface forms:
58 //
59 // POSS - possessive determiner directly before head ("my fish", "his book")
60 // ATTR - adjective directly before head ("red car", "small house")
61 func RenderEN(set []SetEntry) string {
62 mods := map[int32][]int32{}
63 var subj, verb, obj, scope, mod, comp, oper []int32
64 var copulas, adjs []int32
65 for i, e := range set {
66 if e.ModKind == MKCop {
67 copulas = append(copulas, int32(i))
68 continue
69 }
70 if e.ModKind == MKAdj {
71 adjs = append(adjs, int32(i))
72 continue
73 }
74 if e.Head >= 0 && int(e.Head) < len(set) {
75 mods[int32(e.Head)] = append(mods[int32(e.Head)], int32(i))
76 continue
77 }
78 switch e.Role {
79 case HistTopic, HistSubject:
80 subj = append(subj, int32(i))
81 case HistVerb:
82 verb = append(verb, int32(i))
83 case HistObject:
84 obj = append(obj, int32(i))
85 case HistScope:
86 scope = append(scope, int32(i))
87 case HistModifier:
88 mod = append(mod, int32(i))
89 case HistComplement:
90 comp = append(comp, int32(i))
91 case HistOperator:
92 oper = append(oper, int32(i))
93 }
94 }
95
96 var parts []string
97
98 // Determine subject atom for copula agreement (am/are/is/was/were).
99 subjAtom := ""
100 subjPlural := false
101 if len(subj) > 0 {
102 s := set[subj[0]]
103 subjAtom = s.Atom
104 subjPlural = s.Morph&MetaNumPlural != 0
105 }
106
107 for _, i := range subj {
108 parts = appendENWithMods(parts, set, i, mods, "")
109 }
110
111 if len(copulas) > 0 {
112 c := set[copulas[0]]
113 parts = appendEN(parts, enCopulaForm(c.Morph))
114 prep := oblRoleToEnPrep(c.OblRole)
115 parts = appendENWithMods(parts, set, copulas[0], mods, prep)
116 for _, ci := range copulas[1:] {
117 cc := set[ci]
118 parts = appendEN(parts, enCopulaForm(cc.Morph))
119 parts = appendENWithMods(parts, set, ci, mods, oblRoleToEnPrep(cc.OblRole))
120 }
121 }
122
123 if len(adjs) > 0 {
124 a := set[adjs[0]]
125 parts = appendEN(parts, enCopulaForm(a.Morph))
126 parts = appendEN(parts, formatENAdj(a))
127 for _, ai := range adjs[1:] {
128 aa := set[ai]
129 parts = appendEN(parts, enCopulaForm(aa.Morph))
130 parts = appendEN(parts, formatENAdj(aa))
131 }
132 }
133
134 objsEmitted := false
135 if len(verb) > 0 {
136 // Emit adverbs that modify this verb BEFORE the verb form.
137 vIdx := verb[0]
138 for _, mIdx := range mods[vIdx] {
139 if set[mIdx].ModKind == MKAdv {
140 parts = appendEN(parts, set[mIdx].Atom)
141 }
142 }
143 v := set[vIdx]
144 switch {
145 case v.Morph&MetaMoodVol != 0:
146 parts = appendEN(parts, "let's")
147 parts = appendEN(parts, v.Atom)
148 case v.Morph&MetaCausative != 0:
149 past := v.Morph&MetaTensePast != 0
150 third := v.Morph&Meta3Sg != 0
151 switch {
152 case past:
153 parts = appendEN(parts, "made")
154 case third:
155 parts = appendEN(parts, "makes")
156 default:
157 parts = appendEN(parts, "make")
158 }
159 for _, i := range obj {
160 parts = appendENWithMods(parts, set, i, mods, "")
161 }
162 parts = appendEN(parts, v.Atom)
163 objsEmitted = true
164 case v.Morph&MetaPassive != 0:
165 parts = appendEN(parts, enSubjCopula(subjAtom, subjPlural, v.Morph))
166 parts = appendEN(parts, formatENVerbPP(v))
167 case v.Morph&MetaAspectProg != 0:
168 parts = appendEN(parts, enSubjCopula(subjAtom, subjPlural, v.Morph))
169 parts = appendEN(parts, formatENVerbProg(v.Atom))
170 default:
171 parts = appendEN(parts, formatENVerb(v))
172 }
173 for _, vi := range verb[1:] {
174 parts = appendEN(parts, formatENVerb(set[vi]))
175 }
176 }
177
178 if !objsEmitted {
179 for _, i := range obj {
180 parts = appendENWithMods(parts, set, i, mods, "")
181 }
182 }
183 for _, i := range scope {
184 prep := oblRoleToEnPrep(set[i].OblRole)
185 if prep == "" {
186 prep = "in"
187 }
188 parts = appendENWithMods(parts, set, i, mods, prep)
189 }
190 for _, i := range mod {
191 prep := oblRoleToEnPrep(set[i].OblRole)
192 if prep == "" {
193 prep = "with"
194 }
195 parts = appendENWithMods(parts, set, i, mods, prep)
196 }
197 for _, i := range comp {
198 parts = appendENWithMods(parts, set, i, mods, "")
199 }
200 for _, i := range oper {
201 prep := oblRoleToEnPrep(set[i].OblRole)
202 if prep == "" {
203 prep = "of"
204 }
205 parts = appendENWithMods(parts, set, i, mods, prep)
206 }
207
208 return joinSpace(parts)
209 }
210
211 // appendENWithMods emits an optional preposition, then this entry's pre-head
212 // modifiers (POSS, ATTR), then the head noun, then any MKCoord peers joined
213 // with "and", then any MKRel relative clauses prefixed with "that".
214 func appendENWithMods(parts []string, set []SetEntry, idx int32, mods map[int32][]int32, prep string) []string {
215 if prep != "" {
216 parts = appendEN(parts, prep)
217 }
218 // Pre-head modifiers: POSS, ATTR. Skip MKCoord/MKAdv/MKRel - those emit
219 // elsewhere relative to the head.
220 for _, mIdx := range mods[idx] {
221 m := set[mIdx]
222 if m.ModKind == MKCoord || m.ModKind == MKAdv || m.ModKind == MKRel {
223 continue
224 }
225 parts = appendEN(parts, m.Atom)
226 }
227 parts = appendEN(parts, formatENNoun(set[idx]))
228 // Post-head coordination peers: "and" + peer-atom for each MKCoord.
229 for _, mIdx := range mods[idx] {
230 if set[mIdx].ModKind != MKCoord {
231 continue
232 }
233 parts = appendEN(parts, "and")
234 parts = appendEN(parts, formatENNoun(set[mIdx]))
235 }
236 // Post-head relative clauses: "that" + verb-form for each MKRel modifier.
237 // Intransitive REL only - the verb is the sole predicate of the sub-clause.
238 for _, mIdx := range mods[idx] {
239 if set[mIdx].ModKind != MKRel {
240 continue
241 }
242 parts = appendEN(parts, "that")
243 parts = appendEN(parts, formatENVerb(set[mIdx]))
244 }
245 return parts
246 }
247
248 // enSubjCopula selects the copula form based on the subject atom and verb morph.
249 // "i" -> am/was, "you"/"we"/"they"/plural -> are/were, others -> is/was.
250 func enSubjCopula(subjAtom string, subjPlural bool, morph uint16) string {
251 past := morph&MetaTensePast != 0
252 switch {
253 case subjAtom == "i":
254 if past {
255 return "was"
256 }
257 return "am"
258 case subjAtom == "you" || subjAtom == "we" || subjAtom == "they" || subjPlural:
259 if past {
260 return "were"
261 }
262 return "are"
263 default:
264 if past {
265 return "was"
266 }
267 return "is"
268 }
269 }
270
271 // enCopulaForm returns the appropriate "be" form for EN copula rendering.
272 // Selects between is/are/was/were based on tense and 3sg morph bits.
273 // Note: EN doesn't have a politeness distinction; MetaFormalityPol is JA-only.
274 func enCopulaForm(morph uint16) string {
275 past := morph&MetaTensePast != 0
276 thirdSg := morph&Meta3Sg != 0
277 switch {
278 case past && thirdSg:
279 return "was"
280 case past:
281 return "were"
282 case thirdSg:
283 return "is"
284 default:
285 return "are"
286 }
287 }
288
289 // oblRoleToEnPrep maps an oblique semantic role to the canonical EN preposition.
290 // This is the cross-language layer: OblRole is language-independent, prep is EN-specific.
291 func oblRoleToEnPrep(or uint8) string {
292 switch or {
293 case ORGoal:
294 return "to"
295 case ORLoc:
296 return "in"
297 case ORSource:
298 return "from"
299 case ORLimit:
300 return "until"
301 case ORInstr:
302 return "with"
303 case ORComit:
304 return "with"
305 case ORBenef:
306 return "for"
307 case ORAgent:
308 return "by"
309 case ORRecip:
310 return "to"
311 case ORPart:
312 return "of"
313 case ORCompare:
314 return "than"
315 }
316 return ""
317 }
318
319 func appendEN(parts []string, w string) []string {
320 if w == "" {
321 return parts
322 }
323 return append(parts, w)
324 }
325
326 func joinSpace(parts []string) string {
327 out := ""
328 for i, p := range parts {
329 if i > 0 {
330 out = out + " "
331 }
332 out = out + p
333 }
334 return out
335 }
336
337 // pronounCase normalizes EN pronoun surface form based on the slot's role.
338 // Subject role -> nominative (i, he, she, we, they); object/oblique roles ->
339 // accusative (me, him, her, us, them). Closed set; non-pronoun atoms pass
340 // through unchanged.
341 func pronounCase(atom string, role int32) string {
342 subjRole := role == HistSubject || role == HistTopic
343 switch atom {
344 case "i", "me":
345 if subjRole {
346 return "i"
347 }
348 return "me"
349 case "he", "him":
350 if subjRole {
351 return "he"
352 }
353 return "him"
354 case "she":
355 if subjRole {
356 return "she"
357 }
358 return "her"
359 case "we", "us":
360 if subjRole {
361 return "we"
362 }
363 return "us"
364 case "they", "them":
365 if subjRole {
366 return "they"
367 }
368 return "them"
369 }
370 return atom
371 }
372
373 // formatENNoun emits "the lemma" or "a lemma" with plural if applicable.
374 func formatENNoun(e SetEntry) string {
375 if e.Atom == "" {
376 return ""
377 }
378 // Untranslated marker: emit verbatim, no determiner or plural suffix.
379 if e.Atom == UntranslatedMarker {
380 return e.Atom
381 }
382 // Cross-language leakage guard: if the atom contains non-ASCII bytes,
383 // the EN-side lookup didn't resolve to an English atom. Don't apply
384 // determiner or plural suffix - that produces nonsense like "雨るs".
385 // Pass the atom through unchanged so the failure is visible upstream.
386 if !isASCIIOnly(e.Atom) {
387 return e.Atom
388 }
389 det := ""
390 if e.Morph&MetaDefDef != 0 {
391 det = "the "
392 }
393 noun := pronounCase(e.Atom, e.Role)
394 if e.Morph&MetaNumPlural != 0 {
395 noun = pluralizeEN(noun)
396 }
397 return det + noun
398 }
399
400 // formatENVerb emits the verb with tense/aspect/3sg suffix as appropriate.
401 func formatENVerb(e SetEntry) string {
402 if e.Atom == "" {
403 return ""
404 }
405 if e.Atom == UntranslatedMarker {
406 return e.Atom
407 }
408 // Cross-language leakage guard: non-ASCII atoms are unresolved JA
409 // fragments; don't apply EN inflection.
410 if !isASCIIOnly(e.Atom) {
411 return e.Atom
412 }
413 // Check irregular table first (reverse lookup).
414 if surface, ok := enIrregularReverse[verbKey(e.Atom, e.Morph)]; ok {
415 return surface
416 }
417 if e.Morph&MetaPolarNeg != 0 {
418 // Emit "not lemma" auxiliary form.
419 if e.Morph&MetaTensePast != 0 {
420 return "did not " + e.Atom
421 }
422 if e.Morph&Meta3Sg != 0 {
423 return "does not " + e.Atom
424 }
425 return "do not " + e.Atom
426 }
427 if e.Morph&MetaTensePast != 0 {
428 return enVerbPast(e.Atom)
429 }
430 if e.Morph&Meta3Sg != 0 {
431 return enVerb3Sg(e.Atom)
432 }
433 return e.Atom
434 }
435
436 // formatENVerbPP returns the past-participle form of a verb for passive voice.
437 // Looks up irregular table with key (lemma, MetaTensePast|MetaPassive) for
438 // PPs that differ from simple-past, then falls back to (lemma, MetaTensePast),
439 // then to regular -ed.
440 func formatENVerbPP(e SetEntry) string {
441 if e.Atom == "" {
442 return ""
443 }
444 if surface, ok := enIrregularReverse[verbKey(e.Atom, MetaTensePast|MetaPassive)]; ok {
445 return surface
446 }
447 if surface, ok := enIrregularReverse[verbKey(e.Atom, MetaTensePast)]; ok {
448 return surface
449 }
450 return enVerbPast(e.Atom)
451 }
452
453 func formatENVerbProg(atom string) string {
454 if atom == UntranslatedMarker {
455 return atom
456 }
457 if !isASCIIOnly(atom) {
458 return atom
459 }
460 if surface, ok := enIrregularReverse[verbKey(atom, MetaAspectProg)]; ok {
461 return surface
462 }
463 return enVerbProg(atom)
464 }
465
466 // formatENAdj returns the comparative surface form when MetaCompare is set
467 // (looked up in enIrregularReverse with key (lemma, MetaCompare)), otherwise
468 // returns the lemma atom unchanged.
469 func formatENAdj(e SetEntry) string {
470 if e.Atom == UntranslatedMarker {
471 return e.Atom
472 }
473 if !isASCIIOnly(e.Atom) {
474 return e.Atom
475 }
476 if e.Morph&MetaCompare != 0 {
477 if surface, ok := enIrregularReverse[verbKey(e.Atom, MetaCompare)]; ok {
478 return surface
479 }
480 // Uncomparable / intensifier words: never take -er suffix; prefix
481 // with "more" instead. Catches "verier", "morer", "stiller" etc.
482 if enUncomparable()[e.Atom] {
483 return "more " + e.Atom
484 }
485 return adjComparativeEN(e.Atom)
486 }
487 return e.Atom
488 }
489
490 // enUncomparable lists adjectives/adverbs that don't form -er comparatives.
491 // Most are intensifiers and quantity words that should take "more" instead.
492 func enUncomparable() map[string]bool {
493 return map[string]bool{
494 "very": true, "more": true, "most": true, "much": true, "many": true,
495 "quite": true, "rather": true, "just": true, "only": true,
496 "also": true, "even": true, "still": true, "again": true,
497 "too": true, "so": true, "no": true, "not": true,
498 "a": true, "an": true, "the": true, "this": true, "that": true,
499 "some": true, "any": true, "every": true, "all": true, "each": true,
500 "none": true,
501 }
502 }
503
504 // adjComparativeEN forms the comparative of a regular adjective stem.
505 func adjComparativeEN(stem string) string {
506 if hasSuffix(stem, "e") {
507 return stem + "r"
508 }
509 if hasSuffix(stem, "y") && len(stem) >= 2 && !isVowel(stem[len(stem)-2]) {
510 return stem[:len(stem)-1] + "ier"
511 }
512 // CVC doubling for one-syllable adjectives: big -> bigger, hot -> hotter.
513 if isCVCDoubling(stem) {
514 return stem + string([]byte{stem[len(stem)-1]}) + "er"
515 }
516 return stem + "er"
517 }
518
519 // isASCIIOnly returns true when every byte of s is in the ASCII range.
520 // Used by the EN renderer to detect cross-language atom leakage: if the
521 // looked-up "EN atom" contains non-ASCII bytes, the lattice lookup failed
522 // and we have a JA fragment that should pass through without EN inflection.
523 func isASCIIOnly(s string) bool {
524 for i := 0; i < len(s); i++ {
525 if s[i] >= 0x80 {
526 return false
527 }
528 }
529 return true
530 }
531
532 // isCVCDoubling returns true when stem ends in consonant-vowel-consonant
533 // (the final consonant is not w, x, y - those don't double). Used by the
534 // regular -ing/-ed/-er formers to decide whether to double the final
535 // consonant. Approximation: doesn't check syllable count, so multi-
536 // syllable words like "open" -> "opener" would double wrongly; this rule
537 // is more conservative by only firing on stems of length <= 5.
538 func isCVCDoubling(stem string) bool {
539 n := len(stem)
540 if n < 3 || n > 5 {
541 return false
542 }
543 c1 := stem[n-3]
544 v := stem[n-2]
545 c2 := stem[n-1]
546 if !isVowel(v) {
547 return false
548 }
549 if isVowel(c1) {
550 return false
551 }
552 if isVowel(c2) {
553 return false
554 }
555 // Excluded final consonants: w, x, y (these don't double in standard English).
556 if c2 == 'w' || c2 == 'x' || c2 == 'y' {
557 return false
558 }
559 return true
560 }
561
562 // verbKey builds the (lemma, morph) key: lemma, "|", then the low and high
563 // bytes of morph. The bytes are appended raw, as in the moxie source.
564 func verbKey(lemma string, morph uint16) string {
565 return lemma + "|" + string([]byte{byte(morph), byte(morph >> 8)})
566 }
567
568 // Regular EN conjugation rules (deterministic).
569 func enVerbPast(stem string) string {
570 if hasSuffix(stem, "e") {
571 return stem + "d"
572 }
573 if hasSuffix(stem, "y") && len(stem) >= 2 && !isVowel(stem[len(stem)-2]) {
574 return stem[:len(stem)-1] + "ied"
575 }
576 if isCVCDoubling(stem) {
577 return stem + string([]byte{stem[len(stem)-1]}) + "ed"
578 }
579 return stem + "ed"
580 }
581
582 func enVerb3Sg(stem string) string {
583 if hasSuffix(stem, "s") || hasSuffix(stem, "x") || hasSuffix(stem, "z") ||
584 hasSuffix(stem, "sh") || hasSuffix(stem, "ch") {
585 return stem + "es"
586 }
587 if hasSuffix(stem, "y") && len(stem) >= 2 && !isVowel(stem[len(stem)-2]) {
588 return stem[:len(stem)-1] + "ies"
589 }
590 return stem + "s"
591 }
592
593 func enVerbProg(stem string) string {
594 // -ie verbs become -y + ing: lie -> lying, die -> dying, tie -> tying.
595 if hasSuffix(stem, "ie") {
596 return stem[:len(stem)-2] + "ying"
597 }
598 if hasSuffix(stem, "e") && !hasSuffix(stem, "ee") {
599 return stem[:len(stem)-1] + "ing"
600 }
601 if isCVCDoubling(stem) {
602 return stem + string([]byte{stem[len(stem)-1]}) + "ing"
603 }
604 return stem + "ing"
605 }
606
607 func pluralizeEN(stem string) string {
608 if hasSuffix(stem, "s") || hasSuffix(stem, "x") || hasSuffix(stem, "z") ||
609 hasSuffix(stem, "sh") || hasSuffix(stem, "ch") {
610 return stem + "es"
611 }
612 if hasSuffix(stem, "y") && len(stem) >= 2 && !isVowel(stem[len(stem)-2]) {
613 return stem[:len(stem)-1] + "ies"
614 }
615 return stem + "s"
616 }
617
618 func isVowel(c byte) bool {
619 switch c {
620 case 'a', 'e', 'i', 'o', 'u':
621 return true
622 }
623 return false
624 }
625
626 // enIrregularReverse caches buildEnIrregularReverse. moxie rebuilds the map on
627 // every lookup; the table is a constant, so the result is identical and the
628 // random map iteration order that decides first-seen surface is fixed at the
629 // first call instead of varying per call.
630 var enIrregularReverse = buildEnIrregularReverse()
631
632 // buildEnIrregularReverse builds the (lemma, morph) -> surface form map from enIrregular.
633 func buildEnIrregularReverse() map[string]string {
634 m := map[string]string{}
635 for surface, lr := range enIrregular {
636 key := verbKey(lr.Lemma, lr.Morph)
637 // Prefer first-seen surface for each (lemma, morph) pair.
638 if _, exists := m[key]; !exists {
639 m[key] = surface
640 }
641 }
642 return m
643 }
644
645 // enIrregular is the irregular table in extract_en.go; the reverse
646 // lookup in this file is built from it at init.
647
648 // hasSuffix is the string suffix test the renderers use; moxie has it in
649 // extract.mx as hasSuffix.
650 func hasSuffix(s, suffix string) bool {
651 return len(s) >= len(suffix) && s[len(s)-len(suffix):] == suffix
652 }
653