using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using CppSharp.AST;
namespace CppSharp.Generators
{
///
/// Kinds of language generators.
///
public enum GeneratorKind
{
CLI,
CSharp,
}
///
/// Output generated by each backend generator.
///
public struct GeneratorOutput
{
///
/// Translation unit associated with output.
///
public TranslationUnit TranslationUnit;
///
/// Text templates with generated output.
///
public List Templates;
}
///
/// Generators are the base class for each language backend.
///
public abstract class Generator : IDisposable
{
public static string CurrentOutputNamespace = string.Empty;
public Driver Driver { get; private set; }
protected Generator(Driver driver)
{
Driver = driver;
CppSharp.AST.Type.TypePrinterDelegate += TypePrinterDelegate;
}
///
/// Called when a translation unit is generated.
///
public Action OnUnitGenerated = delegate { };
///
/// Setup any generator-specific passes here.
///
public abstract bool SetupPasses();
///
/// Setup any generator-specific processing here.
///
public virtual void Process()
{
}
///
/// Generates the outputs.
///
public virtual List Generate()
{
var outputs = new List();
var units = Driver.ASTContext.TranslationUnits.Where(
u => u.IsGenerated && u.HasDeclarations && !u.IsSystemHeader && u.IsValid).ToList();
if (Driver.Options.IsCSharpGenerator && Driver.Options.GenerateSingleCSharpFile)
GenerateSingleTemplate(outputs);
else
GenerateTemplates(outputs, units);
return outputs;
}
private void GenerateTemplates(List outputs, List units)
{
foreach (var unit in units)
{
var includeDir = Path.GetDirectoryName(unit.FilePath);
var templates = Generate(new[] { unit });
if (templates.Count == 0)
return;
CurrentOutputNamespace = unit.Module.OutputNamespace;
foreach (var template in templates)
{
template.Process();
}
var output = new GeneratorOutput
{
TranslationUnit = unit,
Templates = templates
};
outputs.Add(output);
OnUnitGenerated(output);
}
}
private void GenerateSingleTemplate(ICollection outputs)
{
foreach (var module in Driver.Options.Modules)
{
CurrentOutputNamespace = module.OutputNamespace;
var output = new GeneratorOutput
{
TranslationUnit = new TranslationUnit
{
FilePath = string.Format("{0}.cs", module.OutputNamespace ?? module.LibraryName),
Module = module
},
Templates = Generate(module.Units)
};
output.Templates[0].Process();
outputs.Add(output);
OnUnitGenerated(output);
}
}
///
/// Generates the outputs for a given translation unit.
///
public abstract List Generate(IEnumerable units);
protected abstract string TypePrinterDelegate(CppSharp.AST.Type type);
public static string GeneratedIdentifier(string id)
{
return "__" + id;
}
public void Dispose()
{
CppSharp.AST.Type.TypePrinterDelegate -= TypePrinterDelegate;
}
}
}