FST  openfst-1.7.9
OpenFst Library
replace.h
Go to the documentation of this file.
1 // See www.openfst.org for extensive documentation on this weighted
2 // finite-state transducer library.
3 //
4 // Functions and classes for the recursive replacement of FSTs.
5 
6 #ifndef FST_REPLACE_H_
7 #define FST_REPLACE_H_
8 
9 #include <set>
10 #include <string>
11 #include <unordered_map>
12 #include <utility>
13 #include <vector>
14 
15 #include <fst/types.h>
16 #include <fst/log.h>
17 
18 #include <fst/cache.h>
19 #include <fst/expanded-fst.h>
20 #include <fst/fst-decl.h> // For optional argument declarations.
21 #include <fst/fst.h>
22 #include <fst/matcher.h>
23 #include <fst/replace-util.h>
24 #include <fst/state-table.h>
25 #include <fst/test-properties.h>
26 
27 namespace fst {
28 
29 // Replace state tables have the form:
30 //
31 // template <class Arc, class P>
32 // class ReplaceStateTable {
33 // public:
34 // using Label = typename Arc::Label Label;
35 // using StateId = typename Arc::StateId;
36 //
37 // using PrefixId = P;
38 // using StateTuple = ReplaceStateTuple<StateId, PrefixId>;
39 // using StackPrefix = ReplaceStackPrefix<Label, StateId>;
40 //
41 // // Required constructor.
42 // ReplaceStateTable(
43 // const std::vector<std::pair<Label, const Fst<Arc> *>> &fst_list,
44 // Label root);
45 //
46 // // Required copy constructor that does not copy state.
47 // ReplaceStateTable(const ReplaceStateTable<Arc, PrefixId> &table);
48 //
49 // // Looks up state ID by tuple, adding it if it doesn't exist.
50 // StateId FindState(const StateTuple &tuple);
51 //
52 // // Looks up state tuple by ID.
53 // const StateTuple &Tuple(StateId id) const;
54 //
55 // // Lookus up prefix ID by stack prefix, adding it if it doesn't exist.
56 // PrefixId FindPrefixId(const StackPrefix &stack_prefix);
57 //
58 // // Looks up stack prefix by ID.
59 // const StackPrefix &GetStackPrefix(PrefixId id) const;
60 // };
61 
62 // Tuple that uniquely defines a state in replace.
63 template <class S, class P>
65  using StateId = S;
66  using PrefixId = P;
67 
71 
72  PrefixId prefix_id; // Index in prefix table.
73  StateId fst_id; // Current FST being walked.
74  StateId fst_state; // Current state in FST being walked (not to be
75  // confused with the thse StateId of the combined FST).
76 };
77 
78 // Equality of replace state tuples.
79 template <class StateId, class PrefixId>
82  return x.prefix_id == y.prefix_id && x.fst_id == y.fst_id &&
83  x.fst_state == y.fst_state;
84 }
85 
86 // Functor returning true for tuples corresponding to states in the root FST.
87 template <class StateId, class PrefixId>
89  public:
91  return tuple.prefix_id == 0;
92  }
93 };
94 
95 // Functor for fingerprinting replace state tuples.
96 template <class StateId, class PrefixId>
98  public:
99  explicit ReplaceFingerprint(const std::vector<uint64> *size_array)
100  : size_array_(size_array) {}
101 
103  return tuple.prefix_id * size_array_->back() +
104  size_array_->at(tuple.fst_id - 1) + tuple.fst_state;
105  }
106 
107  private:
108  const std::vector<uint64> *size_array_;
109 };
110 
111 // Useful when the fst_state uniquely define the tuple.
112 template <class StateId, class PrefixId>
114  public:
116  return tuple.fst_state;
117  }
118 };
119 
120 // A generic hash function for replace state tuples.
121 template <typename S, typename P>
122 class ReplaceHash {
123  public:
124  size_t operator()(const ReplaceStateTuple<S, P> &t) const {
125  static constexpr size_t prime0 = 7853;
126  static constexpr size_t prime1 = 7867;
127  return t.prefix_id + t.fst_id * prime0 + t.fst_state * prime1;
128  }
129 };
130 
131 // Container for stack prefix.
132 template <class Label, class StateId>
134  public:
135  struct PrefixTuple {
137  : fst_id(fst_id), nextstate(nextstate) {}
138 
139  Label fst_id;
141  };
142 
144 
146  : prefix_(other.prefix_) {}
147 
148  void Push(StateId fst_id, StateId nextstate) {
149  prefix_.push_back(PrefixTuple(fst_id, nextstate));
150  }
151 
152  void Pop() { prefix_.pop_back(); }
153 
154  const PrefixTuple &Top() const { return prefix_[prefix_.size() - 1]; }
155 
156  size_t Depth() const { return prefix_.size(); }
157 
158  public:
159  std::vector<PrefixTuple> prefix_;
160 };
161 
162 // Equality stack prefix classes.
163 template <class Label, class StateId>
166  if (x.prefix_.size() != y.prefix_.size()) return false;
167  for (size_t i = 0; i < x.prefix_.size(); ++i) {
168  if (x.prefix_[i].fst_id != y.prefix_[i].fst_id ||
169  x.prefix_[i].nextstate != y.prefix_[i].nextstate) {
170  return false;
171  }
172  }
173  return true;
174 }
175 
176 // Hash function for stack prefix to prefix id.
177 template <class Label, class StateId>
179  public:
180  size_t operator()(const ReplaceStackPrefix<Label, StateId> &prefix) const {
181  size_t sum = 0;
182  for (const auto &pair : prefix.prefix_) {
183  static constexpr size_t prime = 7863;
184  sum += pair.fst_id + pair.nextstate * prime;
185  }
186  return sum;
187  }
188 };
189 
190 // Replace state tables.
191 
192 // A two-level state table for replace. Warning: calls CountStates to compute
193 // the number of states of each component FST.
194 template <class Arc, class P = ssize_t>
196  public:
197  using Label = typename Arc::Label;
198  using StateId = typename Arc::StateId;
199 
200  using PrefixId = P;
201 
203  using StateTable =
209  using StackPrefixTable =
212 
214  const std::vector<std::pair<Label, const Fst<Arc> *>> &fst_list,
215  Label root)
216  : root_size_(0) {
217  size_array_.push_back(0);
218  for (const auto &fst_pair : fst_list) {
219  if (fst_pair.first == root) {
220  root_size_ = CountStates(*(fst_pair.second));
221  size_array_.push_back(size_array_.back());
222  } else {
223  size_array_.push_back(size_array_.back() +
224  CountStates(*(fst_pair.second)));
225  }
226  }
227  state_table_.reset(
228  new StateTable(ReplaceRootSelector<StateId, PrefixId>(),
229  ReplaceFstStateFingerprint<StateId, PrefixId>(),
231  root_size_, root_size_ + size_array_.back()));
232  }
233 
236  : root_size_(table.root_size_),
237  size_array_(table.size_array_),
238  prefix_table_(table.prefix_table_) {
239  state_table_.reset(
240  new StateTable(ReplaceRootSelector<StateId, PrefixId>(),
241  ReplaceFstStateFingerprint<StateId, PrefixId>(),
243  root_size_, root_size_ + size_array_.back()));
244  }
245 
246  StateId FindState(const StateTuple &tuple) {
247  return state_table_->FindState(tuple);
248  }
249 
250  const StateTuple &Tuple(StateId id) const { return state_table_->Tuple(id); }
251 
252  PrefixId FindPrefixId(const StackPrefix &prefix) {
253  return prefix_table_.FindId(prefix);
254  }
255 
256  const StackPrefix &GetStackPrefix(PrefixId id) const {
257  return prefix_table_.FindEntry(id);
258  }
259 
260  private:
261  StateId root_size_;
262  std::vector<uint64> size_array_;
263  std::unique_ptr<StateTable> state_table_;
264  StackPrefixTable prefix_table_;
265 };
266 
267 // Default replace state table.
268 template <class Arc, class P /* = size_t */>
270  : public CompactHashStateTable<ReplaceStateTuple<typename Arc::StateId, P>,
271  ReplaceHash<typename Arc::StateId, P>> {
272  public:
273  using Label = typename Arc::Label;
274  using StateId = typename Arc::StateId;
275 
276  using PrefixId = P;
278  using StateTable =
281  using StackPrefixTable =
284 
285  using StateTable::FindState;
286  using StateTable::Tuple;
287 
289  const std::vector<std::pair<Label, const Fst<Arc> *>> &, Label) {}
290 
292  : StateTable(), prefix_table_(table.prefix_table_) {}
293 
294  PrefixId FindPrefixId(const StackPrefix &prefix) {
295  return prefix_table_.FindId(prefix);
296  }
297 
298  const StackPrefix &GetStackPrefix(PrefixId id) const {
299  return prefix_table_.FindEntry(id);
300  }
301 
302  private:
303  StackPrefixTable prefix_table_;
304 };
305 
306 // By default ReplaceFst will copy the input label of the replace arc.
307 // The call_label_type and return_label_type options specify how to manage
308 // the labels of the call arc and the return arc of the replace FST
309 template <class Arc, class StateTable = DefaultReplaceStateTable<Arc>,
310  class CacheStore = DefaultCacheStore<Arc>>
311 struct ReplaceFstOptions : CacheImplOptions<CacheStore> {
312  using Label = typename Arc::Label;
313 
314  // Index of root rule for expansion.
316  // How to label call arc.
318  // How to label return arc.
320  // Specifies output label to put on call arc; if kNoLabel, use existing label
321  // on call arc. Otherwise, use this field as the output label.
322  Label call_output_label = kNoLabel;
323  // Specifies label to put on return arc.
324  Label return_label = 0;
325  // Take ownership of input FSTs?
326  bool take_ownership = false;
327  // Pointer to optional pre-constructed state table.
328  StateTable *state_table = nullptr;
329 
331  Label root = kNoLabel)
332  : CacheImplOptions<CacheStore>(opts), root(root) {}
333 
334  explicit ReplaceFstOptions(const CacheOptions &opts, Label root = kNoLabel)
335  : CacheImplOptions<CacheStore>(opts), root(root) {}
336 
337  // FIXME(kbg): There are too many constructors here. Come up with a consistent
338  // position for call_output_label (probably the very end) so that it is
339  // possible to express all the remaining constructors with a single
340  // default-argument constructor. Also move clients off of the "backwards
341  // compatibility" constructor, for good.
342 
343  explicit ReplaceFstOptions(Label root) : root(root) {}
344 
345  explicit ReplaceFstOptions(Label root, ReplaceLabelType call_label_type,
346  ReplaceLabelType return_label_type,
347  Label return_label)
348  : root(root),
349  call_label_type(call_label_type),
350  return_label_type(return_label_type),
351  return_label(return_label) {}
352 
353  explicit ReplaceFstOptions(Label root, ReplaceLabelType call_label_type,
354  ReplaceLabelType return_label_type,
355  Label call_output_label, Label return_label)
356  : root(root),
357  call_label_type(call_label_type),
358  return_label_type(return_label_type),
359  call_output_label(call_output_label),
360  return_label(return_label) {}
361 
362  explicit ReplaceFstOptions(const ReplaceUtilOptions &opts)
363  : ReplaceFstOptions(opts.root, opts.call_label_type,
364  opts.return_label_type, opts.return_label) {}
365 
367 
368  // For backwards compatibility.
369  ReplaceFstOptions(int64 root, bool epsilon_replace_arc)
370  : root(root),
371  call_label_type(epsilon_replace_arc ? REPLACE_LABEL_NEITHER
373  call_output_label(epsilon_replace_arc ? 0 : kNoLabel) {}
374 };
375 
376 // Forward declaration.
377 template <class Arc, class StateTable, class CacheStore>
379 
380 template <class Arc>
381 using FstList = std::vector<std::pair<typename Arc::Label, const Fst<Arc> *>>;
382 
383 // Returns true if label type on arc results in epsilon input label.
384 inline bool EpsilonOnInput(ReplaceLabelType label_type) {
385  return label_type == REPLACE_LABEL_NEITHER ||
386  label_type == REPLACE_LABEL_OUTPUT;
387 }
388 
389 // Returns true if label type on arc results in epsilon input label.
390 inline bool EpsilonOnOutput(ReplaceLabelType label_type) {
391  return label_type == REPLACE_LABEL_NEITHER ||
392  label_type == REPLACE_LABEL_INPUT;
393 }
394 
395 // Returns true if for either the call or return arc ilabel != olabel.
396 template <class Label>
397 bool ReplaceTransducer(ReplaceLabelType call_label_type,
398  ReplaceLabelType return_label_type,
399  Label call_output_label) {
400  return call_label_type == REPLACE_LABEL_INPUT ||
401  call_label_type == REPLACE_LABEL_OUTPUT ||
402  (call_label_type == REPLACE_LABEL_BOTH &&
403  call_output_label != kNoLabel) ||
404  return_label_type == REPLACE_LABEL_INPUT ||
405  return_label_type == REPLACE_LABEL_OUTPUT;
406 }
407 
408 template <class Arc>
409 uint64 ReplaceFstProperties(typename Arc::Label root_label,
410  const FstList<Arc> &fst_list,
411  ReplaceLabelType call_label_type,
412  ReplaceLabelType return_label_type,
413  typename Arc::Label call_output_label,
414  bool *sorted_and_non_empty) {
415  using Label = typename Arc::Label;
416  std::vector<uint64> inprops;
417  bool all_ilabel_sorted = true;
418  bool all_olabel_sorted = true;
419  bool all_non_empty = true;
420  // All nonterminals are negative?
421  bool all_negative = true;
422  // All nonterminals are positive and form a dense range containing 1?
423  bool dense_range = true;
424  Label root_fst_idx = 0;
425  for (Label i = 0; i < fst_list.size(); ++i) {
426  const auto label = fst_list[i].first;
427  if (label >= 0) all_negative = false;
428  if (label > fst_list.size() || label <= 0) dense_range = false;
429  if (label == root_label) root_fst_idx = i;
430  const auto *fst = fst_list[i].second;
431  if (fst->Start() == kNoStateId) all_non_empty = false;
432  if (!fst->Properties(kILabelSorted, false)) all_ilabel_sorted = false;
433  if (!fst->Properties(kOLabelSorted, false)) all_olabel_sorted = false;
434  inprops.push_back(fst->Properties(kCopyProperties, false));
435  }
436  const auto props = ReplaceProperties(
437  inprops, root_fst_idx, EpsilonOnInput(call_label_type),
438  EpsilonOnInput(return_label_type), EpsilonOnOutput(call_label_type),
439  EpsilonOnOutput(return_label_type),
440  ReplaceTransducer(call_label_type, return_label_type, call_output_label),
441  all_non_empty, all_ilabel_sorted, all_olabel_sorted,
442  all_negative || dense_range);
443  const bool sorted = props & (kILabelSorted | kOLabelSorted);
444  *sorted_and_non_empty = all_non_empty && sorted;
445  return props;
446 }
447 
448 namespace internal {
449 
450 // The replace implementation class supports a dynamic expansion of a recursive
451 // transition network represented as label/FST pairs with dynamic replacable
452 // arcs.
453 template <class Arc, class StateTable, class CacheStore>
455  : public CacheBaseImpl<typename CacheStore::State, CacheStore> {
456  public:
457  using Label = typename Arc::Label;
458  using StateId = typename Arc::StateId;
459  using Weight = typename Arc::Weight;
460 
461  using State = typename CacheStore::State;
463  using PrefixId = typename StateTable::PrefixId;
466  using NonTerminalHash = std::unordered_map<Label, Label>;
467 
468  using FstImpl<Arc>::SetType;
475 
476  using CacheImpl::HasArcs;
477  using CacheImpl::HasFinal;
478  using CacheImpl::HasStart;
479  using CacheImpl::PushArc;
480  using CacheImpl::SetArcs;
481  using CacheImpl::SetFinal;
482  using CacheImpl::SetStart;
483 
484  friend class ReplaceFstMatcher<Arc, StateTable, CacheStore>;
485 
486  ReplaceFstImpl(const FstList<Arc> &fst_list,
488  : CacheImpl(opts),
489  call_label_type_(opts.call_label_type),
490  return_label_type_(opts.return_label_type),
491  call_output_label_(opts.call_output_label),
492  return_label_(opts.return_label),
493  state_table_(opts.state_table ? opts.state_table
494  : new StateTable(fst_list, opts.root)) {
495  SetType("replace");
496  // If the label is epsilon, then all replace label options are equivalent,
497  // so we set the label types to NEITHER for simplicity.
498  if (call_output_label_ == 0) call_label_type_ = REPLACE_LABEL_NEITHER;
499  if (return_label_ == 0) return_label_type_ = REPLACE_LABEL_NEITHER;
500  if (!fst_list.empty()) {
501  SetInputSymbols(fst_list[0].second->InputSymbols());
502  SetOutputSymbols(fst_list[0].second->OutputSymbols());
503  }
504  fst_array_.push_back(nullptr);
505  for (Label i = 0; i < fst_list.size(); ++i) {
506  const auto label = fst_list[i].first;
507  const auto *fst = fst_list[i].second;
508  nonterminal_hash_[label] = fst_array_.size();
509  nonterminal_set_.insert(label);
510  fst_array_.emplace_back(opts.take_ownership ? fst : fst->Copy());
511  if (i) {
512  if (!CompatSymbols(InputSymbols(), fst->InputSymbols())) {
513  FSTERROR() << "ReplaceFstImpl: Input symbols of FST " << i
514  << " do not match input symbols of base FST (0th FST)";
515  SetProperties(kError, kError);
516  }
517  if (!CompatSymbols(OutputSymbols(), fst->OutputSymbols())) {
518  FSTERROR() << "ReplaceFstImpl: Output symbols of FST " << i
519  << " do not match output symbols of base FST (0th FST)";
520  SetProperties(kError, kError);
521  }
522  }
523  }
524  const auto nonterminal = nonterminal_hash_[opts.root];
525  if ((nonterminal == 0) && (fst_array_.size() > 1)) {
526  FSTERROR() << "ReplaceFstImpl: No FST corresponding to root label "
527  << opts.root << " in the input tuple vector";
528  SetProperties(kError, kError);
529  }
530  root_ = (nonterminal > 0) ? nonterminal : 1;
531  bool all_non_empty_and_sorted = false;
532  SetProperties(ReplaceFstProperties(opts.root, fst_list, call_label_type_,
533  return_label_type_, call_output_label_,
534  &all_non_empty_and_sorted));
535  // Enables optional caching as long as sorted and all non-empty.
536  always_cache_ = !all_non_empty_and_sorted;
537  VLOG(2) << "ReplaceFstImpl::ReplaceFstImpl: always_cache = "
538  << (always_cache_ ? "true" : "false");
539  }
540 
542  : CacheImpl(impl),
543  call_label_type_(impl.call_label_type_),
544  return_label_type_(impl.return_label_type_),
545  call_output_label_(impl.call_output_label_),
546  return_label_(impl.return_label_),
547  always_cache_(impl.always_cache_),
548  state_table_(new StateTable(*(impl.state_table_))),
549  nonterminal_set_(impl.nonterminal_set_),
550  nonterminal_hash_(impl.nonterminal_hash_),
551  root_(impl.root_) {
552  SetType("replace");
553  SetProperties(impl.Properties(), kCopyProperties);
554  SetInputSymbols(impl.InputSymbols());
555  SetOutputSymbols(impl.OutputSymbols());
556  fst_array_.reserve(impl.fst_array_.size());
557  fst_array_.emplace_back(nullptr);
558  for (Label i = 1; i < impl.fst_array_.size(); ++i) {
559  fst_array_.emplace_back(impl.fst_array_[i]->Copy(true));
560  }
561  }
562 
563  // Computes the dependency graph of the replace class and returns
564  // true if the dependencies are cyclic. Cyclic dependencies will result
565  // in an un-expandable FST.
566  bool CyclicDependencies() const {
567  const ReplaceUtilOptions opts(root_);
568  ReplaceUtil<Arc> replace_util(fst_array_, nonterminal_hash_, opts);
569  return replace_util.CyclicDependencies();
570  }
571 
573  if (!HasStart()) {
574  if (fst_array_.size() == 1) {
575  SetStart(kNoStateId);
576  return kNoStateId;
577  } else {
578  const auto fst_start = fst_array_[root_]->Start();
579  if (fst_start == kNoStateId) return kNoStateId;
580  const auto prefix = GetPrefixId(StackPrefix());
581  const auto start =
582  state_table_->FindState(StateTuple(prefix, root_, fst_start));
583  SetStart(start);
584  return start;
585  }
586  } else {
587  return CacheImpl::Start();
588  }
589  }
590 
592  if (HasFinal(s)) return CacheImpl::Final(s);
593  const auto &tuple = state_table_->Tuple(s);
594  auto weight = Weight::Zero();
595  if (tuple.prefix_id == 0) {
596  const auto fst_state = tuple.fst_state;
597  weight = fst_array_[tuple.fst_id]->Final(fst_state);
598  }
599  if (always_cache_ || HasArcs(s)) SetFinal(s, weight);
600  return weight;
601  }
602 
603  size_t NumArcs(StateId s) {
604  if (HasArcs(s)) {
605  return CacheImpl::NumArcs(s);
606  } else if (always_cache_) { // If always caching, expands and caches state.
607  Expand(s);
608  return CacheImpl::NumArcs(s);
609  } else { // Otherwise computes the number of arcs without expanding.
610  const auto tuple = state_table_->Tuple(s);
611  if (tuple.fst_state == kNoStateId) return 0;
612  auto num_arcs = fst_array_[tuple.fst_id]->NumArcs(tuple.fst_state);
613  if (ComputeFinalArc(tuple, nullptr)) ++num_arcs;
614  return num_arcs;
615  }
616  }
617 
618  // Returns whether a given label is a non-terminal.
619  bool IsNonTerminal(Label label) const {
620  if (label < *nonterminal_set_.begin() ||
621  label > *nonterminal_set_.rbegin()) {
622  return false;
623  } else {
624  return nonterminal_hash_.count(label);
625  }
626  // TODO(allauzen): be smarter and take advantage of all_dense or
627  // all_negative. Also use this in ComputeArc. This would require changes to
628  // Replace so that recursing into an empty FST lead to a non co-accessible
629  // state instead of deleting the arc as done currently. The current use
630  // correct, since labels are sorted if all_non_empty is true.
631  }
632 
634  if (HasArcs(s)) {
635  return CacheImpl::NumInputEpsilons(s);
636  } else if (always_cache_ || !Properties(kILabelSorted)) {
637  // If always caching or if the number of input epsilons is too expensive
638  // to compute without caching (i.e., not ilabel-sorted), then expands and
639  // caches state.
640  Expand(s);
641  return CacheImpl::NumInputEpsilons(s);
642  } else {
643  // Otherwise, computes the number of input epsilons without caching.
644  const auto tuple = state_table_->Tuple(s);
645  if (tuple.fst_state == kNoStateId) return 0;
646  size_t num = 0;
647  if (!EpsilonOnInput(call_label_type_)) {
648  // If EpsilonOnInput(c) is false, all input epsilon arcs
649  // are also input epsilons arcs in the underlying machine.
650  num = fst_array_[tuple.fst_id]->NumInputEpsilons(tuple.fst_state);
651  } else {
652  // Otherwise, one need to consider that all non-terminal arcs
653  // in the underlying machine also become input epsilon arc.
654  ArcIterator<Fst<Arc>> aiter(*fst_array_[tuple.fst_id], tuple.fst_state);
655  for (; !aiter.Done() && ((aiter.Value().ilabel == 0) ||
656  IsNonTerminal(aiter.Value().olabel));
657  aiter.Next()) {
658  ++num;
659  }
660  }
661  if (EpsilonOnInput(return_label_type_) &&
662  ComputeFinalArc(tuple, nullptr)) {
663  ++num;
664  }
665  return num;
666  }
667  }
668 
670  if (HasArcs(s)) {
672  } else if (always_cache_ || !Properties(kOLabelSorted)) {
673  // If always caching or if the number of output epsilons is too expensive
674  // to compute without caching (i.e., not olabel-sorted), then expands and
675  // caches state.
676  Expand(s);
678  } else {
679  // Otherwise, computes the number of output epsilons without caching.
680  const auto tuple = state_table_->Tuple(s);
681  if (tuple.fst_state == kNoStateId) return 0;
682  size_t num = 0;
683  if (!EpsilonOnOutput(call_label_type_)) {
684  // If EpsilonOnOutput(c) is false, all output epsilon arcs are also
685  // output epsilons arcs in the underlying machine.
686  num = fst_array_[tuple.fst_id]->NumOutputEpsilons(tuple.fst_state);
687  } else {
688  // Otherwise, one need to consider that all non-terminal arcs in the
689  // underlying machine also become output epsilon arc.
690  ArcIterator<Fst<Arc>> aiter(*fst_array_[tuple.fst_id], tuple.fst_state);
691  for (; !aiter.Done() && ((aiter.Value().olabel == 0) ||
692  IsNonTerminal(aiter.Value().olabel));
693  aiter.Next()) {
694  ++num;
695  }
696  }
697  if (EpsilonOnOutput(return_label_type_) &&
698  ComputeFinalArc(tuple, nullptr)) {
699  ++num;
700  }
701  return num;
702  }
703  }
704 
705  uint64 Properties() const override { return Properties(kFstProperties); }
706 
707  // Sets error if found, and returns other FST impl properties.
708  uint64 Properties(uint64 mask) const override {
709  if (mask & kError) {
710  for (Label i = 1; i < fst_array_.size(); ++i) {
711  if (fst_array_[i]->Properties(kError, false)) {
712  SetProperties(kError, kError);
713  }
714  }
715  }
716  return FstImpl<Arc>::Properties(mask);
717  }
718 
719  // Returns the base arc iterator, and if arcs have not been computed yet,
720  // extends and recurses for new arcs.
722  if (!HasArcs(s)) Expand(s);
723  CacheImpl::InitArcIterator(s, data);
724  // TODO(allauzen): Set behaviour of generic iterator.
725  // Warning: ArcIterator<ReplaceFst<A>>::InitCache() relies on current
726  // behaviour.
727  }
728 
729  // Extends current state (walk arcs one level deep).
730  void Expand(StateId s) {
731  const auto tuple = state_table_->Tuple(s);
732  if (tuple.fst_state == kNoStateId) { // Local FST is empty.
733  SetArcs(s);
734  return;
735  }
736  ArcIterator<Fst<Arc>> aiter(*fst_array_[tuple.fst_id], tuple.fst_state);
737  Arc arc;
738  // Creates a final arc when needed.
739  if (ComputeFinalArc(tuple, &arc)) PushArc(s, std::move(arc));
740  // Expands all arcs leaving the state.
741  for (; !aiter.Done(); aiter.Next()) {
742  if (ComputeArc(tuple, aiter.Value(), &arc)) PushArc(s, std::move(arc));
743  }
744  SetArcs(s);
745  }
746 
747  void Expand(StateId s, const StateTuple &tuple,
748  const ArcIteratorData<Arc> &data) {
749  if (tuple.fst_state == kNoStateId) { // Local FST is empty.
750  SetArcs(s);
751  return;
752  }
753  ArcIterator<Fst<Arc>> aiter(data);
754  Arc arc;
755  // Creates a final arc when needed.
756  if (ComputeFinalArc(tuple, &arc)) AddArc(s, arc);
757  // Expands all arcs leaving the state.
758  for (; !aiter.Done(); aiter.Next()) {
759  if (ComputeArc(tuple, aiter.Value(), &arc)) AddArc(s, arc);
760  }
761  SetArcs(s);
762  }
763 
764  // If acpp is null, only returns true if a final arcp is required, but does
765  // not actually compute it.
766  bool ComputeFinalArc(const StateTuple &tuple, Arc *arcp,
767  uint8 flags = kArcValueFlags) {
768  const auto fst_state = tuple.fst_state;
769  if (fst_state == kNoStateId) return false;
770  // If state is final, pops the stack.
771  if (fst_array_[tuple.fst_id]->Final(fst_state) != Weight::Zero() &&
772  tuple.prefix_id) {
773  if (arcp) {
774  arcp->ilabel = (EpsilonOnInput(return_label_type_)) ? 0 : return_label_;
775  arcp->olabel =
776  (EpsilonOnOutput(return_label_type_)) ? 0 : return_label_;
777  if (flags & kArcNextStateValue) {
778  const auto &stack = state_table_->GetStackPrefix(tuple.prefix_id);
779  const auto prefix_id = PopPrefix(stack);
780  const auto &top = stack.Top();
781  arcp->nextstate = state_table_->FindState(
782  StateTuple(prefix_id, top.fst_id, top.nextstate));
783  }
784  if (flags & kArcWeightValue) {
785  arcp->weight = fst_array_[tuple.fst_id]->Final(fst_state);
786  }
787  }
788  return true;
789  } else {
790  return false;
791  }
792  }
793 
794  // Computes an arc in the FST corresponding to one in the underlying machine.
795  // Returns false if the underlying arc corresponds to no arc in the resulting
796  // FST.
797  bool ComputeArc(const StateTuple &tuple, const Arc &arc, Arc *arcp,
798  uint8 flags = kArcValueFlags) {
799  if (!EpsilonOnInput(call_label_type_) &&
800  (flags == (flags & (kArcILabelValue | kArcWeightValue)))) {
801  *arcp = arc;
802  return true;
803  }
804  if (arc.olabel == 0 || arc.olabel < *nonterminal_set_.begin() ||
805  arc.olabel > *nonterminal_set_.rbegin()) { // Expands local FST.
806  const auto nextstate =
807  flags & kArcNextStateValue
808  ? state_table_->FindState(
809  StateTuple(tuple.prefix_id, tuple.fst_id, arc.nextstate))
810  : kNoStateId;
811  *arcp = Arc(arc.ilabel, arc.olabel, arc.weight, nextstate);
812  } else {
813  // Checks for non-terminal.
814  const auto it = nonterminal_hash_.find(arc.olabel);
815  if (it != nonterminal_hash_.end()) { // Recurses into non-terminal.
816  const auto nonterminal = it->second;
817  const auto nt_prefix =
818  PushPrefix(state_table_->GetStackPrefix(tuple.prefix_id),
819  tuple.fst_id, arc.nextstate);
820  // If the start state is valid, replace; othewise, the arc is implicitly
821  // deleted.
822  const auto nt_start = fst_array_[nonterminal]->Start();
823  if (nt_start != kNoStateId) {
824  const auto nt_nextstate = flags & kArcNextStateValue
825  ? state_table_->FindState(StateTuple(
826  nt_prefix, nonterminal, nt_start))
827  : kNoStateId;
828  const auto ilabel =
829  (EpsilonOnInput(call_label_type_)) ? 0 : arc.ilabel;
830  const auto olabel =
831  (EpsilonOnOutput(call_label_type_))
832  ? 0
833  : ((call_output_label_ == kNoLabel) ? arc.olabel
834  : call_output_label_);
835  *arcp = Arc(ilabel, olabel, arc.weight, nt_nextstate);
836  } else {
837  return false;
838  }
839  } else {
840  const auto nextstate =
841  flags & kArcNextStateValue
842  ? state_table_->FindState(
843  StateTuple(tuple.prefix_id, tuple.fst_id, arc.nextstate))
844  : kNoStateId;
845  *arcp = Arc(arc.ilabel, arc.olabel, arc.weight, nextstate);
846  }
847  }
848  return true;
849  }
850 
851  // Returns the arc iterator flags supported by this FST.
853  uint8 flags = kArcValueFlags;
854  if (!always_cache_) flags |= kArcNoCache;
855  return flags;
856  }
857 
858  StateTable *GetStateTable() const { return state_table_.get(); }
859 
860  const Fst<Arc> *GetFst(Label fst_id) const {
861  return fst_array_[fst_id].get();
862  }
863 
864  Label GetFstId(Label nonterminal) const {
865  const auto it = nonterminal_hash_.find(nonterminal);
866  if (it == nonterminal_hash_.end()) {
867  FSTERROR() << "ReplaceFstImpl::GetFstId: Nonterminal not found: "
868  << nonterminal;
869  }
870  return it->second;
871  }
872 
873  // Returns true if label type on call arc results in epsilon input label.
874  bool EpsilonOnCallInput() { return EpsilonOnInput(call_label_type_); }
875 
876  private:
877  // The unique index into stack prefix table.
878  PrefixId GetPrefixId(const StackPrefix &prefix) {
879  return state_table_->FindPrefixId(prefix);
880  }
881 
882  // The prefix ID after a stack pop.
883  PrefixId PopPrefix(StackPrefix prefix) {
884  prefix.Pop();
885  return GetPrefixId(prefix);
886  }
887 
888  // The prefix ID after a stack push.
889  PrefixId PushPrefix(StackPrefix prefix, Label fst_id, StateId nextstate) {
890  prefix.Push(fst_id, nextstate);
891  return GetPrefixId(prefix);
892  }
893 
894  // Runtime options
895  ReplaceLabelType call_label_type_; // How to label call arc.
896  ReplaceLabelType return_label_type_; // How to label return arc.
897  int64 call_output_label_; // Specifies output label to put on call arc
898  int64 return_label_; // Specifies label to put on return arc.
899  bool always_cache_; // Disable optional caching of arc iterator?
900 
901  // State table.
902  std::unique_ptr<StateTable> state_table_;
903 
904  // Replace components.
905  std::set<Label> nonterminal_set_;
906  NonTerminalHash nonterminal_hash_;
907  std::vector<std::unique_ptr<const Fst<Arc>>> fst_array_;
908  Label root_;
909 };
910 
911 } // namespace internal
912 
913 //
914 // ReplaceFst supports dynamic replacement of arcs in one FST with another FST.
915 // This replacement is recursive. ReplaceFst can be used to support a variety of
916 // delayed constructions such as recursive
917 // transition networks, union, or closure. It is constructed with an array of
918 // FST(s). One FST represents the root (or topology) machine. The root FST
919 // refers to other FSTs by recursively replacing arcs labeled as non-terminals
920 // with the matching non-terminal FST. Currently the ReplaceFst uses the output
921 // symbols of the arcs to determine whether the arc is a non-terminal arc or
922 // not. A non-terminal can be any label that is not a non-zero terminal label in
923 // the output alphabet.
924 //
925 // Note that the constructor uses a vector of pairs. These correspond to the
926 // tuple of non-terminal Label and corresponding FST. For example to implement
927 // the closure operation we need 2 FSTs. The first root FST is a single
928 // self-loop arc on the start state.
929 //
930 // The ReplaceFst class supports an optionally caching arc iterator.
931 //
932 // The ReplaceFst needs to be built such that it is known to be ilabel- or
933 // olabel-sorted (see usage below).
934 //
935 // Observe that Matcher<Fst<A>> will use the optionally caching arc iterator
936 // when available (the FST is ilabel-sorted and matching on the input, or the
937 // FST is olabel -orted and matching on the output). In order to obtain the
938 // most efficient behaviour, it is recommended to set call_label_type to
939 // REPLACE_LABEL_INPUT or REPLACE_LABEL_BOTH and return_label_type to
940 // REPLACE_LABEL_OUTPUT or REPLACE_LABEL_NEITHER. This means that the call arc
941 // does not have epsilon on the input side and the return arc has epsilon on the
942 // input side) and matching on the input side.
943 //
944 // This class attaches interface to implementation and handles reference
945 // counting, delegating most methods to ImplToFst.
946 template <class A, class T /* = DefaultReplaceStateTable<A> */,
947  class CacheStore /* = DefaultCacheStore<A> */>
948 class ReplaceFst
949  : public ImplToFst<internal::ReplaceFstImpl<A, T, CacheStore>> {
950  public:
951  using Arc = A;
952  using Label = typename Arc::Label;
953  using StateId = typename Arc::StateId;
954  using Weight = typename Arc::Weight;
955 
956  using StateTable = T;
957  using Store = CacheStore;
958  using State = typename CacheStore::State;
961 
963 
964  friend class ArcIterator<ReplaceFst<Arc, StateTable, CacheStore>>;
965  friend class StateIterator<ReplaceFst<Arc, StateTable, CacheStore>>;
966  friend class ReplaceFstMatcher<Arc, StateTable, CacheStore>;
967 
968  ReplaceFst(const std::vector<std::pair<Label, const Fst<Arc> *>> &fst_array,
969  Label root)
970  : ImplToFst<Impl>(std::make_shared<Impl>(
971  fst_array, ReplaceFstOptions<Arc, StateTable, CacheStore>(root))) {}
972 
973  ReplaceFst(const std::vector<std::pair<Label, const Fst<Arc> *>> &fst_array,
975  : ImplToFst<Impl>(std::make_shared<Impl>(fst_array, opts)) {}
976 
977  // See Fst<>::Copy() for doc.
978  ReplaceFst(const ReplaceFst &fst, bool safe = false)
979  : ImplToFst<Impl>(fst, safe) {}
980 
981  // Get a copy of this ReplaceFst. See Fst<>::Copy() for further doc.
982  ReplaceFst *Copy(bool safe = false) const override {
983  return new ReplaceFst(*this, safe);
984  }
985 
986  inline void InitStateIterator(StateIteratorData<Arc> *data) const override;
987 
988  void InitArcIterator(StateId s, ArcIteratorData<Arc> *data) const override {
989  GetMutableImpl()->InitArcIterator(s, data);
990  }
991 
992  MatcherBase<Arc> *InitMatcher(MatchType match_type) const override {
993  if ((GetImpl()->ArcIteratorFlags() & kArcNoCache) &&
994  ((match_type == MATCH_INPUT && Properties(kILabelSorted, false)) ||
995  (match_type == MATCH_OUTPUT && Properties(kOLabelSorted, false)))) {
997  match_type);
998  } else {
999  VLOG(2) << "Not using replace matcher";
1000  return nullptr;
1001  }
1002  }
1003 
1004  bool CyclicDependencies() const { return GetImpl()->CyclicDependencies(); }
1005 
1006  const StateTable &GetStateTable() const {
1007  return *GetImpl()->GetStateTable();
1008  }
1009 
1010  const Fst<Arc> &GetFst(Label nonterminal) const {
1011  return *GetImpl()->GetFst(GetImpl()->GetFstId(nonterminal));
1012  }
1013 
1014  private:
1017 
1018  ReplaceFst &operator=(const ReplaceFst &) = delete;
1019 };
1020 
1021 // Specialization for ReplaceFst.
1022 template <class Arc, class StateTable, class CacheStore>
1023 class StateIterator<ReplaceFst<Arc, StateTable, CacheStore>>
1024  : public CacheStateIterator<ReplaceFst<Arc, StateTable, CacheStore>> {
1025  public:
1027  : CacheStateIterator<ReplaceFst<Arc, StateTable, CacheStore>>(
1028  fst, fst.GetMutableImpl()) {}
1029 };
1030 
1031 // Specialization for ReplaceFst, implementing optional caching. It is be used
1032 // as follows:
1033 //
1034 // ReplaceFst<A> replace;
1035 // ArcIterator<ReplaceFst<A>> aiter(replace, s);
1036 // // Note: ArcIterator< Fst<A>> is always a caching arc iterator.
1037 // aiter.SetFlags(kArcNoCache, kArcNoCache);
1038 // // Uses the arc iterator, no arc will be cached, no state will be expanded.
1039 // // Arc flags can be used to decide which component of the arc need to be
1040 // computed.
1041 // aiter.SetFlags(kArcILabelValue, kArcValueFlags);
1042 // // Wants the ilabel for this arc.
1043 // aiter.Value(); // Does not compute the destination state.
1044 // aiter.Next();
1045 // aiter.SetFlags(kArcNextStateValue, kArcNextStateValue);
1046 // // Wants the ilabel and next state for this arc.
1047 // aiter.Value(); // Does compute the destination state and inserts it
1048 // // in the replace state table.
1049 // // No additional arcs have been cached at this point.
1050 template <class Arc, class StateTable, class CacheStore>
1051 class ArcIterator<ReplaceFst<Arc, StateTable, CacheStore>> {
1052  public:
1053  using StateId = typename Arc::StateId;
1054 
1055  using StateTuple = typename StateTable::StateTuple;
1056 
1058  : fst_(fst),
1059  s_(s),
1060  pos_(0),
1061  offset_(0),
1062  flags_(kArcValueFlags),
1063  arcs_(nullptr),
1064  data_flags_(0),
1065  final_flags_(0) {
1066  cache_data_.ref_count = nullptr;
1067  local_data_.ref_count = nullptr;
1068  // If FST does not support optional caching, forces caching.
1069  if (!(fst_.GetImpl()->ArcIteratorFlags() & kArcNoCache) &&
1070  !(fst_.GetImpl()->HasArcs(s_))) {
1071  fst_.GetMutableImpl()->Expand(s_);
1072  }
1073  // If state is already cached, use cached arcs array.
1074  if (fst_.GetImpl()->HasArcs(s_)) {
1075  (fst_.GetImpl())
1076  ->internal::template CacheBaseImpl<
1077  typename CacheStore::State,
1078  CacheStore>::InitArcIterator(s_, &cache_data_);
1079  num_arcs_ = cache_data_.narcs;
1080  arcs_ = cache_data_.arcs; // arcs_ is a pointer to the cached arcs.
1081  data_flags_ = kArcValueFlags; // All the arc member values are valid.
1082  } else { // Otherwise delay decision until Value() is called.
1083  tuple_ = fst_.GetImpl()->GetStateTable()->Tuple(s_);
1084  if (tuple_.fst_state == kNoStateId) {
1085  num_arcs_ = 0;
1086  } else {
1087  // The decision to cache or not to cache has been defered until Value()
1088  // or
1089  // SetFlags() is called. However, the arc iterator is set up now to be
1090  // ready for non-caching in order to keep the Value() method simple and
1091  // efficient.
1092  const auto *rfst = fst_.GetImpl()->GetFst(tuple_.fst_id);
1093  rfst->InitArcIterator(tuple_.fst_state, &local_data_);
1094  // arcs_ is a pointer to the arcs in the underlying machine.
1095  arcs_ = local_data_.arcs;
1096  // Computes the final arc (but not its destination state) if a final arc
1097  // is required.
1098  bool has_final_arc = fst_.GetMutableImpl()->ComputeFinalArc(
1099  tuple_, &final_arc_, kArcValueFlags & ~kArcNextStateValue);
1100  // Sets the arc value flags that hold for final_arc_.
1101  final_flags_ = kArcValueFlags & ~kArcNextStateValue;
1102  // Computes the number of arcs.
1103  num_arcs_ = local_data_.narcs;
1104  if (has_final_arc) ++num_arcs_;
1105  // Sets the offset between the underlying arc positions and the
1106  // positions
1107  // in the arc iterator.
1108  offset_ = num_arcs_ - local_data_.narcs;
1109  // Defers the decision to cache or not until Value() or SetFlags() is
1110  // called.
1111  data_flags_ = 0;
1112  }
1113  }
1114  }
1115 
1117  if (cache_data_.ref_count) --(*cache_data_.ref_count);
1118  if (local_data_.ref_count) --(*local_data_.ref_count);
1119  }
1120 
1121  void ExpandAndCache() const {
1122  // TODO(allauzen): revisit this.
1123  // fst_.GetImpl()->Expand(s_, tuple_, local_data_);
1124  // (fst_.GetImpl())->CacheImpl<A>*>::InitArcIterator(s_,
1125  // &cache_data_);
1126  //
1127  fst_.InitArcIterator(s_, &cache_data_); // Expand and cache state.
1128  arcs_ = cache_data_.arcs; // arcs_ is a pointer to the cached arcs.
1129  data_flags_ = kArcValueFlags; // All the arc member values are valid.
1130  offset_ = 0; // No offset.
1131  }
1132 
1133  void Init() {
1134  if (flags_ & kArcNoCache) { // If caching is disabled
1135  // arcs_ is a pointer to the arcs in the underlying machine.
1136  arcs_ = local_data_.arcs;
1137  // Sets the arcs value flags that hold for arcs_.
1138  data_flags_ = kArcWeightValue;
1139  if (!fst_.GetMutableImpl()->EpsilonOnCallInput()) {
1140  data_flags_ |= kArcILabelValue;
1141  }
1142  // Sets the offset between the underlying arc positions and the positions
1143  // in the arc iterator.
1144  offset_ = num_arcs_ - local_data_.narcs;
1145  } else {
1146  ExpandAndCache();
1147  }
1148  }
1149 
1150  bool Done() const { return pos_ >= num_arcs_; }
1151 
1152  const Arc &Value() const {
1153  // If data_flags_ is 0, non-caching was not requested.
1154  if (!data_flags_) {
1155  // TODO(allauzen): Revisit this.
1156  if (flags_ & kArcNoCache) {
1157  // Should never happen.
1158  FSTERROR() << "ReplaceFst: Inconsistent arc iterator flags";
1159  }
1160  ExpandAndCache();
1161  }
1162  if (pos_ - offset_ >= 0) { // The requested arc is not the final arc.
1163  const auto &arc = arcs_[pos_ - offset_];
1164  if ((data_flags_ & flags_) == (flags_ & kArcValueFlags)) {
1165  // If the value flags match the recquired value flags then returns the
1166  // arc.
1167  return arc;
1168  } else {
1169  // Otherwise, compute the corresponding arc on-the-fly.
1170  fst_.GetMutableImpl()->ComputeArc(tuple_, arc, &arc_,
1171  flags_ & kArcValueFlags);
1172  return arc_;
1173  }
1174  } else { // The requested arc is the final arc.
1175  if ((final_flags_ & flags_) != (flags_ & kArcValueFlags)) {
1176  // If the arc value flags that hold for the final arc do not match the
1177  // requested value flags, then
1178  // final_arc_ needs to be updated.
1179  fst_.GetMutableImpl()->ComputeFinalArc(tuple_, &final_arc_,
1180  flags_ & kArcValueFlags);
1181  final_flags_ = flags_ & kArcValueFlags;
1182  }
1183  return final_arc_;
1184  }
1185  }
1186 
1187  void Next() { ++pos_; }
1188 
1189  size_t Position() const { return pos_; }
1190 
1191  void Reset() { pos_ = 0; }
1192 
1193  void Seek(size_t pos) { pos_ = pos; }
1194 
1195  uint8 Flags() const { return flags_; }
1196 
1197  void SetFlags(uint8 flags, uint8 mask) {
1198  // Updates the flags taking into account what flags are supported
1199  // by the FST.
1200  flags_ &= ~mask;
1201  flags_ |= (flags & fst_.GetImpl()->ArcIteratorFlags());
1202  // If non-caching is not requested (and caching has not already been
1203  // performed), then flush data_flags_ to request caching during the next
1204  // call to Value().
1205  if (!(flags_ & kArcNoCache) && data_flags_ != kArcValueFlags) {
1206  if (!fst_.GetImpl()->HasArcs(s_)) data_flags_ = 0;
1207  }
1208  // If data_flags_ has been flushed but non-caching is requested before
1209  // calling Value(), then set up the iterator for non-caching.
1210  if ((flags & kArcNoCache) && (!data_flags_)) Init();
1211  }
1212 
1213  private:
1214  const ReplaceFst<Arc, StateTable, CacheStore> &fst_; // Reference to the FST.
1215  StateId s_; // State in the FST.
1216  mutable StateTuple tuple_; // Tuple corresponding to state_.
1217 
1218  ssize_t pos_; // Current position.
1219  mutable ssize_t offset_; // Offset between position in iterator and in arcs_.
1220  ssize_t num_arcs_; // Number of arcs at state_.
1221  uint8 flags_; // Behavorial flags for the arc iterator
1222  mutable Arc arc_; // Memory to temporarily store computed arcs.
1223 
1224  mutable ArcIteratorData<Arc> cache_data_; // Arc iterator data in cache.
1225  mutable ArcIteratorData<Arc> local_data_; // Arc iterator data in local FST.
1226 
1227  mutable const Arc *arcs_; // Array of arcs.
1228  mutable uint8 data_flags_; // Arc value flags valid for data in arcs_.
1229  mutable Arc final_arc_; // Final arc (when required).
1230  mutable uint8 final_flags_; // Arc value flags valid for final_arc_.
1231 
1232  ArcIterator(const ArcIterator &) = delete;
1233  ArcIterator &operator=(const ArcIterator &) = delete;
1234 };
1235 
1236 template <class Arc, class StateTable, class CacheStore>
1237 class ReplaceFstMatcher : public MatcherBase<Arc> {
1238  public:
1239  using Label = typename Arc::Label;
1240  using StateId = typename Arc::StateId;
1241  using Weight = typename Arc::Weight;
1242 
1245 
1246  using StateTuple = typename StateTable::StateTuple;
1247 
1248  // This makes a copy of the FST.
1250  MatchType match_type)
1251  : owned_fst_(fst.Copy()),
1252  fst_(*owned_fst_),
1253  impl_(fst_.GetMutableImpl()),
1254  s_(fst::kNoStateId),
1255  match_type_(match_type),
1256  current_loop_(false),
1257  final_arc_(false),
1258  loop_(kNoLabel, 0, Weight::One(), kNoStateId) {
1259  if (match_type_ == fst::MATCH_OUTPUT) {
1260  std::swap(loop_.ilabel, loop_.olabel);
1261  }
1262  InitMatchers();
1263  }
1264 
1265  // This doesn't copy the FST.
1267  MatchType match_type)
1268  : fst_(*fst),
1269  impl_(fst_.GetMutableImpl()),
1270  s_(fst::kNoStateId),
1271  match_type_(match_type),
1272  current_loop_(false),
1273  final_arc_(false),
1274  loop_(kNoLabel, 0, Weight::One(), kNoStateId) {
1275  if (match_type_ == fst::MATCH_OUTPUT) {
1276  std::swap(loop_.ilabel, loop_.olabel);
1277  }
1278  InitMatchers();
1279  }
1280 
1281  // This makes a copy of the FST.
1282  ReplaceFstMatcher(const ReplaceFstMatcher &matcher, bool safe = false)
1283  : owned_fst_(matcher.fst_.Copy(safe)),
1284  fst_(*owned_fst_),
1285  impl_(fst_.GetMutableImpl()),
1286  s_(fst::kNoStateId),
1287  match_type_(matcher.match_type_),
1288  current_loop_(false),
1289  final_arc_(false),
1290  loop_(fst::kNoLabel, 0, Weight::One(), fst::kNoStateId) {
1291  if (match_type_ == fst::MATCH_OUTPUT) {
1292  std::swap(loop_.ilabel, loop_.olabel);
1293  }
1294  InitMatchers();
1295  }
1296 
1297  // Creates a local matcher for each component FST in the RTN. LocalMatcher is
1298  // a multi-epsilon wrapper matcher. MultiEpsilonMatcher is used to match each
1299  // non-terminal arc, since these non-terminal
1300  // turn into epsilons on recursion.
1301  void InitMatchers() {
1302  const auto &fst_array = impl_->fst_array_;
1303  matcher_.resize(fst_array.size());
1304  for (Label i = 0; i < fst_array.size(); ++i) {
1305  if (fst_array[i]) {
1306  matcher_[i].reset(
1307  new LocalMatcher(*fst_array[i], match_type_, kMultiEpsList));
1308  auto it = impl_->nonterminal_set_.begin();
1309  for (; it != impl_->nonterminal_set_.end(); ++it) {
1310  matcher_[i]->AddMultiEpsLabel(*it);
1311  }
1312  }
1313  }
1314  }
1315 
1316  ReplaceFstMatcher *Copy(bool safe = false) const override {
1317  return new ReplaceFstMatcher(*this, safe);
1318  }
1319 
1320  MatchType Type(bool test) const override {
1321  if (match_type_ == MATCH_NONE) return match_type_;
1322  const auto true_prop =
1323  match_type_ == MATCH_INPUT ? kILabelSorted : kOLabelSorted;
1324  const auto false_prop =
1325  match_type_ == MATCH_INPUT ? kNotILabelSorted : kNotOLabelSorted;
1326  const auto props = fst_.Properties(true_prop | false_prop, test);
1327  if (props & true_prop) {
1328  return match_type_;
1329  } else if (props & false_prop) {
1330  return MATCH_NONE;
1331  } else {
1332  return MATCH_UNKNOWN;
1333  }
1334  }
1335 
1336  const Fst<Arc> &GetFst() const override { return fst_; }
1337 
1338  uint64 Properties(uint64 props) const override { return props; }
1339 
1340  // Sets the state from which our matching happens.
1341  void SetState(StateId s) final {
1342  if (s_ == s) return;
1343  s_ = s;
1344  tuple_ = impl_->GetStateTable()->Tuple(s_);
1345  if (tuple_.fst_state == kNoStateId) {
1346  done_ = true;
1347  return;
1348  }
1349  // Gets current matcher, used for non-epsilon matching.
1350  current_matcher_ = matcher_[tuple_.fst_id].get();
1351  current_matcher_->SetState(tuple_.fst_state);
1352  loop_.nextstate = s_;
1353  final_arc_ = false;
1354  }
1355 
1356  // Searches for label from previous set state. If label == 0, first
1357  // hallucinate an epsilon loop; otherwise use the underlying matcher to
1358  // search for the label or epsilons. Note since the ReplaceFst recursion
1359  // on non-terminal arcs causes epsilon transitions to be created we use
1360  // MultiEpsilonMatcher to search for possible matches of non-terminals. If the
1361  // component FST
1362  // reaches a final state we also need to add the exiting final arc.
1363  bool Find(Label label) final {
1364  bool found = false;
1365  label_ = label;
1366  if (label_ == 0 || label_ == kNoLabel) {
1367  // Computes loop directly, avoiding Replace::ComputeArc.
1368  if (label_ == 0) {
1369  current_loop_ = true;
1370  found = true;
1371  }
1372  // Searches for matching multi-epsilons.
1373  final_arc_ = impl_->ComputeFinalArc(tuple_, nullptr);
1374  found = current_matcher_->Find(kNoLabel) || final_arc_ || found;
1375  } else {
1376  // Searches on a sub machine directly using sub machine matcher.
1377  found = current_matcher_->Find(label_);
1378  }
1379  return found;
1380  }
1381 
1382  bool Done() const final {
1383  return !current_loop_ && !final_arc_ && current_matcher_->Done();
1384  }
1385 
1386  const Arc &Value() const final {
1387  if (current_loop_) return loop_;
1388  if (final_arc_) {
1389  impl_->ComputeFinalArc(tuple_, &arc_);
1390  return arc_;
1391  }
1392  const auto &component_arc = current_matcher_->Value();
1393  impl_->ComputeArc(tuple_, component_arc, &arc_);
1394  return arc_;
1395  }
1396 
1397  void Next() final {
1398  if (current_loop_) {
1399  current_loop_ = false;
1400  return;
1401  }
1402  if (final_arc_) {
1403  final_arc_ = false;
1404  return;
1405  }
1406  current_matcher_->Next();
1407  }
1408 
1409  ssize_t Priority(StateId s) final { return fst_.NumArcs(s); }
1410 
1411  private:
1412  std::unique_ptr<const ReplaceFst<Arc, StateTable, CacheStore>> owned_fst_;
1415  LocalMatcher *current_matcher_;
1416  std::vector<std::unique_ptr<LocalMatcher>> matcher_;
1417  StateId s_; // Current state.
1418  Label label_; // Current label.
1419  MatchType match_type_; // Supplied by caller.
1420  mutable bool done_;
1421  mutable bool current_loop_; // Current arc is the implicit loop.
1422  mutable bool final_arc_; // Current arc for exiting recursion.
1423  mutable StateTuple tuple_; // Tuple corresponding to state_.
1424  mutable Arc arc_;
1425  Arc loop_;
1426 
1427  ReplaceFstMatcher &operator=(const ReplaceFstMatcher &) = delete;
1428 };
1429 
1430 template <class Arc, class StateTable, class CacheStore>
1432  StateIteratorData<Arc> *data) const {
1433  data->base =
1435 }
1436 
1438 
1439 // Recursively replaces arcs in the root FSTs with other FSTs.
1440 // This version writes the result of replacement to an output MutableFst.
1441 //
1442 // Replace supports replacement of arcs in one Fst with another FST. This
1443 // replacement is recursive. Replace takes an array of FST(s). One FST
1444 // represents the root (or topology) machine. The root FST refers to other FSTs
1445 // by recursively replacing arcs labeled as non-terminals with the matching
1446 // non-terminal FST. Currently Replace uses the output symbols of the arcs to
1447 // determine whether the arc is a non-terminal arc or not. A non-terminal can be
1448 // any label that is not a non-zero terminal label in the output alphabet.
1449 //
1450 // Note that input argument is a vector of pairs. These correspond to the tuple
1451 // of non-terminal Label and corresponding FST.
1452 template <class Arc>
1453 void Replace(const std::vector<std::pair<typename Arc::Label, const Fst<Arc> *>>
1454  &ifst_array,
1455  MutableFst<Arc> *ofst,
1457  opts.gc = true;
1458  opts.gc_limit = 0; // Caches only the last state for fastest copy.
1459  *ofst = ReplaceFst<Arc>(ifst_array, opts);
1460 }
1461 
1462 template <class Arc>
1463 void Replace(const std::vector<std::pair<typename Arc::Label, const Fst<Arc> *>>
1464  &ifst_array,
1465  MutableFst<Arc> *ofst, const ReplaceUtilOptions &opts) {
1466  Replace(ifst_array, ofst, ReplaceFstOptions<Arc>(opts));
1467 }
1468 
1469 // For backwards compatibility.
1470 template <class Arc>
1471 void Replace(const std::vector<std::pair<typename Arc::Label, const Fst<Arc> *>>
1472  &ifst_array,
1473  MutableFst<Arc> *ofst, typename Arc::Label root,
1474  bool epsilon_on_replace) {
1475  Replace(ifst_array, ofst, ReplaceFstOptions<Arc>(root, epsilon_on_replace));
1476 }
1477 
1478 template <class Arc>
1479 void Replace(const std::vector<std::pair<typename Arc::Label, const Fst<Arc> *>>
1480  &ifst_array,
1481  MutableFst<Arc> *ofst, typename Arc::Label root) {
1482  Replace(ifst_array, ofst, ReplaceFstOptions<Arc>(root));
1483 }
1484 
1485 } // namespace fst
1486 
1487 #endif // FST_REPLACE_H_
ssize_t NumOutputEpsilons(const ExpandedFst< Arc > &fst, typename Arc::StateId s)
Definition: expanded-fst.h:100
ReplaceFstOptions(const CacheOptions &opts, Label root=kNoLabel)
Definition: replace.h:334
typename CacheStore::State State
Definition: replace.h:461
void SetState(StateId s) final
Definition: replace.h:1341
ArcIterator(const ReplaceFst< Arc, StateTable, CacheStore > &fst, StateId s)
Definition: replace.h:1057
const StateTuple & Tuple(StateId id) const
Definition: replace.h:250
constexpr int kNoLabel
Definition: fst.h:185
std::vector< PrefixTuple > prefix_
Definition: replace.h:159
MatcherBase< Arc > * InitMatcher(MatchType match_type) const override
Definition: replace.h:992
void Expand(StateId s, const StateTuple &tuple, const ArcIteratorData< Arc > &data)
Definition: replace.h:747
const StateTable & GetStateTable() const
Definition: replace.h:1006
const StackPrefix & GetStackPrefix(PrefixId id) const
Definition: replace.h:298
constexpr uint64 kNotOLabelSorted
Definition: properties.h:85
uint64_t uint64
Definition: types.h:32
void Next() final
Definition: replace.h:1397
const Fst< Arc > * GetFst(Label fst_id) const
Definition: replace.h:860
ReplaceStateTuple(PrefixId prefix_id=-1, StateId fst_id=kNoStateId, StateId fst_state=kNoStateId)
Definition: replace.h:68
typename StateTable::PrefixId PrefixId
Definition: replace.h:463
PrefixId FindPrefixId(const StackPrefix &prefix)
Definition: replace.h:294
ReplaceFstOptions(int64 root, bool epsilon_replace_arc)
Definition: replace.h:369
ReplaceFstOptions(const ReplaceUtilOptions &opts)
Definition: replace.h:362
PrefixId prefix_id
Definition: replace.h:72
size_t NumOutputEpsilons(StateId s)
Definition: replace.h:669
bool EpsilonOnOutput(ReplaceLabelType label_type)
Definition: replace.h:390
ReplaceFstMatcher(const ReplaceFst< Arc, StateTable, CacheStore > *fst, MatchType match_type)
Definition: replace.h:1266
typename CacheStore::State State
Definition: replace.h:958
ReplaceLabelType
Definition: replace-util.h:29
Arc::Weight Final(const ExpandedFst< Arc > &fst, typename Arc::StateId s)
Definition: expanded-fst.h:83
const SymbolTable * OutputSymbols() const
Definition: fst.h:750
MatchType
Definition: fst.h:177
uint64 ReplaceProperties(const std::vector< uint64 > &inprops, size_t root, bool epsilon_on_call, bool epsilon_on_return, bool out_epsilon_on_call, bool out_epsilon_on_return, bool replace_transducer, bool no_empty_fst, bool all_ilabel_sorted, bool all_olabel_sorted, bool all_negative_or_dense)
Definition: properties.cc:237
constexpr uint64 kILabelSorted
Definition: properties.h:78
ReplaceFst(const std::vector< std::pair< Label, const Fst< Arc > * >> &fst_array, const ReplaceFstOptions< Arc, StateTable, CacheStore > &opts)
Definition: replace.h:973
uint64 Properties(uint64 mask) const override
Definition: replace.h:708
void InitArcIterator(StateId s, ArcIteratorData< Arc > *data) const override
Definition: replace.h:988
bool ReplaceTransducer(ReplaceLabelType call_label_type, ReplaceLabelType return_label_type, Label call_output_label)
Definition: replace.h:397
void Push(StateId fst_id, StateId nextstate)
Definition: replace.h:148
VectorHashReplaceStateTable(const VectorHashReplaceStateTable< Arc, PrefixId > &table)
Definition: replace.h:234
SetType
Definition: set-weight.h:38
MatchType Type(bool test) const override
Definition: replace.h:1320
typename Arc::Weight Weight
Definition: replace.h:1241
typename ReplaceFst< Arc, StateTable, CacheStore >::Arc Arc
Definition: cache.h:1154
ssize_t NumArcs(const ExpandedFst< Arc > &fst, typename Arc::StateId s)
Definition: expanded-fst.h:89
constexpr uint64 kNotILabelSorted
Definition: properties.h:80
bool EpsilonOnInput(ReplaceLabelType label_type)
Definition: replace.h:384
void Replace(const std::vector< std::pair< typename Arc::Label, const Fst< Arc > * >> &ifst_array, MutableFst< Arc > *ofst, std::vector< std::pair< typename Arc::Label, typename Arc::Label >> *parens, const PdtReplaceOptions< Arc > &opts)
Definition: replace.h:776
bool CyclicDependencies() const
Definition: replace.h:1004
const uint32 kMultiEpsList
Definition: matcher.h:1215
VectorHashReplaceStateTable(const std::vector< std::pair< Label, const Fst< Arc > * >> &fst_list, Label root)
Definition: replace.h:213
ReplaceFstOptions(const CacheImplOptions< CacheStore > &opts, Label root=kNoLabel)
Definition: replace.h:330
bool Find(Label label) final
Definition: replace.h:1363
const PrefixTuple & Top() const
Definition: replace.h:154
const Fst< Arc > & GetFst(Label nonterminal) const
Definition: replace.h:1010
constexpr uint64 kFstProperties
Definition: properties.h:310
constexpr uint64 kCopyProperties
Definition: properties.h:147
constexpr int kNoStateId
Definition: fst.h:186
uint64 operator()(const ReplaceStateTuple< StateId, PrefixId > &tuple) const
Definition: replace.h:115
const Arc & Value() const
Definition: fst.h:525
DefaultReplaceStateTable(const DefaultReplaceStateTable< Arc, PrefixId > &table)
Definition: replace.h:291
void InitArcIterator(StateId s, ArcIteratorData< Arc > *data)
Definition: replace.h:721
std::vector< std::pair< typename Arc::Label, const Fst< Arc > * >> FstList
Definition: replace.h:381
int64_t int64
Definition: types.h:27
#define FSTERROR()
Definition: util.h:36
ReplaceFstImpl(const ReplaceFstImpl &impl)
Definition: replace.h:541
size_t operator()(const ReplaceStateTuple< S, P > &t) const
Definition: replace.h:124
StateIteratorBase< Arc > * base
Definition: fst.h:366
typename Arc::Weight Weight
Definition: replace.h:459
ssize_t NumInputEpsilons(const ExpandedFst< Arc > &fst, typename Arc::StateId s)
Definition: expanded-fst.h:94
void InitStateIterator(StateIteratorData< Arc > *data) const override
Definition: replace.h:1431
typename Arc::StateId StateId
Definition: replace.h:198
bool operator==(const PdtStateTuple< S, K > &x, const PdtStateTuple< S, K > &y)
Definition: pdt.h:133
uint8_t uint8
Definition: types.h:29
const Fst< Arc > & GetFst() const override
Definition: replace.h:1336
bool ComputeArc(const StateTuple &tuple, const Arc &arc, Arc *arcp, uint8 flags=kArcValueFlags)
Definition: replace.h:797
Weight Final(StateId s)
Definition: replace.h:591
constexpr uint64 kOLabelSorted
Definition: properties.h:83
#define VLOG(level)
Definition: log.h:47
size_t NumArcs(StateId s)
Definition: replace.h:603
typename Arc::Label Label
Definition: replace.h:197
bool Done() const
Definition: fst.h:521
bool ComputeFinalArc(const StateTuple &tuple, Arc *arcp, uint8 flags=kArcValueFlags)
Definition: replace.h:766
ReplaceFst * Copy(bool safe=false) const override
Definition: replace.h:982
uint64 Properties(uint64 props) const override
Definition: replace.h:1338
PrefixId FindPrefixId(const StackPrefix &prefix)
Definition: replace.h:252
const StackPrefix & GetStackPrefix(PrefixId id) const
Definition: replace.h:256
ReplaceFst(const std::vector< std::pair< Label, const Fst< Arc > * >> &fst_array, Label root)
Definition: replace.h:968
ReplaceFstOptions(Label root, ReplaceLabelType call_label_type, ReplaceLabelType return_label_type, Label return_label)
Definition: replace.h:345
uint64 operator()(const ReplaceStateTuple< StateId, PrefixId > &tuple) const
Definition: replace.h:102
typename Arc::Label Label
Definition: replace.h:312
ReplaceFstMatcher * Copy(bool safe=false) const override
Definition: replace.h:1316
void Expand(StateId s)
Definition: replace.h:730
ReplaceFst(const ReplaceFst &fst, bool safe=false)
Definition: replace.h:978
const Arc & Value() const final
Definition: replace.h:1386
uint8 ArcIteratorFlags() const
Definition: replace.h:852
Label GetFstId(Label nonterminal) const
Definition: replace.h:864
typename internal::ReplaceFstImpl< Arc, StateTable, CacheStore >::Arc Arc
Definition: fst.h:195
size_t Depth() const
Definition: replace.h:156
const SymbolTable * InputSymbols() const
Definition: fst.h:748
Arc::StateId CountStates(const Fst< Arc > &fst)
Definition: expanded-fst.h:155
bool CyclicDependencies() const
Definition: replace-util.h:119
typename Arc::Label Label
Definition: replace.h:1239
size_t operator()(const ReplaceStackPrefix< Label, StateId > &prefix) const
Definition: replace.h:180
size_t NumInputEpsilons(StateId s)
Definition: replace.h:633
ssize_t Priority(StateId s) final
Definition: replace.h:1409
ReplaceFstOptions(Label root, ReplaceLabelType call_label_type, ReplaceLabelType return_label_type, Label call_output_label, Label return_label)
Definition: replace.h:353
ReplaceFstMatcher(const ReplaceFstMatcher &matcher, bool safe=false)
Definition: replace.h:1282
ReplaceFstOptions(Label root)
Definition: replace.h:343
constexpr uint64 kError
Definition: properties.h:36
bool CyclicDependencies() const
Definition: replace.h:566
typename StateTable::StateTuple StateTuple
Definition: replace.h:1246
ReplaceFstImpl(const FstList< Arc > &fst_list, const ReplaceFstOptions< Arc, StateTable, CacheStore > &opts)
Definition: replace.h:486
uint64 Properties() const override
Definition: replace.h:705
ReplaceFstMatcher(const ReplaceFst< Arc, StateTable, CacheStore > &fst, MatchType match_type)
Definition: replace.h:1249
typename Arc::StateId StateId
Definition: replace.h:274
bool CompatSymbols(const SymbolTable *syms1, const SymbolTable *syms2, bool warning=true)
void Expand(const Fst< Arc > &ifst, const std::vector< std::pair< typename Arc::Label, typename Arc::Label >> &parens, const std::vector< typename Arc::Label > &assignments, MutableFst< Arc > *ofst, const MPdtExpandOptions &opts)
Definition: expand.h:302
ReplaceFingerprint(const std::vector< uint64 > *size_array)
Definition: replace.h:99
uint64 ReplaceFstProperties(typename Arc::Label root_label, const FstList< Arc > &fst_list, ReplaceLabelType call_label_type, ReplaceLabelType return_label_type, typename Arc::Label call_output_label, bool *sorted_and_non_empty)
Definition: replace.h:409
ReplaceStackPrefix(const ReplaceStackPrefix &other)
Definition: replace.h:145
typename Arc::StateId StateId
Definition: replace.h:458
bool Done() const final
Definition: replace.h:1382
StateId FindState(const StateTuple &tuple)
Definition: replace.h:246
bool IsNonTerminal(Label label) const
Definition: replace.h:619
typename Arc::StateId StateId
Definition: replace.h:1240
DefaultReplaceStateTable(const std::vector< std::pair< Label, const Fst< Arc > * >> &, Label)
Definition: replace.h:288
StateIterator(const ReplaceFst< Arc, StateTable, CacheStore > &fst)
Definition: replace.h:1026
typename Arc::Label Label
Definition: replace.h:457
PrefixTuple(Label fst_id=kNoLabel, StateId nextstate=kNoStateId)
Definition: replace.h:136
bool operator()(const ReplaceStateTuple< StateId, PrefixId > &tuple) const
Definition: replace.h:90
StateTable * GetStateTable() const
Definition: replace.h:858
std::unordered_map< Label, Label > NonTerminalHash
Definition: replace.h:466
void Next()
Definition: fst.h:529