js: initial support for optional return unwrapping (#6926)
							parent
							
								
									789912238f
								
							
						
					
					
						commit
						aa90625819
					
				| 
						 | 
				
			
			@ -37,7 +37,52 @@ pub fn exit(c int) {
 | 
			
		|||
	JS.process.exit(c)
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
pub fn unwrap(opt any) any {
 | 
			
		||||
	o := &Option(opt)
 | 
			
		||||
	if o.not_ok {
 | 
			
		||||
		panic(o.error)
 | 
			
		||||
		return o.error
 | 
			
		||||
	}
 | 
			
		||||
	return opt
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
pub fn panic(s string) {
 | 
			
		||||
	eprintln('V panic: $s')
 | 
			
		||||
	exit(1)
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
struct Option {
 | 
			
		||||
	not_ok  bool
 | 
			
		||||
	is_none bool
 | 
			
		||||
	error   string
 | 
			
		||||
	ecode   int
 | 
			
		||||
	data    any
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
pub fn (o Option) str() string {
 | 
			
		||||
   if !o.not_ok {
 | 
			
		||||
	  return 'Option{ ok }'
 | 
			
		||||
   }
 | 
			
		||||
   if o.is_none {
 | 
			
		||||
	  return 'Option{ none }'
 | 
			
		||||
   }
 | 
			
		||||
   return 'Option{ error: "${o.error}" }'
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
pub fn error(s string) Option {
 | 
			
		||||
	return Option{
 | 
			
		||||
		not_ok: true
 | 
			
		||||
		is_none: false
 | 
			
		||||
		error: s
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
pub fn error_with_code(s string, code int) Option {
 | 
			
		||||
	return Option{
 | 
			
		||||
		not_ok: true
 | 
			
		||||
		is_none: false
 | 
			
		||||
		error: s
 | 
			
		||||
		ecode: code
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
| 
						 | 
				
			
			
 | 
			
		|||
| 
						 | 
				
			
			@ -1175,6 +1175,10 @@ fn (mut g JsGen) gen_call_expr(it ast.CallExpr) {
 | 
			
		|||
	} else {
 | 
			
		||||
		name = g.js_name(it.name)
 | 
			
		||||
	}
 | 
			
		||||
	call_return_is_optional := it.return_type.has_flag(.optional)
 | 
			
		||||
	if call_return_is_optional {
 | 
			
		||||
		g.write('builtin.unwrap(')
 | 
			
		||||
	}
 | 
			
		||||
	g.expr(it.left)
 | 
			
		||||
	if it.is_method { // foo.bar.baz()
 | 
			
		||||
		sym := g.table.get_type_symbol(it.receiver_type)
 | 
			
		||||
| 
						 | 
				
			
			@ -1224,8 +1228,12 @@ fn (mut g JsGen) gen_call_expr(it ast.CallExpr) {
 | 
			
		|||
			g.write(', ')
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
	if call_return_is_optional {
 | 
			
		||||
		g.write('))')
 | 
			
		||||
	} else {
 | 
			
		||||
		g.write(')')
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
fn (mut g JsGen) gen_ident(node ast.Ident) {
 | 
			
		||||
	mut name := g.js_name(node.name)
 | 
			
		||||
| 
						 | 
				
			
			
 | 
			
		|||
		Loading…
	
		Reference in New Issue