Compare commits
No commits in common. "2830a1befdad3d65b70b6d64070a49d17fddb933" and "6c774f960afcb992fa8d7560c91b4440a00d80a8" have entirely different histories.
2830a1befd
...
6c774f960a
@ -22,11 +22,11 @@
|
||||
|
||||
## v0.0.9
|
||||
|
||||
- [x] Hand-make CLI, remove clap
|
||||
- [x] Compile a single file
|
||||
- [ ] Display error messages during compilation instead of panicking
|
||||
- [ ] Improve errror messages
|
||||
- [ ] Hand made CLI, remove clap
|
||||
- [ ] Compile a single file
|
||||
- [ ] Implement code generation for ast nodes implemented as of now
|
||||
- [ ] Display error messages during compilation
|
||||
- [ ] Improve errror messages
|
||||
|
||||
|
||||
|
||||
|
@ -1,50 +0,0 @@
|
||||
use colored::*;
|
||||
|
||||
pub fn compile_command(arguments: Vec<String>) {
|
||||
if arguments.is_empty() {
|
||||
println!("{}", compile_help());
|
||||
println!("{}: {}", "error".on_red(), "No file specified");
|
||||
return;
|
||||
}
|
||||
if arguments.len() > 1 {
|
||||
println!("{}", compile_help());
|
||||
println!(
|
||||
"{}: {}",
|
||||
"error".on_red(),
|
||||
"Only a single file can be compiled at a time"
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
let argument = &arguments[0];
|
||||
if argument.starts_with("-") {
|
||||
let opt_str = argument.as_str();
|
||||
|
||||
println!("{}", compile_help());
|
||||
|
||||
if opt_str != "-h" && opt_str != "--help" {
|
||||
println!(
|
||||
"{}: {}",
|
||||
"error".on_red(),
|
||||
"Invalid option. The compile command only accepts the `-h` or `--help` option"
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
crate::file::compile_file(argument);
|
||||
}
|
||||
|
||||
fn compile_help() -> String {
|
||||
format!(
|
||||
r#"Compile a single file in place. If the file to compile
|
||||
references other THP files, they will be (typechecked?) as well.
|
||||
|
||||
Usage:
|
||||
|
||||
`thp compile {0}` Compile {0} and output in the same directory
|
||||
`thp compile -h` Print this message & exit
|
||||
"#,
|
||||
"_file_".green()
|
||||
)
|
||||
}
|
@ -7,11 +7,11 @@ enum EmptyOptions {
|
||||
Version,
|
||||
}
|
||||
|
||||
pub fn empty_command(arguments: Vec<String>) {
|
||||
pub fn empty_command(options: &Vec<String>) {
|
||||
// Add all options to a set
|
||||
let mut options_set = std::collections::HashSet::new();
|
||||
for option in arguments {
|
||||
match expand_option(&option) {
|
||||
for option in options {
|
||||
match expand_option(option) {
|
||||
Ok(o) => {
|
||||
options_set.insert(o);
|
||||
}
|
||||
|
@ -1,14 +1,14 @@
|
||||
use crate::cli::get_help_text;
|
||||
use colored::*;
|
||||
|
||||
pub fn help_command(arguments: Vec<String>) {
|
||||
pub fn help_command(options: &Vec<String>) {
|
||||
println!("{}", get_help_text());
|
||||
|
||||
if arguments.len() > 0 {
|
||||
if options.len() > 0 {
|
||||
println!(
|
||||
"{}: {}",
|
||||
"warning".yellow(),
|
||||
"The help command doesn't take any argument."
|
||||
"The help command doesn't take any options."
|
||||
);
|
||||
}
|
||||
}
|
||||
|
@ -1,9 +1,8 @@
|
||||
mod compile;
|
||||
mod empty;
|
||||
mod help;
|
||||
mod types;
|
||||
|
||||
use types::CommandType;
|
||||
use types::{Command, CommandType};
|
||||
|
||||
use colored::*;
|
||||
|
||||
@ -40,7 +39,7 @@ fn get_version() -> String {
|
||||
}
|
||||
|
||||
pub fn run_cli() {
|
||||
let (command, args) = match parse_args() {
|
||||
let command = match parse_args() {
|
||||
Ok(c) => c,
|
||||
Err(reason) => {
|
||||
println!("{}", get_help_text());
|
||||
@ -49,17 +48,38 @@ pub fn run_cli() {
|
||||
}
|
||||
};
|
||||
|
||||
command.run(args);
|
||||
command.run();
|
||||
}
|
||||
|
||||
fn parse_args() -> Result<(CommandType, Vec<String>), String> {
|
||||
fn parse_args() -> Result<Command, String> {
|
||||
let mut args = std::env::args().collect::<Vec<String>>();
|
||||
|
||||
// Remove the first argument, which is the path to the executable
|
||||
args.remove(0);
|
||||
|
||||
let command = match args.get(0) {
|
||||
Some(command) if !command.starts_with('-') => match command.as_str() {
|
||||
let mut args = args.into_iter();
|
||||
let mut options = Vec::new();
|
||||
|
||||
let command = match args.next() {
|
||||
Some(command) if !command.starts_with('-') => Some(command),
|
||||
Some(option) => {
|
||||
options.push(option);
|
||||
None
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
|
||||
for arg in args {
|
||||
if arg.starts_with('-') {
|
||||
options.push(arg);
|
||||
} else {
|
||||
return Err(format!(
|
||||
"Unexpected command `{}`. There can only be one command",
|
||||
arg
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
let command = match command {
|
||||
Some(command) => match command.as_str() {
|
||||
"c" | "compile" => CommandType::Compile,
|
||||
"f" | "format" => CommandType::Format,
|
||||
"r" | "repl" => CommandType::Repl,
|
||||
@ -70,12 +90,8 @@ fn parse_args() -> Result<(CommandType, Vec<String>), String> {
|
||||
"help" | "h" => CommandType::Help,
|
||||
_ => return Err(format!("Unknown command `{}`", command)),
|
||||
},
|
||||
_ => CommandType::None,
|
||||
None => CommandType::None,
|
||||
};
|
||||
|
||||
if command != CommandType::None {
|
||||
args.remove(0);
|
||||
}
|
||||
|
||||
Ok((command, args))
|
||||
Ok(Command { command, options })
|
||||
}
|
||||
|
@ -1,4 +1,10 @@
|
||||
#[derive(Debug, PartialEq)]
|
||||
#[derive(Debug)]
|
||||
pub struct Command {
|
||||
pub command: CommandType,
|
||||
pub options: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum CommandType {
|
||||
Compile,
|
||||
Format,
|
||||
@ -11,11 +17,16 @@ pub enum CommandType {
|
||||
None,
|
||||
}
|
||||
|
||||
impl Command {
|
||||
pub fn run(&self) {
|
||||
self.command.run(&self.options);
|
||||
}
|
||||
}
|
||||
|
||||
impl CommandType {
|
||||
pub fn run(&self, options: Vec<String>) {
|
||||
pub fn run(&self, options: &Vec<String>) {
|
||||
match self {
|
||||
CommandType::Help => super::help::help_command(options),
|
||||
CommandType::Compile => super::compile::compile_command(options),
|
||||
CommandType::None => super::empty::empty_command(options),
|
||||
_ => {
|
||||
println!("Not implemented yet! {:?} {:?}", self, options);
|
||||
|
@ -4,27 +4,38 @@ use crate::syntax::ast::var_binding::Binding;
|
||||
impl Transpilable for Binding {
|
||||
/// Transpiles val and var bindings into PHP.
|
||||
fn transpile(&self) -> String {
|
||||
let expression_str = self.expression.transpile();
|
||||
match self {
|
||||
Binding::Val(val_binding) => {
|
||||
let expression_str = val_binding.expression.transpile();
|
||||
|
||||
format!("${} = {};", self.identifier, expression_str)
|
||||
format!("${} = {};", val_binding.identifier, expression_str)
|
||||
}
|
||||
Binding::Var(var_binding) => {
|
||||
let expression_str = var_binding.expression.transpile();
|
||||
|
||||
format!("${} = {};", var_binding.identifier, expression_str)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::syntax::ast::{var_binding::Binding, Expression};
|
||||
use crate::syntax::ast::{
|
||||
var_binding::{Binding, ValBinding},
|
||||
Expression,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn binding_should_transpile() {
|
||||
let id = String::from("identifier");
|
||||
let value = String::from("322");
|
||||
let binding = Binding {
|
||||
let binding = Binding::Val(ValBinding {
|
||||
datatype: None,
|
||||
identifier: Box::new(id),
|
||||
expression: Expression::Number(Box::new(value)),
|
||||
is_mutable: false,
|
||||
};
|
||||
});
|
||||
|
||||
let result = binding.transpile();
|
||||
|
||||
|
@ -18,18 +18,20 @@ impl Transpilable for ModuleAST {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::syntax::ast::{var_binding::Binding, Expression, TopLevelDeclaration};
|
||||
use crate::syntax::ast::{
|
||||
var_binding::{Binding, ValBinding},
|
||||
Expression, TopLevelDeclaration,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn module_ast_should_transpile() {
|
||||
let id = String::from("identifier");
|
||||
let value = String::from("322");
|
||||
let binding = Binding {
|
||||
let binding = Binding::Val(ValBinding {
|
||||
datatype: None,
|
||||
identifier: Box::new(id),
|
||||
expression: Expression::Number(Box::new(value)),
|
||||
is_mutable: false,
|
||||
};
|
||||
});
|
||||
|
||||
let module = ModuleAST {
|
||||
declarations: vec![TopLevelDeclaration::Binding(binding)],
|
||||
|
@ -4,8 +4,8 @@ use crate::lexic::{token::Token, utils, LexResult};
|
||||
/// Checks if a String is a keyword, and returns its TokenType
|
||||
fn str_is_keyword(s: &String) -> Option<TokenType> {
|
||||
match s.as_str() {
|
||||
"let" => Some(TokenType::LET),
|
||||
"mut" => Some(TokenType::MUT),
|
||||
"var" => Some(TokenType::VAR),
|
||||
"val" => Some(TokenType::VAL),
|
||||
"fun" => Some(TokenType::FUN),
|
||||
_ => None,
|
||||
}
|
||||
@ -141,23 +141,23 @@ mod tests {
|
||||
// Should scan keywords
|
||||
#[test]
|
||||
fn test_4() {
|
||||
let input = str_to_vec("mut");
|
||||
let input = str_to_vec("var");
|
||||
let start_pos = 0;
|
||||
if let LexResult::Some(token, next) = scan(*input.get(0).unwrap(), &input, start_pos) {
|
||||
assert_eq!(3, next);
|
||||
assert_eq!(TokenType::MUT, token.token_type);
|
||||
assert_eq!("mut", token.value);
|
||||
assert_eq!(TokenType::VAR, token.token_type);
|
||||
assert_eq!("var", token.value);
|
||||
assert_eq!(0, token.position);
|
||||
} else {
|
||||
panic!()
|
||||
}
|
||||
|
||||
let input = str_to_vec("let");
|
||||
let input = str_to_vec("val");
|
||||
let start_pos = 0;
|
||||
if let LexResult::Some(token, next) = scan(*input.get(0).unwrap(), &input, start_pos) {
|
||||
assert_eq!(3, next);
|
||||
assert_eq!(TokenType::LET, token.token_type);
|
||||
assert_eq!("let", token.value);
|
||||
assert_eq!(TokenType::VAL, token.token_type);
|
||||
assert_eq!("val", token.value);
|
||||
assert_eq!(0, token.position);
|
||||
} else {
|
||||
panic!()
|
||||
|
@ -15,8 +15,8 @@ pub enum TokenType {
|
||||
Comment,
|
||||
INDENT,
|
||||
DEDENT,
|
||||
LET,
|
||||
MUT,
|
||||
VAR,
|
||||
VAL,
|
||||
EOF,
|
||||
FUN,
|
||||
}
|
||||
|
@ -1,9 +1,21 @@
|
||||
use super::Expression;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Binding {
|
||||
pub enum Binding {
|
||||
Val(ValBinding),
|
||||
Var(VarBinding),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ValBinding {
|
||||
pub datatype: Option<String>,
|
||||
pub identifier: Box<String>,
|
||||
pub expression: Expression,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct VarBinding {
|
||||
pub datatype: Option<String>,
|
||||
pub identifier: Box<String>,
|
||||
pub expression: Expression,
|
||||
pub is_mutable: bool,
|
||||
}
|
||||
|
@ -1,4 +1,4 @@
|
||||
use super::ast::var_binding::Binding;
|
||||
use super::ast::var_binding::{Binding, ValBinding, VarBinding};
|
||||
use super::utils::{parse_token_type, try_operator};
|
||||
use super::{expression, ParseResult};
|
||||
use crate::error_handling::SyntaxError;
|
||||
@ -8,22 +8,22 @@ use crate::utils::Result3;
|
||||
pub fn try_parse<'a>(tokens: &'a Vec<Token>, pos: usize) -> ParseResult<Binding, ()> {
|
||||
let mut current_pos = pos;
|
||||
|
||||
// TODO: Detect if the binding starts with a datatype
|
||||
|
||||
/*
|
||||
* let keyword
|
||||
* val/var keyword
|
||||
*/
|
||||
let (is_mutable, binding_token, next_pos) = {
|
||||
let let_token = parse_token_type(tokens, current_pos, TokenType::LET);
|
||||
match let_token {
|
||||
ParseResult::Ok(let_token, next_let) => {
|
||||
let mut_token = parse_token_type(tokens, next_let, TokenType::MUT);
|
||||
match mut_token {
|
||||
ParseResult::Ok(_mut_token, next_mut) => (true, let_token, next_mut),
|
||||
_ => (false, let_token, next_let),
|
||||
let (is_val, binding_token, next_pos) = {
|
||||
let res1 = parse_token_type(tokens, current_pos, TokenType::VAL);
|
||||
match res1 {
|
||||
ParseResult::Ok(val_token, next) => (true, val_token, next),
|
||||
_ => {
|
||||
let res2 = parse_token_type(tokens, current_pos, TokenType::VAR);
|
||||
match res2 {
|
||||
ParseResult::Ok(var_token, next) => (false, var_token, next),
|
||||
// Neither VAL nor VAR were matched, the caller should try
|
||||
// other constructs
|
||||
_ => return ParseResult::Unmatched,
|
||||
}
|
||||
}
|
||||
_ => return ParseResult::Unmatched,
|
||||
}
|
||||
};
|
||||
current_pos = next_pos;
|
||||
@ -50,7 +50,7 @@ pub fn try_parse<'a>(tokens: &'a Vec<Token>, pos: usize) -> ParseResult<Binding,
|
||||
return ParseResult::Err(SyntaxError {
|
||||
reason: format!(
|
||||
"There should be an identifier after a `{}` token",
|
||||
if is_mutable { "val" } else { "var" }
|
||||
if is_val { "val" } else { "var" }
|
||||
),
|
||||
error_start: binding_token.position,
|
||||
error_end: binding_token.get_end_position(),
|
||||
@ -95,11 +95,18 @@ pub fn try_parse<'a>(tokens: &'a Vec<Token>, pos: usize) -> ParseResult<Binding,
|
||||
};
|
||||
current_pos = next_pos;
|
||||
|
||||
let binding = Binding {
|
||||
datatype: None,
|
||||
identifier: Box::new(identifier.value.clone()),
|
||||
expression,
|
||||
is_mutable,
|
||||
let binding = if is_val {
|
||||
Binding::Val(ValBinding {
|
||||
datatype: None,
|
||||
identifier: Box::new(identifier.value.clone()),
|
||||
expression,
|
||||
})
|
||||
} else {
|
||||
Binding::Var(VarBinding {
|
||||
datatype: None,
|
||||
identifier: Box::new(identifier.value.clone()),
|
||||
expression,
|
||||
})
|
||||
};
|
||||
|
||||
ParseResult::Ok(binding, current_pos)
|
||||
@ -112,8 +119,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn should_parse_val_binding() {
|
||||
let tokens = get_tokens(&String::from("let identifier = 20")).unwrap();
|
||||
let ParseResult::Ok(binding, _) = try_parse(&tokens, 0) else {
|
||||
let tokens = get_tokens(&String::from("val identifier = 20")).unwrap();
|
||||
let ParseResult::Ok(Binding::Val(binding), _) = try_parse(&tokens, 0) else {
|
||||
panic!()
|
||||
};
|
||||
|
||||
@ -122,11 +129,11 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn should_parse_val() {
|
||||
let tokens = get_tokens(&String::from("let")).unwrap();
|
||||
let token = *try_token_type(&tokens, 0, TokenType::LET).unwrap();
|
||||
let tokens = get_tokens(&String::from("val")).unwrap();
|
||||
let token = *try_token_type(&tokens, 0, TokenType::VAL).unwrap();
|
||||
|
||||
assert_eq!(TokenType::LET, token.token_type);
|
||||
assert_eq!("let", token.value);
|
||||
assert_eq!(TokenType::VAL, token.token_type);
|
||||
assert_eq!("val", token.value);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -168,8 +175,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn should_return_correct_error() {
|
||||
let tokens = get_tokens(&String::from("let")).unwrap();
|
||||
assert_eq!(TokenType::LET, tokens[0].token_type);
|
||||
let tokens = get_tokens(&String::from("val")).unwrap();
|
||||
assert_eq!(TokenType::VAL, tokens[0].token_type);
|
||||
assert_eq!(0, tokens[0].position);
|
||||
let binding = try_parse(&tokens, 0);
|
||||
|
||||
@ -184,8 +191,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn should_return_error_when_identifier_is_wrong() {
|
||||
let tokens = get_tokens(&String::from("let 322")).unwrap();
|
||||
assert_eq!(TokenType::LET, tokens[0].token_type);
|
||||
let tokens = get_tokens(&String::from("val 322")).unwrap();
|
||||
assert_eq!(TokenType::VAL, tokens[0].token_type);
|
||||
assert_eq!(0, tokens[0].position);
|
||||
let binding = try_parse(&tokens, 0);
|
||||
|
||||
@ -197,7 +204,7 @@ mod tests {
|
||||
_ => panic!("Error expected"),
|
||||
}
|
||||
|
||||
let tokens = get_tokens(&String::from("let \"hello\"")).unwrap();
|
||||
let tokens = get_tokens(&String::from("val \"hello\"")).unwrap();
|
||||
let binding = try_parse(&tokens, 0);
|
||||
|
||||
match binding {
|
||||
@ -211,7 +218,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn should_return_error_when_equal_op_is_wrong() {
|
||||
let tokens = get_tokens(&String::from("let id \"error\"")).unwrap();
|
||||
let tokens = get_tokens(&String::from("val id \"error\"")).unwrap();
|
||||
let binding = try_parse(&tokens, 0);
|
||||
|
||||
match binding {
|
||||
|
@ -39,7 +39,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn should_parse_binding() {
|
||||
let input = String::from("let identifier = 20");
|
||||
let input = String::from("val identifier = 20");
|
||||
let tokens = crate::lexic::get_tokens(&input).unwrap();
|
||||
let statement = try_parse(&tokens, 0);
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user