/* ========================================================================
* Copyright (c) 2005-2025 The OPC Foundation, Inc. All rights reserved.
*
* OPC Foundation MIT License 1.00
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* The complete license agreement can be found here:
* http://opcfoundation.org/License/MIT/1.00/
* ======================================================================*/
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using NUnit.Framework;
namespace Opc.Ua.SourceGeneration
{
///
/// A pooled structure deriving from a structure of another model's
/// assembly must not depend on members only the current generator
/// emits into that assembly.
///
[TestFixture]
[Category("SourceGeneration")]
[SetCulture("en-us")]
[SetUICulture("en-us")]
public class CrossModelPooledStructureTests
{
///
/// E-1: the derived pooled extension overrides and calls
/// base.ResetForReuse(), which a base structure generated by an
/// older generator does not have (CS0115/CS0117). A base from
/// another model now gets the variant that relies only on Reuse().
/// E-2: the same holds for the virtual ReuseCore(), and the variant
/// has to compile against a current base that declares it too.
///
[TestCase(true)]
[TestCase(false)]
public void DerivedStructureCompilesAgainstBaseWithoutResetForReuse(bool olderProducer)
{
CSharpCompilation producer = GenerateProducerWithoutResetForReuse(olderProducer);
CSharpCompilation consumer = ModelDependencyScannerTests
.CreateStackCompilation("PooledConsumer")
.AddReferences(producer.ToMetadataReference());
GeneratorDriver driver = CreateDriver("ModelB.xml", ModelBDesign);
driver = driver.RunGeneratorsAndUpdateCompilation(
consumer,
out Compilation output,
out ImmutableArray diagnostics);
Assert.That(diagnostics.Where(d => d.Severity == DiagnosticSeverity.Error), Is.Empty);
string generated = string.Join(
"\n",
driver.GetRunResult().Results[0].GeneratedSources.Select(s => s.SourceText.ToString()));
Assert.That(generated, Does.Contain("partial class DerivedStruct"));
Assert.That(generated, Does.Not.Contain("base.ResetForReuse()"));
Assert.That(
output.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error),
Is.Empty,
string.Join(Environment.NewLine, output.GetDiagnostics()));
}
///
/// Generates ModelA and strips the overridable ResetForReuse() from
/// its pooled extension, which is what a ModelA assembly built by
/// the previous generator looks like.
///
private static CSharpCompilation GenerateProducerWithoutResetForReuse(bool olderProducer)
{
CSharpCompilation compilation = ModelDependencyScannerTests
.CreateStackCompilation("PooledProducer");
GeneratorDriver driver = CreateDriver("ModelA.xml", ModelADesign);
driver = driver.RunGeneratorsAndUpdateCompilation(
compilation,
out Compilation _,
out ImmutableArray diagnostics);
Assert.That(diagnostics.Where(d => d.Severity == DiagnosticSeverity.Error), Is.Empty);
CSharpParseOptions parseOptions = new CSharpParseOptions()
.WithKind(SourceCodeKind.Regular)
.WithLanguageVersion(LanguageVersion.CSharp11);
bool stripped = false;
foreach (GeneratedSourceResult source in driver.GetRunResult().Results[0].GeneratedSources)
{
string text = source.SourceText.ToString();
if (olderProducer &&
text.Contains("protected virtual void ResetForReuse()", StringComparison.Ordinal))
{
text = text
.Replace(
"protected virtual void ResetForReuse()",
"private void OldGeneratorReset()",
StringComparison.Ordinal)
.Replace("ResetForReuse();", "OldGeneratorReset();", StringComparison.Ordinal)
.Replace(
"protected virtual void ReuseCore()",
"private void OldGeneratorReuse()",
StringComparison.Ordinal)
.Replace("ReuseCore();", "OldGeneratorReuse();", StringComparison.Ordinal);
stripped = true;
}
compilation = compilation.AddSyntaxTrees(
CSharpSyntaxTree.ParseText(text, parseOptions, source.HintName));
}
Assert.That(stripped, Is.EqualTo(olderProducer), "the producer has a pooled structure");
Assert.That(
compilation.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error),
Is.Empty,
string.Join(Environment.NewLine, compilation.GetDiagnostics()));
return compilation;
}
private static GeneratorDriver CreateDriver(string path, string design)
{
var options = new AnalyzerOptionsProvider(
new Dictionary
{
["build_property.ModelSourceGeneratorOmitFluentApi"] = "true",
["build_property.ModelSourceGeneratorOmitEventRecords"] = "true"
});
return CSharpGeneratorDriver.Create(new ModelSourceGenerator())
.WithUpdatedParseOptions(new CSharpParseOptions()
.WithKind(SourceCodeKind.Regular)
.WithLanguageVersion(LanguageVersion.CSharp11))
.AddAdditionalTexts([EmbeddedText.Create(path, design)])
.WithUpdatedAnalyzerConfigOptions(options);
}
private const string ModelADesign =
"""
http://opcfoundation.org/UA/
http://test.org/UA/PooledA/
""";
private const string ModelBDesign =
"""
http://test.org/UA/PooledB/
http://test.org/UA/PooledA/
http://opcfoundation.org/UA/
""";
}
}