diff --git a/src/AST/SymbolContext.cs b/src/AST/SymbolContext.cs new file mode 100644 index 00000000..8acca9a9 --- /dev/null +++ b/src/AST/SymbolContext.cs @@ -0,0 +1,106 @@ +using System.Collections.Generic; + +namespace CppSharp.AST +{ + /// + /// Represents a shared library or a static library archive. + /// + public class NativeLibrary + { + public NativeLibrary(string file) + : this() + { + FileName = file; + } + + public NativeLibrary() + { + Symbols = new List(); + } + + /// + /// File name of the library. + /// + public string FileName; + + /// + /// Symbols gathered from the library. + /// + public IList Symbols; + } + + public class SymbolContext + { + /// + /// List of native libraries. + /// + public List Libraries; + + /// + /// Index of all symbols to their respective libraries. + /// + public Dictionary Symbols; + + public SymbolContext() + { + Libraries = new List(); + Symbols = new Dictionary(); + } + + public NativeLibrary FindOrCreateLibrary(string file) + { + var library = Libraries.Find(m => m.FileName.Equals(file)); + + if (library == null) + { + library = new NativeLibrary(file); + Libraries.Add(library); + } + + return library; + } + + public void IndexSymbols() + { + foreach (var library in Libraries) + { + foreach (var symbol in library.Symbols) + Symbols[symbol] = library; + } + } + + public bool FindSymbol(ref string symbol) + { + NativeLibrary lib; + + if (FindLibraryBySymbol(symbol, out lib)) + return true; + + // Check for C symbols with a leading underscore. + if (FindLibraryBySymbol("_" + symbol, out lib)) + { + symbol = "_" + symbol; + return true; + } + + if (FindLibraryBySymbol("_imp_" + symbol, out lib)) + { + symbol = "_imp_" + symbol; + return true; + } + + if (FindLibraryBySymbol("__imp_" + symbol, out lib)) + { + symbol = "__imp_" + symbol; + return true; + } + + return false; + } + + public bool FindLibraryBySymbol(string symbol, out NativeLibrary library) + { + return Symbols.TryGetValue(symbol, out library); + } + } +}