Ejemplo n.º 1
0
 VisualBasicSyntaxNode Convert(CSharpSyntaxNode input, SemanticModel semanticModel, Document targetDocument)
 {
     return(CSharpConverter.Convert(input, semanticModel, targetDocument));
 }
Ejemplo n.º 2
0
        private static int Main(string[] _)
        {
            if (string.IsNullOrWhiteSpace(MlSdkPath))
            {
                Console.WriteLine("No mlsdk environment variable is defined. Make sure you have downloaded the latest magic leap sdk from The Lab, and define this path to the sdk version you wish to use. ex: \"C:\\Users\\your-account\\MagicLeap\\mlsdk\"");
                Console.WriteLine("Press any key to exit...");
                Console.ReadLine();
                return(1);
            }

            Console.WriteLine($"Found mlsdk at path: {MlSdkPath}");
            //Directory.GetFiles($"{BaseSdkPath}include", "*.h", SearchOption.TopDirectoryOnly).ToList();
            var files = new List <string>
            {
                $"{BaseSdkPath}include\\ml_camera.h",
                $"{BaseSdkPath}include\\ml_camera_metadata.h",
                $"{BaseSdkPath}include\\ml_lifecycle.h",
                $"{BaseSdkPath}include\\ml_graphics.h",
                $"{BaseSdkPath}include\\ml_graphics_utils.h",
                $"{BaseSdkPath}include\\ml_input.h",
                $"{BaseSdkPath}include\\ml_logging.h",
                $"{BaseSdkPath}include\\ml_movement.h",
                $"{BaseSdkPath}include\\ml_controller.h",
                $"{BaseSdkPath}include\\ml_aruco_tracking.h",
                $"{BaseSdkPath}include\\ml_cv_camera.h",
                $"{BaseSdkPath}include\\ml_data_array.h",
                $"{BaseSdkPath}include\\ml_eye_tracking.h",
                $"{BaseSdkPath}include\\ml_found_object.h",
                $"{BaseSdkPath}include\\ml_hand_meshing.h",
                $"{BaseSdkPath}include\\ml_hand_tracking.h",
                $"{BaseSdkPath}include\\ml_head_tracking.h",
                $"{BaseSdkPath}include\\ml_image_tracking.h",
                $"{BaseSdkPath}include\\ml_lighting_tracking.h",
                $"{BaseSdkPath}include\\ml_meshing2.h",
                $"{BaseSdkPath}include\\ml_perception.h",
                $"{BaseSdkPath}include\\ml_persistent_coordinate_frames.h",
                $"{BaseSdkPath}include\\ml_planes.h",
                $"{BaseSdkPath}include\\ml_raycast.h",
                $"{BaseSdkPath}include\\ml_snapshot.h",
            };

            var csOptions = new CSharpConverterOptions
            {
                GenerateAsInternal               = true,
                GenerateEnumItemAsFields         = true,
                DispatchOutputPerInclude         = true,
                DefaultDllImportNameAndArguments = "ERROR",
                MappingRules =
                {
                    // DllImportLibrary in later version of CppAst.CodeGen
                    //e => e.Map("*").DllImportLibrary("\"ml_camera\"", "ml_camera.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_camera_metadata\"", "ml_camera_metadata.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_lifecycle\"", "ml_lifecycle.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_lifecycle\"", "ml_fileinfo.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_graphics\"", "ml_graphics.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_graphics_utils\"", "ml_graphics_utils.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_input\"", "ml_input.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_ext_logging\"", "ml_logging.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_movement\"", "ml_movement.h"),

                    //e => e.Map("*").DllImportLibrary("\"ml_perception_client\"", "ml_controller.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_perception_client\"", "ml_aruco_tracking.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_perception_client\"", "ml_cv_camera.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_perception_client\"", "ml_data_array.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_perception_client\"", "ml_eye_tracking.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_perception_client\"", "ml_found_object.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_perception_client\"", "ml_hand_meshing.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_perception_client\"", "ml_hand_tracking.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_perception_client\"", "ml_head_tracking.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_perception_client\"", "ml_image_tracking.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_perception_client\"", "ml_lighting_tracking.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_perception_client\"", "ml_meshing2.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_perception_client\"", "ml_perception.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_perception_client\"", "ml_persistent_coordinate_frames.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_perception_client\"", "ml_planes.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_perception_client\"", "ml_raycast.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_perception_client\"", "ml_snapshot.h"),

                    //e => e.Map("*").DllImportLibrary("\"ml_audio\"", "ml_audio.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_app_connect\"", "ml_app_connect.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_avatar\"", "ml_avatar.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_bluetooth_adapter\"", "ml_bluetooth_adapter.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_bluetooth_gatt\"", "ml_bluetooth_gatt.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_bluetooth_le\"", "ml_bluetooth_le.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_bluetooth\"", "ml_bluetooth.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_connections\"", "ml_connections.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_contacts\"", "ml_contacts.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_dca\"", "ml_dca.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_dispatch\"", "ml_dispatch.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_identity\"", "ml_identity.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_identity\"", "ml_token_identity.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_locale\"", "ml_locale.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_location\"", "ml_location.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_media_ccparser\"", "ml_media_cea608_caption.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_media_ccparser\"", "ml_media_cea708_caption.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_mediacodec\"", "ml_mediacodec.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_mediacodeclist\"", "ml_mediacodeclist.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_mediacrypto\"", "ml_media_crypto.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_media_data_source\"", "ml_media_data_source.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_mediadrm\"", "ml_media_drm.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_mediaerror\"", "ml_media_error.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_mediaextractor\"", "ml_media_extractor.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_mediaformat\"", "ml_media_format.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_mediaplayer\"", "ml_media_player.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_mediastream_source\"", "ml_mediastream_source.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_mediacodec\"", "ml_media_surface_texture.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_musicservice_provider\"", "ml_musicservice_provider.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_musicservice\"", "ml_music_service.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_networking\"", "ml_networking.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_platform\"", "ml_platform.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_privileges\"", "ml_privilege_functions.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_purchase\"", "ml_purchase.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_remote\"", "ml_remote.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_screens\"", "ml_screens.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_secure_storage\"", "ml_secure_storage.h"),
                    //e => e.Map("*").DllImportLibrary("\"ml_sharedfile\"", "ml_sharedfile.h"),
                }
            };

            var csCompilation = CSharpConverter.Convert(files, csOptions);

            if (csCompilation.HasErrors)
            {
                foreach (var message in csCompilation.Diagnostics.Messages)
                {
                    Console.Error.WriteLine(message);
                }

                Console.Error.WriteLine("Unexpected parsing errors");
                Console.WriteLine("Press any key to exit...");
                Console.ReadLine();
                return(1);
            }

            var fileSystem = new PhysicalFileSystem();

            csCompilation.DumpTo(
                new CodeWriter(
                    new CodeWriterOptions(
                        new SubFileSystem(fileSystem, fileSystem.ConvertPathFromInternal(OUTPUT_DIRECTORY)))));

            Console.WriteLine("Press any key to exit...");
            Console.ReadLine();
            return(0);
        }
Ejemplo n.º 3
0
        static void Main(string[] args)
        {
            // RAML files to be processed
            string[] inputFiles = null;

            // read config file
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json");

            Configuration = builder.Build();

            var appconfig = new AppConfig();

            Configuration.Bind(appconfig);

            string fileName             = appconfig.InputFileName;
            string inputDirectory       = appconfig.InputDirectory;
            string outputDirectory      = appconfig.OutputDirectory;
            bool   generateXml          = appconfig.GenerateXmlSchema.HasValue ? appconfig.GenerateXmlSchema.Value : false;
            bool   generateJson         = appconfig.GenerateJsonSchema.HasValue ? appconfig.GenerateJsonSchema.Value : false;
            bool   generateCSharp       = appconfig.GenerateCSharpCode.HasValue ? appconfig.GenerateCSharpCode.Value : false;
            bool   generateTypeScript   = appconfig.GenerateTypeScriptCode.HasValue ? appconfig.GenerateTypeScriptCode.Value : false;
            bool   generateDescriptions = appconfig.GenerateDescriptions.HasValue ? appconfig.GenerateDescriptions.Value : false;

            RootTypeNames = appconfig.RootTypes;


            if (inputDirectory == null)
            {
                inputDirectory = Directory.GetCurrentDirectory();
            }

            if (outputDirectory == null)
            {
                outputDirectory = inputDirectory;
            }

            string xmlNamespace        = "http://tempuri.org/";
            string xmlOutputDirectory  = null;
            string csNamespace         = "DataContract";
            string csOutputDirectory   = null;
            string jsonOutputDirectory = null;
            string tsOutputDirectory   = null;
            int?   tsIndentSize        = null;

            var csconfig = new CSharpConfig();

            Configuration.GetSection(ConfigurationStrings.CSharpSectionName).Bind(csconfig);
            if (!string.IsNullOrEmpty(csconfig.Namespace))
            {
                csNamespace = csconfig.Namespace;
            }
            csOutputDirectory = csconfig.OutputDirectory;

            var tsonconfig = new TypeScriptConfig();

            Configuration.GetSection(ConfigurationStrings.TypeScriptSectionName).Bind(tsonconfig);
            bool tsDisableTSLint = false;

            if (tsonconfig != null)
            {
                tsOutputDirectory = tsonconfig.OutputDirectory;
                if (tsonconfig.IndentSize.HasValue)
                {
                    tsIndentSize = tsonconfig.IndentSize.Value;
                }
                if (tsonconfig.DisableTSLint.HasValue)
                {
                    tsDisableTSLint = tsonconfig.DisableTSLint.Value;
                }
            }

            var jsonconfig = new JsonSchemaConfig();

            Configuration.GetSection(ConfigurationStrings.JsonSectionName).Bind(jsonconfig);
            jsonOutputDirectory = jsonconfig.OutputDirectory;

            var xmlconfig = new XmlSchemaConfig();

            Configuration.GetSection(ConfigurationStrings.XmlSectionName).Bind(xmlconfig);
            xmlNamespace       = xmlconfig.Namespace;
            xmlOutputDirectory = xmlconfig.OutputDirectory;


            // override using input parameters
            foreach (string arg in args)
            {
                if (string.Compare(arg, 0, "/file:", 0, 6, true) == 0)
                {
                    fileName = arg.Substring(6);
                }
                else if (string.Compare(arg, 0, "/xmlNS:", 0, 7, true) == 0)
                {
                    xmlNamespace = arg.Substring(7);
                }
                else if (string.Compare(arg, 0, "/csNS:", 0, 74, true) == 0)
                {
                    csNamespace = arg.Substring(6);
                }
                else if (string.Compare(arg, 0, "/cs", 0, 3, true) == 0)
                {
                    generateCSharp = true;
                }
                else if (string.Compare(arg, 0, "/ts", 0, 3, true) == 0)
                {
                    generateTypeScript = true;
                }
                else if (string.Compare(arg, 0, "/inputDir:", 0, 10, true) == 0)
                {
                    inputDirectory = arg.Substring(10);
                }
                else if (string.Compare(arg, 0, "/outputDir:", 0, 11, true) == 0)
                {
                    outputDirectory = arg.Substring(11);
                }
                else if (string.Compare(arg, 0, "/xml", 0, 4, true) == 0)
                {
                    generateXml = true;
                }
                else if (string.Compare(arg, 0, "/json", 0, 5, true) == 0)
                {
                    generateJson = true;
                }
                else if (string.Compare(arg, 0, "/desc", 0, 5, true) == 0)
                {
                    generateDescriptions = true;
                }
                else
                {
                    Console.WriteLine(ErrorMessages.UnrecognizedParameter, arg);
                    ShowHelp();
                    return;
                }
            }

            if (!string.IsNullOrEmpty(fileName))  // do single file if it was specified
            {
                inputFiles    = new string[1];
                inputFiles[0] = Path.GetFullPath(fileName);
            }
            else
            {
                inputFiles = Directory.GetFiles(Path.GetFullPath(inputDirectory), "*." + FileExtensions.Raml);
            }

            var options = new ConversionOptions()
            {
                GenerateDescriptions = generateDescriptions,
                XmlNamespace         = xmlNamespace,
                CSharpNamespace      = csNamespace,
                OutputDirectory      = outputDirectory
            };


            foreach (string file in inputFiles)
            {
                var ramlFile = new RamlFile(file);

                if (generateJson)
                {
                    if (!string.IsNullOrEmpty(jsonOutputDirectory))
                    {
                        options.OutputDirectory = jsonOutputDirectory;
                    }

                    var jsonConverter = new JsonConverter(ramlFile);
                    jsonConverter.ConvertRaml(options);
                }

                if (generateXml)
                {
                    if (!string.IsNullOrEmpty(xmlOutputDirectory))
                    {
                        options.OutputDirectory = xmlOutputDirectory;
                    }

                    var xmlConverter = new XmlConverter(ramlFile);
                    xmlConverter.ConvertRaml(options);
                }
                if (generateCSharp)
                {
                    if (!string.IsNullOrEmpty(csOutputDirectory))
                    {
                        options.OutputDirectory = csOutputDirectory;
                    }

                    var cSharpConverter = new CSharpConverter(ramlFile);
                    cSharpConverter.ConvertRaml(options);
                }
                if (generateTypeScript)
                {
                    if (!string.IsNullOrEmpty(tsOutputDirectory))
                    {
                        options.OutputDirectory = tsOutputDirectory;
                    }
                    if (tsIndentSize.HasValue)
                    {
                        options.IndentSize = tsIndentSize;
                    }

                    options.DisableTSLint = tsDisableTSLint;

                    var typeScriptConverter = new TypeScriptConverter(ramlFile);
                    typeScriptConverter.ConvertRaml(options);
                }
            }
        }
Ejemplo n.º 4
0
 public void Register(CSharpConverter converter, CSharpConverterPipeline pipeline)
 {
     pipeline.EnumConverters.Add(ConvertEnum);
 }
Ejemplo n.º 5
0
 VisualBasicSyntaxNode Convert(CSharpSyntaxNode input, SemanticModel semanticModel)
 {
     return(CSharpConverter.Convert(input, semanticModel));
 }
Ejemplo n.º 6
0
        private static void GenerateElf()
        {
            var cppOptions = new CSharpConverterOptions()
            {
                DefaultClassLib                  = "ElfNative",
                DefaultNamespace                 = "LibObjectFile.Elf",
                DefaultOutputFilePath            = "/LibObjectFile.Elf.generated.cs",
                DefaultDllImportNameAndArguments = "NotUsed",
                MappingRules =
                {
                    map => map.MapMacroToConst("^EI.*",           "uint8_t"),
                    map => map.MapMacroToConst("^ELFMAG\\d",      "uint8_t"),
                    map => map.MapMacroToConst("^ELFCLASS.*",     "uint8_t"),
                    map => map.MapMacroToConst("^ELFDATA.*",      "uint8_t"),
                    map => map.MapMacroToConst("^ELFOSABI.*",     "uint8_t"),
                    map => map.MapMacroToConst("^ET_.*",          "uint16_t"),
                    map => map.MapMacroToConst("^EM_.*",          "uint16_t"),
                    map => map.MapMacroToConst("^EV_.*",          "uint8_t"),
                    map => map.MapMacroToConst("^SHN_.*",         "uint32_t"),
                    map => map.MapMacroToConst("^SHT_.*",         "uint32_t"),
                    map => map.MapMacroToConst("^SHF_.*",         "uint32_t"),
                    map => map.MapMacroToConst("^EF_.*",          "uint32_t"),
                    map => map.MapMacroToConst("^PT_.*",          "uint32_t"),
                    map => map.MapMacroToConst("^PF_.*",          "uint32_t"),
                    map => map.MapMacroToConst("^NT_.*",          "uint32_t"),
                    map => map.MapMacroToConst("^DT_.*",          "int32_t"),
                    map => map.MapMacroToConst("^DF_.*",          "uint32_t"),
                    map => map.MapMacroToConst("^DTF_.*",         "uint32_t"),
                    map => map.MapMacroToConst("^VER_DEF_.*",     "uint16_t"),
                    map => map.MapMacroToConst("^VER_FLG_.*",     "uint16_t"),
                    map => map.MapMacroToConst("^VER_NDX_.*",     "uint16_t"),
                    map => map.MapMacroToConst("^VER_NEED_.*",    "uint16_t"),
                    map => map.MapMacroToConst("^ELFCOMPRESS_.*", "int32_t"),
                    map => map.MapMacroToConst("^SYMINFO_.*",     "uint16_t"),
                    map => map.MapMacroToConst("^STB_.*",         "uint8_t"),
                    map => map.MapMacroToConst("^STT_.*",         "uint8_t"),
                    map => map.MapMacroToConst("^STN_.*",         "uint8_t"),
                    map => map.MapMacroToConst("^STV_.*",         "uint8_t"),
                    map => map.MapMacroToConst("^R_.*",           "uint32_t"),
                    map => map.MapMacroToConst("ELF_NOTE_OS_.*",  "uint32_t"),
                }
            };

            cppOptions.ConfigureForWindowsMsvc(CppTargetCpu.X86_64);
            cppOptions.Defines.Add("_AMD64_");
            cppOptions.Defines.Add("_TARGET_AMD64_");
            cppOptions.Defines.Add("STARK_NO_ENUM_FLAG");
            cppOptions.GenerateEnumItemAsFields = false;
            cppOptions.IncludeFolders.Add(Environment.CurrentDirectory);

            var csCompilation = CSharpConverter.Convert(@"#include ""elf.h""", cppOptions);

            AssertCompilation(csCompilation);

            // Add pragma
            var csFile = csCompilation.Members.OfType <CSharpGeneratedFile>().First();
            var ns     = csFile.Members.OfType <CSharpNamespace>().First();

            csFile.Members.Insert(csFile.Members.IndexOf(ns), new CSharpLineElement("#pragma warning disable 1591"));

            ProcessEnum(cppOptions, csCompilation, "EM_", "ElfArch");
            ProcessEnum(cppOptions, csCompilation, "ELFOSABI_", "ElfOSABI");
            ProcessEnum(cppOptions, csCompilation, "R_", "ElfRelocationType");
            ProcessEnum(cppOptions, csCompilation, "NT_", "ElfNoteType");

            csCompilation.DumpTo(GetCodeWriter(Path.Combine("LibObjectFile", "generated")));
        }
Ejemplo n.º 7
0
        public static void ProcessFile(string inputFile, string outputPath, string outputFile, string defaultNamespace, string defaultClass)
        {
            inputFile = Path.GetFullPath(inputFile);

            Console.WriteLine($"Processing file '{Path.GetFileName(inputFile)}'...");

            //Writing
            var converterOptions = new CSharpConverterOptions()
            {
                DefaultNamespace                 = defaultNamespace,
                DefaultClassLib                  = defaultClass,
                DefaultOutputFilePath            = outputFile,
                DefaultDllImportNameAndArguments = "Library",
                DispatchOutputPerInclude         = false,
                GenerateEnumItemAsFields         = false,
                TypedefCodeGenKind               = CppTypedefCodeGenKind.NoWrap,

                MappingRules =
                {
                    //Remove prefixes from elements' names.
                    e => e.MapAll <CppElement>().CppAction((converter,                                                        element) => {
                        if (element is ICppMember member)
                        {
                            string prefix = member switch {
                                CppType _ => "IPL",
                                CppEnumItem _ => "IPL_",
                                _ => null
                            };

                            if (prefix != null)
                            {
                                member.Name = StringUtils.Capitalize(StringUtils.RemovePrefix(member.Name,                    prefix));
                            }
                        }
                    }).CSharpAction((converter,                                                                               element) => {
                        if (element is CSharpMethod method)
                        {
                            const string Prefix = "ipl";

                            string oldName = method.Name;
                            string newName = StringUtils.Capitalize(StringUtils.RemovePrefix(oldName,                         Prefix));

                            //Add an EntryPoint parameter to the DllImportAttribute, so that this rename doesn't break anything.
                            if (method.Attributes.FirstOrDefault(attrib => attrib is CSharpDllImportAttribute) is CSharpDllImportAttribute dllImportAttribute)
                            {
                                dllImportAttribute.EntryPoint = $@"""{oldName}""";
                            }

                            method.Name = newName;
                        }
                    }),

                    //Replace the bool enum with an actual bool.
                    e => e.Map <CppEnum>("Bool").Discard(),
                    e => e.MapAll <CppDeclaration>().CSharpAction((converter,                                                 element) => {
                        CSharpType type;
                        Action <CSharpType> setType;

                        if (element is CSharpField field)
                        {
                            type    = field.FieldType;
                            setType = value => field.FieldType = value;
                        }
                        else if (element is CSharpParameter parameter)
                        {
                            type    = parameter.ParameterType;
                            setType = value => parameter.ParameterType = value;
                        }
                        else
                        {
                            return;
                        }

                        if (type is CSharpFreeType freeType && freeType.Text == "unsupported_type /* enum Bool {...} */")
                        {
                            var boolean = converter.GetCSharpType(CppPrimitiveType.Bool,                                      element);

                            setType(boolean);

                            if (boolean is CSharpTypeWithAttributes typeWithAttributes)
                            {
                                foreach (CSharpMarshalAttribute attribute in typeWithAttributes.Attributes.Where(a => a is CSharpMarshalAttribute))
                                {
                                    attribute.UnmanagedType = CSharpUnmanagedKind.U4;
                                }
                            }
                        }
                    }),

                    //Rename enum elements from SCREAMING_SNAKECASE to LameupperCamelcase. There are manual fixes below, for cases where words aren't separated.
                    e => e.MapAll <CppEnumItem>().CppAction((converter,                                                       element) => {
                        var enumItem = (CppEnumItem)element;

                        string name     = enumItem.Name;
                        string[] splits = name.Split('_');

                        if (splits.Length > 1)
                        {
                            string prefix = splits[0];

                            //Remove (potentially partial) prefixes of enum's name on its items' names.
                            if (name.Length > prefix.Length + 1 && name.StartsWith(prefix,                                    StringComparison.InvariantCultureIgnoreCase))
                            {
                                name   = name.Substring(prefix.Length + 1);
                                splits = name.Split('_');
                            }

                            //Capitalize each part
                            for (int i = 0; i < splits.Length; i++)
                            {
                                string split = splits[i];
                                char[] chars = split.ToCharArray();

                                for (int j = 0; j < chars.Length; j++)
                                {
                                    chars[j] = j == 0 ? char.ToUpper(chars[j]) : char.ToLower(chars[j]);
                                }

                                splits[i] = new string(chars);
                            }

                            name = string.Join(string.Empty,                                                                  splits);
                        }

                        enumItem.Name = name;
                    }),

                    //Fix weird 'ref void' parameters.
                    e => e.MapAll <CppParameter>().CSharpAction((converter,                                                   element) => {
                        var parameter     = (CSharpParameter)element;
                        var parameterType = parameter.ParameterType;

                        if (parameterType is CSharpRefType refType && refType.ElementType is CSharpPrimitiveType primitiveType && primitiveType.Kind == CSharpPrimitiveKind.Void)
                        {
                            parameter.ParameterType = CSharpPrimitiveType.IntPtr;
                        }
                    }),

                    //Turn some 'ref' parameters to 'out' or 'in' based on \param documentation.
                    e => e.MapAll <CppParameter>().CSharpAction((converter,                                                   element) => {
                        var parameter = (CSharpParameter)element;

                        if (!(parameter.ParameterType is CSharpRefType refParameterType))
                        {
                            return;
                        }

                        if (!(element.Parent is CSharpMethod method) || !(method.CppElement is CppFunction function))
                        {
                            return;
                        }

                        if (!(function.Comment?.Children?.FirstOrDefault(c => c is CppCommentParamCommand pc && pc.ParamName == parameter.Name) is CppCommentParamCommand parameterComment))
                        {
                            return;
                        }

                        if (!(parameterComment?.Children?.FirstOrDefault() is CppCommentParagraph paragraph))
                        {
                            return;
                        }

                        string paragraphText = paragraph.ToString().Trim();

                        if (paragraphText.StartsWith("[out]"))
                        {
                            refParameterType.Kind = CSharpRefKind.Out;
                        }
                        else if (paragraphText.StartsWith("[in]"))                            //Never actually used
                        {
                            refParameterType.Kind = CSharpRefKind.In;
                        }
                    }),

                    //Turn a 2D fixed array into an 1D one.
                    e => e.Map <CppField>("Matrix4x4::elements").Type("float",                                       16),

                    //Manually fix casing on some enum properties. This could theoretically be made automatic through crazy dictionary-based algorithms, but that's overkill.
                    e => e.Map <CppEnumItem>("Error::Outofmemory").Name("OutOfMemory"),
                    e => e.Map <CppEnumItem>("SceneType::Radeonrays").Name("RadeonRays"),
                    e => e.Map <CppEnumItem>("ConvolutionType::Trueaudionext").Name("TrueAudioNext"),
                    e => e.Map <CppEnumItem>("ChannelLayout::Fivepointone").Name("FivePointOne"),
                    e => e.Map <CppEnumItem>("ChannelLayout::Sevenpointone").Name("SevenPointOne"),
                    e => e.Map <CppEnumItem>("AmbisonicsOrdering::Fursemalham").Name("FurseMalham"),
                    e => e.Map <CppEnumItem>("AmbisonicsNormalization::Fursemalham").Name("FurseMalham"),
                    e => e.Map <CppEnumItem>("AmbisonicsNormalization::Sn3d").Name("SN3D"),
                    e => e.Map <CppEnumItem>("AmbisonicsNormalization::N3d").Name("N3D"),
                    e => e.Map <CppEnumItem>("DistanceAttenuationModelType::Inversedistance").Name("InversedDistance"),
                    e => e.Map <CppEnumItem>("DirectOcclusionMode::Notransmission").Name("NoTransmission"),
                    e => e.Map <CppEnumItem>("DirectOcclusionMode::Transmissionbyvolume").Name("TransmissionByVolume"),
                    e => e.Map <CppEnumItem>("DirectOcclusionMode::Transmissionbyfrequency").Name("TransmissionByFrequency"),
                    e => e.Map <CppEnumItem>("BakedDataType::Staticsource").Name("StaticSource"),
                    e => e.Map <CppEnumItem>("BakedDataType::Staticlistener").Name("StaticListener"),
                    e => e.Map <CppEnumItem>("BakedDataType::Uniformfloor").Name("UniformFloor"),
                }
            };

            converterOptions.IncludeFolders.Add(Path.GetDirectoryName(inputFile));

            var compilation = CSharpConverter.Convert(new List <string> {
                inputFile
            }, converterOptions);

            if (compilation.HasErrors)
            {
                foreach (var message in compilation.Diagnostics.Messages)
                {
                    if (message.Type == CppLogMessageType.Error)
                    {
                        Console.WriteLine(message);
                    }
                }

                Console.ReadKey();

                return;
            }

            using var fileSystem    = new PhysicalFileSystem();
            using var subFileSystem = new SubFileSystem(fileSystem, fileSystem.ConvertPathFromInternal(outputPath));

            var codeWriterOptions = new CodeWriterOptions(subFileSystem);
            var codeWriter        = new CodeWriter(codeWriterOptions);

            compilation.DumpTo(codeWriter);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Generates the PInvoke layer from Monocypher C header files.
        /// - Raw functions
        /// - The same functions using Span&lt;T&gt; when possible
        /// </summary>
        public void GeneratePInvoke()
        {
            var srcFolder  = Path.Combine(MonocypherFolder, "src");
            var destFolder = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, @"..\..\..\..\..\Monocypher"));

            if (!Directory.Exists(srcFolder))
            {
                throw new DirectoryNotFoundException($"The source folder `{srcFolder}` doesn't exist");
            }
            if (!Directory.Exists(destFolder))
            {
                throw new DirectoryNotFoundException($"The destination folder `{destFolder}` doesn't exist");
            }


            var marshalNoFreeNative = new CSharpMarshalAttribute(CSharpUnmanagedKind.CustomMarshaler)
            {
                MarshalTypeRef = "typeof(UTF8MarshallerNoFree)"
            };

            var csOptions = new CSharpConverterOptions()
            {
                DefaultClassLib                  = "Monocypher",
                DefaultNamespace                 = "Monocypher",
                DefaultOutputFilePath            = "/Monocypher.generated.cs",
                DefaultDllImportNameAndArguments = "MonocypherDll",
                GenerateAsInternal               = false,
                DispatchOutputPerInclude         = false,

                MappingRules =
                {
                    e => e.Map <CppField>("crypto_blake2b_vtable").Discard(),
                    e => e.Map <CppField>("crypto_sha512_vtable").Discard(),
                }
            };

            csOptions.Plugins.Insert(0, new FixedArrayTypeConverter());
            csOptions.IncludeFolders.Add(srcFolder);
            var files = new List <string>()
            {
                Path.Combine(srcFolder, "monocypher.h"),
                Path.Combine(srcFolder, "optional", "monocypher-ed25519.h"),
            };

            var csCompilation = CSharpConverter.Convert(files, csOptions);

            if (csCompilation.HasErrors)
            {
                foreach (var message in csCompilation.Diagnostics.Messages)
                {
                    Console.Error.WriteLine(message);
                }
                Console.Error.WriteLine("Unexpected parsing errors");
                Environment.Exit(1);
            }


            var monocypher = csCompilation.Members.OfType <CSharpGeneratedFile>().First().Members.OfType <CSharpNamespace>().First().Members.OfType <CSharpClass>().First();

            ProcessInvokeFunctions(monocypher);

            var fs = new PhysicalFileSystem();

            {
                var subfs      = new SubFileSystem(fs, fs.ConvertPathFromInternal(destFolder));
                var codeWriter = new CodeWriter(new CodeWriterOptions(subfs));
                csCompilation.DumpTo(codeWriter);
            }
        }
Ejemplo n.º 9
0
        public void CheckFunction()
        {
            var options = new CSharpConverterOptions()
            {
                GenerateAsInternal   = true,
                TypedefCodeGenKind   = CppTypedefCodeGenKind.Wrap,
                TypedefWrapWhiteList =
                {
                    "git_my_string"
                }
            };

            var csCompilation = CSharpConverter.Convert(@"
            #ifdef WIN32
            #define EXPORT_API __declspec(dllexport)
            #else
            #define EXPORT_API __attribute__((visibility(""default"")))
            #endif

            enum Toto
            {
                TOTO = 0,
                TOTO_FLAG = 1 << 0,
            };

            // This is a comment
            struct Tata
            {
                int a;

                int b;
                int c;
                char items[4];
                int item2[8];

                const char* d;
            };

            struct git_my_repo;

            typedef int git_my_yoyo;

            typedef const char* git_my_string;

            // This is a comment.
            // This is another comment
            // @param myrepo yoyo
            // @return This is a big list of things to return
            EXPORT_API bool function0(git_my_repo* myrepo, int a, float b, const char* text, const char text2[], bool arg4[], git_my_yoyo arg5, git_my_string arg6);
            ", options);

            Assert.False(csCompilation.HasErrors);

            var fs         = new MemoryFileSystem();
            var codeWriter = new CodeWriter(new CodeWriterOptions(fs));

            csCompilation.DumpTo(codeWriter);

            var text = fs.ReadAllText(options.DefaultOutputFilePath);

            Console.WriteLine(text);
        }
 public async Task <SyntaxNode> SingleFirstPassAsync(Document document)
 {
     return(await CSharpConverter.ConvertCompilationTreeAsync(document, _vbViewOfCsSymbols, _vbReferenceProject, OptionalOperations, _cancellationToken));
 }