Nasty.Language.GrammarLoader (Nasty v0.3.0)
View SourceLoads and caches grammar rules from external resource files.
Supports loading grammar rules from .exs files in priv/languages/{lang}/grammars/
and provides caching for efficient rule lookup.
Grammar File Format
Grammar files should return an Elixir map with rule definitions:
# priv/languages/english/grammars/phrase_rules.exs
%{
noun_phrases: [
%{
pattern: [:det, :adj, :noun],
description: "Basic NP with determiner and adjective",
examples: ["the big dog", "a red car"]
}
],
verb_phrases: [
%{
pattern: [:verb, :np],
description: "Transitive verb with object",
examples: ["eat food", "read books"]
}
]
}Usage
# Load default grammar
{:ok, rules} = GrammarLoader.load(:en, :phrase_rules)
# Load custom variant
{:ok, rules} = GrammarLoader.load(:en, :phrase_rules, variant: :formal)
# Load from custom file
{:ok, rules} = GrammarLoader.load_file("path/to/custom_grammar.exs")Caching
Grammar rules are cached in ETS after first load for performance.
Use clear_cache/0 or clear_cache/2 to invalidate cache.
Summary
Functions
Clears the entire grammar cache.
Clears cache for specific language and rule type.
Loads grammar rules for a language and rule type.
Loads grammar rules from a custom file path.
Starts the grammar loader and initializes the cache.
Validates grammar rules structure.
Types
Functions
@spec clear_cache() :: :ok
Clears the entire grammar cache.
Examples
iex> GrammarLoader.clear_cache()
:ok
Clears cache for specific language and rule type.
Examples
iex> GrammarLoader.clear_cache(:en, :phrase_rules)
:ok
@spec load(language(), rule_type(), keyword()) :: load_result()
Loads grammar rules for a language and rule type.
Parameters
language- Language code (:en,:es,:ca)rule_type- Type of rules (:phrase_rules,:dependency_rules, etc.)opts- Options::variant- Grammar variant to load (default::default):force_reload- Skip cache and reload from disk (default:false)
Returns
{:ok, rules}- Map of grammar rules{:error, reason}- Error loading rules
Examples
iex> GrammarLoader.load(:en, :phrase_rules)
{:ok, %{noun_phrases: [...], verb_phrases: [...]}}
iex> GrammarLoader.load(:en, :phrase_rules, variant: :formal)
{:ok, %{noun_phrases: [...]}}
@spec load_file( String.t(), keyword() ) :: load_result()
Loads grammar rules from a custom file path.
Parameters
file_path- Absolute or relative path to.exsgrammar fileopts- Options::cache_key- Custom cache key (default: file path)
Returns
{:ok, rules}- Map of grammar rules{:error, reason}- Error loading file
Examples
iex> GrammarLoader.load_file("my_grammar.exs")
{:ok, %{...}}
@spec start_link() :: {:ok, pid()}
Starts the grammar loader and initializes the cache.
Called automatically by the application supervisor.
@spec validate_rules(rules()) :: :ok
Validates grammar rules structure.
Returns :ok if valid, raises if invalid.
Examples
iex> GrammarLoader.validate_rules(%{noun_phrases: []})
:ok