Skip to content

Commit af02cf9

Browse files
committed
error and exit
1 parent 55bc932 commit af02cf9

3 files changed

Lines changed: 31 additions & 1 deletion

File tree

lang/src/functions.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@ pub fn get_functions() -> Vec<BuiltinFn> {
2222
builtin("float", float),
2323
builtin("str", str),
2424
builtin("bool", bool),
25+
builtin("exit", exit),
26+
builtin("error", error),
2527
]
2628
}
2729

@@ -123,4 +125,25 @@ fn bool(args: Vec<Value>) -> Result<Value, String> {
123125
}
124126

125127
Ok(Value::Bool(args[0].truthy()))
128+
}
129+
130+
fn exit(args: Vec<Value>) -> Result<Value, String> {
131+
if args.len() == 0 {
132+
std::process::exit(0);
133+
} else if args.len() == 1 {
134+
match &args[0] {
135+
Value::Int(i) => std::process::exit(*i as i32),
136+
_ => return Err(format!("exit() argument must be an int, got {}", args[0].type_name())),
137+
}
138+
} else {
139+
return Err(format!("exit() takes at most one argument ({} given)", args.len()));
140+
}
141+
}
142+
143+
fn error(args: Vec<Value>) -> Result<Value, String> {
144+
if args.len() != 1 {
145+
return Err(format!("error() takes exactly one argument ({} given)", args.len()));
146+
}
147+
148+
Err(format!("{}", args[0]))
126149
}

lang/src/vm/vm.rs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -240,7 +240,13 @@ impl VM {
240240

241241
match (func.func)(args) {
242242
Ok(result) => self.stack.push(result),
243-
Err(e) => return Err(self.runtime_error(format!("error calling {}(): {}", func.name, e), span)),
243+
Err(e) => {
244+
if func.name == "error" && !e.contains("error() takes exactly one argument") {
245+
return Err(self.runtime_error(format!("{}", e), span));
246+
}
247+
248+
return Err(self.runtime_error(format!("error calling {}(): {}", func.name, e), span));
249+
}
244250
}
245251
}
246252

lang/test

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
error("hi");

0 commit comments

Comments
 (0)