cgen: fix slices

pull/3947/head
Alexander Medvednikov 2020-03-06 22:24:39 +01:00
parent 81ce524705
commit 1a8b7d0447
5 changed files with 30 additions and 6 deletions

View File

@ -497,8 +497,10 @@ mut:
// s[10..20]
pub struct RangeExpr {
pub:
low Expr
high Expr
low Expr
high Expr
has_high bool
has_low bool
}
pub struct CastExpr {

View File

@ -598,11 +598,22 @@ fn (g mut Gen) index_expr(node ast.IndexExpr) {
g.write('array_slice(')
g.expr(node.left)
g.write(', ')
// g.expr(it.low)
g.write('0')
if it.has_low {
g.expr(it.low)
}
else {
g.write('0')
}
g.write(', ')
g.expr(it.high)
if it.has_high {
g.expr(it.high)
}
else {
g.expr(node.left)
g.write('.len')
}
g.write(')')
return
}
else {}
}
@ -618,7 +629,7 @@ fn (g mut Gen) index_expr(node ast.IndexExpr) {
g.write(')')
}
else if sym.kind == .string {
g.write('string_get(')
g.write('string_at(')
g.expr(node.left)
g.write(', ')
g.expr(node.index)

View File

@ -66,6 +66,8 @@ i < 10; i++) {
1, 2, 3,
});
array_int nums2 = array_slice(nums, 0, 2);
array_int nums3 = array_slice(nums, 1, 2);
array_int nums4 = array_slice(nums, 1, nums.len);
int number = array_get(nums, 0);
array_bool bools = new_array_from_c_array(2, 2, sizeof(array_bool), (bool[]){
true, false,

View File

@ -61,6 +61,8 @@ fn foo(a int) {
}
nums := [1,2,3]
nums2 := nums[..2]
nums3 := nums[1..2]
nums4 := nums[1..]
number := nums[0]
bools := [true, false]
users := [User{}]

View File

@ -817,7 +817,9 @@ fn (p mut Parser) prefix_expr() ast.PrefixExpr {
fn (p mut Parser) index_expr(left ast.Expr) ast.IndexExpr {
// left == `a` in `a[0]`
p.next() // [
mut has_low := true
if p.tok.kind == .dotdot {
has_low = false
// [..end]
p.next()
high := p.expr(0)
@ -828,15 +830,18 @@ fn (p mut Parser) index_expr(left ast.Expr) ast.IndexExpr {
index: ast.RangeExpr{
low: ast.Expr{}
high: high
has_high: true
}
}
}
expr := p.expr(0) // `[expr]` or `[expr..]`
mut has_high := false
if p.tok.kind == .dotdot {
// [start..end] or [start..]
p.check(.dotdot)
mut high := ast.Expr{}
if p.tok.kind != .rsbr {
has_high = true
high = p.expr(0)
}
p.check(.rsbr)
@ -846,6 +851,8 @@ fn (p mut Parser) index_expr(left ast.Expr) ast.IndexExpr {
index: ast.RangeExpr{
low: expr
high: high
has_high: has_high
has_low: has_low
}
}
}