/// <summary>
        /// Inform about substrings.
        /// </summary>
        /// <param name="ctx">The context.</param>
        /// <param name="name">The name.</param>
        /// <param name="fakeChild">True if it's a fake child.</param>
        /// <param name="splitter">The <see cref="Splitter"/>.</param>
        private void InformSubstrings(ParserRuleContext ctx, string name, bool fakeChild, Splitter splitter)
        {
            var text   = AntlrUtils.GetSourceText(ctx);
            var path   = this.Inform(ctx, name, text, fakeChild);
            var ranges = this.analyzer.GetRequiredInformRanges(path);

            if (ranges.Count > 4)
            { // Benchmarks showed this to be the breakeven point. (see below)
                var splitList = splitter.CreateSplitList(text);
                foreach (var range in ranges)
                {
                    var value = splitter.GetSplitRange(text, splitList, range);
                    if (value != null)
                    {
                        this.Inform(ctx, ctx, name + range, value, true);
                    }
                }
            }
            else
            {
                foreach (var range in ranges)
                {
                    var value = splitter.GetSplitRange(text, range);
                    if (value != null)
                    {
                        this.Inform(ctx, ctx, name + range, value, true);
                    }
                }
            }
        }
        private BinaryTreeNode GetBinaryTree(string s)
        {
            var parser = AntlrUtils.GetParser(s);
            var cst    = parser.compileUnit();

            return(new BuildBinaryTreeVisitor().VisitCompileUnit(cst));
        }
Пример #3
0
        static void Main(string[] args)
        {
            while (true)
            {
                Console.Write("> ");
                var exprText = Console.ReadLine();

                if (string.IsNullOrWhiteSpace(exprText))
                {
                    break;
                }

                var parser = AntlrUtils.GetParser(exprText);

                //try
                //{
                var cst  = parser.compileUnit();
                var ast  = new BuildBinaryTreeVisitor().VisitCompileUnit(cst);
                var expr = new BuildExpressionVisitor().Visit((ExpressionNode)ast);
                //expr.Simplify();

                Console.WriteLine(expr.ToString());
                //}
                //catch (Exception ex)
                //{
                //    Console.WriteLine(ex);
                //}

                Console.WriteLine();
            }
        }
        private void ReadBeforeEventCalculation(RecordRefModel model, ManagedFolder entity, string componentFolderPath)
        {
            var isSearchFolderReq = model.Requisites
                                    .FirstOrDefault(r => r.Name == IsSearchFolderRequisiteName);

            if (isSearchFolderReq == null)
            {
                log.Warn($"Requisite \"{IsSearchFolderRequisiteName}\" not found for managed folder \"{entity.Name}\"");
                return;
            }
            if (string.Equals(isSearchFolderReq.Value, "Да", StringComparison.OrdinalIgnoreCase))
            {
                var beforeEventFilePath = Path.Combine(componentFolderPath, "Event.isbl");
                if (File.Exists(beforeEventFilePath))
                {
                    var beforeEventDecodedDfm = File.ReadAllText(beforeEventFilePath, Encoding.GetEncoding(1251));
                    if (!string.IsNullOrWhiteSpace(beforeEventDecodedDfm))
                    {
                        var beforeSearchEventDfm  = ManagedFoldersDFMConverter.DeConvert(beforeEventDecodedDfm);
                        var beforeSearchEventText = AntlrUtils.Parse <string, DfmGrammarParser, StringListPropValueListener>(
                            beforeSearchEventDfm, p => p.property());
                        entity.SearchDescription = new SearchDescription
                        {
                            BeforeSearchEventText = beforeSearchEventText
                        };
                    }
                }
            }
        }
Пример #5
0
        /// <summary>
        /// It walks to the next step in the tree.
        /// If the next step is null returns the provided value or source text of the node as result.
        /// </summary>
        /// <param name="tree">The node tree.</param>
        /// <param name="value">The provided value.</param>
        /// <returns>The <see cref="WalkList.WalkResult"/>.</returns>
        protected WalkList.WalkResult WalkNextStep(IParseTree tree, string value)
        {
            if (this.NextStep is null)
            {
                var res = value;
                if (value is null)
                {
                    res = AntlrUtils.GetSourceText((ParserRuleContext)tree);
                }

                if (this.Verbose)
                {
                    Logger.Info($"{this.Logprefix} Final (implicit) step: {res}");
                }

                return(new WalkList.WalkResult(tree, res));
            }

            if (this.Verbose)
            {
                Logger.Info($"{this.Logprefix} Tree: >>>{AntlrUtils.GetSourceText((ParserRuleContext)tree)}<<<");
                Logger.Info($"{this.Logprefix} Enter step({this.stepNr}): {this.NextStep}");
            }

            var result = this.NextStep.Walk(tree, value);

            if (this.Verbose)
            {
                Logger.Info($"{this.Logprefix} Result: >>>{(result is null ? "null" : result.ToString())}<<<");
                Logger.Info($"{this.Logprefix} Leave step({(result is null ? "-" : "+")}): {this.NextStep}");
            }

            return(result);
        }
Пример #6
0
        private Expression GetExpression(string exprText)
        {
            var parser = AntlrUtils.GetParser(exprText);
            var cst    = parser.compileUnit();
            var ast    = new BuildBinaryTreeVisitor().VisitCompileUnit(cst);

            return(new BuildExpressionVisitor().Visit((ExpressionNode)ast));
        }
Пример #7
0
        /// <summary>
        /// If value is null returns the value of the text value of the node.
        /// Otherwise it just return the provided value.
        /// </summary>
        /// <param name="tree">The node tree.</param>
        /// <param name="value">The provided value.</param>
        /// <returns>The value.</returns>
        protected string GetActualValue(IParseTree tree, string value)
        {
            if (value is null)
            {
                return(AntlrUtils.GetSourceText((ParserRuleContext)tree));
            }

            return(value);
        }
 /// <summary>
 /// Inform about a node.
 /// </summary>
 /// <param name="ctx">The context.</param>
 /// <param name="path">The name.</param>
 /// <returns>The inform result.</returns>
 private string Inform(IParseTree ctx, string path)
 {
     return(this.Inform(ctx, path, AntlrUtils.GetSourceText((ParserRuleContext)ctx)));
 }
Пример #9
0
        // Here's where we do the real work...
        public static void translateFile(string fullName)
        {
            long startTime = DateTime.Now.Ticks;

            if (cfg.DebugLevel > 3)
            {
                Console.Out.WriteLine("Translating file {0}", fullName);
            }
            if (cfg.DebugLevel > 5)
            {
                Console.Out.WriteLine("Parsing file {0}", fullName);
            }
            CommonTreeNodeStream csTree = parseFile(fullName);

            if (cfg.DumpCSharp && csTree != null)
            {
                AntlrUtils.DumpNodesFlat(csTree, "C Sharp Parse Tree");
                csTree.Reset();
            }

            if (csTree != null)
            {
                // Make java compilation units from C# file
                JavaMaker javaMaker = new JavaMaker(csTree);
                javaMaker.Filename         = fullName;
                javaMaker.TraceDestination = Console.Error;

                javaMaker.Cfg       = cfg;
                javaMaker.CUMap     = new Dictionary <string, CUnit>();
                javaMaker.CUKeys    = new List <string>();
                javaMaker.IsJavaish = cfg.InternalIsJavaish;

                javaMaker.EnumXmlWriter = enumXmlWriter;

                if (cfg.DebugLevel >= 1)
                {
                    Console.Out.WriteLine("Translating {0} to Java", fullName);
                }

                javaMaker.compilation_unit();

                int saveEmittedCommentTokenIdx = 0;
                for (int i = 0; i < javaMaker.CUKeys.Count; i++)
                {
                    string     typeName = javaMaker.CUKeys[i];
                    CommonTree typeAST  = javaMaker.CUMap[typeName].Tree;

                    string claName = typeName.Substring(typeName.LastIndexOf('.') + 1);
                    string nsDir   = typeName.LastIndexOf('.') >= 0 ? typeName.Substring(0, typeName.LastIndexOf('.')).Replace('.', Path.DirectorySeparatorChar) : "";

                    if (cfg.CheatDir != "")
                    {
                        String ignoreMarker = Path.Combine(cfg.CheatDir, Path.Combine(nsDir, claName + ".none"));
                        if (File.Exists(ignoreMarker))
                        {
                            // Don't generate this class
                            continue;
                        }
                    }
                    // Make sure parent directory exists
                    String javaFDir  = Path.Combine(cfg.OutDir, nsDir);
                    String javaFName = Path.Combine(javaFDir, claName + ".java");
                    if (!Directory.Exists(javaFDir))
                    {
                        Directory.CreateDirectory(javaFDir);
                    }
                    if (cfg.CheatDir != "")
                    {
                        String cheatFile = Path.Combine(cfg.CheatDir, Path.Combine(nsDir, claName + ".java"));
                        if (File.Exists(cheatFile))
                        {
                            // the old switcheroo
                            File.Copy(cheatFile, javaFName, true);
                            continue;
                        }
                    }

                    // Translate calls to .Net to calls to Java libraries
                    CommonTreeNodeStream javaSyntaxNodes = new CommonTreeNodeStream(typeAST);
                    if (cfg.DumpJavaSyntax && javaSyntaxNodes != null)
                    {
                        AntlrUtils.DumpNodesFlat(javaSyntaxNodes, "Java Syntax Parse Tree for " + claName);
                        javaSyntaxNodes.Reset();
                    }
                    javaSyntaxNodes.TokenStream = csTree.TokenStream;

                    NetMaker netMaker = new NetMaker(javaSyntaxNodes);
                    netMaker.Filename         = fullName;
                    netMaker.TraceDestination = Console.Error;

                    netMaker.Cfg    = cfg;
                    netMaker.AppEnv = AppEnv;

                    netMaker.SearchPath      = javaMaker.CUMap[typeName].SearchPath;
                    netMaker.AliasKeys       = javaMaker.CUMap[typeName].NameSpaceAliasKeys;
                    netMaker.AliasNamespaces = javaMaker.CUMap[typeName].NameSpaceAliasValues;

                    netMaker.IsJavaish = cfg.InternalIsJavaish;
                    netMaker.Imports   = new Set <String>();
                    netMaker.AddToImports(javaMaker.Imports);

                    if (cfg.DebugLevel > 5)
                    {
                        Console.Out.WriteLine("Translating {0} Net Calls to Java", javaFName);
                    }
                    NetMaker.compilation_unit_return javaCompilationUnit = netMaker.compilation_unit();

                    CommonTreeNodeStream javaCompilationUnitNodes = new CommonTreeNodeStream(javaCompilationUnit.Tree);
                    javaCompilationUnitNodes.TokenStream = csTree.TokenStream;

                    if (cfg.DumpJava && javaCompilationUnitNodes != null)
                    {
                        AntlrUtils.DumpNodesFlat(javaCompilationUnitNodes, "Final Java Parse Tree for " + claName);
                        javaCompilationUnitNodes.Reset();
                    }
                    // Pretty print java parse tree as text
                    JavaPrettyPrint outputMaker = new JavaPrettyPrint(javaCompilationUnitNodes);
                    outputMaker.Filename         = fullName;
                    outputMaker.TraceDestination = Console.Error;
                    outputMaker.TemplateLib      = templates;

                    outputMaker.Cfg = cfg;
                    outputMaker.EmittedCommentTokenIdx = saveEmittedCommentTokenIdx;
                    bool isPartial = javaMaker.CUMap[typeName].IsPartial;
                    if (isPartial)
                    {
                        if (!partialTypes.ContainsKey(typeName))
                        {
                            partialTypes[typeName]          = new ClassDescriptorSerialized(claName);
                            partialTypes[typeName].FileName = javaFName;
                        }
                        outputMaker.PartialDescriptor = partialTypes[typeName];
                    }

                    outputMaker.IsLast = i == (javaMaker.CUKeys.Count - 1);

                    if (!isPartial)
                    {
                        if (cfg.DebugLevel >= 1)
                        {
                            Console.Out.WriteLine("Writing out {0}", javaFName);
                        }
                        StreamWriter javaW = new StreamWriter(javaFName);
                        javaW.Write(outputMaker.compilation_unit().ToString().Replace("//CS2J:Java code:", ""));
                        javaW.Close();
                    }
                    else
                    {
                        // fill out partialTypes[typeName]
                        outputMaker.compilation_unit();
                    }
                    saveEmittedCommentTokenIdx = outputMaker.EmittedCommentTokenIdx;
                }
            }

            double elapsedTime = ((DateTime.Now.Ticks - startTime) / TimeSpan.TicksPerMillisecond) / 1000.0;

            System.Console.Out.WriteLine("Processed {0} in: {1} seconds.", fullName, elapsedTime);
            System.Console.Out.WriteLine("");
            System.Console.Out.WriteLine("");
        }