gramforge
raw JSON → 1.0.9 verified Sat May 09 auth: no python
gramforge is a Python library for efficient multi-language generation from context-free or context-sensitive grammars (CFG/CSG). It supports generating strings and structures from grammar definitions, suitable for tasks like fuzzing, test generation, and language prototyping. Current version is 1.0.9, with a stable release cadence.
pip install gramforge Common errors
error ModuleNotFoundError: No module named 'gramforge' ↓
cause Package not installed or installed in wrong environment.
fix
Run 'pip install gramforge' in the correct Python environment.
error AttributeError: module 'gramforge' has no attribute 'Grammar' ↓
cause Wrong import path; user tried to import 'gramforge' then access Grammar.
fix
Use 'from gramforge import Grammar' instead of 'import gramforge'.
error gramforge.grammar.ParseError: Expected '=' ↓
cause Grammar rule syntax error, e.g., missing '=' or incorrect formatting.
fix
Check grammar rules: each production should be like 'NonTerminal = ...'.
Warnings
gotcha Grammar syntax is custom and not compatible with common grammar formats (e.g., ANTLR, EBNF). Double-check the format for rules and terminals. ↓
fix Refer to the official documentation for grammar syntax (e.g., S = 'hello' Name).
gotcha The generator is not deterministic unless explicitly seeded. Repeated calls to generate() may yield different outputs. ↓
fix Use gen = Generator(grammar, seed=42) for reproducible output.
gotcha Grammar.from_string() may raise ParseError for malformed rules. Always catch exceptions when processing dynamic grammars. ↓
fix Wrap in try-except: try: grammar = Grammar.from_string(rule) except Exception as e: print(e).
Imports
- Grammar wrong
import Grammarcorrectfrom gramforge import Grammar - Generator wrong
from gramforge.generator import Generatorcorrectfrom gramforge import Generator
Quickstart
from gramforge import Grammar, Generator
# Define a simple grammar
grammar = Grammar.from_string('''
S = 'Hello ' Name
Name = 'world' | 'Alice' | 'Bob'
''')
# Create a generator
gen = Generator(grammar)
# Generate a string
result = gen.generate()
print(result) # e.g., 'Hello world'