Exemple #1
0
        public void TestProcessCommandLineArguments2()
        {
            // Generate two options files, where the first refers to the second
            string       atFolder = Environment.ExpandEnvironmentVariables("%TEMP%");
            string       file1    = "test ProcessCmdLine 1.txt";
            string       file2    = "test ProcessCmdLine 2.txt";
            StreamWriter w        = new StreamWriter(Path.Combine(atFolder, file1));

            w.WriteLine("\"@" + file2 + "\" fox--jumps\n--over");
            w.Close();
            w = new StreamWriter(Path.Combine(atFolder, file2));
            w.WriteLine("these arguments are ignored (arg limit exceeded)");
            w.Close();

            // Expand command line and ensure that the arg limit is enforced
            List <string> args    = G.SplitCommandLineArguments("\"@" + file1 + "\" \"lazy dog\"");
            var           options = new DList <KeyValuePair <string, string> >();
            var           msgs    = new MessageHolder();

            using (MessageSink.SetDefault(msgs))
                UG.ProcessCommandLineArguments(args, options, atFolder, null, null, 5);

            ExpectList(args.AsListSource(), "@" + file1, "@" + file2, "fox--jumps", "lazy dog");
            ExpectList(options, P("over", null));
            ExpectList(msgs.List.AsListSource().Select(msg => msg.ToString()),
                       "@test ProcessCmdLine 2.txt: Warning: Limit of 5 commands exceeded");
        }
Exemple #2
0
        public virtual int Generate(string inputFilePath, string inputFileContents, string defaultNamespace, IntPtr[] outputFileContents, out uint outputSize, IVsGeneratorProgress progressCallback)
        {
            string inputFolder = Path.GetDirectoryName(inputFilePath);
            string oldCurDir   = Environment.CurrentDirectory;

            try {
                Environment.CurrentDirectory = inputFolder;                 // --macros should be relative to file being processed

                var sourceFile = new StringCharSourceFile(inputFileContents, inputFilePath);
                var sink       = ToMessageSink(progressCallback);

                var c = new Compiler(sink, sourceFile);

                var options = new BMultiMap <string, string>();
                var argList = G.SplitCommandLineArguments(defaultNamespace);
                UG.ProcessCommandLineArguments(argList, options, "", LEL.Compiler.ShortOptions, LEL.Compiler.TwoArgOptions);

                string _;
                var    KnownOptions = LEL.Compiler.KnownOptions;
                if (options.TryGetValue("help", out _) || options.TryGetValue("?", out _))
                {
                    LEL.Compiler.ShowHelp(KnownOptions);
                }

                Symbol minSeverity = MessageSink.Note;
                var    filter      = new SeverityMessageFilter(MessageSink.Console, minSeverity);

                if (LEL.Compiler.ProcessArguments(c, options))
                {
                    LEL.Compiler.WarnAboutUnknownOptions(options, MessageSink.Console, KnownOptions);
                    if (c != null)
                    {
                        c.MacroProcessor.PreOpenedNamespaces.Add(GSymbol.Get("LEL.Prelude"));
                        c.MacroProcessor.PreOpenedNamespaces.Add(GSymbol.Get("Loyc.LLParserGenerator"));
                        c.AddMacros(typeof(Loyc.LLParserGenerator.Macros).Assembly);
                        c.Run();
                    }

                    var outputBytes = Encoding.UTF8.GetBytes(c.Output.ToString());
                    c.Output              = null;        // no longer needed
                    outputSize            = (uint)outputBytes.Length;
                    outputFileContents[0] = Marshal.AllocCoTaskMem(outputBytes.Length);
                    Marshal.Copy(outputBytes, 0, outputFileContents[0], outputBytes.Length);
                }
                else
                {
                    outputFileContents[0] = IntPtr.Zero;
                    outputSize            = 0;
                }
                return(VSConstants.S_OK);
            } finally {
                Environment.CurrentDirectory = oldCurDir;
            }
        }
Exemple #3
0
        private void RunLeMP(IList <string> args, string inputCode, string inputPath)
        {
            var options = new BMultiMap <string, string>();

            UG.ProcessCommandLineArguments(args, options, "", LeMP.Compiler.ShortOptions, LeMP.Compiler.TwoArgOptions);

            string _;
            var    KnownOptions = LeMP.Compiler.KnownOptions;

            if (options.TryGetValue("help", out _) || options.TryGetValue("?", out _))
            {
                var ms = new MemoryStream();
                LeMP.Compiler.ShowHelp(LeMP.Compiler.KnownOptions, new StreamWriter(ms));
                string output = Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Length);
                _outFileName = null;
                ShowOutput(output);
            }
            else
            {
                var sink       = MessageSink.FromDelegate(WriteMessage);
                var sourceFile = new InputOutput((UString)inputCode, Path.GetFileName(inputPath));

                var c = new Compiler(sink, sourceFile);
                c.Files = new List <InputOutput> {
                    sourceFile
                };
                c.Parallel = false;                 // only one file, parallel doesn't help

                if (LeMP.Compiler.ProcessArguments(c, options))
                {
                    LeMP.Compiler.WarnAboutUnknownOptions(options, sink, KnownOptions);

                    c.AddMacros(typeof(global::LeMP.StandardMacros).Assembly);
                    c.MacroProcessor.PreOpenedNamespaces.Add(GSymbol.Get("LeMP"));
                    c.MacroProcessor.PreOpenedNamespaces.Add(GSymbol.Get("LeMP.Prelude"));
                    if (inputPath.EndsWith(".les", StringComparison.OrdinalIgnoreCase))
                    {
                        c.MacroProcessor.PreOpenedNamespaces.Add(GSymbol.Get("LeMP.Prelude.Les"));
                    }

                    LempStarted = true;
                    new Thread(() => {
                        try {
                            c.Run();
                            // Must get OutFileName after calling Run()
                            _outFileName = sourceFile.OutFileName;
                            ShowOutput(c.Output.ToString());
                        } finally { LempStarted = false; }
                    }).Start();
                }
            }
        }
Exemple #4
0
        [STAThread]         // Required by ICSharpCode.TextEditor
        public static void Main(string[] args)
        {
            BMultiMap <string, string> options = new BMultiMap <string, string>();

            var argList = args.ToList();

            UG.ProcessCommandLineArguments(argList, options, "", ShortOptions, TwoArgOptions);
            if (!options.ContainsKey("nologo"))
            {
                Console.WriteLine("LeMP macro compiler (beta)");
            }

            string _;

            if (options.TryGetValue("help", out _) || options.TryGetValue("?", out _))
            {
                ShowHelp(KnownOptions.OrderBy(p => p.Key));
                return;
            }

            if (options.ContainsKey("editor"))
            {
                Console.WriteLine("Starting editor...");
                System.Windows.Forms.Application.EnableVisualStyles();
                System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(false);
                System.Windows.Forms.Application.Run(new TextEditor.LempDemoForm());
                return;
            }

            Severity minSeverity = Severity.Note;

                        #if DEBUG
            minSeverity = Severity.Debug;
                        #endif
            var filter = new SeverityMessageFilter(MessageSink.Console, minSeverity);

            Compiler c = ProcessArguments(options, filter, typeof(BuiltinMacros), argList);
            Compiler.WarnAboutUnknownOptions(options, MessageSink.Console, KnownOptions);
            if (c != null)
            {
                c.AddMacros(typeof(global::LeMP.StandardMacros).Assembly);
                c.MacroProcessor.PreOpenedNamespaces.Add(GSymbol.Get("LeMP.Prelude"));
                c.MacroProcessor.PreOpenedNamespaces.Add(GSymbol.Get("LeMP"));
                using (LNode.PushPrinter(EcsNodePrinter.PrintPlainCSharp))
                    c.Run();
            }
            else if (args.Length == 0)
            {
                ShowHelp(KnownOptions.OrderBy(p => p.Key));
            }
        }
Exemple #5
0
        /// <summary>Processes command-line arguments to build a BMultiMap and
        /// sends those options to the other overload of this method.</summary>
        /// <param name="args">Arg list from which to extract options. **NOTE**:
        /// discovered options are removed from the list. This parameter
        /// cannot be an array.</param>
        /// <param name="warnAboutUnknownOptions">Whether this method should
        /// call <see cref="WarnAboutUnknownOptions"/> for you.</param>
        /// <param name="autoOpenInputFiles">Whether to open input files
        /// for you by calling <see cref="OpenSourceFiles(IMessageSink, IEnumerable{string})"/>.
        /// </param>
        /// <param name="inputFiles">A list of input files to open if
        /// autoOpenInputFiles is true. If this is null, The input files are
        /// assumed to be those command-line arguments left over after the options
        /// are removed.</param>
        /// <returns>The map of options (key-value pairs and, for options that
        /// don't have a value, key-null pairs).</returns>
        /// <remarks>
        /// Note: If you get your command-line arguments as a single
        /// string, use <see cref="G.SplitCommandLineArguments(string)"/> first
        /// to split it into an array.
        /// <para/>
        /// This method doesn't check for --help. To implement --help, call
        /// <see cref="MaybeShowHelp"/> on the return value.
        /// </remarks>
        public BMultiMap <string, string> ProcessArguments(IList <string> args, bool warnAboutUnknownOptions, bool autoOpenInputFiles, IList <string> inputFiles = null)
        {
            BMultiMap <string, string> options = new BMultiMap <string, string>();

            UG.ProcessCommandLineArguments(args, options, "", ShortOptions, TwoArgOptions);
            if (inputFiles == null && autoOpenInputFiles)
            {
                inputFiles = args;
            }
            if (!ProcessArguments(options, warnAboutUnknownOptions, inputFiles))
            {
                return(null);
            }
            return(options);
        }
Exemple #6
0
        public void TestProcessCommandLineArguments1()
        {
            string commandLine = "-abZ -ab123 and -a=Foo --Apple:No -b plantain --a %TEMP% @notExpanded --banana -Z --empty=";
            var    args        = G.SplitCommandLineArguments(commandLine);

            var shortOpts = new Dictionary <char, string> {
                { 'a', null }, { 'b', "banana" }
            };
            var twoArgOptions = new InvertibleSet <string>(new[] { "banana" });
            var options       = new DList <KeyValuePair <string, string> >();

            UG.ProcessCommandLineArguments(args, options, null, shortOpts, twoArgOptions, expandEnvVars: false);

            ExpectList(args.AsListSource(), "-abZ", "and", "%TEMP%", "@notExpanded", "-Z");
            ExpectList(options, P("a", null), P("banana", "123"), P("a", "Foo"), P("apple", "No"), P("banana", "plantain"), P("a", null), P("banana", null), P("empty", ""));
        }
Exemple #7
0
        public static void Main(params string[] args)
        {
            IDictionary <string, Pair <string, string> > KnownOptions = LeMP.Compiler.KnownOptions;

            if (args.Length != 0)
            {
                BMultiMap <string, string> options = new BMultiMap <string, string>();

                var argList = args.ToList();
                UG.ProcessCommandLineArguments(argList, options, "", LeMP.Compiler.ShortOptions, LeMP.Compiler.TwoArgOptions);
                if (!options.ContainsKey("nologo"))
                {
                    Console.WriteLine("LLLPG/LeMP macro compiler");
                }

                string _;
                if (options.TryGetValue("help", out _) || options.TryGetValue("?", out _) || args.Length == 0)
                {
                    LeMP.Compiler.ShowHelp(KnownOptions.OrderBy(p => p.Key));
                    return;
                }

                Severity minSeverity = Severity.Note;
                                #if DEBUG
                minSeverity = Severity.Debug;
                                #endif
                var filter = new SeverityMessageFilter(MessageSink.Console, minSeverity);

                LeMP.Compiler c = LeMP.Compiler.ProcessArguments(options, filter, typeof(LeMP.Prelude.Les.Macros), argList);
                LeMP.Compiler.WarnAboutUnknownOptions(options, MessageSink.Console, KnownOptions);
                if (c != null)
                {
                    c.MacroProcessor.PreOpenedNamespaces.Add(GSymbol.Get("LeMP.Prelude"));
                    c.MacroProcessor.PreOpenedNamespaces.Add(Loyc.LLPG.Macros.MacroNamespace);
                    c.AddMacros(Assembly.GetExecutingAssembly());
                    c.AddMacros(typeof(LeMP.Prelude.Macros).Assembly);
                    c.Run();
                }
            }
            else
            {
                LeMP.Compiler.ShowHelp(KnownOptions.OrderBy(p => p.Key));
                Tests();
                Ecs.Program.Main(args);                 // do EC# tests
            }
        }
Exemple #8
0
        public static void Main(string[] args)
        {
            BMultiMap <string, string> options = new BMultiMap <string, string>();

            var argList = args.ToList();

            UG.ProcessCommandLineArguments(argList, options, "", ShortOptions, TwoArgOptions);
            if (!options.ContainsKey("nologo"))
            {
                Console.WriteLine("LeMP macro compiler (pre-alpha)");
            }

            string _;

            if (options.TryGetValue("help", out _) || options.TryGetValue("?", out _))
            {
                ShowHelp(KnownOptions.OrderBy(p => p.Key));
                return;
            }

            Severity minSeverity = Severity.Note;

                        #if DEBUG
            minSeverity = Severity.Debug;
                        #endif
            var filter = new SeverityMessageFilter(MessageSink.Console, minSeverity);

            Compiler c = ProcessArguments(argList, options, filter, typeof(Macros));
            Compiler.WarnAboutUnknownOptions(options, MessageSink.Console, KnownOptions);
            if (c != null)
            {
                c.MacroProcessor.PreOpenedNamespaces.Add(GSymbol.Get("LeMP.Prelude"));
                using (LNode.PushPrinter(Ecs.EcsNodePrinter.PrintPlainCSharp))
                    c.Run();
            }
            else if (args.Length == 0)
            {
                Console.WriteLine("Running unit tests...");
                RunTests.Run(new Loyc.Syntax.Les.LesLexerTests());
                RunTests.Run(new Loyc.Syntax.Les.LesParserTests());
                RunLeMPTests();
                Ecs.Program.RunEcsTests();
            }
        }
Exemple #9
0
        protected override byte[] Generate(string inputFilePath, string inputFileContents, string defaultNamespace, IVsGeneratorProgress progressCallback)
        {
            string oldCurDir = Environment.CurrentDirectory;

            try {
                string inputFolder = Path.GetDirectoryName(inputFilePath);
                Environment.CurrentDirectory = inputFolder;                 // --macros should be relative to file being processed

                var options = new BMultiMap <string, string>();
                var argList = G.SplitCommandLineArguments(defaultNamespace);
                UG.ProcessCommandLineArguments(argList, options, "", LeMP.Compiler.ShortOptions, LeMP.Compiler.TwoArgOptions);

                string _;
                var    KnownOptions = LeMP.Compiler.KnownOptions;
                if (options.TryGetValue("help", out _) || options.TryGetValue("?", out _))
                {
                    LeMP.Compiler.ShowHelp(KnownOptions);
                }

                // Originally I wrote a conversion from IVsGeneratorProgress to
                // IMessageSink so that errors could be reported immediately and
                // directly to Visual Studio. This broke in a bizarre way when I
                // added processing on a separate thread (in order to be able to
                // abort the thread if it runs too long); I got the following
                // InvalidCastException: "Unable to cast COM object of type 'System.__ComObject'
                // to interface type 'Microsoft.VisualStudio.Shell.Interop.IVsGeneratorProgress'.
                // This operation failed because the QueryInterface call on the COM component for
                // the interface with IID '{BED89B98-6EC9-43CB-B0A8-41D6E2D6669D}' failed due to
                // the following error: No such interface supported (Exception from HRESULT:
                // 0x80004002 (E_NOINTERFACE))."
                //
                // A simple solution is to store the messages rather than reporting
                // them immediately. I'll report the errors at the very end.
                MessageHolder sink = new MessageHolder();

                var sourceFile = new InputOutput((UString)inputFileContents, inputFilePath);

                var c = new Compiler(sink, sourceFile)
                {
                    AbortTimeout = TimeSpan.FromSeconds(10),
                    Parallel     = false                 // only one file, parallel doesn't help
                };

                if (c.ProcessArguments(options))
                {
                    if (options.ContainsKey("no-out-header"))
                    {
                        options.Remove("no-out-header", 1);
                        c.NoOutHeader = true;
                    }
                    LeMP.Compiler.WarnAboutUnknownOptions(options, sink, KnownOptions);
                    if (c != null)
                    {
                        if (inputFilePath.EndsWith(".les", StringComparison.OrdinalIgnoreCase))
                        {
                            c.MacroProcessor.PreOpenedNamespaces.Add(GSymbol.Get("LeMP.Prelude.Les"));
                        }
                        Configure(c);
                        c.Run();

                        // Report errors
                        foreach (var msg in sink.List)
                        {
                            ReportErrorToVS(progressCallback, msg.Severity, msg.Context, msg.Format, msg.Args);
                        }

                        return(Encoding.UTF8.GetBytes(c.Output.ToString()));
                    }
                }
                return(null);
            } finally {
                Environment.CurrentDirectory = oldCurDir;
            }
        }
Exemple #10
0
        [STAThread]         // Required by ICSharpCode.TextEditor
        public static void Main(string[] args)
        {
            BMultiMap <string, string> options = new BMultiMap <string, string>();

            var argList = args.ToList();

            UG.ProcessCommandLineArguments(argList, options, "", ShortOptions, TwoArgOptions);
            if (!options.ContainsKey("nologo"))
            {
                Console.WriteLine("LeMP macro compiler (pre-alpha)");
            }

            string _;

            if (options.TryGetValue("help", out _) || options.TryGetValue("?", out _))
            {
                ShowHelp(KnownOptions.OrderBy(p => p.Key));
                return;
            }
            if (options.ContainsKey("editor"))
            {
                Console.WriteLine("Starting editor...");
                System.Windows.Forms.Application.EnableVisualStyles();
                System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(false);
                System.Windows.Forms.Application.Run(new TextEditor.LempDemoForm());
                return;
            }

            Severity minSeverity = Severity.Note;

                        #if DEBUG
            minSeverity = Severity.Debug;
                        #endif
            var filter = new SeverityMessageFilter(MessageSink.Console, minSeverity);

            Compiler c = ProcessArguments(options, filter, typeof(Macros), argList);
            Compiler.WarnAboutUnknownOptions(options, MessageSink.Console, KnownOptions);
            if (c != null)
            {
                c.AddMacros(typeof(global::LeMP.StandardMacros).Assembly);
                c.MacroProcessor.PreOpenedNamespaces.Add(GSymbol.Get("LeMP.Prelude"));
                c.MacroProcessor.PreOpenedNamespaces.Add(GSymbol.Get("LeMP"));
                using (LNode.PushPrinter(Ecs.EcsNodePrinter.PrintPlainCSharp))
                    c.Run();
            }
            else if (args.Length == 0)
            {
                ShowHelp(KnownOptions.OrderBy(p => p.Key));

                Console.WriteLine();
                Console.WriteLine("LeMP started without arguments. Starting editor (--editor)");

                var thread = new ThreadEx(() => {
                    System.Windows.Forms.Application.EnableVisualStyles();
                    System.Windows.Forms.Application.Run(new TextEditor.LempDemoForm());
                });
                thread.Thread.SetApartmentState(ApartmentState.STA);
                thread.Start();

                Console.WriteLine("Press Enter to run unit tests. Using the editor? Keep the terminal open.");
                Console.ReadLine();

                RunTests.Run(new Loyc.Syntax.Lexing.TokenTests());
                RunTests.Run(new Loyc.Syntax.Les.LesLexerTests());
                RunTests.Run(new Loyc.Syntax.Les.LesParserTests());
                RunTests.Run(new Loyc.Syntax.Les.LesPrinterTests());
                RunLeMPTests();
                Ecs.Program.RunEcsTests();
            }
        }