/*
# **Project Requirements: WYRE Framework**
## **1. Project Overview**
The **WYRE Framework** is designed to generate a fully functional application backend and API, as well as necessary frontend communication, using a user-friendly scripting language called **WYRE Script**. The goal is to allow users to define the complete backend architecture, including database schemas, validation, APIs, and business logic, using a simple and concise language. WYRE Framework will generate both the backend (written in Rust) and establish an API connection for the frontend (using WebSocket for communication). The framework will also allow inline business logic scripting in **JavaScript** or **Dart** for flexibility, especially for operations like validation, authorization, and custom logic.
---
## **2. Core Functionalities**
### **2.1 WYRE Script Definition**
The WYRE Script will serve as the user interface for defining backend application structure. The language will allow users to define:
- **Data Models (Database Schema)**: Ability to define database entities (tables) and their relationships (e.g., one-to-one, one-to-many, many-to-many).
- **CRUD Operations**: Automatic generation of Create, Read, Update, and Delete (CRUD) functions for all models defined in the script.
- **API Endpoints**: Define API routes corresponding to CRUD operations or any custom functions/services.
- **Fine-Grained Access Control**: Control access at both the **column level** and **item level**, ensuring granular permissions on individual fields and records.
- **Custom Business Logic**: Inline support for embedding JavaScript or Dart business logic that is triggered during various lifecycle events (before-save, after-create, etc.).
- **Validations**: Users can specify model-level and field-level validation rules.
- **Authentication and Authorization**: Define authentication mechanisms (e.g., JWT) and authorization rules (e.g., role-based access control).
- **Services and Hooks**: Ability to define custom services (e.g., email sending, notifications) and lifecycle hooks (e.g., on data changes, before/after validation, etc.).
---
### **2.2 Backend Code Generation**
The WYRE Script will be compiled into a full Rust backend. Key features of the backend:
#### **2.2.1 Database Model Generation**
- **Schema Generation**: Automatic generation of SQL (or other database) schemas for data models. The system will select an optimal database solution (e.g., SLED, SQLite) to match the application’s requirements.
- **Column-Level and Item-Level Access Control**: Control and enforce permissions on specific fields and records in the database.
- **Relationships**: Support for various relationships between models (e.g., foreign keys, joins, one-to-one, one-to-many, many-to-many).
- **Database Queries**: CRUD operations will be generated automatically, ensuring efficient querying and data manipulation.
#### **2.2.2 API Generation**
- **REST or WebSocket API**: For every data model, corresponding CRUD routes will be generated. A WebSocket connection will be used to enable a real-time API connection between the client and server.
- **RPC Mechanism**: API calls can be made like Remote Procedure Calls (RPC) from the frontend, allowing seamless communication.
- **Real-Time Data**: Using WebSockets, real-time data updates (push notifications) should be supported for certain API calls.
#### **2.2.3 Custom Business Logic Layer**
- **JavaScript or Dart Support**: The framework should support the inclusion of business logic using JavaScript or Dart, depending on what is deemed optimal for the scenario.
- **Inline Scripting**: WYRE Script should allow users to write JavaScript or Dart code inline to handle custom business logic (e.g., validation, transformation, hooks). The generated Rust backend will then embed this logic using serialization/deserialization through **MessagePack**.
- **Lifecycle Hooks**: The user should be able to define logic for events like:
- Before saving data
- After updating a record
- Before deleting data
- After creating a new entity
- **MessagePack Serialization**: All data communication between JavaScript/Dart and Rust should use MessagePack for efficient binary serialization and deserialization.
#### **2.2.4 Validation and Authorization**
- **Field-Level Validation**: Users can define validation rules for each model field (e.g., length constraints, format validation).
- **Model-Level Validation**: Define business rules that span across multiple fields (e.g., ensure one field is dependent on another).
- **Role-Based Authorization**: Define access rules based on user roles. Granular access can be applied at both the column and item level.
- **Custom Validation Logic**: Custom validation logic can be embedded using JavaScript or Dart and applied before data is persisted to the database.
#### **2.2.5 WebSocket-Based Communication Layer**
- **Real-Time WebSocket API**: Instead of traditional HTTP requests, a WebSocket layer should be implemented to allow real-time communication between the client and server.
- **Session Management**: Handle authentication (e.g., JWT token management) over WebSocket, allowing for persistent sessions and secure communication.
- **Stateful RPC Communication**: Frontend clients should be able to invoke backend functions through RPC-like mechanisms over WebSocket, ensuring smooth and interactive real-time updates.
---
### **2.3 Frontend Code Generation**
The WYRE framework will also generate frontend code to facilitate communication with the generated backend:
#### **2.3.1 API Client Generation**
- **RPC Client**: Generate a frontend client (JavaScript/TypeScript) that allows the frontend to call the backend’s API as if it were a local function using the WebSocket connection.
- **Data Serialization/Deserialization**: Ensure smooth serialization and deserialization of data between the frontend and backend, using MessagePack.
- **Authentication Management**: The generated frontend code should include functionality to manage JWT-based authentication (e.g., token storage, renewal).
- **Real-Time Updates**: The WebSocket-based communication should allow real-time updates from the backend to be pushed to the frontend (e.g., live data sync).
---
### **2.4 Scripting and Customization Features**
The framework should provide customizable scripting capabilities for end users:
#### **2.4.1 JavaScript/Dart Integration**
- **Business Logic Integration**: Allow the user to write custom business logic (e.g., custom validation, field transformations, data authorization) directly inside WYRE scripts. This logic will be embedded into the generated Rust backend using JavaScript or Dart.
- **Selection of JavaScript or Dart**: The system should allow the developer to choose between JavaScript or Dart for embedding business logic. The developer should evaluate which is more optimal for the use case.
- **Seamless Integration with Rust**: The business logic code written in JavaScript or Dart should seamlessly integrate with Rust, utilizing serialization (MessagePack) for efficient data transfer between Rust and JavaScript/Dart code.
#### **2.4.2 Validation Hooks**
- **Custom Validation Logic**: Users should be able to define custom validation logic in JavaScript or Dart for fields and models.
- **Field-Level Hooks**: Ability to add hooks that trigger custom logic before data is validated, saved, or retrieved.
- **Model-Level Hooks**: Add lifecycle hooks that trigger custom logic before or after model-level operations (e.g., before saving, after creating).
---
## **3. Non-Functional Requirements**
### **3.1 Performance**
- **Efficient Data Access**: The database should be chosen based on performance requirements (e.g., SLED or SQLite). The framework should optimize CRUD operations for minimal latency.
- **Real-Time Capabilities**: Use WebSocket for all API communications to enable real-time, bidirectional communication between client and server.
### **3.2 Security**
- **JWT Authentication**: Use JSON Web Tokens (JWT) for stateless user authentication and authorization.
- **Granular Access Control**: Implement fine-grained access control mechanisms at the column and row level.
- **Secure WebSocket Communication**: Ensure WebSocket communication is encrypted (wss://) for secure real-time data transfer.
### **3.3 Extensibility**
- **Pluggable Business Logic**: Allow easy extension of business logic in JavaScript or Dart, with future support for additional languages if necessary.
- **Customizable API**: The framework should be flexible enough to allow developers to customize or extend the generated APIs.
### **3.4 Maintainability**
- **Code Modularity**: The generated code should be well-structured and modular, making it easy for developers to maintain and extend.
- **Well-Defined Documentation**: Ensure that the generated backend and frontend code are well-documented.
---
## **4. Developer Responsibilities**
### **4.1 Rust Backend**
- **Database Integration**: Integrate a lightweight, performant database such as SLED or SQLite. Ensure it supports CRUD operations, relationships, and granular access control.
- **API Generation**: Develop logic to automatically generate REST/WebSocket APIs based on the WYRE script definitions.
- **MessagePack Integration**: Implement serialization/deserialization between Rust and JavaScript/Dart using MessagePack for efficient data exchange.
- **WebSocket Communication**: Build a WebSocket-based communication layer to allow real-time interactions between the client and server.
### **4.2 JavaScript/Dart Integration**
- **Inline Script Embedding**: Embed JavaScript/Dart code into the Rust backend, using MessagePack for communication between the two languages.
- **Lifecycle Hooks**: Implement support for lifecycle hooks (before-create, after-save, etc.) that trigger custom JavaScript/Dart logic.
### **4.3 Frontend Integration**
- **Frontend API Client**: Generate a WebSocket-based RPC client for the frontend to interact with the backend.
- **Real-Time Data Handling**: Ensure the frontend is capable of handling real-time updates from the backend
*/
use pest::Parser;
use pest_derive::Parser;
use std::collections::HashMap;
use std::fs::{self, File};
use std::io::Write;
use std::path::Path;
#[derive(Parser)]
#[grammar = "wyre_script.pest"]
struct WyreScript;
const SAMPLE_WYRE_SCRIPT: &str = r#"
// Sample WYRE script
// Custom enums
enum UserRole {
ADMIN,
USER,
GUEST
}
enum ListingStatus {
ACTIVE,
INACTIVE,
SOLD
}
// Models with optional fields and default values
model User {
id: uuid
name: string
email: string & unique
password: string
role: UserRole = UserRole.USER
bio: string | null
created_at: timestamp = now()
updated_at: timestamp | null
}
model Listing {
id: uuid
title: string
description: string | null
price: decimal
status: ListingStatus = ListingStatus.ACTIVE
created_at: timestamp = now()
updated_at: timestamp | null
created_by: one<User>
watching: many<User>
tags: many<Tag>
views: int = 0
}
model Tag {
id: uuid
name: string & unique
description: string | null
parent: one<Tag> | null
}
// Custom function with optional and default parameters
function generateSlug(title: string, separator: string = "-", maxLength: int? = 100): string {
let slug = title.toLowerCase().replace(/\s+/g, separator);
return maxLength ? slug.slice(0, maxLength) : slug;
}:ts
// Services with optional and default parameters
service UserService {
#[allow(admin)]
create_user(user: User): User
#[allow(admin, owner)]
get_user(id: uuid): User
#[allow(admin, owner)]
update_user(id: uuid, user: User): User
#[allow(admin)]
delete_user(id: uuid): boolean
#[allow(all)]
search_users(query: string = "", role: UserRole = UserRole.USER, page: int = 1, limit: int = 20): many<User>
}
service AuthService {
#[allow(all)]
login(email: string, password: string): string
#[allow(authenticated)]
logout(token: string): boolean
#[allow(all)]
register(name: string, email: string, password: string, role: UserRole = UserRole.USER): User
}
service ListingService {
#[allow(authenticated)]
create_listing(listing: Listing): Listing
#[allow(owner, admin)]
update_listing(id: uuid, listing: Listing): Listing
#[allow(owner, admin)]
delete_listing(id: uuid): boolean
#[allow(all)]
get_listing(id: uuid): Listing
#[allow(all)]
search_listings(query: string = "", category: string = "", status: ListingStatus = ListingStatus.ACTIVE, page: int = 1, limit: int = 20): many<Listing>
}
service TagService {
#[allow(admin)]
create_tag(tag: Tag): Tag
#[allow(all)]
get_tag(id: uuid): Tag
#[allow(admin)]
update_tag(id: uuid, tag: Tag): Tag
#[allow(admin)]
delete_tag(id: uuid): boolean
#[allow(all)]
search_tags(query: string | null, page: int = 1, limit: int = 20): many<Tag>
}
// Hooks with explicit types
hook User.before_create(user: User) {
user.password = bcrypt.hash(user.password, 10);
user.email = user.email.toLowerCase();
}:ts
hook User.before_update(user: User) {
if (user.password) {
user.password = bcrypt.hash(user.password, 10);
}
user.updated_at = new Date();
}:ts
hook Listing.before_create(listing: Listing) {
listing.slug = generateSlug(listing.title);
listing.views = 0;
}:ts
hook Listing.after_update(listing: Listing) {
if (listing.status === ListingStatus.SOLD) {
for (const watcher of listing.watching) {
sendNotification(watcher.id, `The listing "${listing.title}" has been sold.`);
}
}
}:ts
// Realtime with optional parameter and explicit return type
realtime listen_new_listings(category: string?): Stream<Listing> {
let stream = Listing.stream().filter(listing => listing.status === ListingStatus.ACTIVE);
if (category) {
stream = stream.filter(listing => listing.tags.some(tag => tag.name === category));
}
return stream.map(listing => ({
id: listing.id,
title: listing.title,
price: listing.price,
slug: listing.slug,
views: listing.views
}));
}:js
realtime listen_user_activity(userId: uuid): Stream<User> {
return User.stream()
.filter(user => user.id === userId)
.map(user => ({
id: user.id,
name: user.name,
email: user.email,
role: user.role,
lastActive: new Date()
}));
}:js
"#;
#[derive(Debug, Clone)]
struct Enum {
name: String,
variants: Vec<String>,
}
#[derive(Debug, Clone)]
struct Model {
name: String,
fields: Vec<Field>,
}
#[derive(Debug, Clone)]
struct Field {
name: String,
field_type: String,
is_optional: bool,
default_value: Option<String>,
}
#[derive(Debug, Clone)]
struct Function {
name: String,
params: Vec<Parameter>,
return_type: String,
body: String,
language: String,
}
#[derive(Debug, Clone)]
struct Parameter {
name: String,
param_type: String,
is_optional: bool,
default_value: Option<String>,
}
#[derive(Debug, Clone)]
struct Service {
name: String,
methods: Vec<Method>,
}
#[derive(Debug, Clone)]
struct Method {
name: String,
params: Vec<Parameter>,
return_type: String,
allowed_roles: Vec<String>,
}
#[derive(Debug, Clone)]
struct Hook {
model: String,
event: String,
params: Vec<Parameter>,
body: String,
language: String,
}
#[derive(Debug, Clone)]
struct Realtime {
name: String,
params: Vec<Parameter>,
return_type: String,
body: String,
language: String,
}
struct CodeGenerator {
enums: Vec<Enum>,
models: Vec<Model>,
functions: Vec<Function>,
services: Vec<Service>,
hooks: Vec<Hook>,
realtimes: Vec<Realtime>,
}
impl CodeGenerator {
fn new() -> Self {
CodeGenerator {
enums: Vec::new(),
models: Vec::new(),
functions: Vec::new(),
services: Vec::new(),
hooks: Vec::new(),
realtimes: Vec::new(),
}
}
fn parse_wyre_script(&mut self, pairs: pest::iterators::Pairs<Rule>) {
for pair in pairs {
match pair.as_rule() {
Rule::enum_definition => self.parse_enum(pair),
Rule::model_definition => self.parse_model(pair),
Rule::function_definition => self.parse_function(pair),
Rule::service_definition => self.parse_service(pair),
Rule::hook_definition => self.parse_hook(pair),
Rule::realtime_definition => self.parse_realtime(pair),
_ => {}
}
}
}
fn parse_enum(&mut self, pair: pest::iterators::Pair<Rule>) {
let mut inner = pair.into_inner();
let name = inner.next().unwrap().as_str().to_string();
let variants = inner.map(|p| p.as_str().to_string()).collect();
self.enums.push(Enum { name, variants });
}
fn parse_model(&mut self, pair: pest::iterators::Pair<Rule>) {
let mut inner = pair.into_inner();
let name = inner.next().unwrap().as_str().to_string();
let fields = inner.map(|p| self.parse_field(p)).collect();
self.models.push(Model { name, fields });
}
fn parse_field(&self, pair: pest::iterators::Pair<Rule>) -> Field {
let mut inner = pair.into_inner();
let name = inner.next().unwrap().as_str().to_string();
let field_type = inner.next().unwrap().as_str().to_string();
let is_optional = inner.any(|p| p.as_rule() == Rule::null_option);
let default_value = inner.find(|p| p.as_rule() == Rule::default_value)
.map(|p| p.into_inner().next().unwrap().as_str().to_string());
Field { name, field_type, is_optional, default_value }
}
fn parse_function(&mut self, pair: pest::iterators::Pair<Rule>) {
let mut inner = pair.into_inner();
let name = inner.next().unwrap().as_str().to_string();
let params = inner.next().unwrap().into_inner().map(|p| self.parse_parameter(p)).collect();
let return_type = inner.next().unwrap().as_str().to_string();
let body = inner.next().unwrap().as_str().to_string();
let language = inner.next().unwrap().as_str().to_string();
self.functions.push(Function { name, params, return_type, body, language });
}
fn parse_parameter(&self, pair: pest::iterators::Pair<Rule>) -> Parameter {
let mut inner = pair.into_inner();
let name = inner.next().unwrap().as_str().to_string();
let param_type = inner.next().unwrap().as_str().to_string();
let is_optional = inner.any(|p| p.as_rule() == Rule::null_option);
let default_value = inner.find(|p| p.as_rule() == Rule::default_value)
.map(|p| p.into_inner().next().unwrap().as_str().to_string());
Parameter { name, param_type, is_optional, default_value }
}
fn parse_service(&mut self, pair: pest::iterators::Pair<Rule>) {
let mut inner = pair.into_inner();
let name = inner.next().unwrap().as_str().to_string();
let methods = inner.map(|p| self.parse_method(p)).collect();
self.services.push(Service { name, methods });
}
fn parse_method(&self, pair: pest::iterators::Pair<Rule>) -> Method {
let mut inner = pair.into_inner();
let allowed_roles = inner.next().unwrap().into_inner()
.map(|p| p.as_str().to_string()).collect();
let name = inner.next().unwrap().as_str().to_string();
let params = inner.next().unwrap().into_inner().map(|p| self.parse_parameter(p)).collect();
let return_type = inner.next().unwrap().as_str().to_string();
Method { name, params, return_type, allowed_roles }
}
fn parse_hook(&mut self, pair: pest::iterators::Pair<Rule>) {
let mut inner = pair.into_inner();
let model = inner.next().unwrap().as_str().to_string();
let event = inner.next().unwrap().as_str().to_string();
let params = inner.next().unwrap().into_inner().map(|p| self.parse_parameter(p)).collect();
let body = inner.next().unwrap().as_str().to_string();
let language = inner.next().unwrap().as_str().to_string();
self.hooks.push(Hook { model, event, params, body, language });
}
fn parse_realtime(&mut self, pair: pest::iterators::Pair<Rule>) {
let mut inner = pair.into_inner();
let name = inner.next().unwrap().as_str().to_string();
let params = inner.next().unwrap().into_inner().map(|p| self.parse_parameter(p)).collect();
let return_type = inner.next().unwrap().as_str().to_string();
let body = inner.next().unwrap().as_str().to_string();
let language = inner.next().unwrap().as_str().to_string();
self.realtimes.push(Realtime { name, params, return_type, body, language });
}
fn generate_code(&self) -> String {
let mut code = String::new();
code.push_str(&self.generate_imports());
code.push_str(&self.generate_enums());
code.push_str(&self.generate_models());
code.push_str(&self.generate_functions());
code.push_str(&self.generate_services());
code.push_str(&self.generate_hooks());
code.push_str(&self.generate_realtimes());
code.push_str(&self.generate_main());
code
}
fn generate_imports(&self) -> String {
r#"use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use std::collections::HashSet;
use bigdecimal::BigDecimal;
use async_trait::async_trait;
use bcrypt;
use tokio::sync::mpsc;
use tokio::time::{interval, Duration};
use warp::Filter;
use sled;
use anyhow::{Result, Error};
"#
.to_string()
}
fn generate_enums(&self) -> String {
let mut code = String::new();
for enum_def in &self.enums {
code.push_str(&format!(
"#[derive(Debug, Clone, PartialEq)]\npub enum {} {{\n",
enum_def.name
));
for variant in &enum_def.variants {
code.push_str(&format!(" {},\n", variant));
}
code.push_str("}\n\n");
}
code
}
fn generate_models(&self) -> String {
let mut code = String::new();
for model in &self.models {
code.push_str(&format!(
"#[derive(Debug, Clone)]\npub struct {} {{\n",
model.name
));
for field in &model.fields {
let field_type = if field.is_optional {
format!("Option<{}>", field.field_type)
} else {
field.field_type.clone()
};
code.push_str(&format!(" pub {}: {},\n", field.name, field_type));
}
code.push_str("}\n\n");
// Generate CRUD operations
code.push_str(&self.generate_crud_operations(model));
}
code
}
fn generate_crud_operations(&self, model: &Model) -> String {
let model_name = &model.name;
format!(
r#"impl {0} {{
pub async fn create(db: &sled::Db, item: &{0}) -> Result<()> {{
let id = item.id.to_string();
let data = bincode::serialize(item)?;
db.insert(id.as_bytes(), data)?;
Ok(())
}}
pub async fn read(db: &sled::Db, id: &Uuid) -> Result<Option<{0}>> {{
if let Some(data) = db.get(id.to_string())? {{
let item: {0} = bincode::deserialize(&data)?;
Ok(Some(item))
}} else {{
Ok(None)
}}
}}
pub async fn update(db: &sled::Db, id: &Uuid, item: &{0}) -> Result<()> {{
let data = bincode::serialize(item)?;
db.insert(id.to_string(), data)?;
Ok(())
}}
pub async fn delete(db: &sled::Db, id: &Uuid) -> Result<()> {{
db.remove(id.to_string())?;
Ok(())
}}
}}
"#,
model_name
)
}
fn generate_functions(&self) -> String {
let mut code = String::new();
for function in &self.functions {
code.push_str(&format!("pub fn {}(", function.name));
for (i, param) in function.params.iter().enumerate() {
if i > 0 {
code.push_str(", ");
}
code.push_str(&format!("{}: {}", param.name, param.param_type));
if param.is_optional {
code.push_str(" = None");
} else if let Some(ref default) = param.default_value {
code.push_str(&format!(" = {}", default));
}
}
code.push_str(&format!(") -> {} {{\n", function.return_type));
code.push_str(&format!(" // Implementation in {}\n", function.language));
code.push_str(" unimplemented!()\n");
code.push_str("}\n\n");
}
code
}
fn generate_services(&self) -> String {
let mut code = String::new();
for service in &self.services {
code.push_str(&format!("#[async_trait]\npub trait {} {{\n", service.name));
for method in &service.methods {
code.push_str(&format!(" #[allow({})]\n", method.allowed_roles.join(", ")));
code.push_str(&format!(" async fn {}(", method.name));
for (i, param) in method.params.iter().enumerate() {
if i > 0 {
code.push_str(", ");
}
code.push_str(&format!("{}: {}", param.name, param.param_type));
}
code.push_str(&format!(") -> Result<{}, Error>;\n", method.return_type));
}
code.push_str("}\n\n");
// Generate a mock implementation
code.push_str(&format!("pub struct Mock{};\n\n", service.name));
code.push_str(&format!("#[async_trait]\nimpl {} for Mock{} {{\n", service.name, service.name));
for method in &service.methods {
code.push_str(&format!(" async fn {}(", method.name));
for (i, param) in method.params.iter().enumerate() {
if i > 0 {
code.push_str(", ");
}
code.push_str(&format!("{}: {}", param.name, param.param_type));
}
code.push_str(&format!(") -> Result<{}, Error> {{\n", method.return_type));
code.push_str(" unimplemented!()\n");
code.push_str(" }\n\n");
}
code.push_str("}\n\n");
}
code
}
fn generate_hooks(&self) -> String {
let mut code = String::new();
for hook in &self.hooks {
code.push_str(&format!("pub fn {}(", hook.model));
for (i, param) in hook.params.iter().enumerate() {
if i > 0 {
code.push_str(", ");
}
code.push_str(&format!("{}: {}", param.name, param.param_type));
}
code.push_str(&format!(") -> Result<(), Error> {{
// Implementation in {}\n", hook.language));
code.push_str(" unimplemented!()\n");
code.push_str("}\n\n");
}
code
}
fn generate_realtimes(&self) -> String {
let mut code = String::new();
for realtime in &self.realtimes {
code.push_str(&format!("pub fn {}(", realtime.name));
for (i, param) in realtime.params.iter().enumerate() {
if i > 0 {
code.push_str(", ");
}
code.push_str(&format!("{}: {}", param.name, param.param_type));
}
code.push_str(&format!(") -> Result<(), Error> {{
// Implementation in {}\n", realtime.language));
code.push_str(" unimplemented!()\n");
code.push_str("}\n\n");
}
code
}
fn generate_main(&self) -> String {
let mut code = String::new();
code.push_str("fn main() -> Result<()> {\n");
code.push_str(" println!(\"Wyre backend started\");\n");
code.push_str(" Ok(())");
code.push_str("}\n");
code
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let parser = WyreScript::parse(Rule::wyre_script, SAMPLE_WYRE_SCRIPT);
match parser {
Ok(parsed) => {
println!("\n\x1b[1;36m┌────────────────────────────────────────────────────────────────────────────┐\x1b[0m");
println!("\x1b[1;36m│\x1b[0m \x1b[1;32mParsed script\x1b[0m \x1b[1;36m│\x1b[0m");
println!("\x1b[1;36m└────────────────────────────────────────────────────────────────────────────┘\x1b[0m");
for pair in parsed.clone() {
print_pair(pair, 0);
}
let mut generator = CodeGenerator::new();
generator.parse_wyre_script(parsed.into_iter());
let generated_code = generator.generate_code();
println!("\n\x1b[1;36m┌────────────────────────────────────────────────────────────────────────────┐\x1b[0m");
println!("\x1b[1;36m│\x1b[0m \x1b[1;33mGenerated code\x1b[0m \x1b[1;36m│\x1b[0m");
println!("\x1b[1;36m└────────────────────────────────────────────────────────────────────────────┘\x1b[0m");
println!("\x1b[0;37m{}\x1b[0m", generated_code);
write_to_file("generated_code.rs", generated_code);
}
Err(e) => {
println!("\n\x1b[1;36m┌────────────────────────────────────────────────────────────────────────────┐\x1b[0m");
println!("\x1b[1;36m│\x1b[0m \x1b[1;31mError parsing script\x1b[0m \x1b[1;36m│\x1b[0m");
println!("\x1b[1;36m└────────────────────────────────────────────────────────────────────────────┘\x1b[0m");
println!("\x1b[1;31m{}\x1b[0m", e);
}
}
Ok(())
}
fn print_pair(pair: pest::iterators::Pair<Rule>, indent: usize) {
let indent_str = " ".repeat(indent);
println!("\x1b[1;34m{}├─ \x1b[1;35mRule:\x1b[0m {:?}", indent_str, pair.as_rule());
println!("\x1b[1;34m{}│ ├─ \x1b[1;36mSpan:\x1b[0m {:?}", indent_str, pair.as_span());
println!("\x1b[1;34m{}│ └─ \x1b[1;33mText:\x1b[0m {}", indent_str, pair.as_str());
let inner_pairs: Vec<_> = pair.into_inner().collect();
for (i, inner_pair) in inner_pairs.clone().into_iter().enumerate() {
if i == inner_pairs.len() - 1 {
println!("\x1b[1;34m{}└─\x1b[0m", indent_str);
} else {
println!("\x1b[1;34m{}│\x1b[0m", indent_str);
}
print_pair(inner_pair, indent + 1);
}
}
fn write_to_file<T: AsRef<str>>(filename: &str, content: T) {
ensure_dir_exists("workspace/src");
let content = content.as_ref();
let mut file = File::create(format!("workspace/src/{}", filename)).expect("Failed to create file");
file.write_all(content.as_bytes()).expect("Failed to write to file");
println!("\x1b[1;32m✔ File '{}' created successfully.\x1b[0m", filename);
}
fn ensure_dir_exists(path: &str) {
if !Path::new(path).exists() {
std::fs::create_dir_all(path).expect("Failed to create directory");
println!("\x1b[1;33m➜ Directory '{}' created.\x1b[0m", path);
}
}