Skip to content

Commit

Permalink
Refactoring after clippy lint
Browse files Browse the repository at this point in the history
  • Loading branch information
e3m3 committed Sep 11, 2024
1 parent 2bbbc76 commit d079d3a
Show file tree
Hide file tree
Showing 12 changed files with 118 additions and 281 deletions.
3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,6 @@ llvm-sys = { version = "=181.1.1", features = ["force-dynamic"] }

[dev-dependencies]
lit = "1.0.4"

[lints.clippy]
unused_unit = "allow"
11 changes: 3 additions & 8 deletions src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,9 @@ pub fn op_to_string(op: &Operator) -> String {

pub type Vars = Vec<String>;

#[derive(Clone)]
#[derive(Clone,Default)]
pub enum ExprKind<'a> {
#[default]
Undefined,
Factor(Factor),
BinaryOp(Operator, &'a Expr<'a>, &'a Expr<'a>),
Expand All @@ -67,20 +68,14 @@ pub fn vars_to_string(vars: &Vars) -> String {
format!("Vars([{}])", vars.join(","))
}

impl <'a> Default for ExprKind<'a> {
fn default() -> Self {
ExprKind::Undefined
}
}

pub struct Expr<'a> {
expr: ExprKind<'a>,
vars: usize,
}

impl <'a> Expr<'a> {
pub fn new(expr: ExprKind<'a>, n: usize) -> Self {
Expr{expr: expr, vars: n}
Expr{expr, vars: n}
}

pub fn new_number(n: i64) -> Self {
Expand Down
16 changes: 5 additions & 11 deletions src/irgen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ use std::ffi::c_uint;
use crate::ast;
use crate::exit_code;
use crate::module;
use crate::options;

use ast::Ast;
use ast::AstGenerator;
Expand All @@ -29,19 +28,14 @@ use exit_code::exit;
use exit_code::ExitCode;
use module::FunctionSignature;
use module::ModuleBundle;
use options::RunOptions;

pub struct IRGen<'a, 'b> {
bundle: &'a mut ModuleBundle<'b>,
_options: &'a RunOptions,
}

impl <'a, 'b> IRGen<'a, 'b> {
pub fn new(bundle: &'a mut ModuleBundle<'b>, options: &'a RunOptions) -> Self {
IRGen{
bundle: bundle,
_options: options,
}
pub fn new(bundle: &'a mut ModuleBundle<'b>) -> Self {
IRGen{bundle}
}

fn gen_entry(&mut self, n: usize) -> LLVMBasicBlockRef {
Expand Down Expand Up @@ -131,7 +125,7 @@ impl <'a, 'b> IRGen<'a, 'b> {
/// needed if longer multi-statement programs are implemented.
fn gen_expr_withdecl(&mut self, vars: &Vars, e: &Expr) -> GenResult {
let f = self.bundle.f.expect("Missing parent function");
for (i, var) in vars.into_iter().enumerate() {
for (i, var) in vars.iter().enumerate() {
unsafe {
let alloca_value = self.bundle.gen_alloca(var.as_str(), self.bundle.t_i64);
let init_value = LLVMGetParam(f, i as c_uint);
Expand All @@ -141,8 +135,8 @@ impl <'a, 'b> IRGen<'a, 'b> {
self.visit(e)
}

pub fn gen(ast: &dyn Ast, bundle: &'a mut ModuleBundle<'b>, options: &'a RunOptions) -> bool {
let mut ir_gen = IRGen::new(bundle, options);
pub fn gen(ast: &dyn Ast, bundle: &'a mut ModuleBundle<'b>) -> bool {
let mut ir_gen = IRGen::new(bundle);
let n = ast.get_vars();
let bb = ir_gen.gen_entry(n);
let ir_gen_result: GenResult = ast.accept_gen(&mut ir_gen);
Expand Down
58 changes: 31 additions & 27 deletions src/lex.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// Copyright 2024, Giordano Salvador
// SPDX-License-Identifier: BSD-3-Clause

use std::fmt;
use std::fmt::Display;
use std::io::BufRead;
use std::io::BufReader;
use std::io::Read;
Expand All @@ -12,8 +14,10 @@ use exit_code::exit;
use exit_code::ExitCode;
use options::RunOptions;

#[derive(Clone,Copy,Eq,PartialEq)]
#[derive(Clone,Copy,Default,Eq,PartialEq)]
pub enum TokenKind {
#[default]
Unknown,
Comma,
Comment,
Colon,
Expand All @@ -27,7 +31,6 @@ pub enum TokenKind {
Plus,
Slash,
Star,
Unknown,
With,
}

Expand All @@ -51,12 +54,6 @@ pub fn token_kind_to_string(k: TokenKind) -> String {
})
}

impl Default for TokenKind {
fn default() -> Self {
TokenKind::Unknown
}
}

#[derive(Clone)]
pub struct Token {
pub kind: TokenKind,
Expand All @@ -71,7 +68,7 @@ impl Default for Token {

impl Token {
pub fn new(k: TokenKind, text: String) -> Self {
Token{kind: k, text: text}
Token{kind: k, text}
}

pub fn is(&self, k: TokenKind) -> bool {
Expand All @@ -89,9 +86,11 @@ impl Token {
}
f(self, false, ks)
}
}

pub fn to_string(&self) -> String {
format!("{}:{}", token_kind_to_string(self.kind), self.text)
impl Display for Token {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}:{}", token_kind_to_string(self.kind), self.text)
}
}

Expand All @@ -105,14 +104,13 @@ pub struct Lexer<'a, T: Read> {

impl <'a, T: Read> Lexer<'a, T> {
pub fn new(readable: T, options: &'a RunOptions) -> Self {
let lexer = Lexer{
Lexer{
buffer: BufReader::new(readable),
line: String::new(),
line_count: 0,
position: 0,
options: options,
};
lexer
options,
}
}

fn has_next(&mut self) -> bool {
Expand Down Expand Up @@ -192,14 +190,12 @@ impl <'a, T: Read> Lexer<'a, T> {
if Self::is_whitespace(c) {
self.form_token(t, pos_start, pos_start + 1, TokenKind::Eol);
} else if Self::is_digit(c) {
if c == '0' {
if self.has_next_in_line(pos_start + 1) {
c = self.next_char_in_line(pos_start + 1);
if c == 'x' {
let pos_end: usize = self.collect_token_sequence(pos_start + 2, Self::is_hex_digit);
self.form_token(t, pos_start, pos_end, TokenKind::Number);
return;
}
if c == '0' && self.has_next_in_line(pos_start + 1) {
c = self.next_char_in_line(pos_start + 1);
if c == 'x' {
let pos_end: usize = self.collect_token_sequence(pos_start + 2, Self::is_hex_digit);
self.form_token(t, pos_start, pos_end, TokenKind::Number);
return;
}
}
let pos_end: usize = self.collect_token_sequence(pos_start + 1, Self::is_digit);
Expand Down Expand Up @@ -269,19 +265,27 @@ impl <'a, T: Read> Lexer<'a, T> {
}

fn is_digit(c: char) -> bool {
c >= '0' && c <= '9'
c.is_ascii_digit()
}

fn is_ident(c: char) -> bool {
Self::is_digit(c) || Self::is_letter(c)
}

fn is_hex_digit(c: char) -> bool {
(c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')
Self::is_digit(c) || Self::is_letter_lower(c) || Self::is_letter_upper(c)
}

fn is_letter_lower(c:char) -> bool {
c.is_ascii_lowercase()
}

fn is_letter_upper(c:char) -> bool {
c.is_ascii_uppercase()
}

fn is_letter(c: char) -> bool {
(c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_'
Self::is_letter_lower(c) || Self::is_letter_upper(c) || c == '_'
}

pub fn lex_input(ts: &mut Vec<Token>, lex: &mut Lexer<'a, T>, options: &RunOptions) -> () {
Expand All @@ -292,7 +296,7 @@ impl <'a, T: Read> Lexer<'a, T> {
eprintln!("Found unknown token '{}' in lexer", t.text);
if !options.drop_token { exit(ExitCode::LexerError); }
} else if options.verbose {
eprintln!("Lexed token '{}'", t.to_string());
eprintln!("Lexed token '{}'", t);
}
if t.is(TokenKind::Comment) || t.is(TokenKind::Eol) {
// Drop the comments and end of lines before parsing
Expand Down
42 changes: 20 additions & 22 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,12 +95,12 @@ fn output_type_to_string(t: OutputType) -> String {
}

fn parse_args<'a>(
args: &'a Vec<String>,
args: &'a [String],
input: &mut InputType<'a>,
output: &mut OutputType<'a>,
options: &mut RunOptions
) {
let _bin_name: &String = args.get(0).unwrap();
let _bin_name: &String = args.first().unwrap();
let mut arg: &'a String;
let mut i: usize = 1;

Expand All @@ -114,7 +114,7 @@ fn parse_args<'a>(
"-h" => help(ExitCode::Ok),
"--help" => help(ExitCode::Ok),
"--lex" => options.lex_exit = true,
"--llvmir" => options.codegen_type = CodeGenType::LLVMIR,
"--llvmir" => options.codegen_type = CodeGenType::Llvmir,
"--nomain" => options.no_main = true,
"--notarget" => options.no_target = true,
"-o" => *output = OutputType::File(parse_arg_after(args, &mut i)),
Expand All @@ -124,7 +124,7 @@ fn parse_args<'a>(
"-O3" => options.opt_level = OptLevel::O3,
"--parse" => options.parse_exit = true,
"--sem" => options.sem_exit = true,
"-S" => options.codegen_type = CodeGenType::LLVMIR,
"-S" => options.codegen_type = CodeGenType::Llvmir,
"-v" => options.verbose = true,
"--verbose" => options.verbose = true,
"--version" => print_pkg_info(true),
Expand Down Expand Up @@ -152,10 +152,10 @@ fn parse_args<'a>(
if ext != ".bc" && ext != ".ll" {
eprintln!("Output name '{}' should end in '.bc' or '.ll", f);
exit(ExitCode::ArgParseError);
} else if ext == ".bc" && options.codegen_type == CodeGenType::LLVMIR {
} else if ext == ".bc" && options.codegen_type == CodeGenType::Llvmir {
eprintln!("LLVM IR file type (with '-S' flag) should match output name ('.ll' extension)");
exit(ExitCode::ArgParseError);
} else if ext == ".ll" && options.codegen_type == CodeGenType::BYTECODE {
} else if ext == ".ll" && options.codegen_type == CodeGenType::Bytecode {
eprintln!("Bytecode file type (missing '-S' flag) should match output name ('.bc' extension)");
exit(ExitCode::ArgParseError);
}
Expand All @@ -167,7 +167,7 @@ fn parse_args<'a>(
}
}

fn parse_arg_after<'a>(args: &'a Vec<String>, i: &mut usize) -> &'a str {
fn parse_arg_after<'a>(args: &'a [String], i: &mut usize) -> &'a str {
let name_option = args.get(*i).unwrap();
match args.get(*i + 1) {
Some(arg) => {
Expand Down Expand Up @@ -205,15 +205,13 @@ fn parse_arg_complex<'a>(
}
}
}
} else if *input != InputType::None {
eprintln!("Found more than one input ('{}' and '{}')", input_type_to_string(*input), arg);
help(ExitCode::ArgParseError);
} else if arg.len() == 1 && lead_char == '-' {
*input = InputType::Stdin;
} else {
if *input != InputType::None {
eprintln!("Found more than one input ('{}' and '{}')", input_type_to_string(*input), arg);
help(ExitCode::ArgParseError);
} else if arg.len() == 1 && lead_char == '-' {
*input = InputType::Stdin;
} else {
*input = InputType::File(arg.as_str());
}
*input = InputType::File(arg.as_str());
}
}

Expand All @@ -226,19 +224,19 @@ fn write_module(bundle: &mut ModuleBundle, codegen_type: CodeGenType, output: &O
match *output {
OutputType::Stdout => {
match codegen_type {
CodeGenType::LLVMIR => {
CodeGenType::Llvmir => {
let string: String = bundle.to_string();
println!("{}", string);
},
CodeGenType::BYTECODE => {
CodeGenType::Bytecode => {
eprintln!("Unimplemented: writing bytecode to Stdout");
return false;
},
}
},
OutputType::File(f) => {
match codegen_type {
CodeGenType::LLVMIR => {
CodeGenType::Llvmir => {
let string: String = bundle.to_string();
let mut file = match File::create(f) {
Ok(file) => file,
Expand All @@ -255,12 +253,12 @@ fn write_module(bundle: &mut ModuleBundle, codegen_type: CodeGenType, output: &O
}
}
},
CodeGenType::BYTECODE => bundle.write_bitcode_to_file(f),
CodeGenType::Bytecode => bundle.write_bitcode_to_file(f),
}
},
}

return true;
true
}

fn main() -> ! {
Expand Down Expand Up @@ -302,7 +300,7 @@ fn main() -> ! {

let module_name_irgen = String::from("calcc");
let mut module_irgen = ModuleBundle::new(&module_name_irgen, options.verbose);
let irgen_status: bool = IRGen::gen(*ast, &mut module_irgen, &options);
let irgen_status: bool = IRGen::gen(*ast, &mut module_irgen);
assert!(irgen_status);
let irgen_verify: bool = module_irgen.verify_module();
if !irgen_verify {
Expand All @@ -321,7 +319,7 @@ fn main() -> ! {
//let f_sig = module_main.get_f_sig_from_context(&module_irgen.f_sig.clone().unwrap());
let f_sig = &module_irgen.f_sig.clone().unwrap();

let maingen_status: bool = MainGen::gen(&mut module_main, &f_sig, &options);
let maingen_status: bool = MainGen::gen(&mut module_main, f_sig);
assert!(maingen_status);

// NOTE: Linking modules causes verifier errors for unmatched contexts of LLVMTypeRef. Skip verification.
Expand Down
Loading

0 comments on commit d079d3a

Please sign in to comment.