CryptoPatrick / code

Code · Language

gf-core

A Rust runtime for Grammatical Framework: parse and generate natural language from one grammar.

What it is

Grammatical Framework (GF) is a programming language for grammars. You write one abstract syntax (what can be said) and one concrete syntax per language (how it’s said). The GF compiler turns them into a PGF file, and a runtime uses that file to parse text into trees and linearise trees back into text, in any of the languages.

gf-core is a runtime for those compiled grammars, written in Rust, so GF can be embedded in Rust programs without the Haskell toolchain at run time. It is a runtime only: grammars are still compiled with the official GF compiler.

Using it

A two-language greeting grammar:

abstract Hello = {
  flags startcat = Greeting ;
  cat Greeting ; Recipient ;
  fun Hello : Recipient -> Greeting ;
      World, Mum, Friends : Recipient ;
}

concrete HelloEng of Hello = {
  lincat Greeting, Recipient = {s : Str} ;
  lin Hello recip = {s = "hello" ++ recip.s} ;
      World = {s = "world"} ; Mum = {s = "mum"} ; Friends = {s = "friends"} ;
}

An Italian concrete syntax (HelloIta) maps the same functions to “ciao”, “mondo”, “mamma”, “amici”. Compile both with gf -make HelloEng.gf HelloIta.gf to get Hello.pgf. gf-core then loads the grammar (via pgf2json) and builds a GFGrammar that can parse “hello world” into the tree Hello World and linearise that tree as “ciao mondo”.

Ideas for using it

  • Controlled natural language. Let users write rules in a restricted, unambiguous English that maps one-to-one onto logic, a deterministic alternative to an LLM for formalising requirements.
  • Multilingual output. Generate the same message in several languages from one tree, for example notifications or reports.
  • Command interfaces. Parse a small command language (“move the red block onto the table”) into structured actions.

Status

Prototype. Loads compiled grammars and handles parsing and linearisation for small grammars; larger resource-grammar coverage is untested.