pub struct GFAbstract {
pub startcat: String,
/* private fields */
}
Expand description
Abstract grammar defining logical structure via functions, categories, and types.
The abstract grammar specifies the semantic structure without tying it to specific forms. It defines functions (fun) that combine categories (cat) into new categories.
§Example
abstract Lang = {
cat Sentence;
fun MakeSentence : Noun -> Verb -> Sentence;
}
Fields§
§startcat: String
Starting category for parsing/linearization.
Implementations§
Source§impl GFAbstract
impl GFAbstract
Sourcepub fn from_json(json: Abstract) -> Self
pub fn from_json(json: Abstract) -> Self
Converts from JSON abstract to GFAbstract.
§Arguments
json
- The Abstract structure from JSON.
§Examples
use gf_core::{GFAbstract, Abstract};
use std::collections::HashMap;
let json = Abstract { name: "TestGrammar".to_string(), startcat: "S".to_string(), funs: HashMap::new() };
let abs = GFAbstract::from_json(json);
assert_eq!(abs.startcat, "S");
Sourcepub fn add_type(&mut self, fun: String, args: Vec<String>, cat: String)
pub fn add_type(&mut self, fun: String, args: Vec<String>, cat: String)
Adds a new function type to the abstract.
§Arguments
fun
- Function name.args
- Argument categories.cat
- Result category.
§Examples
use gf_core::GFAbstract;
use std::collections::HashMap;
let mut abs = GFAbstract::new("S".to_string(), HashMap::new());
abs.add_type("MakeS".to_string(), vec!["NP".to_string(), "VP".to_string()], "S".to_string());
assert_eq!(abs.get_cat("MakeS").unwrap(), "S");
Sourcepub fn get_args(&self, fun: &str) -> Option<&Vec<String>>
pub fn get_args(&self, fun: &str) -> Option<&Vec<String>>
Gets arguments for a function.
§Arguments
fun
- Function name.
§Returns
Optional reference to vector of argument categories.
§Examples
use gf_core::GFAbstract;
use std::collections::HashMap;
let mut abs = GFAbstract::new("S".to_string(), HashMap::new());
abs.add_type("MakeS".to_string(), vec!["NP".to_string(), "VP".to_string()], "S".to_string());
assert_eq!(abs.get_args("MakeS").unwrap(), &vec!["NP".to_string(), "VP".to_string()]);
Sourcepub fn get_cat(&self, fun: &str) -> Option<&String>
pub fn get_cat(&self, fun: &str) -> Option<&String>
Gets category for a function.
§Arguments
fun
- Function name.
§Returns
Optional reference to result category.
§Examples
use gf_core::GFAbstract;
use std::collections::HashMap;
let mut abs = GFAbstract::new("S".to_string(), HashMap::new());
abs.add_type("MakeS".to_string(), vec!["NP".to_string(), "VP".to_string()], "S".to_string());
assert_eq!(abs.get_cat("MakeS").unwrap(), "S");
Sourcepub fn handle_literals(&self, tree: Fun, type: &str) -> Fun
pub fn handle_literals(&self, tree: Fun, type: &str) -> Fun
Handles literal wrapping for strings, ints, floats.
Modifies tree nodes representing literals to wrap them in appropriate literal functions.
§Arguments
tree
- The tree to process.type_
- The type of the current node.
§Returns
Processed tree.
§Examples
use gf_core::{GFAbstract, Fun};
use std::collections::HashMap;
let abs = GFAbstract::new("S".to_string(), HashMap::new());
let tree = Fun::new("\"hello\"".to_string(), vec![]);
let handled = abs.handle_literals(tree, "String");
assert_eq!(handled.name, "String_Literal_\"hello\"");
Sourcepub fn copy_tree(&self, x: &Fun) -> Fun
pub fn copy_tree(&self, x: &Fun) -> Fun
Deep copies a tree.
§Arguments
x
- The tree to copy.
§Returns
A deep clone of the tree.
§Examples
use gf_core::{GFAbstract, Fun};
use std::collections::HashMap;
let abs = GFAbstract::new("S".to_string(), HashMap::new());
let tree = Fun::new("Test".to_string(), vec![Fun::new("Arg".to_string(), vec![])]);
let copy = abs.copy_tree(&tree);
assert_eq!(tree.name, copy.name);
assert_eq!(tree.args.len(), copy.args.len());
Sourcepub fn parse_tree(&self, str: &str, type: Option<&String>) -> Option<Fun>
pub fn parse_tree(&self, str: &str, type: Option<&String>) -> Option<Fun>
Parses a string into a tree.
§Arguments
str
- The string representation of the tree.type_
- Optional type for annotation.
§Returns
Optional parsed and annotated tree.
§Examples
use gf_core::GFAbstract;
use std::collections::HashMap;
let abs = GFAbstract::new("S".to_string(), HashMap::new());
let tree = abs.parse_tree("Test (Arg)", None);
assert!(tree.is_some());
let tree = tree.unwrap();
assert_eq!(tree.name, "Test");
assert_eq!(tree.args.len(), 1);
assert_eq!(tree.args[0].name, "Arg");
Examples found in repository?
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}
Trait Implementations§
Source§impl Clone for GFAbstract
impl Clone for GFAbstract
Source§fn clone(&self) -> GFAbstract
fn clone(&self) -> GFAbstract
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source
. Read more