using System.Diagnostics.CodeAnalysis;
using java.util;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using JavaAst = com.github.javaparser.ast;
namespace JavaToCSharp;
public static class Extensions
{
///
/// Converts a Java Iterable to a .NET IEnumerable<T> and filters the elements of type T.
///
/// Type of items to be returned.
/// The java Iterable to be enumerated.
/// A filtered enumeration of items of type T
public static IEnumerable OfType(this java.lang.Iterable iterable)
{
var iterator = iterable.iterator();
while (iterator.hasNext())
{
if (iterator.next() is T item)
{
yield return item;
}
}
}
public static List? ToList(this java.util.List? list)
{
if (list == null)
return null;
var newList = new List();
for (int i = 0; i < list.size(); i++)
{
newList.Add((T)list.get(i));
}
return newList;
}
public static bool HasFlag(this java.util.EnumSet values, T flag) => values.contains(flag);
[return: NotNullIfNotNull(nameof(node))]
public static TSyntax? WithJavaComments(this TSyntax? syntax,
ConversionContext context,
JavaAst.Node? node)
where TSyntax : SyntaxNode
=> context.Options.IncludeComments
? CommentsHelper.AddCommentsTrivias(syntax, node)
: syntax;
public static CompilationUnitSyntax WithPackageFileComments(this CompilationUnitSyntax syntax,
ConversionContext context,
JavaAst.CompilationUnit compilationUnit,
JavaAst.PackageDeclaration? packageDeclaration)
=> context.Options.IncludeComments
? CommentsHelper.AddPackageComments(syntax, compilationUnit, packageDeclaration)
: syntax;
public static T? FromOptional(this Optional optional)
where T : class
=> optional.isPresent()
? optional.get() as T ??
throw new InvalidOperationException($"Optional did not convert to {typeof(T)}")
: null;
public static T FromRequiredOptional(this Optional optional)
where T : class
=> optional.isPresent()
? optional.get() as T ??
throw new InvalidOperationException($"Optional did not convert to {typeof(T)}")
: throw new InvalidOperationException("Required optional did not have a value");
public static ISet ToModifierKeywordSet(this JavaAst.NodeList nodeList)
=> nodeList.ToList()?.Select(i => i.getKeyword()).ToHashSet()
?? new HashSet();
public static TSyntax WithLeadingNewLines(this TSyntax syntax, int count = 1)
where TSyntax : SyntaxNode
=> syntax.WithLeadingTrivia(Enumerable.Repeat(Whitespace.NewLine, count));
public static TSyntax WithTrailingNewLines(this TSyntax syntax, int count = 1)
where TSyntax : SyntaxNode
=> syntax.WithTrailingTrivia(Enumerable.Repeat(Whitespace.NewLine, count));
}