Created
June 28, 2025 21:17
-
-
Save freedomtowin/716c55f5cc540fdba1c6ae0fa1050ead to your computer and use it in GitHub Desktop.
Example of creating a Gist using Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
impl ToTokens for Comprehension { | |
fn to_tokens(&self, tokens: &mut TokenStream2) { | |
let all_for_if_clauses = | |
std::iter::once(&self.for_if_clause).chain(&self.additional_for_if_clauses); | |
let mut innermost_to_outermost = all_for_if_clauses.rev(); | |
let mut output = { | |
// innermost is a special case--here we do the mapping | |
let innermost = innermost_to_outermost | |
.next() | |
.expect("We know we have at least one ForIfClause (self.for_if_clause)"); | |
let ForIfClause { | |
pattern, | |
sequence, | |
conditions, | |
} = innermost; | |
let Mapping(mapping) = &self.mapping; | |
quote! { | |
::core::iter::IntoIterator::into_iter(#sequence).filter_map(move |#pattern| { | |
(true #(&& (#conditions))*).then(|| #mapping) | |
}) | |
} | |
}; | |
// Now we walk through the rest of the ForIfClauses, wrapping the current `output` in a new layer of iteration each time. | |
// We also add an extra call to '.flatten()'. | |
output = innermost_to_outermost.fold(output, |current_output, next_layer| { | |
let ForIfClause { | |
pattern, | |
sequence, | |
conditions, | |
} = next_layer; | |
quote! { | |
::core::iter::IntoIterator::into_iter(#sequence).filter_map(move |#pattern| { | |
(true #(&& (#conditions))*).then(|| #current_output) | |
}) | |
.flatten() | |
} | |
}); | |
tokens.extend(output) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment