GFConcrete

Struct GFConcrete 

Source
pub struct GFConcrete {
    pub flags: HashMap<String, String>,
    pub start_cats: HashMap<String, (i32, i32)>,
    pub total_fids: i32,
    pub pproductions: HashMap<i32, Vec<Production>>,
    /* private fields */
}
Expand description

Concrete syntax for linearizing abstract trees.

Defines realizations (linearizations) of the abstract grammar, which can be natural language, images, etc.

A concrete grammar maps abstract functions to linearization rules, which produce output forms based on the arguments.

§Example

concrete LangEng of Lang = {
  lincat Sentence = Str;
  lin MakeSentence n v = n ++ v;
}

Fields§

§flags: HashMap<String, String>

Flags for concrete-specific settings.

§start_cats: HashMap<String, (i32, i32)>

Start category ranges.

§total_fids: i32

Total number of FIds.

§pproductions: HashMap<i32, Vec<Production>>

Parameter productions.

Implementations§

Source§

impl GFConcrete

Source

pub fn new( flags: HashMap<String, String>, functions: Vec<RuntimeCncFun>, productions: HashMap<i32, Vec<Production>>, start_cats: HashMap<String, (i32, i32)>, total_fids: i32, ) -> Self

Creates a new concrete grammar.

§Arguments
  • flags - Concrete-specific flags.
  • functions - List of runtime concrete functions.
  • productions - Map of productions by FId.
  • start_cats - Start category ranges.
  • total_fids - Total number of FIds.
§Examples
use gf_core::{GFConcrete, RuntimeCncFun, LinType, Production};
use std::collections::HashMap;
let flags = HashMap::new();
let functions = vec![];
let productions = HashMap::new();
let start_cats = HashMap::new();
let total_fids = 0;
let concrete = GFConcrete::new(flags, functions, productions, start_cats, total_fids);
Source

pub fn from_json(json: Concrete) -> Self

Converts from JSON concrete to GFConcrete.

This method deserializes a Concrete structure into a usable GFConcrete, resolving sequence indices to actual symbols.

§Arguments
  • json - The Concrete structure from JSON.
Source

pub fn linearize_syms(&self, tree: &Fun, tag: &str) -> Vec<LinearizedSym>

Linearizes a tree into symbols with tags.

Produces a vector of linearized symbols for the tree, handling different types like metas, literals, and functions.

§Arguments
  • tree - The abstract tree to linearize.
  • tag - The tag for tracking.
§Returns

Vector of LinearizedSym.

Source

pub fn syms2toks(&self, syms: &[Sym]) -> Vec<TaggedString>

Converts symbols to tagged tokens.

Processes a sequence of symbols into tagged strings, handling KS and KP symbols.

§Arguments
  • syms - Slice of symbols.
§Returns

Vector of TaggedString.

Source

pub fn linearize_all(&self, tree: &Fun) -> Vec<String>

Linearizes a tree to all possible strings.

§Arguments
  • tree - The tree to linearize.
§Returns

Vector of all possible linearizations.

Source

pub fn linearize(&self, tree: &Fun) -> String

Linearizes a tree to a single string (first variant).

§Arguments
  • tree - The tree to linearize.
§Returns

The linearized string.

Examples found in repository?
examples/basic_usage.rs (line 66)
18fn main() -> Result<(), Box<dyn std::error::Error>> {
19    // Uncomment the line below to see debug output from GF-Core operations
20    set_debug(true);
21    
22    // Load a PGF grammar from binary file and convert to JSON
23    println!("LOG: Reading binary PGF file from disk...");
24    let pgf_content = fs::read("grammars/Food/Food.pgf")?;
25    
26    println!("LOG: Attemp at parsing PGF file Food.pgf starting...");
27    let pgf = pgf2json::parse_pgf(&Bytes::from(pgf_content))?;
28    
29    println!("LOG: Attemp at transforming pgf data to json...");
30    let json_string = pgf2json::pgf_to_json(&pgf)?;
31    
32    println!("LOG: Result of parsing (json_string): {json_string}");
33    println!("TODO: Verify that json_string is json formated!");
34    
35    // Parse JSON string back into PGF struct for runtime usage
36    let json_value: serde_json::Value = serde_json::from_str(&json_string)?;
37    println!("TODO: Understand purpose of (json_value): {json_string}" );
38    
39    let pgf_struct: PGF = serde_json::from_value(json_value)?;
40    println!("TODO: Understand content of (pgf_struct): {:?}", pgf_struct);
41    
42    // Convert to runtime grammar
43    println!("TODO: Purpose of GFGrammar::from_json(pgf_struct)");
44    let grammar: GFGrammar = GFGrammar::from_json(pgf_struct);
45    
46    
47    // Test our fixed abstract syntax parsing
48    println!("LOG: Testing fixed abstract syntax parsing");
49    
50    let test_cases = [
51        "Fish",
52        "This(Fish)", 
53        "Is(This(Fish), Delicious)",
54        "MakeS (NP) (VP)",
55    ];
56    
57    for test_case in test_cases {
58        println!("\nTesting abstract syntax: '{}'", test_case);
59        match grammar.abstract_grammar.parse_tree(test_case, None) {
60            Some(tree) => {
61                println!("✓ Parsed successfully: {}", tree.print());
62                
63                // Try to linearize this tree
64                if let Some(eng_concrete) = grammar.concretes.get("FoodEng") {
65                    println!("LOG: Attempting linearization with FoodEng concrete grammar");
66                    let english_output = eng_concrete.linearize(&tree);
67                    println!("  English: '{}'", english_output);
68                }
69            }
70            None => {
71                println!("✗ Failed to parse");
72            }
73        }
74    }
75    
76    // Also test the natural language parsing for comparison
77    println!("\n=== Natural Language Parsing (for comparison) ===");
78    if let Some(eng_concrete) = grammar.concretes.get("FoodEng") {
79        let trees = eng_concrete.parse_string("this fish is delicious", &grammar.abstract_grammar.startcat);
80        
81        if trees.is_empty() {
82            println!("No valid parse found for 'this fish is delicious'");
83        } else {
84            println!("Found {} parse tree(s):", trees.len());
85            for (i, tree) in trees.iter().enumerate() {
86                println!("  Tree {}: {}", i + 1, tree.print());
87                
88                // Linearize back to English
89                let english_output = eng_concrete.linearize(tree);
90                println!("  English: {}", english_output);
91            }
92        }
93    }
94
95    // Note: FoodIta concrete grammar not available in this PGF file
96    println!("Available concrete grammars: {:?}", grammar.concretes.keys().collect::<Vec<_>>());
97
98    Ok(())
99}
Source

pub fn tag_and_linearize(&self, tree: &Fun) -> Vec<TaggedString>

Linearizes a tree with tags.

§Arguments
  • tree - The tree to linearize.
§Returns

Vector of tagged strings.

Source

pub fn parse_string(&self, input: &str, cat: &str) -> Vec<Fun>

Parses a string into trees using the given start category.

§Arguments
  • input - The input string.
  • cat - The start category.
§Returns

Vector of parsed trees.

Examples found in repository?
examples/basic_usage.rs (line 79)
18fn main() -> Result<(), Box<dyn std::error::Error>> {
19    // Uncomment the line below to see debug output from GF-Core operations
20    set_debug(true);
21    
22    // Load a PGF grammar from binary file and convert to JSON
23    println!("LOG: Reading binary PGF file from disk...");
24    let pgf_content = fs::read("grammars/Food/Food.pgf")?;
25    
26    println!("LOG: Attemp at parsing PGF file Food.pgf starting...");
27    let pgf = pgf2json::parse_pgf(&Bytes::from(pgf_content))?;
28    
29    println!("LOG: Attemp at transforming pgf data to json...");
30    let json_string = pgf2json::pgf_to_json(&pgf)?;
31    
32    println!("LOG: Result of parsing (json_string): {json_string}");
33    println!("TODO: Verify that json_string is json formated!");
34    
35    // Parse JSON string back into PGF struct for runtime usage
36    let json_value: serde_json::Value = serde_json::from_str(&json_string)?;
37    println!("TODO: Understand purpose of (json_value): {json_string}" );
38    
39    let pgf_struct: PGF = serde_json::from_value(json_value)?;
40    println!("TODO: Understand content of (pgf_struct): {:?}", pgf_struct);
41    
42    // Convert to runtime grammar
43    println!("TODO: Purpose of GFGrammar::from_json(pgf_struct)");
44    let grammar: GFGrammar = GFGrammar::from_json(pgf_struct);
45    
46    
47    // Test our fixed abstract syntax parsing
48    println!("LOG: Testing fixed abstract syntax parsing");
49    
50    let test_cases = [
51        "Fish",
52        "This(Fish)", 
53        "Is(This(Fish), Delicious)",
54        "MakeS (NP) (VP)",
55    ];
56    
57    for test_case in test_cases {
58        println!("\nTesting abstract syntax: '{}'", test_case);
59        match grammar.abstract_grammar.parse_tree(test_case, None) {
60            Some(tree) => {
61                println!("✓ Parsed successfully: {}", tree.print());
62                
63                // Try to linearize this tree
64                if let Some(eng_concrete) = grammar.concretes.get("FoodEng") {
65                    println!("LOG: Attempting linearization with FoodEng concrete grammar");
66                    let english_output = eng_concrete.linearize(&tree);
67                    println!("  English: '{}'", english_output);
68                }
69            }
70            None => {
71                println!("✗ Failed to parse");
72            }
73        }
74    }
75    
76    // Also test the natural language parsing for comparison
77    println!("\n=== Natural Language Parsing (for comparison) ===");
78    if let Some(eng_concrete) = grammar.concretes.get("FoodEng") {
79        let trees = eng_concrete.parse_string("this fish is delicious", &grammar.abstract_grammar.startcat);
80        
81        if trees.is_empty() {
82            println!("No valid parse found for 'this fish is delicious'");
83        } else {
84            println!("Found {} parse tree(s):", trees.len());
85            for (i, tree) in trees.iter().enumerate() {
86                println!("  Tree {}: {}", i + 1, tree.print());
87                
88                // Linearize back to English
89                let english_output = eng_concrete.linearize(tree);
90                println!("  English: {}", english_output);
91            }
92        }
93    }
94
95    // Note: FoodIta concrete grammar not available in this PGF file
96    println!("Available concrete grammars: {:?}", grammar.concretes.keys().collect::<Vec<_>>());
97
98    Ok(())
99}
Source

pub fn complete(&self, input: &str, cat: &str) -> CompletionResult

Provides completions for partial input.

§Arguments
  • input - The partial input string.
  • cat - The start category.
§Returns

CompletionResult with consumed tokens and suggestions.

Trait Implementations§

Source§

impl Clone for GFConcrete

Source§

fn clone(&self) -> GFConcrete

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for GFConcrete

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.