Skip to content

Commit

Permalink
Pointer work
Browse files Browse the repository at this point in the history
  • Loading branch information
cody-quinn committed Sep 13, 2023
1 parent a224e3b commit 11ee6dc
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 30 deletions.
4 changes: 2 additions & 2 deletions examples/pointer.sloth
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
fn main() Int {
val x: Int = 0;
val xPtr: Int = *x;
val xPtr: &Int = &x;
val x: Int = @xPtr;
}
}
25 changes: 10 additions & 15 deletions sloth/src/parser/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -271,24 +271,19 @@ pub struct FunctionInput {
}

#[derive(PartialEq, Clone, Debug)]
pub struct TypeIdentifier {
pub name: String,
pub is_list: bool,
pub enum TypeIdentifier {
Pointer(Box<TypeIdentifier>),
Array(Box<TypeIdentifier>),
Standard { name: String },
}

impl Display for TypeIdentifier {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if self.is_list {
write!(f, "[")?;
}

write!(f, "{}", self.name)?;

if self.is_list {
write!(f, "]")?;
match self {
TypeIdentifier::Pointer(inner) => write!(f, "&{inner}"),
TypeIdentifier::Array(inner) => write!(f, "[{inner}]"),
TypeIdentifier::Standard { name } => write!(f, "{name}"),
}

Ok(())
}
}

Expand Down Expand Up @@ -437,7 +432,7 @@ impl TryFrom<TokenType> for UnaryOp {
TokenType::Bang => Self::Not,
TokenType::Minus => Self::Neg,

TokenType::Star => Self::Reference,
TokenType::Amp => Self::Reference,
TokenType::At => Self::Dereference,

_ => return Err(ParsingError::InvalidOp),
Expand All @@ -453,7 +448,7 @@ impl Display for UnaryOp {
UnaryOp::Not => "!",
UnaryOp::Neg => "-",

UnaryOp::Reference => "*",
UnaryOp::Reference => "&",
UnaryOp::Dereference => "@",
};

Expand Down
29 changes: 16 additions & 13 deletions sloth/src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,19 +130,22 @@ impl<'a> AstParser<'a> {
}

pub fn consume_type(&mut self) -> Result<TypeIdentifier, ParsingError> {
let is_list = self.peek().tt == TokenType::OpeningBracket;

if is_list {
self.consume(TokenType::OpeningBracket, "Expected '['")?;
}

let name = self.consume_identifier()?;

if is_list {
self.consume(TokenType::ClosingBracket, "Expected ']'")?;
}

Ok(TypeIdentifier { name, is_list })
Ok(match self.peek().tt {
TokenType::OpeningBracket => {
self.consume(TokenType::OpeningBracket, "Expected '['")?;
let typ = TypeIdentifier::Array(Box::new(self.consume_type()?));
self.consume(TokenType::ClosingBracket, "Expected ']'")?;

typ
}
TokenType::Amp => {
self.consume(TokenType::Amp, "Expected '&'")?;
TypeIdentifier::Pointer(Box::new(self.consume_type()?))
}
_ => TypeIdentifier::Standard {
name: self.consume_identifier()?,
},
})
}

pub fn reserve_id(&mut self) -> i32 {
Expand Down

0 comments on commit 11ee6dc

Please sign in to comment.