private void btnGenerate_Click(object sender, EventArgs e)
 {
     foreach (var fileName in VB6Compiler.GetFiles(Folder))
     {
         var compileResult = VB6Compiler.Compile(fileName, null, false);
         var tree          = new VB6NodeTree(compileResult);
         ASTPatternGenerator.GetCode(tree);
     }
 }
 private void ShowFiles()
 {
     lstFileNames.Items.Clear();
     foreach (var fileName in VB6Compiler.GetFiles(Folder))
     {
         lstFileNames.Items.Add(fileName);
     }
     //TranslatorForPattern.IntializeTranslatorForPattern();
 }
        private void btnTest_Click(object sender, EventArgs e)
        {
            var enabled = DebugClass.Enabled;

            DebugClass.Enabled      = false;
            frmPatternsForm         = new frmPatterns(new List <string>(VB6Compiler.GetFiles(Folder)));
            frmPatternsForm.Visible = true;
            //var tfp = new TranslatorForPattern();
            DebugClass.Enabled = enabled;
        }
 public void CompileAll()
 {
     foreach (var fileName in fileNames)
     {
         if (fileName.EndsWith(".frx", StringComparison.InvariantCulture))
         {
             continue;
         }
         compileResults[fileName] = VB6Compiler.Compile(fileName, null, false);
     }
 }
        private void btnConvert_Click(object sender, EventArgs e)
        {
            var fileName = (string)lstFileNames.SelectedItem;

            var compileResult = VB6Compiler.Compile(fileName);

            txtVBCode.Text           = compileResult.VBCode;
            txtCSharpCode.Text      += "// C Sharp Code:\r\n" + compileResult.CSharpCode;
            txtVBCode.ScrollBars     = ScrollBars.Both;
            txtCSharpCode.ScrollBars = ScrollBars.Both;
        }
Exemple #6
0
        public static void Compile(IEnumerable <string> Files)
        {
            foreach (var fname in Files)
            {
                DebugClass.LogStandard("Parsing file: " + fname);

                var compileResult = VB6Compiler.Compile(fname);

                DebugClass.LogStandard(compileResult.CSharpCode);
            }
        }
Exemple #7
0
        // This method looks up the depth of the $CONTENT identifier.
        // We use it to determine where to cut relative paths.

        // TODO: Parse wrapper only once, not one time per pattern. Well, it hardly matters for performance I think, so leave it.
        public void SetCutDepthAndCutPath()
        {
            var wrapperCompileResult = VB6Compiler.Compile("Test.bas", vbWrapperCode, false);
            var translator           = new Translator(wrapperCompileResult);

            DebugClass.LogError("SetCutDepthAndCutPath: " + vbWrapperCode);

            var visitorCallback = new VisitorCallback()
            {
                Callback = (node, parent) =>
                {
                    var identifier = node.getText().Trim('"').Trim();
                    //if (identifier == Content)
                    var path = translator.GetExtendedPathList(node);

                    DebugClass.LogError("SetCutDepthAndCutPath: " + VbCode + ": " + PrintPath(path));

                    if (identifier == Content)
                    {
                        // Exact match
                        if (path[path.Count - 1].NodeTypeName == "VsICSContext")
                        {
                            cutDepthOfContent = path.Count - 1;
                            DebugClass.LogError("SetCutDepth: MATCH");
                        }
                        // Bounded
                        if (!PathContains(path, "VsICSContext"))
                        {
                            cutDepthOfContent = path.Count;
                            DebugClass.LogError("SetCutDepth: BOUND MATCH");
                        }
                        cutPath = path.Take(cutDepthOfContent).ToList();
                    }
                }
            };

            // First time is to set cutDepthOfContent
            VB6Compiler.Visit(wrapperCompileResult, visitorCallback);
            // Second time is to set cutPath
            VB6Compiler.Visit(wrapperCompileResult, visitorCallback);
            if (cutDepthOfContent == -1)
            {
                throw new InvalidOperationException(nameof(cutDepthOfContent) + " not initialized");
            }
        }
        private void frmVB6ASTBrowser_Load(object sender, EventArgs e)
        {
            var compileResult = VB6Compiler.Compile(FileName, null, false);

            nodeMap = new Dictionary <ParseTree, TreeNode>();

            translator = new Translator(compileResult);

            var visitorCallback = new VisitorCallback()
            {
                Callback = (node, parent) =>
                {
                    var    name      = VbToCsharpPattern.LookupNodeType(node);
                    var    lines     = node.getText().Split('\n');
                    string firstLine = (lines.Length > 0) ? lines[0] : "";

                    if (parent != null && nodeMap.ContainsKey(parent))
                    {
                        var tvNode = nodeMap[parent].Nodes.Add(nodeMap.Count.ToString(new NumberFormatInfo()), name + ": " + firstLine);
                        tvNode.Tag    = node;
                        nodeMap[node] = tvNode;
                    }
                    else
                    {
                        var tvNode = treVB6AST.Nodes.Add(nodeMap.Count.ToString(new NumberFormatInfo()), name + ": " + firstLine);
                        tvNode.Tag    = node;
                        nodeMap[node] = tvNode;
                    }

                    //nodes.Add(node);
                }
            };

            txtDebug.ScrollBars = ScrollBars.Both;

            VB6Compiler.Visit(compileResult, visitorCallback);

            //treVB6AST.ExpandAll();
        }
Exemple #9
0
        public VB6NodeTree(CompileResult compileResult)
        {
            var visitorCallback = Init();

            VB6Compiler.Visit(compileResult, visitorCallback);
        }
Exemple #10
0
        public void VbParsePattern(string pattern)
        {
            SetCutDepthAndCutPath();

            var code          = vbWrapperCode.Replace(Content, pattern);
            var compileResult = VB6Compiler.Compile("Test.bas", code, false);
            var translator    = new Translator(compileResult);

            PatternIdentifiers = GetIdentifiersAndSetTokens(translator, compileResult);

            var       paths = new List <IndexedPath> [PatternIdentifiers.Length];
            ParseTree root  = null;

            DebugClass.LogError("PATTERN: " + VbCode);

            var visitorCallback = new VisitorCallback()
            {
                Callback = (node, parent) =>
                {
                    DebugClass.LogError("Node: " + PrintPath(translator.GetExtendedPathList(node)) + ": " + node.getText());

                    if (root == null)
                    {
                        root = node;
                    }

                    var i = 0;
                    foreach (var identifier in PatternIdentifiers)
                    {
                        if (node.getText().Trim('"') == identifier &&
                            IsInsideSubOrFunction(translator.GetExtendedPathList(node)))
                        {
                            var path = translator.GetExtendedPathList(node);
                            if (paths[i] == null)
                            {
                                paths[i] = path;
                            }
                        }

                        i++;
                    }
                }
            };

            VB6Compiler.Visit(compileResult, visitorCallback);

            var lowestCommonDepth = -1;
            var cutDepth          = -1;

            var comparePath = paths.Length > 0 ? paths[0] : tokenPath;

            if (comparePath == null)
            {
                DebugClass.LogError("VB Code: " + VbCode);
                throw new InvalidOperationException(nameof(comparePath) + " is null");
            }
            int commonDepth = Math.Min(cutPath.Count, comparePath.Count);

            for (int i = 0; i < commonDepth; i++)
            {
                DebugClass.LogError("COMPARE PATHS: " + PrintPath(cutPath));
                foreach (var path in paths)
                {
                    DebugClass.LogError("COMPARE PATHS: " + PrintPath(path));
                }
                DebugClass.LogError("");
                if (cutPath[i].NodeTypeName != comparePath[i].NodeTypeName)
                {
                    break;
                }
                else
                {
                    lowestCommonDepth = Math.Min(comparePath.Count - 1, i + 1);
                }
            }

            if (lowestCommonDepth >= comparePath.Count)
            {
                DebugClass.LogError("VB Code: " + VbCode + ", Identifier: " + PatternIdentifiers[0]);
            }
            VbTreeNodeType = comparePath[lowestCommonDepth].NodeTypeName;

            // Skip uninteresting wrapper nodes
            while (VbTreeNodeType == "VsICSContext" ||
                   VbTreeNodeType == "ImplicitCallStmt_InStmtContext")
            {
                lowestCommonDepth++;
                VbTreeNodeType = comparePath[lowestCommonDepth].NodeTypeName;
            }

            // VbTreeNodeType == "ICS_B_ProcedureCallContext")
            while (VbTreeNodeType == "ArgsCallContext" ||
                   VbTreeNodeType == "AmbiguousIdentifierContext")
            {
                lowestCommonDepth--;
                VbTreeNodeType = comparePath[lowestCommonDepth].NodeTypeName;
            }

            cutDepth = lowestCommonDepth + 1;
            finalCutDepthOfContent = cutDepth;

            var cutPaths = new List <IndexedPath> [PatternIdentifiers.Length];
            var k        = 0;

            foreach (var path in paths)
            {
                var cutPath = new List <IndexedPath>();
                for (var i = cutDepth; i < path.Count; i++)
                {
                    cutPath.Add(path[i]);
                }

                cutPaths[k] = cutPath;
                k++;
            }

            VbPaths = cutPaths;
        }
Exemple #11
0
        public string[] GetIdentifiersAndSetTokens(Translator translator, CompileResult compileResult)
        {
            var identifiers   = new List <string>();
            var tokensPerNode = new List <TokenInfo>();
            //var tokens = new List<Tuple<int, string>>();

            var seen = new Dictionary <string, bool>();

            var visitorCallback = new VisitorCallback()
            {
                Callback = (node, parent) =>
                {
                    //if (node.GetType().Name == "AmbiguousIdentifierContext")
                    var identifier = node.getText().Trim('"').Trim();



                    //DebugClass.Log("GetIdentifier: " + identifier);
                    var path = translator.GetExtendedPathList(node);
                    if (IsInsideSubOrFunction(path))
                    {
                        if (identifier.Length == 1 &&
                            identifier.All(char.IsUpper))
                        {
                            if (!seen.ContainsKey(identifier))
                            {
                                seen[identifier] = true;
                                if (identifier != ReservedLetterForDiscardedResults)
                                {
                                    identifiers.Add(identifier);
                                }
                            }
                        }
                        else
                        {
                            // A general method will for each token add the parent node, and its path,
                            // then extract this path for each token, extract all tokens from path and
                            // check that the token exists in the extracted tokens.
                            // Does this account for the order? Partly, it accounts for the order
                            // within different nodes, but not multiple tokens within the same node.
                            // So to handle that we need to group tokens by node.

                            var tokens = GetTokens(node);
                            if (tokens.Count > 0)
                            {
                                tokenPath = tokenPath ?? path;
                                tokensPerNode.Add(new TokenInfo(path, tokens.Select(x => x.Item2).ToList()));
                                DebugClass.LogError("TOKENS" + string.Join("@", tokens));
                            }
                        }
                    }
                }
            };

            VB6Compiler.Visit(compileResult, visitorCallback);

            _patternTokens = tokensPerNode;

            if (cutDepthOfContent == -1)
            {
                throw new InvalidOperationException(nameof(cutDepthOfContent) + " not initialized");
            }

            return(identifiers.ToArray());
        }
        private void btnTranslateWithLogging_Click(object sender, EventArgs e)
        {
            var outFolder       = Folder + "-out";
            var extraModuleName = "VB6CompilerExtra.bas";

            var extraModule = @"
Public Sub Log(ByVal Msg As String)
    Static FileNum As Single
    If FileNum = 0 Then
        FileNum = FreeFile
        Open App.Path & ""\ProgramLog.txt"" For Output As FileNum
    End If
    Print #FileNum, Msg
End Sub

Public Sub LogEnter(ParamArray Text() As Variant)
    Dim intLoopIndex As Integer, Serialized As String
    Serialized = """"
    For intLoopIndex = 0 To UBound(Text)
      Serialized = Serialized & "", "" & Text(intLoopIndex)
    Next intLoopIndex
    Log ""ENTER "" & Serialized
End Sub

Public Sub LogLeave(ParamArray Text() As Variant)
    Dim intLoopIndex As Integer, Serialized As String
    Serialized = """"
    For intLoopIndex = 0 To UBound(Text)
      Serialized = Serialized & "", "" & Text(intLoopIndex)
    Next intLoopIndex
    Log ""LEAVE "" & Serialized
End Sub

Public Function SerializeInteger(arg as Integer) as String
    SerializeInteger = CStr(arg)
End Function

Public Function SerializeDouble(arg as Double) as String
    SerializeDouble = CStr(arg)
End Function

Public Function SerializeSingle(arg as Single) as String
    SerializeSingle = CStr(arg)
End Function

Public Function SerializeBoolean(arg as Boolean) as String
    If arg Then
        SerializeBoolean = ""True""
    Else
        SerializeBoolean = ""False""
    End If
End Function

Public Function SerializeForm(arg as Form) as String
    SerializeForm = arg.Name
End Function

Public Function SerializeString(arg As String) As String
    SerializeString = arg
End Function

Public Function SerializeDate(arg As Date) As String
    SerializeDate = CStr(arg)
End Function
";

            foreach (var fileName in VB6Compiler.GetFiles(Folder, true, true))
            {
                var    bname       = Path.GetFileName(fileName);
                string outFileName = Path.Combine(outFolder, bname);
                if (
                    (fileName.EndsWith(".frx", System.StringComparison.InvariantCulture)) ||
                    (fileName.EndsWith(".vbw", System.StringComparison.InvariantCulture)))
                {
                    System.IO.File.Copy(fileName, outFileName, true);
                    continue;
                }
                if (fileName.EndsWith(".vbp", System.StringComparison.InvariantCulture))
                {
                    var text = System.IO.File.ReadAllText(fileName, Encoding.GetEncoding(1252));
                    text += "Module=mod_VB6CompilerExtra; " + extraModuleName + "\r\n";
                    System.IO.File.WriteAllText(outFileName, text, Encoding.GetEncoding(1252));
                    continue;
                }

                var compileResult = VB6Compiler.Compile(fileName, null, false);
                var tree          = new VB6NodeTree(compileResult);
                tree.AddExtraModule = (a, b) =>
                {
                    extraModule += b;
                };
                var se = VB6NodeTranslatorLoader.Translate(tree);
                var sl = se.ToList();
                sl.AddRange(GetComments(compileResult));
                sl.Sort((a, b) => a.index.CompareTo(b.index));
                //var s = String.Join("", sl.Select(x => x.index.ToString() + ":" + x.token));
                var s = String.Join("", sl.Select(x => x.token));
                System.IO.Directory.CreateDirectory(outFolder);
                s = Regex.Replace(s, "([^\r])\n", "$1\r\n");
                System.IO.File.WriteAllText(outFileName, s, Encoding.GetEncoding(1252));
            }

            System.IO.File.WriteAllText(Path.Combine(outFolder, extraModuleName), extraModule, Encoding.GetEncoding(1252));

            string            message = "Wrote new files to: " + outFolder;
            string            caption = "Compilation Successful!";
            MessageBoxButtons buttons = MessageBoxButtons.OK;
            var result = MessageBox.Show(message, caption, buttons);
        }