Add C and C++ library support
import "zlib.h" reads the header (cc -E + a small C declaration parser), links via pkg-config or link "name", and builds .c/.cpp files next to the program. C structs become Dino structs, pointers become pointer types (nil = NULL), T* parameters take variables or lists. Adds dino header, editor completion/hover for C names, docs chapter 13, a raylib example, and tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
5b42e2a3bd
commit
2f44f09b6a
26 files changed
+3418
-70
No files matched your search
+386
-12
@@ -5,6 +5,7 @@ use std::collections::{HashMap, HashSet};
|
||||
use crate::ast::*;
|
||||
use crate::error::{Diag, PResult};
|
||||
use crate::hir::*;
|
||||
use crate::cheader::{self, CTy};
|
||||
use crate::stdlib::{self, ModuleValue};
|
||||
use crate::types::{Num, Ty};
|
||||
|
||||
@@ -17,12 +18,23 @@ pub fn check_project(main: &Program, modules: &[(String, Program)]) -> PResult<H
|
||||
Checker::new().program(main, modules)
|
||||
}
|
||||
|
||||
/// Like `check_project`, with the C headers the program imports already read.
|
||||
pub fn check_project_c(main: &Program, modules: &[(String, Program)], clibs: Vec<cheader::Lib>) -> PResult<HProgram> {
|
||||
let mut c = Checker::new();
|
||||
c.clibs = clibs;
|
||||
c.program(main, modules)
|
||||
}
|
||||
|
||||
/// What an `import` name stands for.
|
||||
#[derive(Clone, Debug)]
|
||||
enum Target {
|
||||
Builtin(&'static str),
|
||||
/// A file of the user's; the full import path (`utils`, `a.b`).
|
||||
User(String),
|
||||
/// A C header (index into `clibs`): its names are used as `zlib.name`.
|
||||
C(usize),
|
||||
/// One name picked from a C header with `import "zlib.h" { name }`.
|
||||
CItem(usize),
|
||||
}
|
||||
|
||||
const BUILTINS: &[&str] = &[
|
||||
@@ -146,6 +158,10 @@ struct Checker {
|
||||
/// While checking a generic function: what its type names (`T`) stand for.
|
||||
tsubst: HashMap<String, Ty>,
|
||||
inst_queue: Vec<Instance>,
|
||||
/// The C headers the program imports.
|
||||
clibs: Vec<cheader::Lib>,
|
||||
/// Structs that come from C headers: table name -> how C spells the type.
|
||||
c_structs: HashMap<String, String>,
|
||||
}
|
||||
|
||||
// ---------- names used inside a function body (to find what a closure captures) ----------
|
||||
@@ -410,6 +426,7 @@ fn has_call(h: &HExpr) -> bool {
|
||||
| HExprKind::ListPop(_)
|
||||
| HExprKind::MapCall { .. }
|
||||
| HExprKind::Builtin { .. }
|
||||
| HExprKind::CCall { .. }
|
||||
| HExprKind::CallValue { .. }
|
||||
| HExprKind::IfaceCall { .. }
|
||||
| HExprKind::Closure { .. }
|
||||
@@ -514,6 +531,8 @@ impl Checker {
|
||||
bounds_of: HashMap::new(),
|
||||
tsubst: HashMap::new(),
|
||||
inst_queue: Vec::new(),
|
||||
clibs: Vec::new(),
|
||||
c_structs: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -523,6 +542,7 @@ impl Checker {
|
||||
let mut mods: Vec<(&str, &Program)> = modules.iter().map(|(k, p)| (k.as_str(), p)).collect();
|
||||
mods.push(("", main));
|
||||
self.known_modules = modules.iter().map(|(k, _)| k.clone()).collect();
|
||||
self.register_c_structs();
|
||||
|
||||
for (key, p) in &mods {
|
||||
self.enter(key);
|
||||
@@ -577,7 +597,11 @@ impl Checker {
|
||||
let types = type_order
|
||||
.into_iter()
|
||||
.map(|name| match self.structs.get(name) {
|
||||
Some(info) => HTypeDef::Struct(HStruct { name: name.to_string(), fields: info.fields.clone() }),
|
||||
Some(info) => HTypeDef::Struct(HStruct {
|
||||
name: name.to_string(),
|
||||
fields: info.fields.clone(),
|
||||
c: self.c_structs.get(name).cloned(),
|
||||
}),
|
||||
None => HTypeDef::Enum(HEnum {
|
||||
name: name.to_string(),
|
||||
variants: self.enums[name]
|
||||
@@ -591,7 +615,21 @@ impl Checker {
|
||||
let mut ifaces: Vec<(String, Vec<(String, Vec<Ty>, Ty)>)> =
|
||||
self.ifaces.iter().map(|(k, i)| (k.clone(), i.methods.clone())).collect();
|
||||
ifaces.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
Ok(HProgram { types, funcs, ifaces })
|
||||
let mut c = CInfo::default();
|
||||
for lib in &self.clibs {
|
||||
let add = |list: &mut Vec<String>, items: Vec<String>| {
|
||||
for i in items {
|
||||
if !list.contains(&i) {
|
||||
list.push(i);
|
||||
}
|
||||
}
|
||||
};
|
||||
add(&mut c.headers, vec![lib.header.clone()]);
|
||||
add(&mut c.cflags, lib.cflags.clone());
|
||||
add(&mut c.libs, lib.libs.clone());
|
||||
add(&mut c.sources, lib.sources.iter().map(|p| p.display().to_string()).collect());
|
||||
}
|
||||
Ok(HProgram { types, funcs, ifaces, c })
|
||||
}
|
||||
|
||||
/// Start checking the module `key`.
|
||||
@@ -1012,8 +1050,8 @@ impl Checker {
|
||||
}
|
||||
|
||||
fn import(&mut self, i: &Import) -> PResult<()> {
|
||||
if i.alias.is_some() {
|
||||
return unsupported(i.span, "importing a C library");
|
||||
if i.c {
|
||||
return self.import_c(i);
|
||||
}
|
||||
let alias = i.path.rsplit('.').next().unwrap().to_string();
|
||||
if self.imports.contains_key(&alias) {
|
||||
@@ -1046,15 +1084,41 @@ impl Checker {
|
||||
fn user_alias(&self, e: &Expr) -> Option<String> {
|
||||
match self.alias_target(e)? {
|
||||
Target::User(p) => Some(p.clone()),
|
||||
Target::Builtin(_) => None,
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// If `e` is the name of an imported C header, which one.
|
||||
fn c_alias(&self, e: &Expr) -> Option<usize> {
|
||||
match self.alias_target(e)? {
|
||||
Target::C(i) => Some(*i),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A name picked from a C header (`import "zlib.h" { name }`), not hidden by a variable.
|
||||
fn c_item(&self, name: &str) -> Option<usize> {
|
||||
if self.lookup(name).is_some() || self.implicit_field(name).is_some() {
|
||||
return None;
|
||||
}
|
||||
match self.imports.get(name)? {
|
||||
Target::CItem(i) => Some(*i),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The table name for a type or function written as `name` or `module.name`.
|
||||
fn global_key(&self, e: &Expr) -> Option<String> {
|
||||
match &e.kind {
|
||||
ExprKind::Ident(n) => Some(self.q(n)),
|
||||
ExprKind::Field { expr, name } => Some(format!("{}.{}", self.user_alias(expr)?, name)),
|
||||
ExprKind::Ident(n) => match self.c_item(n) {
|
||||
Some(i) => Some(format!("{}.{n}", self.clibs[i].prefix)),
|
||||
None => Some(self.q(n)),
|
||||
},
|
||||
ExprKind::Field { expr, name } => match self.alias_target(expr)? {
|
||||
Target::User(p) => Some(format!("{p}.{name}")),
|
||||
Target::C(i) => Some(format!("{}.{name}", self.clibs[*i].prefix)),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -1063,7 +1127,266 @@ impl Checker {
|
||||
fn module_alias(&self, e: &Expr) -> Option<&'static str> {
|
||||
match self.alias_target(e)? {
|
||||
Target::Builtin(m) => Some(m),
|
||||
Target::User(_) => None,
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- C headers ----------
|
||||
|
||||
fn import_c(&mut self, i: &Import) -> PResult<()> {
|
||||
let Some(idx) = self.clibs.iter().position(|l| l.header == i.path) else {
|
||||
return Err(Diag::new(format!("the C header `{}` could not be read", i.path), i.span));
|
||||
};
|
||||
let lib = &self.clibs[idx];
|
||||
match &i.names {
|
||||
None => {
|
||||
let alias = i.alias.clone().unwrap_or_else(|| lib.prefix.clone());
|
||||
if self.imports.contains_key(&alias) {
|
||||
return Err(Diag::new(
|
||||
format!("`{alias}` is imported twice; give the header another name, like `import c{alias} \"{}\"`", i.path),
|
||||
i.span,
|
||||
));
|
||||
}
|
||||
self.imports.insert(alias, Target::C(idx));
|
||||
}
|
||||
Some(names) => {
|
||||
for (n, span) in names {
|
||||
if !lib.names().contains(&n.as_str()) && lib.func(n).is_none() {
|
||||
let hint = similar(n, &lib.names()).map(|s| format!(" (did you mean `{s}`?)")).unwrap_or_default();
|
||||
return Err(Diag::new(format!("`{}` has no `{n}`{hint}", lib.header), *span));
|
||||
}
|
||||
if self.imports.contains_key(n) {
|
||||
return Err(Diag::new(format!("`{n}` is imported twice"), *span));
|
||||
}
|
||||
self.imports.insert(n.clone(), Target::CItem(idx));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The Dino type for a C type, if it has one.
|
||||
fn c_type(&self, lib: usize, t: &CTy) -> Option<Ty> {
|
||||
Some(match t {
|
||||
CTy::Void => Ty::Unit,
|
||||
CTy::Num(t) => *t,
|
||||
CTy::Str => Ty::Str,
|
||||
CTy::Handle(n) if n == "pointer" => Ty::CPtr("pointer"),
|
||||
CTy::Handle(n) => Ty::CPtr(Box::leak(format!("{}.{n}", self.clibs[lib].prefix).into_boxed_str())),
|
||||
CTy::Struct(n) => Ty::Struct(self.structs.get(&format!("{}.{n}", self.clibs[lib].prefix))?.name),
|
||||
CTy::Ptr { .. } | CTy::Unsupported(_) => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Structs from C headers become Dino structs (`raylib.Color`), converted at calls.
|
||||
fn register_c_structs(&mut self) {
|
||||
for li in 0..self.clibs.len() {
|
||||
let prefix = self.clibs[li].prefix.clone();
|
||||
for s in self.clibs[li].structs.clone() {
|
||||
let key = format!("{prefix}.{}", s.name);
|
||||
let name: &'static str = Box::leak(key.clone().into_boxed_str());
|
||||
self.structs.insert(key.clone(), StructInfo { name, fields: Vec::new(), methods: HashMap::new(), span: Span::default() });
|
||||
self.c_structs.insert(key, s.c.clone());
|
||||
}
|
||||
for s in self.clibs[li].structs.clone() {
|
||||
let key = format!("{prefix}.{}", s.name);
|
||||
let fields: Vec<(String, Ty)> =
|
||||
s.fields.iter().map(|(n, t)| (n.clone(), self.c_type(li, t).unwrap_or(Ty::CPtr("pointer")))).collect();
|
||||
self.structs.get_mut(&key).unwrap().fields = fields;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The type `name` from C header `lib` (`zlib.gzFile`, `raylib.Color`).
|
||||
fn c_named_type(&self, lib: usize, name: &str, span: Span) -> PResult<Ty> {
|
||||
let l = &self.clibs[lib];
|
||||
if l.strukt(name).is_some() {
|
||||
return self.c_type(lib, &CTy::Struct(name.to_string())).ok_or_else(|| Diag::new("unknown C struct", span));
|
||||
}
|
||||
if l.has_handle(name) {
|
||||
return Ok(self.c_type(lib, &CTy::Handle(name.to_string())).unwrap());
|
||||
}
|
||||
let types: Vec<&str> = l.structs.iter().map(|s| s.name.as_str()).chain(l.handles.iter().map(|h| h.as_str())).collect();
|
||||
let hint = similar(name, &types).map(|s| format!(" (did you mean `{s}`?)")).unwrap_or_default();
|
||||
Err(Diag::new(format!("`{}` has no type `{name}`{hint}", l.header), span))
|
||||
}
|
||||
|
||||
/// A constant from a C header: `zlib.Z_OK`, `raylib.RED`.
|
||||
fn c_value(&self, lib: usize, name: &str, span: Span) -> PResult<HExpr> {
|
||||
let l = &self.clibs[lib];
|
||||
if let Some(c) = l.konst(name) {
|
||||
return Ok(match &c.value {
|
||||
cheader::Value::Int(i) => mk(HExprKind::Int(*i), Ty::Int),
|
||||
cheader::Value::Float(f) => mk(HExprKind::Float(*f), Ty::Float),
|
||||
cheader::Value::Str(s) => mk(HExprKind::Str(s.clone()), Ty::Str),
|
||||
cheader::Value::Struct(sn) => {
|
||||
let ty = self.c_named_type(lib, sn, span)?;
|
||||
mk(HExprKind::CRaw(name.to_string()), ty)
|
||||
}
|
||||
});
|
||||
}
|
||||
if l.func(name).is_some() {
|
||||
return Err(Diag::new(format!("`{name}` is a C function; call it like `{name}(...)`"), span));
|
||||
}
|
||||
if l.strukt(name).is_some() || l.has_handle(name) {
|
||||
return Err(Diag::new(format!("`{name}` is a C type, not a value"), span));
|
||||
}
|
||||
let hint = similar(name, &l.names()).map(|s| format!(" (did you mean `{s}`?)")).unwrap_or_default();
|
||||
Err(Diag::new(format!("`{}` has no `{name}`{hint}", l.header), span))
|
||||
}
|
||||
|
||||
fn c_call(&mut self, lib: usize, name: &str, args: &[Expr], span: Span, name_span: Span) -> PResult<HExpr> {
|
||||
let l = &self.clibs[lib];
|
||||
let Some(f) = l.func(name).cloned() else {
|
||||
if l.konst(name).is_some() {
|
||||
return Err(Diag::new(format!("`{name}` is a constant, not a function"), name_span));
|
||||
}
|
||||
if l.strukt(name).is_some() {
|
||||
return Err(Diag::new(format!("`{name}` is a C struct; build one with `{name}{{...}}`"), name_span));
|
||||
}
|
||||
let hint = similar(name, &l.names()).map(|s| format!(" (did you mean `{s}`?)")).unwrap_or_default();
|
||||
return Err(Diag::new(format!("`{}` has no function `{name}`{hint}", l.header), name_span));
|
||||
};
|
||||
if let Some(why) = &f.problem {
|
||||
return Err(Diag::new(format!("`{name}` can't be called from Dino: it {why}"), name_span));
|
||||
}
|
||||
if args.len() != f.params.len() {
|
||||
let names: Vec<String> = f
|
||||
.params
|
||||
.iter()
|
||||
.map(|(n, t)| if n.is_empty() { self.c_param_text(lib, t) } else { format!("{n}: {}", self.c_param_text(lib, t)) })
|
||||
.collect();
|
||||
return Err(Diag::new(
|
||||
format!(
|
||||
"`{name}` takes {} argument{} ({}), but {} {} given",
|
||||
f.params.len(),
|
||||
if f.params.len() == 1 { "" } else { "s" },
|
||||
names.join(", "),
|
||||
args.len(),
|
||||
if args.len() == 1 { "was" } else { "were" },
|
||||
),
|
||||
span,
|
||||
));
|
||||
}
|
||||
let mut hs = Vec::new();
|
||||
let mut modes = Vec::new();
|
||||
for ((pname, pt), a) in f.params.iter().zip(args) {
|
||||
let (h, m) = self.c_arg(lib, name, pname, pt, a)?;
|
||||
hs.push(h);
|
||||
modes.push(m);
|
||||
}
|
||||
let ret = self.c_type(lib, &f.ret).unwrap_or(Ty::CPtr("pointer"));
|
||||
Ok(mk(HExprKind::CCall { name: name.to_string(), args: hs, modes }, ret))
|
||||
}
|
||||
|
||||
/// How a C parameter type reads in a message.
|
||||
fn c_param_text(&self, lib: usize, t: &CTy) -> String {
|
||||
match t {
|
||||
CTy::Ptr { to, .. } if matches!(**to, CTy::Struct(_) | CTy::Handle(_)) => {
|
||||
self.c_type(lib, to).map_or("pointer".into(), |t| format!("{t} variable"))
|
||||
}
|
||||
CTy::Ptr { to, konst } => match self.c_type(lib, to) {
|
||||
Some(inner) if *konst => format!("{inner} or []{inner}"),
|
||||
Some(inner) => format!("{inner} variable or []{inner}"),
|
||||
None => "pointer".into(),
|
||||
},
|
||||
t => self.c_type(lib, t).map_or("?".into(), |t| t.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn c_arg(&mut self, lib: usize, fname: &str, pname: &str, pt: &CTy, a: &Expr) -> PResult<(HExpr, CArg)> {
|
||||
let null = || Ok((mk(HExprKind::Bool(false), Ty::Bool), CArg::Null));
|
||||
let is_nil = matches!(a.kind, ExprKind::Nil);
|
||||
let what = if pname.is_empty() { format!("this argument of `{fname}`") } else { format!("`{pname}` of `{fname}`") };
|
||||
match pt {
|
||||
CTy::Str => {
|
||||
if is_nil {
|
||||
return null();
|
||||
}
|
||||
let h = self.expr(a, Some(Ty::Str))?;
|
||||
match h.ty {
|
||||
Ty::Str => Ok((h, CArg::Str)),
|
||||
Ty::List(Ty::Num(Num::U8 | Num::I8)) => Ok((h, CArg::Buffer)),
|
||||
t => Err(Diag::new(format!("{what} is a `string` (or a `[]u8` to fill in), found `{t}`"), a.span)),
|
||||
}
|
||||
}
|
||||
CTy::Handle(_) => {
|
||||
let want = self.c_type(lib, pt).unwrap();
|
||||
if is_nil {
|
||||
return Ok((mk(HExprKind::Nil, want), CArg::Value));
|
||||
}
|
||||
let h = self.expr(a, Some(want))?;
|
||||
match h.ty {
|
||||
Ty::CPtr(x) if Ty::CPtr(x) == want || x == "pointer" || want == Ty::CPtr("pointer") => Ok((h, CArg::Value)),
|
||||
Ty::List(e) if want == Ty::CPtr("pointer") && (e.is_number() || *e == Ty::Bool) => Ok((h, CArg::Buffer)),
|
||||
Ty::Str if want == Ty::CPtr("pointer") => Ok((h, CArg::Str)),
|
||||
t => Err(Diag::new(format!("{what} is a `{want}`, found `{t}`"), a.span)),
|
||||
}
|
||||
}
|
||||
CTy::Ptr { to, konst } => {
|
||||
let Some(inner) = self.c_type(lib, to) else {
|
||||
return Err(Diag::new(format!("{what} has a type Dino can't pass"), a.span));
|
||||
};
|
||||
if is_nil {
|
||||
return null();
|
||||
}
|
||||
// `sqlite3 **db`: a pointer variable the function fills in
|
||||
if let Ty::CPtr(want) = inner {
|
||||
let h = self.expr(a, Some(inner))?;
|
||||
let fits = |t: Ty| matches!(t, Ty::CPtr(x) if x == want || x == "pointer" || want == "pointer");
|
||||
if !fits(h.ty) {
|
||||
return Err(Diag::new(format!("{what} is a `{inner}` variable that the function fills in, found `{}`", h.ty), a.span));
|
||||
}
|
||||
if *konst {
|
||||
return Ok((h, CArg::AddrIn));
|
||||
}
|
||||
let thing = if pname.is_empty() { "this argument".to_string() } else { format!("`{pname}`") };
|
||||
let p = self.place(a).map_err(|_| {
|
||||
Diag::new(format!("`{fname}` writes into {thing}, so it must be a variable (or a field of one)"), a.span)
|
||||
})?;
|
||||
return Ok((p, CArg::Addr));
|
||||
}
|
||||
let h = self.expr(a, Some(inner))?;
|
||||
if h.ty == Ty::list(inner) {
|
||||
if matches!(inner, Ty::Struct(_)) {
|
||||
return Err(Diag::new(format!("{what} wants C structs in a row; a Dino list of structs can't be passed"), a.span));
|
||||
}
|
||||
return Ok((h, CArg::Buffer));
|
||||
}
|
||||
if let Ty::CPtr(_) = h.ty {
|
||||
return Ok((h, CArg::Value));
|
||||
}
|
||||
let h = self.coerce(h, inner, a.span).map_err(|_| {
|
||||
Diag::new(
|
||||
format!(
|
||||
"{what} is {} `{inner}` (or a list `[]{inner}`), found something else",
|
||||
if *konst { "a" } else { "a variable of type" }
|
||||
),
|
||||
a.span,
|
||||
)
|
||||
})?;
|
||||
if *konst {
|
||||
return Ok((h, CArg::AddrIn));
|
||||
}
|
||||
let p = self.place(a).map_err(|_| {
|
||||
let thing = if pname.is_empty() { "this argument".to_string() } else { format!("`{pname}`") };
|
||||
Diag::new(format!("`{fname}` writes into {thing}, so it must be a variable (or a field of one)"), a.span)
|
||||
})?;
|
||||
Ok((p, CArg::Addr))
|
||||
}
|
||||
CTy::Num(_) | CTy::Struct(_) => {
|
||||
let want = self.c_type(lib, pt).unwrap();
|
||||
// a C `char` takes a Dino character: `'a'`
|
||||
if matches!(want, Ty::Num(Num::I8 | Num::U8)) {
|
||||
let h = self.expr(a, Some(want))?;
|
||||
if h.ty == Ty::Char {
|
||||
return Ok((mk(HExprKind::Convert(Box::new(h)), want), CArg::Value));
|
||||
}
|
||||
return Ok((self.coerce(h, want, a.span)?, CArg::Value));
|
||||
}
|
||||
Ok((self.expr_as(a, want)?, CArg::Value))
|
||||
}
|
||||
CTy::Void | CTy::Unsupported(_) => Err(Diag::new(format!("{what} has a type Dino can't pass"), a.span)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1281,6 +1604,10 @@ impl Checker {
|
||||
"f64" => Ok(Ty::Float),
|
||||
n if Num::ALL.iter().any(|k| k.name() == n) => Ok(conversion_target(n).unwrap()),
|
||||
n if self.tsubst.contains_key(n) => Ok(self.tsubst[n]),
|
||||
n if matches!(self.imports.get(n), Some(Target::CItem(..))) => {
|
||||
let Some(Target::CItem(lib)) = self.imports.get(n) else { unreachable!() };
|
||||
self.c_named_type(*lib, n, span)
|
||||
}
|
||||
n => {
|
||||
let key = self.q(n);
|
||||
if self.ifaces.contains_key(&key) {
|
||||
@@ -1333,6 +1660,10 @@ impl Checker {
|
||||
}
|
||||
self.instantiate_type(&key, &shown, tys, span)
|
||||
}
|
||||
Type::Named { path, args } if path.len() == 2 && args.is_empty() && matches!(self.imports.get(&path[0]), Some(Target::C(_))) => {
|
||||
let Some(Target::C(lib)) = self.imports.get(&path[0]) else { unreachable!() };
|
||||
self.c_named_type(*lib, &path[1], span)
|
||||
}
|
||||
Type::Named { path, args } if path.len() == 2 && args.is_empty() => {
|
||||
let Some(Target::User(module)) = self.imports.get(&path[0]) else {
|
||||
return Err(Diag::new(format!("unknown type `{}.{}` (is `{}` imported?)", path[0], path[1], path[0]), span));
|
||||
@@ -1496,7 +1827,7 @@ impl Checker {
|
||||
},
|
||||
Ty::List(_) => HExprKind::ListLit { elems: Vec::new() },
|
||||
Ty::Map(..) => HExprKind::MapLit { entries: Vec::new() },
|
||||
Ty::Error | Ty::Opt(_) | Ty::Weak(_) | Ty::Shared(_) | Ty::Func(_) | Ty::Iface(_) => HExprKind::Nil,
|
||||
Ty::Error | Ty::Opt(_) | Ty::Weak(_) | Ty::Shared(_) | Ty::Func(_) | Ty::Iface(_) | Ty::CPtr(_) => HExprKind::Nil,
|
||||
Ty::Tuple(items) => HExprKind::TupleLit(items.iter().map(|t| self.zero_expr(*t)).collect()),
|
||||
Ty::Unit => unreachable!("nothing has no zero value"),
|
||||
};
|
||||
@@ -2218,7 +2549,7 @@ impl Checker {
|
||||
Some(h) => h,
|
||||
None => self.expr(other, None)?,
|
||||
};
|
||||
if !matches!(h.ty, Ty::Opt(_) | Ty::Error | Ty::Weak(_) | Ty::Iface(_)) {
|
||||
if !matches!(h.ty, Ty::Opt(_) | Ty::Error | Ty::Weak(_) | Ty::Iface(_) | Ty::CPtr(_)) {
|
||||
return Err(Diag::new(
|
||||
format!("a `{}` can never be nil, so comparing it with `nil` is pointless", h.ty),
|
||||
e.span,
|
||||
@@ -2253,6 +2584,10 @@ impl Checker {
|
||||
let m = self.module_alias(expr).unwrap();
|
||||
self.module_value(m, name, e.span)
|
||||
}
|
||||
ExprKind::Field { expr, name } if self.c_alias(expr).is_some() => {
|
||||
let lib = self.c_alias(expr).unwrap();
|
||||
self.c_value(lib, name, e.span)
|
||||
}
|
||||
ExprKind::Generic { .. } => Err(Diag::new(
|
||||
"a generic type is not a value; build one with `Name[types]{...}` or pick an enum case with `Name[types].Case`",
|
||||
e.span,
|
||||
@@ -2315,7 +2650,7 @@ impl Checker {
|
||||
e.span,
|
||||
)),
|
||||
ExprKind::Nil => match expect {
|
||||
Some(t @ (Ty::Opt(_) | Ty::Error | Ty::Weak(_) | Ty::Iface(_))) => Ok(mk(HExprKind::Nil, t)),
|
||||
Some(t @ (Ty::Opt(_) | Ty::Error | Ty::Weak(_) | Ty::Iface(_) | Ty::CPtr(_))) => Ok(mk(HExprKind::Nil, t)),
|
||||
_ => Err(Diag::new(
|
||||
"can't tell what `nil` stands for here; it needs a type like `User?` or `error` (for example `return value, nil`)",
|
||||
e.span,
|
||||
@@ -2469,6 +2804,9 @@ impl Checker {
|
||||
if let Some(c) = self.consts.get(&key) {
|
||||
return Ok(c.clone());
|
||||
}
|
||||
if let Some(lib) = self.c_item(name) {
|
||||
return self.c_value(lib, name, span);
|
||||
}
|
||||
if self.funcs.contains_key(&key) {
|
||||
return self.func_value(&key, name, span);
|
||||
}
|
||||
@@ -2860,7 +3198,7 @@ impl Checker {
|
||||
BinOp::Sub | BinOp::Mul | BinOp::Div => t.is_number(),
|
||||
BinOp::Rem => t.is_int(),
|
||||
BinOp::Eq | BinOp::Ne => {
|
||||
t.is_number() || matches!(t, Ty::Bool | Ty::Str | Ty::Char)
|
||||
t.is_number() || matches!(t, Ty::Bool | Ty::Str | Ty::Char | Ty::CPtr(_))
|
||||
|| matches!(t, Ty::Enum(n) if self.enums[n].variants.iter().all(|v| v.fields.is_empty()))
|
||||
}
|
||||
BinOp::Lt | BinOp::Gt | BinOp::Le | BinOp::Ge => t.is_number() || t == Ty::Str || t == Ty::Char,
|
||||
@@ -3132,6 +3470,14 @@ impl Checker {
|
||||
|
||||
fn call(&mut self, callee: &Expr, args: &[Expr], span: Span) -> PResult<HExpr> {
|
||||
match &callee.kind {
|
||||
ExprKind::Field { expr, name } if self.c_alias(expr).is_some() => {
|
||||
let lib = self.c_alias(expr).unwrap();
|
||||
self.c_call(lib, name, args, span, callee.span)
|
||||
}
|
||||
ExprKind::Ident(name) if self.c_item(name).is_some() => {
|
||||
let lib = self.c_item(name).unwrap();
|
||||
self.c_call(lib, name, args, span, callee.span)
|
||||
}
|
||||
ExprKind::Field { expr, name } if self.module_alias(expr).is_some() => {
|
||||
let m = self.module_alias(expr).unwrap();
|
||||
self.module_call(m, name, args, span, callee.span)
|
||||
@@ -3821,3 +4167,31 @@ fn check_mutating_calls(funcs: &[HFunc]) -> PResult<()> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The name in `names` closest to `name`, if one is close enough to be a likely typo.
|
||||
fn similar<'a>(name: &str, names: &[&'a str]) -> Option<&'a str> {
|
||||
fn dist(a: &str, b: &str) -> usize {
|
||||
let (a, b): (Vec<char>, Vec<char>) = (a.chars().collect(), b.chars().collect());
|
||||
let mut prev: Vec<usize> = (0..=b.len()).collect();
|
||||
let mut prev2: Vec<usize> = prev.clone();
|
||||
for i in 1..=a.len() {
|
||||
let mut cur = vec![i; b.len() + 1];
|
||||
for j in 1..=b.len() {
|
||||
let cost = if a[i - 1] == b[j - 1] { 0 } else { 1 };
|
||||
cur[j] = (prev[j] + 1).min(cur[j - 1] + 1).min(prev[j - 1] + cost);
|
||||
// two letters swapped count as one mistake
|
||||
if i > 1 && j > 1 && a[i - 1] == b[j - 2] && a[i - 2] == b[j - 1] {
|
||||
cur[j] = cur[j].min(prev2[j - 2] + 1);
|
||||
}
|
||||
}
|
||||
prev2 = std::mem::replace(&mut prev, cur);
|
||||
}
|
||||
prev[b.len()]
|
||||
}
|
||||
let lower = name.to_lowercase();
|
||||
if let Some(n) = names.iter().find(|n| n.to_lowercase() == lower) {
|
||||
return Some(n);
|
||||
}
|
||||
let limit = (name.chars().count() / 3).max(1);
|
||||
names.iter().map(|n| (dist(&lower, &n.to_lowercase()), *n)).filter(|(d, _)| *d <= limit).min_by_key(|(d, _)| *d).map(|(_, n)| n)
|
||||
}
|
||||
Reference in new issue
Block a user