1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
|
//! "Options", keyword modifiers for an expansion
//!
//! These "combine": multiple specifications of the same option
//! are allowed, so long as they are compatible.
use super::prelude::*;
use adviseable::*;
use OptionDetails as OD;
//---------- types, ordered from general to specific ----------
/// Where are we finding these options?
#[derive(Debug, Copy, Clone)]
pub enum OpContext {
/// Just before a precanned template
///
/// `define_derivae_deftly!{ Template OPTIONS: ...`
TemplateDefinition,
/// Just before an adhoc template
///
/// `derive_deftly_adhoc!{ Driver OPTIONS: ...`
TemplateAdhoc,
/// In the driver's application
///
/// `#[derive_deftly(Template[OPTIONS])]`
DriverApplicationCapture,
/// Module definition.
///
/// `define_derivae_deftly_module!{ Module OPTIONS: ...`
ModuleDefinition,
/// Driver's application options as they appear in the ultimate expansion
///
/// With the versioning, so `1 1 AOPTIONS`.
DriverApplicationPassed,
}
/// All the template options, as a tokenstream, but sanity-checked
///
/// These have been syntax checked, but not semantically checked.
/// The purpose of the syntax check is to get syntax errors early,
/// when a template is defined - rather than when it's applied.
///
/// This also helps with cross-crate compatibility.
#[derive(Default, Debug, Clone)]
pub struct UnprocessedOptions {
ts: TokenStream,
pub beta_enabled: Option<beta::Enabled>,
}
impl_to_tokens!(UnprocessedOptions, ts);
/// Template options, semantically resolved
#[derive(Default, Debug, Clone)]
pub struct DdOptions {
pub dbg: bool,
pub driver_kind: Option<DdOptVal<ExpectedDriverKind>>,
pub expect_target: Option<DdOptVal<check::Target>>,
pub beta_enabled: Option<beta::Enabled>,
}
/// A single template option
#[derive(Debug)]
struct DdOption {
pub kw_span: Span,
pub od: OptionDetails,
}
/// Enum for the details of a template option
#[derive(Debug, Clone)]
#[allow(non_camel_case_types)] // clearer to use the exact ident
enum OptionDetails {
dbg,
For(DdOptVal<ExpectedDriverKind>),
expect(DdOptVal<check::Target>),
beta_deftly(beta::Enabled),
}
/// Value for an option
///
/// If `V` is `FromStr` and `DdOptValDescribable`,
/// this is `Parse`, taking a single keyword.
#[derive(Debug, Clone, Copy)]
pub struct DdOptVal<V> {
pub value: V,
pub span: Span,
}
/// Things that go into a `DdOptVal`
pub trait DdOptValDescribable {
const DESCRIPTION: &'static str;
}
/// The (single) expected driver kind
//
// At some future point, we may want `for ...` keywords that
// specify a range of possible drivers. Then we'll need both
// this enum, and a *set* of it, and calculate the intersection
// in update_from_option.
#[derive(Debug, Clone, Copy, Eq, PartialEq, EnumString, Display)]
#[strum(serialize_all = "snake_case")]
pub enum ExpectedDriverKind {
Struct,
Enum,
Union,
}
#[derive(Debug, Copy, Clone)]
pub struct OpCompatVersions {
/// Increased when we make a wholly-incompatible change
///
/// Bumping this will cause rejection of AOPTIONS by old d-d engines.
/// Hopefully a newer d-d will able to cope with both.
major: OpCompatVersionNumber,
/// Increased when we make a more subtle change
///
/// Current d-d versions will ignore this.
/// Bumping it can be used to psas information
/// from a newer capturing d-d to a newer template/driver d-d.
minor: OpCompatVersionNumber,
/// Span for error reporting
span: Span,
}
type OpCompatVersionNumber = u32;
impl OpCompatVersions {
pub fn ours() -> Self {
OpCompatVersions {
major: 1,
minor: 0,
span: Span::call_site(),
}
}
}
impl DdOptValDescribable for ExpectedDriverKind {
const DESCRIPTION: &'static str = "expected driver kind (in `for` option)";
}
//---------- parsing ----------
impl OpContext {
fn allowed(self, option: &DdOption) -> syn::Result<()> {
use OpContext as OC;
match self {
OC::ModuleDefinition => {
return match &option.od {
OD::beta_deftly(..) => Ok(()),
_other => Err(option.kw_span.error(
"only beta_deftly is allowed in module definitions",
)),
}
}
_other => {}
}
match &option.od {
OD::dbg => return Ok(()),
OD::expect(v) => return check::check_expect_opcontext(v, self),
OD::For(..) => {}
OD::beta_deftly(..) => {}
}
match self {
OC::TemplateDefinition => Ok(()),
OC::TemplateAdhoc => Ok(()),
OC::DriverApplicationCapture | OC::DriverApplicationPassed => {
Err(option.kw_span.error(
"this derive-deftly option is only supported in templates",
))
}
OC::ModuleDefinition => panic!("handled earlier"),
}
}
fn parse_versions(
self,
input: ParseStream,
) -> syn::Result<OpCompatVersions> {
use OpContext as OC;
let ours = OpCompatVersions::ours();
let got = match self {
OC::TemplateDefinition
| OC::TemplateAdhoc
| OC::ModuleDefinition
| OC::DriverApplicationCapture => ours,
OC::DriverApplicationPassed => input.parse()?,
};
if got.major != ours.major {
return Err(got.error(format_args!(
"Incompatible major version for AOPTIONS (driver {}, template/engine {})",
got.major,
ours.major,
)));
}
Ok(got)
}
}
impl ToTokens for OpCompatVersions {
fn to_tokens(&self, out: &mut TokenStream) {
let OpCompatVersions { major, minor, span } = OpCompatVersions::ours();
out.extend(quote_spanned! {span=> #major #minor });
}
}
impl Parse for OpCompatVersions {
fn parse(input: ParseStream) -> syn::Result<Self> {
let number = move || {
let lit: syn::LitInt = input.parse()?;
Ok::<_, syn::Error>((lit.span(), lit.base10_parse()?))
};
let (span, major) = number()?;
let (_, minor) = number()?;
Ok(OpCompatVersions { major, minor, span })
}
}
fn continue_options(input: ParseStream) -> Option<Lookahead1> {
if input.is_empty() {
return None;
}
let la = input.lookahead1();
if la.peek(Token![:]) || la.peek(Token![=]) {
return None;
}
Some(la)
}
impl UnprocessedOptions {
pub fn parse(
input: ParseStream,
opcontext: OpContext,
) -> syn::Result<Self> {
let mut beta_enabled = None;
// Scan ahead for a syntax check (and beta enablement)
DdOption::parse_several(&input.fork(), opcontext, |opt| {
match &opt.od {
OD::beta_deftly(be) => beta_enabled = Some(*be),
_ => {}
};
Ok(())
})?;
// Collect everything until the : or =
let mut out = TokenStream::new();
while continue_options(input).is_some() {
let tt: TokenTree = input.parse()?;
out.extend([tt]);
}
Ok(UnprocessedOptions {
ts: out,
beta_enabled,
})
}
}
impl DdOptions {
pub fn parse_update(
&mut self,
input: ParseStream,
opcontext: OpContext,
) -> syn::Result<()> {
DdOption::parse_several(input, opcontext, |option| {
self.update_from_option(option)
})
}
}
impl DdOption {
/// Parses zero or more options, in `opcontext`
///
/// With `OpContext::DriverApplicationPassed`,
/// expects to find the version information too.
fn parse_several(
input: ParseStream,
opcontext: OpContext,
mut each: impl FnMut(DdOption) -> syn::Result<()>,
) -> syn::Result<()> {
let _versions = opcontext
.parse_versions(input)
.map_err(advise_incompatibility)?;
while let Some(la) = continue_options(input) {
if !la.peek(Ident::peek_any) {
return Err(la.error());
}
let option = input.parse()?;
opcontext.allowed(&option)?;
each(option)?;
let la = if let Some(la) = continue_options(input) {
la
} else {
break;
};
if !la.peek(Token![,]) {
return Err(la.error());
}
let _: Token![,] = input.parse()?;
}
Ok(())
}
}
impl Parse for DdOption {
fn parse(input: ParseStream) -> syn::Result<Self> {
let kw: IdentAny = input.parse()?;
let from_od = |od| {
Ok(DdOption {
kw_span: kw.span(),
od,
})
};
// See keyword_general! in utils.rs
macro_rules! keyword { { $($args:tt)* } => {
keyword_general! { kw from_od OD; $($args)* }
} }
keyword! { dbg }
keyword! { "for": For(input.parse()?) }
keyword! { expect(input.parse()?) }
keyword! { beta_deftly(beta::Enabled::new_for_dd_option(kw.span())?) }
Err(kw.error("unknown derive-deftly option"))
}
}
impl<V: FromStr + DdOptValDescribable> Parse for DdOptVal<V> {
fn parse(input: ParseStream) -> syn::Result<Self> {
let kw: IdentAny = input.parse()?;
let value = kw.to_string().parse().map_err(|_| {
kw.error(format_args!("unknown value for {}", V::DESCRIPTION))
})?;
let span = kw.span();
Ok(DdOptVal { value, span })
}
}
//---------- processing ----------
impl UnprocessedOptions {
#[allow(dead_code)] // Currently unused, retain it in case we need it
pub fn is_empty(&self) -> bool {
self.ts.is_empty()
}
}
impl DdOptions {
/// Update `self` according to the option specified in `option`
///
/// On error (eg, contradictory options), fails.
fn update_from_option(&mut self, option: DdOption) -> syn::Result<()> {
fn store<V>(
already: &mut Option<DdOptVal<V>>,
new: DdOptVal<V>,
) -> syn::Result<()>
where
V: PartialEq + DdOptValDescribable,
{
match already {
Some(already) if already.value == new.value => Ok(()),
Some(already) => {
Err([(already.span, "first"), (new.span, "second")].error(
format_args!(
"contradictory values for {}",
V::DESCRIPTION,
),
))
}
None => {
*already = Some(new);
Ok(())
}
}
}
Ok(match option.od {
OD::dbg => self.dbg = true,
OD::expect(spec) => store(&mut self.expect_target, spec)?,
OD::For(spec) => store(&mut self.driver_kind, spec)?,
OD::beta_deftly(be) => self.beta_enabled = Some(be),
})
}
}
|