Compare commits

...

6 Commits

Author SHA1 Message Date
1224c612c7 Codegen & compile char, change *str to *char 2025-07-22 15:07:33 +03:00
108cf6efa5 Add FCmp to codegen 2025-07-22 15:01:02 +03:00
9b9398ac26 Add lexing of escaped characters, add parsing of characters 2025-07-22 14:57:09 +03:00
e220900ac3 Start adding chars 2025-07-22 14:44:28 +03:00
9c0d373f9d Fix casting to same type 2025-07-22 14:21:17 +03:00
e27aa4b8ab Fix pointer-casting 2025-07-22 14:19:28 +03:00
13 changed files with 131 additions and 109 deletions

View File

@ -1,14 +1,14 @@
extern fn puts(message: *str) -> i32;
extern fn puts(message: *char) -> i32;
extern fn malloc(size: u64) -> *u8;
extern fn div(numerator: i32, denominator: i32) -> div_t;
struct div_t {
quotient: i32,
remainder: i32,
}
extern fn div(numerator: i32, denominator: i32) -> div_t;
pub fn print(message: *str) {
pub fn print(message: *char) {
puts(message);
}
@ -16,6 +16,10 @@ pub fn int_div(numerator: i32, denominator: i32) -> div_t {
return div(numerator, denominator);
}
pub fn allocate(size: u64) -> *u8 {
malloc(size)
}
fn main() -> u16 {
return 0;
}

View File

@ -31,7 +31,7 @@ pub enum TypeKind {
F128,
F80,
F128PPC,
Str,
Char,
Array(Box<TypeKind>, u64),
Custom(String),
Borrow(Box<TypeKind>, bool),
@ -44,6 +44,7 @@ pub enum Literal {
Decimal(f64),
Bool(bool),
String(String),
Char(char),
}
#[derive(Debug, Clone)]

View File

@ -60,7 +60,7 @@ impl Parse for Type {
"f80" => TypeKind::F80,
"f128" => TypeKind::F128,
"f128ppc" => TypeKind::F128PPC,
"str" => TypeKind::Str,
"char" => TypeKind::Char,
_ => TypeKind::Custom(ident),
}
} else {
@ -177,6 +177,20 @@ impl Parse for PrimaryExpression {
stream.get_range().unwrap(),
)
}
Token::CharLit(v) => {
stream.next(); // Consume
let chars = v.as_bytes();
if chars.len() == 0 {
stream.expected_err("char to not be empty")?;
} else if chars.len() > 0 {
stream.expected_err("char to only have one char inside it")?;
}
Expression(
Kind::Literal(Literal::Char(v.chars().next().unwrap())),
stream.get_range().unwrap(),
)
}
Token::True => {
stream.next(); // Consume
Expression(

View File

@ -289,6 +289,7 @@ impl ast::Literal {
ast::Literal::Bool(v) => mir::Literal::Bool(*v),
ast::Literal::String(val) => mir::Literal::String(val.clone()),
ast::Literal::Decimal(v) => mir::Literal::Vague(mir::VagueLiteral::Decimal(*v)),
ast::Literal::Char(inner) => mir::Literal::Char(*inner),
}
}
}
@ -310,7 +311,6 @@ impl From<ast::TypeKind> for mir::TypeKind {
ast::TypeKind::Array(type_kind, length) => {
mir::TypeKind::Array(Box::new(mir::TypeKind::from(*type_kind.clone())), *length)
}
ast::TypeKind::Str => mir::TypeKind::Str,
ast::TypeKind::Custom(name) => mir::TypeKind::CustomType(name.clone()),
ast::TypeKind::Borrow(type_kind, mutable) => {
mir::TypeKind::Borrow(Box::new(mir::TypeKind::from(*type_kind.clone())), *mutable)
@ -325,6 +325,7 @@ impl From<ast::TypeKind> for mir::TypeKind {
ast::TypeKind::F80 => mir::TypeKind::F80,
ast::TypeKind::F128 => mir::TypeKind::F128,
ast::TypeKind::F128PPC => mir::TypeKind::F128PPC,
ast::TypeKind::Char => mir::TypeKind::Char,
}
}
}

View File

@ -18,8 +18,8 @@ use crate::{
error_raporting::ModuleMap,
lexer::{FullToken, Position},
mir::{
self, Metadata, NamedVariableRef, StructField, StructType, TypeDefinition,
TypeDefinitionKind, TypeKind, VagueLiteral,
self, implement::TypeCategory, Metadata, NamedVariableRef, StructField, StructType,
TypeDefinition, TypeDefinitionKind, TypeKind, VagueLiteral,
},
};
@ -247,7 +247,7 @@ impl mir::Module {
insert_debug!(&TypeKind::I64);
insert_debug!(&TypeKind::I128);
insert_debug!(&TypeKind::Void);
insert_debug!(&TypeKind::Str);
insert_debug!(&TypeKind::Char);
for typedef in &self.typedefs {
let type_value = match &typedef.kind {
@ -633,7 +633,11 @@ impl mir::Expression {
.expect("rhs has no return value")
.instr();
let lhs_type = lhs_exp.return_type(&Default::default()).unwrap().1;
let instr = match (binop, lhs_type.signed(), lhs_type.is_float()) {
let instr = match (
binop,
lhs_type.signed(),
lhs_type.category() == TypeCategory::Real,
) {
(mir::BinaryOperator::Add, _, false) => Instr::Add(lhs, rhs),
(mir::BinaryOperator::Add, _, true) => Instr::FAdd(lhs, rhs),
(mir::BinaryOperator::Minus, _, false) => Instr::Sub(lhs, rhs),
@ -641,10 +645,8 @@ impl mir::Expression {
(mir::BinaryOperator::Mult, _, false) => Instr::Mul(lhs, rhs),
(mir::BinaryOperator::Mult, _, true) => Instr::FMul(lhs, rhs),
(mir::BinaryOperator::And, _, _) => Instr::And(lhs, rhs),
(mir::BinaryOperator::Cmp(i), _, false) => {
Instr::ICmp(i.int_predicate(), lhs, rhs)
}
_ => todo!(),
(mir::BinaryOperator::Cmp(i), _, false) => Instr::ICmp(i.predicate(), lhs, rhs),
(mir::BinaryOperator::Cmp(i), _, true) => Instr::FCmp(i.predicate(), lhs, rhs),
};
Some(StackValue(
StackValueKind::Immutable(scope.block.build(instr).unwrap()),
@ -771,7 +773,7 @@ impl mir::Expression {
*further_inner,
)
} else {
let TypeKind::Array(elem_ty, _) = *inner else {
let TypeKind::Array(_, _) = *inner else {
panic!();
};
(
@ -1030,18 +1032,25 @@ impl mir::Expression {
}
mir::ExprKind::CastTo(expression, type_kind) => {
let val = expression.codegen(scope, state)?;
let cast_instr = val
.1
.get_type(scope.type_values, scope.types)
.cast_instruction(
val.instr(),
&type_kind.get_type(scope.type_values, scope.types),
)
.unwrap();
Some(StackValue(
val.0.derive(scope.block.build(cast_instr).unwrap()),
type_kind.clone(),
))
if val.1 == *type_kind {
Some(val)
} else if let (TypeKind::UserPtr(_), TypeKind::UserPtr(_)) = (&val.1, type_kind) {
Some(val)
} else {
let cast_instr = val
.1
.get_type(scope.type_values, scope.types)
.cast_instruction(
val.instr(),
&type_kind.get_type(scope.type_values, scope.types),
)
.unwrap();
Some(StackValue(
val.0.derive(scope.block.build(cast_instr).unwrap()),
type_kind.clone(),
))
}
}
};
if let Some(value) = &value {
@ -1150,7 +1159,7 @@ impl mir::IfExpression {
}
}
impl mir::CmpOperator {
fn int_predicate(&self) -> CmpPredicate {
fn predicate(&self) -> CmpPredicate {
match self {
mir::CmpOperator::LT => CmpPredicate::LT,
mir::CmpOperator::GT => CmpPredicate::GT,
@ -1192,6 +1201,7 @@ impl mir::Literal {
mir::Literal::F80(val) => ConstValue::F80(val),
mir::Literal::F128(val) => ConstValue::F128(val),
mir::Literal::F128PPC(val) => ConstValue::F128PPC(val),
mir::Literal::Char(c) => ConstValue::U8(c as u8),
})
}
}
@ -1221,7 +1231,7 @@ impl TypeKind {
TypeKind::F128 => Type::F128,
TypeKind::F80 => Type::F80,
TypeKind::F128PPC => Type::F128PPC,
TypeKind::Str => Type::I8,
TypeKind::Char => Type::I8,
TypeKind::Array(elem_t, len) => {
Type::Array(Box::new(elem_t.get_type(type_vals, typedefs)), *len)
}
@ -1361,7 +1371,7 @@ impl TypeKind {
| TypeKind::F128
| TypeKind::F128PPC => DwarfEncoding::Float,
TypeKind::Void => DwarfEncoding::Address,
TypeKind::Str => DwarfEncoding::UnsignedChar,
TypeKind::Char => DwarfEncoding::UnsignedChar,
TypeKind::Array(_, _) => DwarfEncoding::Address,
TypeKind::CustomType(_) => DwarfEncoding::Address,
_ => panic!("tried fetching debug-type for non-supported type!"),

View File

@ -1,4 +1,4 @@
use std::{fmt::Debug, str::Chars};
use std::{fmt::Debug, hint::unreachable_unchecked, str::Chars};
static DECIMAL_NUMERICS: &[char] = &['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
@ -8,7 +8,9 @@ pub enum Token {
Identifier(String),
/// Number with at most one decimal point
DecimalValue(u64),
/// Some string literal that was surrounded by "quotes".
/// Some character literal that was surrounded by 'single-quotes'.
CharLit(String),
/// Some string literal that was surrounded by "double-quotes".
StringLit(String),
// Keywords
@ -112,6 +114,7 @@ impl ToString for Token {
match &self {
Token::Identifier(ident) => ident.clone(),
Token::DecimalValue(val) => val.to_string(),
Token::CharLit(lit) => format!("\'{}\'", lit),
Token::StringLit(lit) => format!("\"{}\"", lit),
Token::LetKeyword => String::from("let"),
Token::MutKeyword => String::from("mut"),
@ -245,24 +248,35 @@ pub fn tokenize<T: Into<String>>(to_tokenize: T) -> Result<Vec<FullToken>, Error
}
continue;
}
'\"' => {
'\"' | '\'' => {
let mut value = String::new();
let mut ignore_next = false;
while cursor.first().is_some() && (cursor.first() != Some('\"') || ignore_next) {
if cursor.first() == Some('\\') && !ignore_next {
cursor.next(); // Consume backslash anjd always add next character
ignore_next = true;
let mut escape_next = false;
while cursor.first().is_some()
&& (cursor.first() != Some(*character) || escape_next)
{
if cursor.first() == Some('\\') && !escape_next {
cursor.next(); // Consume backslash and always add next character
escape_next = true;
} else {
ignore_next = false;
value += &cursor.next().unwrap().to_string();
let c = &cursor.next().unwrap();
if escape_next {
value += &escape_char(&c).to_string();
} else {
value += &c.to_string();
}
escape_next = false;
}
}
if cursor.first() == Some('\"') {
if cursor.first() == Some(*character) {
cursor.next();
} else {
return Err(Error::MissingQuotation(position));
}
Token::StringLit(value)
match character {
'\'' => Token::CharLit(value),
'\"' => Token::StringLit(value),
_ => unsafe { unreachable_unchecked() },
}
}
// "words"
c if c.is_alphabetic() => {
@ -347,6 +361,15 @@ pub fn tokenize<T: Into<String>>(to_tokenize: T) -> Result<Vec<FullToken>, Error
Ok(tokens)
}
fn escape_char(c: &char) -> char {
match c {
't' => '\t',
'n' => '\n',
'r' => '\r',
_ => *c,
}
}
#[derive(thiserror::Error, Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum Error {
#[error("Invalid token '{}' ", .0)]

View File

@ -269,6 +269,7 @@ impl Display for Literal {
Literal::F80(val) => write!(f, "{}f80", val),
Literal::F128(val) => write!(f, "{}f128", val),
Literal::F128PPC(val) => write!(f, "{}f128ppc", val),
Literal::Char(c) => std::fmt::Debug::fmt(c, f),
}
}
}
@ -336,7 +337,7 @@ impl Display for TypeKind {
TypeKind::U64 => write!(f, "u64"),
TypeKind::U128 => write!(f, "u128"),
TypeKind::Void => write!(f, "void"),
TypeKind::Str => write!(f, "str"),
TypeKind::Char => write!(f, "char"),
TypeKind::Array(type_kind, len) => {
f.write_char('[')?;
Display::fmt(type_kind, f)?;

View File

@ -1,6 +1,4 @@
use crate::util::try_all;
use super::{pass::ScopeFunction, typecheck::ErrorKind, typerefs::TypeRefs, VagueType as Vague, *};
use super::{typecheck::ErrorKind, typerefs::TypeRefs, VagueType as Vague, *};
#[derive(Debug, Clone)]
pub enum ReturnTypeOther {
@ -81,8 +79,12 @@ impl TypeKind {
let other_cat = other.category();
match (self, other) {
(TypeKind::UserPtr(_), TypeKind::UserPtr(_)) => Ok(other.clone()),
(TypeKind::Char, TypeKind::U8) => Ok(other.clone()),
(TypeKind::U8, TypeKind::Char) => Ok(other.clone()),
_ => match (&self_cat, &other_cat) {
(TypeCategory::Integer, TypeCategory::Integer) => Ok(other.clone()),
(TypeCategory::Integer, TypeCategory::Real) => Ok(other.clone()),
(TypeCategory::Real, TypeCategory::Integer) => Ok(other.clone()),
(TypeCategory::Real, TypeCategory::Real) => Ok(other.clone()),
_ => Err(ErrorKind::NotCastableTo(self.clone(), other.clone())),
},
@ -119,38 +121,7 @@ impl TypeKind {
TypeKind::U64 => false,
TypeKind::U128 => false,
TypeKind::Void => false,
TypeKind::Str => false,
TypeKind::Array(_, _) => false,
TypeKind::CustomType(_) => false,
TypeKind::CodegenPtr(_) => false,
TypeKind::Vague(_) => false,
TypeKind::Borrow(_, _) => false,
TypeKind::UserPtr(_) => false,
TypeKind::F16 => true,
TypeKind::F32B => true,
TypeKind::F32 => true,
TypeKind::F64 => true,
TypeKind::F128 => true,
TypeKind::F80 => true,
TypeKind::F128PPC => true,
}
}
pub fn is_float(&self) -> bool {
match self {
TypeKind::Bool => false,
TypeKind::I8 => false,
TypeKind::I16 => false,
TypeKind::I32 => false,
TypeKind::I64 => false,
TypeKind::I128 => false,
TypeKind::U8 => false,
TypeKind::U16 => false,
TypeKind::U32 => false,
TypeKind::U64 => false,
TypeKind::U128 => false,
TypeKind::Void => false,
TypeKind::Str => false,
TypeKind::Char => false,
TypeKind::Array(_, _) => false,
TypeKind::CustomType(_) => false,
TypeKind::CodegenPtr(_) => false,
@ -181,7 +152,7 @@ impl TypeKind {
TypeKind::I128 => 128,
TypeKind::U128 => 128,
TypeKind::Void => 0,
TypeKind::Str => 8,
TypeKind::Char => 8,
TypeKind::Array(type_kind, len) => type_kind.size_of() * len,
TypeKind::CustomType(_) => 32,
TypeKind::CodegenPtr(_) => 64,
@ -212,7 +183,7 @@ impl TypeKind {
TypeKind::I128 => 128,
TypeKind::U128 => 128,
TypeKind::Void => 0,
TypeKind::Str => 8,
TypeKind::Char => 8,
TypeKind::Array(type_kind, _) => type_kind.alignment(),
TypeKind::CustomType(_) => 32,
TypeKind::CodegenPtr(_) => 64,
@ -248,7 +219,7 @@ impl TypeKind {
| TypeKind::U32
| TypeKind::U64
| TypeKind::U128
| TypeKind::Str => TypeCategory::Integer,
| TypeKind::Char => TypeCategory::Integer,
TypeKind::F16
| TypeKind::F32B
| TypeKind::F32
@ -273,6 +244,7 @@ impl TypeKind {
}
}
#[derive(PartialEq, Eq, PartialOrd, Ord)]
pub enum TypeCategory {
Integer,
Real,
@ -610,6 +582,7 @@ impl Literal {
Literal::F80(_) => None,
Literal::F128(_) => None,
Literal::F128PPC(_) => None,
Literal::Char(_) => None,
}
}
}

View File

@ -98,7 +98,7 @@ pub enum TypeKind {
F128,
F80,
F128PPC,
Str,
Char,
Array(Box<TypeKind>, u64),
CustomType(String),
Borrow(Box<TypeKind>, bool),
@ -162,6 +162,7 @@ pub enum Literal {
F128PPC(f64),
Bool(bool),
String(String),
Char(char),
Vague(VagueLiteral),
}
@ -185,7 +186,7 @@ impl Literal {
Literal::U64(_) => TypeKind::U64,
Literal::U128(_) => TypeKind::U128,
Literal::Bool(_) => TypeKind::Bool,
Literal::String(_) => TypeKind::UserPtr(Box::new(TypeKind::Str)),
Literal::String(_) => TypeKind::UserPtr(Box::new(TypeKind::Char)),
Literal::Vague(VagueLiteral::Number(_)) => TypeKind::Vague(VagueType::Integer),
Literal::Vague(VagueLiteral::Decimal(_)) => TypeKind::Vague(VagueType::Decimal),
Literal::F16(_) => TypeKind::F16,
@ -195,6 +196,7 @@ impl Literal {
Literal::F80(_) => TypeKind::F80,
Literal::F128(_) => TypeKind::F128,
Literal::F128PPC(_) => TypeKind::F128PPC,
Literal::Char(_) => TypeKind::Char,
}
}
}

View File

@ -728,29 +728,12 @@ impl Literal {
if let Some(hint) = &hint {
use Literal as L;
use VagueLiteral as VagueL;
if *hint == self.as_type() {
return Ok(self);
}
Ok(match (self.clone(), hint) {
(L::I8(_), TypeKind::I8) => self,
(L::I16(_), TypeKind::I16) => self,
(L::I32(_), TypeKind::I32) => self,
(L::I64(_), TypeKind::I64) => self,
(L::I128(_), TypeKind::I128) => self,
(L::U8(_), TypeKind::U8) => self,
(L::U16(_), TypeKind::U16) => self,
(L::U32(_), TypeKind::U32) => self,
(L::U64(_), TypeKind::U64) => self,
(L::U128(_), TypeKind::U128) => self,
(L::F16(_), TypeKind::F16) => self,
(L::F32(_), TypeKind::F32) => self,
(L::F32B(_), TypeKind::F32B) => self,
(L::F64(_), TypeKind::F64) => self,
(L::F80(_), TypeKind::F80) => self,
(L::F128(_), TypeKind::F128) => self,
(L::F128PPC(_), TypeKind::F128PPC) => self,
(L::Bool(_), TypeKind::Bool) => self,
(L::String(_), TypeKind::UserPtr(ptr)) => match *ptr.clone() {
TypeKind::Str => self,
_ => Err(ErrorKind::LiteralIncompatible(self, hint.clone()))?,
},
// TODO make sure that v is actually able to fit in the
// requested type
(L::Vague(VagueL::Number(v)), TypeKind::I8) => L::I8(v as i8),

View File

@ -1,11 +1,18 @@
// Arithmetic, function calls and imports!
import std::allocate;
import std::print;
fn other() -> i16 {
return 6;
}
fn main() -> u32 {
let value = other() as u32;
let other_value = other() as f32;
let same_value = other() as i16;
return value;
let v = (allocate(4) as *u32);
return v[0];
}

5
reid_src/char.reid Normal file
View File

@ -0,0 +1,5 @@
// Arithmetic, function calls and imports!
pub fn main() -> char {
return 'b';
}

View File

@ -1,8 +1,6 @@
// Arithmetic, function calls and imports!
extern fn malloc(size: u64) -> *u8;
fn main() -> u8 {
let mut ptr = malloc(4);