Struct wiggle_generate::config::Config
source · pub struct Config {
pub witx: WitxConf,
pub errors: ErrorConf,
pub async_: AsyncConf,
pub wasmtime: bool,
pub tracing: TracingConf,
}
Fields§
§witx: WitxConf
§errors: ErrorConf
§async_: AsyncConf
§wasmtime: bool
§tracing: TracingConf
Implementations§
source§impl Config
impl Config
sourcepub fn build(
fields: impl Iterator<Item = ConfigField>,
err_loc: Span
) -> Result<Self>
pub fn build(
fields: impl Iterator<Item = ConfigField>,
err_loc: Span
) -> Result<Self>
Examples found in repository?
src/config.rs (line 153)
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 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549
fn parse(input: ParseStream) -> Result<Self> {
let contents;
let _lbrace = braced!(contents in input);
let fields: Punctuated<ConfigField, Token![,]> =
contents.parse_terminated(ConfigField::parse)?;
Ok(Config::build(fields.into_iter(), input.span())?)
}
}
/// The witx document(s) that will be loaded from a [`Config`](struct.Config.html).
///
/// A witx interface definition can be provided either as a collection of relative paths to
/// documents, or as a single inlined string literal. Note that `(use ...)` directives are not
/// permitted when providing a string literal.
#[derive(Debug, Clone)]
pub enum WitxConf {
/// A collection of paths pointing to witx files.
Paths(Paths),
/// A single witx document, provided as a string literal.
Literal(Literal),
}
impl WitxConf {
/// Load the `witx` document.
///
/// # Panics
///
/// This method will panic if the paths given in the `witx` field were not valid documents, or
/// if any of the given documents were not syntactically valid.
pub fn load_document(&self) -> witx::Document {
match self {
Self::Paths(paths) => witx::load(paths.as_ref()).expect("loading witx"),
Self::Literal(doc) => witx::parse(doc.as_ref()).expect("parsing witx"),
}
}
}
/// A collection of paths, pointing to witx documents.
#[derive(Debug, Clone)]
pub struct Paths(Vec<PathBuf>);
impl Paths {
/// Create a new, empty collection of paths.
pub fn new() -> Self {
Default::default()
}
}
impl Default for Paths {
fn default() -> Self {
Self(Default::default())
}
}
impl AsRef<[PathBuf]> for Paths {
fn as_ref(&self) -> &[PathBuf] {
self.0.as_ref()
}
}
impl AsMut<[PathBuf]> for Paths {
fn as_mut(&mut self) -> &mut [PathBuf] {
self.0.as_mut()
}
}
impl FromIterator<PathBuf> for Paths {
fn from_iter<I>(iter: I) -> Self
where
I: IntoIterator<Item = PathBuf>,
{
Self(iter.into_iter().collect())
}
}
impl Parse for Paths {
fn parse(input: ParseStream) -> Result<Self> {
let content;
let _ = bracketed!(content in input);
let path_lits: Punctuated<LitStr, Token![,]> = content.parse_terminated(Parse::parse)?;
let expanded_paths = path_lits
.iter()
.map(|lit| {
PathBuf::from(
shellexpand::env(&lit.value())
.expect("shell expansion")
.as_ref(),
)
})
.collect::<Vec<PathBuf>>();
Ok(Paths(expanded_paths))
}
}
/// A single witx document, provided as a string literal.
#[derive(Debug, Clone)]
pub struct Literal(String);
impl AsRef<str> for Literal {
fn as_ref(&self) -> &str {
self.0.as_ref()
}
}
impl Parse for Literal {
fn parse(input: ParseStream) -> Result<Self> {
Ok(Self(input.parse::<syn::LitStr>()?.value()))
}
}
#[derive(Clone, Default, Debug)]
/// Map from abi error type to rich error type
pub struct ErrorConf(HashMap<Ident, ErrorConfField>);
impl ErrorConf {
pub fn iter(&self) -> impl Iterator<Item = (&Ident, &ErrorConfField)> {
self.0.iter()
}
}
impl Parse for ErrorConf {
fn parse(input: ParseStream) -> Result<Self> {
let content;
let _ = braced!(content in input);
let items: Punctuated<ErrorConfField, Token![,]> =
content.parse_terminated(Parse::parse)?;
let mut m = HashMap::new();
for i in items {
match m.insert(i.abi_error().clone(), i.clone()) {
None => {}
Some(prev_def) => {
return Err(Error::new(
*i.err_loc(),
format!(
"duplicate definition of rich error type for {:?}: previously defined at {:?}",
i.abi_error(), prev_def.err_loc(),
),
))
}
}
}
Ok(ErrorConf(m))
}
}
#[derive(Debug, Clone)]
pub enum ErrorConfField {
Trappable(TrappableErrorConfField),
User(UserErrorConfField),
}
impl ErrorConfField {
pub fn abi_error(&self) -> &Ident {
match self {
Self::Trappable(t) => &t.abi_error,
Self::User(u) => &u.abi_error,
}
}
pub fn err_loc(&self) -> &Span {
match self {
Self::Trappable(t) => &t.err_loc,
Self::User(u) => &u.err_loc,
}
}
}
impl Parse for ErrorConfField {
fn parse(input: ParseStream) -> Result<Self> {
let err_loc = input.span();
let abi_error = input.parse::<Ident>()?;
let _arrow: Token![=>] = input.parse()?;
let lookahead = input.lookahead1();
if lookahead.peek(kw::trappable) {
let _ = input.parse::<kw::trappable>()?;
let rich_error = input.parse()?;
Ok(ErrorConfField::Trappable(TrappableErrorConfField {
abi_error,
rich_error,
err_loc,
}))
} else {
let rich_error = input.parse::<syn::Path>()?;
Ok(ErrorConfField::User(UserErrorConfField {
abi_error,
rich_error,
err_loc,
}))
}
}
}
#[derive(Clone, Debug)]
pub struct TrappableErrorConfField {
pub abi_error: Ident,
pub rich_error: Ident,
pub err_loc: Span,
}
#[derive(Clone)]
pub struct UserErrorConfField {
pub abi_error: Ident,
pub rich_error: syn::Path,
pub err_loc: Span,
}
impl std::fmt::Debug for UserErrorConfField {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ErrorConfField")
.field("abi_error", &self.abi_error)
.field("rich_error", &"(...)")
.field("err_loc", &self.err_loc)
.finish()
}
}
#[derive(Clone, Default, Debug)]
/// Modules and funcs that have async signatures
pub struct AsyncConf {
blocking: bool,
functions: AsyncFunctions,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum Asyncness {
/// Wiggle function is synchronous, wasmtime Func is synchronous
Sync,
/// Wiggle function is asynchronous, but wasmtime Func is synchronous
Blocking,
/// Wiggle function and wasmtime Func are asynchronous.
Async,
}
impl Asyncness {
pub fn is_async(&self) -> bool {
match self {
Self::Async => true,
_ => false,
}
}
pub fn is_blocking(&self) -> bool {
match self {
Self::Blocking => true,
_ => false,
}
}
pub fn is_sync(&self) -> bool {
match self {
Self::Sync => true,
_ => false,
}
}
}
#[derive(Clone, Debug)]
pub enum AsyncFunctions {
Some(HashMap<String, Vec<String>>),
All,
}
impl Default for AsyncFunctions {
fn default() -> Self {
AsyncFunctions::Some(HashMap::default())
}
}
impl AsyncConf {
pub fn get(&self, module: &str, function: &str) -> Asyncness {
let a = if self.blocking {
Asyncness::Blocking
} else {
Asyncness::Async
};
match &self.functions {
AsyncFunctions::Some(fs) => {
if fs
.get(module)
.and_then(|fs| fs.iter().find(|f| *f == function))
.is_some()
{
a
} else {
Asyncness::Sync
}
}
AsyncFunctions::All => a,
}
}
pub fn contains_async(&self, module: &witx::Module) -> bool {
for f in module.funcs() {
if self.get(module.name.as_str(), f.name.as_str()).is_async() {
return true;
}
}
false
}
}
impl Parse for AsyncFunctions {
fn parse(input: ParseStream) -> Result<Self> {
let content;
let lookahead = input.lookahead1();
if lookahead.peek(syn::token::Brace) {
let _ = braced!(content in input);
let items: Punctuated<FunctionField, Token![,]> =
content.parse_terminated(Parse::parse)?;
let mut functions: HashMap<String, Vec<String>> = HashMap::new();
use std::collections::hash_map::Entry;
for i in items {
let function_names = i
.function_names
.iter()
.map(|i| i.to_string())
.collect::<Vec<String>>();
match functions.entry(i.module_name.to_string()) {
Entry::Occupied(o) => o.into_mut().extend(function_names),
Entry::Vacant(v) => {
v.insert(function_names);
}
}
}
Ok(AsyncFunctions::Some(functions))
} else if lookahead.peek(Token![*]) {
let _: Token![*] = input.parse().unwrap();
Ok(AsyncFunctions::All)
} else {
Err(lookahead.error())
}
}
}
#[derive(Clone)]
pub struct FunctionField {
pub module_name: Ident,
pub function_names: Vec<Ident>,
pub err_loc: Span,
}
impl Parse for FunctionField {
fn parse(input: ParseStream) -> Result<Self> {
let err_loc = input.span();
let module_name = input.parse::<Ident>()?;
let _doublecolon: Token![::] = input.parse()?;
let lookahead = input.lookahead1();
if lookahead.peek(syn::token::Brace) {
let content;
let _ = braced!(content in input);
let function_names: Punctuated<Ident, Token![,]> =
content.parse_terminated(Parse::parse)?;
Ok(FunctionField {
module_name,
function_names: function_names.iter().cloned().collect(),
err_loc,
})
} else if lookahead.peek(Ident) {
let name = input.parse()?;
Ok(FunctionField {
module_name,
function_names: vec![name],
err_loc,
})
} else {
Err(lookahead.error())
}
}
}
#[derive(Clone)]
pub struct WasmtimeConfig {
pub c: Config,
pub target: syn::Path,
}
#[derive(Clone)]
pub enum WasmtimeConfigField {
Core(ConfigField),
Target(syn::Path),
}
impl WasmtimeConfig {
pub fn build(fields: impl Iterator<Item = WasmtimeConfigField>, err_loc: Span) -> Result<Self> {
let mut target = None;
let mut cs = Vec::new();
for f in fields {
match f {
WasmtimeConfigField::Target(c) => {
if target.is_some() {
return Err(Error::new(err_loc, "duplicate `target` field"));
}
target = Some(c);
}
WasmtimeConfigField::Core(c) => cs.push(c),
}
}
let c = Config::build(cs.into_iter(), err_loc)?;
Ok(WasmtimeConfig {
c,
target: target
.take()
.ok_or_else(|| Error::new(err_loc, "`target` field required"))?,
})
}
sourcepub fn load_document(&self) -> Document
pub fn load_document(&self) -> Document
Load the witx
document for the configuration.
Panics
This method will panic if the paths given in the witx
field were not valid documents.