-
-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathHCLoader.cs
More file actions
2807 lines (2481 loc) · 92.4 KB
/
Copy pathHCLoader.cs
File metadata and controls
2807 lines (2481 loc) · 92.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2015-2025 SIL International
// This software is licensed under the LGPL, version 2.1 or later
// (http://www.gnu.org/licenses/lgpl-2.1.html)
using SIL.Extensions;
using SIL.LCModel;
using SIL.LCModel.Core.Phonology;
using SIL.LCModel.Core.WritingSystems;
using SIL.LCModel.DomainServices;
using SIL.Machine.Annotations;
using SIL.Machine.FeatureModel;
using SIL.Machine.Matching;
using SIL.Machine.Morphology.HermitCrab;
using SIL.Machine.Morphology.HermitCrab.MorphologicalRules;
using SIL.Machine.Morphology.HermitCrab.PhonologicalRules;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Linq;
namespace SIL.FieldWorks.WordWorks.Parser
{
public class HCLoader
{
public static Language Load(LcmCache cache, IHCLoadErrorLogger logger)
{
var loader = new HCLoader(cache, logger);
loader.LoadLanguage();
return loader.m_language;
}
private static readonly string[] VariableNames =
{
"α", "β", "γ", "δ", "ε", "ζ", "η", "θ", "ι", "κ", "λ", "μ", "ν", "ξ",
"ο", "π", "ρ", "σ", "τ", "υ", "φ", "χ", "ψ", "ω"
};
private readonly LcmCache m_cache;
private readonly Dictionary<IMoForm, List<Allomorph>> m_allomorphs;
private readonly Dictionary<IMoMorphSynAnalysis, List<Morpheme>> m_morphemes;
private readonly Dictionary<IMoStemName, StemName> m_stemNames;
private readonly Dictionary<ICmObject, MprFeature> m_mprFeatures;
private Language m_language;
private CharacterDefinitionTable m_table;
private Stratum m_morphophonemic;
private Stratum m_clitic;
private ComplexFeature m_headFeature;
private SymbolicFeature m_posFeature;
private readonly IHCLoadErrorLogger m_logger;
private readonly PhonEnvRecognizer m_envValidator;
private readonly Dictionary<string, IPhNaturalClass> m_naturalClassLookup;
private readonly Dictionary<IPhNaturalClass, NaturalClass> m_naturalClasses;
private readonly Dictionary<IPhTerminalUnit, CharacterDefinition> m_charDefs;
private readonly Dictionary<string, int> m_CompoundRuleLookup;
private readonly bool m_noDefaultCompounding;
private readonly bool m_notOnClitics;
private readonly bool m_acceptUnspecifiedGraphemes;
private readonly string m_strataString;
private readonly IList<IList<string>> m_strata;
private readonly Dictionary<LexEntry, string> m_entryName;
private SimpleContext m_any;
private CharacterDefinition m_null;
private CharacterDefinition m_morphBdry;
private HCLoader(LcmCache cache, IHCLoadErrorLogger logger)
{
m_cache = cache;
m_logger = logger;
m_allomorphs = new Dictionary<IMoForm, List<Allomorph>>();
m_morphemes = new Dictionary<IMoMorphSynAnalysis, List<Morpheme>>();
m_stemNames = new Dictionary<IMoStemName, StemName>();
m_mprFeatures = new Dictionary<ICmObject, MprFeature>();
m_envValidator = new PhonEnvRecognizer(
RemoveDottedCircles(m_cache.LangProject.PhonologicalDataOA.AllPhonemes().ToArray()),
m_cache.LangProject.PhonologicalDataOA.AllNaturalClassAbbrs().ToArray());
m_naturalClassLookup = new Dictionary<string, IPhNaturalClass>();
foreach (IPhNaturalClass nc in m_cache.LanguageProject.PhonologicalDataOA.NaturalClassesOS)
m_naturalClassLookup[nc.Abbreviation.BestAnalysisAlternative.Text] = nc;
XElement parserParamsElem = XElement.Parse(m_cache.LanguageProject.MorphologicalDataOA.ParserParameters);
XElement hcElem = parserParamsElem.Element("HC");
m_noDefaultCompounding = hcElem != null && ((bool?)hcElem.Element("NoDefaultCompounding") ?? false);
m_notOnClitics = hcElem == null || ((bool?)hcElem.Element("NotOnClitics") ?? true);
m_acceptUnspecifiedGraphemes = hcElem != null && ((bool?)hcElem.Element("AcceptUnspecifiedGraphemes") ?? false);
m_strata = new List<IList<string>>();
if (hcElem != null && hcElem.Element("Strata") != null)
{
m_strataString = (string)hcElem.Element("Strata");
m_strata = ParseStrataString(m_strataString);
}
m_CompoundRuleLookup = new Dictionary<string, int>();
XElement cRulesEelem = parserParamsElem.Element("CompoundRules");
if (cRulesEelem != null)
{
foreach (var cRule in cRulesEelem.Elements())
{
int maxApps = Int32.Parse(cRule.Attribute("maxApps").Value);
m_CompoundRuleLookup[cRule.Attribute("guid").Value] = maxApps;
}
}
m_entryName = new Dictionary<LexEntry, string>();
m_naturalClasses = new Dictionary<IPhNaturalClass, NaturalClass>();
m_charDefs = new Dictionary<IPhTerminalUnit, CharacterDefinition>();
}
private IList<IList<string>> ParseStrataString(string strataString)
{
// Tokenize strataString based on commas and parentheses.
string[] tokens = Regex.Split(strataString, @"([(,)])")
.Select(sValue => sValue.Trim())
.Where(s => !string.IsNullOrWhiteSpace(s))
.ToArray();
// Group rules into strata based on parentheses.
IList<IList<string>> strata = new List<IList<string>>();
bool parentheses = false;
foreach (string token in tokens)
{
if (token == "(")
{
parentheses = true;
strata.Add(new List<string>());
}
else if (token == ")")
{
parentheses = false;
}
else if (token != ",")
{
if (!parentheses)
{
strata.Add(new List<string>());
}
strata.Last().Add(token);
}
}
return strata;
}
private string[] RemoveDottedCircles(string[] phonemes)
{
return phonemes.Select(RemoveDottedCircles).ToArray();
}
private string RemoveDottedCircles(string text)
{
string dottedCircle = "\u25CC";
return text?.Replace(dottedCircle, string.Empty);
}
private void LoadLanguage()
{
m_language = new Language { Name = m_cache.ProjectId.Name };
var inflClassesGroup = new MprFeatureGroup { Name = "inflClasses", MatchType = MprFeatureGroupMatchType.Any };
var posSymbols = new List<FeatureSymbol>();
foreach (IPartOfSpeech pos in m_cache.LanguageProject.AllPartsOfSpeech)
{
posSymbols.Add(new FeatureSymbol("pos" + pos.Hvo) { Description = pos.Abbreviation.BestAnalysisAlternative.Text });
foreach (IMoInflClass inflClass in pos.InflectionClassesOC)
LoadInflClassMprFeature(inflClass, inflClassesGroup);
}
if (inflClassesGroup.MprFeatures.Count > 0)
m_language.MprFeatureGroups.Add(inflClassesGroup);
var prodRestrictsGroup = new MprFeatureGroup { Name = "exceptionFeatures", MatchType = MprFeatureGroupMatchType.All };
foreach (ICmPossibility prodRestrict in m_cache.LanguageProject.MorphologicalDataOA.ProdRestrictOA.ReallyReallyAllPossibilities)
LoadMprFeature(prodRestrict, prodRestrictsGroup);
if (prodRestrictsGroup.MprFeatures.Count > 0)
m_language.MprFeatureGroups.Add(prodRestrictsGroup);
var lexEntryInflTypesGroup = new MprFeatureGroup { Name = "lexEntryInflTypes", MatchType = MprFeatureGroupMatchType.All };
foreach (ILexEntryInflType inflType in m_cache.ServiceLocator.GetInstance<ILexEntryInflTypeRepository>().AllInstances())
LoadMprFeature(inflType, lexEntryInflTypesGroup);
if (lexEntryInflTypesGroup.MprFeatures.Count > 0)
m_language.MprFeatureGroups.Add(lexEntryInflTypesGroup);
m_posFeature = m_language.SyntacticFeatureSystem.AddPartsOfSpeech(posSymbols);
m_headFeature = m_language.SyntacticFeatureSystem.AddHeadFeature();
LoadFeatureSystem(m_cache.LanguageProject.MsFeatureSystemOA, m_language.SyntacticFeatureSystem);
LoadFeatureSystem(m_cache.LanguageProject.PhFeatureSystemOA, m_language.PhonologicalFeatureSystem);
var anyNC = new NaturalClass(FeatureStruct.New().Value) { Name = "Any" };
m_language.NaturalClasses.Add(anyNC);
m_any = new SimpleContext(anyNC, Enumerable.Empty<SymbolicFeatureValue>());
LoadCharacterDefinitionTable(m_cache.LanguageProject.PhonologicalDataOA.PhonemeSetsOS[0]);
foreach (IMoStemName stemName in m_cache.ServiceLocator.GetInstance<IMoStemNameRepository>().AllInstances())
{
var pos = stemName.OwnerOfClass<IPartOfSpeech>();
var regions = new List<FeatureStruct>();
foreach (IFsFeatStruc fs in stemName.RegionsOC.Where(fs => !fs.IsEmpty))
{
var hcFS = new FeatureStruct();
hcFS.AddValue(m_headFeature, LoadFeatureStruct(fs, m_language.SyntacticFeatureSystem));
hcFS.AddValue(m_posFeature, LoadAllPartsOfSpeech(pos));
hcFS.Freeze();
regions.Add(hcFS);
}
if (regions.Count > 0)
{
var hcStemName = new StemName(regions) { Name = stemName.Name.BestAnalysisAlternative.Text };
m_stemNames[stemName] = hcStemName;
m_language.StemNames.Add(hcStemName);
}
}
m_morphophonemic = new Stratum(m_table) { Name = "Morphology", MorphologicalRuleOrder = MorphologicalRuleOrder.Unordered };
m_language.Strata.Add(m_morphophonemic);
m_clitic = new Stratum(m_table) { Name = "Clitics", MorphologicalRuleOrder = MorphologicalRuleOrder.Unordered };
m_language.Strata.Add(m_clitic);
m_language.Strata.Add(new Stratum(m_table) { Name = "Surface" });
if (m_cache.LanguageProject.MorphologicalDataOA.CompoundRulesOS.Count == 0 && !m_noDefaultCompounding)
{
m_morphophonemic.MorphologicalRules.AddRange(DefaultCompoundingRules());
}
else
{
foreach (IMoCompoundRule compoundRule in m_cache.LanguageProject.MorphologicalDataOA.CompoundRulesOS.Where(r => !r.Disabled))
{
switch (compoundRule.ClassID)
{
case MoEndoCompoundTags.kClassId:
m_morphophonemic.MorphologicalRules.Add(LoadEndoCompoundingRule((IMoEndoCompound)compoundRule));
break;
case MoExoCompoundTags.kClassId:
m_morphophonemic.MorphologicalRules.AddRange(LoadExoCompoundingRule((IMoExoCompound)compoundRule));
break;
}
}
}
foreach (ILexEntry entry in m_cache.LanguageProject.LexDbOA.Entries)
{
var stemAllos = new List<IMoStemAllomorph>();
var cliticStemAllos = new List<IMoStemAllomorph>();
var affixAllos = new List<IMoForm>();
var cliticAffixAllos = new List<IMoForm>();
foreach (IMoForm form in entry.AlternateFormsOS.Concat(entry.LexemeFormOA))
{
if (form == null)
continue;
if (IsValidLexEntryForm(form))
{
if (IsCliticType(form.MorphTypeRA))
cliticStemAllos.Add((IMoStemAllomorph)form);
else
stemAllos.Add((IMoStemAllomorph)form);
}
if (IsValidRuleForm(form))
{
if (IsCliticType(form.MorphTypeRA))
cliticAffixAllos.Add(form);
else
affixAllos.Add(form);
}
}
if (stemAllos.Count > 0)
LoadLexEntries(m_morphophonemic, entry, stemAllos);
if (cliticStemAllos.Count > 0)
LoadLexEntries(m_clitic, entry, cliticStemAllos);
if (affixAllos.Count > 0)
LoadMorphologicalRules(m_morphophonemic, entry, affixAllos);
if (cliticAffixAllos.Count > 0)
LoadMorphologicalRules(m_clitic, entry, cliticAffixAllos);
}
foreach (IMoInflAffixTemplate template in m_cache.ServiceLocator.GetInstance<IMoInflAffixTemplateRepository>().AllInstances().Where(t => !t.Disabled))
{
IMoInflAffixSlot[] slots = template.SuffixSlotsRS.Concat(template.PrefixSlotsRS.Reverse()).Where(s => s.Affixes.Any(msa => m_morphemes.ContainsKey(msa))).ToArray();
if (slots.Length > 0)
m_morphophonemic.AffixTemplates.Add(LoadAffixTemplate(template, slots));
}
foreach (IPhSegmentRule prule in m_cache.LanguageProject.PhonologicalDataOA.PhonRulesOS.Where(r => !r.Disabled).OrderBy(r => r.OrderNumber))
{
switch (prule.ClassID)
{
case PhRegularRuleTags.kClassId:
var regRule = (IPhRegularRule)prule;
if (regRule.StrucDescOS.Count > 0 || regRule.RightHandSidesOS.Any(rhs => rhs.StrucChangeOS.Count > 0))
{
RewriteRule hcRegRule = LoadRewriteRule(regRule);
if (hcRegRule == null)
continue;
// Choose which stratum the phonological rules apply on.
if (!m_notOnClitics)
m_clitic.PhonologicalRules.Add(hcRegRule);
else
m_morphophonemic.PhonologicalRules.Add(hcRegRule);
m_language.PhonologicalRules.Add(hcRegRule);
}
break;
case PhMetathesisRuleTags.kClassId:
var metaRule = (IPhMetathesisRule)prule;
if (metaRule.LeftSwitchIndex != -1 && metaRule.RightSwitchIndex != -1)
{
MetathesisRule hcMetaRule = LoadMetathesisRule(metaRule);
// Choose which stratum the phonological rules apply on.
if (!m_notOnClitics)
m_clitic.PhonologicalRules.Add(hcMetaRule);
else
m_morphophonemic.PhonologicalRules.Add(hcMetaRule);
m_language.PhonologicalRules.Add(hcMetaRule);
}
break;
}
}
m_language.NaturalClasses.AddRange(m_naturalClasses.Values.Where(nc => nc != null));
foreach (IMoAlloAdhocProhib alloAdhocProhib in m_cache.ServiceLocator.GetInstance<IMoAlloAdhocProhibRepository>().AllInstances()
.Where(a => !a.Disabled && a.FirstAllomorphRA != null && a.RestOfAllosRS.Count > 0))
{
LoadAllomorphCoOccurrenceRules(alloAdhocProhib);
}
foreach (IMoMorphAdhocProhib morphAdhocProhib in m_cache.ServiceLocator.GetInstance<IMoMorphAdhocProhibRepository>().AllInstances()
.Where(a => !a.Disabled && a.FirstMorphemeRA != null && a.RestOfMorphsRS.Count > 0))
{
LoadMorphemeCoOccurrenceRules(morphAdhocProhib);
}
if (m_strata.Count > 0)
{
CreateStrata();
}
}
private void CreateStrata()
{
// Replace the default strata of m_morphophonemics and m_clitic with the user-defined strata.
// The phonological rules are stored in m_morphophonemics unless NotOnClitics is false.
Stratum cliticsStratum = null;
Stratum compoundRulesStratum = null;
Stratum morphologyStratum = null;
Stratum phonologyStratum = null;
Stratum templateStratum = null;
foreach (IList<string> stratumRules in m_strata)
{
if (stratumRules.Count == 0)
{
continue;
}
Stratum stratum = new Stratum(m_table) { Name = stratumRules[0], MorphologicalRuleOrder = MorphologicalRuleOrder.Unordered };
// m_clitic should always be last.
int cliticIndex = m_language.Strata.IndexOf(m_clitic);
m_language.Strata.Insert(cliticIndex, stratum);
foreach (string rule in stratumRules)
{
// Save predefined classes for later.
switch (rule)
{
case "Clitics":
cliticsStratum = stratum;
break;
case "CompoundRules":
compoundRulesStratum = stratum;
break;
case "Morphology":
morphologyStratum = stratum;
break;
case "Phonology":
phonologyStratum = stratum;
break;
case "Templates":
templateStratum = stratum;
break;
default:
{
// Move the given rule to stratum.
bool found = false;
if (MoveRule(rule, m_morphophonemic, stratum))
found = true;
if (MoveRule(rule, m_clitic, stratum))
found = true;
if (!found)
m_logger.InvalidStrata(m_strataString, "Unknown rule in Strata: " + rule + ".");
break;
}
}
}
}
// Process phonology before cliticsStratum and morphologyStratum.
if (phonologyStratum != null)
{
// Move remaining phonological rules to phonologyStratum.
phonologyStratum.PhonologicalRules.AddRange(m_morphophonemic.PhonologicalRules);
phonologyStratum.PhonologicalRules.AddRange(m_clitic.PhonologicalRules);
m_morphophonemic.PhonologicalRules.Clear();
m_clitic.PhonologicalRules.Clear();
}
else
{
// Move remaining phonological rules just before clitic stratum.
int cliticIndex = m_language.Strata.IndexOf(m_clitic);
if (cliticIndex > 1)
{
m_language.Strata[cliticIndex - 1].PhonologicalRules.AddRange(m_morphophonemic.PhonologicalRules);
m_morphophonemic.PhonologicalRules.Clear();
}
}
if (compoundRulesStratum != null)
{
// Move remaining compound rules to compoundRulesStratum.
foreach (IMorphologicalRule rule in m_morphophonemic.MorphologicalRules.ToList())
{
if (rule is CompoundingRule)
{
compoundRulesStratum.MorphologicalRules.Add(rule);
m_morphophonemic.MorphologicalRules.Remove(rule);
}
}
}
if (templateStratum != null)
{
// Move remaining templates to templateStratum.
templateStratum.AffixTemplates.AddRange(m_morphophonemic.AffixTemplates);
m_morphophonemic.AffixTemplates.Clear();
}
if (cliticsStratum != null)
{
// Replace m_clitic with cliticsStratum.
MoveRules(m_clitic, cliticsStratum);
}
// Process morphology last.
if (morphologyStratum != null)
{
MoveRules(m_morphophonemic, morphologyStratum);
}
// Remove empty strata.
foreach (Stratum stratum in m_language.Strata.ToList())
{
if (stratum.Entries.Count == 0 &&
stratum.AffixTemplates.Count == 0 &&
stratum.MorphologicalRules.Count == 0 &&
stratum.PhonologicalRules.Count == 0)
{
m_language.Strata.Remove(stratum);
}
}
}
void MoveRules(Stratum source, Stratum target)
{
target.AffixTemplates.AddRange(source.AffixTemplates);
target.Entries.AddRange(source.Entries);
target.MorphologicalRules.AddRange(source.MorphologicalRules);
target.PhonologicalRules.AddRange(source.PhonologicalRules);
m_language.Strata.Remove(source);
}
private bool MoveRule(string ruleName, Stratum source, Stratum target)
{
bool found = false;
found |= MoveMatchingItems(source.Entries, target.Entries, entry => m_entryName[entry] == ruleName);
found |= MoveMatchingItems(source.MorphologicalRules, target.MorphologicalRules, rule => rule.Name == ruleName);
found |= MoveMatchingItems(source.PhonologicalRules, target.PhonologicalRules, rule => rule.Name == ruleName);
found |= MoveMatchingItems(source.AffixTemplates, target.AffixTemplates, rule => rule.Name == ruleName);
return found;
}
private bool MoveMatchingItems<T>(ICollection<T> source, ICollection<T> target, Func<T, bool> filterFunction)
{
var itemsToMove = source.Where(filterFunction).ToList();
if (itemsToMove.Count == 0) return false;
foreach (var item in itemsToMove)
{
target.Add(item);
source.Remove(item);
}
return true;
}
private void LoadInflClassMprFeature(IMoInflClass inflClass, MprFeatureGroup inflClassesGroup)
{
LoadMprFeature(inflClass, inflClassesGroup);
foreach (IMoInflClass subclass in inflClass.SubclassesOC)
LoadInflClassMprFeature(subclass, inflClassesGroup);
}
private bool HasValidRuleForm(ILexEntry entry)
{
if (entry.IsCircumfix() && entry.LexemeFormOA is IMoAffixAllomorph)
{
bool hasPrefix = false, hasSuffix = false;
foreach (IMoForm form in entry.AlternateFormsOS.Where(IsValidRuleForm))
{
if (form.MorphTypeRA.Guid == MoMorphTypeTags.kguidMorphPrefix)
hasPrefix = true;
else if (form.MorphTypeRA.Guid == MoMorphTypeTags.kguidMorphSuffix)
hasSuffix = true;
if (hasPrefix && hasSuffix)
return true;
}
return false;
}
return entry.AllAllomorphs.Any(IsValidRuleForm);
}
private bool IsValidRuleForm(IMoForm form)
{
var affixProcess = form as IMoAffixProcess;
if (affixProcess != null)
return affixProcess.InputOS.Count > 1 || affixProcess.OutputOS.Count > 1;
string formStr = RemoveDottedCircles(form.Form.VernacularDefaultWritingSystem.Text);
if (form.IsAbstract || string.IsNullOrEmpty(formStr))
return false;
if (form.MorphTypeRA != null)
{
switch (form.MorphTypeRA.Guid.ToString())
{
case MoMorphTypeTags.kMorphProclitic:
case MoMorphTypeTags.kMorphEnclitic:
return true;
case MoMorphTypeTags.kMorphPrefix:
case MoMorphTypeTags.kMorphPrefixingInterfix:
case MoMorphTypeTags.kMorphSuffix:
case MoMorphTypeTags.kMorphSuffixingInterfix:
if (formStr.Contains("[") && !formStr.Contains("[...]"))
return ((IMoAffixAllomorph)form).PhoneEnvRC.Any(env => IsValidEnvironment(env.StringRepresentation.Text));
return true;
case MoMorphTypeTags.kMorphInfix:
case MoMorphTypeTags.kMorphInfixingInterfix:
return ((IMoAffixAllomorph)form).PositionRS.Any(env => IsValidEnvironment(env.StringRepresentation.Text));
}
}
return false;
}
private void LoadMprFeature(ICmObject obj, MprFeatureGroup group)
{
var feat = new MprFeature { Name = obj.ShortName };
group.MprFeatures.Add(feat);
m_mprFeatures[obj] = feat;
m_language.MprFeatures.Add(feat);
}
private bool IsValidLexEntryForm(IMoForm form)
{
if (!(form is IMoStemAllomorph))
return false;
string formStr = RemoveDottedCircles(form.Form.VernacularDefaultWritingSystem.Text);
if (form.IsAbstract || string.IsNullOrEmpty(formStr))
return false;
return IsStemType(form.MorphTypeRA) || IsCliticType(form.MorphTypeRA);
}
private static bool IsStemType(IMoMorphType type)
{
if (type == null)
return false;
switch (type.Guid.ToString())
{
case MoMorphTypeTags.kMorphRoot:
case MoMorphTypeTags.kMorphStem:
case MoMorphTypeTags.kMorphBoundRoot:
case MoMorphTypeTags.kMorphBoundStem:
case MoMorphTypeTags.kMorphPhrase:
return true;
}
return false;
}
private static bool IsCliticType(IMoMorphType type)
{
if (type == null)
return false;
switch (type.Guid.ToString())
{
case MoMorphTypeTags.kMorphClitic:
case MoMorphTypeTags.kMorphEnclitic:
case MoMorphTypeTags.kMorphProclitic:
case MoMorphTypeTags.kMorphParticle:
return true;
}
return false;
}
private void LoadLexEntries(Stratum stratum, ILexEntry entry, IList<IMoStemAllomorph> allos)
{
if (entry.SensesOS.Count == 0)
{
foreach (ILexEntryRef lexEntryRef in entry.EntryRefsOS)
{
foreach (ILexEntryInflType inflType in GetInflTypes(lexEntryRef))
{
foreach (ICmObject component in lexEntryRef.ComponentLexemesRS)
{
var mainEntry = component as ILexEntry;
if (mainEntry != null)
{
foreach (IMoStemMsa msa in mainEntry.MorphoSyntaxAnalysesOC.OfType<IMoStemMsa>())
LoadLexEntryOfVariant(stratum, inflType, msa, allos, entry.ShortName);
}
else
{
ILexSense sense = (ILexSense)component;
LoadLexEntryOfVariant(stratum, inflType, (IMoStemMsa)sense.MorphoSyntaxAnalysisRA, allos, entry.ShortName);
}
}
}
}
}
foreach (IMoStemMsa msa in entry.MorphoSyntaxAnalysesOC.OfType<IMoStemMsa>())
LoadLexEntry(stratum, msa, allos, entry.ShortName);
}
private IEnumerable<ILexEntryInflType> GetInflTypes(ILexEntryRef lexEntryRef)
{
if (lexEntryRef.VariantEntryTypesRS.Count == 0)
{
yield return null;
yield break;
}
bool normalTypeFound = false;
foreach (ILexEntryType type in lexEntryRef.VariantEntryTypesRS)
{
var inflType = type as ILexEntryInflType;
if (inflType != null)
{
yield return inflType;
}
else if (!normalTypeFound)
{
yield return null;
normalTypeFound = true;
}
}
}
private void AddEntry(Stratum stratum, LexEntry hcEntry, IMoMorphSynAnalysis msa, string name)
{
if (hcEntry.Allomorphs.Count > 0)
{
stratum.Entries.Add(hcEntry);
m_entryName[hcEntry] = name;
m_morphemes.GetOrCreate(msa, () => new List<Morpheme>()).Add(hcEntry);
}
}
private void LoadLexEntry(Stratum stratum, IMoStemMsa msa, IList<IMoStemAllomorph> allos, string name)
{
var hcEntry = new LexEntry();
IMoInflClass inflClass = GetInflClass(msa);
if (inflClass != null)
hcEntry.MprFeatures.Add(m_mprFeatures[inflClass]);
foreach (ICmPossibility prodRestrict in msa.ProdRestrictRC)
hcEntry.MprFeatures.Add(m_mprFeatures[prodRestrict]);
hcEntry.Gloss = GetGloss(msa);
var fs = new FeatureStruct();
if (msa.PartOfSpeechRA != null)
fs.AddValue(m_posFeature, m_posFeature.PossibleSymbols["pos" + msa.PartOfSpeechRA.Hvo]);
else
hcEntry.IsPartial = true;
if (msa.MsFeaturesOA != null && !msa.MsFeaturesOA.IsEmpty)
fs.AddValue(m_headFeature, LoadFeatureStruct(msa.MsFeaturesOA, m_language.SyntacticFeatureSystem));
fs.Freeze();
hcEntry.SyntacticFeatureStruct = fs;
hcEntry.Properties[HCParser.MsaID] = msa.Hvo;
foreach (IMoStemAllomorph allo in allos)
{
try
{
RootAllomorph hcAllo = LoadRootAllomorph(allo, msa);
hcEntry.Allomorphs.Add(hcAllo);
m_allomorphs.GetOrCreate(allo, () => new List<Allomorph>()).Add(hcAllo);
}
catch (InvalidShapeException ise)
{
m_logger.InvalidShape(ise.String, ise.Position, msa);
}
}
AddEntry(stratum, hcEntry, msa, name);
}
private void LoadLexEntryOfVariant(Stratum stratum, ILexEntryInflType inflType, IMoStemMsa msa, IList<IMoStemAllomorph> allos, string name)
{
var hcEntry = new LexEntry();
IMoInflClass inflClass = GetInflClass(msa);
if (inflClass != null)
hcEntry.MprFeatures.Add(m_mprFeatures[inflClass]);
foreach (ICmPossibility prodRestrict in msa.ProdRestrictRC)
hcEntry.MprFeatures.Add(m_mprFeatures[prodRestrict]);
// TODO: irregularly inflected forms should be handled by rule blocking in HC
if (inflType != null)
hcEntry.MprFeatures.Add(m_mprFeatures[inflType]);
var glossSB = new StringBuilder();
if (inflType != null)
{
string prepend = inflType.GlossPrepend.BestAnalysisAlternative.Text;
if (prepend != "***")
glossSB.Append(prepend);
}
glossSB.Append(GetGloss(msa));
if (inflType != null)
{
string append = inflType.GlossAppend.BestAnalysisAlternative.Text;
if (append != "***")
glossSB.Append(append);
}
hcEntry.Gloss = glossSB.ToString();
var fs = new FeatureStruct();
if (msa.PartOfSpeechRA != null)
fs.AddValue(m_posFeature, m_posFeature.PossibleSymbols["pos" + msa.PartOfSpeechRA.Hvo]);
else
hcEntry.IsPartial = true;
FeatureStruct headFS = null;
if (msa.MsFeaturesOA != null && !msa.MsFeaturesOA.IsEmpty)
headFS = LoadFeatureStruct(msa.MsFeaturesOA, m_language.SyntacticFeatureSystem);
if (inflType != null)
{
if (inflType.InflFeatsOA != null && !inflType.InflFeatsOA.IsEmpty)
{
FeatureStruct inflFS = LoadFeatureStruct(inflType.InflFeatsOA, m_language.SyntacticFeatureSystem);
if (headFS == null)
headFS = inflFS;
else
headFS.Add(inflFS);
}
}
if (headFS != null)
fs.AddValue(m_headFeature, headFS);
fs.Freeze();
hcEntry.SyntacticFeatureStruct = fs;
hcEntry.Properties[HCParser.MsaID] = msa.Hvo;
if (inflType != null)
hcEntry.Properties[HCParser.InflTypeID] = inflType.Hvo;
foreach (IMoStemAllomorph allo in allos)
{
try
{
RootAllomorph hcAllo = LoadRootAllomorph(allo, msa);
hcEntry.Allomorphs.Add(hcAllo);
m_allomorphs.GetOrCreate(allo, () => new List<Allomorph>()).Add(hcAllo);
}
catch (InvalidShapeException ise)
{
m_logger.InvalidShape(ise.String, ise.Position, msa);
}
}
AddEntry(stratum, hcEntry, msa, name);
}
private RootAllomorph LoadRootAllomorph(IMoStemAllomorph allo, IMoMorphSynAnalysis msa)
{
string form = FormatForm(RemoveDottedCircles(allo.Form.VernacularDefaultWritingSystem.Text));
Shape shape = Segment(form);
var hcAllo = new RootAllomorph(new Segments(m_table, form, shape));
foreach (IPhEnvironment env in allo.PhoneEnvRC)
{
string error;
if (IsValidEnvironment(env.StringRepresentation.Text, out error))
{
Tuple<string, string> contexts = SplitEnvironment(env);
hcAllo.Environments.Add(new AllomorphEnvironment(ConstraintType.Require, LoadEnvironmentPattern(contexts.Item1, true),
LoadEnvironmentPattern(contexts.Item2, false))
{ Name = env.StringRepresentation.Text });
}
else
{
m_logger.InvalidEnvironment(allo, env, error, msa);
}
}
StemName hcStemName;
if (allo.StemNameRA != null && m_stemNames.TryGetValue(allo.StemNameRA, out hcStemName))
hcAllo.StemName = hcStemName;
switch (allo.MorphTypeRA.Guid.ToString())
{
case MoMorphTypeTags.kMorphBoundRoot:
case MoMorphTypeTags.kMorphBoundStem:
hcAllo.IsBound = true;
break;
}
hcAllo.Properties[HCParser.FormID] = allo.Hvo;
return hcAllo;
}
private void LoadMorphologicalRules(Stratum stratum, ILexEntry entry, IList<IMoForm> allos)
{
if (!HasValidRuleForm(entry))
return;
if (entry.SensesOS.Count == 0)
{
foreach (ILexEntryRef lexEntryRef in entry.EntryRefsOS)
{
foreach (ICmObject component in lexEntryRef.ComponentLexemesRS)
{
var mainEntry = component as ILexEntry;
if (mainEntry != null)
{
foreach (IMoMorphSynAnalysis msa in mainEntry.MorphoSyntaxAnalysesOC)
LoadMorphologicalRule(stratum, entry, allos, msa);
}
else
{
var sense = (ILexSense)component;
LoadMorphologicalRule(stratum, entry, allos, sense.MorphoSyntaxAnalysisRA);
}
}
}
}
foreach (IMoMorphSynAnalysis msa in entry.MorphoSyntaxAnalysesOC)
LoadMorphologicalRule(stratum, entry, allos, msa);
}
private void LoadMorphologicalRule(Stratum stratum, ILexEntry entry, IList<IMoForm> allos, IMoMorphSynAnalysis msa)
{
AffixProcessRule mrule = null;
Stratum s = stratum;
switch (msa.ClassID)
{
case MoDerivAffMsaTags.kClassId:
mrule = LoadDerivAffixProcessRule(entry, (IMoDerivAffMsa)msa, allos);
break;
case MoInflAffMsaTags.kClassId:
var inflMsa = (IMoInflAffMsa)msa;
if (inflMsa.SlotsRC.Count > 0)
s = null;
mrule = LoadInflAffixProcessRule(entry, inflMsa, allos);
break;
case MoUnclassifiedAffixMsaTags.kClassId:
mrule = LoadUnclassifiedAffixProcessRule(entry, (IMoUnclassifiedAffixMsa)msa, allos);
break;
case MoStemMsaTags.kClassId:
mrule = LoadCliticAffixProcessRule(entry, (IMoStemMsa)msa, allos);
break;
}
if (mrule != null)
{
mrule.Gloss = GetGloss(msa);
AddMorphologicalRule(s, mrule, msa);
}
}
private string GetGloss(IMoMorphSynAnalysis msa)
{
ILexSense sense = msa.OwnerOfClass<ILexEntry>().SenseWithMsa(msa);
return sense == null ? null : sense.Gloss.BestAnalysisAlternative.Text;
}
private void AddMorphologicalRule(Stratum stratum, AffixProcessRule rule, IMoMorphSynAnalysis msa)
{
if (rule.Allomorphs.Count > 0)
{
if (stratum != null)
stratum.MorphologicalRules.Add(rule);
m_morphemes.GetOrCreate(msa, () => new List<Morpheme>()).Add(rule);
}
}
private AffixProcessRule LoadDerivAffixProcessRule(ILexEntry entry, IMoDerivAffMsa msa, IList<IMoForm> allos)
{
var mrule = new AffixProcessRule { Name = entry.ShortName };
var requiredFS = new FeatureStruct();
if (msa.FromPartOfSpeechRA != null)
requiredFS.AddValue(m_posFeature, LoadAllPartsOfSpeech(msa.FromPartOfSpeechRA));
if (msa.FromMsFeaturesOA != null && !msa.FromMsFeaturesOA.IsEmpty)
requiredFS.AddValue(m_headFeature, LoadFeatureStruct(msa.FromMsFeaturesOA, m_language.SyntacticFeatureSystem));
requiredFS.Freeze();
mrule.RequiredSyntacticFeatureStruct = requiredFS;
var outFS = new FeatureStruct();
if (msa.ToPartOfSpeechRA != null)
outFS.AddValue(m_posFeature, m_posFeature.PossibleSymbols["pos" + msa.ToPartOfSpeechRA.Hvo]);
if (msa.ToMsFeaturesOA != null && !msa.ToMsFeaturesOA.IsEmpty)
outFS.AddValue(m_headFeature, LoadFeatureStruct(msa.ToMsFeaturesOA, m_language.SyntacticFeatureSystem));
outFS.Freeze();
mrule.OutSyntacticFeatureStruct = outFS;
var requiredMprFeatures = new List<MprFeature>();
if (msa.FromInflectionClassRA != null)
requiredMprFeatures.AddRange(LoadAllInflClasses(msa.FromInflectionClassRA));
foreach (ICmPossibility prodRestrict in msa.FromProdRestrictRC)
requiredMprFeatures.Add(m_mprFeatures[prodRestrict]);
var outMprFeatures = new List<MprFeature>();
if (msa.ToInflectionClassRA != null)
outMprFeatures.Add(m_mprFeatures[msa.ToInflectionClassRA]);
foreach (ICmPossibility prodRestrict in msa.ToProdRestrictRC)
outMprFeatures.Add(m_mprFeatures[prodRestrict]);
StemName hcStemName;
if (msa.FromStemNameRA != null && m_stemNames.TryGetValue(msa.FromStemNameRA, out hcStemName))
mrule.RequiredStemName = hcStemName;
mrule.Properties[HCParser.MsaID] = msa.Hvo;
foreach (AffixProcessAllomorph hcAllo in LoadAffixProcessAllomorphs(msa, allos))
{
hcAllo.RequiredMprFeatures.AddRange(requiredMprFeatures);
hcAllo.OutMprFeatures.AddRange(outMprFeatures);
mrule.Allomorphs.Add(hcAllo);
}
return mrule;
}
private AffixProcessRule LoadInflAffixProcessRule(ILexEntry entry, IMoInflAffMsa msa, IList<IMoForm> allos)
{
// TODO: use realizational affix process rules
var mrule = new AffixProcessRule
{
Name = entry.ShortName,
IsPartial = msa.SlotsRC.Count == 0
};
var requiredFS = new FeatureStruct();
if (msa.PartOfSpeechRA != null)
requiredFS.AddValue(m_posFeature, LoadAllPartsOfSpeech(msa.PartOfSpeechRA));
if (msa.InflFeatsOA != null && !msa.InflFeatsOA.IsEmpty)
requiredFS.AddValue(m_headFeature, LoadFeatureStruct(msa.InflFeatsOA, m_language.SyntacticFeatureSystem));
requiredFS.Freeze();
mrule.RequiredSyntacticFeatureStruct = requiredFS;
var requiredMprFeatures = new List<MprFeature>();
foreach (ICmPossibility prodRestrict in msa.FromProdRestrictRC)
requiredMprFeatures.Add(m_mprFeatures[prodRestrict]);
mrule.Properties[HCParser.MsaID] = msa.Hvo;
foreach (AffixProcessAllomorph hcAllo in LoadAffixProcessAllomorphs(msa, allos))
{
hcAllo.RequiredMprFeatures.AddRange(requiredMprFeatures);
mrule.Allomorphs.Add(hcAllo);
}
return mrule;