Add object primitives, official ext/llm, and HTTPS/dotenv platform.
Introduce # objects with ## methods (handles + ` x.method `), ship OpenAI-compatible ext/llm, and upgrade net/sys for HTTPS headers and dotenv loading. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
b974f10c6e
commit
b00b018056
55 files changed
+1741
-291
No files matched your search
+113
-4
@@ -13,6 +13,7 @@ use crate::value::Value;
|
||||
|
||||
struct FlatFun {
|
||||
name: String,
|
||||
level: u8,
|
||||
parent: Option<usize>,
|
||||
params: Vec<String>,
|
||||
body: Vec<Stmt>,
|
||||
@@ -33,10 +34,30 @@ pub fn compile_module(path: Option<&Path>, module: &Module) -> Result<Program> {
|
||||
.iter()
|
||||
.position(|f| f.name == "main" && f.parent.is_none())
|
||||
.or_else(|| {
|
||||
flat.iter()
|
||||
.position(|f| f.parent.is_none() && f.params.is_empty())
|
||||
let tops: Vec<usize> = flat
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, f)| f.parent.is_none() && f.level == 1 && f.params.is_empty())
|
||||
.map(|(i, _)| i)
|
||||
.collect();
|
||||
if tops.len() == 1 {
|
||||
Some(tops[0])
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.ok_or_else(|| anyhow::anyhow!("bytecode: no entry function"))?;
|
||||
.ok_or_else(|| anyhow::anyhow!("bytecode: no `# main` object"))?;
|
||||
|
||||
let mut objects = Vec::new();
|
||||
let mut methods = Vec::new();
|
||||
for (i, f) in flat.iter().enumerate() {
|
||||
if f.parent.is_none() && f.level == 1 {
|
||||
objects.push((f.name.clone(), i));
|
||||
for &cid in &f.children {
|
||||
methods.push((i, flat[cid].name.clone(), cid));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let path_buf = path.map(|p| p.to_path_buf());
|
||||
let mut functions = Vec::new();
|
||||
@@ -44,13 +65,19 @@ pub fn compile_module(path: Option<&Path>, module: &Module) -> Result<Program> {
|
||||
functions.push(compile_function(i, &flat, path_buf.as_deref())?);
|
||||
}
|
||||
|
||||
Ok(Program { functions, entry })
|
||||
Ok(Program {
|
||||
functions,
|
||||
entry,
|
||||
objects,
|
||||
methods,
|
||||
})
|
||||
}
|
||||
|
||||
fn collect_fun(fun: &Function, parent: Option<usize>, flat: &mut Vec<FlatFun>) -> usize {
|
||||
let id = flat.len();
|
||||
flat.push(FlatFun {
|
||||
name: fun.name.clone(),
|
||||
level: fun.level,
|
||||
parent,
|
||||
params: fun.params.clone(),
|
||||
body: fun.body.clone(),
|
||||
@@ -80,6 +107,18 @@ fn compile_function(fn_id: usize, flat: &[FlatFun], path: Option<&Path>) -> Resu
|
||||
for (i, p) in fun.params.iter().enumerate() {
|
||||
locals.insert(p.clone(), i as u8);
|
||||
}
|
||||
let is_method = fun
|
||||
.parent
|
||||
.map(|pid| flat[pid].level == 1 && flat[pid].parent.is_none())
|
||||
.unwrap_or(false);
|
||||
if is_method {
|
||||
for name in ["自", "self"] {
|
||||
if !locals.contains_key(name) {
|
||||
let s = locals.len() as u8;
|
||||
locals.insert(name.to_string(), s);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut c = FnCompiler {
|
||||
path,
|
||||
flat,
|
||||
@@ -324,6 +363,10 @@ impl<'a> FnCompiler<'a> {
|
||||
call.callee =
|
||||
crate::aliases::normalize_call_callee_and_args(&call.callee, &mut call.args);
|
||||
|
||||
if let Some(recv) = &call.receiver {
|
||||
return self.compile_method_call(recv, &call, as_stmt);
|
||||
}
|
||||
|
||||
match call.callee.as_str() {
|
||||
"print" => {
|
||||
let text_expr = call
|
||||
@@ -499,6 +542,72 @@ impl<'a> FnCompiler<'a> {
|
||||
)));
|
||||
}
|
||||
self.emit(Op::Call(fid as u16, params.len() as u8));
|
||||
if self.flat[fid].parent.is_none() && self.flat[fid].level == 1 {
|
||||
let ti = self.add_const(Value::Text(self.flat[fid].name.clone()));
|
||||
self.emit(Op::TagInstance(ti));
|
||||
}
|
||||
if as_stmt {
|
||||
self.emit(Op::Pop);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn compile_method_call(&mut self, recv: &str, call: &CallExpr, as_stmt: bool) -> Result<()> {
|
||||
// Resolve method among all object children by name (unique enough for compile);
|
||||
// runtime still checks `_type`.
|
||||
let mut method_fid = None;
|
||||
for f in self.flat {
|
||||
if f.parent.is_none() && f.level == 1 {
|
||||
for &cid in &f.children {
|
||||
if self.flat[cid].name == call.callee {
|
||||
method_fid = Some(cid);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if method_fid.is_some() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let fid = method_fid.ok_or_else(|| {
|
||||
self.err(format!("unknown method `{}`", call.callee))
|
||||
})?;
|
||||
let params = self.flat[fid].params.clone();
|
||||
let mut named: HashMap<String, &Expr> = HashMap::new();
|
||||
let mut positionals = Vec::new();
|
||||
for a in &call.args {
|
||||
match a {
|
||||
Arg::Positional(e) => positionals.push(e),
|
||||
Arg::Named { name, value } => {
|
||||
named.insert(name.clone(), value);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut pos_i = 0;
|
||||
for p in ¶ms {
|
||||
if let Some(e) = named.get(p) {
|
||||
self.compile_expr(e)?;
|
||||
} else if pos_i < positionals.len() {
|
||||
self.compile_expr(positionals[pos_i])?;
|
||||
pos_i += 1;
|
||||
} else {
|
||||
return Err(self.err(format!("missing argument for parameter `{p}`")));
|
||||
}
|
||||
}
|
||||
if pos_i < positionals.len() {
|
||||
return Err(self.err(format!(
|
||||
"too many positional arguments ({} extra)",
|
||||
positionals.len() - pos_i
|
||||
)));
|
||||
}
|
||||
let slot = self
|
||||
.locals
|
||||
.get(recv)
|
||||
.copied()
|
||||
.ok_or_else(|| self.err(format!("undefined variable `{recv}`")))?;
|
||||
self.emit(Op::GetLocal(slot));
|
||||
let name_i = self.add_const(Value::Text(call.callee.clone()));
|
||||
self.emit(Op::MethodCall(name_i, params.len() as u8));
|
||||
if as_stmt {
|
||||
self.emit(Op::Pop);
|
||||
}
|
||||
|
||||
@@ -54,6 +54,11 @@ pub enum Op {
|
||||
GetIndex,
|
||||
/// Call function by index; argc values are on the stack (param order).
|
||||
Call(u16, u8),
|
||||
/// After a constructor Call: tag top-of-stack map with `_type` = constants[idx].
|
||||
TagInstance(u16),
|
||||
/// Method call: stack has argc args (param order) then receiver on top.
|
||||
/// constants[name_idx] is method name text; resolve via receiver `_type`.
|
||||
MethodCall(u16, u8),
|
||||
/// Host primitive: pop `argc` args (param order), push result.
|
||||
HostCall(u16, u8),
|
||||
Return,
|
||||
@@ -75,6 +80,10 @@ pub struct FnChunk {
|
||||
pub struct Program {
|
||||
pub functions: Vec<FnChunk>,
|
||||
pub entry: usize,
|
||||
/// Top-level object name → function index (level-1).
|
||||
pub objects: Vec<(String, usize)>,
|
||||
/// (object_fn_idx, method_name) → method fn idx
|
||||
pub methods: Vec<(usize, String, usize)>,
|
||||
}
|
||||
|
||||
impl Program {
|
||||
|
||||
@@ -336,6 +336,69 @@ impl Vm {
|
||||
slots,
|
||||
});
|
||||
}
|
||||
Op::TagInstance(idx) => {
|
||||
let type_name = match fun.constants.get(idx as usize) {
|
||||
Some(Value::Text(s)) => s.clone(),
|
||||
_ => {
|
||||
return Err(self.err_at(span, "TagInstance needs type name constant"));
|
||||
}
|
||||
};
|
||||
let v = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
|
||||
stack.push(tag_instance_value(&type_name, v));
|
||||
}
|
||||
Op::MethodCall(name_idx, argc) => {
|
||||
let argc = argc as usize;
|
||||
let method_name = match fun.constants.get(name_idx as usize) {
|
||||
Some(Value::Text(s)) => s.clone(),
|
||||
_ => {
|
||||
return Err(self.err_at(span, "MethodCall needs method name constant"));
|
||||
}
|
||||
};
|
||||
let recv = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
|
||||
let mut vals = Vec::with_capacity(argc);
|
||||
for _ in 0..argc {
|
||||
vals.push(pop(&mut stack).map_err(|m| self.err_at(span, m))?);
|
||||
}
|
||||
vals.reverse();
|
||||
let type_name = instance_type_name_bc(&recv).map_err(|m| self.err_at(span, m))?;
|
||||
let obj_idx = program
|
||||
.objects
|
||||
.iter()
|
||||
.find(|(n, _)| n == &type_name)
|
||||
.map(|(_, i)| *i)
|
||||
.ok_or_else(|| {
|
||||
self.err_at(span, format!("unknown object type `{type_name}`"))
|
||||
})?;
|
||||
let method_fid = program
|
||||
.methods
|
||||
.iter()
|
||||
.find(|(o, m, _)| *o == obj_idx && m == &method_name)
|
||||
.map(|(_, _, i)| *i)
|
||||
.ok_or_else(|| {
|
||||
self.err_at(
|
||||
span,
|
||||
format!("unknown method `{type_name}.{method_name}`"),
|
||||
)
|
||||
})?;
|
||||
let callee = &program.functions[method_fid];
|
||||
if callee.params.len() != argc {
|
||||
return Err(self.err_at(span, "method argument count mismatch"));
|
||||
}
|
||||
let mut slots = vec![Value::None; callee.locals.len().max(1)];
|
||||
for (i, v) in vals.into_iter().enumerate() {
|
||||
slots[i] = v;
|
||||
}
|
||||
for (i, name) in callee.locals.iter().enumerate() {
|
||||
if name == "自" || name == "self" {
|
||||
slots[i] = recv.clone();
|
||||
}
|
||||
}
|
||||
frames.push(Frame {
|
||||
fn_idx: method_fid,
|
||||
ip: 0,
|
||||
slots,
|
||||
});
|
||||
}
|
||||
Op::Return => {
|
||||
let ret = pop(&mut stack).unwrap_or(Value::None);
|
||||
frames.pop();
|
||||
@@ -397,3 +460,33 @@ fn cmp(stack: &mut Vec<Value>, pred: impl Fn(std::cmp::Ordering) -> bool) -> Res
|
||||
stack.push(Value::Bool(pred(ord)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn instance_type_name_bc(v: &Value) -> Result<String, String> {
|
||||
match v {
|
||||
Value::Map(entries) => entries
|
||||
.iter()
|
||||
.find(|(k, _)| k == "_type")
|
||||
.and_then(|(_, v)| match v {
|
||||
Value::Text(s) => Some(s.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.ok_or_else(|| "method receiver needs a map with `_type`".into()),
|
||||
_ => Err("method receiver must be an object map".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn tag_instance_value(type_name: &str, value: Value) -> Value {
|
||||
match value {
|
||||
Value::Map(mut entries) => {
|
||||
if !entries.iter().any(|(k, _)| k == "_type") {
|
||||
entries.insert(0, ("_type".into(), Value::Text(type_name.into())));
|
||||
}
|
||||
Value::Map(entries)
|
||||
}
|
||||
Value::None => Value::Map(vec![("_type".into(), Value::Text(type_name.into()))]),
|
||||
other => Value::Map(vec![
|
||||
("_type".into(), Value::Text(type_name.into())),
|
||||
("value".into(), other),
|
||||
]),
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user