| @@ -0,0 +1,1202 @@ |
| 1 | +//! Signature resolution and body lowering. |
| 2 | + |
| 3 | +use std::collections::HashMap; |
| 4 | + |
| 5 | +use tilc_diag::Diagnostic; |
| 6 | +use tilc_span::{FileId, Span, TextRange}; |
| 7 | +use tilc_syntax::ast::{self, AstNode}; |
| 8 | +use tilc_syntax::{SyntaxKind, SyntaxToken}; |
| 9 | + |
| 10 | +use crate::body::*; |
| 11 | +use crate::def::*; |
| 12 | +use crate::{Hir, Pending, codes}; |
| 13 | + |
| 14 | +/// Results computed with `&Hir`, applied afterwards. |
| 15 | +enum Lowered { |
| 16 | + Alias(TypeRef), |
| 17 | + Fields(Vec<FieldDef>), |
| 18 | + Fn(FnSig, Option<Body>), |
| 19 | + Impl(TypeRef, Vec<TypeRef>), |
| 20 | + Op(FnSig), |
| 21 | + Nothing, |
| 22 | +} |
| 23 | + |
| 24 | +pub(crate) fn lower_pending(hir: &mut Hir, pending: Vec<Pending>, diags: &mut Vec<Diagnostic>) { |
| 25 | + let mut results = Vec::with_capacity(pending.len()); |
| 26 | + for p in &pending { |
| 27 | + let (id, lowered) = lower_one(hir, p, diags); |
| 28 | + results.push((id, lowered)); |
| 29 | + } |
| 30 | + for (id, lowered) in results { |
| 31 | + match (&mut hir.defs[id].kind, lowered) { |
| 32 | + (DefKind::Type(t), Lowered::Alias(target)) => t.body = TypeBody::Alias(target), |
| 33 | + (DefKind::Ctor(c), Lowered::Fields(fields)) => c.fields = fields, |
| 34 | + (DefKind::Fn(f), Lowered::Fn(sig, body)) => { |
| 35 | + f.sig = sig; |
| 36 | + f.body = body; |
| 37 | + } |
| 38 | + (DefKind::Impl(i), Lowered::Impl(target, constraints)) => { |
| 39 | + i.target = target; |
| 40 | + i.constraints = constraints; |
| 41 | + } |
| 42 | + (DefKind::Op(o), Lowered::Op(sig)) => o.sig = sig, |
| 43 | + _ => {} |
| 44 | + } |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +fn lower_one(hir: &Hir, pending: &Pending, diags: &mut Vec<Diagnostic>) -> (DefId, Lowered) { |
| 49 | + let id = match pending { |
| 50 | + Pending::Type(id, _) |
| 51 | + | Pending::Ctor(id, _) |
| 52 | + | Pending::Fn(id, _) |
| 53 | + | Pending::Impl(id, _) |
| 54 | + | Pending::Op(id, _) => *id, |
| 55 | + }; |
| 56 | + let def = &hir.defs[id]; |
| 57 | + let mut cx = Cx { |
| 58 | + hir, |
| 59 | + module: def.module, |
| 60 | + file: hir.modules[def.module].file, |
| 61 | + diags, |
| 62 | + }; |
| 63 | + let lowered = match pending { |
| 64 | + Pending::Type(_, t) => t |
| 65 | + .alias() |
| 66 | + .map_or(Lowered::Nothing, |ty| Lowered::Alias(cx.lower_type(&ty))), |
| 67 | + Pending::Ctor(_, v) => Lowered::Fields( |
| 68 | + v.fields() |
| 69 | + .iter() |
| 70 | + .map(|f| FieldDef { |
| 71 | + label: f.name().map(|n| n.text()), |
| 72 | + ty: cx.lower_opt_type(f.ty(), f.syntax().text_range()), |
| 73 | + }) |
| 74 | + .collect(), |
| 75 | + ), |
| 76 | + Pending::Fn(_, f) => { |
| 77 | + let sig = cx.lower_sig( |
| 78 | + f.param_list(), |
| 79 | + f.ret_type(), |
| 80 | + f.where_clause(), |
| 81 | + f.syntax().text_range(), |
| 82 | + ); |
| 83 | + let DefKind::Fn(fn_def) = &def.kind else { |
| 84 | + unreachable!() |
| 85 | + }; |
| 86 | + let is_extern = def.has_attr("extern"); |
| 87 | + let in_impl = fn_def |
| 88 | + .owner |
| 89 | + .is_some_and(|o| matches!(hir.defs[o].kind, DefKind::Impl(_))); |
| 90 | + let needs_signature = (def.is_pub || is_extern || fn_def.owner.is_some()) && !in_impl; |
| 91 | + if needs_signature { |
| 92 | + cx.require_annotations( |
| 93 | + &def.name, |
| 94 | + &sig, |
| 95 | + def.span.range, |
| 96 | + describe_fn(def, fn_def, hir), |
| 97 | + ); |
| 98 | + } |
| 99 | + let body = f.body().map(|b| { |
| 100 | + let mut bl = BodyLowerer::new(&mut cx); |
| 101 | + bl.lower_fn_body(f.param_list(), &b); |
| 102 | + bl.body |
| 103 | + }); |
| 104 | + Lowered::Fn(sig, body) |
| 105 | + } |
| 106 | + Pending::Impl(_, i) => { |
| 107 | + let target = cx.lower_opt_type(i.target(), i.syntax().text_range()); |
| 108 | + let constraints = i |
| 109 | + .where_clause() |
| 110 | + .map(|w| w.constraints().map(|c| cx.lower_type(&c)).collect()) |
| 111 | + .unwrap_or_default(); |
| 112 | + Lowered::Impl(target, constraints) |
| 113 | + } |
| 114 | + Pending::Op(_, op) => { |
| 115 | + let sig = cx.lower_sig( |
| 116 | + op.param_list(), |
| 117 | + op.ret_type(), |
| 118 | + None, |
| 119 | + op.syntax().text_range(), |
| 120 | + ); |
| 121 | + cx.require_annotations(&def.name, &sig, def.span.range, "effect operation"); |
| 122 | + Lowered::Op(sig) |
| 123 | + } |
| 124 | + }; |
| 125 | + (id, lowered) |
| 126 | +} |
| 127 | + |
| 128 | +fn describe_fn(def: &DefData, f: &FnDef, hir: &Hir) -> &'static str { |
| 129 | + match f.owner.map(|o| &hir.defs[o].kind) { |
| 130 | + Some(DefKind::Trait(_)) => "trait method", |
| 131 | + _ if def.has_attr("extern") => "extern function", |
| 132 | + _ => "public function", |
| 133 | + } |
| 134 | +} |
| 135 | + |
| 136 | +/// Lowering context for one item. |
| 137 | +struct Cx<'a, 'd> { |
| 138 | + hir: &'a Hir, |
| 139 | + module: ModuleId, |
| 140 | + file: FileId, |
| 141 | + diags: &'d mut Vec<Diagnostic>, |
| 142 | +} |
| 143 | + |
| 144 | +impl Cx<'_, '_> { |
| 145 | + fn span(&self, range: TextRange) -> Span { |
| 146 | + Span { |
| 147 | + file: self.file, |
| 148 | + range, |
| 149 | + } |
| 150 | + } |
| 151 | + |
| 152 | + fn error(&mut self, code: &'static str, message: impl Into<String>, range: TextRange) { |
| 153 | + let span = self.span(range); |
| 154 | + self.diags.push(Diagnostic::error(code, message, span)); |
| 155 | + } |
| 156 | + |
| 157 | + fn lower_opt_type(&mut self, ty: Option<ast::Type>, fallback: TextRange) -> TypeRef { |
| 158 | + match ty { |
| 159 | + Some(ty) => self.lower_type(&ty), |
| 160 | + None => TypeRef::Error { span: fallback }, |
| 161 | + } |
| 162 | + } |
| 163 | + |
| 164 | + fn lower_type(&mut self, ty: &ast::Type) -> TypeRef { |
| 165 | + let span = ty.syntax().text_range(); |
| 166 | + match ty { |
| 167 | + ast::Type::PathType(p) => { |
| 168 | + let segments: Vec<_> = p.segments().collect(); |
| 169 | + let args = p.type_args().iter().map(|a| self.lower_type(a)).collect(); |
| 170 | + match self.resolve_type_path(&segments, span) { |
| 171 | + Some(TypeRef::Var { name, span }) => TypeRef::Var { name, span }, |
| 172 | + Some(TypeRef::Def { def, .. }) => TypeRef::Def { def, args, span }, |
| 173 | + _ => TypeRef::Error { span }, |
| 174 | + } |
| 175 | + } |
| 176 | + ast::Type::FnType(f) => { |
| 177 | + let params = f.params().map(|t| self.lower_type(&t)).collect(); |
| 178 | + let ret = f.ret_type(); |
| 179 | + let ret_ty = self.lower_opt_type(ret.as_ref().and_then(|r| r.ty()), span); |
| 180 | + let effects = ret |
| 181 | + .and_then(|r| r.effect_row()) |
| 182 | + .map(|row| self.lower_effect_row(&row)); |
| 183 | + TypeRef::Fn { |
| 184 | + params, |
| 185 | + ret: Box::new(ret_ty), |
| 186 | + effects, |
| 187 | + span, |
| 188 | + } |
| 189 | + } |
| 190 | + ast::Type::TupleType(t) => TypeRef::Tuple { |
| 191 | + elems: t.types().map(|t| self.lower_type(&t)).collect(), |
| 192 | + span, |
| 193 | + }, |
| 194 | + } |
| 195 | + } |
| 196 | + |
| 197 | + /// Resolve `Name`, `module.Name` or a type variable `a`. Returns `None` |
| 198 | + /// after reporting an error. |
| 199 | + fn resolve_type_path(&mut self, segments: &[ast::NameRef], span: TextRange) -> Option<TypeRef> { |
| 200 | + match segments { |
| 201 | + [single] => { |
| 202 | + let name = single.text(); |
| 203 | + if let Some(def) = self.hir.lookup_type(self.module, &name) { |
| 204 | + return Some(TypeRef::Def { |
| 205 | + def, |
| 206 | + args: Vec::new(), |
| 207 | + span, |
| 208 | + }); |
| 209 | + } |
| 210 | + if name.starts_with(|c: char| c.is_lowercase() || c == '_') { |
| 211 | + return Some(TypeRef::Var { name, span }); |
| 212 | + } |
| 213 | + self.error( |
| 214 | + codes::UNRESOLVED_TYPE, |
| 215 | + format!("no type, trait or effect named `{name}` is in scope"), |
| 216 | + span, |
| 217 | + ); |
| 218 | + None |
| 219 | + } |
| 220 | + [module, name] => { |
| 221 | + let (module_name, name) = (module.text(), name.text()); |
| 222 | + let Some(target) = self.hir.lookup_module(self.module, &module_name) else { |
| 223 | + self.error( |
| 224 | + codes::UNRESOLVED_MODULE, |
| 225 | + format!("no module `{module_name}` is imported"), |
| 226 | + span, |
| 227 | + ); |
| 228 | + return None; |
| 229 | + }; |
| 230 | + match self.hir.exports[target.index()].types.get(&name) { |
| 231 | + Some(&def) => Some(TypeRef::Def { |
| 232 | + def, |
| 233 | + args: Vec::new(), |
| 234 | + span, |
| 235 | + }), |
| 236 | + None => { |
| 237 | + let path = &self.hir.modules[target].path; |
| 238 | + let msg = if self.hir.scopes[target.index()].types.contains_key(&name) { |
| 239 | + format!("`{name}` is private to `{path}`") |
| 240 | + } else { |
| 241 | + format!("`{path}` has no type, trait or effect named `{name}`") |
| 242 | + }; |
| 243 | + self.error(codes::UNRESOLVED_TYPE, msg, span); |
| 244 | + None |
| 245 | + } |
| 246 | + } |
| 247 | + } |
| 248 | + _ => { |
| 249 | + self.error( |
| 250 | + codes::UNRESOLVED_TYPE, |
| 251 | + "type paths have at most one module qualifier", |
| 252 | + span, |
| 253 | + ); |
| 254 | + None |
| 255 | + } |
| 256 | + } |
| 257 | + } |
| 258 | + |
| 259 | + fn lower_effect_row(&mut self, row: &ast::EffectRow) -> EffectRowRef { |
| 260 | + let labels = row.labels().iter().map(|l| self.lower_type(l)).collect(); |
| 261 | + let tail = row.tail().map(|t| Box::new(self.lower_type(&t))); |
| 262 | + EffectRowRef { |
| 263 | + labels, |
| 264 | + tail, |
| 265 | + span: row.syntax().text_range(), |
| 266 | + } |
| 267 | + } |
| 268 | + |
| 269 | + fn lower_sig( |
| 270 | + &mut self, |
| 271 | + params: Option<ast::ParamList>, |
| 272 | + ret: Option<ast::RetType>, |
| 273 | + where_clause: Option<ast::WhereClause>, |
| 274 | + item_range: TextRange, |
| 275 | + ) -> FnSig { |
| 276 | + let params = params |
| 277 | + .map(|list| { |
| 278 | + list.params() |
| 279 | + .map(|p| { |
| 280 | + let name = match p.pat() { |
| 281 | + Some(ast::Pat::BindPat(b)) => { |
| 282 | + b.name().map(|n| n.text()).unwrap_or_default() |
| 283 | + } |
| 284 | + _ => "_".to_owned(), |
| 285 | + }; |
| 286 | + Param { |
| 287 | + name, |
| 288 | + ty: p.ty().map(|t| self.lower_type(&t)), |
| 289 | + span: p.syntax().text_range(), |
| 290 | + } |
| 291 | + }) |
| 292 | + .collect() |
| 293 | + }) |
| 294 | + .unwrap_or_default(); |
| 295 | + let ret_span = ret |
| 296 | + .as_ref() |
| 297 | + .map(|r| r.syntax().text_range()) |
| 298 | + .or(Some(item_range)); |
| 299 | + FnSig { |
| 300 | + params, |
| 301 | + ret: ret |
| 302 | + .as_ref() |
| 303 | + .and_then(|r| r.ty()) |
| 304 | + .map(|t| self.lower_type(&t)), |
| 305 | + effects: ret |
| 306 | + .and_then(|r| r.effect_row()) |
| 307 | + .map(|row| self.lower_effect_row(&row)), |
| 308 | + constraints: where_clause |
| 309 | + .map(|w| w.constraints().map(|c| self.lower_type(&c)).collect()) |
| 310 | + .unwrap_or_default(), |
| 311 | + ret_span, |
| 312 | + } |
| 313 | + } |
| 314 | + |
| 315 | + /// Public functions, externs, trait methods and effect operations need |
| 316 | + /// complete signatures (ADR 0001): their types form module interfaces. |
| 317 | + fn require_annotations(&mut self, name: &str, sig: &FnSig, name_range: TextRange, what: &str) { |
| 318 | + for p in &sig.params { |
| 319 | + if p.ty.is_none() { |
| 320 | + self.error( |
| 321 | + codes::MISSING_ANNOTATION, |
| 322 | + format!("{what} `{name}` needs a type for parameter `{}`", p.name), |
| 323 | + p.span, |
| 324 | + ); |
| 325 | + } |
| 326 | + } |
| 327 | + if sig.ret.is_none() { |
| 328 | + let range = sig.ret_span.unwrap_or(name_range); |
| 329 | + let span = self.span(range); |
| 330 | + self.diags.push( |
| 331 | + Diagnostic::error( |
| 332 | + codes::MISSING_ANNOTATION, |
| 333 | + format!("{what} `{name}` needs a return type"), |
| 334 | + span, |
| 335 | + ) |
| 336 | + .with_note("write `-> T`, and `/ <effects>` if it performs any"), |
| 337 | + ); |
| 338 | + } |
| 339 | + } |
| 340 | +} |
| 341 | + |
| 342 | +/// Lowers one function body: expressions, patterns and local scopes. |
| 343 | +struct BodyLowerer<'c, 'a, 'd> { |
| 344 | + cx: &'c mut Cx<'a, 'd>, |
| 345 | + body: Body, |
| 346 | + /// Innermost scope last. |
| 347 | + scopes: Vec<HashMap<String, LocalId>>, |
| 348 | + /// Names bound by the pattern being lowered (to detect duplicates and |
| 349 | + /// make every alternative of an or-pattern bind the same names). |
| 350 | + pattern_bindings: Option<PatternBindings>, |
| 351 | + reported_html: bool, |
| 352 | +} |
| 353 | + |
| 354 | +#[derive(Default)] |
| 355 | +struct PatternBindings { |
| 356 | + /// Names bound so far, with their locals. |
| 357 | + bound: HashMap<String, LocalId>, |
| 358 | + /// While lowering a non-first alternative: the names it must bind. |
| 359 | + expected: Option<HashMap<String, LocalId>>, |
| 360 | + /// Names bound by the current alternative (for completeness checks). |
| 361 | + in_alternative: Vec<String>, |
| 362 | +} |
| 363 | + |
| 364 | +impl<'c, 'a, 'd> BodyLowerer<'c, 'a, 'd> { |
| 365 | + fn new(cx: &'c mut Cx<'a, 'd>) -> Self { |
| 366 | + BodyLowerer { |
| 367 | + cx, |
| 368 | + body: Body::default(), |
| 369 | + scopes: vec![HashMap::new()], |
| 370 | + pattern_bindings: None, |
| 371 | + reported_html: false, |
| 372 | + } |
| 373 | + } |
| 374 | + |
| 375 | + fn alloc_expr(&mut self, expr: Expr, range: TextRange) -> ExprId { |
| 376 | + self.body.expr_spans.push(range); |
| 377 | + self.body.exprs.alloc(expr) |
| 378 | + } |
| 379 | + |
| 380 | + fn alloc_pat(&mut self, pat: Pat, range: TextRange) -> PatId { |
| 381 | + self.body.pat_spans.push(range); |
| 382 | + self.body.pats.alloc(pat) |
| 383 | + } |
| 384 | + |
| 385 | + fn missing(&mut self, range: TextRange) -> ExprId { |
| 386 | + self.alloc_expr(Expr::Missing, range) |
| 387 | + } |
| 388 | + |
| 389 | + fn lookup_local(&self, name: &str) -> Option<LocalId> { |
| 390 | + self.scopes.iter().rev().find_map(|s| s.get(name).copied()) |
| 391 | + } |
| 392 | + |
| 393 | + fn with_scope<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T { |
| 394 | + self.scopes.push(HashMap::new()); |
| 395 | + let result = f(self); |
| 396 | + self.scopes.pop(); |
| 397 | + result |
| 398 | + } |
| 399 | + |
| 400 | + fn bind(&mut self, name: String, range: TextRange) -> LocalId { |
| 401 | + let local = self.body.locals.alloc(Local { |
| 402 | + name: name.clone(), |
| 403 | + span: range, |
| 404 | + }); |
| 405 | + self.scopes |
| 406 | + .last_mut() |
| 407 | + .expect("a scope is always open") |
| 408 | + .insert(name, local); |
| 409 | + local |
| 410 | + } |
| 411 | + |
| 412 | + fn lower_fn_body(&mut self, params: Option<ast::ParamList>, block: &ast::Block) { |
| 413 | + if let Some(params) = params { |
| 414 | + for p in params.params() { |
| 415 | + let pat = self.lower_top_pat(p.pat(), p.syntax().text_range()); |
| 416 | + self.body.params.push(pat); |
| 417 | + } |
| 418 | + } |
| 419 | + let root = self.lower_block(block); |
| 420 | + self.body.root = Some(root); |
| 421 | + } |
| 422 | + |
| 423 | + // ---- expressions ----------------------------------------------------- |
| 424 | + |
| 425 | + fn lower_opt_expr(&mut self, expr: Option<ast::Expr>, fallback: TextRange) -> ExprId { |
| 426 | + match expr { |
| 427 | + Some(e) => self.lower_expr(&e), |
| 428 | + None => self.missing(fallback), |
| 429 | + } |
| 430 | + } |
| 431 | + |
| 432 | + fn lower_expr(&mut self, expr: &ast::Expr) -> ExprId { |
| 433 | + let range = expr.syntax().text_range(); |
| 434 | + match expr { |
| 435 | + ast::Expr::Literal(lit) => { |
| 436 | + let lowered = lit.token().and_then(|t| self.lower_literal(&t, false)); |
| 437 | + match lowered { |
| 438 | + Some(lit) => self.alloc_expr(Expr::Lit(lit), range), |
| 439 | + None => self.missing(range), |
| 440 | + } |
| 441 | + } |
| 442 | + ast::Expr::PathExpr(p) => { |
| 443 | + let name = p.name_ref().map(|n| n.text()).unwrap_or_default(); |
| 444 | + self.resolve_value(&name, range) |
| 445 | + } |
| 446 | + ast::Expr::FieldExpr(f) => self.lower_field(f, range), |
| 447 | + ast::Expr::ParenExpr(p) => self.lower_opt_expr(p.expr(), range), |
| 448 | + ast::Expr::TupleExpr(t) => { |
| 449 | + let elems = t.exprs().map(|e| self.lower_expr(&e)).collect(); |
| 450 | + self.alloc_expr(Expr::Tuple(elems), range) |
| 451 | + } |
| 452 | + ast::Expr::ListExpr(l) => { |
| 453 | + let elems = l.elements().map(|e| self.lower_expr(&e)).collect(); |
| 454 | + let tail = l |
| 455 | + .spread() |
| 456 | + .map(|s| self.lower_opt_expr(s.expr(), s.syntax().text_range())); |
| 457 | + self.alloc_expr(Expr::List { elems, tail }, range) |
| 458 | + } |
| 459 | + ast::Expr::Block(b) => self.lower_block(b), |
| 460 | + ast::Expr::BinExpr(b) => self.lower_binary(b, range), |
| 461 | + ast::Expr::PrefixExpr(p) => self.lower_prefix(p, range), |
| 462 | + ast::Expr::CallExpr(c) => { |
| 463 | + let callee = self.lower_opt_expr(c.callee(), range); |
| 464 | + let (args, spread) = self.lower_args(c.args()); |
| 465 | + self.alloc_expr( |
| 466 | + Expr::Call { |
| 467 | + callee, |
| 468 | + args, |
| 469 | + spread, |
| 470 | + }, |
| 471 | + range, |
| 472 | + ) |
| 473 | + } |
| 474 | + ast::Expr::IfExpr(i) => { |
| 475 | + let cond = self.lower_opt_expr(i.condition(), range); |
| 476 | + let then_branch = match i.then_branch() { |
| 477 | + Some(b) => self.lower_block(&b), |
| 478 | + None => self.missing(range), |
| 479 | + }; |
| 480 | + let else_branch = i |
| 481 | + .else_branch() |
| 482 | + .map(|e| self.lower_opt_expr(e.expr(), e.syntax().text_range())); |
| 483 | + self.alloc_expr( |
| 484 | + Expr::If { |
| 485 | + cond, |
| 486 | + then_branch, |
| 487 | + else_branch, |
| 488 | + }, |
| 489 | + range, |
| 490 | + ) |
| 491 | + } |
| 492 | + ast::Expr::MatchExpr(m) => { |
| 493 | + let scrutinee = self.lower_opt_expr(m.scrutinee(), range); |
| 494 | + let arms = m |
| 495 | + .arms() |
| 496 | + .map(|arm| { |
| 497 | + self.with_scope(|this| { |
| 498 | + let pat = this.lower_top_pat(arm.pat(), arm.syntax().text_range()); |
| 499 | + let guard = arm.guard().map(|g| this.lower_expr(&g)); |
| 500 | + let body = this.lower_opt_expr(arm.body(), arm.syntax().text_range()); |
| 501 | + MatchArm { pat, guard, body } |
| 502 | + }) |
| 503 | + }) |
| 504 | + .collect(); |
| 505 | + self.alloc_expr(Expr::Match { scrutinee, arms }, range) |
| 506 | + } |
| 507 | + ast::Expr::LambdaExpr(l) => self.with_scope(|this| { |
| 508 | + let params = l |
| 509 | + .param_list() |
| 510 | + .map(|list| { |
| 511 | + list.params() |
| 512 | + .map(|p| { |
| 513 | + let ty = p.ty().map(|t| this.cx.lower_type(&t)); |
| 514 | + (this.lower_top_pat(p.pat(), p.syntax().text_range()), ty) |
| 515 | + }) |
| 516 | + .collect() |
| 517 | + }) |
| 518 | + .unwrap_or_default(); |
| 519 | + let ret = l |
| 520 | + .ret_type() |
| 521 | + .and_then(|r| r.ty()) |
| 522 | + .map(|t| this.cx.lower_type(&t)); |
| 523 | + let body = match l.body() { |
| 524 | + Some(b) => this.lower_block(&b), |
| 525 | + None => this.missing(range), |
| 526 | + }; |
| 527 | + this.alloc_expr(Expr::Lambda { params, ret, body }, range) |
| 528 | + }), |
| 529 | + ast::Expr::HandleExpr(h) => self.lower_handle(h, range), |
| 530 | + ast::Expr::HtmlElement(el) => { |
| 531 | + if !self.reported_html { |
| 532 | + self.reported_html = true; |
| 533 | + let span = self.cx.span(range); |
| 534 | + self.cx.diags.push(Diagnostic::warning( |
| 535 | + codes::HTML_NOT_CHECKED, |
| 536 | + "inline HTML is parsed but not type-checked yet (milestone M8)", |
| 537 | + span, |
| 538 | + )); |
| 539 | + } |
| 540 | + let mut holes = Vec::new(); |
| 541 | + self.lower_html_holes(el, &mut holes); |
| 542 | + self.alloc_expr(Expr::Html { holes }, range) |
| 543 | + } |
| 544 | + } |
| 545 | + } |
| 546 | + |
| 547 | + fn lower_html_holes(&mut self, el: &ast::HtmlElement, holes: &mut Vec<ExprId>) { |
| 548 | + if let Some(open) = el.open_tag() { |
| 549 | + for attr in open.attrs() { |
| 550 | + if let Some(e) = attr.expr_value().and_then(|v| v.expr()) { |
| 551 | + holes.push(self.lower_expr(&e)); |
| 552 | + } |
| 553 | + } |
| 554 | + } |
| 555 | + for child in el.children() { |
| 556 | + match child { |
| 557 | + ast::HtmlChild::HtmlElement(inner) => self.lower_html_holes(&inner, holes), |
| 558 | + ast::HtmlChild::HtmlExpr(hole) => { |
| 559 | + if let Some(e) = hole.expr() { |
| 560 | + holes.push(self.lower_expr(&e)); |
| 561 | + } |
| 562 | + } |
| 563 | + } |
| 564 | + } |
| 565 | + } |
| 566 | + |
| 567 | + /// A name in expression position: local, then item (own, imported, |
| 568 | + /// prelude). |
| 569 | + fn resolve_value(&mut self, name: &str, range: TextRange) -> ExprId { |
| 570 | + if let Some(local) = self.lookup_local(name) { |
| 571 | + return self.alloc_expr(Expr::Local(local), range); |
| 572 | + } |
| 573 | + if let Some(def) = self.cx.hir.lookup_value(self.cx.module, name) { |
| 574 | + return self.alloc_expr(Expr::Def(def), range); |
| 575 | + } |
| 576 | + if self.cx.hir.lookup_module(self.cx.module, name).is_some() { |
| 577 | + self.cx.error( |
| 578 | + codes::NOT_A_VALUE, |
| 579 | + format!("`{name}` is a module, not a value; write `{name}.item`"), |
| 580 | + range, |
| 581 | + ); |
| 582 | + } else if self.cx.hir.lookup_type(self.cx.module, name).is_some() { |
| 583 | + self.cx.error( |
| 584 | + codes::NOT_A_VALUE, |
| 585 | + format!("`{name}` is a type, trait or effect, not a value"), |
| 586 | + range, |
| 587 | + ); |
| 588 | + } else { |
| 589 | + self.cx.error( |
| 590 | + codes::UNRESOLVED_NAME, |
| 591 | + format!("no value named `{name}` is in scope"), |
| 592 | + range, |
| 593 | + ); |
| 594 | + } |
| 595 | + self.missing(range) |
| 596 | + } |
| 597 | + |
| 598 | + /// `module.item` (when `module` names an import and is not shadowed by |
| 599 | + /// a local) or a record field / tuple index. |
| 600 | + fn lower_field(&mut self, f: &ast::FieldExpr, range: TextRange) -> ExprId { |
| 601 | + if let Some(ast::Expr::PathExpr(base)) = f.base() { |
| 602 | + let base_name = base.name_ref().map(|n| n.text()).unwrap_or_default(); |
| 603 | + let module = self.cx.hir.lookup_module(self.cx.module, &base_name); |
| 604 | + if let (Some(module), None, Some(field)) = |
| 605 | + (module, self.lookup_local(&base_name), f.field()) |
| 606 | + { |
| 607 | + let name = field.text(); |
| 608 | + return match self.cx.hir.exports[module.index()].values.get(&name) { |
| 609 | + Some(&def) => self.alloc_expr(Expr::Def(def), range), |
| 610 | + None => { |
| 611 | + let path = &self.cx.hir.modules[module].path; |
| 612 | + let msg = if self.cx.hir.scopes[module.index()] |
| 613 | + .values |
| 614 | + .contains_key(&name) |
| 615 | + { |
| 616 | + ( |
| 617 | + codes::PRIVATE_ITEM, |
| 618 | + format!("`{name}` is private to `{path}`"), |
| 619 | + ) |
| 620 | + } else { |
| 621 | + ( |
| 622 | + codes::UNRESOLVED_NAME, |
| 623 | + format!("`{path}` has no value named `{name}`"), |
| 624 | + ) |
| 625 | + }; |
| 626 | + self.cx.error(msg.0, msg.1, field.syntax().text_range()); |
| 627 | + self.missing(range) |
| 628 | + } |
| 629 | + }; |
| 630 | + } |
| 631 | + } |
| 632 | + let base = self.lower_opt_expr(f.base(), range); |
| 633 | + if let Some(index) = f.index() { |
| 634 | + return match index.text().parse::<u32>() { |
| 635 | + Ok(index) => self.alloc_expr(Expr::TupleIndex { base, index }, range), |
| 636 | + Err(_) => { |
| 637 | + self.cx.error( |
| 638 | + codes::INT_OUT_OF_RANGE, |
| 639 | + "tuple index is too large", |
| 640 | + index.text_range(), |
| 641 | + ); |
| 642 | + self.missing(range) |
| 643 | + } |
| 644 | + }; |
| 645 | + } |
| 646 | + match f.field() { |
| 647 | + Some(name) => self.alloc_expr( |
| 648 | + Expr::Field { |
| 649 | + base, |
| 650 | + name: name.text(), |
| 651 | + }, |
| 652 | + range, |
| 653 | + ), |
| 654 | + None => self.missing(range), |
| 655 | + } |
| 656 | + } |
| 657 | + |
| 658 | + fn lower_args(&mut self, args: Vec<ast::ArgOrSpread>) -> (Vec<Arg>, Option<ExprId>) { |
| 659 | + let mut lowered = Vec::new(); |
| 660 | + let mut spread = None; |
| 661 | + for arg in args { |
| 662 | + match arg { |
| 663 | + ast::ArgOrSpread::Arg(a) => { |
| 664 | + let expr = self.lower_opt_expr(a.expr(), a.syntax().text_range()); |
| 665 | + lowered.push(Arg { |
| 666 | + label: a.label().map(|l| l.text()), |
| 667 | + expr, |
| 668 | + }); |
| 669 | + } |
| 670 | + ast::ArgOrSpread::Spread(s) => { |
| 671 | + spread = Some(self.lower_opt_expr(s.expr(), s.syntax().text_range())) |
| 672 | + } |
| 673 | + } |
| 674 | + } |
| 675 | + (lowered, spread) |
| 676 | + } |
| 677 | + |
| 678 | + fn lower_binary(&mut self, b: &ast::BinExpr, range: TextRange) -> ExprId { |
| 679 | + let Some(op) = b.op() else { |
| 680 | + return self.missing(range); |
| 681 | + }; |
| 682 | + let lhs = self.lower_opt_expr(b.lhs(), range); |
| 683 | + if op.kind() == SyntaxKind::PIPE_GT { |
| 684 | + return self.lower_pipe(lhs, b.rhs(), range); |
| 685 | + } |
| 686 | + let rhs = self.lower_opt_expr(b.rhs(), range); |
| 687 | + let op = match op.kind() { |
| 688 | + SyntaxKind::PIPE2 => BinOp::Or, |
| 689 | + SyntaxKind::AMP2 => BinOp::And, |
| 690 | + SyntaxKind::EQ2 => BinOp::Eq, |
| 691 | + SyntaxKind::NEQ => BinOp::Ne, |
| 692 | + SyntaxKind::LT => BinOp::Lt, |
| 693 | + SyntaxKind::GT => BinOp::Gt, |
| 694 | + SyntaxKind::LTEQ => BinOp::Le, |
| 695 | + SyntaxKind::GTEQ => BinOp::Ge, |
| 696 | + SyntaxKind::LT_GT => BinOp::Concat, |
| 697 | + SyntaxKind::PLUS => BinOp::Add, |
| 698 | + SyntaxKind::MINUS => BinOp::Sub, |
| 699 | + SyntaxKind::STAR => BinOp::Mul, |
| 700 | + SyntaxKind::SLASH => BinOp::Div, |
| 701 | + SyntaxKind::PERCENT => BinOp::Rem, |
| 702 | + _ => return self.missing(range), |
| 703 | + }; |
| 704 | + self.alloc_expr(Expr::Binary { op, lhs, rhs }, range) |
| 705 | + } |
| 706 | + |
| 707 | + /// `x |> f(a)` is `f(x, a)`; `x |> f` is `f(x)` (Gleam semantics). |
| 708 | + fn lower_pipe(&mut self, lhs: ExprId, rhs: Option<ast::Expr>, range: TextRange) -> ExprId { |
| 709 | + let lhs_arg = Arg { |
| 710 | + label: None, |
| 711 | + expr: lhs, |
| 712 | + }; |
| 713 | + match rhs { |
| 714 | + Some(ast::Expr::CallExpr(call)) => { |
| 715 | + let callee = self.lower_opt_expr(call.callee(), range); |
| 716 | + let (rest, spread) = self.lower_args(call.args()); |
| 717 | + let args = std::iter::once(lhs_arg).chain(rest).collect(); |
| 718 | + self.alloc_expr( |
| 719 | + Expr::Call { |
| 720 | + callee, |
| 721 | + args, |
| 722 | + spread, |
| 723 | + }, |
| 724 | + range, |
| 725 | + ) |
| 726 | + } |
| 727 | + other => { |
| 728 | + let callee = self.lower_opt_expr(other, range); |
| 729 | + self.alloc_expr( |
| 730 | + Expr::Call { |
| 731 | + callee, |
| 732 | + args: vec![lhs_arg], |
| 733 | + spread: None, |
| 734 | + }, |
| 735 | + range, |
| 736 | + ) |
| 737 | + } |
| 738 | + } |
| 739 | + } |
| 740 | + |
| 741 | + fn lower_prefix(&mut self, p: &ast::PrefixExpr, range: TextRange) -> ExprId { |
| 742 | + let negate = p.op().is_some_and(|t| t.kind() == SyntaxKind::MINUS); |
| 743 | + // Fold `-<literal>` so the most negative Int is expressible. |
| 744 | + if let (true, Some(ast::Expr::Literal(lit))) = (negate, p.expr()) |
| 745 | + && let Some(tok) = lit |
| 746 | + .token() |
| 747 | + .filter(|t| matches!(t.kind(), SyntaxKind::INT | SyntaxKind::FLOAT)) |
| 748 | + { |
| 749 | + return match self.lower_literal(&tok, true) { |
| 750 | + Some(lit) => self.alloc_expr(Expr::Lit(lit), range), |
| 751 | + None => self.missing(range), |
| 752 | + }; |
| 753 | + } |
| 754 | + let expr = self.lower_opt_expr(p.expr(), range); |
| 755 | + let op = if negate { UnOp::Neg } else { UnOp::Not }; |
| 756 | + self.alloc_expr(Expr::Unary { op, expr }, range) |
| 757 | + } |
| 758 | + |
| 759 | + fn lower_handle(&mut self, h: &ast::HandleExpr, range: TextRange) -> ExprId { |
| 760 | + let body = match h.body() { |
| 761 | + Some(b) => self.lower_block(&b), |
| 762 | + None => self.missing(range), |
| 763 | + }; |
| 764 | + let mut clauses = Vec::new(); |
| 765 | + for clause in h.clauses() { |
| 766 | + let clause_range = clause.syntax().text_range(); |
| 767 | + let name = clause.op().map(|n| n.text()).unwrap_or_default(); |
| 768 | + let is_return = name == "return"; |
| 769 | + let op = if is_return { |
| 770 | + None |
| 771 | + } else { |
| 772 | + match self.cx.hir.lookup_value(self.cx.module, &name) { |
| 773 | + Some(def) if matches!(self.cx.hir.defs[def].kind, DefKind::Op(_)) => Some(def), |
| 774 | + Some(_) => { |
| 775 | + self.cx.error( |
| 776 | + codes::INVALID_HANDLER, |
| 777 | + format!("`{name}` is not an effect operation"), |
| 778 | + clause_range, |
| 779 | + ); |
| 780 | + None |
| 781 | + } |
| 782 | + None => { |
| 783 | + self.cx.error( |
| 784 | + codes::UNRESOLVED_NAME, |
| 785 | + format!("no effect operation named `{name}` is in scope"), |
| 786 | + clause_range, |
| 787 | + ); |
| 788 | + None |
| 789 | + } |
| 790 | + } |
| 791 | + }; |
| 792 | + let lowered = self.with_scope(|this| { |
| 793 | + let params: Vec<_> = clause |
| 794 | + .param_list() |
| 795 | + .map(|list| { |
| 796 | + list.params() |
| 797 | + .map(|p| this.lower_top_pat(p.pat(), p.syntax().text_range())) |
| 798 | + .collect() |
| 799 | + }) |
| 800 | + .unwrap_or_default(); |
| 801 | + let resume = (!is_return).then(|| this.bind("resume".to_owned(), clause_range)); |
| 802 | + let body = this.lower_opt_expr(clause.body(), clause_range); |
| 803 | + HandlerClause { |
| 804 | + op, |
| 805 | + is_return, |
| 806 | + params, |
| 807 | + resume, |
| 808 | + body, |
| 809 | + span: clause_range, |
| 810 | + } |
| 811 | + }); |
| 812 | + clauses.push(lowered); |
| 813 | + } |
| 814 | + self.alloc_expr(Expr::Handle { body, clauses }, range) |
| 815 | + } |
| 816 | + |
| 817 | + /// A block; `use` turns the statements after it into a callback. |
| 818 | + fn lower_block(&mut self, block: &ast::Block) -> ExprId { |
| 819 | + let range = block.syntax().text_range(); |
| 820 | + let stmts: Vec<_> = block.stmts().collect(); |
| 821 | + self.with_scope(|this| this.lower_stmts(&stmts, range)) |
| 822 | + } |
| 823 | + |
| 824 | + fn lower_stmts(&mut self, stmts: &[ast::Stmt], range: TextRange) -> ExprId { |
| 825 | + let mut lowered = Vec::new(); |
| 826 | + let mut tail = None; |
| 827 | + for (i, stmt) in stmts.iter().enumerate() { |
| 828 | + let is_last = i + 1 == stmts.len(); |
| 829 | + match stmt { |
| 830 | + ast::Stmt::LetStmt(l) => { |
| 831 | + let init = self.lower_opt_expr(l.init(), l.syntax().text_range()); |
| 832 | + let ty = l.ty().map(|t| self.cx.lower_type(&t)); |
| 833 | + let pat = self.lower_top_pat(l.pat(), l.syntax().text_range()); |
| 834 | + lowered.push(Stmt::Let { pat, ty, init }); |
| 835 | + } |
| 836 | + ast::Stmt::Expr(e) => { |
| 837 | + let e = self.lower_expr(e); |
| 838 | + if is_last { |
| 839 | + tail = Some(e); |
| 840 | + } else { |
| 841 | + lowered.push(Stmt::Expr(e)); |
| 842 | + } |
| 843 | + } |
| 844 | + ast::Stmt::UseStmt(u) => { |
| 845 | + tail = Some(self.lower_use(u, &stmts[i + 1..], range)); |
| 846 | + break; |
| 847 | + } |
| 848 | + } |
| 849 | + } |
| 850 | + self.alloc_expr( |
| 851 | + Expr::Block { |
| 852 | + stmts: lowered, |
| 853 | + tail, |
| 854 | + }, |
| 855 | + range, |
| 856 | + ) |
| 857 | + } |
| 858 | + |
| 859 | + /// `use a, b <- f(x)` + rest ⇒ `f(x, fn(a, b) { rest })` |
| 860 | + fn lower_use( |
| 861 | + &mut self, |
| 862 | + u: &ast::UseStmt, |
| 863 | + rest: &[ast::Stmt], |
| 864 | + block_range: TextRange, |
| 865 | + ) -> ExprId { |
| 866 | + let use_range = u.syntax().text_range(); |
| 867 | + let callback_range = TextRange::new(use_range.start(), block_range.end()); |
| 868 | + let call = u.call(); |
| 869 | + let (callee, mut args, spread) = match &call { |
| 870 | + Some(ast::Expr::CallExpr(c)) => { |
| 871 | + let callee = self.lower_opt_expr(c.callee(), use_range); |
| 872 | + let (args, spread) = self.lower_args(c.args()); |
| 873 | + (callee, args, spread) |
| 874 | + } |
| 875 | + other => ( |
| 876 | + self.lower_opt_expr(other.clone(), use_range), |
| 877 | + Vec::new(), |
| 878 | + None, |
| 879 | + ), |
| 880 | + }; |
| 881 | + let callback = self.with_scope(|this| { |
| 882 | + let params = u |
| 883 | + .pats() |
| 884 | + .map(|p| { |
| 885 | + ( |
| 886 | + this.lower_top_pat(Some(p.clone()), p.syntax().text_range()), |
| 887 | + None, |
| 888 | + ) |
| 889 | + }) |
| 890 | + .collect(); |
| 891 | + let body = this.lower_stmts(rest, callback_range); |
| 892 | + this.alloc_expr( |
| 893 | + Expr::Lambda { |
| 894 | + params, |
| 895 | + ret: None, |
| 896 | + body, |
| 897 | + }, |
| 898 | + callback_range, |
| 899 | + ) |
| 900 | + }); |
| 901 | + args.push(Arg { |
| 902 | + label: None, |
| 903 | + expr: callback, |
| 904 | + }); |
| 905 | + self.alloc_expr( |
| 906 | + Expr::Call { |
| 907 | + callee, |
| 908 | + args, |
| 909 | + spread, |
| 910 | + }, |
| 911 | + use_range, |
| 912 | + ) |
| 913 | + } |
| 914 | + |
| 915 | + fn lower_literal(&mut self, tok: &SyntaxToken, negative: bool) -> Option<Lit> { |
| 916 | + let text = tok.text(); |
| 917 | + let range = tok.text_range(); |
| 918 | + match tok.kind() { |
| 919 | + SyntaxKind::INT => { |
| 920 | + let digits = text.replace('_', ""); |
| 921 | + let parsed = if let Some(hex) = digits.strip_prefix("0x") { |
| 922 | + i128::from_str_radix(hex, 16) |
| 923 | + } else if let Some(bin) = digits.strip_prefix("0b") { |
| 924 | + i128::from_str_radix(bin, 2) |
| 925 | + } else { |
| 926 | + digits.parse::<i128>() |
| 927 | + }; |
| 928 | + let value = parsed.ok().map(|v| if negative { -v } else { v }); |
| 929 | + // Int is 63-bit (docs/runtime-abi.md). |
| 930 | + match value.filter(|v| (-(1i128 << 62)..(1i128 << 62)).contains(v)) { |
| 931 | + Some(v) => Some(Lit::Int(v as i64)), |
| 932 | + None => { |
| 933 | + self.cx.error( |
| 934 | + codes::INT_OUT_OF_RANGE, |
| 935 | + "integer literal does not fit in Int (63-bit: -2^62 to 2^62-1)", |
| 936 | + range, |
| 937 | + ); |
| 938 | + None |
| 939 | + } |
| 940 | + } |
| 941 | + } |
| 942 | + SyntaxKind::FLOAT => { |
| 943 | + let v: f64 = text.replace('_', "").parse().ok()?; |
| 944 | + Some(Lit::Float(if negative { -v } else { v })) |
| 945 | + } |
| 946 | + SyntaxKind::STRING => self.unescape(text, range).map(Lit::String), |
| 947 | + _ => None, |
| 948 | + } |
| 949 | + } |
| 950 | + |
| 951 | + fn unescape(&mut self, text: &str, range: TextRange) -> Option<String> { |
| 952 | + let inner = text |
| 953 | + .strip_prefix('"') |
| 954 | + .map(|t| t.strip_suffix('"').unwrap_or(t)) |
| 955 | + .unwrap_or(text); |
| 956 | + let mut out = String::with_capacity(inner.len()); |
| 957 | + let mut chars = inner.chars(); |
| 958 | + let mut ok = true; |
| 959 | + while let Some(c) = chars.next() { |
| 960 | + if c != '\\' { |
| 961 | + out.push(c); |
| 962 | + continue; |
| 963 | + } |
| 964 | + match chars.next() { |
| 965 | + Some('n') => out.push('\n'), |
| 966 | + Some('t') => out.push('\t'), |
| 967 | + Some('r') => out.push('\r'), |
| 968 | + Some('0') => out.push('\0'), |
| 969 | + Some('\\') => out.push('\\'), |
| 970 | + Some('"') => out.push('"'), |
| 971 | + Some('u') => { |
| 972 | + let rest: String = chars.by_ref().take_while(|&c| c != '}').collect(); |
| 973 | + match rest |
| 974 | + .strip_prefix('{') |
| 975 | + .and_then(|h| u32::from_str_radix(h, 16).ok()) |
| 976 | + .and_then(char::from_u32) |
| 977 | + { |
| 978 | + Some(c) => out.push(c), |
| 979 | + None => ok = false, |
| 980 | + } |
| 981 | + } |
| 982 | + _ => ok = false, |
| 983 | + } |
| 984 | + } |
| 985 | + if !ok { |
| 986 | + self.cx.error( |
| 987 | + codes::INVALID_ESCAPE, |
| 988 | + "invalid escape sequence; valid ones are \\n \\t \\r \\0 \\\\ \\\" \\u{hex}", |
| 989 | + range, |
| 990 | + ); |
| 991 | + return None; |
| 992 | + } |
| 993 | + Some(out) |
| 994 | + } |
| 995 | + |
| 996 | + // ---- patterns -------------------------------------------------------- |
| 997 | + |
| 998 | + /// A complete pattern (not a sub-pattern): its bindings are checked as |
| 999 | + /// a unit. |
| 1000 | + fn lower_top_pat(&mut self, pat: Option<ast::Pat>, fallback: TextRange) -> PatId { |
| 1001 | + let saved = self.pattern_bindings.replace(PatternBindings::default()); |
| 1002 | + let id = match pat { |
| 1003 | + Some(p) => self.lower_pat(&p), |
| 1004 | + None => self.alloc_pat(Pat::Missing, fallback), |
| 1005 | + }; |
| 1006 | + self.pattern_bindings = saved; |
| 1007 | + id |
| 1008 | + } |
| 1009 | + |
| 1010 | + fn bind_in_pattern(&mut self, name: String, range: TextRange) -> LocalId { |
| 1011 | + let bindings = self |
| 1012 | + .pattern_bindings |
| 1013 | + .get_or_insert_with(PatternBindings::default); |
| 1014 | + if let Some(expected) = &bindings.expected { |
| 1015 | + // A later alternative of an or-pattern: reuse the first one's local. |
| 1016 | + if let Some(&local) = expected.get(&name) { |
| 1017 | + bindings.in_alternative.push(name); |
| 1018 | + return local; |
| 1019 | + } |
| 1020 | + self.cx.error( |
| 1021 | + codes::PATTERN_BINDINGS, |
| 1022 | + format!("`{name}` is not bound in the first alternative of this or-pattern"), |
| 1023 | + range, |
| 1024 | + ); |
| 1025 | + } else if bindings.bound.contains_key(&name) { |
| 1026 | + self.cx.error( |
| 1027 | + codes::PATTERN_BINDINGS, |
| 1028 | + format!("`{name}` is bound more than once in this pattern"), |
| 1029 | + range, |
| 1030 | + ); |
| 1031 | + } |
| 1032 | + let local = self.bind(name.clone(), range); |
| 1033 | + let bindings = self.pattern_bindings.as_mut().expect("set above"); |
| 1034 | + bindings.bound.insert(name.clone(), local); |
| 1035 | + bindings.in_alternative.push(name); |
| 1036 | + local |
| 1037 | + } |
| 1038 | + |
| 1039 | + fn lower_pat(&mut self, pat: &ast::Pat) -> PatId { |
| 1040 | + let range = pat.syntax().text_range(); |
| 1041 | + let lowered = match pat { |
| 1042 | + ast::Pat::WildcardPat(_) => Pat::Wild, |
| 1043 | + ast::Pat::BindPat(b) => match b.name() { |
| 1044 | + Some(name) => Pat::Bind(self.bind_in_pattern(name.text(), range)), |
| 1045 | + None => Pat::Missing, |
| 1046 | + }, |
| 1047 | + ast::Pat::LiteralPat(l) => match l |
| 1048 | + .token() |
| 1049 | + .and_then(|t| self.lower_literal(&t, l.is_negative())) |
| 1050 | + { |
| 1051 | + Some(lit) => Pat::Lit { |
| 1052 | + lit, |
| 1053 | + negative: l.is_negative(), |
| 1054 | + }, |
| 1055 | + None => Pat::Missing, |
| 1056 | + }, |
| 1057 | + ast::Pat::CtorPat(c) => self.lower_ctor_pat(c, range), |
| 1058 | + ast::Pat::TuplePat(t) => Pat::Tuple(t.pats().map(|p| self.lower_pat(&p)).collect()), |
| 1059 | + ast::Pat::ListPat(l) => { |
| 1060 | + let mut elems = Vec::new(); |
| 1061 | + let mut rest = None; |
| 1062 | + for p in l.pats() { |
| 1063 | + if let ast::Pat::RestPat(r) = &p { |
| 1064 | + let r_range = r.syntax().text_range(); |
| 1065 | + if rest.is_some() { |
| 1066 | + self.cx.error( |
| 1067 | + codes::PATTERN_BINDINGS, |
| 1068 | + "a list pattern has at most one `..`", |
| 1069 | + r_range, |
| 1070 | + ); |
| 1071 | + } |
| 1072 | + rest = Some(r.name().map(|n| self.bind_in_pattern(n.text(), r_range))); |
| 1073 | + } else { |
| 1074 | + if rest.is_some() { |
| 1075 | + self.cx.error( |
| 1076 | + codes::PATTERN_BINDINGS, |
| 1077 | + "`..` must come last in a list pattern", |
| 1078 | + p.syntax().text_range(), |
| 1079 | + ); |
| 1080 | + } |
| 1081 | + elems.push(self.lower_pat(&p)); |
| 1082 | + } |
| 1083 | + } |
| 1084 | + Pat::List { elems, rest } |
| 1085 | + } |
| 1086 | + ast::Pat::RestPat(_) => { |
| 1087 | + self.cx.error( |
| 1088 | + codes::PATTERN_BINDINGS, |
| 1089 | + "`..` is only allowed in list and constructor patterns", |
| 1090 | + range, |
| 1091 | + ); |
| 1092 | + Pat::Missing |
| 1093 | + } |
| 1094 | + ast::Pat::AltPat(alt) => self.lower_alternatives(alt), |
| 1095 | + ast::Pat::AsPat(a) => { |
| 1096 | + let inner = match a.pat() { |
| 1097 | + Some(p) => self.lower_pat(&p), |
| 1098 | + None => self.alloc_pat(Pat::Missing, range), |
| 1099 | + }; |
| 1100 | + match a.name() { |
| 1101 | + Some(name) => { |
| 1102 | + let local = self.bind_in_pattern(name.text(), name.syntax().text_range()); |
| 1103 | + Pat::As { pat: inner, local } |
| 1104 | + } |
| 1105 | + None => return inner, |
| 1106 | + } |
| 1107 | + } |
| 1108 | + }; |
| 1109 | + self.alloc_pat(lowered, range) |
| 1110 | + } |
| 1111 | + |
| 1112 | + /// Every alternative must bind the same names, to the same locals. |
| 1113 | + fn lower_alternatives(&mut self, alt: &ast::AltPat) -> Pat { |
| 1114 | + let mut pats = Vec::new(); |
| 1115 | + for (i, p) in alt.alternatives().enumerate() { |
| 1116 | + if i == 1 { |
| 1117 | + let bindings = self |
| 1118 | + .pattern_bindings |
| 1119 | + .get_or_insert_with(PatternBindings::default); |
| 1120 | + bindings.expected = Some(bindings.bound.clone()); |
| 1121 | + } |
| 1122 | + if let Some(b) = self.pattern_bindings.as_mut() { |
| 1123 | + b.in_alternative.clear(); |
| 1124 | + } |
| 1125 | + pats.push(self.lower_pat(&p)); |
| 1126 | + if i >= 1 { |
| 1127 | + let b = self.pattern_bindings.as_ref().expect("set above"); |
| 1128 | + let missing: Vec<_> = b |
| 1129 | + .expected |
| 1130 | + .iter() |
| 1131 | + .flat_map(|e| e.keys()) |
| 1132 | + .filter(|name| !b.in_alternative.contains(name)) |
| 1133 | + .cloned() |
| 1134 | + .collect(); |
| 1135 | + for name in missing { |
| 1136 | + self.cx.error( |
| 1137 | + codes::PATTERN_BINDINGS, |
| 1138 | + format!("`{name}` must be bound in every alternative of this or-pattern"), |
| 1139 | + p.syntax().text_range(), |
| 1140 | + ); |
| 1141 | + } |
| 1142 | + } |
| 1143 | + } |
| 1144 | + if let Some(b) = self.pattern_bindings.as_mut() { |
| 1145 | + b.expected = None; |
| 1146 | + } |
| 1147 | + Pat::Or(pats) |
| 1148 | + } |
| 1149 | + |
| 1150 | + fn lower_ctor_pat(&mut self, c: &ast::CtorPat, range: TextRange) -> Pat { |
| 1151 | + let path: Vec<_> = c.path().collect(); |
| 1152 | + let def = match path.as_slice() { |
| 1153 | + [single] => self.cx.hir.lookup_value(self.cx.module, &single.text()), |
| 1154 | + [module, name] => self |
| 1155 | + .cx |
| 1156 | + .hir |
| 1157 | + .lookup_module(self.cx.module, &module.text()) |
| 1158 | + .and_then(|m| { |
| 1159 | + self.cx.hir.exports[m.index()] |
| 1160 | + .values |
| 1161 | + .get(&name.text()) |
| 1162 | + .copied() |
| 1163 | + }), |
| 1164 | + _ => None, |
| 1165 | + }; |
| 1166 | + let shown = path.iter().map(|n| n.text()).collect::<Vec<_>>().join("."); |
| 1167 | + let args: Vec<PatArg> = c |
| 1168 | + .args() |
| 1169 | + .iter() |
| 1170 | + .map(|a| PatArg { |
| 1171 | + label: a.label().map(|l| l.text()), |
| 1172 | + pat: match a.pat() { |
| 1173 | + Some(p) => self.lower_pat(&p), |
| 1174 | + None => self.alloc_pat(Pat::Missing, a.syntax().text_range()), |
| 1175 | + }, |
| 1176 | + }) |
| 1177 | + .collect(); |
| 1178 | + match def { |
| 1179 | + Some(def) if matches!(self.cx.hir.defs[def].kind, DefKind::Ctor(_)) => Pat::Ctor { |
| 1180 | + def, |
| 1181 | + args, |
| 1182 | + rest: c.has_rest(), |
| 1183 | + }, |
| 1184 | + Some(_) => { |
| 1185 | + self.cx.error( |
| 1186 | + codes::NOT_A_VALUE, |
| 1187 | + format!("`{shown}` is not a constructor"), |
| 1188 | + range, |
| 1189 | + ); |
| 1190 | + Pat::Missing |
| 1191 | + } |
| 1192 | + None => { |
| 1193 | + self.cx.error( |
| 1194 | + codes::UNRESOLVED_NAME, |
| 1195 | + format!("no constructor named `{shown}` is in scope"), |
| 1196 | + range, |
| 1197 | + ); |
| 1198 | + Pat::Missing |
| 1199 | + } |
| 1200 | + } |
| 1201 | + } |
| 1202 | +} |