fix(compiler-cli): validate host directive in local compilation

Matches ngtsc's validation for host directives in the preprocessor.
This commit is contained in:
Kristiyan Kostadinov
2026-10-29 22:35:52 +01:00
committed by Kristiyan Kostadinov
parent 47edfd51a2
commit 323495c2ec
5 changed files with 139 additions and 26 deletions
@@ -273,7 +273,7 @@ pub struct DirectiveData {
/// Stage 2 can chase cross-file arrays and aliases before it is projected onto the wire.
pub host_directives: Option<Resolved<Vec<HostDirectiveEntry>>>,
pub host_directives_span: Option<oxc_span::Span>,
pub unsupported_host_directive_spans: Vec<oxc_span::Span>,
pub unsupported_host_directives: Vec<(Resolved<()>, oxc_span::Span)>,
/// The directive's own `hostDirectives`, resolved in stage 2 — what ngtsc's
/// `TypeCheckScopeRegistry` puts in `directivesOnHost` ahead of the directive itself when
/// type-checking its host bindings. Components keep theirs on
@@ -431,6 +431,29 @@ async fn complete_style_urls<Fs: crate::ResourceResolverFs + Clone + 'static>(
}
}
/// In non-`emitDeclarationOnly` local compilation, ngtsc still runs the partial evaluator over
/// `hostDirectives`, so expressions like `forwardRef(() => DepA)` that resolve within the
/// compilation unit succeed while unresolved external expressions remain dynamic and report NG11003.
async fn complete_unsupported_host_directives<Fs: crate::ResourceResolverFs + Clone + 'static>(
entries: &mut Vec<(Resolved<()>, oxc_span::Span)>,
ctx: &crate::query::QueryContext<Fs>,
foreign: &[&dyn crate::evaluator::ForeignFunctionResolver],
) {
if entries.is_empty() {
return;
}
for (probe, _) in entries.iter_mut() {
probe.complete_with(ctx, foreign).await;
}
entries.retain(|(probe, _)| {
matches!(
probe.raw().unwrap_named(),
crate::evaluator::ResolvedValue::Dynamic(_)
| crate::evaluator::ResolvedValue::Incomplete(_)
)
});
}
/// Stage 2 for a `templateUrl` that named a constant from another file: complete the
/// expression, then read the template exactly as Stage 1 reads a literal URL — still relative
/// to the component's own file, not to the file declaring the constant, as ngtsc's
@@ -482,7 +505,7 @@ impl Default for DirectiveData {
host_properties: Vec::new(),
host_directives: None,
host_directives_span: None,
unsupported_host_directive_spans: Vec::new(),
unsupported_host_directives: Vec::new(),
resolved_host_directives: None,
host_directive_diagnostics: Vec::new(),
providers_span: None,
@@ -1753,6 +1776,14 @@ impl ClassData {
if let Some(template) = &mut c.template {
template.complete_with(ctx, foreign).await;
}
if !ctx.engine.emit_declaration_only {
complete_unsupported_host_directives(
&mut c.directive.unsupported_host_directives,
ctx,
foreign,
)
.await;
}
}
DecoratorData::Directive(d) => {
if let Some(export_as) = &mut d.export_as {
@@ -1764,6 +1795,14 @@ impl ClassData {
for name in d.host_listener_event_names_mut() {
name.complete_with(ctx, foreign).await;
}
if !ctx.engine.emit_declaration_only {
complete_unsupported_host_directives(
&mut d.unsupported_host_directives,
ctx,
foreign,
)
.await;
}
}
_ => {}
}
@@ -2680,22 +2719,26 @@ impl ClassData {
converter: &crate::utils::Utf8ToUtf16,
diagnostics: &mut Vec<crate::NgDiagnostic>,
) {
if cx.emit_declaration_only {
for span in &d.unsupported_host_directive_spans {
if cx.emit_declaration_only || cx.mode != WireMode::Semantic {
let mode_name = if cx.emit_declaration_only {
"experimental declaration-only emission"
} else {
"local compilation"
};
for (_, span) in &d.unsupported_host_directives {
push_error(
diagnostics,
file_path,
converter,
"11003",
*span,
"In experimental declaration-only emission mode, host directive cannot be an expression. Use an identifier instead".to_string(),
format!(
"In {mode_name} mode, host directive cannot be an expression. Use an identifier instead"
),
);
}
return;
}
if cx.mode != WireMode::Semantic {
return;
}
if let (Some(host_directives), Some(span)) = (&d.host_directives, d.host_directives_span) {
// A lingering hole means the value was never completed (e.g. a poisoned file);
// its entries can't be judged either way.
@@ -4564,7 +4607,9 @@ impl ClassData {
d: &DirectiveData,
cx: &WireContext,
) -> Option<Vec<HostDirectiveMetadata>> {
if cx.emit_declaration_only && !d.unsupported_host_directive_spans.is_empty() {
if (cx.emit_declaration_only || cx.mode != WireMode::Semantic)
&& !d.unsupported_host_directives.is_empty()
{
return None;
}
let slot = d.host_directives.as_ref()?;
@@ -155,8 +155,8 @@ pub fn extract_directive_metadata<'a>(
"hostDirectives" => {
// Evaluated via the partial evaluator (`extractHostDirectives` in ngtsc `shared.ts`).
let evaluated = evaluate_expression(&p.value, eval);
data.unsupported_host_directive_spans =
extract_unsupported_host_directive_spans(&evaluated, semantic);
data.unsupported_host_directives =
extract_unsupported_host_directives(&evaluated, semantic, eval.file);
data.host_directives = Some(Resolved::from_syntax(evaluated, eval.file));
data.host_directives_span = Some(p.value.span());
}
@@ -223,26 +223,28 @@ fn fold_or_defer_io_array(data: &mut DirectiveData, array: IoMetadataArray) {
.push(array);
}
/// Spans of `hostDirectives` entries that resolve to an external reference (`Incomplete`) via an
/// Entries in `hostDirectives` that evaluate to an external reference (`Incomplete`) via an
/// expression other than a plain identifier or static property access (rejected in local and
/// `emitDeclarationOnly` compilation modes by ngtsc's `extractHostDirectives`).
fn extract_unsupported_host_directive_spans(
/// `emitDeclarationOnly` compilation modes by ngtsc's `extractHostDirectives` when unresolved).
fn extract_unsupported_host_directives(
evaluated: &ResolvedValue,
semantic: &Semantic<'_>,
) -> Vec<oxc_span::Span> {
origin: crate::query::FileId,
) -> Vec<(Resolved<()>, oxc_span::Span)> {
let ResolvedValue::Array(items) = evaluated.unwrap_named() else {
return Vec::new();
};
items
.iter()
.filter_map(|item| unsupported_host_directive_span(item, semantic))
.filter_map(|item| unsupported_host_directive_entry(item, semantic, origin))
.collect()
}
fn unsupported_host_directive_span(
fn unsupported_host_directive_entry(
item: &ResolvedValue,
semantic: &Semantic<'_>,
) -> Option<oxc_span::Span> {
origin: crate::query::FileId,
) -> Option<(Resolved<()>, oxc_span::Span)> {
let dir_val = match item.unwrap_named() {
ResolvedValue::Map(map) => map.get("directive")?,
other => other,
@@ -261,7 +263,7 @@ fn unsupported_host_directive_span(
if is_supported {
return None;
}
if hole.synthetic {
let span = if hole.synthetic {
let call_span = hole.node_id.and_then(|id| {
semantic.nodes().ancestors(id).find_map(|ancestor| {
let oxc_ast::AstKind::CallExpression(call) = ancestor.kind() else {
@@ -270,9 +272,11 @@ fn unsupported_host_directive_span(
Some(call.span)
})
});
return Some(call_span.unwrap_or(hole.span));
}
Some(hole.span)
call_span.unwrap_or(hole.span)
} else {
hole.span
};
Some((Resolved::from_syntax(dir_val.clone(), origin), span))
}
/// The transforms of the `inputs` entries written in place as object literals, keyed by the
@@ -7534,3 +7534,69 @@ fn test_ambient_constructors_and_injectable_options() {
]
);
}
#[test]
fn test_local_compilation_unsupported_host_directive_expression() {
let source = r#"
import { Component, forwardRef } from '@angular/core';
import { ExternalDirective } from 'some_where';
import { KnownDirective } from './known';
@Component({
selector: 'bad-comp',
template: '',
hostDirectives: [forwardRef(() => ExternalDirective)],
})
export class BadComp {}
@Component({
selector: 'good-comp',
template: '',
hostDirectives: [forwardRef(() => KnownDirective)],
})
export class GoodComp {}
"#;
let known = r#"
import { Directive } from '@angular/core';
@Directive({ selector: '[known]' })
export class KnownDirective {}
"#;
let mut virtual_files = HashMap::new();
virtual_files.insert("/project/app.ts".to_string(), source.to_string());
virtual_files.insert("/project/known.ts".to_string(), known.to_string());
virtual_files.insert(
"/project/tsconfig.json".to_string(),
r#"{"files": ["app.ts", "known.ts"]}"#.to_string(),
);
let analyzer = Analyzer::new(AnalyzerOptions {
tsconfig_path: Some("/project/tsconfig.json".to_string()),
optimize: Some(false),
virtual_files: Some(virtual_files),
..Default::default()
})
.unwrap();
let iterator = analyzer.analyze().unwrap();
let mut app_meta = None;
while let Some(chunk) = futures::executor::block_on(iterator.next()).unwrap() {
for file in chunk.files {
if file.file_path == "/project/app.ts" {
app_meta = Some(file);
}
}
}
let meta = app_meta.expect("app.ts metadata");
assert_eq!(meta.diagnostics.len(), 1, "{:?}", meta.diagnostics);
let diag = &meta.diagnostics[0];
assert_eq!(diag.code, 11003);
assert_eq!(
diag.message_text,
"In local compilation mode, host directive cannot be an expression. Use an identifier instead"
);
let span = diag.span.as_ref().expect("span");
assert_eq!(
&source[span.start as usize..span.end as usize],
"forwardRef(() => ExternalDirective)"
);
assert!(meta.classes[0].component.as_ref().unwrap().host_directives.is_none());
assert!(meta.classes[1].component.as_ref().unwrap().host_directives.is_some());
}
@@ -317,8 +317,6 @@ const NGP_KNOWN_NGTSC_FAILURES: ReadonlySet<string> = new Set([
'import generation should report an error when a library entry-point does not export the symbol',
'import generation should report an error when using a directive outside of rootDirs',
'local compilation custom decorator should produce diagnostic for each custom decorator',
'local compilation host directives should generate component hostDirectives definition without input and output',
'local compilation host directives should produce fatal diagnostics for host directives with forward references of externally imported directive',
'local compilation input transform should not check inline function param type',
'ngtsc @defer block @Component.deferredImports block-specific deferredImports mapping should report error when defer block has no name parameter but deferredImports is an object',
'ngtsc @defer block @Component.deferredImports block-specific deferredImports mapping should report error when name parameter references missing block in deferredImports',
@@ -1928,8 +1928,8 @@ runInEachFileSystem(() => {
env.driveMain();
const jsContents = env.getContents('test.js');
expect(jsContents).toContain(
'features: [i0.ɵɵHostDirectivesFeature([ExternalDirective, n.ExternalDirective, LocalDirective])]',
expect(jsContents).toMatch(
/features: \[i0\.ɵɵHostDirectivesFeature\(\[ExternalDirective, \w+\.ExternalDirective, LocalDirective\]\)\]/,
);
});