From 304d82a0a1961e1eb41179f9ebda37d9d9873a1a Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Wed, 2 Apr 2014 09:47:11 -0700 Subject: [PATCH] syntax: Tweak parsing lifetime bounds on closures In summary these are some example transitions this change makes: 'a || => ||: 'a proc:Send() => proc():Send The intended syntax for closures is to put the lifetime bound not at the front but rather in the list of bounds. Currently there is no official support in the AST for bounds that are not 'static, so this case is currently specially handled in the parser to desugar to what the AST is expecting. Additionally, this moves the bounds on procedures to the correct position, which is after the argument list. The current grammar for closures and procedures is: procedure := 'proc' [ '<' lifetime-list '>' ] '(' arg-list ')' [ ':' bound-list ] [ '->' type ] closure := [ 'unsafe' ] ['<' lifetime-list '>' ] '|' arg-list '|' [ ':' bound-list ] [ '->' type ] lifetime-list := lifetime | lifetime ',' lifetime-list arg-list := ident ':' type | ident ':' type ',' arg-list bound-list := bound | bound '+' bound-list bound := path | lifetime This does not currently handle the << ambiguity in `Option<<'a>||>`, I am deferring that to a later patch. Additionally, this removes the support for the obsolete syntaxes of ~fn and &fn. Closes #10553 Closes #10767 Closes #11209 Closes #11210 Closes #11211 --- src/doc/rust.md | 39 ++- src/libsyntax/parse/obsolete.rs | 12 - src/libsyntax/parse/parser.rs | 223 +++++++++--------- ...ure-bounds-static-cant-capture-borrowed.rs | 4 +- src/test/run-pass/closure-syntax.rs | 74 ++++++ src/test/run-pass/issue-10767.rs | 15 ++ src/test/run-pass/once-move-out-on-stack.rs | 2 +- 7 files changed, 242 insertions(+), 127 deletions(-) create mode 100644 src/test/run-pass/closure-syntax.rs create mode 100644 src/test/run-pass/issue-10767.rs diff --git a/src/doc/rust.md b/src/doc/rust.md index 9e211dda2fb40..dc750df3a285d 100644 --- a/src/doc/rust.md +++ b/src/doc/rust.md @@ -3327,8 +3327,21 @@ x = bo(5,7); ### Closure types -The type of a closure mapping an input of type `A` to an output of type `B` is `|A| -> B`. A closure with no arguments or return values has type `||`. +~~~~ {.notrust .ebnf .notation} +closure_type := [ 'unsafe' ] [ '<' lifetime-list '>' ] '|' arg-list '|' + [ ':' bound-list ] [ '->' type ] +procedure_type := 'proc' [ '<' lifetime-list '>' ] '(' arg-list ')' + [ ':' bound-list ] [ '->' type ] +lifetime-list := lifetime | lifetime ',' lifetime-list +arg-list := ident ':' type | ident ':' type ',' arg-list +bound-list := bound | bound '+' bound-list +bound := path | lifetime +~~~~ +The type of a closure mapping an input of type `A` to an output of type `B` is +`|A| -> B`. A closure with no arguments or return values has type `||`. +Similarly, a procedure mapping `A` to `B` is `proc(A) -> B` and a no-argument +and no-return value closure has type `proc()`. An example of creating and calling a closure: @@ -3351,6 +3364,30 @@ call_closure(closure_no_args, closure_args); ``` +Unlike closures, procedures may only be invoked once, but own their +environment, and are allowed to move out of their environment. Procedures are +allocated on the heap (unlike closures). An example of creating and calling a +procedure: + +```rust +let string = ~"Hello"; + +// Creates a new procedure, passing it to the `spawn` function. +spawn(proc() { + println!("{} world!", string); +}) + +// the variable `string` has been moved into the previous procedure, so it is +// no longer usable. + + +// Create an invoke a procedure. Note that the procedure is *moved* when +// invoked, so it cannot be invoked again. +let f = proc(n) { n + 22 }; +println!("answer: {}", f(20)); + +``` + ### Object types Every trait item (see [traits](#traits)) defines a type with the same name as the trait. diff --git a/src/libsyntax/parse/obsolete.rs b/src/libsyntax/parse/obsolete.rs index 63b3fb09ee3cd..d09a002e11765 100644 --- a/src/libsyntax/parse/obsolete.rs +++ b/src/libsyntax/parse/obsolete.rs @@ -36,8 +36,6 @@ pub enum ObsoleteSyntax { ObsoleteEnumWildcard, ObsoleteStructWildcard, ObsoleteVecDotDotWildcard, - ObsoleteBoxedClosure, - ObsoleteClosureType, ObsoleteMultipleImport, ObsoleteManagedPattern, ObsoleteManagedString, @@ -111,16 +109,6 @@ impl<'a> ParserObsoleteMethods for Parser<'a> { "vec slice wildcard", "use `..` instead of `.._` for matching slices" ), - ObsoleteBoxedClosure => ( - "managed or owned closure", - "managed closures have been removed and owned closures are \ - now written `proc()`" - ), - ObsoleteClosureType => ( - "closure type", - "closures are now written `|A| -> B` rather than `&fn(A) -> \ - B`." - ), ObsoleteMultipleImport => ( "multiple imports", "only one import is allowed per `use` statement" diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 83cc92d48284a..8cf0937534748 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -30,7 +30,7 @@ use ast::{ExprMethodCall, ExprParen, ExprPath, ExprProc}; use ast::{ExprRepeat, ExprRet, ExprStruct, ExprTup, ExprUnary}; use ast::{ExprVec, ExprVstore, ExprVstoreSlice}; use ast::{ExprVstoreMutSlice, ExprWhile, ExprForLoop, ExternFn, Field, FnDecl}; -use ast::{ExprVstoreUniq, Onceness, Once, Many}; +use ast::{ExprVstoreUniq, Once, Many}; use ast::{ForeignItem, ForeignItemStatic, ForeignItemFn, ForeignMod}; use ast::{Ident, ImpureFn, Inherited, Item, Item_, ItemStatic}; use ast::{ItemEnum, ItemFn, ItemForeignMod, ItemImpl}; @@ -893,8 +893,44 @@ impl<'a> Parser<'a> { // Parses a procedure type (`proc`). The initial `proc` keyword must // already have been parsed. pub fn parse_proc_type(&mut self) -> Ty_ { - let bounds = self.parse_optional_ty_param_bounds(); - let (decl, lifetimes) = self.parse_ty_fn_decl(false); + /* + + proc <'lt> (S) [:Bounds] -> T + ^~~^ ^~~~^ ^ ^~~~~~~~^ ^ + | | | | | + | | | | Return type + | | | Bounds + | | Argument types + | Lifetimes + the `proc` keyword + + */ + + // NOTE: remove after the next stage0 snap + let (decl, lifetimes, bounds) = if self.token == token::COLON { + let (_, bounds) = self.parse_optional_ty_param_bounds(false); + let (decl, lifetimes) = self.parse_ty_fn_decl(false); + (decl, lifetimes, bounds) + } else { + let lifetimes = if self.eat(&token::LT) { + let lifetimes = self.parse_lifetimes(); + self.expect_gt(); + lifetimes + } else { + Vec::new() + }; + + let (inputs, variadic) = self.parse_fn_args(false, false); + let (_, bounds) = self.parse_optional_ty_param_bounds(false); + let (ret_style, ret_ty) = self.parse_ret_ty(); + let decl = P(FnDecl { + inputs: inputs, + output: ret_ty, + cf: ret_style, + variadic: variadic + }); + (decl, lifetimes, bounds) + }; TyClosure(@ClosureTy { sigil: OwnedSigil, region: None, @@ -907,102 +943,68 @@ impl<'a> Parser<'a> { } // parse a TyClosure type - pub fn parse_ty_closure(&mut self, - opt_sigil: Option, - mut region: Option) - -> Ty_ { + pub fn parse_ty_closure(&mut self) -> Ty_ { /* - (&|~|@) ['r] [unsafe] [once] fn [:Bounds] <'lt> (S) -> T - ^~~~~~^ ^~~^ ^~~~~~~^ ^~~~~^ ^~~~~~~~^ ^~~~^ ^~^ ^ - | | | | | | | | - | | | | | | | Return type - | | | | | | Argument types - | | | | | Lifetimes - | | | | Closure bounds - | | | Once-ness (a.k.a., affine) - | | Purity - | Lifetime bound - Allocation type + [unsafe] [once] <'lt> |S| [:Bounds] -> T + ^~~~~~~^ ^~~~~^ ^~~~^ ^ ^~~~~~~~^ ^ + | | | | | | + | | | | | Return type + | | | | Closure bounds + | | | Argument types + | | Lifetimes + | Once-ness (a.k.a., affine) + Purity */ - // At this point, the allocation type and lifetime bound have been - // parsed. - + // NOTE: remove 'let region' after a stage0 snap + let region = self.parse_opt_lifetime(); let purity = self.parse_unsafety(); - let onceness = parse_onceness(self); - - let (sigil, decl, lifetimes, bounds) = match opt_sigil { - Some(sigil) => { - // Old-style closure syntax (`fn(A)->B`). - self.expect_keyword(keywords::Fn); - let bounds = self.parse_optional_ty_param_bounds(); - let (decl, lifetimes) = self.parse_ty_fn_decl(false); - (sigil, decl, lifetimes, bounds) - } - None => { - // New-style closure syntax (`<'lt>|A|:K -> B`). - let lifetimes = if self.eat(&token::LT) { - let lifetimes = self.parse_lifetimes(); - self.expect_gt(); - - // Re-parse the region here. What a hack. - if region.is_some() { - self.span_err(self.last_span, - "lifetime declarations must precede \ - the lifetime associated with a \ - closure"); - } - region = self.parse_opt_lifetime(); + let onceness = if self.eat_keyword(keywords::Once) {Once} else {Many}; - lifetimes - } else { - Vec::new() - }; + let lifetimes = if self.eat(&token::LT) { + let lifetimes = self.parse_lifetimes(); + self.expect_gt(); - let inputs = if self.eat(&token::OROR) { - Vec::new() - } else { - self.expect_or(); - let inputs = self.parse_seq_to_before_or( - &token::COMMA, - |p| p.parse_arg_general(false)); - self.expect_or(); - inputs - }; + lifetimes + } else { + Vec::new() + }; - let bounds = self.parse_optional_ty_param_bounds(); + let inputs = if self.eat(&token::OROR) { + Vec::new() + } else { + self.expect_or(); + let inputs = self.parse_seq_to_before_or( + &token::COMMA, + |p| p.parse_arg_general(false)); + self.expect_or(); + inputs + }; - let (return_style, output) = self.parse_ret_ty(); - let decl = P(FnDecl { - inputs: inputs, - output: output, - cf: return_style, - variadic: false - }); + let (new_region, bounds) = self.parse_optional_ty_param_bounds(true); - (BorrowedSigil, decl, lifetimes, bounds) - } - }; + // NOTE: this should be removed after a stage0 snap + let region = new_region.or(region); + + let (return_style, output) = self.parse_ret_ty(); + let decl = P(FnDecl { + inputs: inputs, + output: output, + cf: return_style, + variadic: false + }); - return TyClosure(@ClosureTy { - sigil: sigil, + TyClosure(@ClosureTy { + sigil: BorrowedSigil, region: region, purity: purity, onceness: onceness, bounds: bounds, decl: decl, lifetimes: lifetimes, - }); - - fn parse_onceness(this: &mut Parser) -> Onceness { - if this.eat_keyword(keywords::Once) { - Once - } else { - Many - } - } + }) } pub fn parse_unsafety(&mut self) -> Purity { @@ -1246,6 +1248,7 @@ impl<'a> Parser<'a> { self.token == token::BINOP(token::OR) || self.token == token::OROR || self.token == token::LT || + // NOTE: remove this clause after a stage0 snap Parser::token_is_lifetime(&self.token) { // CLOSURE // @@ -1253,9 +1256,7 @@ impl<'a> Parser<'a> { // introduce a closure, once procs can have lifetime bounds. We // will need to refactor the grammar a little bit at that point. - let lifetime = self.parse_opt_lifetime(); - let result = self.parse_ty_closure(None, lifetime); - result + self.parse_ty_closure() } else if self.eat_keyword(keywords::Typeof) { // TYPEOF // In order to not be ambiguous, the type must be surrounded by parens. @@ -1289,23 +1290,6 @@ impl<'a> Parser<'a> { pub fn parse_box_or_uniq_pointee(&mut self, sigil: ast::Sigil) -> Ty_ { - // ~'foo fn() or ~fn() are parsed directly as obsolete fn types: - match self.token { - token::LIFETIME(..) => { - let lifetime = self.parse_lifetime(); - self.obsolete(self.last_span, ObsoleteBoxedClosure); - return self.parse_ty_closure(Some(sigil), Some(lifetime)); - } - - token::IDENT(..) => { - if self.token_is_old_style_closure_keyword() { - self.obsolete(self.last_span, ObsoleteBoxedClosure); - return self.parse_ty_closure(Some(sigil), None); - } - } - _ => {} - } - // other things are parsed as @/~ + a type. Note that constructs like // ~[] and ~str will be resolved during typeck to slices and so forth, // rather than boxed ptrs. But the special casing of str/vec is not @@ -1321,11 +1305,6 @@ impl<'a> Parser<'a> { // look for `&'lt` or `&'foo ` and interpret `foo` as the region name: let opt_lifetime = self.parse_opt_lifetime(); - if self.token_is_old_style_closure_keyword() { - self.obsolete(self.last_span, ObsoleteClosureType); - return self.parse_ty_closure(Some(BorrowedSigil), opt_lifetime); - } - let mt = self.parse_mt(); return TyRptr(opt_lifetime, mt); } @@ -1541,7 +1520,8 @@ impl<'a> Parser<'a> { // Next, parse a colon and bounded type parameters, if applicable. let bounds = if mode == LifetimeAndTypesAndBounds { - self.parse_optional_ty_param_bounds() + let (_, bounds) = self.parse_optional_ty_param_bounds(false); + bounds } else { None }; @@ -3378,11 +3358,19 @@ impl<'a> Parser<'a> { // Returns "Some(Empty)" if there's a colon but nothing after (e.g. "T:") // Returns "Some(stuff)" otherwise (e.g. "T:stuff"). // NB: The None/Some distinction is important for issue #7264. - fn parse_optional_ty_param_bounds(&mut self) -> Option> { + // + // Note that the `allow_any_lifetime` argument is a hack for now while the + // AST doesn't support arbitrary lifetimes in bounds on type parameters. In + // the future, this flag should be removed, and the return value of this + // function should be Option<~[TyParamBound]> + fn parse_optional_ty_param_bounds(&mut self, allow_any_lifetime: bool) + -> (Option, Option>) + { if !self.eat(&token::COLON) { - return None; + return (None, None); } + let mut ret_lifetime = None; let mut result = vec!(); loop { match self.token { @@ -3390,6 +3378,19 @@ impl<'a> Parser<'a> { let lifetime_interned_string = token::get_ident(lifetime); if lifetime_interned_string.equiv(&("static")) { result.push(RegionTyParamBound); + if allow_any_lifetime && ret_lifetime.is_none() { + ret_lifetime = Some(ast::Lifetime { + id: ast::DUMMY_NODE_ID, + span: self.span, + name: lifetime.name + }); + } + } else if allow_any_lifetime && ret_lifetime.is_none() { + ret_lifetime = Some(ast::Lifetime { + id: ast::DUMMY_NODE_ID, + span: self.span, + name: lifetime.name + }); } else { self.span_err(self.span, "`'static` is the only permissible region bound here"); @@ -3408,13 +3409,13 @@ impl<'a> Parser<'a> { } } - return Some(OwnedSlice::from_vec(result)); + return (ret_lifetime, Some(OwnedSlice::from_vec(result))); } // matches typaram = IDENT optbounds ( EQ ty )? fn parse_ty_param(&mut self) -> TyParam { let ident = self.parse_ident(); - let opt_bounds = self.parse_optional_ty_param_bounds(); + let (_, opt_bounds) = self.parse_optional_ty_param_bounds(false); // For typarams we don't care about the difference b/w "" and "". let bounds = opt_bounds.unwrap_or_default(); diff --git a/src/test/compile-fail/closure-bounds-static-cant-capture-borrowed.rs b/src/test/compile-fail/closure-bounds-static-cant-capture-borrowed.rs index 1c6d65ba54167..9176412cd79fe 100644 --- a/src/test/compile-fail/closure-bounds-static-cant-capture-borrowed.rs +++ b/src/test/compile-fail/closure-bounds-static-cant-capture-borrowed.rs @@ -12,8 +12,8 @@ fn bar(blk: ||:'static) { } fn foo(x: &()) { - bar(|| { - let _ = x; //~ ERROR does not fulfill `'static` + bar(|| { //~ ERROR cannot infer an appropriate lifetime + let _ = x; }) } diff --git a/src/test/run-pass/closure-syntax.rs b/src/test/run-pass/closure-syntax.rs new file mode 100644 index 0000000000000..e891328b62869 --- /dev/null +++ b/src/test/run-pass/closure-syntax.rs @@ -0,0 +1,74 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![allow(dead_code)] + +fn foo() {} + +trait Bar1 {} +impl Bar1 for proc() {} + +trait Bar2 {} +impl Bar2 for proc(): Send {} + +trait Bar3 {} +impl<'b> Bar3 for <'a>|&'a int|: 'b + Send -> &'a int {} + +trait Bar4 {} +impl Bar4 for proc<'a>(&'a int) -> &'a int {} + +struct Foo<'a> { + a: ||: 'a, + b: ||: 'static, + c: <'b>||: 'a, + d: ||: 'a + Share, + e: <'b>|int|: 'a + Share -> &'b f32, + f: proc(), + g: proc(): 'static + Share, + h: proc<'b>(int): Share -> &'b f32, +} + +fn f<'a>(a: &'a int, f: <'b>|&'b int| -> &'b int) -> &'a int { + f(a) +} + +fn g<'a>(a: &'a int, f: proc<'b>(&'b int) -> &'b int) -> &'a int { + f(a) +} + +fn bar<'b>() { + foo::<||>(); + foo::<|| -> ()>(); + foo::<||:>(); + foo::<||:'b>(); + foo::<||:'b + Share>(); + foo::<||:Share>(); + foo::< <'a>|int, f32, &'a int|:'b + Share -> &'a int>(); + foo::(); + foo:: ()>(); + foo::(); + foo::(); + foo::(); + foo::(int, f32, &'a int):'static + Share -> &'a int>(); + + // issue #11209 + let _: 'b ||; // for comparison + let _: <'a> ||; + + let _: Option<||:'b>; + // let _: Option<<'a>||>; + let _: Option< <'a>||>; + + // issue #11210 + let _: 'static ||; +} + +pub fn main() { +} diff --git a/src/test/run-pass/issue-10767.rs b/src/test/run-pass/issue-10767.rs new file mode 100644 index 0000000000000..34eb6ce030ddc --- /dev/null +++ b/src/test/run-pass/issue-10767.rs @@ -0,0 +1,15 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +fn main() { + fn f() { + }; + let _: ~fn() = ~f; +} diff --git a/src/test/run-pass/once-move-out-on-stack.rs b/src/test/run-pass/once-move-out-on-stack.rs index f14827c7245f4..995fc0911130e 100644 --- a/src/test/run-pass/once-move-out-on-stack.rs +++ b/src/test/run-pass/once-move-out-on-stack.rs @@ -12,7 +12,7 @@ // ignore-fast -#[feature(once_fns)]; +#![feature(once_fns)] extern crate sync; use sync::Arc;