Пример #1
0
        public bool SourceRemove(CodeSource aSource)
        {
            CodeSourceManager manager = iManager.Plugin.SourceManager;
            bool removed = manager.Remove(aSource);

            return(removed);
        }
Пример #2
0
        private void Skip(CodeSource aSource)
        {
            System.Diagnostics.Debug.Assert(aSource.TimeToRead == CodeSource.TTimeToRead.EReadWhenNeeded);
            bool primeCompleted = base.AddToCompleted(aSource);

            CheckForCompletion(primeCompleted);
        }
Пример #3
0
        private void Source_EventHandler(CodeSource.TEvent aEvent, CodeSource aSource, object aData)
        {
            bool primeCompleted = false;

            // Map source event onto a primer event
            if (aEvent == CodeSource.TEvent.EReadingProgress)
            {
                base.SaveLatestProgress(aSource, (int)aData);
            }

            // If all sources are complete, then are we also done?
            if (aEvent == CodeSource.TEvent.EReadingComplete)
            {
                // We don't need to listen to this source anymore
                aSource.EventHandler -= new CodeSource.EventHandlerFunction(Source_EventHandler);

                // Source is 100% complete now.
                base.SaveLatestProgress(aSource, 100);

                // It's complete, so record as such so that we can tell when all the sources
                // are now ready.
                primeCompleted = base.AddToCompleted(aSource);
            }

            CheckForCompletion(primeCompleted);
        }
Пример #4
0
        private ParsingError GenerateError(string data, string codeFileName, int line, int column, string rest, bool isWarning = false)
        {
            ParsingError error;
            TextSpan     textSpan;

            if (_grammarCodeMapping.TryGetValue(codeFileName, out List <TextSpanMapping> textSpanMappings))
            {
                string grammarFileName = GetGrammarFromCodeFileName(_currentRuntimeInfo, codeFileName);
                textSpan = TextHelpers.GetSourceTextSpanForLine(textSpanMappings, line, grammarFileName);
                error    = new ParsingError(textSpan, $"{grammarFileName}:{textSpan.GetLineColumn().BeginLine}:{rest}",
                                            WorkflowStage.ParserCompiled, isWarning);
            }
            else
            {
                Dictionary <string, CodeSource> grammarFilesData = _result.ParserGeneratedState.GrammarCheckedState.GrammarFilesData;
                CodeSource codeSource =
                    grammarFilesData.FirstOrDefault(file => file.Key.EndsWith(codeFileName, StringComparison.OrdinalIgnoreCase)).Value;

                textSpan = codeSource != null
                    ? new LineColumnTextSpan(line, column, codeSource).GetTextSpan()
                    : TextSpan.Empty;
                error = new ParsingError(textSpan, data, WorkflowStage.ParserCompiled, isWarning);
            }

            return(error);
        }
Пример #5
0
        public bool SourceAdd(CodeSource aSource)
        {
            CodeSourceManager manager = iManager.Plugin.SourceManager;
            bool added = manager.Add(aSource);

            return(added);
        }
Пример #6
0
        public void ParserGeneratedStageErrors()
        {
            var grammarText =
                $@"grammar {TestGrammarName};
                start:  rule1+;
                rule:   DIGIT;
                CHAR:   [a-z]+;
                DIGIT:  [0-9]+;
                WS:     [ \r\n\t]+ -> skip;";
            var workflow = new Workflow(GrammarFactory.CreateDefaultCombinedAndFill(grammarText, TestGrammarName, "."));

            var state = workflow.Process();

            Assert.AreEqual(WorkflowStage.ParserGenerated, state.Stage, state.Exception?.ToString());

            var    grammarSource       = new CodeSource(TestGrammarName + ".g4", File.ReadAllText(TestGrammarName + ".g4"));
            char   separator           = Path.DirectorySeparatorChar;
            string testGrammarFullName = $"{Environment.CurrentDirectory}{separator}.{separator}{TestGrammarName}.g4";
            ParserGeneratedState parserGeneratedState = state as ParserGeneratedState;
            string str = new ParsingError(2, 24, $"error(56): {testGrammarFullName}:2:24: reference to undefined rule: rule1", grammarSource, WorkflowStage.ParserGenerated).ToString();

            CollectionAssert.AreEquivalent(
                new [] {
                new ParsingError(2, 24, $"error(56): {testGrammarFullName}:2:24: reference to undefined rule: rule1", grammarSource, WorkflowStage.ParserGenerated),
            },
                parserGeneratedState.Errors);
        }
Пример #7
0
        private void GetGeneratedFileNames(GrammarCheckedState grammarCheckedState, string generatedGrammarName, string workingDirectory,
                                           List <string> generatedFiles, bool lexer)
        {
            string grammarNameExt;

            if (_grammar.Type == GrammarType.Combined)
            {
                grammarNameExt = _grammar.Files.FirstOrDefault(file => Path.GetExtension(file)
                                                               .Equals(Grammar.AntlrDotExt, StringComparison.OrdinalIgnoreCase));
            }
            else
            {
                string postfix = lexer ? Grammar.LexerPostfix : Grammar.ParserPostfix;
                grammarNameExt = _grammar.Files.FirstOrDefault(file => file.Contains(postfix) &&
                                                               Path.GetExtension(file).Equals(Grammar.AntlrDotExt, StringComparison.OrdinalIgnoreCase));
            }

            string shortGeneratedFile = generatedGrammarName +
                                        (lexer ? _currentRuntimeInfo.LexerPostfix : _currentRuntimeInfo.ParserPostfix) +
                                        "." + _currentRuntimeInfo.Extensions[0];

            string  generatedFileDir = workingDirectory;
            Runtime runtime          = _currentRuntimeInfo.Runtime;

            if ((runtime == Runtime.Java || runtime == Runtime.Go) && !string.IsNullOrWhiteSpace(_result.ParserGeneratedState.PackageName))
            {
                generatedFileDir = Path.Combine(generatedFileDir, _result.ParserGeneratedState.PackageName);
            }
            string generatedFile = Path.Combine(generatedFileDir, shortGeneratedFile);

            generatedFiles.Add(generatedFile);
            CodeSource codeSource = new CodeSource(generatedFile, File.ReadAllText(generatedFile));

            _grammarCodeMapping[shortGeneratedFile] = TextHelpers.Map(grammarCheckedState.GrammarActionsTextSpan[grammarNameExt], codeSource, lexer);
        }
        public static string GetCodeSourceLocation()
        {
            var f = default(FileInfo);

            try
            {
                // Error	40	The call is ambiguous between the following methods or properties: 'ScriptCoreLibJava.Extensions.BCLImplementationExtensions.ToClass(System.Type)' and 'ScriptCoreLibJava.Extensions.BCLImplementationExtensions.ToClass(System.Type)'	X:\jsc.svn\core\ScriptCoreLib.Ultra\ScriptCoreLib.Ultra\Java\Interop\CodeSourceLocationProvider.cs	22	27	ScriptCoreLib.Ultra

                var cls = BCLImplementationExtensions.ToClass(typeof(CodeSourceLocationProvider));

                ProtectionDomain pDomain = cls.getProtectionDomain();
                CodeSource       cSource = pDomain.getCodeSource();
                URL loc = cSource.getLocation();


                var ff     = loc.getFile();
                var prefix = "file:/";

                if (prefix == ff.Substring(0, prefix.Length))
                {
                    ff = ff.Substring(prefix.Length);
                }

                f = new FileInfo(ff);
            }
            catch
            {
                throw new NotSupportedException();
            }

            return(f.FullName);
        }
 private static void EnsureCodeSource(CodeSource cSource)
 {
     if (cSource == null)
     {
         throw new InvalidOperationException();
     }
 }
Пример #10
0
        /*
         * Defines a Class using the class bytes obtained from the specified
         * Resource. The resulting Class must be resolved before it can be
         * used.
         */
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: private Class defineClass(String name, sun.misc.Resource res) throws java.io.IOException
        private Class DefineClass(String name, Resource res)
        {
            long t0  = System.nanoTime();
            int  i   = name.LastIndexOf('.');
            URL  url = res.CodeSourceURL;

            if (i != -1)
            {
                String pkgname = name.Substring(0, i);
                // Check if package already loaded.
                Manifest man = res.Manifest;
                DefinePackageInternal(pkgname, man, url);
            }
            // Now read the class bytes and define the class
            java.nio.ByteBuffer bb = res.ByteBuffer;
            if (bb != null)
            {
                // Use (direct) ByteBuffer:
                CodeSigner[] signers = res.CodeSigners;
                CodeSource   cs      = new CodeSource(url, signers);
                sun.misc.PerfCounter.ReadClassBytesTime.addElapsedTimeFrom(t0);
                return(DefineClass(name, bb, cs));
            }
            else
            {
                sbyte[] b = res.Bytes;
                // must read certificates AFTER reading bytes.
                CodeSigner[] signers = res.CodeSigners;
                CodeSource   cs      = new CodeSource(url, signers);
                sun.misc.PerfCounter.ReadClassBytesTime.addElapsedTimeFrom(t0);
                return(DefineClass(name, b, 0, b.Length, cs));
            }
        }
Пример #11
0
        public void SeparatedLexerAndParserErrors()
        {
            var lexerText  = $@"lexer grammar {TestGrammarName};
                CHAR:   a-z]+;
                DIGIT: [0-9]+;
                WS:    [ \r\n\t]+ -> skip;";
            var parserText = $@"parser grammar {TestGrammarName};
                start: DIGIT+;
                #";
            var workflow   = new Workflow(GrammarFactory.CreateDefaultSeparatedAndFill(lexerText, parserText, TestGrammarName, "."));

            var state = workflow.Process();

            Assert.AreEqual(WorkflowStage.GrammarChecked, state.Stage, state.Exception?.ToString());

            var testLexerSource  = new CodeSource(TestGrammarName + "Lexer.g4", File.ReadAllText(TestGrammarName + "Lexer.g4"));
            var testParserSource = new CodeSource(TestGrammarName + "Parser.g4", File.ReadAllText(TestGrammarName + "Parser.g4"));
            GrammarCheckedState grammarCheckedState = state as GrammarCheckedState;

            CollectionAssert.AreEquivalent(
                new [] {
                new ParsingError(2, 25, $"error: {TestGrammarName}Lexer.g4:2:25: token recognition error at: '-z'", testLexerSource, WorkflowStage.GrammarChecked),
                new ParsingError(2, 27, $"error: {TestGrammarName}Lexer.g4:2:27: token recognition error at: ']'", testLexerSource, WorkflowStage.GrammarChecked),
                new ParsingError(2, 28, $"error: {TestGrammarName}Lexer.g4:2:28: mismatched input '+' expecting {{ASSIGN, PLUS_ASSIGN}}", testLexerSource, WorkflowStage.GrammarChecked),
                new ParsingError(3, 16, $"error: {TestGrammarName}Parser.g4:3:16: extraneous input '#' expecting {{<EOF>, 'mode'}}", testParserSource, WorkflowStage.GrammarChecked)
            },
                grammarCheckedState.Errors);
        }
Пример #12
0
        private void AddCSharpError(string data)
        {
            if (data.Contains(": error CS"))
            {
                var          errorString = Helpers.FixEncoding(data);
                ParsingError error;
                CodeSource   grammarSource = CodeSource.Empty;
                try
                {
                    // Format:
                    // Lexer.cs(106,11): error CS0103: The  name 'a' does not exist in the current context
                    var    strs             = errorString.Split(':');
                    int    leftParenInd     = strs[0].IndexOf('(');
                    string codeFileName     = strs[0].Remove(leftParenInd);
                    string grammarFileName  = GetGrammarFromCodeFileName(_currentRuntimeInfo, codeFileName);
                    string lineColumnString = strs[0].Substring(leftParenInd);
                    lineColumnString = lineColumnString.Substring(1, lineColumnString.Length - 2); // Remove parenthesis.
                    var    strs2  = lineColumnString.Split(',');
                    int    line   = int.Parse(strs2[0]);
                    int    column = int.Parse(strs2[1]);
                    string rest   = string.Join(":", strs.Skip(1));

                    error = GenerateError(data, codeFileName, line, column, rest);
                }
                catch
                {
                    error = new ParsingError(errorString, grammarSource, WorkflowStage.ParserCompiled);
                }
                AddError(error);
            }
        }
Пример #13
0
        public void TestConstructor()
        {
            var source = new CodeSource();

            Assert.AreNotEqual(string.Empty, source.CodePK);
            Assert.DoesNotThrow(() => new Guid(source.CodePK));
        }
Пример #14
0
        public static void Main(string[] args)
        {
            if (args.Length < 2)
            {
                Console.WriteLine("wtf dude give some files: <output> <file.lah...>");
            }
            var outname = args[0];
            var sources = new string[] {
                "stdlib/mem.lah",
                "stdlib/collections.lah",
                "stdlib/math.lah"
            }.Concat(args.Skip(1));

            foreach (var file in args.Skip(1))
            {
                Console.WriteLine($"Compiling {file}");
            }
            var multiSource = new MultiCodeSource(sources.Select(x => CodeSource.FromFile(x)).ToArray());

            Console.WriteLine(multiSource.Content);
            var parser  = new LahdaParser(new LahdaLexer(new CompilationConfiguration(multiSource)));
            var output  = new StringBuilderOutput();
            var codeGen = new CodeGenerator(output, parser.Root());

            codeGen.Build();
            if (File.Exists(outname))
            {
                File.Delete(outname);
            }
            File.WriteAllText(outname, output.ToString());
        }
Пример #15
0
        void UpdateIndex(string fullPath, PendingRetrySource pendingRetrySource = null)
        {
            if (IsFile(fullPath))
            {
                var fileInfo = new FileInfo(fullPath);
                try
                {
                    Thread.Sleep(WaitMilliseconds); // Wait to let file finished write to disk

                    if (fileInfo.Exists)
                    {
                        var content  = FilesContentHelper.ReadAllText(fullPath);
                        var document = CodeIndexBuilder.GetDocumentFromSource(CodeSource.GetCodeSource(fileInfo, content));
                        CodeIndexBuilder.UpdateIndex(config.LuceneIndexForCode, GetNoneTokenizeFieldTerm(nameof(CodeSource.FilePath), fullPath), document);
                        WordsHintBuilder.UpdateWordsHint(config, WordSegmenter.GetWords(content), log);
                        pendingChanges++;
                    }
                }
                catch (IOException)
                {
                    AddFileChangesToRetrySouce(fullPath, WatcherChangeTypes.Changed, pendingRetrySource);
                }
                catch (Exception ex)
                {
                    log?.Error(ex.ToString());
                }
            }
        }
Пример #16
0
 /*
  * Create a unique mapping from codeSigner cache entries to CodeSource.
  * In theory, multiple URLs origins could map to a single locally cached
  * and shared JAR file although in practice there will be a single URL in use.
  */
 private CodeSource MapSignersToCodeSource(URL url, CodeSigner[] signers)
 {
     lock (this)
     {
         Map <CodeSigner[], CodeSource> map;
         if (url == LastURL)
         {
             map = LastURLMap;
         }
         else
         {
             map = UrlToCodeSourceMap.Get(url);
             if (map == null)
             {
                 map = new HashMap <>();
                 UrlToCodeSourceMap.Put(url, map);
             }
             LastURLMap = map;
             LastURL    = url;
         }
         CodeSource cs = map.Get(signers);
         if (cs == null)
         {
             cs = new VerifierCodeSource(Csdomain, url, signers);
             SignerToCodeSource.Put(signers, cs);
         }
         return(cs);
     }
 }
Пример #17
0
 protected OptionMatcher(CodeSource codeSource, GrammarType grammarType, Action <ParsingError> errorEvent)
 {
     Regex       = new Regex($@"({Name})\s*=\s*(\w+);", RegexOptions.IgnoreCase | RegexOptions.Compiled);
     CodeSource  = codeSource ?? throw new ArgumentNullException(nameof(codeSource));
     GrammarType = grammarType;
     ErrorAction = errorEvent ?? throw new ArgumentNullException(nameof(errorEvent));
 }
Пример #18
0
        public void Parse(CodeSource source, string fileName, IEnumerable <string> parentFiles, bool visible)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
            _source      = source;
            _code        = new CodeParser(_source.Text);
            _fileName    = fileName;
            _parentFiles = parentFiles.ToArray();

            FunctionFileScanning.FFUtil.FileNameIsClass(_fileName, out _className);

            var scope = new Scope(this, 0, ScopeHint.None, visible, _model.DefinitionProvider);

            scope.ClassName = _className;
            Scope           = scope;

            while (_code.SkipWhiteSpace())
            {
                var stmt = StatementToken.TryParse(scope);
                if (stmt != null)
                {
                    AddToken(stmt);
                }
            }

            Span = new Span(0, _code.Length);
        }
Пример #19
0
        public void TestGetDocumentFromSource()
        {
            var codeSource = new CodeSource
            {
                FileName      = "Dummy File 2",
                FileExtension = "cs",
                FilePath      = @"C:\Dummy File 2.cs",
                Content       = "Test Content" + Environment.NewLine + "A New Line For Test"
            };

            var document = IndexBuilderHelper.GetDocumentFromSource(codeSource);

            Assert.AreEqual(9, document.Fields.Count);
            Assert.NotNull(document.Get(nameof(CodeSource.FilePath) + Constants.NoneTokenizeFieldSuffix));
            Assert.NotNull(document.Get(nameof(CodeSource.Content) + Constants.CaseSensitive));

            var convertBack = document.GetObject <CodeSource>();

            Assert.AreEqual(codeSource.FilePath, convertBack.FilePath);
            Assert.AreEqual(codeSource.Content, convertBack.Content);
            Assert.AreEqual(codeSource.IndexDate, convertBack.IndexDate);
            Assert.AreEqual(codeSource.LastWriteTimeUtc, convertBack.LastWriteTimeUtc);
            Assert.AreEqual(codeSource.CodePK, convertBack.CodePK);
            Assert.AreEqual(codeSource.FileName, convertBack.FileName);
            Assert.AreEqual(codeSource.FileExtension, convertBack.FileExtension);
            Assert.AreEqual(codeSource.Info, convertBack.Info);
        }
Пример #20
0
        public List <FileInfo> BuildIndexByBatch(IEnumerable <FileInfo> fileInfos, bool needCommit, bool triggerMerge, bool applyAllDeletes, CancellationToken cancellationToken, bool brandNewBuild, int batchSize = 10000)
        {
            cancellationToken.ThrowIfCancellationRequested();
            fileInfos.RequireNotNull(nameof(fileInfos));
            batchSize.RequireRange(nameof(batchSize), int.MaxValue, 50);

            var codeDocuments    = new List <Document>();
            var wholeWords       = new HashSet <string>();
            var newHintWords     = new HashSet <string>();
            var failedIndexFiles = new List <FileInfo>();

            try
            {
                foreach (var fileInfo in fileInfos)
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    try
                    {
                        if (fileInfo.Exists)
                        {
                            var source = CodeSource.GetCodeSource(fileInfo, FilesContentHelper.ReadAllText(fileInfo.FullName));

                            AddHintWords(newHintWords, wholeWords, source.Content);

                            var doc = IndexBuilderHelper.GetDocumentFromSource(source);
                            codeDocuments.Add(doc);

                            Log.LogInformation($"{Name}: Add index for {source.FilePath}");
                        }
                    }
                    catch (Exception ex)
                    {
                        failedIndexFiles.Add(fileInfo);
                        Log.LogError($"{Name}: Add index for {fileInfo.FullName} failed, exception: " + ex);
                    }

                    if (codeDocuments.Count >= batchSize)
                    {
                        BuildIndex(needCommit, triggerMerge, applyAllDeletes, codeDocuments, newHintWords, cancellationToken, brandNewBuild);
                        codeDocuments.Clear();
                        newHintWords.Clear();
                    }
                }

                if (codeDocuments.Count > 0)
                {
                    BuildIndex(needCommit, triggerMerge, applyAllDeletes, codeDocuments, newHintWords, cancellationToken, brandNewBuild);
                }

                return(failedIndexFiles);
            }
            finally
            {
                wholeWords.Clear();
                newHintWords.Clear();
                codeDocuments.Clear();
            }
        }
Пример #21
0
        public void CanCreateWithContents()
        {
            var contents = Guid.NewGuid().ToString();

            var actual = new CodeSource(contents);

            actual.Contents.Should().Be(contents);
            actual.FilePath.Should().BeEmpty();
        }
Пример #22
0
        public ShowMeTheCodeVm GetShowMeTheCode()
        {
            codeSource = new CodeSource();

            return(new ShowMeTheCodeVm()
            {
                URLGitHub = codeSource.URLGitHub
            });
        }
Пример #23
0
        protected void ReportWarning(string message, IToken token, Group group, CodeSource codeSource)
        {
            var warningTextSpan = new TextSpan(token.StartIndex + group.Index, group.Length, codeSource);
            var lineColumn      = codeSource.ToLineColumn(warningTextSpan);
            var error           = new ParsingError(warningTextSpan,
                                                   Helpers.FormatErrorMessage(codeSource, lineColumn.BeginLine, lineColumn.BeginColumn, message, true),
                                                   WorkflowStage.GrammarChecked, true);

            ErrorAction(error);
        }
Пример #24
0
        public static void BuildIndexByBatch(CodeIndexConfiguration config, bool triggerMerge, bool applyAllDeletes, bool needFlush, IEnumerable <FileInfo> fileInfos, bool deleteExistIndex, ILog log, out List <FileInfo> failedIndexFiles, int batchSize = 1000, bool needHint = true)
        {
            config.RequireNotNull(nameof(config));
            fileInfos.RequireNotNull(nameof(fileInfos));
            batchSize.RequireRange(nameof(batchSize), int.MaxValue, 50);

            var needDeleteExistIndex = deleteExistIndex && IndexExists(config.LuceneIndexForCode);
            var documents            = new List <Document>();

            failedIndexFiles = new List <FileInfo>();

            foreach (var fileInfo in fileInfos)
            {
                try
                {
                    if (fileInfo.Exists)
                    {
                        var source = CodeSource.GetCodeSource(fileInfo, FilesContentHelper.ReadAllText(fileInfo.FullName));

                        if (needDeleteExistIndex)
                        {
                            DeleteIndex(config.LuceneIndexForCode, new Term(nameof(CodeSource.FilePath) + Constants.NoneTokenizeFieldSuffix, source.FilePath));
                        }

                        if (needHint)
                        {
                            WordsHintBuilder.AddWords(WordSegmenter.GetWords(source.Content));
                        }

                        var doc = GetDocumentFromSource(source);
                        documents.Add(doc);

                        log?.Info($"Add index For {source.FilePath}");
                    }
                }
                catch (Exception ex)
                {
                    failedIndexFiles.Add(fileInfo);
                    log?.Error($"Add index for {fileInfo.FullName} failed, exception: " + ex.ToString());
                }

                if (documents.Count >= batchSize)
                {
                    BuildIndex(config, triggerMerge, applyAllDeletes, documents, needFlush, log);
                    documents.Clear();
                }
            }

            if (documents.Count > 0)
            {
                BuildIndex(config, triggerMerge, applyAllDeletes, documents, needFlush, log);
            }
        }
Пример #25
0
        private void Compile_Click(object sender, EventArgs e)
        {
            Save();

            Jun.Tokenizer tokenizer = new Jun.Tokenizer(Context);
            Jun.Parser    parser    = new Jun.Parser(Context);

            try
            {
                tokenizer.Tokenize(Source.Source.Split('\n'));
            }
            catch (JunException ex)
            {
                MessageBox.Show(ex.Message, "Tokenizing Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                CodeSource.Focus();
                CodeSource.Selection = new Range(CodeSource, tokenizer.Column - 1, tokenizer.Line - 1, tokenizer.Column, tokenizer.Line - 1);
                return;
            }

            try
            {
                parser.Parse(tokenizer.Tokens);
            }
            catch (JunException ex)
            {
                // delete temporary
                foreach (CompiledScript scr in parser.TemporaryScripts)
                {
                    Context.Djn.Remove(scr.Resource.ID);
                }

                MessageBox.Show(ex.Message, "Parsing Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                CodeSource.Focus();
                CodeSource.Selection.Start = new Place(0, parser.LineNumber);
                CodeSource.SelectNext(@"\w+");
                return;
            }

            // copy all compiled scripts into the container
            foreach (Jun.Script js in parser.Scripts)
            {
                short          id  = parser.Constants[js.Name];
                CompiledScript scr = Context.Djn[id] as CompiledScript;

                scr.Resource.Flags      = js.Public ? ResourceFlags.None : ResourceFlags.Private;
                scr.Resource.OnlyDesign = false;
                scr.Bytecode            = js.Code.ToArray();
            }

            Context.UnsavedChanges = true;
            MessageBox.Show("Compiled!");
        }
Пример #26
0
 public static Document GetDocumentFromSource(CodeSource source)
 {
     return(new Document
     {
         new TextField(nameof(source.FileName), source.FileName.ToStringSafe(), Field.Store.YES),
         // StringField indexes but doesn't tokenize
         new StringField(nameof(source.FileExtension), source.FileExtension.ToStringSafe(), Field.Store.YES),
         new StringField(nameof(source.FilePath) + Constants.NoneTokenizeFieldSuffix, source.FilePath.ToStringSafe(), Field.Store.YES),
         new TextField(nameof(source.FilePath), source.FilePath.ToStringSafe(), Field.Store.YES),
         new TextField(nameof(source.Content), source.Content.ToStringSafe(), Field.Store.YES),
         new Int64Field(nameof(source.IndexDate), source.IndexDate.Ticks, Field.Store.YES),
         new Int64Field(nameof(source.LastWriteTimeUtc), source.LastWriteTimeUtc.Ticks, Field.Store.YES),
         new StringField(nameof(source.CodePK), source.CodePK.ToString(), Field.Store.YES)
     });
 }
        public void CodeGenerator_should_generate_godlike_code(string content, int i)
        {
            var codeSource = CodeSource.FromMemory(content);
            var parser     = new LahdaParser(new LahdaLexer(new CompilationConfiguration(codeSource)));
            var output     = new StringBuilderOutput();
            var codeGen    = new CodeGenerator(output, parser.Root());

            codeGen.Build();
            var path = $"test_{i}.s";

            if (File.Exists(path))
            {
                File.Delete(path);
            }
            File.WriteAllText(path, output.ToString());
        }
Пример #28
0
        public void TestGetCodeSource()
        {
            var dateTime = DateTime.UtcNow;
            var fileInfo = new FileInfo("AAA.txt");
            var source   = CodeSource.GetCodeSource(fileInfo, "ABCD");

            Assert.AreEqual("AAA.txt", source.FileName);
            Assert.AreEqual("ABCD", source.Content);
            Assert.AreEqual("txt", source.FileExtension);
            Assert.AreEqual(fileInfo.FullName, source.FilePath);
            Assert.AreEqual(fileInfo.LastWriteTimeUtc, source.LastWriteTimeUtc);
            Assert.LessOrEqual(dateTime, source.IndexDate);
            Assert.AreNotEqual(string.Empty, source.CodePK);
            Assert.DoesNotThrow(() => new Guid(source.CodePK));
            Assert.AreEqual($"FileName: {source.FileName}{Environment.NewLine}FilePath: {source.FilePath}{Environment.NewLine}Index Date: {source.IndexDate.ToLocalTime()}{Environment.NewLine}Last Modify Date:{source.LastWriteTimeUtc.ToLocalTime()}", source.Info);
        }
Пример #29
0
 /// <summary>
 /// Try to load jar from relative ../lib/ directory for cases when we do not have jars in a class path. </summary>
 /// <param name="jar"> - path to a jar file to load. </param>
 /// <returns> loaded jar file </returns>
 /// <exception cref="EmbeddedJarNotFoundException"> if jar not exist or file name can't be represented as URI. </exception>
 private File LoadJarFromRelativePath(string jar)
 {
     try
     {
         CodeSource codeSource = this.GetType().ProtectionDomain.CodeSource;
         URI        uri        = codeSource.Location.toURI();
         File       jarFile    = new File(Path.GetDirectoryName(uri), jar);
         if (!jarFile.exists())
         {
             throw new EmbeddedJarNotFoundException("Jar file '" + jar + "' not found.");
         }
         return(jarFile);
     }
     catch (URISyntaxException)
     {
         throw new EmbeddedJarNotFoundException("Jar file '" + jar + "' not found.");
     }
 }
Пример #30
0
        public Expression(string sourceCode, CodeSource format, Module module)
        {
            error = module.Error;

            if (format == CodeSource.FILE)
            {
                lex = new FileLex(sourceCode, error);
            }
            else
            {
                lex = new StringLex(sourceCode, error);
            }

            this.module = module;

            gen  = new CodeGeneration(module);
            vtab = new SymbolTable(Constant.MAX_SYMBOL_TABLE_SIZE, error);
        }
Пример #31
0
 /**
  * Answers a PermissionCollection object containing the set of permissions
  * granted to the specified CodeSource.
  *
  * The default implementation of this method returns
  * Policy.UNSUPPORTED_EMPTY_COLLECTION object. This method can be overridden
  * if the policy implementation can return a set of permissions granted to a
  * CodeSource.
  *
  * @param codesource -
  *            the CodeSource to which the returned PermissionCollection has
  *            been granted.
  * @return a set of permissions granted to the specified CodeSource. If this
  *         operation is supported, the returned set of permissions must be a
  *         new mutable instance and it must support heterogeneous Permission
  *         types. If this operation is not supported,
  *         Policy.UNSUPPORTED_EMPTY_COLLECTION is returned.
  */
 protected internal PermissionCollection engineGetPermissions(CodeSource codesource)
 {
     return Policy.UNSUPPORTED_EMPTY_COLLECTION;
 }