maetl / calyx

A Ruby library for generating text with recursive template grammars.
MIT License
61 stars 5 forks source link

Nested expressions in expanded symbols causes confusing behaviour with unique rules #25

Open maetl opened 5 years ago

maetl commented 5 years ago

The test case below explains the issue fairly well.

Unique rules work intuitively when the expansion is one level deep and the possible options are always single atoms of text.

grammar = Calyx::Grammar.new do
  start "{sentence}{br}{sentence}{br}{sentence}"
  br "\n"
  sentence "I won a {$medal_type} medal!"
  medal_type "gold", "silver", "bronze"
end

puts grammar.generate

But when the unique rule contains nested expressions, the evaluation result gets memorised in the lookup table, not the actual unique symbols to be picked from. For example, the grammar below gives counter-intuitive results because the evaluated result isn’t comparably unique—so either gold, silver or bronze rules can end up being repeated multiple times instead of only being selected once.

nested_grammar = Calyx::Grammar.new do
  start "{sentence}{br}{sentence}{br}{sentence}"
  br "\n"
  sentence "I won a {$medal_type} medal!"
  medal_type "{gold}", "{silver}", "{bronze}"
  gold "gold", "golden"
  silver "silver", "silvery"
  bronze "bronze", "bronzed"
end

puts nested_grammar.generate