Skip to content

Add support for registering attributes with rustc in plugins #25168

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
May 24, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions src/librustc/plugin/registry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ use syntax::codemap::Span;
use syntax::parse::token;
use syntax::ptr::P;
use syntax::ast;
use syntax::feature_gate::AttributeType;

use std::collections::HashMap;
use std::borrow::ToOwned;
Expand Down Expand Up @@ -54,6 +55,9 @@ pub struct Registry<'a> {

#[doc(hidden)]
pub llvm_passes: Vec<String>,

#[doc(hidden)]
pub attributes: Vec<(String, AttributeType)>,
}

impl<'a> Registry<'a> {
Expand All @@ -67,6 +71,7 @@ impl<'a> Registry<'a> {
lint_passes: vec!(),
lint_groups: HashMap::new(),
llvm_passes: vec!(),
attributes: vec!(),
}
}

Expand Down Expand Up @@ -130,4 +135,19 @@ impl<'a> Registry<'a> {
pub fn register_llvm_pass(&mut self, name: &str) {
self.llvm_passes.push(name.to_owned());
}


/// Register an attribute with an attribute type.
///
/// Registered attributes will bypass the `custom_attribute` feature gate.
/// `Whitelisted` attributes will additionally not trigger the `unused_attribute`
/// lint. `CrateLevel` attributes will not be allowed on anything other than a crate.
pub fn register_attribute(&mut self, name: String, ty: AttributeType) {
if let AttributeType::Gated(..) = ty {
self.sess.span_err(self.krate_span, "plugin tried to register a gated \
attribute. Only `Normal`, `Whitelisted`, \
and `CrateLevel` attributes are allowed");
}
self.attributes.push((name, ty));
}
}
3 changes: 3 additions & 0 deletions src/librustc/session/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ use syntax::parse;
use syntax::parse::token;
use syntax::parse::ParseSess;
use syntax::{ast, codemap};
use syntax::feature_gate::AttributeType;

use rustc_back::target::Target;

Expand Down Expand Up @@ -54,6 +55,7 @@ pub struct Session {
pub lint_store: RefCell<lint::LintStore>,
pub lints: RefCell<NodeMap<Vec<(lint::LintId, codemap::Span, String)>>>,
pub plugin_llvm_passes: RefCell<Vec<String>>,
pub plugin_attributes: RefCell<Vec<(String, AttributeType)>>,
pub crate_types: RefCell<Vec<config::CrateType>>,
pub crate_metadata: RefCell<Vec<String>>,
pub features: RefCell<feature_gate::Features>,
Expand Down Expand Up @@ -416,6 +418,7 @@ pub fn build_session_(sopts: config::Options,
lint_store: RefCell::new(lint::LintStore::new()),
lints: RefCell::new(NodeMap()),
plugin_llvm_passes: RefCell::new(Vec::new()),
plugin_attributes: RefCell::new(Vec::new()),
crate_types: RefCell::new(Vec::new()),
crate_metadata: RefCell::new(Vec::new()),
delayed_span_bug: RefCell::new(None),
Expand Down
8 changes: 5 additions & 3 deletions src/librustc_driver/driver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -444,7 +444,8 @@ pub fn phase_2_configure_and_expand(sess: &Session,
}
});

let Registry { syntax_exts, lint_passes, lint_groups, llvm_passes, .. } = registry;
let Registry { syntax_exts, lint_passes, lint_groups,
llvm_passes, attributes, .. } = registry;

{
let mut ls = sess.lint_store.borrow_mut();
Expand All @@ -457,6 +458,7 @@ pub fn phase_2_configure_and_expand(sess: &Session,
}

*sess.plugin_llvm_passes.borrow_mut() = llvm_passes;
*sess.plugin_attributes.borrow_mut() = attributes.clone();
}

// Lint plugins are registered; now we can process command line flags.
Expand Down Expand Up @@ -511,7 +513,7 @@ pub fn phase_2_configure_and_expand(sess: &Session,
let features =
syntax::feature_gate::check_crate(sess.codemap(),
&sess.parse_sess.span_diagnostic,
&krate);
&krate, &attributes);
*sess.features.borrow_mut() = features;
sess.abort_if_errors();
});
Expand Down Expand Up @@ -541,7 +543,7 @@ pub fn phase_2_configure_and_expand(sess: &Session,
let features =
syntax::feature_gate::check_crate(sess.codemap(),
&sess.parse_sess.span_diagnostic,
&krate);
&krate, &attributes);
*sess.features.borrow_mut() = features;
sess.abort_if_errors();
});
Expand Down
19 changes: 18 additions & 1 deletion src/librustc_lint/builtin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -641,9 +641,26 @@ impl LintPass for UnusedAttributes {
}
}

let plugin_attributes = cx.sess().plugin_attributes.borrow_mut();
for &(ref name, ty) in plugin_attributes.iter() {
if ty == AttributeType::Whitelisted && attr.check_name(&*name) {
break;
}
}

if !attr::is_used(attr) {
cx.span_lint(UNUSED_ATTRIBUTES, attr.span, "unused attribute");
if KNOWN_ATTRIBUTES.contains(&(&attr.name(), AttributeType::CrateLevel)) {
// Is it a builtin attribute that must be used at the crate level?
let known_crate = KNOWN_ATTRIBUTES.contains(&(&attr.name(),
AttributeType::CrateLevel));
// Has a plugin registered this attribute as one which must be used at
// the crate level?
let plugin_crate = plugin_attributes.iter()
.find(|&&(ref x, t)| {
&*attr.name() == &*x &&
AttributeType::CrateLevel == t
}).is_some();
if known_crate || plugin_crate {
let msg = match attr.node.style {
ast::AttrOuter => "crate-level attribute should be an inner \
attribute: add an exclamation mark: #![foo]",
Expand Down
44 changes: 31 additions & 13 deletions src/libsyntax/feature_gate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -359,6 +359,7 @@ struct Context<'a> {
features: Vec<&'static str>,
span_handler: &'a SpanHandler,
cm: &'a CodeMap,
plugin_attributes: &'a [(String, AttributeType)],
}

impl<'a> Context<'a> {
Expand All @@ -373,7 +374,7 @@ impl<'a> Context<'a> {
self.features.iter().any(|&n| n == feature)
}

fn check_attribute(&self, attr: &ast::Attribute) {
fn check_attribute(&self, attr: &ast::Attribute, is_macro: bool) {
debug!("check_attribute(attr = {:?})", attr);
let name = &*attr.name();
for &(n, ty) in KNOWN_ATTRIBUTES {
Expand All @@ -385,6 +386,15 @@ impl<'a> Context<'a> {
return;
}
}
for &(ref n, ref ty) in self.plugin_attributes.iter() {
if &*n == name {
// Plugins can't gate attributes, so we don't check for it
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Isn't it more that plugins register "known" attributes, i.e. they no longer count as custom?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This code does feature gating of specific attrs; even if custom_attribute is on, attributes like rustc_on_unimplemented can't be used until the specific feature is turned on. AttributeType has a Gated variant that we check for in the code above, but we don't do that here since plugin_attributes cannot contain Gated types.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The code below doesn't look at Gated attributes at all, the only reason for this shortcircuit to exist here would be to avoid the custom_attribute feature gate. :)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, so the comment is just contrasting to the behaviour of the code above. Makes sense.

Could you still point out that the loop is still necessary to short-circuit to avoid the checks below.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed

// unlike the code above; we only use this loop to
// short-circuit to avoid the checks below
debug!("check_attribute: {:?} is registered by a plugin, {:?}", name, ty);
return;
}
}
if name.starts_with("rustc_") {
self.gate_feature("rustc_attrs", attr.span,
"unless otherwise specified, attributes \
Expand All @@ -395,12 +405,18 @@ impl<'a> Context<'a> {
"attributes of the form `#[derive_*]` are reserved \
for the compiler");
} else {
self.gate_feature("custom_attribute", attr.span,
&format!("The attribute `{}` is currently \
unknown to the compiler and \
may have meaning \
added to it in the future",
name));
// Only run the custom attribute lint during regular
// feature gate checking. Macro gating runs
// before the plugin attributes are registered
// so we skip this then
if !is_macro {
self.gate_feature("custom_attribute", attr.span,
&format!("The attribute `{}` is currently \
unknown to the compiler and \
may have meaning \
added to it in the future",
name));
}
}
}
}
Expand Down Expand Up @@ -479,7 +495,7 @@ impl<'a, 'v> Visitor<'v> for MacroVisitor<'a> {
}

fn visit_attribute(&mut self, attr: &'v ast::Attribute) {
self.context.check_attribute(attr);
self.context.check_attribute(attr, true);
}
}

Expand All @@ -498,7 +514,7 @@ impl<'a> PostExpansionVisitor<'a> {
impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> {
fn visit_attribute(&mut self, attr: &ast::Attribute) {
if !self.context.cm.span_allows_unstable(attr.span) {
self.context.check_attribute(attr);
self.context.check_attribute(attr, false);
}
}

Expand Down Expand Up @@ -685,6 +701,7 @@ impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> {

fn check_crate_inner<F>(cm: &CodeMap, span_handler: &SpanHandler,
krate: &ast::Crate,
plugin_attributes: &[(String, AttributeType)],
check: F)
-> Features
where F: FnOnce(&mut Context, &ast::Crate)
Expand All @@ -693,6 +710,7 @@ fn check_crate_inner<F>(cm: &CodeMap, span_handler: &SpanHandler,
features: Vec::new(),
span_handler: span_handler,
cm: cm,
plugin_attributes: plugin_attributes,
};

let mut accepted_features = Vec::new();
Expand Down Expand Up @@ -765,14 +783,14 @@ fn check_crate_inner<F>(cm: &CodeMap, span_handler: &SpanHandler,

pub fn check_crate_macros(cm: &CodeMap, span_handler: &SpanHandler, krate: &ast::Crate)
-> Features {
check_crate_inner(cm, span_handler, krate,
check_crate_inner(cm, span_handler, krate, &[] as &'static [_],
|ctx, krate| visit::walk_crate(&mut MacroVisitor { context: ctx }, krate))
}

pub fn check_crate(cm: &CodeMap, span_handler: &SpanHandler, krate: &ast::Crate)
-> Features
pub fn check_crate(cm: &CodeMap, span_handler: &SpanHandler, krate: &ast::Crate,
plugin_attributes: &[(String, AttributeType)]) -> Features
{
check_crate_inner(cm, span_handler, krate,
check_crate_inner(cm, span_handler, krate, plugin_attributes,
|ctx, krate| visit::walk_crate(&mut PostExpansionVisitor { context: ctx },
krate))
}
30 changes: 30 additions & 0 deletions src/test/auxiliary/attr_plugin_test.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// 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 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// force-host

#![feature(plugin_registrar)]
#![feature(rustc_private)]

extern crate syntax;

extern crate rustc;

use syntax::feature_gate::AttributeType;
use rustc::plugin::Registry;



#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
reg.register_attribute("foo".to_owned(), AttributeType::Normal);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hm, what's the point of registering a Normal attribute?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, it gets an unused attribute warning, but it doesn't get the custom_attribute feature gate. Whitelist doesn't get either.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep. Normal is something that I don't expect will be used often, but I just added support for it so that people can silence an annoying feature gate if they want to. (that feature gate exists solely for backcompat reasons; and if you're using plugins it doesn't matter anyway)

reg.register_attribute("bar".to_owned(), AttributeType::CrateLevel);
reg.register_attribute("baz".to_owned(), AttributeType::Whitelisted);
}
30 changes: 30 additions & 0 deletions src/test/compile-fail-fulldeps/plugin-attr-register-deny.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// 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 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// aux-build:attr_plugin_test.rs
// ignore-stage1

#![feature(plugin)]
#![plugin(attr_plugin_test)]
#![deny(unused_attributes)]

#[baz]
fn baz() { } // no error

#[foo]
pub fn main() {
//~^^ ERROR unused
#[bar]
fn inner() {}
//~^^ ERROR crate
//~^^^ ERROR unused
baz();
inner();
}