[Codegen] Minimal codegen for a Block

master
Araozu 2024-01-02 07:06:46 -05:00
parent ef70bc1cc0
commit 61de3b100f
9 changed files with 43 additions and 3 deletions

View File

@ -15,6 +15,7 @@
- Watch mode
- Formatter
- Simple language server
- Decide how to handle comments in the syntax (?)
## v0.0.10

14
src/codegen/block.rs Normal file
View File

@ -0,0 +1,14 @@
use crate::syntax::ast::Block;
use super::Transpilable;
impl Transpilable for Block {
fn transpile(&self) -> String {
// TODO: Handle indentation
self.statements
.iter()
.map(|x| x.transpile())
.collect::<Vec<_>>()
.join("\n")
}
}

View File

@ -4,7 +4,11 @@ use super::Transpilable;
impl Transpilable for FunctionDeclaration {
fn transpile(&self) -> String {
format!("function {}() {{}}", self.identifier)
format!(
"function {}() {{\n{}\n}}",
self.identifier,
self.block.transpile()
)
}
}

View File

@ -1,9 +1,11 @@
use crate::syntax::ast::ModuleAST;
mod binding;
mod block;
mod expression;
mod function_declaration;
mod module_ast;
mod statement;
mod top_level_construct;
/// Trait that the AST and its nodes implement to support transformation to PHP

View File

@ -11,7 +11,7 @@ impl Transpilable for ModuleAST {
.map(|binding| binding.transpile())
.collect();
bindings_str.join("\n")
format!("<?php\n\n{}\n", bindings_str.join("\n"))
}
}

9
src/codegen/statement.rs Normal file
View File

@ -0,0 +1,9 @@
use crate::syntax::ast::statement::Statement;
use super::Transpilable;
impl Transpilable for Statement {
fn transpile(&self) -> String {
String::from("// TODO (statement)")
}
}

View File

@ -449,4 +449,12 @@ mod indentation_tests {
assert_eq!(TokenType::DEDENT, tokens[8].token_type);
assert_eq!(TokenType::EOF, tokens[9].token_type);
}
#[test]
fn should_lex_comments() {
let input = String::from("// ??");
let tokens = get_tokens(&input).unwrap();
assert_eq!(TokenType::Comment, tokens[0].token_type);
}
}

View File

@ -18,6 +18,7 @@ pub enum TopLevelDeclaration {
pub struct FunctionDeclaration {
pub identifier: Box<String>,
pub params_list: Box<ParamsList>,
pub block: Box<Block>,
}
#[derive(Debug)]

View File

@ -64,7 +64,7 @@ pub fn try_parse<'a>(tokens: &'a Vec<Token>, pos: usize) -> ParseResult<Function
};
current_pos = next_pos;
let (_block, next_pos) = match parse_block(tokens, current_pos) {
let (block, next_pos) = match parse_block(tokens, current_pos) {
ParseResult::Ok(block, next_pos) => (block, next_pos),
ParseResult::Err(error) => {
return ParseResult::Err(error);
@ -91,6 +91,7 @@ pub fn try_parse<'a>(tokens: &'a Vec<Token>, pos: usize) -> ParseResult<Function
FunctionDeclaration {
identifier: Box::new(identifier.value.clone()),
params_list: Box::new(params_list),
block: Box::new(block),
},
current_pos,
)