Skip to content

Commit

Permalink
parse number literals
Browse files Browse the repository at this point in the history
  • Loading branch information
StunxFS committed Dec 5, 2024
1 parent c6db77f commit 9e79074
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 14 deletions.
12 changes: 9 additions & 3 deletions compiler/ast/Expr.v
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

module ast

pub type Expr = EmptyExpr | UnaryExpr | BinaryExpr | RuneLit | IntegerLit
pub type Expr = EmptyExpr | UnaryExpr | BinaryExpr | CharLiteral | IntegerLiteral | FloatLiteral

pub struct EmptyExpr {
pub:
Expand Down Expand Up @@ -62,14 +62,20 @@ pub:
pos FilePos
}

pub struct RuneLit {
pub struct CharLiteral {
pub:
value string
is_byte bool
pos FilePos
}

pub struct IntegerLit {
pub struct IntegerLiteral {
pub:
value string
pos FilePos
}

pub struct FloatLiteral {
pub:
value string
pos FilePos
Expand Down
45 changes: 35 additions & 10 deletions compiler/parser/expr.v
Original file line number Diff line number Diff line change
Expand Up @@ -171,17 +171,14 @@ fn (mut p Parser) parse_unary_expr() ast.Expr {

fn (mut p Parser) parse_primary_expr() ast.Expr {
match p.tok.kind {
.char, .number, .string {
return p.parse_literal()
}
.kw_if {}
.kw_match {}
.kw_break {}
.kw_continue {}
.kw_return {}
.number {
return p.parse_integer_lit()
}
.char {
return p.parse_rune_lit()
}
else {
context.error('invalid expression: unexpected ${p.tok}', p.tok.pos)
p.abort = true
Expand All @@ -190,10 +187,38 @@ fn (mut p Parser) parse_primary_expr() ast.Expr {
return ast.empty_expr
}

fn (mut p Parser) parse_integer_lit() ast.IntegerLit {
return ast.IntegerLit{}
fn (mut p Parser) parse_literal() ast.Expr {
return match p.tok.kind {
.char {
p.parse_char_literal()
}
.number {
p.parse_number_literal()
}
else {
context.error('invalid literal expression: found ${p.tok}', p.tok.pos)
ast.empty_expr
}
}
}

fn (mut p Parser) parse_number_literal() ast.Expr {
pos := p.tok.pos
value := p.tok.lit
p.next()
return if (value.len > 2 && value[..2] !in ['0x', '0o', '0b']) && value.index_any('.eE') >= 0 {
ast.IntegerLiteral{
value: value
pos: pos
}
} else {
ast.FloatLiteral{
value: value
pos: pos
}
}
}

fn (mut p Parser) parse_rune_lit() ast.RuneLit {
return ast.RuneLit{}
fn (mut p Parser) parse_char_literal() ast.Expr {
return ast.CharLiteral{}
}
2 changes: 1 addition & 1 deletion compiler/parser/stmt.v
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ fn (mut p Parser) parse_fn_stmt(is_pub bool) ast.FnStmt {
p.expect(.colon)
arg_type := p.parse_type()
mut arg_default_expr := ast.empty_expr
if p.accept(.eq) {
if p.accept(.assign) {
arg_default_expr = p.parse_expr()
}
args << ast.FnArg{arg_name, arg_name_pos, arg_type, arg_default_expr}
Expand Down

0 comments on commit 9e79074

Please sign in to comment.