use std::path::Path;
use cpp_parser::{CppTokenData, SourceRange};
use crate::{
Origin,
directive::{Directive, DirectiveKind},
expand::{Diagnostic, ExpandedToken, expand},
guard::Branch,
macros::{MacroBindings, MacroTable},
token::is_trivia,
};
#[derive(Debug, Clone, Default)]
pub struct CookedStream {
pub tokens: Vec<ExpandedToken>,
pub diagnostics: Vec<Diagnostic>,
pub messages: Vec<(DirectiveKind, String, usize)>,
pub inactive: Vec<SourceRange>,
pub assumed_undefined: usize,
pub exhausted: bool,
pub pragma_lines: Vec<std::ops::Range<usize>>,
}
impl CookedStream {
pub fn is_empty(&self) -> bool {
self.tokens.is_empty()
}
pub fn plain(&self) -> Vec<crate::token::Token> {
self.tokens.iter().map(|it| it.token.clone()).collect()
}
pub fn spellings(&self) -> String {
self.tokens
.iter()
.map(|it| it.token.text())
.collect::<Vec<_>>()
.join(" ")
}
pub fn render(&self) -> RenderedCooked {
let mut text = String::new();
let mut spans = Vec::with_capacity(self.tokens.len());
let mut lines = self.pragma_lines.iter().peekable();
let mut break_next = false;
let mut previous_source_end: Option<usize> = None;
let mut previous_cooked: Option<String> = None;
for (index, cooked) in self.tokens.iter().enumerate() {
while lines.next_if(|line| line.end <= index).is_some() {}
let starts_a_line = lines.peek().is_some_and(|line| line.start == index);
let touching = match cooked.origin {
Origin::Source => match previous_source_end {
Some(end) => end == cooked.token.range.start_offset,
None => match previous_cooked.as_deref() {
Some(previous) => !joining_would_merge(previous, cooked.token.text()),
None => false,
},
},
_ => match previous_cooked.as_deref() {
Some(previous) => !joining_would_merge(previous, cooked.token.text()),
None => false,
},
};
if !text.is_empty() {
if break_next || starts_a_line {
text.push('\n');
} else if !touching {
text.push(' ');
}
}
break_next = lines.peek().is_some_and(|line| line.end == index + 1);
previous_source_end = match cooked.origin {
Origin::Source => Some(cooked.token.range.end_offset()),
_ => None,
};
previous_cooked = Some(cooked.token.text().to_string());
let start = text.len();
text.push_str(cooked.token.text());
spans.push(RenderedSpan {
cooked: SourceRange::new(start, text.len() - start),
written: written_at(cooked),
reported: cooked.diagnostic_range(),
origin: cooked.origin.clone(),
});
}
RenderedCooked { text, spans }
}
}
fn written_at(cooked: &ExpandedToken) -> Option<SourceRange> {
match &cooked.origin {
Origin::Pasted { call_site } | Origin::Stringized { call_site } => Some(*call_site),
Origin::Source => Some(cooked.token.range),
Origin::Expanded { invocations } => match invocations.first().map(|it| it.written_in) {
Some(Some(crate::macros::MacroFile::Here)) => Some(cooked.token.range),
_ => None,
},
}
}
#[derive(Debug, Clone, Default)]
pub struct RenderedCooked {
pub text: String,
pub spans: Vec<RenderedSpan>,
}
impl RenderedCooked {
pub fn weight(&self) -> usize {
self.text.len() + self.spans.len() * std::mem::size_of::<RenderedSpan>()
}
}
fn joining_would_merge(left: &str, right: &str) -> bool {
if left.is_empty() || right.is_empty() {
return false;
}
let joined = format!("{left}{right}");
let (tokens, _) = cpp_parser::lex(&joined, &cpp_parser::LexerConfig::default());
match tokens.first() {
Some(first) => first.range.end_offset() != left.len(),
None => true,
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RenderedSpan {
pub cooked: SourceRange,
pub written: Option<SourceRange>,
pub reported: SourceRange,
pub origin: Origin,
}
impl RenderedCooked {
pub fn written_at(&self, cooked_offset: usize) -> Option<SourceRange> {
self.span_at(cooked_offset)?.written
}
pub fn reported_at(&self, cooked_offset: usize) -> Option<SourceRange> {
Some(self.span_at(cooked_offset)?.reported)
}
fn span_at(&self, cooked_offset: usize) -> Option<&RenderedSpan> {
let index = self
.spans
.partition_point(|span| span.cooked.end_offset() <= cooked_offset);
self.spans.get(index)
}
pub fn written_span(&self, cooked: SourceRange) -> Option<SourceRange> {
self.span_covering(cooked, |span| span.written)
}
pub fn reported_span(&self, cooked: SourceRange) -> Option<SourceRange> {
self.span_covering(cooked, |span| Some(span.reported))
}
fn span_covering(
&self,
cooked: SourceRange,
place: impl Fn(&RenderedSpan) -> Option<SourceRange>,
) -> Option<SourceRange> {
let first = self
.spans
.partition_point(|span| span.cooked.end_offset() <= cooked.start_offset);
let last = self
.spans
.partition_point(|span| span.cooked.start_offset < cooked.end_offset());
let chosen = self.spans[first..last]
.iter()
.filter_map(&place)
.collect::<Vec<_>>();
let start = chosen.iter().map(|range| range.start_offset).min()?;
let end = chosen.iter().map(|range| range.end_offset()).max()?;
Some(SourceRange::new(start, end.saturating_sub(start)))
}
}
struct Region {
outer_is_live: bool,
taken: bool,
live: bool,
}
pub fn cook(source: &str, tokens: &[CppTokenData]) -> CookedStream {
cook_with(source, tokens, &MacroTable::new())
}
type InForceDefinition<'a> = (&'a str, Option<std::sync::Arc<str>>, std::sync::Arc<str>);
fn definition_text(name: &str, parameters: Option<&str>, body: &str) -> String {
let head = match parameters {
Some(list) => format!("{name}{list}"),
None => name.to_string(),
};
if body.is_empty() {
head
} else {
format!("{head} {body}")
}
}
#[derive(Debug, Clone, Default)]
pub struct Configuration {
pub table: MacroTable,
pub function_like_without_parameters: usize,
pub in_force_without_a_parameter_list: usize,
pub without_a_body: usize,
pub unreadable: usize,
}
#[derive(Default)]
pub struct ParsedDefinitions {
parsed:
std::collections::HashMap<DefinitionKey, Option<std::sync::Arc<crate::macros::MacroDef>>>,
}
type DefinitionKey = (Box<str>, Option<std::sync::Arc<str>>, std::sync::Arc<str>);
impl ParsedDefinitions {
pub fn new() -> Self {
Self::default()
}
pub fn len(&self) -> usize {
self.parsed.len()
}
pub fn is_empty(&self) -> bool {
self.parsed.is_empty()
}
pub(crate) fn definition(
&mut self,
name: &str,
parameters: Option<&std::sync::Arc<str>>,
body: &std::sync::Arc<str>,
) -> Option<std::sync::Arc<crate::macros::MacroDef>> {
let key: DefinitionKey = (
Box::from(name),
parameters.cloned(),
std::sync::Arc::clone(body),
);
if let Some(known) = self.parsed.get(&key) {
return known.clone();
}
let definition =
parse_a_definition(&definition_text(name, parameters.map(|list| &**list), body))
.map(std::sync::Arc::new);
self.parsed.insert(key, definition.clone());
definition
}
}
fn parse_a_definition(text: &str) -> Option<crate::macros::MacroDef> {
let (tokens, _) = cpp_parser::lex(text, &cpp_parser::LexerConfig::default());
let range = SourceRange::new(0, text.len());
let tokens: Vec<crate::token::Token> = tokens
.iter()
.map(|token| {
crate::token::Token::new(
token.kind,
&text[token.range.start_offset..token.range.end_offset()],
token.range,
)
})
.collect();
let mut definition = crate::macros::parse_define(&tokens, range)?;
definition.written_in = None;
Some(definition)
}
pub fn configuration_from_environment(environment: &dyn cpp_parser::MacroFacts) -> Configuration {
configuration_from_environment_with(environment, true)
}
pub fn configuration_from_environment_with(
environment: &dyn cpp_parser::MacroFacts,
use_in_force_bodies: bool,
) -> Configuration {
configuration_from_environment_and(
environment,
use_in_force_bodies,
&mut ParsedDefinitions::new(),
)
}
pub fn configuration_from_environment_and(
environment: &dyn cpp_parser::MacroFacts,
use_in_force_bodies: bool,
parsed: &mut ParsedDefinitions,
) -> Configuration {
let usable =
|function_like: Option<bool>, parameters: Option<&std::sync::Arc<str>>| match function_like
{
Some(false) => true,
Some(true) => parameters.is_some(),
None => false,
};
let mut in_force: Vec<InForceDefinition<'_>> = Vec::new();
let mut bodies_in_force = 0usize;
environment.for_each_body_in_force(&mut |facts| {
bodies_in_force += 1;
if use_in_force_bodies && usable(facts.function_like, facts.parameters) {
in_force.push((
facts.name,
facts.parameters.cloned(),
std::sync::Arc::clone(facts.body),
));
}
});
let mut out = Configuration {
in_force_without_a_parameter_list: bodies_in_force - in_force.len(),
..Configuration::default()
};
environment.for_each_definition(&mut |facts| {
let usable = !facts.function_like || facts.parameters.is_some();
if !usable {
out.function_like_without_parameters += 1;
return;
}
let Some(body) = facts.body_text else {
out.without_a_body += 1;
return;
};
match parsed.definition(facts.name, facts.parameters, body) {
Some(definition) => out.table.define_shared_at(definition, facts.at),
None => out.unreadable += 1,
}
});
for (name, parameters, body) in in_force {
match parsed.definition(name, parameters.as_ref(), &body) {
Some(definition) => out.table.define_shared_at(definition, 0),
None => out.unreadable += 1,
}
}
out
}
pub struct FileMacros<'unit> {
view: crate::MacroView<'unit>,
definitions: &'unit crate::UnitDefinitions,
seed: Option<&'unit MacroTable>,
use_in_force_bodies: bool,
}
impl<'unit> FileMacros<'unit> {
pub fn new(
view: crate::MacroView<'unit>,
definitions: &'unit crate::UnitDefinitions,
seed: Option<&'unit MacroTable>,
use_in_force_bodies: bool,
) -> Self {
FileMacros {
view,
definitions,
seed,
use_in_force_bodies,
}
}
fn in_force(&self, name: &str) -> Option<&'unit std::sync::Arc<crate::macros::MacroDef>> {
if !self.use_in_force_bodies {
return None;
}
self.definitions.of(self.view.visible_body_in_force(name)?)
}
fn positional(
&self,
name: &str,
) -> Option<(usize, &'unit std::sync::Arc<crate::macros::MacroDef>)> {
let (at, index) = self.view.visible_binding(name)?;
Some((at, self.definitions.of(index)?))
}
}
impl crate::macros::MacroBindings for FileMacros<'_> {
fn definition_at(&self, name: &str, offset: usize) -> Option<&crate::macros::MacroDef> {
let found = self.definition_at_traced(name, offset);
if let Some(wanted) = crate::probes::macro_name()
&& wanted == name
{
match &found {
None => {
let in_force = self.in_force(name).map(|_| "yes").unwrap_or("no");
let positional = match self.view.visible_binding(name) {
None => "no-binding".to_string(),
Some((at, index)) => format!(
"binding@{} definition={}",
at,
if self.definitions.of(index).is_some() {
"yes"
} else {
"NO"
}
),
};
let seed = self
.seed
.and_then(|seed| seed.definition(name))
.map(|_| "yes")
.unwrap_or("no");
eprintln!(
"cppls-macro: {name} at {offset} -> not defined (in_force={in_force} positional={positional} seed={seed})"
);
}
Some(definition) => {
let body: Vec<&str> = definition
.body
.significant()
.map(|token| token.text())
.collect();
let params: Vec<&str> = definition
.params
.as_ref()
.map(|list| list.iter().map(|held| held.name.as_ref()).collect())
.unwrap_or_default();
eprintln!(
"cppls-macro: {name} at {offset} -> function_like={} params={params:?} body={:?}",
definition.params.is_some(),
body.join(" ")
);
}
}
}
found
}
fn definition(&self, name: &str) -> Option<&crate::macros::MacroDef> {
self.definition_at(name, usize::MAX)
}
}
impl FileMacros<'_> {
fn definition_at_traced(&self, name: &str, offset: usize) -> Option<&crate::macros::MacroDef> {
if let Some(definition) = self.in_force(name) {
return Some(definition);
}
if let Some((at, definition)) = self.positional(name)
&& at <= offset
{
return Some(definition);
}
self.seed?.definition_at(name, offset)
}
}
impl cpp_parser::MacroBodies for FileMacros<'_> {
fn body_at(&self, name: &str, at: usize) -> Option<std::borrow::Cow<'_, str>> {
let definition = crate::macros::MacroBindings::definition_at(self, name, at)?;
let mut spelling = String::new();
for token in definition.body.significant() {
if !spelling.is_empty() {
spelling.push(' ');
}
spelling.push_str(&token.text);
}
Some(std::borrow::Cow::Owned(spelling))
}
}
struct Live<'base> {
own: MacroTable,
base: &'base dyn crate::macros::MacroBindings,
pushed: Vec<(String, Option<std::sync::Arc<crate::macros::MacroDef>>)>,
search: Option<&'base dyn HeaderSearch>,
directory: &'base Path,
}
impl crate::macros::MacroBindings for Live<'_> {
fn definition_at(&self, name: &str, offset: usize) -> Option<&crate::macros::MacroDef> {
self.own
.definition_at(name, offset)
.or_else(|| self.base.definition_at(name, offset))
}
fn definition(&self, name: &str) -> Option<&crate::macros::MacroDef> {
self.own
.definition(name)
.or_else(|| self.base.definition(name))
}
}
impl crate::condition::MacroValues for Live<'_> {
fn lookup(&self, name: &str) -> crate::condition::Lookup<'_> {
match self.definition(name) {
Some(definition) => crate::condition::Lookup::Defined(definition),
None => crate::condition::Lookup::Undefined,
}
}
fn builtin_operator(&self, name: &str, operand: &str) -> Option<crate::condition::Value> {
use crate::condition::Value;
if name != "__has_include" {
return None;
}
let search = self.search?;
let (header, quoted) = split_a_header_operand(operand)?;
Some(if search.has(header, quoted, self.directory) {
Value::Known(1)
} else {
Value::Known(0)
})
}
}
pub struct Over<'a> {
newest: &'a dyn crate::macros::MacroBindings,
oldest: &'a dyn crate::macros::MacroBindings,
}
impl<'a> Over<'a> {
pub fn new(
newest: &'a dyn crate::macros::MacroBindings,
oldest: &'a dyn crate::macros::MacroBindings,
) -> Self {
Over { newest, oldest }
}
}
impl crate::macros::MacroBindings for Over<'_> {
fn definition_at(&self, name: &str, offset: usize) -> Option<&crate::macros::MacroDef> {
self.newest
.definition_at(name, offset)
.or_else(|| self.oldest.definition_at(name, offset))
}
fn definition(&self, name: &str) -> Option<&crate::macros::MacroDef> {
self.newest
.definition(name)
.or_else(|| self.oldest.definition(name))
}
}
pub fn attribute_support(spelling: &str) -> Option<i128> {
attribute_support_in(spelling, false)
}
pub fn attribute_support_in(spelling: &str, msvc: bool) -> Option<i128> {
let name: String = spelling.split_whitespace().collect();
if msvc {
return Some(msvc_attribute_value(&name));
}
let bare = name.strip_prefix("msvc::").unwrap_or(&name);
match bare {
"no_specializations" | "lifetimebound" | "intrinsic" | "known_semantics" | "noop_dtor" => {
Some(1)
}
"maybe_unused" => Some(0),
"clang::no_specializations" => Some(0),
_ => None,
}
}
fn msvc_attribute_value(name: &str) -> i128 {
match name {
"carries_dependency" | "noreturn" => 200809,
"deprecated" => 201309,
"fallthrough" | "maybe_unused" => 201603,
"likely" | "unlikely" => 201803,
"nodiscard" => 201907,
"assume" => 202207,
"msvc::no_unique_address"
| "msvc::forceinline"
| "msvc::forceinline_calls"
| "msvc::noinline" => 201803,
"msvc::noop_dtor" | "msvc::maybe_unused" | "msvc::no_tls_guard" => 201603,
"msvc::lifetimebound" => 202302,
"msvc::intrinsic" => 202210,
"msvc::known_semantics" | "msvc::flatten" | "msvc::constexpr" => 202002,
"msvc::no_specializations" => 202412,
"gsl::suppress" => 1,
_ => 0,
}
}
pub trait HeaderSearch {
fn has(&self, name: &str, quoted: bool, directory: &Path) -> bool;
}
pub fn split_a_header_operand(operand: &str) -> Option<(&str, bool)> {
if let Some(inner) = operand
.strip_prefix('<')
.and_then(|rest| rest.strip_suffix('>'))
{
return (!inner.is_empty()).then_some((inner, false));
}
if let Some(inner) = operand
.strip_prefix('"')
.and_then(|rest| rest.strip_suffix('"'))
{
return (!inner.is_empty()).then_some((inner, true));
}
None
}
pub struct Search<'a, F: crate::file::paths::FileProvider> {
files: &'a F,
config: &'a crate::include::config::CompilerConfig,
}
impl<'a, F: crate::file::paths::FileProvider> Search<'a, F> {
pub fn new(files: &'a F, config: &'a crate::include::config::CompilerConfig) -> Self {
Search { files, config }
}
}
impl<F: crate::file::paths::FileProvider> HeaderSearch for Search<'_, F> {
fn has(&self, name: &str, quoted: bool, directory: &Path) -> bool {
use crate::file::paths::join_normalized;
let wanted = Path::new(name);
let case_insensitive = cfg!(windows);
if wanted.is_absolute() {
return self.files.exists(wanted);
}
if quoted
&& self
.files
.exists(&join_normalized(directory, wanted, case_insensitive))
{
return true;
}
self.config.include_paths.iter().any(|path| {
self.files
.exists(&join_normalized(&path.directory, wanted, case_insensitive))
})
}
}
pub fn cook_with(
source: &str,
tokens: &[CppTokenData],
initial: &dyn crate::macros::MacroBindings,
) -> CookedStream {
cook_with_search(source, tokens, initial, None, Path::new(""))
}
pub fn cook_with_search(
source: &str,
tokens: &[CppTokenData],
initial: &dyn crate::macros::MacroBindings,
search: Option<&dyn HeaderSearch>,
directory: &Path,
) -> CookedStream {
let directives = crate::directive::scan_directives(source, tokens);
let mut live = Live {
own: MacroTable::new(),
base: initial,
pushed: Vec::new(),
search,
directory,
};
let mut regions: Vec<Region> = Vec::new();
let mut out = CookedStream::default();
let mut run_from = 0usize;
let mut directive_index = 0usize;
for token_index in 0..=tokens.len() {
let is_a_directive = directives
.get(directive_index)
.is_some_and(|spanned| spanned.range.start_offset == token_start(tokens, token_index));
if !is_a_directive {
continue;
}
let spanned = &directives[directive_index];
let was_live = is_live(®ions);
if run_from < token_index {
if was_live {
expand_run(source, tokens, run_from, token_index, &live, &mut out);
} else {
let span = span_of(tokens, run_from, token_index);
merge_span(&mut out.inactive, span);
}
}
let kind = spanned.directive.kind();
match kind {
DirectiveKind::If | DirectiveKind::Ifdef | DirectiveKind::Ifndef => {
let holds = decide(
&spanned.directive,
spanned.range,
&live,
tokens,
token_index,
);
regions.push(Region {
outer_is_live: was_live,
taken: holds == Some(true),
live: was_live && holds == Some(true),
});
if holds.is_none()
|| rests_on_an_undefined_name(&spanned.directive, &live, token_index, tokens)
{
out.assumed_undefined += 1;
}
}
DirectiveKind::Elif => {
let holds = decide(
&spanned.directive,
spanned.range,
&live,
tokens,
token_index,
);
if let Some(region) = regions.last_mut() {
region.live = region.outer_is_live && !region.taken && holds == Some(true);
if holds == Some(true) {
region.taken = true;
}
}
if holds.is_none()
|| rests_on_an_undefined_name(&spanned.directive, &live, token_index, tokens)
{
out.assumed_undefined += 1;
}
}
DirectiveKind::Else => {
if let Some(region) = regions.last_mut() {
region.live = region.outer_is_live && !region.taken;
region.taken = true;
}
}
DirectiveKind::Endif => {
regions.pop();
}
DirectiveKind::Define => {
if was_live
&& let Directive::Define(define) = &spanned.directive
&& let Some(definition) = &define.macro_def
{
live.own.define(definition.clone());
}
}
DirectiveKind::Undef => {
if was_live && let Directive::Undef { name: Some(name) } = &spanned.directive {
live.own.undefine(name, spanned.range.start_offset);
}
}
DirectiveKind::Error | DirectiveKind::Warning => {
if was_live && let Directive::Diagnostic { kind, message } = &spanned.directive {
out.messages
.push((*kind, message.clone(), spanned.range.start_offset));
}
}
DirectiveKind::Pragma if was_live => {
let first = tokens
.partition_point(|token| token.range.start_offset < spanned.range.start_offset);
let last = tokens
.partition_point(|token| token.range.start_offset < spanned.range.end_offset());
if !push_and_pop_macro(spanned, source, spanned.range.start_offset, &mut live) {
let before = out.tokens.len();
expand_run(source, tokens, first, last, &live, &mut out);
if out.tokens.len() > before {
out.pragma_lines.push(before..out.tokens.len());
}
}
}
_ => {}
}
if !was_live || !is_live(®ions) {
merge_span(&mut out.inactive, spanned.range);
}
directive_index += 1;
run_from = token_index_after(tokens, spanned.range.end_offset());
}
if run_from < tokens.len() {
if is_live(®ions) {
expand_run(source, tokens, run_from, tokens.len(), &live, &mut out);
} else {
let span = span_of(tokens, run_from, tokens.len());
merge_span(&mut out.inactive, span);
}
}
out
}
fn is_live(regions: &[Region]) -> bool {
regions.last().is_none_or(|region| region.live)
}
fn push_and_pop_macro(
spanned: &crate::directive::SpannedDirective,
source: &str,
at: usize,
live: &mut Live<'_>,
) -> bool {
let crate::directive::Directive::Pragma { tokens } = &spanned.directive else {
return false;
};
let mut spelled: Vec<&str> = tokens
.iter()
.map(|token| token.text())
.filter(|text| !text.is_empty())
.collect();
let Some(kind) = spelled.first().copied() else {
return false;
};
spelled.retain(|text| *text != "(" && *text != ")");
let Some(name) = spelled.get(1).copied().map(unquote_a_pragma_name) else {
return false;
};
if name.is_empty() {
return false;
}
match kind {
"push_macro" => {
let saved = live
.definition_at(&name, at)
.map(|definition| std::sync::Arc::new(definition.clone()));
match &saved {
Some(definition) => live.own.define_shared(std::sync::Arc::clone(definition)),
None => live.own.undefine(&name, at),
}
live.pushed.push((name, saved));
true
}
"pop_macro" => {
let found = live
.pushed
.iter()
.rposition(|(pushed, _)| *pushed == name)
.map(|index| live.pushed.remove(index));
let Some((_, saved)) = found else {
let _ = source;
return true;
};
match saved {
Some(definition) => live.own.define_shared(definition),
None => live.own.undefine(&name, at),
}
true
}
_ => false,
}
}
fn unquote_a_pragma_name(spelling: &str) -> String {
spelling
.strip_prefix('"')
.and_then(|rest| rest.strip_suffix('"'))
.unwrap_or(spelling)
.to_string()
}
fn token_index_after(tokens: &[CppTokenData], offset: usize) -> usize {
tokens.partition_point(|token| token.range.start_offset < offset)
}
fn token_start(tokens: &[CppTokenData], index: usize) -> usize {
tokens
.get(index)
.map_or(usize::MAX, |token| token.range.start_offset)
}
fn span_of(tokens: &[CppTokenData], from: usize, to: usize) -> SourceRange {
match (tokens.get(from), tokens.get(to.saturating_sub(1))) {
(Some(first), Some(last)) => SourceRange::new(
first.range.start_offset,
last.range
.end_offset()
.saturating_sub(first.range.start_offset),
),
_ => SourceRange::new(0, 0),
}
}
fn merge_span(spans: &mut Vec<SourceRange>, span: SourceRange) {
match spans.last_mut() {
Some(last) if last.end_offset() >= span.start_offset => {
let start = last.start_offset;
let end = last.end_offset().max(span.end_offset());
*last = SourceRange::new(start, end.saturating_sub(start));
}
_ => spans.push(span),
}
}
fn decide(
directive: &Directive,
range: SourceRange,
live: &dyn crate::macros::MacroBindings,
tokens: &[CppTokenData],
token_index: usize,
) -> Option<bool> {
let branch = branch_of(directive, range)?;
let offset = token_start(tokens, token_index);
let macros = crate::preprocess::PositionalMacros {
table: live,
offset,
};
branch.holds(¯os)
}
fn rests_on_an_undefined_name(
directive: &Directive,
live: &dyn crate::macros::MacroBindings,
token_index: usize,
tokens: &[CppTokenData],
) -> bool {
let offset = token_start(tokens, token_index);
let unknown = |name: &str| live.definition_at(name, offset).is_none();
match directive {
Directive::Ifdef { name, .. } => unknown(name),
Directive::Conditional { condition, .. } => condition.iter().any(|token| {
token.is_identifier()
&& !matches!(token.text(), "defined" | "true" | "false")
&& unknown(token.text())
}),
_ => false,
}
}
fn branch_of(directive: &Directive, range: SourceRange) -> Option<Branch> {
use crate::directive::DirectiveKind as Kind;
let kind: Kind = directive.kind();
if !(kind.opens_a_condition() || kind.closes_a_condition()) {
return None;
}
let (tokens, name) = match directive {
Directive::Conditional { condition, .. } => (condition.clone(), None),
Directive::Ifdef { name, .. } => (Vec::new(), Some(name.clone())),
_ => (Vec::new(), None),
};
Some(Branch::new(kind, tokens, name, range))
}
fn expand_run(
source: &str,
tokens: &[CppTokenData],
from: usize,
to: usize,
live: &dyn crate::macros::MacroBindings,
out: &mut CookedStream,
) {
let run = crate::directive::to_tokens(source, &tokens[from..to]);
let offset = token_start(tokens, from);
let macros = crate::preprocess::PositionalMacros {
table: live,
offset,
};
let expansion = expand(&run, ¯os);
out.diagnostics.extend(expansion.diagnostics);
out.exhausted |= expansion.exhausted;
out.tokens.extend(
expansion
.tokens
.into_iter()
.filter(|token| !is_trivia(token.token.kind)),
);
}