Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/review/hermitcrab.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ Governs `src/SIL.Machine.Morphology.HermitCrab/**/*.cs`.
whether equivalent analyses can be merged safely. The merge key
(`AnalysisMergeKey`) compares exactly these fields: shape, stratum identity, syntactic
feature structure, realizational feature structure, non-head count, per-rule
unapplication counts, and `FinalTemplateState`. Check a new field against that list.
unapplication counts, `FinalTemplateState`, and `NeedsPartial`. Check a new field against that list.
- Inspect allocations and retained object lifetimes only in changed inner loops. If the
change claims a performance improvement, require a reproducible benchmark or measured
artifact in addition to semantic regression tests.
Expand Down
25 changes: 19 additions & 6 deletions src/SIL.Machine.Morphology.HermitCrab/AnalysisAffixTemplateRule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,12 @@ public IEnumerable<Word> Apply(Word input)
if (_morpher.TraceManager.IsTracing)
_morpher.TraceManager.BeginUnapplyTemplate(_template, input);

// Do not allow a final template to unapply if we don't need to worry about partial rules
// and a non-template was last unapplied.
if (
(!_morpher.HasPartialRules || _morpher.AlwaysEnforceFinalTemplates)
&& input.FinalTemplateState == FinalTemplateState.NonTemplate
// In synthesis a non-template rule follows a final template only if a partial rule applied earlier.
bool afterNonTemplate =
_morpher.TracksFinalTemplateState
&& _template.IsFinal
)
&& input.FinalTemplateState == FinalTemplateState.NonTemplate;
if (afterNonTemplate && _morpher.IsFinalTemplatePrunable(_template, input))
{
if (_morpher.TraceManager.IsTracing)
{
Expand All @@ -69,6 +68,12 @@ public IEnumerable<Word> Apply(Word input)
return Enumerable.Empty<Word>();

Word inWord = input.Clone();
// The prune check above passed, so the word is partial at this template or the analysis fails.
if (afterNonTemplate)
{
inWord.NeedsPartial = true;
inWord.OwedPartialTemplate = _template;
}
inWord.Freeze();

var output = new HashSet<Word>(FreezableEqualityComparer<Word>.Default);
Expand All @@ -77,6 +82,14 @@ public IEnumerable<Word> Apply(Word input)
else
ParallelApplySlots(inWord, output, fired);

// The output with every slot skipped did not unapply the template, so it owes nothing.
if (afterNonTemplate && output.Remove(inWord))
{
Word unchanged = input.Clone();
unchanged.Freeze();
output.Add(unchanged);
}

return output;
}

Expand Down
15 changes: 14 additions & 1 deletion src/SIL.Machine.Morphology.HermitCrab/AnalysisStratumRule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,11 @@ internal IEnumerable<Word> Apply(Word input, ref int alternativeCount)

private IEnumerable<Word> ApplyMorphologicalRules(Word input)
{
if (_morpher.OwesImpossiblePartial(input))
{
_morpher.TraceOwedPartialDropped(input);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FYI: F12. A trace can show one owed-partial drop twice. Apply passes the same input to both ApplyTemplates and ApplyMorphologicalRules, and each one checks OwesImpossiblePartial and calls TraceOwedPartialDropped. So a word that enters a stratum already owing gets two OwedPartialCannotUnapply nodes. Check and trace once in Apply before building mruleOutWords. Unverified: read from the code. ParseWord_OwedPartialDropped_IsTraced asserts only Is.Not.Empty.

yield break;
}
foreach (Word mruleOutWord in _mrulesRule.Apply(input).Distinct(FreezableEqualityComparer<Word>.Default))
{
switch (_stratum.MorphologicalRuleOrder)
Expand All @@ -203,6 +208,11 @@ private IEnumerable<Word> ApplyMorphologicalRules(Word input)

private IEnumerable<Word> ApplyTemplates(Word input)
{
if (_morpher.OwesImpossiblePartial(input))
{
_morpher.TraceOwedPartialDropped(input);
yield break;
}
foreach (Word tempOutWord in _templatesRule.Apply(input).Distinct(FreezableEqualityComparer<Word>.Default))
{
switch (_stratum.MorphologicalRuleOrder)
Expand Down Expand Up @@ -235,6 +245,7 @@ private IEnumerable<Word> ApplyTemplates(Word input)
private readonly int _nonHeadCount;
private readonly IReadOnlyDictionary<IMorphologicalRule, int> _ruleCounts;
private readonly FinalTemplateState _finalTemplateState;
private readonly bool _needsPartial;
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
private readonly int _hashCode;

// Freezes word.SyntacticFeatureStruct, which Word.Freeze leaves unfrozen.
Expand All @@ -253,6 +264,7 @@ public AnalysisMergeKey(Word word)
_nonHeadCount = word.NonHeadCount;
_ruleCounts = word.UnappliedRuleCounts;
_finalTemplateState = word.FinalTemplateState;
_needsPartial = word.NeedsPartial;

_shape.Freeze();
_syntacticFS.Freeze();
Expand All @@ -265,6 +277,7 @@ public AnalysisMergeKey(Word word)
hash = hash * 31 + _realizationalFS.GetFrozenHashCode();
hash = hash * 31 + _nonHeadCount;
hash = hash * 31 + _finalTemplateState.GetHashCode();
hash = hash * 31 + (_needsPartial ? 1 : 0);
if (_ruleCounts != null)
{
int multisetHash = 0;
Expand Down Expand Up @@ -292,7 +305,7 @@ public bool Equals(AnalysisMergeKey other)
|| !_realizationalFS.ValueEquals(other._realizationalFS)
)
return false;
if (_finalTemplateState != other._finalTemplateState)
if (_finalTemplateState != other._finalTemplateState || _needsPartial != other._needsPartial)
return false;
return RuleCountsEqual(_ruleCounts, other._ruleCounts);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
using System.Collections.Generic;
using System.Linq;
using SIL.Machine.FeatureModel;
using SIL.Machine.Morphology.HermitCrab.MorphologicalRules;

namespace SIL.Machine.Morphology.HermitCrab
{
/// <summary>
/// Finds the affix templates that a partial word can reach in synthesis. A word is partial at a template only if a
/// partial affix-process rule that is neither a template-slot nor a clitic rule applied before it (a partial root
/// takes no template), in the template's stratum or an earlier one. Its part of speech is then whatever that rule
/// leaves, changed by any rules applied since. The search over-approximates: it tracks only the part-of-speech
/// feature, treats an unspecified or variable part of speech as every part of speech, ignores application counts,
/// rule order, template gating and every other feature, and lets every rule of a stratum apply any number of times.
/// A template it does not return can therefore never see a partial word.
/// </summary>
internal static class FinalTemplatePartialReachability
{
public static HashSet<AffixTemplate> Compute(Language lang)
{
var result = new HashSet<AffixTemplate>();
SymbolicFeature posFeature = lang.SyntacticFeatureSystem.PartOfSpeechFeature;
HashSet<FeatureSymbol> all =
posFeature == null
? new HashSet<FeatureSymbol>()
: new HashSet<FeatureSymbol>(posFeature.PossibleSymbols);

// Part-of-speech values a partial word may carry on leaving the strata processed so far.
var reach = new HashSet<FeatureSymbol>();
bool anyPartial = false;
foreach (Stratum stratum in lang.Strata) // synthesis order
{
List<IMorphologicalRule> rules = stratum
.MorphologicalRules.Concat(stratum.AffixTemplates.SelectMany(t => t.Slots).SelectMany(s => s.Rules))
.Distinct()
.ToList();

foreach (AffixProcessRule rule in rules.OfType<AffixProcessRule>().Where(IsSynthesisPartial))
{
anyPartial = true;
reach.UnionWith(
Apply(all, all, rule.RequiredSyntacticFeatureStruct, rule.OutSyntacticFeatureStruct)
);
}
if (!anyPartial)
continue;
if (all.Count == 0)
{
// No parts of speech to tell templates apart: every later template is reachable.
result.UnionWith(stratum.AffixTemplates);
continue;
}

// Close the set under every rule of this stratum.
bool changed = true;
while (changed)
{
changed = false;
foreach (IMorphologicalRule rule in rules)
{
if (reach.Count == 0)
break;
IEnumerable<FeatureSymbol> next = ApplyRule(all, reach, rule);
foreach (FeatureSymbol symbol in next.ToList())
changed |= reach.Add(symbol);
}
}

foreach (AffixTemplate template in stratum.AffixTemplates)
{
if (reach.Count == 0)
continue;
HashSet<FeatureSymbol> required = Constraint(all, template.RequiredSyntacticFeatureStruct);
if (required == null || required.Overlaps(reach))
result.Add(template);
}
}
return result;
}

// Synthesis marks a word partial only for a non-template, non-clitic partial rule
// (SynthesisAffixProcessRule), and a slot or clitic rule is exempt from the final-template check.
internal static bool IsSynthesisPartial(AffixProcessRule rule)
{
return rule.IsPartial && !rule.IsTemplateRule && !rule.GetIsCliticRule();
}

private static IEnumerable<FeatureSymbol> ApplyRule(
HashSet<FeatureSymbol> all,
HashSet<FeatureSymbol> input,
IMorphologicalRule rule
)
{
switch (rule)
{
case AffixProcessRule apr:
return Apply(all, input, apr.RequiredSyntacticFeatureStruct, apr.OutSyntacticFeatureStruct);
case CompoundingRule cr:
return Apply(all, input, cr.HeadRequiredSyntacticFeatureStruct, cr.OutSyntacticFeatureStruct);
case RealizationalAffixProcessRule rr:
return Apply(all, input, rr.RequiredSyntacticFeatureStruct, rr.RealizationalFeatureStruct);
default:
// Unknown rule kind: assume it can produce any part of speech.
return all;
}
}

/// <summary>Unify with <paramref name="required"/>, then priority-union <paramref name="output"/>.</summary>
private static IEnumerable<FeatureSymbol> Apply(
HashSet<FeatureSymbol> all,
HashSet<FeatureSymbol> input,
FeatureStruct required,
FeatureStruct output
)
{
HashSet<FeatureSymbol> req = Constraint(all, required);
bool applicable = req == null ? input.Count > 0 : req.Overlaps(input);
if (!applicable)
return Enumerable.Empty<FeatureSymbol>();
HashSet<FeatureSymbol> outPos = Constraint(all, output);
if (outPos != null)
return outPos;
if (req == null)
return input;
return input.Where(req.Contains);
}

/// <summary>The part-of-speech values a feature structure allows, or null if it leaves them open.</summary>
private static HashSet<FeatureSymbol> Constraint(HashSet<FeatureSymbol> all, FeatureStruct fs)
{
if (fs == null)
return null;
if (!fs.TryGetValue(SyntacticFeatureSystem.PartOfSpeechID, out SymbolicFeatureValue value))
return null;
if (value.IsVariable)
return null;
var symbols = new HashSet<FeatureSymbol>(value.Values);
// A value that names no known symbol is treated as unconstrained, to stay conservative.
return symbols.Count == 0 ? null : symbols;
}
}
}
1 change: 1 addition & 0 deletions src/SIL.Machine.Morphology.HermitCrab/ITraceManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ public enum FailureReason
AllomorphNotApplicable,
LexicalLookupFeatures,
UnreachableRequiredSlot,
OwedPartialCannotUnapply,
}

public interface ITraceManager
Expand Down
95 changes: 92 additions & 3 deletions src/SIL.Machine.Morphology.HermitCrab/Morpher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,82 @@ public Morpher(ITraceManager traceManager, Language lang, int maxDegreeOfParalle

_morphemes = new ReadOnlyObservableCollection<Morpheme>(morphemes);
HasPartialRules = GetPartialMorphemes().Any(morpheme => !(morpheme is LexEntry));
if (HasPartialRules)
{
_partialReachableTemplates = FinalTemplatePartialReachability.Compute(lang);
_partialLookAhead = new PartialRuleLookAhead(lang);
// Only a final template can arm the prune, so without one nothing is tracked.
_canPruneFinalTemplates = lang
.Strata.SelectMany(s => s.AffixTemplates)
.Any(t => t.IsFinal && (_partialLookAhead.IsActive || !_partialReachableTemplates.Contains(t)));
_partialRules = lang
.Strata.SelectMany(s =>
s.MorphologicalRules.Concat(
s.AffixTemplates.SelectMany(t => t.Slots).SelectMany(sl => sl.Rules)
)
)
.OfType<AffixProcessRule>()
.Where(FinalTemplatePartialReachability.IsSynthesisPartial)
.Distinct()
.ToList();
}
}

private readonly HashSet<AffixTemplate> _partialReachableTemplates;
private readonly PartialRuleLookAhead _partialLookAhead;
private readonly bool _canPruneFinalTemplates;
private readonly IReadOnlyList<AffixProcessRule> _partialRules;

/// <summary>
/// Traces the drop of an analysis that still owes a partial rule as an unapplied
/// <see cref="FailureReason.OwedPartialCannotUnapply"/> template, with the partial rules as the failure
/// object.
/// </summary>
internal void TraceOwedPartialDropped(Word input)
{
if (_traceManager.IsTracing && input.OwedPartialTemplate != null)
{
_traceManager.EndUnapplyTemplate(
input.OwedPartialTemplate,
input,
false,
FailureReason.OwedPartialCannotUnapply,
_partialRules
);
}
}

/// <summary>
/// Whether analysis records the template state: the prune is on, or some final template can be pruned in a
/// grammar with partial rules. Otherwise the state would only split equivalent analyses.
/// </summary>
internal bool TracksFinalTemplateState =>
!HasPartialRules || AlwaysEnforceFinalTemplates || _canPruneFinalTemplates;

/// <summary>
/// Whether analysis may refuse to unapply a final template that follows a non-template rule. The synthesis
/// derivation this refuses has a non-partial rule after the final template, which is allowed only when the
/// word is partial there: a partial rule applied before the template. A partial rule leaves the analysis
/// state at none, so it never arms this. Templates no partial word can reach are pruned outright, and
/// others when the shape shows that no partial rule can still be unapplied. In a grammar with both partial
/// rules and lexical families this can drop a duplicate analysis that master returns: a family member

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FYI: F13. "a duplicate analysis that master returns" describes the code relative to a branch. After merge, master is this code, so the sentence stops making sense. .claude/skills/code-comments/SKILL.md forbids history in comments. Say what happens now, for example "can return one analysis where a family member that replaces the root would give two". PartialRulePruneTests.cs:7, :33 and :133 have the same wording.

/// that replaces the root is a fresh word that forgets the pending final template. Only a duplicate is
/// lost, never a distinct analysis. FieldWorks never writes a family.
/// </summary>
internal bool IsFinalTemplatePrunable(AffixTemplate template, Word input)
{
if (!HasPartialRules || AlwaysEnforceFinalTemplates)
return true;
return !_partialReachableTemplates.Contains(template) || !_partialLookAhead.PartialRuleMayUnapply(input);
}

/// <summary>
/// Whether the analysis still owes a partial rule that its shape rules out for it and for anything derived
/// from it.
/// </summary>
internal bool OwesImpossiblePartial(Word input)
{
return input.NeedsPartial && !_partialLookAhead.PartialRuleMayUnapply(input);
}

public IEnumerable<Morpheme> GetPartialMorphemes()
Expand Down Expand Up @@ -135,8 +211,9 @@ public bool PruneRequiredSlots
public bool MergeEquivalentAnalyses { get; set; }

/// <summary>
/// True if any morpheme other than a <see cref="LexEntry"/> is partial. Analysis may prune a final
/// template that follows a non-template rule only when this is false or
/// True if any morpheme other than a <see cref="LexEntry"/> is partial. Synthesis lets a non-template rule
/// follow a final template when the word or the rule is partial, so analysis prunes a final template that
/// follows a non-template rule only where no partial word can be involved, unless
/// <see cref="AlwaysEnforceFinalTemplates"/> is set.
/// </summary>
public bool HasPartialRules { get; }
Expand Down Expand Up @@ -234,7 +311,8 @@ public IEnumerable<Word> ParseWord(string word, out object trace, bool guessRoot
{
// Guess roots when there are no results.
List<Word> matches = new List<Word>();
foreach (Word analysisWord in origAnalyses)
// A partial root takes no template, so the slot rule a flagged analysis owes is never applied.
foreach (Word analysisWord in origAnalyses.Where(w => !w.NeedsPartial))
{
var lexicalGuesses = LexicalGuess(analysisWord).Distinct();
foreach (Word synthesisWord in lexicalGuesses)
Expand Down Expand Up @@ -387,6 +465,12 @@ private IEnumerable<Word> SynthesizeSequential(string word, IEnumerable<Word> an
int alternativeCount = 0;
foreach (Word analysisWord in analyses)
{
// No partial rule was unapplied below the final template that followed a non-template rule.
if (analysisWord.NeedsPartial)
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
{
TraceOwedPartialDropped(analysisWord);
continue;
}
foreach (Word synthesisWord in LexicalLookup(analysisWord))
{
foreach (Word alternative in synthesisWord.ExpandAlternatives())
Expand Down Expand Up @@ -420,6 +504,11 @@ private IEnumerable<Word> SynthesizeParallel(string word, ConcurrentQueue<Word>
for (int i = 0; i < range.Item2 - range.Item1; i++)
{
analyses.TryDequeue(out Word analysisWord);
if (analysisWord.NeedsPartial)
{
TraceOwedPartialDropped(analysisWord);
continue;
}
foreach (Word synthesisWord in LexicalLookup(analysisWord))
{
foreach (Word alternative in synthesisWord.ExpandAlternatives())
Expand Down
Loading
Loading