Browse Source

Remove the Driver dependency from the generators with a BindingContext.

pull/696/head
Joao Matos 10 years ago
parent
commit
4e48af9a4c
  1. 57
      src/Generator/BindingContext.cs
  2. 117
      src/Generator/Driver.cs
  3. 15
      src/Generator/Generator.cs
  4. 12
      src/Generator/Generators/CLI/CLIGenerator.cs
  5. 16
      src/Generator/Generators/CLI/CLIHeaders.cs
  6. 24
      src/Generator/Generators/CLI/CLIMarshal.cs
  7. 38
      src/Generator/Generators/CLI/CLISources.cs
  8. 6
      src/Generator/Generators/CLI/CLITemplate.cs
  9. 19
      src/Generator/Generators/CLI/CLITypePrinter.cs
  10. 8
      src/Generator/Generators/CSharp/CSharpGenerator.cs
  11. 42
      src/Generator/Generators/CSharp/CSharpMarshal.cs
  12. 68
      src/Generator/Generators/CSharp/CSharpSources.cs
  13. 32
      src/Generator/Generators/CSharp/CSharpTypePrinter.cs
  14. 6
      src/Generator/Generators/Marshal.cs
  15. 17
      src/Generator/Generators/Template.cs
  16. 2
      src/Generator/Passes/CheckAbiParameters.cs
  17. 2
      src/Generator/Passes/CheckAmbiguousFunctions.cs
  18. 8
      src/Generator/Passes/CheckDuplicatedNamesPass.cs
  19. 42
      src/Generator/Passes/CheckIgnoredDecls.cs
  20. 2
      src/Generator/Passes/CheckMacrosPass.cs
  21. 6
      src/Generator/Passes/CheckOperatorsOverloads.cs
  22. 2
      src/Generator/Passes/CheckStaticClass.cs
  23. 2
      src/Generator/Passes/CheckVTableComponentsPass.cs
  24. 2
      src/Generator/Passes/CheckVirtualOverrideReturnCovariance.cs
  25. 2
      src/Generator/Passes/CleanInvalidDeclNamesPass.cs
  26. 17
      src/Generator/Passes/CleanUnitPass.cs
  27. 4
      src/Generator/Passes/ConstructorToConversionOperatorPass.cs
  28. 18
      src/Generator/Passes/DelegatesPass.cs
  29. 2
      src/Generator/Passes/FieldToPropertyPass.cs
  30. 7
      src/Generator/Passes/FindSymbolsPass.cs
  31. 4
      src/Generator/Passes/FunctionToInstanceMethodPass.cs
  32. 4
      src/Generator/Passes/FunctionToStaticMethodPass.cs
  33. 6
      src/Generator/Passes/GenerateInlinesCodePass.cs
  34. 8
      src/Generator/Passes/GenerateTemplatesCodePass.cs
  35. 12
      src/Generator/Passes/GetterSetterToPropertyAdvancedPass.cs
  36. 8
      src/Generator/Passes/GetterSetterToPropertyPass.cs
  37. 16
      src/Generator/Passes/HandleDefaultParamValuesPass.cs
  38. 2
      src/Generator/Passes/IgnoreSystemDeclarationsPass.cs
  39. 6
      src/Generator/Passes/MoveFunctionToClassPass.cs
  40. 2
      src/Generator/Passes/MoveOperatorToClassPass.cs
  41. 15
      src/Generator/Passes/ObjectOverridesPass.cs
  42. 17
      src/Generator/Passes/Pass.cs
  43. 9
      src/Generator/Passes/PassBuilder.cs
  44. 8
      src/Generator/Passes/ResolveIncompleteDeclsPass.cs
  45. 10
      src/Generator/Types/Std/Stdlib.cs

57
src/Generator/BindingContext.cs

@ -0,0 +1,57 @@
using CppSharp.AST;
using CppSharp.Generators.CLI;
using CppSharp.Generators.CSharp;
using CppSharp.Passes;
using CppSharp.Types;
using CppSharp.Parser;
using CppSharp.Utils;
using System.Collections.Generic;
namespace CppSharp.Generators
{
public class BindingContext
{
public IDiagnostics Diagnostics { get; set; }
public DriverOptions Options { get; private set; }
public ASTContext ASTContext { get; set; }
public ParserTargetInfo TargetInfo { get; set; }
public SymbolContext Symbols { get; private set; }
public TypeMapDatabase TypeDatabase { get; private set; }
public PassBuilder<TranslationUnitPass> TranslationUnitPasses { get; private set; }
public PassBuilder<GeneratorOutputPass> GeneratorOutputPasses { get; private set; }
public Dictionary<Function, DelegatesPass.DelegateDefinition> Delegates { get; private set; }
private static readonly Dictionary<string, string> libraryMappings = new Dictionary<string, string>();
public BindingContext(IDiagnostics diagnostics, DriverOptions options)
{
Options = options;
Diagnostics = diagnostics;
Symbols = new SymbolContext();
Delegates = new Dictionary<Function, DelegatesPass.DelegateDefinition>();
TypeDatabase = new TypeMapDatabase();
TypeDatabase.SetupTypeMaps(Options.GeneratorKind);
TranslationUnitPasses = new PassBuilder<TranslationUnitPass>(this);
GeneratorOutputPasses = new PassBuilder<GeneratorOutputPass>(this);
}
public void RunPasses()
{
TranslationUnitPasses.RunPasses(pass =>
{
Diagnostics.Debug("Pass '{0}'", pass);
Diagnostics.PushIndent();
pass.VisitLibrary(ASTContext);
Diagnostics.PopIndent();
});
}
}
}

117
src/Generator/Driver.cs

@ -20,36 +20,19 @@ namespace CppSharp
{ {
public class Driver public class Driver
{ {
public IDiagnostics Diagnostics { get; set; } public IDiagnostics Diagnostics { get; private set; }
public DriverOptions Options { get; private set; } public DriverOptions Options { get; private set; }
public Project Project { get; private set; } public Project Project { get; private set; }
public BindingContext Context { get; private set; }
public TypeMapDatabase TypeDatabase { get; private set; }
public PassBuilder<TranslationUnitPass> TranslationUnitPasses { get; private set; }
public PassBuilder<GeneratorOutputPass> GeneratorOutputPasses { get; private set; }
public Generator Generator { get; private set; } public Generator Generator { get; private set; }
public ASTContext ASTContext { get; private set; }
public SymbolContext Symbols { get; private set; }
public Dictionary<Function, DelegatesPass.DelegateDefinition> Delegates { get; private set; }
public bool HasCompilationErrors { get; set; } public bool HasCompilationErrors { get; set; }
private static readonly Dictionary<string, string> libraryMappings = new Dictionary<string, string>();
public Driver(DriverOptions options, IDiagnostics diagnostics) public Driver(DriverOptions options, IDiagnostics diagnostics)
{ {
Options = options; Options = options;
Diagnostics = diagnostics; Diagnostics = diagnostics;
Project = new Project(); Project = new Project();
ASTContext = new ASTContext();
Symbols = new SymbolContext();
Delegates = new Dictionary<Function, DelegatesPass.DelegateDefinition>();
TypeDatabase = new TypeMapDatabase();
TranslationUnitPasses = new PassBuilder<TranslationUnitPass>(this);
GeneratorOutputPasses = new PassBuilder<GeneratorOutputPass>(this);
} }
Generator CreateGeneratorFromKind(GeneratorKind kind) Generator CreateGeneratorFromKind(GeneratorKind kind)
@ -57,9 +40,9 @@ namespace CppSharp
switch (kind) switch (kind)
{ {
case GeneratorKind.CLI: case GeneratorKind.CLI:
return new CLIGenerator(this); return new CLIGenerator(Context);
case GeneratorKind.CSharp: case GeneratorKind.CSharp:
return new CSharpGenerator(this); return new CSharpGenerator(Context);
} }
return null; return null;
@ -81,16 +64,6 @@ namespace CppSharp
options.addIncludeDirs(incDir); options.addIncludeDirs(incDir);
} }
public void Setup()
{
ValidateOptions(Options);
SetupIncludes();
TypeDatabase.SetupTypeMaps(Options.GeneratorKind);
Generator = CreateGeneratorFromKind(Options.GeneratorKind);
}
public void SetupIncludes() public void SetupIncludes()
{ {
if (Platform.IsMacOS) if (Platform.IsMacOS)
@ -99,21 +72,12 @@ namespace CppSharp
Options.SetupMSVC(); Options.SetupMSVC();
} }
public void SortModulesByDependencies() public void Setup()
{ {
if (Options.Modules.All(m => m.Libraries.Any())) ValidateOptions(Options);
{ SetupIncludes();
var sortedModules = Options.Modules.TopologicalSort(m => Context = new BindingContext(Diagnostics, Options);
{ Generator = CreateGeneratorFromKind(Options.GeneratorKind);
return from library in Symbols.Libraries
where m.Libraries.Contains(library.FileName)
from module in Options.Modules
where library.Dependencies.Intersect(module.Libraries).Any()
select module;
});
Options.Modules.Clear();
Options.Modules.AddRange(sortedModules);
}
} }
void OnSourceFileParsed(IList<SourceFile> files, ParserResult result) void OnSourceFileParsed(IList<SourceFile> files, ParserResult result)
@ -244,9 +208,8 @@ namespace CppSharp
parser.SourcesParsed += OnSourceFileParsed; parser.SourcesParsed += OnSourceFileParsed;
parser.ParseProject(Project, Options.UnityBuild); parser.ParseProject(Project, Options.UnityBuild);
TargetInfo = parser.GetTargetInfo(Options); Context.TargetInfo = parser.GetTargetInfo(Options);
Context.ASTContext = ClangParser.ConvertASTContext(parser.ASTContext);
ASTContext = ClangParser.ConvertASTContext(parser.ASTContext);
return !hasParsingErrors; return !hasParsingErrors;
} }
@ -265,6 +228,23 @@ namespace CppSharp
public ParserTargetInfo TargetInfo { get; set; } public ParserTargetInfo TargetInfo { get; set; }
public void SortModulesByDependencies()
{
if (Options.Modules.All(m => m.Libraries.Any()))
{
var sortedModules = Options.Modules.TopologicalSort(m =>
{
return from library in Context.Symbols.Libraries
where m.Libraries.Contains(library.FileName)
from module in Options.Modules
where library.Dependencies.Intersect(module.Libraries).Any()
select module;
});
Options.Modules.Clear();
Options.Modules.AddRange(sortedModules);
}
}
public bool ParseLibraries() public bool ParseLibraries()
{ {
foreach (var module in Options.Modules) foreach (var module in Options.Modules)
@ -274,7 +254,7 @@ namespace CppSharp
foreach (var library in module.Libraries) foreach (var library in module.Libraries)
{ {
if (Symbols.Libraries.Any(l => l.FileName == library)) if (Context.Symbols.Libraries.Any(l => l.FileName == library))
continue; continue;
var parser = new ClangParser(); var parser = new ClangParser();
@ -285,18 +265,23 @@ namespace CppSharp
if (res.Kind != ParserResultKind.Success) if (res.Kind != ParserResultKind.Success)
continue; continue;
Symbols.Libraries.Add(ClangParser.ConvertLibrary(res.Library)); Context.Symbols.Libraries.Add(ClangParser.ConvertLibrary(res.Library));
res.Library.Dispose(); res.Library.Dispose();
} }
} }
} }
Context.Symbols.IndexSymbols();
SortModulesByDependencies();
return true; return true;
} }
public void SetupPasses(ILibrary library) public void SetupPasses(ILibrary library)
{ {
var TranslationUnitPasses = Context.TranslationUnitPasses;
TranslationUnitPasses.AddPass(new SortDeclarationsPass()); TranslationUnitPasses.AddPass(new SortDeclarationsPass());
TranslationUnitPasses.AddPass(new ResolveIncompleteDeclsPass()); TranslationUnitPasses.AddPass(new ResolveIncompleteDeclsPass());
if (Options.IsCSharpGenerator) if (Options.IsCSharpGenerator)
@ -365,14 +350,7 @@ namespace CppSharp
public void ProcessCode() public void ProcessCode()
{ {
TranslationUnitPasses.RunPasses(pass => Context.RunPasses();
{
Diagnostics.Debug("Pass '{0}'", pass);
Diagnostics.PushIndent(4);
pass.VisitLibrary(ASTContext);
Diagnostics.PopIndent();
});
Generator.Process(); Generator.Process();
} }
@ -415,6 +393,8 @@ namespace CppSharp
} }
} }
private static readonly Dictionary<string, string> libraryMappings = new Dictionary<string, string>();
public void CompileCode(AST.Module module) public void CompileCode(AST.Module module)
{ {
var assemblyFile = string.IsNullOrEmpty(module.LibraryName) ? var assemblyFile = string.IsNullOrEmpty(module.LibraryName) ?
@ -447,7 +427,7 @@ namespace CppSharp
var locationRuntime = Path.Combine(outputDir, "CppSharp.Runtime.dll"); var locationRuntime = Path.Combine(outputDir, "CppSharp.Runtime.dll");
compilerParameters.ReferencedAssemblies.Add(locationRuntime); compilerParameters.ReferencedAssemblies.Add(locationRuntime);
compilerParameters.ReferencedAssemblies.AddRange(Symbols.Libraries.SelectMany( compilerParameters.ReferencedAssemblies.AddRange(Context.Symbols.Libraries.SelectMany(
lib => lib.Dependencies.Where( lib => lib.Dependencies.Where(
d => libraryMappings.ContainsKey(d) && d => libraryMappings.ContainsKey(d) &&
!compilerParameters.ReferencedAssemblies.Contains(libraryMappings[d])) !compilerParameters.ReferencedAssemblies.Contains(libraryMappings[d]))
@ -480,12 +460,12 @@ namespace CppSharp
public void AddTranslationUnitPass(TranslationUnitPass pass) public void AddTranslationUnitPass(TranslationUnitPass pass)
{ {
TranslationUnitPasses.AddPass(pass); Context.TranslationUnitPasses.AddPass(pass);
} }
public void AddGeneratorOutputPass(GeneratorOutputPass pass) public void AddGeneratorOutputPass(GeneratorOutputPass pass)
{ {
GeneratorOutputPasses.AddPass(pass); Context.GeneratorOutputPasses.AddPass(pass);
} }
private bool hasParsingErrors; private bool hasParsingErrors;
@ -513,15 +493,9 @@ namespace CppSharp
if (!driver.ParseLibraries()) if (!driver.ParseLibraries())
return; return;
if (!options.Quiet)
Log.Message("Indexing library symbols...");
driver.Symbols.IndexSymbols();
if (!options.Quiet) if (!options.Quiet)
Log.Message("Parsing code..."); Log.Message("Parsing code...");
driver.SortModulesByDependencies();
driver.BuildParseOptions(); driver.BuildParseOptions();
if (!driver.ParseCode()) if (!driver.ParseCode())
@ -530,18 +504,18 @@ namespace CppSharp
return; return;
} }
new CleanUnitPass(options).VisitLibrary(driver.ASTContext); new CleanUnitPass().VisitLibrary(driver.Context.ASTContext);
options.Modules.RemoveAll(m => m != options.SystemModule && !m.Units.GetGenerated().Any()); options.Modules.RemoveAll(m => m != options.SystemModule && !m.Units.GetGenerated().Any());
if (!options.Quiet) if (!options.Quiet)
Log.Message("Processing code..."); Log.Message("Processing code...");
library.Preprocess(driver, driver.ASTContext); library.Preprocess(driver, driver.Context.ASTContext);
driver.SetupPasses(library); driver.SetupPasses(library);
driver.ProcessCode(); driver.ProcessCode();
library.Postprocess(driver, driver.ASTContext); library.Postprocess(driver, driver.Context.ASTContext);
if (!options.Quiet) if (!options.Quiet)
Log.Message("Generating code..."); Log.Message("Generating code...");
@ -550,9 +524,8 @@ namespace CppSharp
foreach (var output in outputs) foreach (var output in outputs)
{ {
foreach (var pass in driver.GeneratorOutputPasses.Passes) foreach (var pass in driver.Context.GeneratorOutputPasses.Passes)
{ {
pass.Driver = driver;
pass.VisitGeneratorOutput(output); pass.VisitGeneratorOutput(output);
} }
} }

15
src/Generator/Generator.cs

@ -38,11 +38,11 @@ namespace CppSharp.Generators
{ {
public static string CurrentOutputNamespace = string.Empty; public static string CurrentOutputNamespace = string.Empty;
public Driver Driver { get; private set; } public BindingContext Context { get; private set; }
protected Generator(Driver driver) protected Generator(BindingContext context)
{ {
Driver = driver; Context = context;
CppSharp.AST.Type.TypePrinterDelegate += TypePrinterDelegate; CppSharp.AST.Type.TypePrinterDelegate += TypePrinterDelegate;
} }
@ -71,11 +71,13 @@ namespace CppSharp.Generators
{ {
var outputs = new List<GeneratorOutput>(); var outputs = new List<GeneratorOutput>();
var units = Driver.ASTContext.TranslationUnits.GetGenerated().ToList(); var units = Context.ASTContext.TranslationUnits.GetGenerated().ToList();
if (Driver.Options.IsCSharpGenerator)
if (Context.Options.IsCSharpGenerator)
GenerateSingleTemplate(outputs); GenerateSingleTemplate(outputs);
else else
GenerateTemplates(outputs, units.Where(u => !u.IsSystemHeader)); GenerateTemplates(outputs, units.Where(u => !u.IsSystemHeader));
return outputs; return outputs;
} }
@ -99,6 +101,7 @@ namespace CppSharp.Generators
TranslationUnit = unit, TranslationUnit = unit,
Templates = templates Templates = templates
}; };
outputs.Add(output); outputs.Add(output);
OnUnitGenerated(output); OnUnitGenerated(output);
@ -107,7 +110,7 @@ namespace CppSharp.Generators
private void GenerateSingleTemplate(ICollection<GeneratorOutput> outputs) private void GenerateSingleTemplate(ICollection<GeneratorOutput> outputs)
{ {
foreach (var module in Driver.Options.Modules) foreach (var module in Context.Options.Modules)
{ {
CurrentOutputNamespace = module.OutputNamespace; CurrentOutputNamespace = module.OutputNamespace;
var output = new GeneratorOutput var output = new GeneratorOutput

12
src/Generator/Generators/CLI/CLIGenerator.cs

@ -11,19 +11,19 @@ namespace CppSharp.Generators.CLI
{ {
private readonly CLITypePrinter typePrinter; private readonly CLITypePrinter typePrinter;
public CLIGenerator(Driver driver) : base(driver) public CLIGenerator(BindingContext context) : base(context)
{ {
typePrinter = new CLITypePrinter(driver); typePrinter = new CLITypePrinter(context);
} }
public override List<Template> Generate(IEnumerable<TranslationUnit> units) public override List<Template> Generate(IEnumerable<TranslationUnit> units)
{ {
var outputs = new List<Template>(); var outputs = new List<Template>();
var header = new CLIHeaders(Driver, units); var header = new CLIHeaders(Context, units);
outputs.Add(header); outputs.Add(header);
var source = new CLISources(Driver, units); var source = new CLISources(Context, units);
outputs.Add(source); outputs.Add(source);
return outputs; return outputs;
@ -33,8 +33,8 @@ namespace CppSharp.Generators.CLI
{ {
// Note: The ToString override will only work if this pass runs // Note: The ToString override will only work if this pass runs
// after the MoveOperatorToCallPass. // after the MoveOperatorToCallPass.
if (Driver.Options.GenerateObjectOverrides) if (Context.Options.GenerateObjectOverrides)
Driver.TranslationUnitPasses.AddPass(new ObjectOverridesPass()); Context.TranslationUnitPasses.AddPass(new ObjectOverridesPass(this));
return true; return true;
} }

16
src/Generator/Generators/CLI/CLIHeaders.cs

@ -15,8 +15,8 @@ namespace CppSharp.Generators.CLI
{ {
public override string FileExtension { get { return "h"; } } public override string FileExtension { get { return "h"; } }
public CLIHeaders(Driver driver, IEnumerable<TranslationUnit> units) public CLIHeaders(BindingContext context, IEnumerable<TranslationUnit> units)
: base(driver, units) : base(context, units)
{ {
} }
@ -52,8 +52,8 @@ namespace CppSharp.Generators.CLI
public void GenerateIncludeForwardRefs() public void GenerateIncludeForwardRefs()
{ {
var typeReferenceCollector = new CLITypeReferenceCollector(Driver.TypeDatabase, var typeReferenceCollector = new CLITypeReferenceCollector(Context.TypeDatabase,
Driver.Options); Context.Options);
typeReferenceCollector.Process(TranslationUnit, filterNamespaces: false); typeReferenceCollector.Process(TranslationUnit, filterNamespaces: false);
var includes = new SortedSet<string>(StringComparer.InvariantCulture); var includes = new SortedSet<string>(StringComparer.InvariantCulture);
@ -131,8 +131,8 @@ namespace CppSharp.Generators.CLI
public void GenerateForwardRefs() public void GenerateForwardRefs()
{ {
var typeReferenceCollector = new CLITypeReferenceCollector(Driver.TypeDatabase, var typeReferenceCollector = new CLITypeReferenceCollector(Context.TypeDatabase,
Driver.Options); Context.Options);
typeReferenceCollector.Process(TranslationUnit); typeReferenceCollector.Process(TranslationUnit);
var typeReferences = typeReferenceCollector.TypeReferences; var typeReferences = typeReferenceCollector.TypeReferences;
@ -336,7 +336,7 @@ namespace CppSharp.Generators.CLI
printer.TypePrinterContext = typeCtx; printer.TypePrinterContext = typeCtx;
var typePrinter = new CLITypePrinter(Driver, typeCtx); var typePrinter = new CLITypePrinter(Context, typeCtx);
var retType = function.ReturnType.Type.Visit(typePrinter, var retType = function.ReturnType.Type.Visit(typePrinter,
function.ReturnType.Qualifiers); function.ReturnType.Qualifiers);
@ -493,7 +493,7 @@ namespace CppSharp.Generators.CLI
WriteLine("void add({0} evt);", @event.Type); WriteLine("void add({0} evt);", @event.Type);
WriteLine("void remove({0} evt);", @event.Type); WriteLine("void remove({0} evt);", @event.Type);
var cliTypePrinter = new CLITypePrinter(Driver); var cliTypePrinter = new CLITypePrinter(Context);
var cliArgs = cliTypePrinter.VisitParameters(@event.Parameters, hasNames: true); var cliArgs = cliTypePrinter.VisitParameters(@event.Parameters, hasNames: true);
WriteLine("void raise({0});", cliArgs); WriteLine("void raise({0});", cliArgs);

24
src/Generator/Generators/CLI/CLIMarshal.cs

@ -20,7 +20,7 @@ namespace CppSharp.Generators.CLI
public override bool VisitType(Type type, TypeQualifiers quals) public override bool VisitType(Type type, TypeQualifiers quals)
{ {
TypeMap typeMap; TypeMap typeMap;
if (Context.Driver.TypeDatabase.FindTypeMap(type, out typeMap) && typeMap.DoesMarshalling) if (Context.Context.TypeDatabase.FindTypeMap(type, out typeMap) && typeMap.DoesMarshalling)
{ {
typeMap.Type = type; typeMap.Type = type;
typeMap.CLIMarshalToManaged(Context); typeMap.CLIMarshalToManaged(Context);
@ -155,7 +155,7 @@ namespace CppSharp.Generators.CLI
} }
TypeMap typeMap = null; TypeMap typeMap = null;
Context.Driver.TypeDatabase.FindTypeMap(pointee, out typeMap); Context.Context.TypeDatabase.FindTypeMap(pointee, out typeMap);
Class @class; Class @class;
if (pointee.TryGetClass(out @class) && typeMap == null) if (pointee.TryGetClass(out @class) && typeMap == null)
@ -175,7 +175,7 @@ namespace CppSharp.Generators.CLI
Encoding.ASCII : Encoding.Unicode; Encoding.ASCII : Encoding.Unicode;
if (Equals(encoding, Encoding.ASCII)) if (Equals(encoding, Encoding.ASCII))
encoding = Context.Driver.Options.Encoding; encoding = Context.Context.Options.Encoding;
string param; string param;
if (Equals(encoding, Encoding.ASCII)) if (Equals(encoding, Encoding.ASCII))
@ -185,7 +185,7 @@ namespace CppSharp.Generators.CLI
param = "E_UTF16"; param = "E_UTF16";
else else
throw new NotSupportedException(string.Format("{0} is not supported yet.", throw new NotSupportedException(string.Format("{0} is not supported yet.",
Context.Driver.Options.Encoding.EncodingName)); Context.Context.Options.Encoding.EncodingName));
return string.Format( return string.Format(
"({0} == 0 ? nullptr : clix::marshalString<clix::{1}>({0}))", "({0} == 0 ? nullptr : clix::marshalString<clix::{1}>({0}))",
@ -237,7 +237,7 @@ namespace CppSharp.Generators.CLI
var decl = typedef.Declaration; var decl = typedef.Declaration;
TypeMap typeMap; TypeMap typeMap;
if (Context.Driver.TypeDatabase.FindTypeMap(decl, out typeMap) && typeMap.DoesMarshalling) if (Context.Context.TypeDatabase.FindTypeMap(decl, out typeMap) && typeMap.DoesMarshalling)
{ {
typeMap.Type = typedef; typeMap.Type = typedef;
typeMap.CLIMarshalToManaged(Context); typeMap.CLIMarshalToManaged(Context);
@ -262,7 +262,7 @@ namespace CppSharp.Generators.CLI
TypeQualifiers quals) TypeQualifiers quals)
{ {
TypeMap typeMap; TypeMap typeMap;
if (Context.Driver.TypeDatabase.FindTypeMap(template, out typeMap) && typeMap.DoesMarshalling) if (Context.Context.TypeDatabase.FindTypeMap(template, out typeMap) && typeMap.DoesMarshalling)
{ {
typeMap.Type = template; typeMap.Type = template;
typeMap.CLIMarshalToManaged(Context); typeMap.CLIMarshalToManaged(Context);
@ -374,7 +374,7 @@ namespace CppSharp.Generators.CLI
private string ToCLITypeName(Declaration decl) private string ToCLITypeName(Declaration decl)
{ {
var typePrinter = new CLITypePrinter(Context.Driver); var typePrinter = new CLITypePrinter(Context.Context);
return typePrinter.VisitDeclaration(decl); return typePrinter.VisitDeclaration(decl);
} }
@ -426,7 +426,7 @@ namespace CppSharp.Generators.CLI
public override bool VisitType(Type type, TypeQualifiers quals) public override bool VisitType(Type type, TypeQualifiers quals)
{ {
TypeMap typeMap; TypeMap typeMap;
if (Context.Driver.TypeDatabase.FindTypeMap(type, out typeMap) && typeMap.DoesMarshalling) if (Context.Context.TypeDatabase.FindTypeMap(type, out typeMap) && typeMap.DoesMarshalling)
{ {
typeMap.Type = type; typeMap.Type = type;
typeMap.CLIMarshalToNative(Context); typeMap.CLIMarshalToNative(Context);
@ -611,7 +611,7 @@ namespace CppSharp.Generators.CLI
var decl = typedef.Declaration; var decl = typedef.Declaration;
TypeMap typeMap; TypeMap typeMap;
if (Context.Driver.TypeDatabase.FindTypeMap(decl, out typeMap) && typeMap.DoesMarshalling) if (Context.Context.TypeDatabase.FindTypeMap(decl, out typeMap) && typeMap.DoesMarshalling)
{ {
typeMap.CLIMarshalToNative(Context); typeMap.CLIMarshalToNative(Context);
return typeMap.IsValueType; return typeMap.IsValueType;
@ -647,7 +647,7 @@ namespace CppSharp.Generators.CLI
TypeQualifiers quals) TypeQualifiers quals)
{ {
TypeMap typeMap; TypeMap typeMap;
if (Context.Driver.TypeDatabase.FindTypeMap(template, out typeMap) && typeMap.DoesMarshalling) if (Context.Context.TypeDatabase.FindTypeMap(template, out typeMap) && typeMap.DoesMarshalling)
{ {
typeMap.Type = template; typeMap.Type = template;
typeMap.CLIMarshalToNative(Context); typeMap.CLIMarshalToNative(Context);
@ -693,7 +693,7 @@ namespace CppSharp.Generators.CLI
private void MarshalRefClass(Class @class) private void MarshalRefClass(Class @class)
{ {
TypeMap typeMap; TypeMap typeMap;
if (Context.Driver.TypeDatabase.FindTypeMap(@class, out typeMap) && typeMap.DoesMarshalling) if (Context.Context.TypeDatabase.FindTypeMap(@class, out typeMap) && typeMap.DoesMarshalling)
{ {
typeMap.CLIMarshalToNative(Context); typeMap.CLIMarshalToNative(Context);
return; return;
@ -775,7 +775,7 @@ namespace CppSharp.Generators.CLI
var fieldRef = string.Format("{0}.{1}", Context.Parameter.Name, var fieldRef = string.Format("{0}.{1}", Context.Parameter.Name,
property.Name); property.Name);
var marshalCtx = new MarshalContext(Context.Driver) var marshalCtx = new MarshalContext(Context.Context)
{ {
ArgName = fieldRef, ArgName = fieldRef,
ParameterIndex = Context.ParameterIndex++, ParameterIndex = Context.ParameterIndex++,

38
src/Generator/Generators/CLI/CLISources.cs

@ -16,8 +16,8 @@ namespace CppSharp.Generators.CLI
/// </summary> /// </summary>
public class CLISources : CLITemplate public class CLISources : CLITemplate
{ {
public CLISources(Driver driver, IEnumerable<TranslationUnit> units) public CLISources(BindingContext context, IEnumerable<TranslationUnit> units)
: base(driver, units) : base(context, units)
{ {
} }
@ -30,8 +30,8 @@ namespace CppSharp.Generators.CLI
var file = Path.GetFileNameWithoutExtension(TranslationUnit.FileName) var file = Path.GetFileNameWithoutExtension(TranslationUnit.FileName)
.Replace('\\', '/'); .Replace('\\', '/');
if (Driver.Options.GenerateName != null) if (Context.Options.GenerateName != null)
file = Driver.Options.GenerateName(TranslationUnit); file = Context.Options.GenerateName(TranslationUnit);
PushBlock(CLIBlockKind.Includes); PushBlock(CLIBlockKind.Includes);
WriteLine("#include \"{0}.h\"", file); WriteLine("#include \"{0}.h\"", file);
@ -60,7 +60,7 @@ namespace CppSharp.Generators.CLI
{ {
PushBlock(CLIBlockKind.IncludesForwardReferences); PushBlock(CLIBlockKind.IncludesForwardReferences);
var typeReferenceCollector = new CLITypeReferenceCollector(Driver.TypeDatabase, Driver.Options); var typeReferenceCollector = new CLITypeReferenceCollector(Context.TypeDatabase, Context.Options);
typeReferenceCollector.Process(TranslationUnit, filterNamespaces: false); typeReferenceCollector.Process(TranslationUnit, filterNamespaces: false);
var includes = new SortedSet<string>(StringComparer.InvariantCulture); var includes = new SortedSet<string>(StringComparer.InvariantCulture);
@ -306,7 +306,7 @@ namespace CppSharp.Generators.CLI
printer.TypePrinterContext = typeCtx; printer.TypePrinterContext = typeCtx;
var typePrinter = new CLITypePrinter(Driver, typeCtx); var typePrinter = new CLITypePrinter(Context, typeCtx);
var retType = function.ReturnType.Type.Visit(typePrinter, var retType = function.ReturnType.Type.Visit(typePrinter,
function.ReturnType.Qualifiers); function.ReturnType.Qualifiers);
@ -412,7 +412,7 @@ namespace CppSharp.Generators.CLI
variable = string.Format("((::{0}*)NativePtr)->{1}", variable = string.Format("((::{0}*)NativePtr)->{1}",
@class.QualifiedOriginalName, decl.OriginalName); @class.QualifiedOriginalName, decl.OriginalName);
var ctx = new MarshalContext(Driver) var ctx = new MarshalContext(Context)
{ {
Parameter = param, Parameter = param,
ArgName = param.Name, ArgName = param.Name,
@ -424,7 +424,7 @@ namespace CppSharp.Generators.CLI
if (isIndexer) if (isIndexer)
{ {
var ctx2 = new MarshalContext(Driver) var ctx2 = new MarshalContext(Context)
{ {
Parameter = indexParameter, Parameter = indexParameter,
ArgName = indexParameter.Name ArgName = indexParameter.Name
@ -499,7 +499,7 @@ namespace CppSharp.Generators.CLI
variable = string.Format("((::{0}*)NativePtr)->{1}", variable = string.Format("((::{0}*)NativePtr)->{1}",
@class.QualifiedOriginalName, decl.OriginalName); @class.QualifiedOriginalName, decl.OriginalName);
var ctx = new MarshalContext(Driver) var ctx = new MarshalContext(Context)
{ {
Declaration = decl, Declaration = decl,
ArgName = decl.Name, ArgName = decl.Name,
@ -581,7 +581,7 @@ namespace CppSharp.Generators.CLI
private void GenerateEventRaise(Event @event, Class @class) private void GenerateEventRaise(Event @event, Class @class)
{ {
var typePrinter = new CLITypePrinter(Driver); var typePrinter = new CLITypePrinter(Context);
var args = typePrinter.VisitParameters(@event.Parameters, hasNames: true); var args = typePrinter.VisitParameters(@event.Parameters, hasNames: true);
WriteLine("void {0}::{1}::raise({2})", QualifiedIdentifier(@class), WriteLine("void {0}::{1}::raise({2})", QualifiedIdentifier(@class),
@ -608,7 +608,7 @@ namespace CppSharp.Generators.CLI
var returns = new List<string>(); var returns = new List<string>();
foreach (var param in @event.Parameters) foreach (var param in @event.Parameters)
{ {
var ctx = new MarshalContext(Driver) var ctx = new MarshalContext(Context)
{ {
ReturnVarName = param.Name, ReturnVarName = param.Name,
ReturnType = param.QualifiedType ReturnType = param.QualifiedType
@ -701,7 +701,7 @@ namespace CppSharp.Generators.CLI
var nativeField = string.Format("{0}{1}", var nativeField = string.Format("{0}{1}",
nativeVar, property.Field.OriginalName); nativeVar, property.Field.OriginalName);
var ctx = new MarshalContext(Driver) var ctx = new MarshalContext(Context)
{ {
ArgName = property.Name, ArgName = property.Name,
ReturnVarName = nativeField, ReturnVarName = nativeField,
@ -847,7 +847,7 @@ namespace CppSharp.Generators.CLI
var paramIndex = 0; var paramIndex = 0;
foreach (var param in method.Parameters) foreach (var param in method.Parameters)
{ {
var ctx = new MarshalContext(Driver) var ctx = new MarshalContext(Context)
{ {
Function = method, Function = method,
Parameter = param, Parameter = param,
@ -883,7 +883,7 @@ namespace CppSharp.Generators.CLI
var varName = string.Format("_native.{0}", property.Field.OriginalName); var varName = string.Format("_native.{0}", property.Field.OriginalName);
var ctx = new MarshalContext(Driver) var ctx = new MarshalContext(Context)
{ {
ReturnVarName = varName, ReturnVarName = varName,
ReturnType = property.QualifiedType ReturnType = property.QualifiedType
@ -959,7 +959,7 @@ namespace CppSharp.Generators.CLI
WriteLine("auto {0} = ::{1}();", valueMarshalName, @class.QualifiedOriginalName); WriteLine("auto {0} = ::{1}();", valueMarshalName, @class.QualifiedOriginalName);
var param = new Parameter { Name = "(*this)" }; var param = new Parameter { Name = "(*this)" };
var ctx = new MarshalContext(Driver) var ctx = new MarshalContext(Context)
{ {
MarshalVarPrefix = valueMarshalName, MarshalVarPrefix = valueMarshalName,
Parameter = param Parameter = param
@ -1034,7 +1034,7 @@ namespace CppSharp.Generators.CLI
var nativeVarName = paramInfo.Name; var nativeVarName = paramInfo.Name;
var ctx = new MarshalContext(Driver) var ctx = new MarshalContext(Context)
{ {
ArgName = nativeVarName, ArgName = nativeVarName,
ReturnVarName = nativeVarName, ReturnVarName = nativeVarName,
@ -1067,7 +1067,7 @@ namespace CppSharp.Generators.CLI
isIntPtr ? "System::IntPtr()" : "nullptr"); isIntPtr ? "System::IntPtr()" : "nullptr");
} }
var ctx = new MarshalContext(Driver) var ctx = new MarshalContext(Context)
{ {
ArgName = returnIdentifier, ArgName = returnIdentifier,
ReturnVarName = returnIdentifier, ReturnVarName = returnIdentifier,
@ -1095,7 +1095,7 @@ namespace CppSharp.Generators.CLI
private void CheckArgumentRange(Function method) private void CheckArgumentRange(Function method)
{ {
if (Driver.Options.MarshalCharAsManagedChar) if (Context.Options.MarshalCharAsManagedChar)
{ {
foreach (var param in method.Parameters.Where( foreach (var param in method.Parameters.Where(
p => p.Type.IsPrimitiveType(PrimitiveType.Char))) p => p.Type.IsPrimitiveType(PrimitiveType.Char)))
@ -1180,7 +1180,7 @@ namespace CppSharp.Generators.CLI
QualifiedType = new QualifiedType(paramType) QualifiedType = new QualifiedType(paramType)
}; };
var ctx = new MarshalContext(Driver) var ctx = new MarshalContext(Context)
{ {
Parameter = effectiveParam, Parameter = effectiveParam,
ParameterIndex = paramIndex, ParameterIndex = paramIndex,

6
src/Generator/Generators/CLI/CLITemplate.cs

@ -61,10 +61,10 @@ namespace CppSharp.Generators.CLI
public ISet<Include> Includes; public ISet<Include> Includes;
protected CLITemplate(Driver driver, IEnumerable<TranslationUnit> units) protected CLITemplate(BindingContext context, IEnumerable<TranslationUnit> units)
: base(driver, units) : base(context, units)
{ {
TypePrinter = new CLITypePrinter(driver); TypePrinter = new CLITypePrinter(context);
Includes = new HashSet<Include>(); Includes = new HashSet<Include>();
} }

19
src/Generator/Generators/CLI/CLITypePrinter.cs

@ -23,24 +23,23 @@ namespace CppSharp.Generators.CLI
public class CLITypePrinter : ITypePrinter<string>, IDeclVisitor<string> public class CLITypePrinter : ITypePrinter<string>, IDeclVisitor<string>
{ {
public Driver Driver { get; set; }
public CLITypePrinterContext TypePrinterContext { get; set; } public CLITypePrinterContext TypePrinterContext { get; set; }
readonly ITypeMapDatabase TypeMapDatabase; public BindingContext Context { get; private set; }
readonly DriverOptions Options;
public CLITypePrinter(Driver driver) public DriverOptions Options { get { return Context.Options; } }
public TypeMapDatabase TypeMapDatabase { get { return Context.TypeDatabase; } }
public CLITypePrinter(BindingContext context)
{ {
Driver = driver; Context = context;
TypeMapDatabase = driver.TypeDatabase;
Options = driver.Options;
TypePrinterContext = new CLITypePrinterContext(); TypePrinterContext = new CLITypePrinterContext();
} }
public CLITypePrinter(Driver driver, CLITypePrinterContext context) public CLITypePrinter(BindingContext context, CLITypePrinterContext typePrinterContext)
: this(driver) : this(context)
{ {
TypePrinterContext = context; TypePrinterContext = typePrinterContext;
} }
public string VisitTagType(TagType tag, TypeQualifiers quals) public string VisitTagType(TagType tag, TypeQualifiers quals)

8
src/Generator/Generators/CSharp/CSharpGenerator.cs

@ -9,9 +9,9 @@ namespace CppSharp.Generators.CSharp
private readonly CSharpTypePrinter typePrinter; private readonly CSharpTypePrinter typePrinter;
private readonly CSharpExpressionPrinter expressionPrinter; private readonly CSharpExpressionPrinter expressionPrinter;
public CSharpGenerator(Driver driver) : base(driver) public CSharpGenerator(BindingContext context) : base(context)
{ {
typePrinter = new CSharpTypePrinter(driver); typePrinter = new CSharpTypePrinter(context);
expressionPrinter = new CSharpExpressionPrinter(typePrinter); expressionPrinter = new CSharpExpressionPrinter(typePrinter);
} }
@ -19,7 +19,7 @@ namespace CppSharp.Generators.CSharp
{ {
var outputs = new List<Template>(); var outputs = new List<Template>();
var template = new CSharpSources(Driver, units, typePrinter, expressionPrinter); var template = new CSharpSources(Context, units, typePrinter, expressionPrinter);
outputs.Add(template); outputs.Add(template);
return outputs; return outputs;
@ -32,7 +32,7 @@ namespace CppSharp.Generators.CSharp
// CheckAbiParameters runs last because hidden structure parameters // CheckAbiParameters runs last because hidden structure parameters
// should always occur first. // should always occur first.
Driver.AddTranslationUnitPass(new CheckAbiParameters()); Context.TranslationUnitPasses.AddPass(new CheckAbiParameters());
return true; return true;
} }

42
src/Generator/Generators/CSharp/CSharpMarshal.cs

@ -19,8 +19,8 @@ namespace CppSharp.Generators.CSharp
public class CSharpMarshalContext : MarshalContext public class CSharpMarshalContext : MarshalContext
{ {
public CSharpMarshalContext(Driver driver) public CSharpMarshalContext(BindingContext context)
: base(driver) : base(context)
{ {
Kind = CSharpMarshalKind.Unknown; Kind = CSharpMarshalKind.Unknown;
ArgumentPrefix = new TextGenerator(); ArgumentPrefix = new TextGenerator();
@ -56,7 +56,7 @@ namespace CppSharp.Generators.CSharp
public CSharpMarshalNativeToManagedPrinter(CSharpMarshalContext context) public CSharpMarshalNativeToManagedPrinter(CSharpMarshalContext context)
: base(context) : base(context)
{ {
typePrinter = new CSharpTypePrinter(context.Driver); typePrinter = new CSharpTypePrinter(context.Context);
} }
public bool MarshalsParameter { get; set; } public bool MarshalsParameter { get; set; }
@ -64,7 +64,7 @@ namespace CppSharp.Generators.CSharp
public override bool VisitType(Type type, TypeQualifiers quals) public override bool VisitType(Type type, TypeQualifiers quals)
{ {
TypeMap typeMap; TypeMap typeMap;
if (Context.Driver.TypeDatabase.FindTypeMap(type, out typeMap) && typeMap.DoesMarshalling) if (Context.Context.TypeDatabase.FindTypeMap(type, out typeMap) && typeMap.DoesMarshalling)
{ {
typeMap.Type = type; typeMap.Type = type;
typeMap.CSharpMarshalToManaged(Context); typeMap.CSharpMarshalToManaged(Context);
@ -77,7 +77,7 @@ namespace CppSharp.Generators.CSharp
public override bool VisitDeclaration(Declaration decl) public override bool VisitDeclaration(Declaration decl)
{ {
TypeMap typeMap; TypeMap typeMap;
if (Context.Driver.TypeDatabase.FindTypeMap(decl, out typeMap) && typeMap.DoesMarshalling) if (Context.Context.TypeDatabase.FindTypeMap(decl, out typeMap) && typeMap.DoesMarshalling)
{ {
typeMap.Declaration = decl; typeMap.Declaration = decl;
typeMap.CSharpMarshalToManaged(Context); typeMap.CSharpMarshalToManaged(Context);
@ -116,7 +116,7 @@ namespace CppSharp.Generators.CSharp
else else
{ {
if (arrayType.IsPrimitiveType(PrimitiveType.Char) && if (arrayType.IsPrimitiveType(PrimitiveType.Char) &&
Context.Driver.Options.MarshalCharAsManagedChar) Context.Context.Options.MarshalCharAsManagedChar)
{ {
supportBefore.WriteLineIndent( supportBefore.WriteLineIndent(
"{0}[i] = global::System.Convert.ToChar({1}[i]);", "{0}[i] = global::System.Convert.ToChar({1}[i]);",
@ -179,7 +179,7 @@ namespace CppSharp.Generators.CSharp
return true; return true;
} }
if (Context.Driver.Options.MarshalCharAsManagedChar && primitive == PrimitiveType.Char) if (Context.Context.Options.MarshalCharAsManagedChar && primitive == PrimitiveType.Char)
Context.Return.Write(string.Format("({0}) ", pointer)); Context.Return.Write(string.Format("({0}) ", pointer));
Context.Return.Write(Context.ReturnVarName); Context.Return.Write(Context.ReturnVarName);
return true; return true;
@ -194,14 +194,14 @@ namespace CppSharp.Generators.CSharp
var encoding = isChar ? Encoding.ASCII : Encoding.Unicode; var encoding = isChar ? Encoding.ASCII : Encoding.Unicode;
if (Equals(encoding, Encoding.ASCII)) if (Equals(encoding, Encoding.ASCII))
encoding = Context.Driver.Options.Encoding; encoding = Context.Context.Options.Encoding;
if (Equals(encoding, Encoding.ASCII)) if (Equals(encoding, Encoding.ASCII))
return string.Format("Marshal.PtrToStringAnsi({0})", varName); return string.Format("Marshal.PtrToStringAnsi({0})", varName);
// If we reach this, we know the string is Unicode. // If we reach this, we know the string is Unicode.
if (type.Type == PrimitiveType.Char || if (type.Type == PrimitiveType.Char ||
Context.Driver.TargetInfo.WCharWidth == 16) Context.Context.TargetInfo.WCharWidth == 16)
return string.Format("Marshal.PtrToStringUni({0})", varName); return string.Format("Marshal.PtrToStringUni({0})", varName);
// If we reach this, we should have an UTF-32 wide string. // If we reach this, we should have an UTF-32 wide string.
@ -219,7 +219,7 @@ namespace CppSharp.Generators.CSharp
return true; return true;
case PrimitiveType.Char: case PrimitiveType.Char:
// returned structs must be blittable and char isn't // returned structs must be blittable and char isn't
if (Context.Driver.Options.MarshalCharAsManagedChar) if (Context.Context.Options.MarshalCharAsManagedChar)
{ {
Context.Return.Write("global::System.Convert.ToChar({0})", Context.Return.Write("global::System.Convert.ToChar({0})",
Context.ReturnVarName); Context.ReturnVarName);
@ -305,7 +305,7 @@ namespace CppSharp.Generators.CSharp
if (parameter.Usage == ParameterUsage.Unknown || parameter.IsIn) if (parameter.Usage == ParameterUsage.Unknown || parameter.IsIn)
return base.VisitParameterDecl(parameter); return base.VisitParameterDecl(parameter);
var ctx = new CSharpMarshalContext(Context.Driver) var ctx = new CSharpMarshalContext(Context.Context)
{ {
ReturnType = Context.ReturnType, ReturnType = Context.ReturnType,
ReturnVarName = Context.ReturnVarName ReturnVarName = Context.ReturnVarName
@ -375,13 +375,13 @@ namespace CppSharp.Generators.CSharp
public CSharpMarshalManagedToNativePrinter(CSharpMarshalContext context) public CSharpMarshalManagedToNativePrinter(CSharpMarshalContext context)
: base(context) : base(context)
{ {
typePrinter = new CSharpTypePrinter(context.Driver); typePrinter = new CSharpTypePrinter(context.Context);
} }
public override bool VisitType(Type type, TypeQualifiers quals) public override bool VisitType(Type type, TypeQualifiers quals)
{ {
TypeMap typeMap; TypeMap typeMap;
if (Context.Driver.TypeDatabase.FindTypeMap(type, out typeMap) && typeMap.DoesMarshalling) if (Context.Context.TypeDatabase.FindTypeMap(type, out typeMap) && typeMap.DoesMarshalling)
{ {
typeMap.Type = type; typeMap.Type = type;
typeMap.CSharpMarshalToNative(Context); typeMap.CSharpMarshalToNative(Context);
@ -394,7 +394,7 @@ namespace CppSharp.Generators.CSharp
public override bool VisitDeclaration(Declaration decl) public override bool VisitDeclaration(Declaration decl)
{ {
TypeMap typeMap; TypeMap typeMap;
if (Context.Driver.TypeDatabase.FindTypeMap(decl, out typeMap) && typeMap.DoesMarshalling) if (Context.Context.TypeDatabase.FindTypeMap(decl, out typeMap) && typeMap.DoesMarshalling)
{ {
typeMap.Declaration = decl; typeMap.Declaration = decl;
typeMap.CSharpMarshalToNative(Context); typeMap.CSharpMarshalToNative(Context);
@ -446,7 +446,7 @@ namespace CppSharp.Generators.CSharp
else else
{ {
if (arrayType.IsPrimitiveType(PrimitiveType.Char) && if (arrayType.IsPrimitiveType(PrimitiveType.Char) &&
Context.Driver.Options.MarshalCharAsManagedChar) Context.Context.Options.MarshalCharAsManagedChar)
{ {
supportBefore.WriteLineIndent( supportBefore.WriteLineIndent(
"{0}[i] = global::System.Convert.ToSByte({1}[i]);", "{0}[i] = global::System.Convert.ToSByte({1}[i]);",
@ -579,7 +579,7 @@ namespace CppSharp.Generators.CSharp
else else
{ {
if (!marshalAsString && if (!marshalAsString &&
Context.Driver.Options.MarshalCharAsManagedChar && Context.Context.Options.MarshalCharAsManagedChar &&
primitive == PrimitiveType.Char) primitive == PrimitiveType.Char)
{ {
typePrinter.PushContext(CSharpTypePrinterContextKind.Native); typePrinter.PushContext(CSharpTypePrinterContextKind.Native);
@ -601,17 +601,17 @@ namespace CppSharp.Generators.CSharp
private string MarshalStringToUnmanaged(string varName) private string MarshalStringToUnmanaged(string varName)
{ {
if (Equals(Context.Driver.Options.Encoding, Encoding.ASCII)) if (Equals(Context.Context.Options.Encoding, Encoding.ASCII))
{ {
return string.Format("Marshal.StringToHGlobalAnsi({0})", varName); return string.Format("Marshal.StringToHGlobalAnsi({0})", varName);
} }
if (Equals(Context.Driver.Options.Encoding, Encoding.Unicode) || if (Equals(Context.Context.Options.Encoding, Encoding.Unicode) ||
Equals(Context.Driver.Options.Encoding, Encoding.BigEndianUnicode)) Equals(Context.Context.Options.Encoding, Encoding.BigEndianUnicode))
{ {
return string.Format("Marshal.StringToHGlobalUni({0})", varName); return string.Format("Marshal.StringToHGlobalUni({0})", varName);
} }
throw new NotSupportedException(string.Format("{0} is not supported yet.", throw new NotSupportedException(string.Format("{0} is not supported yet.",
Context.Driver.Options.Encoding.EncodingName)); Context.Context.Options.Encoding.EncodingName));
} }
public override bool VisitPrimitiveType(PrimitiveType primitive, TypeQualifiers quals) public override bool VisitPrimitiveType(PrimitiveType primitive, TypeQualifiers quals)
@ -622,7 +622,7 @@ namespace CppSharp.Generators.CSharp
return true; return true;
case PrimitiveType.Char: case PrimitiveType.Char:
// returned structs must be blittable and char isn't // returned structs must be blittable and char isn't
if (Context.Driver.Options.MarshalCharAsManagedChar) if (Context.Context.Options.MarshalCharAsManagedChar)
{ {
Context.Return.Write("global::System.Convert.ToSByte({0})", Context.Return.Write("global::System.Convert.ToSByte({0})",
Context.Parameter.Name); Context.Parameter.Name);

68
src/Generator/Generators/CSharp/CSharpSources.cs

@ -131,9 +131,9 @@ namespace CppSharp.Generators.CSharp
get { return "cs"; } get { return "cs"; }
} }
public CSharpSources(Driver driver, IEnumerable<TranslationUnit> units, public CSharpSources(BindingContext context, IEnumerable<TranslationUnit> units,
CSharpTypePrinter typePrinter, CSharpExpressionPrinter expressionPrinter) CSharpTypePrinter typePrinter, CSharpExpressionPrinter expressionPrinter)
: base(driver, units) : base(context, units)
{ {
TypePrinter = typePrinter; TypePrinter = typePrinter;
ExpressionPrinter = expressionPrinter; ExpressionPrinter = expressionPrinter;
@ -163,7 +163,7 @@ namespace CppSharp.Generators.CSharp
PopBlock(NewLineKind.BeforeNextBlock); PopBlock(NewLineKind.BeforeNextBlock);
var module = TranslationUnits.Count == 0 ? var module = TranslationUnits.Count == 0 ?
Driver.Options.SystemModule : TranslationUnit.Module; Context.Options.SystemModule : TranslationUnit.Module;
if (!string.IsNullOrEmpty(module.OutputNamespace)) if (!string.IsNullOrEmpty(module.OutputNamespace))
{ {
PushBlock(CSharpBlockKind.Namespace); PushBlock(CSharpBlockKind.Namespace);
@ -426,11 +426,11 @@ namespace CppSharp.Generators.CSharp
GenerateClassTemplateSpecializationInternal(nestedTemplate); GenerateClassTemplateSpecializationInternal(nestedTemplate);
System.Type typeMap = null; System.Type typeMap = null;
if (Driver.TypeDatabase.TypeMaps.ContainsKey(@class.Name)) if (Context.TypeDatabase.TypeMaps.ContainsKey(@class.Name))
{ {
typeMap = Driver.TypeDatabase.TypeMaps[@class.Name]; typeMap = Context.TypeDatabase.TypeMaps[@class.Name];
// disable the type map for the mapped class itself so that operator params are not mapped // disable the type map for the mapped class itself so that operator params are not mapped
Driver.TypeDatabase.TypeMaps.Remove(@class.Name); Context.TypeDatabase.TypeMaps.Remove(@class.Name);
} }
PushBlock(CSharpBlockKind.Class); PushBlock(CSharpBlockKind.Class);
@ -499,7 +499,7 @@ namespace CppSharp.Generators.CSharp
PopBlock(NewLineKind.BeforeNextBlock); PopBlock(NewLineKind.BeforeNextBlock);
if (typeMap != null) if (typeMap != null)
Driver.TypeDatabase.TypeMaps.Add(@class.Name, typeMap); Context.TypeDatabase.TypeMaps.Add(@class.Name, typeMap);
} }
private void GenerateClassMarshals(Class @class) private void GenerateClassMarshals(Class @class)
@ -672,7 +672,7 @@ namespace CppSharp.Generators.CSharp
retType = function.ReturnType.CSharpType(TypePrinter); retType = function.ReturnType.CSharpType(TypePrinter);
var @params = function.GatherInternalParams(Driver.Options.IsItaniumLikeAbi).Select(p => var @params = function.GatherInternalParams(Context.Options.IsItaniumLikeAbi).Select(p =>
string.Format("{0} {1}", p.CSharpType(TypePrinter), p.Name)).ToList(); string.Format("{0} {1}", p.CSharpType(TypePrinter), p.Name)).ToList();
TypePrinter.PopContext(); TypePrinter.PopContext();
@ -753,7 +753,7 @@ namespace CppSharp.Generators.CSharp
foreach (var @base in @class.Bases.Where(b => b.Class != null)) foreach (var @base in @class.Bases.Where(b => b.Class != null))
{ {
TypeMap typeMap; TypeMap typeMap;
if ((!Driver.TypeDatabase.FindTypeMap(@base.Type, out typeMap) && !@base.Class.IsDeclared) || if ((!Context.TypeDatabase.FindTypeMap(@base.Type, out typeMap) && !@base.Class.IsDeclared) ||
@base.Class.OriginalClass == @class) @base.Class.OriginalClass == @class)
continue; continue;
@ -871,7 +871,7 @@ namespace CppSharp.Generators.CSharp
QualifiedType = decl.QualifiedType QualifiedType = decl.QualifiedType
}; };
var ctx = new CSharpMarshalContext(Driver) var ctx = new CSharpMarshalContext(Context)
{ {
Parameter = param, Parameter = param,
ArgName = param.Name, ArgName = param.Name,
@ -985,9 +985,9 @@ namespace CppSharp.Generators.CSharp
var isChar = finalElementType.IsPrimitiveType(PrimitiveType.Char); var isChar = finalElementType.IsPrimitiveType(PrimitiveType.Char);
string type; string type;
if (Driver.Options.MarshalCharAsManagedChar && isChar) if (Context.Options.MarshalCharAsManagedChar && isChar)
{ {
var typePrinter = new CSharpTypePrinter(Driver); var typePrinter = new CSharpTypePrinter(Context);
typePrinter.PushContext(CSharpTypePrinterContextKind.Native); typePrinter.PushContext(CSharpTypePrinterContextKind.Native);
type = originalType.Visit(typePrinter).Type; type = originalType.Visit(typePrinter).Type;
} }
@ -1090,7 +1090,7 @@ namespace CppSharp.Generators.CSharp
WriteStartBraceIndent(); WriteStartBraceIndent();
var name = @class.Layout.Fields.First(f => f.FieldPtr == field.OriginalPtr).Name; var name = @class.Layout.Fields.First(f => f.FieldPtr == field.OriginalPtr).Name;
var ctx = new CSharpMarshalContext(Driver) var ctx = new CSharpMarshalContext(Context)
{ {
Kind = CSharpMarshalKind.NativeField, Kind = CSharpMarshalKind.NativeField,
ArgName = decl.Name, ArgName = decl.Name,
@ -1125,7 +1125,7 @@ namespace CppSharp.Generators.CSharp
var final = field.Type.GetFinalPointee().Desugar(); var final = field.Type.GetFinalPointee().Desugar();
if (final.IsPrimitiveType() && !final.IsPrimitiveType(PrimitiveType.Void) && if (final.IsPrimitiveType() && !final.IsPrimitiveType(PrimitiveType.Void) &&
(!final.IsPrimitiveType(PrimitiveType.Char) || (!final.IsPrimitiveType(PrimitiveType.Char) ||
(!Driver.Options.MarshalCharAsManagedChar && (!Context.Options.MarshalCharAsManagedChar &&
!((PointerType) field.Type).QualifiedPointee.Qualifiers.IsConst))) !((PointerType) field.Type).QualifiedPointee.Qualifiers.IsConst)))
@return = string.Format("({0}*) {1}", field.Type.GetPointee().Desugar(), @return); @return = string.Format("({0}*) {1}", field.Type.GetPointee().Desugar(), @return);
} }
@ -1159,7 +1159,7 @@ namespace CppSharp.Generators.CSharp
TypePrinter.PopContext(); TypePrinter.PopContext();
var ctx = new CSharpMarshalContext(Driver) var ctx = new CSharpMarshalContext(Context)
{ {
ArgName = decl.Name, ArgName = decl.Name,
ReturnVarName = (isRefTypeArray ? string.Empty : "*") + Generator.GeneratedIdentifier("ptr"), ReturnVarName = (isRefTypeArray ? string.Empty : "*") + Generator.GeneratedIdentifier("ptr"),
@ -1495,7 +1495,7 @@ namespace CppSharp.Generators.CSharp
private void SaveOriginalVTablePointers(Class @class) private void SaveOriginalVTablePointers(Class @class)
{ {
var suffix = Helpers.GetSuffixForInternal(@class); var suffix = Helpers.GetSuffixForInternal(@class);
if (Driver.Options.IsMicrosoftAbi) if (Context.Options.IsMicrosoftAbi)
WriteLine("__OriginalVTables = new void*[] {{ {0} }};", WriteLine("__OriginalVTables = new void*[] {{ {0} }};",
string.Join(", ", string.Join(", ",
@class.Layout.VTablePointers.Select(v => string.Format( @class.Layout.VTablePointers.Select(v => string.Format(
@ -1518,7 +1518,7 @@ namespace CppSharp.Generators.CSharp
var vfptr = @class.Layout.VFTables[i]; var vfptr = @class.Layout.VFTables[i];
var size = vfptr.Layout.Components.Count; var size = vfptr.Layout.Components.Count;
WriteLine("var vfptr{0} = Marshal.AllocHGlobal({1} * {2});", WriteLine("var vfptr{0} = Marshal.AllocHGlobal({1} * {2});",
i, size, Driver.TargetInfo.PointerWidth / 8); i, size, Context.TargetInfo.PointerWidth / 8);
WriteLine("{0}[{1}] = vfptr{1}.ToPointer();", managedVTables, i); WriteLine("{0}[{1}] = vfptr{1}.ToPointer();", managedVTables, i);
AllocateNewVTableEntries(vfptr.Layout.Components, wrappedEntries, AllocateNewVTableEntries(vfptr.Layout.Components, wrappedEntries,
@ -1540,7 +1540,7 @@ namespace CppSharp.Generators.CSharp
WriteLine("{0} = new void*[1];", managedVTables); WriteLine("{0} = new void*[1];", managedVTables);
var size = @class.Layout.Layout.Components.Count; var size = @class.Layout.Layout.Components.Count;
var pointerSize = Driver.TargetInfo.PointerWidth / 8; var pointerSize = Context.TargetInfo.PointerWidth / 8;
WriteLine("var vtptr = Marshal.AllocHGlobal({0} * {1});", size, pointerSize); WriteLine("var vtptr = Marshal.AllocHGlobal({0} * {1});", size, pointerSize);
WriteLine("var vfptr0 = vtptr + {0} * {1};", VTables.ItaniumOffsetToTopAndRTTI, pointerSize); WriteLine("var vfptr0 = vtptr + {0} * {1};", VTables.ItaniumOffsetToTopAndRTTI, pointerSize);
@ -1559,7 +1559,7 @@ namespace CppSharp.Generators.CSharp
private void AllocateNewVTableEntries(IList<VTableComponent> entries, private void AllocateNewVTableEntries(IList<VTableComponent> entries,
IList<VTableComponent> wrappedEntries, string vptr, int tableIndex, bool destructorOnly) IList<VTableComponent> wrappedEntries, string vptr, int tableIndex, bool destructorOnly)
{ {
var pointerSize = Driver.TargetInfo.PointerWidth / 8; var pointerSize = Context.TargetInfo.PointerWidth / 8;
for (var i = 0; i < entries.Count; i++) for (var i = 0; i < entries.Count; i++)
{ {
var entry = entries[i]; var entry = entries[i];
@ -1573,7 +1573,7 @@ namespace CppSharp.Generators.CSharp
entry.Kind == VTableComponentKind.DeletingDtorPointer) && entry.Kind == VTableComponentKind.DeletingDtorPointer) &&
!entry.IsIgnored() && !entry.IsIgnored() &&
(!destructorOnly || entry.Method.IsDestructor || (!destructorOnly || entry.Method.IsDestructor ||
Driver.Options.ExplicitlyPatchedVirtualFunctions.Contains(entry.Method.QualifiedOriginalName))) Context.Options.ExplicitlyPatchedVirtualFunctions.Contains(entry.Method.QualifiedOriginalName)))
WriteLine("{0} = _Thunks[{1}];", managedVftableEntry, wrappedEntries.IndexOf(entry)); WriteLine("{0} = _Thunks[{1}];", managedVftableEntry, wrappedEntries.IndexOf(entry));
else else
WriteLine("{0} = {1};", managedVftableEntry, nativeVftableEntry); WriteLine("{0} = {1};", managedVftableEntry, nativeVftableEntry);
@ -1615,7 +1615,7 @@ namespace CppSharp.Generators.CSharp
if (param.Kind == ParameterKind.IndirectReturnType) if (param.Kind == ParameterKind.IndirectReturnType)
continue; continue;
var ctx = new CSharpMarshalContext(Driver) var ctx = new CSharpMarshalContext(Context)
{ {
ReturnType = param.QualifiedType, ReturnType = param.QualifiedType,
ReturnVarName = param.Name, ReturnVarName = param.Name,
@ -1655,7 +1655,7 @@ namespace CppSharp.Generators.CSharp
}; };
// Marshal the managed result to native // Marshal the managed result to native
var ctx = new CSharpMarshalContext(Driver) var ctx = new CSharpMarshalContext(Context)
{ {
ArgName = Helpers.ReturnIdentifier, ArgName = Helpers.ReturnIdentifier,
Parameter = param, Parameter = param,
@ -1837,7 +1837,7 @@ namespace CppSharp.Generators.CSharp
var returns = new List<string>(); var returns = new List<string>();
foreach (var param in @event.Parameters) foreach (var param in @event.Parameters)
{ {
var ctx = new CSharpMarshalContext(Driver) var ctx = new CSharpMarshalContext(Context)
{ {
ReturnVarName = param.Name, ReturnVarName = param.Name,
ReturnType = param.QualifiedType ReturnType = param.QualifiedType
@ -1970,7 +1970,7 @@ namespace CppSharp.Generators.CSharp
{ {
NativeLibrary library; NativeLibrary library;
if (!Options.CheckSymbols || if (!Options.CheckSymbols ||
Driver.Symbols.FindLibraryBySymbol(dtor.Mangled, out library)) Context.Symbols.FindLibraryBySymbol(dtor.Mangled, out library))
{ {
WriteLine("if (disposing)"); WriteLine("if (disposing)");
if (dtor.IsVirtual) if (dtor.IsVirtual)
@ -2486,7 +2486,7 @@ namespace CppSharp.Generators.CSharp
{ {
var i = VTables.GetVTableIndex(method.OriginalFunction ?? method, @class); var i = VTables.GetVTableIndex(method.OriginalFunction ?? method, @class);
WriteLine("var {0} = *(void**) ((IntPtr) __OriginalVTables[0] + {1} * {2});", WriteLine("var {0} = *(void**) ((IntPtr) __OriginalVTables[0] + {1} * {2});",
Helpers.SlotIdentifier, i, Driver.TargetInfo.PointerWidth / 8); Helpers.SlotIdentifier, i, Context.TargetInfo.PointerWidth / 8);
if (method.IsDestructor && @class.IsAbstract) if (method.IsDestructor && @class.IsAbstract)
{ {
WriteLine("if ({0} != null)", Helpers.SlotIdentifier); WriteLine("if ({0} != null)", Helpers.SlotIdentifier);
@ -2503,7 +2503,7 @@ namespace CppSharp.Generators.CSharp
private string GetDelegateName(Function function, string outputNamespace) private string GetDelegateName(Function function, string outputNamespace)
{ {
var @delegate = Driver.Delegates[function]; var @delegate = Context.Delegates[function];
if (string.IsNullOrWhiteSpace(@delegate.Namespace) || if (string.IsNullOrWhiteSpace(@delegate.Namespace) ||
outputNamespace == @delegate.Namespace) outputNamespace == @delegate.Namespace)
{ {
@ -2651,7 +2651,7 @@ namespace CppSharp.Generators.CSharp
TypeMap typeMap; TypeMap typeMap;
string construct = null; string construct = null;
if (Driver.TypeDatabase.FindTypeMap(retClass, out typeMap)) if (Context.TypeDatabase.FindTypeMap(retClass, out typeMap))
construct = typeMap.CSharpConstruct(); construct = typeMap.CSharpConstruct();
if (construct == null) if (construct == null)
@ -2750,7 +2750,7 @@ namespace CppSharp.Generators.CSharp
if (needsReturn) if (needsReturn)
{ {
var ctx = new CSharpMarshalContext(Driver) var ctx = new CSharpMarshalContext(Context)
{ {
ArgName = Helpers.ReturnIdentifier, ArgName = Helpers.ReturnIdentifier,
ReturnVarName = Helpers.ReturnIdentifier, ReturnVarName = Helpers.ReturnIdentifier,
@ -2838,7 +2838,7 @@ namespace CppSharp.Generators.CSharp
var nativeVarName = paramInfo.Name; var nativeVarName = paramInfo.Name;
var ctx = new CSharpMarshalContext(Driver) var ctx = new CSharpMarshalContext(Context)
{ {
Parameter = param, Parameter = param,
ArgName = nativeVarName, ArgName = nativeVarName,
@ -2911,7 +2911,7 @@ namespace CppSharp.Generators.CSharp
} }
} }
var ctx = new CSharpMarshalContext(Driver) var ctx = new CSharpMarshalContext(Context)
{ {
Parameter = param, Parameter = param,
ParameterIndex = paramIndex, ParameterIndex = paramIndex,
@ -3135,14 +3135,14 @@ namespace CppSharp.Generators.CSharp
private string GetLibraryOf(Declaration declaration) private string GetLibraryOf(Declaration declaration)
{ {
if (declaration.TranslationUnit.IsSystemHeader) if (declaration.TranslationUnit.IsSystemHeader)
return Driver.Options.SystemModule.TemplatesLibraryName; return Context.Options.SystemModule.TemplatesLibraryName;
string libName = declaration.TranslationUnit.Module.SharedLibraryName; string libName = declaration.TranslationUnit.Module.SharedLibraryName;
if (Options.CheckSymbols) if (Options.CheckSymbols)
{ {
NativeLibrary library; NativeLibrary library;
Driver.Symbols.FindLibraryBySymbol(((IMangledDecl) declaration).Mangled, out library); Context.Symbols.FindLibraryBySymbol(((IMangledDecl) declaration).Mangled, out library);
if (library != null) if (library != null)
libName = Path.GetFileNameWithoutExtension(library.FileName); libName = Path.GetFileNameWithoutExtension(library.FileName);
@ -3161,9 +3161,9 @@ namespace CppSharp.Generators.CSharp
if (Platform.IsMacOS) if (Platform.IsMacOS)
{ {
var framework = libName + ".framework"; var framework = libName + ".framework";
for (uint i = 0; i < Driver.Options.LibraryDirsCount; i++) for (uint i = 0; i < Context.Options.LibraryDirsCount; i++)
{ {
var libDir = Driver.Options.getLibraryDirs(i); var libDir = Context.Options.getLibraryDirs(i);
if (Path.GetFileName(libDir) == framework && File.Exists(Path.Combine(libDir, libName))) if (Path.GetFileName(libDir) == framework && File.Exists(Path.Combine(libDir, libName)))
{ {
libName = string.Format("@executable_path/../Frameworks/{0}/{1}", framework, libName); libName = string.Format("@executable_path/../Frameworks/{0}/{1}", framework, libName);

32
src/Generator/Generators/CSharp/CSharpTypePrinter.cs

@ -52,8 +52,6 @@ namespace CppSharp.Generators.CSharp
AppendGlobal = true; AppendGlobal = true;
} }
private readonly Driver driver;
private readonly Stack<CSharpTypePrinterContextKind> contexts; private readonly Stack<CSharpTypePrinterContextKind> contexts;
private readonly Stack<CSharpMarshalKind> marshalKinds; private readonly Stack<CSharpMarshalKind> marshalKinds;
@ -69,10 +67,14 @@ namespace CppSharp.Generators.CSharp
public CSharpTypePrinterContext TypePrinterContext; public CSharpTypePrinterContext TypePrinterContext;
public CSharpTypePrinter(Driver driver) public BindingContext Context { get; set; }
{
this.driver = driver;
public DriverOptions Options { get { return Context.Options; } }
public TypeMapDatabase TypeMapDatabase { get { return Context.TypeDatabase; } }
public CSharpTypePrinter(BindingContext context)
{
Context = context;
contexts = new Stack<CSharpTypePrinterContextKind>(); contexts = new Stack<CSharpTypePrinterContextKind>();
marshalKinds = new Stack<CSharpMarshalKind>(); marshalKinds = new Stack<CSharpMarshalKind>();
PushContext(CSharpTypePrinterContextKind.Managed); PushContext(CSharpTypePrinterContextKind.Managed);
@ -107,7 +109,7 @@ namespace CppSharp.Generators.CSharp
return string.Empty; return string.Empty;
TypeMap typeMap; TypeMap typeMap;
if (driver.TypeDatabase.FindTypeMap(tag.Declaration, out typeMap)) if (TypeMapDatabase.FindTypeMap(tag.Declaration, out typeMap))
{ {
typeMap.Type = tag; typeMap.Type = tag;
TypePrinterContext.CSharpKind = ContextKind; TypePrinterContext.CSharpKind = ContextKind;
@ -165,7 +167,7 @@ namespace CppSharp.Generators.CSharp
// C# does not support fixed arrays of machine pointer type (void* or IntPtr). // C# does not support fixed arrays of machine pointer type (void* or IntPtr).
// In that case, replace it by a pointer to an integer type of the same size. // In that case, replace it by a pointer to an integer type of the same size.
if (arrayElemType == IntPtrType) if (arrayElemType == IntPtrType)
arrayElemType = driver.TargetInfo.PointerWidth == 64 ? "long" : "int"; arrayElemType = Context.TargetInfo.PointerWidth == 64 ? "long" : "int";
// Do not write the fixed keyword multiple times for nested array types // Do not write the fixed keyword multiple times for nested array types
var fixedKeyword = array.Type is ArrayType ? string.Empty : "fixed "; var fixedKeyword = array.Type is ArrayType ? string.Empty : "fixed ";
@ -271,13 +273,13 @@ namespace CppSharp.Generators.CSharp
return "string"; return "string";
if (TypePrinterContext.Parameter == null || TypePrinterContext.Parameter.Name == Helpers.ReturnIdentifier) if (TypePrinterContext.Parameter == null || TypePrinterContext.Parameter.Name == Helpers.ReturnIdentifier)
return IntPtrType; return IntPtrType;
if (driver.Options.Encoding == Encoding.ASCII) if (Options.Encoding == Encoding.ASCII)
return string.Format("[MarshalAs(UnmanagedType.LPStr)] string"); return string.Format("[MarshalAs(UnmanagedType.LPStr)] string");
if (driver.Options.Encoding == Encoding.Unicode || if (Options.Encoding == Encoding.Unicode ||
driver.Options.Encoding == Encoding.BigEndianUnicode) Options.Encoding == Encoding.BigEndianUnicode)
return string.Format("[MarshalAs(UnmanagedType.LPWStr)] string"); return string.Format("[MarshalAs(UnmanagedType.LPWStr)] string");
throw new NotSupportedException(string.Format("{0} is not supported yet.", throw new NotSupportedException(string.Format("{0} is not supported yet.",
driver.Options.Encoding.EncodingName)); Options.Encoding.EncodingName));
} }
var desugared = pointee.Desugar(); var desugared = pointee.Desugar();
@ -360,7 +362,7 @@ namespace CppSharp.Generators.CSharp
var decl = typedef.Declaration; var decl = typedef.Declaration;
TypeMap typeMap; TypeMap typeMap;
if (driver.TypeDatabase.FindTypeMap(decl, out typeMap)) if (TypeMapDatabase.FindTypeMap(decl, out typeMap))
{ {
typeMap.Type = typedef; typeMap.Type = typedef;
TypePrinterContext.CSharpKind = ContextKind; TypePrinterContext.CSharpKind = ContextKind;
@ -408,7 +410,7 @@ namespace CppSharp.Generators.CSharp
var decl = template.Template.TemplatedDecl; var decl = template.Template.TemplatedDecl;
TypeMap typeMap; TypeMap typeMap;
if (!driver.TypeDatabase.FindTypeMap(template, out typeMap)) if (!TypeMapDatabase.FindTypeMap(template, out typeMap))
{ {
if (ContextKind != CSharpTypePrinterContextKind.Native) if (ContextKind != CSharpTypePrinterContextKind.Native)
return GetNestedQualifiedName(decl); return GetNestedQualifiedName(decl);
@ -563,7 +565,7 @@ namespace CppSharp.Generators.CSharp
case PrimitiveType.WideChar: return "char"; case PrimitiveType.WideChar: return "char";
case PrimitiveType.Char: case PrimitiveType.Char:
// returned structs must be blittable and char isn't // returned structs must be blittable and char isn't
return driver.Options.MarshalCharAsManagedChar && return Options.MarshalCharAsManagedChar &&
ContextKind != CSharpTypePrinterContextKind.Native ContextKind != CSharpTypePrinterContextKind.Native
? "char" ? "char"
: "sbyte"; : "sbyte";
@ -576,7 +578,7 @@ namespace CppSharp.Generators.CSharp
case PrimitiveType.ULong: case PrimitiveType.ULong:
case PrimitiveType.LongLong: case PrimitiveType.LongLong:
case PrimitiveType.ULongLong: case PrimitiveType.ULongLong:
return GetIntString(primitive, driver.TargetInfo); return GetIntString(primitive, Context.TargetInfo);
case PrimitiveType.Int128: return "__int128"; case PrimitiveType.Int128: return "__int128";
case PrimitiveType.UInt128: return "__uint128_t"; case PrimitiveType.UInt128: return "__uint128_t";
case PrimitiveType.Half: return "__fp16"; case PrimitiveType.Half: return "__fp16";

6
src/Generator/Generators/Marshal.cs

@ -4,15 +4,15 @@ namespace CppSharp.Generators
{ {
public class MarshalContext public class MarshalContext
{ {
public MarshalContext(Driver driver) public MarshalContext(BindingContext context)
{ {
Driver = driver; Context = context;
SupportBefore = new TextGenerator(); SupportBefore = new TextGenerator();
Return = new TextGenerator(); Return = new TextGenerator();
MarshalVarPrefix = string.Empty; MarshalVarPrefix = string.Empty;
} }
public Driver Driver { get; private set; } public BindingContext Context { get; private set; }
public MarshalPrinter<MarshalContext> MarshalToNative; public MarshalPrinter<MarshalContext> MarshalToNative;

17
src/Generator/Generators/Template.cs

@ -280,26 +280,23 @@ namespace CppSharp.Generators
public abstract class Template : ITextGenerator public abstract class Template : ITextGenerator
{ {
public Driver Driver { get; private set; } public BindingContext Context { get; private set; }
public DriverOptions Options { get; private set; }
public IDiagnostics Log { get { return Context.Diagnostics; } }
public DriverOptions Options { get { return Context.Options; } }
public List<TranslationUnit> TranslationUnits { get; private set; } public List<TranslationUnit> TranslationUnits { get; private set; }
public TranslationUnit TranslationUnit { get { return TranslationUnits[0]; } } public TranslationUnit TranslationUnit { get { return TranslationUnits[0]; } }
public IDiagnostics Log
{
get { return Driver.Diagnostics; }
}
public Block RootBlock { get; private set; } public Block RootBlock { get; private set; }
public Block ActiveBlock { get; private set; } public Block ActiveBlock { get; private set; }
public abstract string FileExtension { get; } public abstract string FileExtension { get; }
protected Template(Driver driver, IEnumerable<TranslationUnit> units) protected Template(BindingContext context, IEnumerable<TranslationUnit> units)
{ {
Driver = driver; Context = context;
Options = driver.Options;
TranslationUnits = new List<TranslationUnit>(units); TranslationUnits = new List<TranslationUnit>(units);
RootBlock = new Block(); RootBlock = new Block();
ActiveBlock = RootBlock; ActiveBlock = RootBlock;

2
src/Generator/Passes/CheckAbiParameters.cs

@ -67,7 +67,7 @@ namespace CppSharp.Passes
// Deleting destructors (default in v-table) accept an i32 bitfield as a // Deleting destructors (default in v-table) accept an i32 bitfield as a
// second parameter.in MS ABI. // second parameter.in MS ABI.
if (method != null && method.IsDestructor && Driver.Options.IsMicrosoftAbi) if (method != null && method.IsDestructor && Options.IsMicrosoftAbi)
{ {
method.Parameters.Add(new Parameter method.Parameters.Add(new Parameter
{ {

2
src/Generator/Passes/CheckAmbiguousFunctions.cs

@ -59,7 +59,7 @@ namespace CppSharp.Passes
} }
if (function.IsAmbiguous) if (function.IsAmbiguous)
Driver.Diagnostics.Debug("Found ambiguous overload: {0}", Diagnostics.Debug("Found ambiguous overload: {0}",
function.QualifiedOriginalName); function.QualifiedOriginalName);
return true; return true;

8
src/Generator/Passes/CheckDuplicatedNamesPass.cs

@ -130,7 +130,7 @@ namespace CppSharp.Passes
if (!VisitDeclaration(decl)) if (!VisitDeclaration(decl))
return false; return false;
if (ASTUtils.CheckIgnoreFunction(decl, Driver.Options)) if (ASTUtils.CheckIgnoreFunction(decl, Options))
return false; return false;
CheckDuplicate(decl); CheckDuplicate(decl);
@ -142,7 +142,7 @@ namespace CppSharp.Passes
if (!VisitDeclaration(decl)) if (!VisitDeclaration(decl))
return false; return false;
if (ASTUtils.CheckIgnoreMethod(decl, Driver.Options)) if (ASTUtils.CheckIgnoreMethod(decl, Options))
return false; return false;
if (decl.ExplicitInterfaceImpl == null) if (decl.ExplicitInterfaceImpl == null)
@ -219,11 +219,11 @@ namespace CppSharp.Passes
// If the name is not yet on the map, then add it. // If the name is not yet on the map, then add it.
if (!names.ContainsKey(fullName)) if (!names.ContainsKey(fullName))
names.Add(fullName, new DeclarationName(Driver.Diagnostics)); names.Add(fullName, new DeclarationName(Diagnostics));
if (names[fullName].UpdateName(decl)) if (names[fullName].UpdateName(decl))
{ {
Driver.Diagnostics.Debug("Duplicate name {0}, renamed to {1}", Diagnostics.Debug("Duplicate name {0}, renamed to {1}",
fullName, decl.Name); fullName, decl.Name);
} }
} }

42
src/Generator/Passes/CheckIgnoredDecls.cs

@ -9,7 +9,7 @@ namespace CppSharp.Passes
{ {
public bool CheckDeclarationAccess(Declaration decl) public bool CheckDeclarationAccess(Declaration decl)
{ {
var generateNonPublicDecls = Driver.Options.IsCSharpGenerator; var generateNonPublicDecls = Options.IsCSharpGenerator;
switch (decl.Access) switch (decl.Access)
{ {
@ -56,7 +56,7 @@ namespace CppSharp.Passes
if (!CheckDeclarationAccess(decl)) if (!CheckDeclarationAccess(decl))
{ {
Log.Debug("Decl '{0}' was ignored due to invalid access", Diagnostics.Debug("Decl '{0}' was ignored due to invalid access",
decl.Name); decl.Name);
decl.GenerationKind = decl is Field ? GenerationKind.Internal : GenerationKind.None; decl.GenerationKind = decl is Field ? GenerationKind.Internal : GenerationKind.None;
return true; return true;
@ -65,7 +65,7 @@ namespace CppSharp.Passes
if (decl.IsDependent) if (decl.IsDependent)
{ {
decl.GenerationKind = decl is Field ? GenerationKind.Internal : GenerationKind.None; decl.GenerationKind = decl is Field ? GenerationKind.Internal : GenerationKind.None;
Log.Debug("Decl '{0}' was ignored due to dependent context", Diagnostics.Debug("Decl '{0}' was ignored due to dependent context",
decl.Name); decl.Name);
return true; return true;
} }
@ -94,7 +94,7 @@ namespace CppSharp.Passes
var cppTypePrinter = new CppTypePrinter(); var cppTypePrinter = new CppTypePrinter();
var typeName = field.Type.Visit(cppTypePrinter); var typeName = field.Type.Visit(cppTypePrinter);
Log.Debug("Field '{0}::{1}' was ignored due to {2} type '{3}'", Diagnostics.Debug("Field '{0}::{1}' was ignored due to {2} type '{3}'",
@class.Name, field.Name, msg, typeName); @class.Name, field.Name, msg, typeName);
return true; return true;
@ -111,7 +111,7 @@ namespace CppSharp.Passes
if (HasInvalidType(ret.Type, out msg)) if (HasInvalidType(ret.Type, out msg))
{ {
function.ExplicitlyIgnore(); function.ExplicitlyIgnore();
Log.Debug("Function '{0}' was ignored due to {1} return decl", Diagnostics.Debug("Function '{0}' was ignored due to {1} return decl",
function.Name, msg); function.Name, msg);
return false; return false;
} }
@ -121,7 +121,7 @@ namespace CppSharp.Passes
if (HasInvalidDecl(param, out msg)) if (HasInvalidDecl(param, out msg))
{ {
function.ExplicitlyIgnore(); function.ExplicitlyIgnore();
Log.Debug("Function '{0}' was ignored due to {1} param", Diagnostics.Debug("Function '{0}' was ignored due to {1} param",
function.Name, msg); function.Name, msg);
return false; return false;
} }
@ -129,7 +129,7 @@ namespace CppSharp.Passes
if (HasInvalidType(param.Type, out msg)) if (HasInvalidType(param.Type, out msg))
{ {
function.ExplicitlyIgnore(); function.ExplicitlyIgnore();
Log.Debug("Function '{0}' was ignored due to {1} param", Diagnostics.Debug("Function '{0}' was ignored due to {1} param",
function.Name, msg); function.Name, msg);
return false; return false;
} }
@ -138,7 +138,7 @@ namespace CppSharp.Passes
if (decayedType != null) if (decayedType != null)
{ {
function.ExplicitlyIgnore(); function.ExplicitlyIgnore();
Log.Debug("Function '{0}' was ignored due to unsupported decayed type param", Diagnostics.Debug("Function '{0}' was ignored due to unsupported decayed type param",
function.Name); function.Name);
return false; return false;
} }
@ -150,7 +150,7 @@ namespace CppSharp.Passes
if (retClass == null) if (retClass == null)
{ {
function.ExplicitlyIgnore(); function.ExplicitlyIgnore();
Log.Debug( Diagnostics.Debug(
"Function '{0}' was ignored due to an indirect return param not of a tag type", "Function '{0}' was ignored due to an indirect return param not of a tag type",
function.Name); function.Name);
return false; return false;
@ -178,7 +178,7 @@ namespace CppSharp.Passes
Class ignoredBase; Class ignoredBase;
if (HasIgnoredBaseClass(method, @class, out ignoredBase)) if (HasIgnoredBaseClass(method, @class, out ignoredBase))
{ {
Log.Debug( Diagnostics.Debug(
"Virtual method '{0}' was ignored due to ignored base '{1}'", "Virtual method '{0}' was ignored due to ignored base '{1}'",
method.QualifiedOriginalName, ignoredBase.Name); method.QualifiedOriginalName, ignoredBase.Name);
@ -225,7 +225,7 @@ namespace CppSharp.Passes
if (HasInvalidType(typedef.Type, out msg)) if (HasInvalidType(typedef.Type, out msg))
{ {
typedef.ExplicitlyIgnore(); typedef.ExplicitlyIgnore();
Log.Debug("Typedef '{0}' was ignored due to {1} type", Diagnostics.Debug("Typedef '{0}' was ignored due to {1} type",
typedef.Name, msg); typedef.Name, msg);
return false; return false;
} }
@ -242,7 +242,7 @@ namespace CppSharp.Passes
if (HasInvalidDecl(property, out msg)) if (HasInvalidDecl(property, out msg))
{ {
property.ExplicitlyIgnore(); property.ExplicitlyIgnore();
Log.Debug("Property '{0}' was ignored due to {1} decl", Diagnostics.Debug("Property '{0}' was ignored due to {1} decl",
property.Name, msg); property.Name, msg);
return false; return false;
} }
@ -250,7 +250,7 @@ namespace CppSharp.Passes
if (HasInvalidType(property.Type, out msg)) if (HasInvalidType(property.Type, out msg))
{ {
property.ExplicitlyIgnore(); property.ExplicitlyIgnore();
Log.Debug("Property '{0}' was ignored due to {1} type", Diagnostics.Debug("Property '{0}' was ignored due to {1} type",
property.Name, msg); property.Name, msg);
return false; return false;
} }
@ -267,7 +267,7 @@ namespace CppSharp.Passes
if (HasInvalidDecl(variable, out msg)) if (HasInvalidDecl(variable, out msg))
{ {
variable.ExplicitlyIgnore(); variable.ExplicitlyIgnore();
Log.Debug("Variable '{0}' was ignored due to {1} decl", Diagnostics.Debug("Variable '{0}' was ignored due to {1} decl",
variable.Name, msg); variable.Name, msg);
return false; return false;
} }
@ -275,7 +275,7 @@ namespace CppSharp.Passes
if (HasInvalidType(variable.Type, out msg)) if (HasInvalidType(variable.Type, out msg))
{ {
variable.ExplicitlyIgnore(); variable.ExplicitlyIgnore();
Log.Debug("Variable '{0}' was ignored due to {1} type", Diagnostics.Debug("Variable '{0}' was ignored due to {1} type",
variable.Name, msg); variable.Name, msg);
return false; return false;
} }
@ -292,7 +292,7 @@ namespace CppSharp.Passes
if (HasInvalidDecl(@event, out msg)) if (HasInvalidDecl(@event, out msg))
{ {
@event.ExplicitlyIgnore(); @event.ExplicitlyIgnore();
Log.Debug("Event '{0}' was ignored due to {1} decl", Diagnostics.Debug("Event '{0}' was ignored due to {1} decl",
@event.Name, msg); @event.Name, msg);
return false; return false;
} }
@ -302,7 +302,7 @@ namespace CppSharp.Passes
if (HasInvalidDecl(param, out msg)) if (HasInvalidDecl(param, out msg))
{ {
@event.ExplicitlyIgnore(); @event.ExplicitlyIgnore();
Log.Debug("Event '{0}' was ignored due to {1} param", Diagnostics.Debug("Event '{0}' was ignored due to {1} param",
@event.Name, msg); @event.Name, msg);
return false; return false;
} }
@ -310,7 +310,7 @@ namespace CppSharp.Passes
if (HasInvalidType(param.Type, out msg)) if (HasInvalidType(param.Type, out msg))
{ {
@event.ExplicitlyIgnore(); @event.ExplicitlyIgnore();
Log.Debug("Event '{0}' was ignored due to {1} param", Diagnostics.Debug("Event '{0}' was ignored due to {1} param",
@event.Name, msg); @event.Name, msg);
return false; return false;
} }
@ -377,7 +377,7 @@ namespace CppSharp.Passes
private bool IsTypeComplete(Type type) private bool IsTypeComplete(Type type)
{ {
TypeMap typeMap; TypeMap typeMap;
if (Driver.TypeDatabase.FindTypeMap(type, out typeMap) && !typeMap.IsIgnored) if (TypeDatabase.FindTypeMap(type, out typeMap) && !typeMap.IsIgnored)
return true; return true;
var desugared = type.Desugar(); var desugared = type.Desugar();
@ -394,7 +394,7 @@ namespace CppSharp.Passes
private bool IsTypeIgnored(Type type) private bool IsTypeIgnored(Type type)
{ {
var checker = new TypeIgnoreChecker(Driver.TypeDatabase); var checker = new TypeIgnoreChecker(TypeDatabase);
type.Visit(checker); type.Visit(checker);
return checker.IsIgnored; return checker.IsIgnored;
@ -407,7 +407,7 @@ namespace CppSharp.Passes
return true; return true;
TypeMap typeMap; TypeMap typeMap;
return Driver.TypeDatabase.FindTypeMap(decl, out typeMap) ? typeMap.IsIgnored : decl.Ignore; return TypeDatabase.FindTypeMap(decl, out typeMap) ? typeMap.IsIgnored : decl.Ignore;
} }
#endregion #endregion

2
src/Generator/Passes/CheckMacrosPass.cs

@ -79,7 +79,7 @@ namespace CppSharp.Passes
e.MacroLocation != MacroLocation.FunctionBody && e.MacroLocation != MacroLocation.FunctionBody &&
e.MacroLocation != MacroLocation.FunctionParameters)) e.MacroLocation != MacroLocation.FunctionParameters))
{ {
Log.Debug("Decl '{0}' was ignored due to ignore macro", Diagnostics.Debug("Decl '{0}' was ignored due to ignore macro",
decl.Name); decl.Name);
decl.ExplicitlyIgnore(); decl.ExplicitlyIgnore();
} }

6
src/Generator/Passes/CheckOperatorsOverloads.cs

@ -26,7 +26,7 @@ namespace CppSharp.Passes
// Check for C++ operators that cannot be represented in C#. // Check for C++ operators that cannot be represented in C#.
CheckInvalidOperators(@class); CheckInvalidOperators(@class);
if (Driver.Options.IsCSharpGenerator) if (Options.IsCSharpGenerator)
{ {
// The comparison operators, if overloaded, must be overloaded in pairs; // The comparison operators, if overloaded, must be overloaded in pairs;
// that is, if == is overloaded, != must also be overloaded. The reverse // that is, if == is overloaded, != must also be overloaded. The reverse
@ -51,7 +51,7 @@ namespace CppSharp.Passes
{ {
if (!IsValidOperatorOverload(@operator) || @operator.IsPure) if (!IsValidOperatorOverload(@operator) || @operator.IsPure)
{ {
Driver.Diagnostics.Debug("Invalid operator overload {0}::{1}", Diagnostics.Debug("Invalid operator overload {0}::{1}",
@class.OriginalName, @operator.OperatorKind); @class.OriginalName, @operator.OperatorKind);
@operator.ExplicitlyIgnore(); @operator.ExplicitlyIgnore();
continue; continue;
@ -115,7 +115,7 @@ namespace CppSharp.Passes
property.QualifiedType = new QualifiedType( property.QualifiedType = new QualifiedType(
pointerType.Pointee, property.QualifiedType.Qualifiers); pointerType.Pointee, property.QualifiedType.Qualifiers);
if (Driver.Options.IsCLIGenerator) if (Options.IsCLIGenerator)
// C++/CLI uses "default" as the indexer property name. // C++/CLI uses "default" as the indexer property name.
property.Name = "default"; property.Name = "default";

2
src/Generator/Passes/CheckStaticClass.cs

@ -19,7 +19,7 @@ namespace CppSharp.Passes
if (!base.VisitDeclaration(decl)) if (!base.VisitDeclaration(decl))
return false; return false;
if (Driver.Options.IsCSharpGenerator) if (Options.IsCSharpGenerator)
{ {
// C# cannot have protected members in static classes. // C# cannot have protected members in static classes.
var @class = decl.Namespace as Class; var @class = decl.Namespace as Class;

2
src/Generator/Passes/CheckVTableComponentsPass.cs

@ -22,7 +22,7 @@ namespace CppSharp.Passes
if (vfptr.Layout.Components.Count == uniqueEntries.Count) if (vfptr.Layout.Components.Count == uniqueEntries.Count)
continue; continue;
Driver.Diagnostics.Warning( Diagnostics.Warning(
"Class '{0}' found with duplicated vftable components", "Class '{0}' found with duplicated vftable components",
@class.Name); @class.Name);
vfptr.Layout.Components = uniqueEntries.ToList(); vfptr.Layout.Components = uniqueEntries.ToList();

2
src/Generator/Passes/CheckVirtualOverrideReturnCovariance.cs

@ -334,7 +334,7 @@ namespace CppSharp.Passes
{ {
method.ReturnType = overridenMethod.ReturnType; method.ReturnType = overridenMethod.ReturnType;
Driver.Diagnostics.Debug( Diagnostics.Debug(
"{0} return type is co-variant with overriden base", "{0} return type is co-variant with overriden base",
method.QualifiedOriginalName); method.QualifiedOriginalName);
} }

2
src/Generator/Passes/CleanInvalidDeclNamesPass.cs

@ -20,7 +20,7 @@ namespace CppSharp.Passes
if (char.IsNumber(name[0])) if (char.IsNumber(name[0]))
return '_' + name; return '_' + name;
if (Driver.Options.IsCLIGenerator) if (Options.IsCLIGenerator)
return CLITemplate.SafeIdentifier(name); return CLITemplate.SafeIdentifier(name);
return Helpers.SafeIdentifier(name); return Helpers.SafeIdentifier(name);
} }

17
src/Generator/Passes/CleanUnitPass.cs

@ -6,11 +6,8 @@ namespace CppSharp.Passes
{ {
public class CleanUnitPass : TranslationUnitPass public class CleanUnitPass : TranslationUnitPass
{ {
public DriverOptions DriverOptions; public CleanUnitPass()
public CleanUnitPass(DriverOptions options)
{ {
DriverOptions = options;
} }
public override bool VisitTranslationUnit(TranslationUnit unit) public override bool VisitTranslationUnit(TranslationUnit unit)
@ -20,14 +17,14 @@ namespace CppSharp.Passes
if (unit.IsSystemHeader) if (unit.IsSystemHeader)
{ {
unit.Module = DriverOptions.SystemModule; unit.Module = Options.SystemModule;
} }
else else
{ {
var includeDir = Path.GetFullPath(Path.GetDirectoryName(unit.FilePath)); var includeDir = Path.GetFullPath(Path.GetDirectoryName(unit.FilePath));
unit.Module = DriverOptions.Modules.FirstOrDefault( unit.Module = Options.Modules.FirstOrDefault(
m => m.IncludeDirs.Any(i => Path.GetFullPath(i) == includeDir)) ?? m => m.IncludeDirs.Any(i => Path.GetFullPath(i) == includeDir)) ??
DriverOptions.MainModule; Options.MainModule;
} }
unit.Module.Units.Add(unit); unit.Module.Units.Add(unit);
// Try to get an include path that works from the original include directories paths // Try to get an include path that works from the original include directories paths
@ -45,9 +42,9 @@ namespace CppSharp.Passes
var includePath = filePath; var includePath = filePath;
var shortestIncludePath = filePath; var shortestIncludePath = filePath;
for (uint i = 0; i < DriverOptions.IncludeDirsCount; ++i) for (uint i = 0; i < Options.IncludeDirsCount; ++i)
{ {
var path = DriverOptions.getIncludeDirs(i); var path = Options.getIncludeDirs(i);
int idx = filePath.IndexOf(path, System.StringComparison.Ordinal); int idx = filePath.IndexOf(path, System.StringComparison.Ordinal);
if (idx == -1) if (idx == -1)
@ -64,7 +61,7 @@ namespace CppSharp.Passes
shortestIncludePath = inc; shortestIncludePath = inc;
} }
includePath = DriverOptions.IncludePrefix includePath = Options.IncludePrefix
+ shortestIncludePath.TrimStart(new char[] { '\\', '/' }); + shortestIncludePath.TrimStart(new char[] { '\\', '/' });
return includePath.Replace('\\', '/'); return includePath.Replace('\\', '/');

4
src/Generator/Passes/ConstructorToConversionOperatorPass.cs

@ -20,7 +20,7 @@ namespace CppSharp.Passes
if (@params.Count == 0) if (@params.Count == 0)
return false; return false;
if (Driver.Options.GenerateDefaultValuesForArguments) if (Options.GenerateDefaultValuesForArguments)
{ {
var nonDefaultParams = @params.Count(p => p.DefaultArgument == null); var nonDefaultParams = @params.Count(p => p.DefaultArgument == null);
if (nonDefaultParams > 1) if (nonDefaultParams > 1)
@ -34,7 +34,7 @@ namespace CppSharp.Passes
var parameter = method.Parameters[0]; var parameter = method.Parameters[0];
// TODO: disable implicit operators for C++/CLI because they seem not to be support parameters // TODO: disable implicit operators for C++/CLI because they seem not to be support parameters
if (!Driver.Options.IsCSharpGenerator) if (!Options.IsCSharpGenerator)
{ {
var pointerType = parameter.Type as PointerType; var pointerType = parameter.Type as PointerType;
if (pointerType != null && !pointerType.IsReference) if (pointerType != null && !pointerType.IsReference)

18
src/Generator/Passes/DelegatesPass.cs

@ -37,7 +37,7 @@ namespace CppSharp.Passes
public override bool VisitLibrary(ASTContext context) public override bool VisitLibrary(ASTContext context)
{ {
foreach (var library in Driver.Options.Modules.SelectMany(m => m.Libraries)) foreach (var library in Options.Modules.SelectMany(m => m.Libraries))
libsDelegates[library] = new Dictionary<string, DelegateDefinition>(); libsDelegates[library] = new Dictionary<string, DelegateDefinition>();
var unit = context.TranslationUnits.GetGenerated().LastOrDefault(); var unit = context.TranslationUnits.GetGenerated().LastOrDefault();
@ -47,7 +47,7 @@ namespace CppSharp.Passes
var result = base.VisitLibrary(context); var result = base.VisitLibrary(context);
foreach (var module in Driver.Options.Modules.Where(m => namespacesDelegates.ContainsKey(m))) foreach (var module in Options.Modules.Where(m => namespacesDelegates.ContainsKey(m)))
module.Units.Last(u => u.HasDeclarations).Declarations.Add(namespacesDelegates[module]); module.Units.Last(u => u.HasDeclarations).Declarations.Add(namespacesDelegates[module]);
return result; return result;
@ -61,7 +61,7 @@ namespace CppSharp.Passes
// dependent types with virtuals have no own virtual layouts // dependent types with virtuals have no own virtual layouts
// so virtuals are considered different objects in template instantiations // so virtuals are considered different objects in template instantiations
// therefore the method itself won't be visited, so let's visit it through the v-table // therefore the method itself won't be visited, so let's visit it through the v-table
if (Driver.Options.IsMicrosoftAbi) if (Options.IsMicrosoftAbi)
{ {
foreach (var method in from vfTable in @class.Layout.VFTables foreach (var method in from vfTable in @class.Layout.VFTables
from component in vfTable.Layout.Components from component in vfTable.Layout.Components
@ -88,7 +88,7 @@ namespace CppSharp.Passes
if (!base.VisitMethodDecl(method) || !method.IsVirtual || method.Ignore) if (!base.VisitMethodDecl(method) || !method.IsVirtual || method.Ignore)
return false; return false;
var @params = method.GatherInternalParams(Driver.Options.IsItaniumLikeAbi, true).ToList(); var @params = method.GatherInternalParams(Options.IsItaniumLikeAbi, true).ToList();
var delegateName = GenerateDelegateSignature(@params, method.ReturnType); var delegateName = GenerateDelegateSignature(@params, method.ReturnType);
var module = method.TranslationUnit.Module; var module = method.TranslationUnit.Module;
@ -132,12 +132,12 @@ namespace CppSharp.Passes
if (existingDelegate != null) if (existingDelegate != null)
{ {
Driver.Delegates.Add(method, existingDelegate); Context.Delegates.Add(method, existingDelegate);
return true; return true;
} }
existingDelegate = new DelegateDefinition(module.OutputNamespace, delegateString); existingDelegate = new DelegateDefinition(module.OutputNamespace, delegateString);
Driver.Delegates.Add(method, existingDelegate); Context.Delegates.Add(method, existingDelegate);
foreach (var library in module.Libraries) foreach (var library in module.Libraries)
libsDelegates[library].Add(delegateString, existingDelegate); libsDelegates[library].Add(delegateString, existingDelegate);
@ -150,11 +150,11 @@ namespace CppSharp.Passes
private DelegateDefinition GetExistingDelegate(IList<string> libraries, string delegateString) private DelegateDefinition GetExistingDelegate(IList<string> libraries, string delegateString)
{ {
if (libraries.Count == 0) if (libraries.Count == 0)
return Driver.Delegates.Values.FirstOrDefault(t => t.Signature == delegateString); return Context.Delegates.Values.FirstOrDefault(t => t.Signature == delegateString);
DelegateDefinition @delegate = null; DelegateDefinition @delegate = null;
if (libraries.Union( if (libraries.Union(
Driver.Symbols.Libraries.Where(l => libraries.Contains(l.FileName)).SelectMany( Context.Symbols.Libraries.Where(l => libraries.Contains(l.FileName)).SelectMany(
l => l.Dependencies)).Any(l => libsDelegates.ContainsKey(l) && l => l.Dependencies)).Any(l => libsDelegates.ContainsKey(l) &&
libsDelegates[l].TryGetValue(delegateString, out @delegate))) libsDelegates[l].TryGetValue(delegateString, out @delegate)))
return @delegate; return @delegate;
@ -196,7 +196,7 @@ namespace CppSharp.Passes
{ {
if (typePrinter == null) if (typePrinter == null)
{ {
typePrinter = new CSharpTypePrinter(Driver); typePrinter = new CSharpTypePrinter(Context);
typePrinter.PushContext(CSharpTypePrinterContextKind.Native); typePrinter.PushContext(CSharpTypePrinterContextKind.Native);
typePrinter.PushMarshalKind(CSharpMarshalKind.GenericDelegate); typePrinter.PushMarshalKind(CSharpMarshalKind.GenericDelegate);
} }

2
src/Generator/Passes/FieldToPropertyPass.cs

@ -51,7 +51,7 @@ namespace CppSharp.Passes
@class.Properties.Add(prop); @class.Properties.Add(prop);
Log.Debug("Property created from field: {0}::{1}", @class.Name, Diagnostics.Debug("Property created from field: {0}::{1}", @class.Name,
field.Name); field.Name);
return false; return false;

7
src/Generator/Passes/FindSymbolsPass.cs

@ -21,8 +21,7 @@ namespace CppSharp.Passes
if (!base.VisitDeclaration(decl)) if (!base.VisitDeclaration(decl))
return false; return false;
var options = Driver.Options; if (!Options.CheckSymbols || Options.IsCLIGenerator)
if (!options.CheckSymbols || options.IsCLIGenerator)
return false; return false;
var mangledDecl = decl as IMangledDecl; var mangledDecl = decl as IMangledDecl;
@ -42,9 +41,9 @@ namespace CppSharp.Passes
{ {
var symbol = mangledDecl.Mangled; var symbol = mangledDecl.Mangled;
if (!Driver.Symbols.FindSymbol(ref symbol)) if (!Context.Symbols.FindSymbol(ref symbol))
{ {
Driver.Diagnostics.Warning("Symbol not found: {0}", symbol); Diagnostics.Warning("Symbol not found: {0}", symbol);
return false; return false;
} }

4
src/Generator/Passes/FunctionToInstanceMethodPass.cs

@ -59,12 +59,12 @@ namespace CppSharp.Passes
Conversion = MethodConversionKind.FunctionToInstanceMethod Conversion = MethodConversionKind.FunctionToInstanceMethod
}; };
if (Driver.Options.GeneratorKind == GeneratorKind.CSharp) if (Options.GeneratorKind == GeneratorKind.CSharp)
method.Parameters = method.Parameters.Skip(1).ToList(); method.Parameters = method.Parameters.Skip(1).ToList();
@class.Methods.Add(method); @class.Methods.Add(method);
Log.Debug("Function converted to instance method: {0}::{1}", @class.Name, Diagnostics.Debug("Function converted to instance method: {0}::{1}", @class.Name,
function.Name); function.Name);
return true; return true;

4
src/Generator/Passes/FunctionToStaticMethodPass.cs

@ -21,7 +21,7 @@ namespace CppSharp.Passes
if (types.Length == 0) if (types.Length == 0)
return false; return false;
var @class = AstContext.FindCompleteClass(types[0]); var @class = ASTContext.FindCompleteClass(types[0]);
if (@class == null) if (@class == null)
return false; return false;
@ -56,7 +56,7 @@ namespace CppSharp.Passes
@class.Methods.Add(method); @class.Methods.Add(method);
Log.Debug("Function converted to static method: {0}::{1}", Diagnostics.Debug("Function converted to static method: {0}::{1}",
@class.Name, function.Name); @class.Name, function.Name);
return true; return true;

6
src/Generator/Passes/GenerateInlinesCodePass.cs

@ -14,14 +14,14 @@ namespace CppSharp.Passes
private void WriteInlinesIncludes() private void WriteInlinesIncludes()
{ {
foreach (var module in Driver.Options.Modules) foreach (var module in Options.Modules)
{ {
var cppBuilder = new StringBuilder(); var cppBuilder = new StringBuilder();
foreach (var header in module.Headers) foreach (var header in module.Headers)
cppBuilder.AppendFormat("#include <{0}>\n", header); cppBuilder.AppendFormat("#include <{0}>\n", header);
var cpp = string.Format("{0}.cpp", module.InlinesLibraryName); var cpp = string.Format("{0}.cpp", module.InlinesLibraryName);
Directory.CreateDirectory(Driver.Options.OutputDir); Directory.CreateDirectory(Options.OutputDir);
var path = Path.Combine(Driver.Options.OutputDir, cpp); var path = Path.Combine(Options.OutputDir, cpp);
File.WriteAllText(path, cppBuilder.ToString()); File.WriteAllText(path, cppBuilder.ToString());
} }
} }

8
src/Generator/Passes/GenerateTemplatesCodePass.cs

@ -39,10 +39,10 @@ namespace CppSharp.Passes
private void WriteTemplateInstantiations() private void WriteTemplateInstantiations()
{ {
foreach (var module in Driver.Options.Modules.Where(m => templateInstantiations.ContainsKey(m))) foreach (var module in Options.Modules.Where(m => templateInstantiations.ContainsKey(m)))
{ {
var cppBuilder = new StringBuilder(); var cppBuilder = new StringBuilder();
if (module == Driver.Options.SystemModule) if (module == Options.SystemModule)
{ {
cppBuilder.Append("#include <string>\n"); cppBuilder.Append("#include <string>\n");
cppBuilder.Append("#include <vector>\n"); cppBuilder.Append("#include <vector>\n");
@ -55,8 +55,8 @@ namespace CppSharp.Passes
cppBuilder.AppendFormat("\ntemplate class {0}{1};", cppBuilder.AppendFormat("\ntemplate class {0}{1};",
Platform.IsWindows ? "__declspec(dllexport) " : string.Empty, templateInstantiation); Platform.IsWindows ? "__declspec(dllexport) " : string.Empty, templateInstantiation);
var cpp = string.Format("{0}.cpp", module.TemplatesLibraryName); var cpp = string.Format("{0}.cpp", module.TemplatesLibraryName);
Directory.CreateDirectory(Driver.Options.OutputDir); Directory.CreateDirectory(Options.OutputDir);
var path = Path.Combine(Driver.Options.OutputDir, cpp); var path = Path.Combine(Options.OutputDir, cpp);
File.WriteAllText(path, cppBuilder.ToString()); File.WriteAllText(path, cppBuilder.ToString());
} }
} }

12
src/Generator/Passes/GetterSetterToPropertyAdvancedPass.cs

@ -15,15 +15,15 @@ namespace CppSharp.Passes
{ {
private class PropertyGenerator private class PropertyGenerator
{ {
private readonly IDiagnostics log; private readonly IDiagnostics Diagnostics;
private readonly List<Method> getters = new List<Method>(); private readonly List<Method> getters = new List<Method>();
private readonly List<Method> setters = new List<Method>(); private readonly List<Method> setters = new List<Method>();
private readonly List<Method> setMethods = new List<Method>(); private readonly List<Method> setMethods = new List<Method>();
private readonly List<Method> nonSetters = new List<Method>(); private readonly List<Method> nonSetters = new List<Method>();
public PropertyGenerator(Class @class, IDiagnostics log) public PropertyGenerator(Class @class, IDiagnostics diags)
{ {
this.log = log; Diagnostics = diags;
foreach (var method in @class.Methods.Where( foreach (var method in @class.Methods.Where(
m => !m.IsConstructor && !m.IsDestructor && !m.IsOperator && m.IsGenerated)) m => !m.IsConstructor && !m.IsDestructor && !m.IsOperator && m.IsGenerated))
DistributeMethod(method); DistributeMethod(method);
@ -70,14 +70,14 @@ namespace CppSharp.Passes
var oldName = method.Name; var oldName = method.Name;
method.Name = string.Format("get{0}{1}", method.Name = string.Format("get{0}{1}",
char.ToUpperInvariant(method.Name[0]), method.Name.Substring(1)); char.ToUpperInvariant(method.Name[0]), method.Name.Substring(1));
log.Debug("Method {0}::{1} renamed to {2}", method.Namespace.Name, oldName, method.Name); Diagnostics.Debug("Method {0}::{1} renamed to {2}", method.Namespace.Name, oldName, method.Name);
} }
foreach (var @event in type.Events.Where(e => e.Name == name)) foreach (var @event in type.Events.Where(e => e.Name == name))
{ {
var oldName = @event.Name; var oldName = @event.Name;
@event.Name = string.Format("on{0}{1}", @event.Name = string.Format("on{0}{1}",
char.ToUpperInvariant(@event.Name[0]), @event.Name.Substring(1)); char.ToUpperInvariant(@event.Name[0]), @event.Name.Substring(1));
log.Debug("Event {0}::{1} renamed to {2}", @event.Namespace.Name, oldName, @event.Name); Diagnostics.Debug("Event {0}::{1} renamed to {2}", @event.Namespace.Name, oldName, @event.Name);
} }
getter.Name = name; getter.Name = name;
GenerateProperty(getter.Namespace, getter, readOnly ? null : setter); GenerateProperty(getter.Namespace, getter, readOnly ? null : setter);
@ -337,7 +337,7 @@ namespace CppSharp.Passes
if (baseClass.IsClass) if (baseClass.IsClass)
VisitClassDecl(baseClass.Class); VisitClassDecl(baseClass.Class);
new PropertyGenerator(@class, Log).GenerateProperties(); new PropertyGenerator(@class, Diagnostics).GenerateProperties();
} }
return false; return false;
} }

8
src/Generator/Passes/GetterSetterToPropertyPass.cs

@ -54,7 +54,7 @@ namespace CppSharp.Passes
var prop2 = @class.Properties.FirstOrDefault(property => property.Name == name); var prop2 = @class.Properties.FirstOrDefault(property => property.Name == name);
if (prop == null && prop2 != null) if (prop == null && prop2 != null)
Driver.Diagnostics.Debug("Property {0}::{1} already exists (type: {2})", Diagnostics.Debug("Property {0}::{1} already exists (type: {2})",
@class.Name, name, type.Type.ToString()); @class.Name, name, type.Type.ToString());
if (prop != null) if (prop != null)
@ -76,7 +76,7 @@ namespace CppSharp.Passes
if (!VisitDeclaration(method)) if (!VisitDeclaration(method))
return false; return false;
if (ASTUtils.CheckIgnoreMethod(method, Driver.Options)) if (ASTUtils.CheckIgnoreMethod(method, Options))
return false; return false;
var @class = method.Namespace as Class; var @class = method.Namespace as Class;
@ -100,7 +100,7 @@ namespace CppSharp.Passes
// Do not generate the original method now that we know it is a getter. // Do not generate the original method now that we know it is a getter.
method.GenerationKind = GenerationKind.Internal; method.GenerationKind = GenerationKind.Internal;
Driver.Diagnostics.Debug("Getter created: {0}::{1}", @class.Name, name); Diagnostics.Debug("Getter created: {0}::{1}", @class.Name, name);
return false; return false;
} }
@ -117,7 +117,7 @@ namespace CppSharp.Passes
// Ignore the original method now that we know it is a setter. // Ignore the original method now that we know it is a setter.
method.GenerationKind = GenerationKind.Internal; method.GenerationKind = GenerationKind.Internal;
Driver.Diagnostics.Debug("Setter created: {0}::{1}", @class.Name, name); Diagnostics.Debug("Setter created: {0}::{1}", @class.Name, name);
return false; return false;
} }

16
src/Generator/Passes/HandleDefaultParamValuesPass.cs

@ -68,7 +68,7 @@ namespace CppSharp.Passes
// constants are obtained through dynamic calls at present so they are not compile-time values in target languages // constants are obtained through dynamic calls at present so they are not compile-time values in target languages
if (expression.Declaration is Variable || if (expression.Declaration is Variable ||
(!Driver.Options.MarshalCharAsManagedChar && (!Options.MarshalCharAsManagedChar &&
desugared.IsPrimitiveType(PrimitiveType.UChar)) || desugared.IsPrimitiveType(PrimitiveType.UChar)) ||
type.IsPrimitiveTypeConvertibleToRef()) type.IsPrimitiveTypeConvertibleToRef())
return null; return null;
@ -120,7 +120,7 @@ namespace CppSharp.Passes
if (desugared.GetFinalPointee().TryGetClass(out @class) && @class.IsValueType) if (desugared.GetFinalPointee().TryGetClass(out @class) && @class.IsValueType)
{ {
result = string.Format("new {0}()", result = string.Format("new {0}()",
new CSharpTypePrinter(Driver).VisitClassDecl(@class)); new CSharpTypePrinter(Context).VisitClassDecl(@class));
return true; return true;
} }
@ -141,10 +141,10 @@ namespace CppSharp.Passes
TypeMap typeMap; TypeMap typeMap;
var typePrinter = new CSharpTypePrinter(Driver); var typePrinter = new CSharpTypePrinter(Context);
typePrinter.PushMarshalKind(CSharpMarshalKind.DefaultExpression); typePrinter.PushMarshalKind(CSharpMarshalKind.DefaultExpression);
var typePrinterResult = type.Visit(typePrinter).Type; var typePrinterResult = type.Visit(typePrinter).Type;
if (Driver.TypeDatabase.FindTypeMap(decl, type, out typeMap)) if (TypeDatabase.FindTypeMap(decl, type, out typeMap))
{ {
var typeInSignature = typeMap.CSharpSignatureType( var typeInSignature = typeMap.CSharpSignatureType(
typePrinter.TypePrinterContext).SkipPointerRefs().Desugar(); typePrinter.TypePrinterContext).SkipPointerRefs().Desugar();
@ -263,13 +263,13 @@ namespace CppSharp.Passes
{ {
statement.Declaration = null; statement.Declaration = null;
result = string.Format("(int) {0}.{1}", result = string.Format("(int) {0}.{1}",
new CSharpTypePrinter(Driver).VisitEnumDecl( new CSharpTypePrinter(Context).VisitEnumDecl(
(Enumeration) enumItem.Namespace), enumItem.Name); (Enumeration) enumItem.Namespace), enumItem.Name);
} }
else else
{ {
result = string.Format("{0}.{1}", result = string.Format("{0}.{1}",
new CSharpTypePrinter(Driver).VisitEnumDecl( new CSharpTypePrinter(Context).VisitEnumDecl(
(Enumeration) enumItem.Namespace), enumItem.Name); (Enumeration) enumItem.Namespace), enumItem.Name);
} }
return true; return true;
@ -292,7 +292,7 @@ namespace CppSharp.Passes
TypeMap typeMap; TypeMap typeMap;
if ((function.Parameters.Count == 0 || if ((function.Parameters.Count == 0 ||
HasSingleZeroArgExpression(function)) && HasSingleZeroArgExpression(function)) &&
Driver.TypeDatabase.FindTypeMap(desugared, out typeMap)) TypeDatabase.FindTypeMap(desugared, out typeMap))
{ {
var typeInSignature = typeMap.CSharpSignatureType(new CSharpTypePrinterContext var typeInSignature = typeMap.CSharpSignatureType(new CSharpTypePrinterContext
{ {
@ -324,7 +324,7 @@ namespace CppSharp.Passes
{ {
int value; int value;
if (int.TryParse(result, out value) && if (int.TryParse(result, out value) &&
((Driver.Options.MarshalCharAsManagedChar && ((Options.MarshalCharAsManagedChar &&
desugared.IsPrimitiveType(PrimitiveType.Char)) || desugared.IsPrimitiveType(PrimitiveType.Char)) ||
desugared.IsPrimitiveType(PrimitiveType.WideChar))) desugared.IsPrimitiveType(PrimitiveType.WideChar)))
{ {

2
src/Generator/Passes/IgnoreSystemDeclarationsPass.cs

@ -35,7 +35,7 @@ namespace CppSharp.Passes
public override bool VisitClassDecl(Class @class) public override bool VisitClassDecl(Class @class)
{ {
if (!base.VisitClassDecl(@class) || Driver.Options.IsCLIGenerator) if (!base.VisitClassDecl(@class) || Options.IsCLIGenerator)
return false; return false;
if (!@class.TranslationUnit.IsSystemHeader) if (!@class.TranslationUnit.IsSystemHeader)

6
src/Generator/Passes/MoveFunctionToClassPass.cs

@ -20,7 +20,7 @@ namespace CppSharp.Passes
if (@class != null && @class.TranslationUnit.Module == function.TranslationUnit.Module) if (@class != null && @class.TranslationUnit.Module == function.TranslationUnit.Module)
{ {
MoveFunction(function, @class); MoveFunction(function, @class);
Log.Debug("Function moved to class: {0}::{1}", @class.Name, function.Name); Diagnostics.Debug("Function moved to class: {0}::{1}", @class.Name, function.Name);
} }
if (function.IsOperator) if (function.IsOperator)
@ -34,10 +34,10 @@ namespace CppSharp.Passes
var unit = @namespace as TranslationUnit; var unit = @namespace as TranslationUnit;
if (unit == null) if (unit == null)
{ {
return Driver.ASTContext.FindClass( return ASTContext.FindClass(
@namespace.Name, ignoreCase: true).FirstOrDefault(); @namespace.Name, ignoreCase: true).FirstOrDefault();
} }
return Driver.ASTContext.FindCompleteClass( return ASTContext.FindCompleteClass(
unit.FileNameWithoutExtension.ToLowerInvariant(), true); unit.FileNameWithoutExtension.ToLowerInvariant(), true);
} }

2
src/Generator/Passes/MoveOperatorToClassPass.cs

@ -41,7 +41,7 @@ namespace CppSharp.Passes
@class.Methods.Add(method); @class.Methods.Add(method);
Driver.Diagnostics.Debug("Function converted to operator: {0}::{1}", Diagnostics.Debug("Function converted to operator: {0}::{1}",
@class.Name, function.Name); @class.Name, function.Name);
return true; return true;

15
src/Generator/Passes/ObjectOverridesPass.cs

@ -15,6 +15,13 @@ namespace CppSharp
// this to work. // this to work.
public class ObjectOverridesPass : TranslationUnitPass public class ObjectOverridesPass : TranslationUnitPass
{ {
private Generator Generator { get; set; }
public ObjectOverridesPass(Generator generator)
{
Generator = generator;
}
private bool needsStreamInclude; private bool needsStreamInclude;
private void OnUnitGenerated(GeneratorOutput output) private void OnUnitGenerated(GeneratorOutput output)
{ {
@ -67,7 +74,7 @@ namespace CppSharp
void GenerateEquals(Class @class, Block block, Method method) void GenerateEquals(Class @class, Block block, Method method)
{ {
var cliTypePrinter = new CLITypePrinter(Driver); var cliTypePrinter = new CLITypePrinter(Context);
var classCliType = @class.Visit(cliTypePrinter); var classCliType = @class.Visit(cliTypePrinter);
block.WriteLine("if (!object) return false;"); block.WriteLine("if (!object) return false;");
@ -93,7 +100,7 @@ namespace CppSharp
// FIXME: Add a better way to hook the event // FIXME: Add a better way to hook the event
if (!isHooked) if (!isHooked)
{ {
Driver.Generator.OnUnitGenerated += OnUnitGenerated; Generator.OnUnitGenerated += OnUnitGenerated;
isHooked = true; isHooked = true;
} }
@ -126,7 +133,7 @@ namespace CppSharp
@class.Methods.Add(toStringMethod); @class.Methods.Add(toStringMethod);
Driver.Diagnostics.Debug("Function converted to ToString: {0}::{1}", Diagnostics.Debug("Function converted to ToString: {0}::{1}",
@class.Name, method.Name); @class.Name, method.Name);
break; break;
@ -172,7 +179,7 @@ namespace CppSharp
AST.Type result; AST.Type result;
if (!typeCache.TryGetValue(typeName, out result)) if (!typeCache.TryGetValue(typeName, out result))
{ {
var typeDef = Driver.ASTContext.FindTypedef(typeName) var typeDef = ASTContext.FindTypedef(typeName)
.FirstOrDefault(); .FirstOrDefault();
if (typeDef != null) if (typeDef != null)
result = new TypedefType() { Declaration = typeDef }; result = new TypedefType() { Declaration = typeDef };

17
src/Generator/Passes/Pass.cs

@ -1,5 +1,6 @@
using CppSharp.AST; using CppSharp.AST;
using CppSharp.Generators; using CppSharp.Generators;
using CppSharp.Types;
namespace CppSharp.Passes namespace CppSharp.Passes
{ {
@ -9,19 +10,17 @@ namespace CppSharp.Passes
/// </summary> /// </summary>
public abstract class TranslationUnitPass : AstVisitor public abstract class TranslationUnitPass : AstVisitor
{ {
public Driver Driver { get; set; } public BindingContext Context { get; set; }
public ASTContext AstContext { get; set; }
public IDiagnostics Diagnostics { get { return Context.Diagnostics; } }
public IDiagnostics Log public DriverOptions Options { get { return Context.Options; } }
{ public ASTContext ASTContext { get { return Context.ASTContext; } }
get { return Driver.Diagnostics; } public TypeMapDatabase TypeDatabase { get { return Context.TypeDatabase; } }
}
public bool ClearVisitedDeclarations = false; public bool ClearVisitedDeclarations = false;
public virtual bool VisitLibrary(ASTContext context) public virtual bool VisitLibrary(ASTContext context)
{ {
AstContext = context;
foreach (var unit in context.TranslationUnits) foreach (var unit in context.TranslationUnits)
VisitTranslationUnit(unit); VisitTranslationUnit(unit);
@ -58,7 +57,7 @@ namespace CppSharp.Passes
/// </summary> /// </summary>
public abstract class GeneratorOutputPass public abstract class GeneratorOutputPass
{ {
public Driver Driver { get; set; } public IDiagnostics Log { get; set; }
public virtual void VisitGeneratorOutput(GeneratorOutput output) public virtual void VisitGeneratorOutput(GeneratorOutput output)
{ {

9
src/Generator/Passes/PassBuilder.cs

@ -1,6 +1,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using CppSharp.Generators;
using CppSharp.Passes; using CppSharp.Passes;
namespace CppSharp namespace CppSharp
@ -11,13 +12,13 @@ namespace CppSharp
/// </summary> /// </summary>
public class PassBuilder<T> public class PassBuilder<T>
{ {
public BindingContext Context { get; private set; }
public List<T> Passes { get; private set; } public List<T> Passes { get; private set; }
public Driver Driver { get; private set; }
public PassBuilder(Driver driver) public PassBuilder(BindingContext context)
{ {
Context = context;
Passes = new List<T>(); Passes = new List<T>();
Driver = driver;
} }
/// <summary> /// <summary>
@ -26,7 +27,7 @@ namespace CppSharp
public void AddPass(T pass) public void AddPass(T pass)
{ {
if (pass is TranslationUnitPass) if (pass is TranslationUnitPass)
(pass as TranslationUnitPass).Driver = Driver; (pass as TranslationUnitPass).Context = Context;
Passes.Add(pass); Passes.Add(pass);
} }

8
src/Generator/Passes/ResolveIncompleteDeclsPass.cs

@ -43,12 +43,12 @@ namespace CppSharp.Passes
goto Out; goto Out;
@enum.CompleteDeclaration = @enum.CompleteDeclaration =
AstContext.FindCompleteEnum(@enum.QualifiedName); ASTContext.FindCompleteEnum(@enum.QualifiedName);
if (@enum.CompleteDeclaration == null) if (@enum.CompleteDeclaration == null)
{ {
@enum.GenerationKind = GenerationKind.Internal; @enum.GenerationKind = GenerationKind.Internal;
Driver.Diagnostics.Warning("Unresolved declaration: {0}", @enum.Name); Diagnostics.Warning("Unresolved declaration: {0}", @enum.Name);
} }
Out: Out:
@ -65,12 +65,12 @@ namespace CppSharp.Passes
return; return;
declaration.CompleteDeclaration = declaration.CompleteDeclaration =
AstContext.FindCompleteClass(declaration.QualifiedName); ASTContext.FindCompleteClass(declaration.QualifiedName);
if (declaration.CompleteDeclaration == null) if (declaration.CompleteDeclaration == null)
{ {
declaration.GenerationKind = GenerationKind.Internal; declaration.GenerationKind = GenerationKind.Internal;
Driver.Diagnostics.Debug("Unresolved declaration: {0}", Diagnostics.Debug("Unresolved declaration: {0}",
declaration.Name); declaration.Name);
} }
} }

10
src/Generator/Types/Std/Stdlib.cs

@ -61,12 +61,12 @@ namespace CppSharp.Types.Std
{ {
var type = ctx.Parameter.Type.Desugar(); var type = ctx.Parameter.Type.Desugar();
ClassTemplateSpecialization basicString = GetBasicString(type); ClassTemplateSpecialization basicString = GetBasicString(type);
var typePrinter = new CSharpTypePrinter(ctx.Driver); var typePrinter = new CSharpTypePrinter(ctx.Context);
typePrinter.PushContext(CSharpTypePrinterContextKind.Native); typePrinter.PushContext(CSharpTypePrinterContextKind.Native);
if (!ctx.Parameter.Type.Desugar().IsAddress()) if (!ctx.Parameter.Type.Desugar().IsAddress())
ctx.Return.Write("*({0}*) ", basicString.Visit(typePrinter)); ctx.Return.Write("*({0}*) ", basicString.Visit(typePrinter));
typePrinter.PopContext(); typePrinter.PopContext();
var allocator = ctx.Driver.ASTContext.FindClass("allocator", false, true).First( var allocator = ctx.Context.ASTContext.FindClass("allocator", false, true).First(
a => a.IsDependent); a => a.IsDependent);
if (type.IsPointer() || (type.IsReference() && ctx.Declaration is Field)) if (type.IsPointer() || (type.IsReference() && ctx.Declaration is Field))
{ {
@ -97,7 +97,7 @@ namespace CppSharp.Types.Std
Declaration c_str = basicString.Methods.FirstOrDefault(m => m.OriginalName == "c_str"); Declaration c_str = basicString.Methods.FirstOrDefault(m => m.OriginalName == "c_str");
if (!c_str.IsGenerated) if (!c_str.IsGenerated)
c_str = basicString.Properties.First(p => p.OriginalName == "c_str"); c_str = basicString.Properties.First(p => p.OriginalName == "c_str");
var typePrinter = new CSharpTypePrinter(ctx.Driver); var typePrinter = new CSharpTypePrinter(ctx.Context);
if (type.IsPointer() || ctx.Declaration is Field) if (type.IsPointer() || ctx.Declaration is Field)
{ {
ctx.Return.Write("{0}.{1}({2}).{3}{4}", ctx.Return.Write("{0}.{1}({2}).{3}{4}",
@ -220,7 +220,7 @@ namespace CppSharp.Types.Std
QualifiedType = type QualifiedType = type
}; };
var elementCtx = new MarshalContext(ctx.Driver) var elementCtx = new MarshalContext(ctx.Context)
{ {
Parameter = param, Parameter = param,
ArgName = param.Name, ArgName = param.Name,
@ -265,7 +265,7 @@ namespace CppSharp.Types.Std
ctx.ReturnVarName); ctx.ReturnVarName);
ctx.SupportBefore.WriteStartBraceIndent(); ctx.SupportBefore.WriteStartBraceIndent();
{ {
var elementCtx = new MarshalContext(ctx.Driver) var elementCtx = new MarshalContext(ctx.Context)
{ {
ReturnVarName = "_element", ReturnVarName = "_element",
ReturnType = type ReturnType = type

Loading…
Cancel
Save