// eliminate "PtrSafe"
 public override void EnterDeclareStmt([NotNull] VBAParser.DeclareStmtContext context)
 {
     if (context.PTRSAFE() != null)
     {
         Rewriter.Replace(context.PTRSAFE().Symbol, "");
     }
 }
 // eliminate config text
 public override void ExitModuleConfig([NotNull] VBAParser.ModuleConfigContext context)
 {
     // remove any config
     if (context != null)
     {
         Rewriter.Replace(context.Start, context.Stop, "");
     }
 }
 // eliminate header text
 public override void ExitModuleHeader([NotNull] VBAParser.ModuleHeaderContext context)
 {
     // remove any header
     if (context != null)
     {
         Rewriter.Replace(context.Start, context.Stop, "");
     }
 }
        // get the name of the file
        public override void EnterAttributeStmt([NotNull] VBAParser.AttributeStmtContext context)
        {
            if (context.implicitCallStmt_InStmt().GetText() == "VB_Name")
            {
                FileName = context.literal()[0].GetText().Trim('"');
            }

            // remove all attributes
            Rewriter.Replace(context.Start, context.Stop, "");
        }
        // you cannot initialize elements inside a Structure
        // since VBA Type(s) are transformed in VB.NET Structure(s)
        // we remove the initialization of array
        public override void ExitTypeStmt_Element([NotNull] VBAParser.TypeStmt_ElementContext context)
        {
            var currentType = Types.Peek();

            if (context.subscripts() != null && !context.subscripts().IsEmpty)
            {
                InitStructures[currentType].Add($"ReDim {context.ambiguousIdentifier().GetText()}({context.subscripts().GetText()})");

                StringBuilder commas = new StringBuilder();
                Enumerable.Range(0, context.subscripts().subscript().Length - 1).ToList().ForEach(x => commas.Append(","));
                Rewriter.Replace(context.subscripts().Start, context.subscripts().Stop, $"{commas.ToString()}");
            }
        }
        // transform a Type in a Structure
        public override void EnterTypeStmt(VBAParser.TypeStmtContext context)
        {
            var typeName = context.ambiguousIdentifier().GetText();

            Types.Push(typeName);
            InitStructures.Add(typeName, new StructureInitializer(typeName));

            Rewriter.Replace(context.TYPE().Symbol, "Structure");
            Rewriter.Replace(context.END_TYPE().Symbol, "End Structure");

            string visibility = context.visibility().GetText();

            foreach (var st in context.typeStmt_Element())
            {
                Rewriter.InsertBefore(st.Start, $"{visibility} ");
            }
        }
        // we search for the Main Sub
        public override void EnterSubStmt([NotNull] VBAParser.SubStmtContext context)
        {
            if (context.ambiguousIdentifier().GetText().Trim() == "Main_Run" ||
                context.ambiguousIdentifier().GetText().Trim() == "Main_Sub" ||
                context.ambiguousIdentifier().GetText().Trim() == "Main")
            {
                MainFile = true;

                Rewriter.Replace(context.ambiguousIdentifier().Start, "Main");
                // Some function of VB.Net are culture-aware,
                // this means, for instance, that when parsing a double from a
                // string it searchs for the proper-culture decimal separator (e.g, ',' or '.'). So, we set a culture that ensure
                // that VB.Net uses a decimal separator '.'
                Rewriter.InsertBefore(context.block().Start, $"{Environment.NewLine}Dim sw As System.Diagnostics.Stopwatch = System.Diagnostics.Stopwatch.StartNew(){Environment.NewLine}");
                Rewriter.InsertBefore(context.block().Start, $"{Environment.NewLine}System.Globalization.CultureInfo.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture{Environment.NewLine}");
                // make the program wait at the end
                Rewriter.InsertBefore(context.block().Stop, $"{Environment.NewLine}Console.WriteLine(\"Press any key to exit the program\"){Environment.NewLine}Console.ReadKey(){Environment.NewLine}");
                Rewriter.InsertBefore(context.block().Stop, $"{Environment.NewLine}sw.Stop(){Environment.NewLine}Console.WriteLine($\"Time elapsed {{sw.Elapsed}}\"){Environment.NewLine}");
            }
        }
Beispiel #8
0
        public override object VisitConstructor_declaration(
            [NotNull] CSharpParser.Constructor_declarationContext context)
        {
            if (GetCurrentNamespace() == _breadcrumbNamespace && GetCurrentClass() == _breadcrumbDeclaration.Identifier)
            {
                _hasBreadcrumbConstructor = true;

                var preCtorWhitespace = Tokens.GetHiddenTokensToLeft(context.Start.TokenIndex, Lexer.Hidden);

                int tabLevels = 1 + ((preCtorWhitespace?.Count ?? 0) > 0 ?
                                     _stringUtilService.CalculateTabLevels(preCtorWhitespace[0]?.Text ?? string.Empty, _tabString) : 0);

                var fixedParams = context?.constructor_declarator()?.formal_parameter_list()?.fixed_parameters()
                                  ?.fixed_parameter();

                if (fixedParams != null)
                {
                    foreach (var fixedParam in fixedParams)
                    {
                        var paramName = $"{fixedParam.type_().GetText()} {fixedParam.identifier().GetText()}";
                        if (_ctorParamDict.ContainsKey(paramName))
                        {
                            _ctorParamDict.Remove(paramName);
                        }
                    }
                }

                var ctorStatements = context?.constructor_body()?.block()?.statement_list();
                if (ctorStatements != null)
                {
                    foreach (var statement in ctorStatements.statement())
                    {
                        var minStatement = _cSharpParserService.GetTextWithWhitespaceMinified(Tokens, statement);
                        if (_ctorAssignmentDict.ContainsKey(minStatement))
                        {
                            _ctorAssignmentDict.Remove(minStatement);
                        }
                    }
                }

                if (_ctorParamDict.Keys.Count > 0)
                {
                    // add params
                    var ctorParams = _ctorParamDict.Values.ToList();

                    var formalParamList = context?.constructor_declarator()?.formal_parameter_list();

                    var finalFixedParam = context?.constructor_declarator()
                                          ?.formal_parameter_list()
                                          ?.fixed_parameters()
                                          ?.fixed_parameter()
                                          ?.Last();

                    int fixedParamStopIndex = finalFixedParam?.Stop?.TokenIndex
                                              ?? context.constructor_declarator().OPEN_PARENS().Symbol.TokenIndex;

                    var paramStringBuilder = new StringBuilder();
                    if (finalFixedParam != null)
                    {
                        var preFinalParamWhitespace = Tokens.GetHiddenTokensToLeft(
                            finalFixedParam?.Start?.TokenIndex ?? -1, Lexer.Hidden);

                        int finalParamtabs = (preFinalParamWhitespace?.Count ?? 0) > 0 ?
                                             _stringUtilService.CalculateTabLevels(preFinalParamWhitespace[0]?.Text ?? string.Empty, _tabString) : 0;

                        if (finalParamtabs > 0)
                        {
                            paramStringBuilder.Append(_cSharpParserService.GenerateFixedParameters(
                                                          ctorParams,
                                                          tabLevels,
                                                          _tabString));

                            if (formalParamList?.parameter_array() != null)
                            {
                                var preParamArrayWhitespaceArray = Tokens.GetHiddenTokensToLeft(
                                    formalParamList.parameter_array().Start.TokenIndex, Lexer.Hidden);

                                string preParamArrayWhitespace =
                                    preParamArrayWhitespaceArray.Count > 0 ?
                                    preParamArrayWhitespaceArray[0].Text : string.Empty;

                                if (!Regex.IsMatch(preParamArrayWhitespace, @"\r?\n"))
                                {
                                    IsModified = true;
                                    Rewriter.InsertBefore(
                                        formalParamList.parameter_array().Start.TokenIndex,
                                        "\r\n" +
                                        _stringUtilService.TabString(string.Empty, finalParamtabs, _tabString));
                                }
                            }
                        }
                        else
                        {
                            paramStringBuilder.Append(_cSharpParserService.GenerateFixedParameters(
                                                          ctorParams,
                                                          tabLevels,
                                                          _tabString,
                                                          false,
                                                          true));
                        }
                    }
                    else
                    {
                        paramStringBuilder.Append(_cSharpParserService.GenerateFixedParameters(
                                                      ctorParams,
                                                      tabLevels,
                                                      _tabString,
                                                      true));

                        if (formalParamList?.parameter_array() != null)
                        {
                            var preParamArrayWhitespaceArray = Tokens.GetHiddenTokensToLeft(
                                formalParamList.parameter_array().Start.TokenIndex, Lexer.Hidden);

                            string preParamArrayWhitespace =
                                preParamArrayWhitespaceArray.Count > 0 ?
                                preParamArrayWhitespaceArray[0].Text : string.Empty;

                            if (!Regex.IsMatch(preParamArrayWhitespace, $"\r?\n"))
                            {
                                IsModified = true;
                                Rewriter.InsertBefore(
                                    formalParamList.parameter_array().Start.TokenIndex,
                                    "\r\n" + _stringUtilService.TabString(string.Empty, tabLevels, _tabString));
                            }
                        }
                    }

                    var paramString = paramStringBuilder.ToString();
                    if (paramString.Length > 0)
                    {
                        IsModified = true;
                        Rewriter.InsertAfter(fixedParamStopIndex, paramString);
                    }
                }

                if (_ctorAssignmentDict.Keys.Count > 0)
                {
                    var ctorAssignments = _ctorAssignmentDict.Values.ToList();

                    var assignmentsString = _cSharpParserService.GenerateSimpleAssignments(
                        ctorAssignments,
                        tabLevels,
                        _tabString);

                    var constructorBody = context?.constructor_body();
                    if (constructorBody.SEMICOLON() != null)
                    {
                        var conBodyBuilder = new StringBuilder();

                        conBodyBuilder.Append("\r\n");
                        conBodyBuilder.Append(_stringUtilService.TabString("{", tabLevels - 1, _tabString));
                        conBodyBuilder.Append(assignmentsString);
                        conBodyBuilder.Append("\r\n");
                        conBodyBuilder.Append(_stringUtilService.TabString("}", tabLevels - 1, _tabString));
                        IsModified = true;
                        Rewriter.Replace(constructorBody.SEMICOLON().Symbol.TokenIndex, conBodyBuilder.ToString());
                    }
                    else
                    {
                        var block = constructorBody.block();

                        int?finalAssignment     = block.statement_list()?.statement()?.Last()?.Stop?.TokenIndex;
                        int assignmentStopIndex = finalAssignment
                                                  ?? block.OPEN_BRACE().Symbol.TokenIndex;

                        var assignmentStringBuilder = new StringBuilder();
                        assignmentStringBuilder.Append(assignmentsString);

                        var postAssignmentStopWhitespaceArray = Tokens.GetHiddenTokensToRight(
                            assignmentStopIndex, Lexer.Hidden);

                        string postAssignmentStopWhitespace =
                            postAssignmentStopWhitespaceArray.Count > 0 ?
                            postAssignmentStopWhitespaceArray[0].Text : string.Empty;

                        if (!Regex.IsMatch(postAssignmentStopWhitespace, @"\r?\n"))
                        {
                            assignmentStringBuilder.Append("\r\n");
                        }

                        var assignmentString = assignmentStringBuilder.ToString();
                        if (assignmentString.Length > 0)
                        {
                            IsModified = true;
                            Rewriter.InsertAfter(assignmentStopIndex, assignmentString);
                        }
                    }
                }
            }

            VisitChildren(context);
            return(null);
        }
        public override object VisitClass_declaration([NotNull] CSharpParser.Class_declarationContext context)
        {
            var currentNamespace = string.Join(".", _currentNamespace.ToArray().Reverse());

            if (context.identifier().GetText() == _constructorClassName &&
                currentNamespace == _constructorClassNamespace)
            {
                _isConstructorClassFound = true;

                var preclassWhitespace = Tokens.GetHiddenTokensToLeft(context.Start.TokenIndex, Lexer.Hidden);

                int classBodyTabLevels = 1 + ((preclassWhitespace?.Count ?? 0) > 0 ?
                                              _stringUtilService.CalculateTabLevels(preclassWhitespace[0]?.Text ?? string.Empty, _tabString) : 0);

                int ctorBodyTabLevels = classBodyTabLevels + 1;

                int?finalConstantOrField = null;
                int?finalField           = null;
                int?finalProperty        = null;

                CSharpParser.Constructor_declarationContext constructorContext = null;
                bool hasServiceField   = false;
                bool hasCtorParam      = false;
                bool hasCtorAssignment = false;

                var members = context?.class_body()?.class_member_declarations()?.class_member_declaration();
                if (members != null)
                {
                    foreach (var member in members)
                    {
                        if (member.constant_declaration() != null)
                        {
                            finalConstantOrField = member.constant_declaration().Stop.TokenIndex;
                        }
                        else if (member.field_declaration() != null)
                        {
                            var fieldDec = member.field_declaration();
                            finalField           = fieldDec.Stop.TokenIndex;
                            finalConstantOrField = fieldDec.Stop.TokenIndex;
                            if (fieldDec.type_().GetText() == _serviceInterfaceType)
                            {
                                foreach (var varDec in fieldDec.variable_declarators().variable_declarator())
                                {
                                    if (varDec.identifier().GetText() ==
                                        $"_{_serviceIdentifier}")
                                    {
                                        hasServiceField = true;
                                        break;
                                    }
                                }
                            }
                        }
                        else if (member.property_declaration() != null)
                        {
                            finalProperty = member.property_declaration().Stop.TokenIndex;
                        }
                        else if (member.constructor_declaration() != null)
                        {
                            constructorContext ??= member.constructor_declaration();
                        }
                    }
                }

                int fieldStopIndex = finalField
                                     ?? finalConstantOrField
                                     ?? context.class_body().OPEN_BRACE().Symbol.TokenIndex;

                int?constructorStopIndex = null;

                var           fieldStringBuilder       = new StringBuilder();
                StringBuilder constructorStringBuilder = null;

                if (!hasServiceField)
                {
                    fieldStringBuilder.Append(_cSharpParserService.GenerateFieldDeclaration(
                                                  _fieldDeclaration,
                                                  classBodyTabLevels,
                                                  _tabString));
                }

                if (constructorContext is null)
                {
                    constructorStopIndex = finalProperty
                                           ?? finalConstantOrField
                                           ?? fieldStopIndex;

                    constructorStringBuilder = constructorStopIndex == fieldStopIndex
                        ? fieldStringBuilder : new StringBuilder();

                    constructorStringBuilder.Append(
                        _cSharpParserService.GenerateConstructorDeclaration(
                            _constructorDeclaration,
                            classBodyTabLevels,
                            _tabString));
                }
                else
                {
                    CSharpParser.Fixed_parameterContext finalFixedParam = null;

                    var formalParamList = constructorContext?.constructor_declarator()?.formal_parameter_list();
                    if (formalParamList != null)
                    {
                        var fixedParams = formalParamList.fixed_parameters();
                        if (fixedParams != null)
                        {
                            foreach (var fixedParam in fixedParams.fixed_parameter())
                            {
                                if (fixedParam.type_().GetText() == _serviceInterfaceType &&
                                    fixedParam.identifier().GetText() == _serviceIdentifier)
                                {
                                    hasCtorParam = true;
                                    break;
                                }
                            }
                            finalFixedParam = fixedParams.fixed_parameter().Last();
                        }
                    }
                    if (!hasCtorParam)
                    {
                        var ctorParam = _cSharpCommonStgService.RenderFixedParameter(_constructorParameter);

                        int fixedParamStopIndex = finalFixedParam?.Stop?.TokenIndex
                                                  ?? constructorContext.constructor_declarator().OPEN_PARENS().Symbol.TokenIndex;

                        var paramStringBuilder = new StringBuilder();
                        if (finalFixedParam != null)
                        {
                            var preFinalParamWhitespace = Tokens.GetHiddenTokensToLeft(
                                finalFixedParam?.Start?.TokenIndex ?? -1, Lexer.Hidden);

                            int finalParamtabs = (preFinalParamWhitespace?.Count ?? 0) > 0 ?
                                                 _stringUtilService.CalculateTabLevels(
                                preFinalParamWhitespace?[0]?.Text ?? string.Empty, _tabString) : 0;

                            if (finalParamtabs > 0)
                            {
                                paramStringBuilder.Append(",\r\n");
                                paramStringBuilder.Append(_stringUtilService.TabString(
                                                              ctorParam,
                                                              finalParamtabs,
                                                              _tabString));
                                if (formalParamList?.parameter_array() != null)
                                {
                                    var preParamArrayWhitespaceArray = Tokens.GetHiddenTokensToLeft(
                                        formalParamList.parameter_array().Start.TokenIndex, Lexer.Hidden);

                                    string preParamArrayWhitespace =
                                        preParamArrayWhitespaceArray.Count > 0 ?
                                        preParamArrayWhitespaceArray[0].Text : string.Empty;

                                    if (!Regex.IsMatch(preParamArrayWhitespace, @"\r?\n"))
                                    {
                                        _isRewritten = true;
                                        Rewriter.InsertBefore(
                                            formalParamList.parameter_array().Start.TokenIndex,
                                            "\r\n" +
                                            _stringUtilService.TabString(string.Empty, finalParamtabs, _tabString));
                                    }
                                }
                            }
                            else
                            {
                                paramStringBuilder.Append(", ");
                                paramStringBuilder.Append(ctorParam);
                            }
                        }
                        else
                        {
                            paramStringBuilder.Append("\r\n");
                            paramStringBuilder.Append(
                                _stringUtilService.TabString(ctorParam, ctorBodyTabLevels, _tabString));
                            if (formalParamList?.parameter_array() != null)
                            {
                                var preParamArrayWhitespaceArray = Tokens.GetHiddenTokensToLeft(
                                    formalParamList.parameter_array().Start.TokenIndex, Lexer.Hidden);

                                string preParamArrayWhitespace =
                                    preParamArrayWhitespaceArray.Count > 0 ?
                                    preParamArrayWhitespaceArray[0].Text : string.Empty;

                                if (!Regex.IsMatch(preParamArrayWhitespace, $"\r?\n"))
                                {
                                    _isRewritten = true;
                                    Rewriter.InsertBefore(
                                        formalParamList.parameter_array().Start.TokenIndex,
                                        "\r\n" +
                                        _stringUtilService.TabString(string.Empty, ctorBodyTabLevels, _tabString));
                                }
                            }
                        }

                        var paramString = paramStringBuilder.ToString();
                        if (paramString.Length > 0)
                        {
                            _isRewritten = true;
                            Rewriter.InsertAfter(fixedParamStopIndex, paramString);
                        }
                    }

                    string ctorAssignString = _cSharpCommonStgService.RenderSimpleAssignment(_constructorAssignment);

                    var constructorBody = constructorContext?.constructor_body();
                    if (constructorBody.SEMICOLON() != null)
                    {
                        _isRewritten = true;
                        Rewriter.Replace(constructorBody.SEMICOLON().Symbol.TokenIndex, _stringUtilService.TabString(
                                             $@"\r\n{{\r\n{_tabString}{ctorAssignString}\r\n}}",
                                             classBodyTabLevels,
                                             _tabString));
                    }
                    else
                    {
                        var block         = constructorBody.block();
                        var statementList = block?.statement_list()?.GetText();
                        if (statementList != null)
                        {
                            var assignmentMatchString =
                                $@"[\s;{{]_{_serviceIdentifier}\s*=\s*{_serviceIdentifier}\s*;";

                            hasCtorAssignment = Regex.Match(statementList, assignmentMatchString).Success;
                        }

                        if (!hasCtorAssignment)
                        {
                            int?finalAssignment     = block.statement_list().statement().Last().Stop.TokenIndex;
                            int assignmentStopIndex = finalAssignment
                                                      ?? block.OPEN_BRACE().Symbol.TokenIndex;

                            var assignmentStringBuilder = new StringBuilder();

                            assignmentStringBuilder.Append("\r\n");
                            assignmentStringBuilder.Append(_stringUtilService.TabString(
                                                               ctorAssignString, ctorBodyTabLevels, _tabString));

                            var postAssignmentStopWhitespaceArray = Tokens.GetHiddenTokensToRight(
                                assignmentStopIndex, Lexer.Hidden);

                            string postAssignmentStopWhitespace =
                                postAssignmentStopWhitespaceArray.Count > 0 ?
                                postAssignmentStopWhitespaceArray[0].Text : string.Empty;

                            if (!Regex.IsMatch(postAssignmentStopWhitespace, @"\r?\n"))
                            {
                                assignmentStringBuilder.Append("\r\n");
                            }

                            var assignmentString = assignmentStringBuilder.ToString();
                            if (assignmentString.Length > 0)
                            {
                                _isRewritten = true;
                                Rewriter.InsertAfter(assignmentStopIndex, assignmentString);
                            }
                        }
                    }
                }

                var fieldString = fieldStringBuilder.ToString();
                if (fieldString.Length > 0)
                {
                    _isRewritten = true;
                    Rewriter.InsertAfter(fieldStopIndex, fieldString);
                }

                if (constructorStringBuilder != null &&
                    constructorStopIndex != fieldStopIndex)
                {
                    var constructorString = constructorStringBuilder.ToString();
                    if (constructorString.Length > 0)
                    {
                        _isRewritten = true;
                        Rewriter.InsertAfter(Tokens.Get(constructorStopIndex ?? -1), constructorString);
                    }
                }
            }
            VisitChildren(context);
            return(null);
        }
 // the Erase statement works differently in VBA and VB.Net
 // in VBA, it deletes the array a re-initialize it
 // in VB.Net, it only deletes it
 public override void EnterEraseStmt([NotNull] VBAParser.EraseStmtContext context)
 {
     Rewriter.Replace(context.Start, context.Stop, $"Array.Clear({context.valueStmt()[0].GetText()}, 0, {context.valueStmt()[0].GetText()}.Length)");
 }