diff --git a/examples/pointer.sloth b/examples/pointer.sloth index 7d7ca10..d39e5a8 100644 --- a/examples/pointer.sloth +++ b/examples/pointer.sloth @@ -1,5 +1,5 @@ fn main() Int { val x: Int = 0; - val xPtr: Int = *x; + val xPtr: &Int = &x; val x: Int = @xPtr; -} \ No newline at end of file +} diff --git a/sloth/src/parser/ast.rs b/sloth/src/parser/ast.rs index a82a6df..966ca1b 100644 --- a/sloth/src/parser/ast.rs +++ b/sloth/src/parser/ast.rs @@ -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), + Array(Box), + 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(()) } } @@ -437,7 +432,7 @@ impl TryFrom 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), @@ -453,7 +448,7 @@ impl Display for UnaryOp { UnaryOp::Not => "!", UnaryOp::Neg => "-", - UnaryOp::Reference => "*", + UnaryOp::Reference => "&", UnaryOp::Dereference => "@", }; diff --git a/sloth/src/parser/mod.rs b/sloth/src/parser/mod.rs index 09a26fd..274b87d 100644 --- a/sloth/src/parser/mod.rs +++ b/sloth/src/parser/mod.rs @@ -130,19 +130,22 @@ impl<'a> AstParser<'a> { } pub fn consume_type(&mut self) -> Result { - 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 {