maetl / calyx

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

Result value object: Breaking API change proposed for 1.0 #23

Open maetl opened 7 years ago

maetl commented 7 years ago

Rather than having to switch between grammar.generate and grammar.evaluate to return a string or raw evaluation tree, this behaviour could be unified by returning a result value object from #generate.

As part of this change, grammar.evaluate would probably be removed from the public API and be considered internal-only.

Rough sketch of the API:

# @return [Calyx::Result]
result = grammar.generate

# Generated text string
result.text

# Generated text converted to a symbol
result.symbol

# Expression tree
result.tree

# Alternative interface
result.to_sym
result.to_s
result.to_exp

This allows both the expanded string and the underlying tree of selected syntax nodes to be easily accessible for all grammar runs, rather than having to pick an output format and call the appropriate method.

It’s also an extension point for overlaying metadata/tagging with chosen productions in future.

If the result object implements #to_s and #inspect it will be straightforward to update a lot of existing usages. However it is a breaking API change so does have potential to cause disruption, which is why I’d like to get it in before 1.0, so that the API can stabilise then.

maetl commented 6 years ago

Upgrade Guide

Calling #evaluate on the grammar instance will now trigger a deprecation warning.

grammar = Calyx::Grammar.new do
  # ...
end

grammar.evaluate

In 0.17, the above behaviour can be reproduced by replacing the call to #evaluate with #generate_result.

grammar = Calyx::Grammar.new do
  # ...
end

grammar.generate_result.tree

In 1.0, #generate_result will move to #generate.