Start working on rust compile step
This commit is contained in:
75
crates/libjrpc/src/compile.rs
Normal file
75
crates/libjrpc/src/compile.rs
Normal file
@ -0,0 +1,75 @@
|
||||
use std::{collections::HashMap, path::PathBuf};
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
|
||||
use crate::ir::{EnumDefinition, ServiceDefinition, TypeDefinition};
|
||||
|
||||
pub trait Compile {
|
||||
fn name(&self) -> String;
|
||||
|
||||
fn start(&mut self, ctx: &mut CompileContext, options: HashMap<String, String>) -> Result<()>;
|
||||
|
||||
fn generate_type(&mut self, ctx: &mut CompileContext, definition: TypeDefinition)
|
||||
-> Result<()>;
|
||||
fn generate_enum(&mut self, ctx: &mut CompileContext, definition: EnumDefinition)
|
||||
-> Result<()>;
|
||||
fn generate_service(
|
||||
&mut self,
|
||||
ctx: &mut CompileContext,
|
||||
definition: ServiceDefinition,
|
||||
) -> Result<()>;
|
||||
|
||||
fn finalize(&mut self, ctx: &mut CompileContext) -> Result<()>;
|
||||
}
|
||||
|
||||
pub struct CompileContext {
|
||||
output_folder: PathBuf,
|
||||
}
|
||||
impl CompileContext {
|
||||
pub fn new(output_folder: &str) -> Self {
|
||||
CompileContext {
|
||||
output_folder: output_folder.into(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn write_file(&self, filename: &str, content: String) -> Result<()> {
|
||||
let res_path = self.output_folder.clone().join(filename);
|
||||
let res_dir = res_path.parent().context("Path has no parent!")?;
|
||||
std::fs::create_dir_all(res_dir)?;
|
||||
std::fs::write(res_path, content)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct FileGenerator {
|
||||
content: String,
|
||||
}
|
||||
|
||||
impl FileGenerator {
|
||||
pub fn new() -> Self {
|
||||
FileGenerator {
|
||||
content: String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn a<T: ToString>(&mut self, indent: u32, content: T) {
|
||||
for _ in 0..indent {
|
||||
self.content.push_str(" ");
|
||||
}
|
||||
self.content.push_str(&content.to_string());
|
||||
self.content.push_str("\n");
|
||||
}
|
||||
|
||||
pub fn add_line(&mut self, line: &str) {
|
||||
self.content.push_str(line);
|
||||
self.content.push_str("\n");
|
||||
}
|
||||
|
||||
pub fn get_content(&mut self) -> String {
|
||||
self.content.clone()
|
||||
}
|
||||
|
||||
pub fn into_content(self) -> String {
|
||||
self.content
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user