/// <summary>
 /// Selects the text specified in the action point
 /// </summary>
 public static void ExecuteActionPoint(ActionPoint point, ScintillaNet.ScintillaControl sci)
 {
     if (point.EntryPosition != -1 && point.ExitPosition != -1)
     {
         Int32 start = sci.MBSafePosition(point.EntryPosition);
         Int32 end = sci.MBSafePosition(point.ExitPosition);
         sci.SetSel(start, end);
     }
     else if (point.EntryPosition != -1 && point.ExitPosition == -1)
     {
         Int32 start = sci.MBSafePosition(point.EntryPosition);
         sci.SetSel(start, start);
     }
 }
 /// <summary>
 /// Processes the snippet and template arguments
 /// </summary>
 public static Int32 PostProcessSnippets(ScintillaNet.ScintillaControl sci, Int32 currentPosition)
 {
     Int32 delta = 0;
     while (sci.SelectText(BOUNDARY, 0) != -1) { sci.ReplaceSel(""); delta -= BOUNDARY.Length; }
     String text = sci.Text; // Store text temporarily
     Int32 entryPosition = sci.MBSafePosition(text.IndexOf(ENTRYPOINT));
     Int32 exitPosition = sci.MBSafePosition(text.IndexOf(EXITPOINT));
     if (entryPosition != -1 && exitPosition != -1)
     {
         sci.SelectText(ENTRYPOINT, 0); sci.ReplaceSel(""); delta -= ENTRYPOINT.Length;
         sci.SelectText(EXITPOINT, 0); sci.ReplaceSel(""); delta -= EXITPOINT.Length;
         sci.SetSel(entryPosition, exitPosition - ENTRYPOINT.Length);
     }
     else if (entryPosition != -1 && exitPosition == -1)
     {
         sci.SelectText(ENTRYPOINT, 0); sci.ReplaceSel(""); delta -= ENTRYPOINT.Length;
         sci.SetSel(entryPosition, entryPosition);
     }
     else sci.SetSel(currentPosition, currentPosition);
     return delta;
 }
        public static void GenerateDelegateMethods(ScintillaNet.ScintillaControl Sci, MemberModel member,
            Dictionary<MemberModel, ClassModel> selectedMembers, ClassModel classModel, ClassModel inClass)
        {
            Sci.BeginUndoAction();
            try
            {
                string result = TemplateUtils.ReplaceTemplateVariable(
                    TemplateUtils.GetTemplate("DelegateMethodsHeader"), 
                    "Class", 
                    classModel.Type);

                int position = -1;
                ClassModel type;
                List<string> importsList = new List<string>();
                bool isStaticMember = false;

                if ((member.Flags & FlagType.Static) > 0)
                    isStaticMember = true;

                inClass.ResolveExtends();
                
                Dictionary<MemberModel, ClassModel>.KeyCollection selectedMemberKeys = selectedMembers.Keys;
                foreach (MemberModel m in selectedMemberKeys)
                {
                    MemberModel mCopy = (MemberModel) m.Clone();

                    string methodTemplate = NewLine;

                    bool overrideFound = false;
                    ClassModel baseClassType = inClass;
                    while (baseClassType != null && !baseClassType.IsVoid())
                    {
                        MemberList inClassMembers = baseClassType.Members;
                        foreach (MemberModel inClassMember in inClassMembers)
                        {
                            if ((inClassMember.Flags & FlagType.Function) > 0
                               && m.Name.Equals(inClassMember.Name))
                            {
                                mCopy.Flags |= FlagType.Override;
                                overrideFound = true;
                                break;
                            }
                        }

                        if (overrideFound)
                            break;

                        baseClassType = baseClassType.Extends;
                    }

                    if (isStaticMember && (m.Flags & FlagType.Static) == 0)
                        mCopy.Flags |= FlagType.Static;

                    if ((m.Flags & FlagType.Setter) > 0)
                    {
                        methodTemplate += TemplateUtils.GetTemplate("Setter");
                        methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Modifiers", 
                            (TemplateUtils.GetStaticExternOverride(m) + TemplateUtils.GetModifiers(m)).Trim());
                        methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Name", m.Name);
                        methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "EntryPoint", "");
                        methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Type", m.Parameters[0].Type);
                        methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Member", member.Name + "." + m.Name);
                        methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Void", ASContext.Context.Features.voidKey ?? "void");
                    }
                    else if ((m.Flags & FlagType.Getter) > 0)
                    {
                        methodTemplate += TemplateUtils.GetTemplate("Getter");
                        methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Modifiers",
                            (TemplateUtils.GetStaticExternOverride(m) + TemplateUtils.GetModifiers(m)).Trim());
                        methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Name", m.Name);
                        methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "EntryPoint", "");
                        methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Type", FormatType(m.Type));
                        methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Member", member.Name + "." + m.Name);
                    }
                    else
                    {
                        methodTemplate += TemplateUtils.GetTemplate("Function");
                        methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Body", "<<$(Return) >>$(Body)");
                        methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "EntryPoint", null);
                        methodTemplate = TemplateUtils.ToDeclarationWithModifiersString(mCopy, methodTemplate);
                        if (m.Type != null && m.Type.ToLower() != "void")
                            methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Return", "return");
                        else
                            methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Return", null);

                        // check for varargs
                        bool isVararg = false;
                        if (m.Parameters != null && m.Parameters.Count > 0)
                        {
                            MemberModel mm = m.Parameters[m.Parameters.Count - 1];
                            if (mm.Name.StartsWith("..."))
                                isVararg = true;
                        }

                        string callMethodTemplate = TemplateUtils.GetTemplate("CallFunction");
                        if (!isVararg)
                        {
                            callMethodTemplate = TemplateUtils.ReplaceTemplateVariable(callMethodTemplate, "Name", member.Name + "." + m.Name);
                            callMethodTemplate = TemplateUtils.ReplaceTemplateVariable(callMethodTemplate, "Arguments", 
                                TemplateUtils.CallParametersString(m));
                            callMethodTemplate += ";";
                        }
                        else 
                        {
                            List<MemberModel> pseudoParamsList = new List<MemberModel>();
                            pseudoParamsList.Add(new MemberModel("null", null, FlagType.ParameterVar, 0));
                            pseudoParamsList.Add(new MemberModel("[$(Subarguments)].concat($(Lastsubargument))", null, FlagType.ParameterVar, 0));
                            MemberModel pseudoParamsOwner = new MemberModel();
                            pseudoParamsOwner.Parameters = pseudoParamsList;

                            callMethodTemplate = TemplateUtils.ReplaceTemplateVariable(callMethodTemplate, "Name",
                                member.Name + "." + m.Name + ".apply");
                            callMethodTemplate = TemplateUtils.ReplaceTemplateVariable(callMethodTemplate, "Arguments",
                                TemplateUtils.CallParametersString(pseudoParamsOwner));
                            callMethodTemplate += ";";

                            List<MemberModel> arrayParamsList = new List<MemberModel>();
                            for (int i = 0; i < m.Parameters.Count - 1; i++)
                            {
                                MemberModel param = m.Parameters[i];
                                arrayParamsList.Add(param);
                            }

                            pseudoParamsOwner.Parameters = arrayParamsList;

                            callMethodTemplate = TemplateUtils.ReplaceTemplateVariable(callMethodTemplate, "Subarguments",
                                TemplateUtils.CallParametersString(pseudoParamsOwner));

                            callMethodTemplate = TemplateUtils.ReplaceTemplateVariable(callMethodTemplate, "Lastsubargument", 
                                m.Parameters[m.Parameters.Count - 1].Name.TrimStart(new char[] { '.', ' '}));
                        }

                        methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Body", callMethodTemplate);
                    }
                    methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "BlankLine", NewLine);
                    result += methodTemplate;

                    if (m.Parameters != null)
                    {
                        for (int i = 0; i < m.Parameters.Count; i++)
                        {
                            MemberModel param = m.Parameters[i];
                            if (param.Type != null)
                            {
                                type = ASContext.Context.ResolveType(param.Type, selectedMembers[m].InFile);
                                importsList.Add(type.QualifiedName);
                            }
                        }
                    }

                    if (position < 0)
                    {
                        MemberModel latest = GetLatestMemberForFunction(inClass, mCopy.Access, mCopy);
                        if (latest == null)
                        {
                            position = Sci.WordStartPosition(Sci.CurrentPos, true);
                            Sci.SetSel(position, Sci.WordEndPosition(position, true));
                        }
                        else
                        {
                            position = Sci.PositionFromLine(latest.LineTo + 1) - ((Sci.EOLMode == 0) ? 2 : 1);
                            Sci.SetSel(position, position);
                        }
                    }
                    else
                    {
                        position = Sci.CurrentPos;
                    }

                    if (m.Type != null)
                    {
                        type = ASContext.Context.ResolveType(m.Type, selectedMembers[m].InFile);
                        importsList.Add(type.QualifiedName);
                    }
                }

                if (importsList.Count > 0 && position > -1)
                {
                    int o = AddImportsByName(importsList, Sci.LineFromPosition(position));
                    position += o;
                    Sci.SetSel(position, position);
                }

                InsertCode(position, result);
            }
            finally { Sci.EndUndoAction(); }
        }
        public static bool RenameMember(ScintillaNet.ScintillaControl Sci, MemberModel member, string newName)
        {
            ContextFeatures features = ASContext.Context.Features;
            string kind = features.varKey;

            if ((member.Flags & FlagType.Getter) > 0)
                kind = features.getKey;
            else if ((member.Flags & FlagType.Setter) > 0)
                kind = features.setKey;
            else if (member.Flags == FlagType.Function)
                kind = features.functionKey;

            Regex reMember = new Regex(String.Format(@"{0}\s+({1})[\s:]", kind, member.Name));

            string line;
            Match m;
            int index, position;
            for (int i = member.LineFrom; i <= member.LineTo; i++)
            {
                line = Sci.GetLine(i);
                m = reMember.Match(line);
                if (m.Success)
                {
                    index = Sci.MBSafeTextLength(line.Substring(0, m.Groups[1].Index));
                    position = Sci.PositionFromLine(i) + index;
                    Sci.SetSel(position, position + member.Name.Length);
                    Sci.ReplaceSel(newName);
                    UpdateLookupPosition(position, 1);
                    return true;
                }
            }
            return false;
        }
 private static bool RemoveOneLocalDeclaration(ScintillaNet.ScintillaControl Sci, MemberModel contextMember)
 {
     string type = "";
     if (contextMember.Type != null && (contextMember.Flags & FlagType.Inferred) == 0)
     {
         type = FormatType(contextMember.Type);
         if (type.IndexOf('*') > 0)
             type = type.Replace("/*", @"/\*\s*").Replace("*/", @"\s*\*/");
         type = @":\s*" + type;
     }
     Regex reDecl = new Regex(String.Format(@"[\s\(]((var|const)\s+{0}\s*{1})\s*", contextMember.Name, type));
     for (int i = contextMember.LineFrom; i <= contextMember.LineTo + 10; i++)
     {
         string text = Sci.GetLine(i);
         Match m = reDecl.Match(text);
         if (m.Success)
         {
             int index = Sci.MBSafeTextLength(text.Substring(0, m.Groups[1].Index));
             int position = Sci.PositionFromLine(i) + index;
             int len = Sci.MBSafeTextLength(m.Groups[1].Value);
             Sci.SetSel(position, position + len);
             if (contextMember.Type == null || (contextMember.Flags & FlagType.Inferred) != 0) Sci.ReplaceSel(contextMember.Name + " ");
             else Sci.ReplaceSel(contextMember.Name);
             UpdateLookupPosition(position, contextMember.Name.Length - len);
             return true;
         }
     }
     return false;
 }
        public static void GenerateExtractVariable(ScintillaNet.ScintillaControl Sci, string NewName)
        {
            FileModel cFile;
            IASContext context = ASContext.Context;
            Int32 pos = Sci.CurrentPos;

            string expression = Sci.SelText.Trim(new char[] { '=', ' ', '\t', '\n', '\r', ';', '.' });
            expression = expression.TrimEnd(new char[] { '(', '[', '{', '<' });
            expression = expression.TrimStart(new char[] { ')', ']', '}', '>' });

            cFile = ASContext.Context.CurrentModel;
            ASFileParser parser = new ASFileParser();
            parser.ParseSrc(cFile, Sci.Text);

            MemberModel current = cFile.Context.CurrentMember;

            string characterClass = ScintillaNet.ScintillaControl.Configuration.GetLanguage(Sci.ConfigurationLanguage).characterclass.Characters;

            int funcBodyStart = ASGenerator.GetBodyStart(current.LineFrom, current.LineTo, Sci);
            Sci.SetSel(funcBodyStart, Sci.LineEndPosition(current.LineTo));
            string currentMethodBody = Sci.SelText;

            bool isExprInSingleQuotes = (expression.StartsWith("'") && expression.EndsWith("'"));
            bool isExprInDoubleQuotes = (expression.StartsWith("\"") && expression.EndsWith("\""));
            int stylemask = (1 << Sci.StyleBits) - 1;
            int lastPos = -1;
            char prevOrNextChar;
            Sci.Colourise(0, -1);
            while (true)
            {
                lastPos = currentMethodBody.IndexOf(expression, lastPos + 1);
                if (lastPos > -1)
                {
                    if (lastPos > 0)
                    {
                        prevOrNextChar = currentMethodBody[lastPos - 1];
                        if (characterClass.IndexOf(prevOrNextChar) > -1)
                        {
                            continue;
                        }
                    }
                    if (lastPos + expression.Length < currentMethodBody.Length)
                    {
                        prevOrNextChar = currentMethodBody[lastPos + expression.Length];
                        if (characterClass.IndexOf(prevOrNextChar) > -1)
                        {
                            continue;
                        }
                    }

                    int style = Sci.StyleAt(funcBodyStart + lastPos) & stylemask;
                    if (ASComplete.IsCommentStyle(style))
                    {
                        continue;
                    }
                    else if ((isExprInDoubleQuotes && currentMethodBody[lastPos] == '"' && currentMethodBody[lastPos + expression.Length - 1] == '"')
                        || (isExprInSingleQuotes && currentMethodBody[lastPos] == '\'' && currentMethodBody[lastPos + expression.Length - 1] == '\''))
                    {

                    }
                    else if (!ASComplete.IsTextStyle(style))
                    {
                        continue;
                    }

                    Sci.SetSel(funcBodyStart + lastPos, funcBodyStart + lastPos + expression.Length);
                    Sci.ReplaceSel(NewName);
                    currentMethodBody = currentMethodBody.Substring(0, lastPos) + NewName + currentMethodBody.Substring(lastPos + expression.Length);
                    lastPos += NewName.Length;
                }
                else
                {
                    break;
                }
            }

            Sci.CurrentPos = funcBodyStart;
            Sci.SetSel(Sci.CurrentPos, Sci.CurrentPos);

            MemberModel m = new MemberModel(NewName, "", FlagType.LocalVar, 0);
            m.Value = expression;

            string snippet = TemplateUtils.GetTemplate("Variable");
            snippet = TemplateUtils.ReplaceTemplateVariable(snippet, "Modifiers", null);
            snippet = TemplateUtils.ToDeclarationString(m, snippet);
            snippet += NewLine + "$(Boundary)";
            SnippetHelper.InsertSnippetText(Sci, Sci.CurrentPos, snippet);
        }
        private static void GenerateVariableJob(GeneratorJobType job, ScintillaNet.ScintillaControl Sci, MemberModel member,
            bool detach, ClassModel inClass)
        {
            int position = 0;
            MemberModel latest = null;
            bool isOtherClass = false;

            Visibility varVisi = job.Equals(GeneratorJobType.Variable) ? GetDefaultVisibility() : Visibility.Public;
            FlagType ft = job.Equals(GeneratorJobType.Constant) ? FlagType.Constant : FlagType.Variable;

            // evaluate, if the variable (or constant) should be generated in other class
            ASResult varResult = ASComplete.GetExpressionType(Sci, Sci.WordEndPosition(Sci.CurrentPos, true));

            int contextOwnerPos = GetContextOwnerEndPos(Sci, Sci.WordStartPosition(Sci.CurrentPos, true));
            MemberModel isStatic = new MemberModel();
            if (contextOwnerPos != -1)
            {
                ASResult contextOwnerResult = ASComplete.GetExpressionType(Sci, contextOwnerPos);
                if (contextOwnerResult != null)
                {
                    if (contextOwnerResult.Member == null && contextOwnerResult.Type != null)
                    {
                        isStatic.Flags |= FlagType.Static;
                    }
                }
            }
            else if (member != null && (member.Flags & FlagType.Static) > 0)
            {
                isStatic.Flags |= FlagType.Static;
            }

            ASResult returnType = null;
            int lineNum = Sci.CurrentLine;
            string line = Sci.GetLine(lineNum);
            
            Match m = Regex.Match(line, "\\b" + Regex.Escape(contextToken) + "\\(");
            if (m.Success)
            {
                returnType = new ASResult();
                returnType.Type = ASContext.Context.ResolveType("Function", null);
            }
            else
            {
                m = Regex.Match(line, @"=\s*[^;\n\r}}]+");
                if (m.Success)
                {
                    int posLineStart = Sci.PositionFromLine(lineNum);
                    if (posLineStart + m.Index >= Sci.CurrentPos)
                    {
                        line = line.Substring(m.Index);
                        StatementReturnType rType = GetStatementReturnType(Sci, inClass, line, posLineStart + m.Index);
                        if (rType != null)
                        {
                            returnType = rType.resolve;
                        }
                    }
                }
            }

            if (varResult.RelClass != null && !varResult.RelClass.IsVoid() && !varResult.RelClass.Equals(inClass))
            {
                AddLookupPosition();
                lookupPosition = -1;

                ASContext.MainForm.OpenEditableDocument(varResult.RelClass.InFile.FileName, false);
                Sci = ASContext.CurSciControl;
                isOtherClass = true;

                FileModel fileModel = new FileModel();
                fileModel.Context = ASContext.Context;
                ASFileParser parser = new ASFileParser();
                parser.ParseSrc(fileModel, Sci.Text);

                foreach (ClassModel cm in fileModel.Classes)
                {
                    if (cm.QualifiedName.Equals(varResult.RelClass.QualifiedName))
                    {
                        varResult.RelClass = cm;
                        break;
                    }
                }
                inClass = varResult.RelClass;

                ASContext.Context.UpdateContext(inClass.LineFrom);
            }

            latest = GetLatestMemberForVariable(job, inClass, varVisi, isStatic);
            
            // if we generate variable in current class..
            if (!isOtherClass && member == null)
            {
                detach = false;
                lookupPosition = -1;
                position = Sci.WordStartPosition(Sci.CurrentPos, true);
                Sci.SetSel(position, Sci.WordEndPosition(position, true));
            }
            else // if we generate variable in another class
            {
                if (latest != null)
                {
                    position = FindNewVarPosition(Sci, inClass, latest);
                }
                else
                {
                    position = GetBodyStart(inClass.LineFrom, inClass.LineTo, Sci);
                    detach = false;
                }
                if (position <= 0) return;
                Sci.SetSel(position, position);
            }

            // if this is a constant, we assign a value to constant
            string returnTypeStr = null;
            string eventValue = null;
            if (job == GeneratorJobType.Constant && returnType == null)
            {
                isStatic.Flags |= FlagType.Static;
                eventValue = "String = \"" + Camelize(contextToken) + "\"";
            }
            else if (returnType != null)
            {
                ClassModel inClassForImport = null;
                if (returnType.InClass != null)
                {
                    inClassForImport = returnType.InClass;
                }
                else if (returnType.RelClass != null)
                {
                    inClassForImport = returnType.RelClass;
                }
                else
                {
                    inClassForImport = inClass;
                }
                List<String> imports = new List<string>();
                if (returnType.Member != null)
                {
                    if (returnType.Member.Type != ASContext.Context.Features.voidKey)
                    {
                        returnTypeStr = FormatType(GetShortType(returnType.Member.Type));
                        imports.Add(getQualifiedType(returnType.Member.Type, inClassForImport));
                    }
                }
                else if (returnType != null && returnType.Type != null)
                {
                    returnTypeStr = FormatType(GetShortType(returnType.Type.QualifiedName));
                    imports.Add(getQualifiedType(returnType.Type.QualifiedName, inClassForImport));
                }
                if (imports.Count > 0)
                {
                    position += AddImportsByName(imports, Sci.LineFromPosition(position));
                    Sci.SetSel(position, position);
                }
            }
            MemberModel newMember = NewMember(contextToken, isStatic, ft, varVisi);
            if (returnTypeStr != null)
            {
                newMember.Type = returnTypeStr;
            }
            else if (eventValue != null)
            {
                newMember.Type = eventValue;
            }
            GenerateVariable(newMember, position, detach);
        }
        private static void GenerateFieldFromParameter(ScintillaNet.ScintillaControl Sci, MemberModel member, ClassModel inClass,
                    Visibility scope)
        {
            int funcBodyStart = GetBodyStart(member.LineFrom, member.LineTo, Sci);

            Sci.SetSel(funcBodyStart, Sci.LineEndPosition(member.LineTo));
            string body = Sci.SelText;
            string trimmed = body.TrimStart();

            Regex re = new Regex("^super\\s*[\\(|\\.]");
            Match m = re.Match(trimmed);
            if (m.Success)
            {
                if (m.Index == 0)
                {
                    int p = funcBodyStart + (body.Length - trimmed.Length);
                    int l = Sci.LineFromPosition(p);
                    p = Sci.PositionFromLine(l + 1);
                    funcBodyStart = GetBodyStart(member.LineFrom, member.LineTo, Sci, p);
                }
            }

            Sci.SetSel(funcBodyStart, funcBodyStart);
            Sci.CurrentPos = funcBodyStart;

            bool isVararg = false;
            string paramName = contextMember.Name;
            if (paramName.StartsWith("..."))
            {
                paramName = paramName.TrimStart(new char[] { ' ', '.' });
                isVararg = true;
            }
            string varName = paramName;
            string scopedVarName = varName;

            if ((scope & Visibility.Public) > 0)
            {
                if ((member.Flags & FlagType.Static) > 0)
                    scopedVarName = inClass.Name + "." + varName;
                else
                    scopedVarName = "this." + varName;
            }
            else
            {
                if (ASContext.CommonSettings.PrefixFields.Length > 0 && !paramName.StartsWith(ASContext.CommonSettings.PrefixFields))
                {
                    scopedVarName = varName = ASContext.CommonSettings.PrefixFields + varName;
                }

                if (ASContext.CommonSettings.GenerateScope || ASContext.CommonSettings.PrefixFields == "")
                {
                    if ((member.Flags & FlagType.Static) > 0)
                        scopedVarName = inClass.Name + "." + varName;
                    else
                        scopedVarName = "this." + varName;
                }
            }

            

            string template = TemplateUtils.GetTemplate("FieldFromParameter");
            template = TemplateUtils.ReplaceTemplateVariable(template, "Name", scopedVarName);
            template = TemplateUtils.ReplaceTemplateVariable(template, "Value", paramName);
            template += "\n$(Boundary)";

            SnippetHelper.InsertSnippetText(Sci, funcBodyStart, template);

            MemberList classMembers = inClass.Members;
            foreach (MemberModel classMember in classMembers)
                if (classMember.Name.Equals(varName))
                    return;

            MemberModel latest = GetLatestMemberForVariable(GeneratorJobType.Variable, inClass, GetDefaultVisibility(), new MemberModel());
            if (latest == null) return;

            int position = FindNewVarPosition(Sci, inClass, latest);
            if (position <= 0) return;
            Sci.SetSel(position, position);
            Sci.CurrentPos = position;

            MemberModel mem = NewMember(varName, member, FlagType.Variable, scope);
            if (isVararg) mem.Type = "Array";
            else mem.Type = contextMember.Type;

            GenerateVariable(mem, position, true);
            ASContext.Panel.RestoreLastLookupPosition();
        }
Exemple #9
0
        public static void GenerateDelegateMethods(ScintillaNet.ScintillaControl Sci, MemberModel member,
            Dictionary<MemberModel, ClassModel> selectedMembers, ClassModel classModel, ClassModel inClass)
        {
            Sci.BeginUndoAction();
            try
            {
                StringBuilder sb = new StringBuilder(
                    String.Format(GetTemplate("DelegateMethodsHeader", "$(Boundary)\n\n/* DELEGATE {0} */"), classModel.Type));

                MemberModel latest;
                int position = -1;
                List<MemberModel> methodParams;
                ClassModel type;
                List<string> importsList = new List<string>();

                bool isStaticMember = false;
                if ((member.Flags & FlagType.Static) > 0)
                {
                    isStaticMember = true;
                }

                inClass.ResolveExtends();
                
                Dictionary<MemberModel, ClassModel>.KeyCollection selectedMemberKeys = selectedMembers.Keys;
                foreach (MemberModel m in selectedMemberKeys)
                {
                    sb.Append("$(Boundary)\n\n");

                    bool overrideFound = false;
                    ClassModel aType = inClass;
                    while (aType != null && !aType.IsVoid())
                    {
                        MemberList inClassMembers = aType.Members;
                        foreach (MemberModel inClassMember in inClassMembers)
                        {
                            if ((inClassMember.Flags & FlagType.Function) > 0
                               && m.Name.Equals(inClassMember.Name))
                            {
                                sb.Append("override ");
                                overrideFound = true;
                                break;
                            }
                        }
                        if (overrideFound)
                        {
                            break;
                        }
                        aType = aType.Extends;
                    }
                        
                    
                    if (isStaticMember)
                    {
                        sb.Append("static ");
                    }

                    sb.Append(GetDeclaration(m))
                        .Append(" $(CSLB){\n\t");

                    if (m.Type != null && m.Type.ToLower() != "void")
                    {
                        sb.Append("return ");
                    }


                    methodParams = m.Parameters;

                    // check for varargs
                    bool isVararg = false;
                    if (methodParams != null && methodParams.Count > 0)
                    {
                        MemberModel mm = methodParams[methodParams.Count - 1];
                        if (mm.Name.StartsWith("..."))
                        {
                            isVararg = true;
                        }
                    }
                    if (!isVararg)
                    {
                        sb.Append(member.Name)
                            .Append(".")
                            .Append(m.Name)
                            .Append("(");

                        if (methodParams != null)
                        {
                            for (int i = 0; i < methodParams.Count; i++)
                            {
                                MemberModel param = methodParams[i];
                                sb.Append(param.Name);
                                if (i + 1 < methodParams.Count)
                                {
                                    sb.Append(", ");
                                }
                            }
                        }

                        sb.Append(");");
                    }
                    else 
                    {
                        sb.Append(member.Name)
                            .Append(".")
                            .Append(m.Name)
                            .Append(".apply(null, [");

                        for (int i = 0; i < methodParams.Count; i++)
                        {
                            MemberModel param = methodParams[i];
                            if (i + 1 < methodParams.Count)
                            {
                                sb.Append(param.Name);
                                if (i + 2 < methodParams.Count)
                                {
                                    sb.Append(", ");
                                }
                            }
                            else
                            {
                                sb.Append("].concat(")
                                    .Append(param.Name.Substring(3))
                                    .Append(")");
                            }
                        }

                        sb.Append(");");
                    }

                    sb.Append("\n}");

                    if (methodParams != null)
                    {
                        for (int i = 0; i < methodParams.Count; i++)
                        {
                            MemberModel param = methodParams[i];
                            if (param.Type != null)
                            {
                                type = ASContext.Context.ResolveType(param.Type, selectedMembers[m].InFile);
                                importsList.Add(type.QualifiedName);
                            }
                        }
                    }

                    if (position < 0)
                    {
                        latest = FindLatest(FlagType.Function, inClass);
                        if (latest == null)
                        {
                            position = Sci.WordStartPosition(Sci.CurrentPos, true);
                            Sci.SetSel(position, Sci.WordEndPosition(position, true));
                        }
                        else
                        {
                            position = Sci.PositionFromLine(latest.LineTo + 1) - ((Sci.EOLMode == 0) ? 2 : 1);
                            Sci.SetSel(position, position);
                        }
                    }
                    else
                    {
                        position = Sci.CurrentPos;
                    }

                    if (m.Type != null)
                    {
                        type = ASContext.Context.ResolveType(m.Type, selectedMembers[m].InFile);
                        importsList.Add(type.QualifiedName);
                    }
                }

                if (importsList.Count > 0 && position > -1)
                {
                    int o = AddImportsByName(importsList, Sci.LineFromPosition(position));
                    position += o;
                    Sci.SetSel(position, position);
                }

                InsertCode(position, sb.ToString());
            }
            finally { Sci.EndUndoAction(); }
        }
Exemple #10
0
        static public void GenerateOverride(ScintillaNet.ScintillaControl Sci, ClassModel ofClass, MemberModel member, int position)
        {
            ContextFeatures features = ASContext.Context.Features;
            List<string> typesUsed = new List<string>();
            bool isProxy = (member.Namespace == "flash_proxy");
            if (isProxy) typesUsed.Add("flash.utils.flash_proxy");
            bool isAS2Event = ASContext.Context.Settings.LanguageId == "AS2" && member.Name.StartsWith("on");
            bool isObjectMethod = ofClass.QualifiedName == "Object";

            int line = Sci.LineFromPosition(position);
            string currentText = Sci.GetLine(line);
            int startPos = currentText.Length;
            GetStartPos(currentText, ref startPos, features.privateKey);
            GetStartPos(currentText, ref startPos, features.protectedKey);
            GetStartPos(currentText, ref startPos, features.internalKey);
            GetStartPos(currentText, ref startPos, features.publicKey);
            GetStartPos(currentText, ref startPos, features.staticKey);
            GetStartPos(currentText, ref startPos, features.overrideKey);
            startPos += Sci.PositionFromLine(line);

            FlagType flags = member.Flags;
            string acc = "";
            string decl = "";
            if (features.hasNamespaces && member.Namespace != null
                && member.Namespace.Length > 0 && member.Namespace != "internal")
                acc = member.Namespace;
            else if ((member.Access & Visibility.Public) > 0) acc = features.publicKey;
            else if ((member.Access & Visibility.Internal) > 0) acc = features.internalKey;
            else if ((member.Access & Visibility.Protected) > 0) acc = features.protectedKey;
            else if ((member.Access & Visibility.Private) > 0) acc = features.privateKey;

            bool isStatic = (flags & FlagType.Static) > 0;
            if (isStatic) acc = features.staticKey + " " + acc;

            if (!isAS2Event && !isObjectMethod)
                acc = features.overrideKey + " " + acc;

            if ((flags & (FlagType.Getter | FlagType.Setter)) > 0)
            {
                string type = member.Type;
                string name = member.Name;
                if (member.Parameters != null && member.Parameters.Count > 0)
                    type = member.Parameters[0].Type;
                type = FormatType(type);
                if (type == null)
                {
                    string message = String.Format(TextHelper.GetString("Info.TypeDeclMissing"), member.Name);
                    ErrorManager.ShowInfo(message);
                    return;
                }

                if (ofClass.Members.Search(name, FlagType.Getter, 0) != null)
                {
                    decl += String.Format(GetTemplate("Getter"),
                        acc, name, type, "super." + name);
                }
                if (ofClass.Members.Search(name, FlagType.Setter, 0) != null)
                {
                    string tpl = GetTemplate("Setter");
                    if (decl.Length > 0)
                    {
                        decl += "\n\n";
                        tpl = tpl.Replace("$(EntryPoint)", "");
                    }
                    decl += String.Format(tpl,
                        acc, name, type, "super." + name, ASContext.Context.Features.voidKey ?? "void");
                }
            }
            else
            {
                string type = FormatType(member.Type);
                if (type == null)
                {
                    string message = String.Format(TextHelper.GetString("Info.TypeDeclMissing"), member.Name);
                    ErrorManager.ShowInfo(message);
                    return;
                }
                if (acc.Length > 0) acc += " ";
                decl = acc + features.functionKey + " ";
                bool noRet = type.Equals("void", StringComparison.OrdinalIgnoreCase);
                type = (noRet) ? ASContext.Context.Features.voidKey : type;
                if (!noRet) typesUsed.Add(getQualifiedType(type, ofClass));
                string action = (isProxy || isAS2Event) ? "" : GetSuperCall(member, typesUsed, ofClass);
                decl += member.Name
                    + String.Format(GetTemplate("MethodOverride"), member.ParametersString(true), type, action);
            }

            Sci.BeginUndoAction();
            try
            {
                if (ASContext.Context.Settings.GenerateImports && typesUsed.Count > 0)
                {
                    int offset = AddImportsByName(typesUsed, line);
                    position += offset;
                    startPos += offset;
                }

                Sci.SetSel(startPos, position + member.Name.Length);
                InsertCode(startPos, decl);
            }
            finally { Sci.EndUndoAction(); }
        }
Exemple #11
0
        private static void GenerateFieldFromParameter(ScintillaNet.ScintillaControl Sci, MemberModel member, ClassModel inClass)
        {
            int funcBodyStart = GetBodyStart(member.LineFrom, member.LineTo, Sci);

            Sci.SetSel(funcBodyStart, Sci.LineEndPosition(member.LineTo));
            string body = Sci.SelText;
            string trimmed = body.TrimStart();

            Regex re = new Regex("^super\\s*[\\(|\\.]");
            Match m = re.Match(trimmed);
            if (m.Success)
            {
                if (m.Index == 0)
                {
                    int p = funcBodyStart + (body.Length - trimmed.Length);
                    int l = Sci.LineFromPosition(p);
                    p = Sci.PositionFromLine(l + 1);
                    funcBodyStart = GetBodyStart(member.LineFrom, member.LineTo, Sci, p);
                }
            }

            Sci.SetSel(funcBodyStart, funcBodyStart);
            Sci.CurrentPos = funcBodyStart;

            bool isVararg = false;
            string paramName = contextMember.Name;
            if (paramName.StartsWith("..."))
            {
                paramName = paramName.TrimStart(new char[] { ' ', '.' });
                isVararg = true;
            }
            string varName = paramName;

            bool addThis = true;
            if (ASContext.CommonSettings.PrefixFields.Length > 0 && !paramName.StartsWith(ASContext.CommonSettings.PrefixFields))
            {
                varName = ASContext.CommonSettings.PrefixFields + varName;
                addThis = ASContext.CommonSettings.GenerateScope;
            }

            StringBuilder sb = new StringBuilder();
            if (addThis) sb.Append("this.");
            sb.Append(varName)
                .Append(" = ")
                .Append(paramName)
                .Append(";")
                .Append(NewLine)
                .Append("$(Boundary)");

            SnippetHelper.InsertSnippetText(Sci, funcBodyStart, sb.ToString());


            MemberList classMembers = inClass.Members;
            foreach (MemberModel classMember in classMembers)
            {
                if (classMember.Name.Equals(varName))
                {
                    return;
                }
            }

            MemberModel latest = FindLatest(FlagType.Variable | FlagType.Constant, GetDefaultVisibility(), inClass);
            if (latest == null) return;

            int position = FindNewVarPosition(Sci, inClass, latest);
            if (position <= 0) return;
            Sci.SetSel(position, position);
            Sci.CurrentPos = position;

            MemberModel mem = NewMember(varName, member, FlagType.Variable, GetDefaultVisibility());
            if (isVararg)
            {
                mem.Type = "Array";
            }
            else
            {
                mem.Type = contextMember.Type;
            }

            GenerateVariable(mem, position, true);
            ASContext.Panel.RestoreLastLookupPosition();
        }
Exemple #12
0
        private static void AddInterfaceDefJob(ClassModel inClass, ScintillaNet.ScintillaControl Sci, MemberModel member)
        {
            ClassModel aType = ASContext.Context.ResolveType(contextParam, ASContext.Context.CurrentModel);
            if (aType.IsVoid()) return;

            FileModel fileModel = ASFileParser.ParseFile(aType.InFile.FileName, ASContext.Context);
            foreach (ClassModel cm in fileModel.Classes)
            {
                if (cm.QualifiedName.Equals(aType.QualifiedName))
                {
                    aType = cm;
                    break;
                }
            }

            StringBuilder snippet = new StringBuilder();


            DockContent dc = ASContext.MainForm.OpenEditableDocument(aType.InFile.FileName, true);
            Sci = ASContext.CurSciControl;

            MemberModel latest = FindLatest(FlagType.Function, aType);
            int position;
            if (latest == null)
            {
                position = GetBodyStart(aType.LineFrom, aType.LineTo, Sci);
            }
            else
            {
                position = Sci.PositionFromLine(latest.LineTo + 1) - ((Sci.EOLMode == 0) ? 1 : 0);
                snippet.Append(NewLine);
            }
            Sci.SetSel(position, position);
            Sci.CurrentPos = position;

            List<MemberModel> parms = member.Parameters;
            snippet.Append("function ")
                .Append(member.ToDeclarationString())
                .Append(";");

            List<string> importsList = new List<string>();
            string t;
            if (parms != null && parms.Count > 0)
            {
                for (int i = 0; i < parms.Count; i++)
                {
                    if (parms[i].Type != null)
                    {
                        t = getQualifiedType(parms[i].Type, inClass); 
                        importsList.Add(t);
                    }
                }
            }

            if (member.Type != null)
            {
                t = getQualifiedType(member.Type, inClass);
                importsList.Add(t);
            }

            if (importsList.Count > 0)
            {
                int o = AddImportsByName(importsList, Sci.LineFromPosition(position));
                position += o;
                Sci.SetSel(position, position);
            }

            InsertCode(position, snippet.ToString());

            Sci.CurrentPos = position;
        }
Exemple #13
0
        private static void AddAsParameter(ClassModel inClass, ScintillaNet.ScintillaControl Sci, MemberModel member, bool detach)
        {
            if (!RemoveLocalDeclaration(Sci, contextMember)) return;

            StringBuilder sb = new StringBuilder();

            int position = Sci.PositionFromLine(member.LineFrom);
            Sci.SetSel(position, Sci.LineEndPosition(member.LineTo));

            string body = Sci.SelText;
            int bracePos = body.IndexOf(')') + position;
            
            if (member.Parameters != null && member.Parameters.Count > 0)
            {
                sb.Append(", ");
            }

            sb.Append(contextMember.Name);

            if (contextMember.Type != null)
            {
                sb.Append(":")
                    .Append(contextMember.Type);
            }

            Sci.SetSel(bracePos, bracePos);
            Sci.CurrentPos = bracePos;
            InsertCode(bracePos, sb.ToString());

            Sci.SetSel(lookupPosition, lookupPosition);
        }
Exemple #14
0
        private static void ChangeMethodDecl(ScintillaNet.ScintillaControl Sci, MemberModel member, ClassModel inClass)
        {
            int wordPos = Sci.WordEndPosition(Sci.CurrentPos, true);
            List<FunctionParameter> functionParameters = ParseFunctionParameters(Sci, wordPos);

            ASResult funcResult = ASComplete.GetExpressionType(Sci, Sci.WordEndPosition(Sci.CurrentPos, true));
            if (funcResult.Member == null)
            {
                return;
            }
            if (funcResult != null && funcResult.inClass != null && !funcResult.inClass.Equals(inClass))
            {
                AddLookupPosition();
                lookupPosition = -1;

                DockContent dc = ASContext.MainForm.OpenEditableDocument(funcResult.inClass.InFile.FileName, true);
                Sci = ASContext.CurSciControl;

                FileModel fileModel = new FileModel();
                ASFileParser parser = new ASFileParser();
                parser.ParseSrc(fileModel, Sci.Text);

                foreach (ClassModel cm in fileModel.Classes)
                {
                    if (cm.QualifiedName.Equals(funcResult.inClass.QualifiedName))
                    {
                        funcResult.inClass = cm;
                        break;
                    }
                }
                inClass = funcResult.inClass;
            }

            MemberList members = inClass.Members;
            foreach (MemberModel m in members)
            {
                if (m.Name == funcResult.Member.Name)
                {
                    funcResult.Member = m;
                }
            }

            bool paramsDiffer = false;
            if (funcResult.Member.Parameters != null)
            {
                // check that parameters have one and the same type
                if (funcResult.Member.Parameters.Count == functionParameters.Count)
                {
                    if (functionParameters.Count > 0)
                    {
                        List<MemberModel> parameters = funcResult.Member.Parameters;
                        for (int i = 0; i < parameters.Count; i++)
                        {
                            MemberModel p = parameters[i];
                            if (p.Type != functionParameters[i].paramType)
                            {
                                paramsDiffer = true;
                                break;
                            }
                        }
                    }
                }
                else
                {
                    paramsDiffer = true;
                }
            }
                // check that parameters count differs
            else if (functionParameters.Count != 0)
            {
                paramsDiffer = true;
            }

            if (paramsDiffer)
            {
                int app = 0;
                List<MemberModel> newParameters = new List<MemberModel>();
                List<MemberModel> existingParameters = funcResult.Member.Parameters;
                for (int i = 0; i < functionParameters.Count; i++)
                {
                    FunctionParameter p = functionParameters[i];
                    if (existingParameters != null
                        && existingParameters.Count > (i - app)
                        && existingParameters[i - app].Type == p.paramType)
                    {
                        newParameters.Add(existingParameters[i - app]);
                    }
                    else
                    {
                        if (existingParameters != null && existingParameters.Count < functionParameters.Count)
                        {
                            app++;
                        }
                        newParameters.Add(new MemberModel(p.param, p.paramType, FlagType.ParameterVar, 0));
                    }
                }
                funcResult.Member.Parameters = newParameters;

                int posStart = Sci.PositionFromLine(funcResult.Member.LineFrom);
                int posEnd = Sci.LineEndPosition(funcResult.Member.LineTo);
                Sci.SetSel(posStart, posEnd);
                string selectedText = Sci.SelText;
                Regex rStart = new Regex(String.Format(@"\s+{0}\s*\(([^\)]*)\)(\s*:\s*([^({{|\n|\r|\s|;)]+))?", funcResult.Member.Name));
                Match mStart = rStart.Match(selectedText);
                if (!mStart.Success)
                {
                    return;
                }

                int start = mStart.Index + posStart;
                int end = start + mStart.Length;

                Sci.SetSel(start, end);

                string decl = funcResult.Member.ToDeclarationString();
                Sci.ReplaceSel(" " + decl);

                // add imports to function argument types
                if (functionParameters.Count > 0)
                {
                    List<string> l = new List<string>();
                    foreach (FunctionParameter fp in functionParameters)
                    {
                        try
                        {
                            l.Add(fp.paramQualType);
                        }
                        catch (Exception)
                        {
                        }
                    }
                    start += AddImportsByName(l, Sci.LineFromPosition(end));
                }

                Sci.SetSel(start, start);
            }
        }
Exemple #15
0
        private static void ConvertToConst(ClassModel inClass, ScintillaNet.ScintillaControl Sci, MemberModel member, bool detach)
        {
            String suggestion = "NEW_CONST";
            String label = TextHelper.GetString("ASCompletion.Label.ConstName");
            String title = TextHelper.GetString("ASCompletion.Title.ConvertToConst");

            Hashtable info = new Hashtable();
            info["suggestion"] = suggestion;
            info["label"] = label;
            info["title"] = title;
            DataEvent de = new DataEvent(EventType.Command, "LineEntryDialog", info);
            EventManager.DispatchEvent(null, de);
            if (!de.Handled)
            {
                return;
            }
            
            suggestion = (string)info["suggestion"];

            int position = Sci.CurrentPos;
            MemberModel latest = null;

            int wordPosEnd = Sci.WordEndPosition(position, true);
            int wordPosStart = Sci.WordStartPosition(position, true);
            char cr = (char)Sci.CharAt(wordPosEnd);
            if (cr == '.')
            {
                wordPosEnd = Sci.WordEndPosition(wordPosEnd + 1, true);
            }
            else
            {
                cr = (char)Sci.CharAt(wordPosStart - 1);
                if (cr == '.')
                {
                    wordPosStart = Sci.WordStartPosition(wordPosStart - 1, true);
                }
            }
            Sci.SetSel(wordPosStart, wordPosEnd);
            string word = Sci.SelText;
            Sci.ReplaceSel(suggestion);
            
            if (member == null)
            {
                detach = false;
                lookupPosition = -1;
                position = Sci.WordStartPosition(Sci.CurrentPos, true);
                Sci.SetSel(position, Sci.WordEndPosition(position, true));
            }
            else
            {
                latest = FindLatest(FlagType.Constant, GetDefaultVisibility(), inClass)
                    ?? FindLatest(FlagType.Variable, GetDefaultVisibility(), inClass);
                if (latest != null)
                {
                    position = FindNewVarPosition(Sci, inClass, latest);
                }
                else
                {
                    position = GetBodyStart(inClass.LineFrom, inClass.LineTo, Sci);
                    detach = false;
                }
                if (position <= 0) return;
                Sci.SetSel(position, position);
            }

            contextToken = suggestion + ":Number = " + word + "";

            GenerateVariable(
                NewMember(contextToken, member, FlagType.Variable | FlagType.Constant | FlagType.Static),
                        position, detach);
        }
Exemple #16
0
        private static void AddAsParameter(ClassModel inClass, ScintillaNet.ScintillaControl Sci, MemberModel member, bool detach)
        {
            if (!RemoveLocalDeclaration(Sci, contextMember)) return;

            int posStart = Sci.PositionFromLine(member.LineFrom);
            int posEnd = Sci.LineEndPosition(member.LineTo);
            Sci.SetSel(posStart, posEnd);
            string selectedText = Sci.SelText;
            Regex rStart = new Regex(@"\s{1}" + member.Name + @"\s*\(([^\)]*)\)(\s*:\s*([^({{|\n|\r|\s|;)]+))?");
            Match mStart = rStart.Match(selectedText);
            if (!mStart.Success)
                return;

            int start = mStart.Index + posStart + 1;
            int end = mStart.Index + posStart + mStart.Length;

            Sci.SetSel(start, end);

            MemberModel memberCopy = (MemberModel) member.Clone();

            if (memberCopy.Parameters == null)
                memberCopy.Parameters = new List<MemberModel>();

            memberCopy.Parameters.Add(contextMember);

            string template = TemplateUtils.ToDeclarationString(memberCopy, TemplateUtils.GetTemplate("MethodDeclaration"));
            InsertCode(start, template);

            int currPos = Sci.LineEndPosition(Sci.CurrentLine);

            Sci.SetSel(currPos, currPos);
            Sci.CurrentPos = currPos;
        }
Exemple #17
0
        private static void AddInterfaceDefJob(ClassModel inClass, ScintillaNet.ScintillaControl Sci, MemberModel member, string interf)
        {
            ClassModel aType = ASContext.Context.ResolveType(interf, ASContext.Context.CurrentModel);
            if (aType.IsVoid()) return;

            FileModel fileModel = ASFileParser.ParseFile(ASContext.Context.CreateFileModel(aType.InFile.FileName));
            foreach (ClassModel cm in fileModel.Classes)
            {
                if (cm.QualifiedName.Equals(aType.QualifiedName))
                {
                    aType = cm;
                    break;
                }
            }

            string template = TemplateUtils.GetTemplate("IFunction");
            if ((member.Flags & FlagType.Getter) > 0)
            {
                template = TemplateUtils.GetTemplate("IGetter");
            }
            else if ((member.Flags & FlagType.Setter) > 0)
            {
                template = TemplateUtils.GetTemplate("ISetter");
            }

            DockContent dc = ASContext.MainForm.OpenEditableDocument(aType.InFile.FileName, true);
            Sci = ASContext.CurSciControl;

            MemberModel latest = GetLatestMemberForFunction(aType, Visibility.Default, new MemberModel());
            int position;
            if (latest == null)
            {
                position = GetBodyStart(aType.LineFrom, aType.LineTo, Sci);
            }
            else
            {
                position = Sci.PositionFromLine(latest.LineTo + 1) - ((Sci.EOLMode == 0) ? 2 : 1);
                template = NewLine + template;
            }
            Sci.SetSel(position, position);
            Sci.CurrentPos = position;

            IASContext context = ASContext.Context;
            ContextFeatures features = context.Features;

            template = TemplateUtils.ToDeclarationString(member, template);
            template = TemplateUtils.ReplaceTemplateVariable(template, "BlankLine", NewLine);
            template = TemplateUtils.ReplaceTemplateVariable(template, "Void", features.voidKey);

            List<string> importsList = new List<string>();
            string t;
            List<MemberModel> parms = member.Parameters;
            if (parms != null && parms.Count > 0)
            {
                for (int i = 0; i < parms.Count; i++)
                {
                    if (parms[i].Type != null)
                    {
                        t = getQualifiedType(parms[i].Type, inClass); 
                        importsList.Add(t);
                    }
                }
            }

            if (member.Type != null)
            {
                t = getQualifiedType(member.Type, inClass);
                importsList.Add(t);
            }

            if (importsList.Count > 0)
            {
                int o = AddImportsByName(importsList, Sci.LineFromPosition(position));
                position += o;
                
            }

            Sci.SetSel(position, position);
            Sci.CurrentPos = position;

            InsertCode(position, template);
        }
Exemple #18
0
        private static void AssignStatementToVar(ClassModel inClass, ScintillaNet.ScintillaControl Sci, MemberModel member)
        {
            int lineNum = Sci.LineFromPosition(Sci.CurrentPos);
            string line = Sci.GetLine(lineNum);
            StatementReturnType returnType = GetStatementReturnType(Sci, inClass, line, Sci.PositionFromLine(lineNum));

            if (returnType == null)
            {
                return;
            }
            
            IASContext cntx = inClass.InFile.Context;
            bool isAs3 = cntx.Settings.LanguageId == "AS3";
            string voidWord = isAs3 ? "void" : "Void";
            string type = null;
            string varname = null;
            string cleanType = null;
            ASResult resolve = returnType.resolve;
            int pos = returnType.position;
            string word = returnType.word;

            if (resolve != null && !resolve.IsNull())
            {
                if (resolve.Member != null && resolve.Member.Type != null)
                {
                    type = resolve.Member.Type;
                }
                else if (resolve.Type != null && resolve.Type.Name != null)
                {
                    type = returnType.resolve.Type.QualifiedName;
                }

                if (resolve.Member != null && resolve.Member.Name != null)
                {
                    varname = GuessVarName(resolve.Member.Name, type);
                }
            }

            if (word != null && Char.IsDigit(word[0]))
            {
                word = null;
            }
            
            if (type == voidWord)
            {
                type = null;
            }
            if (varname == null)
            {
                varname = GuessVarName(word, type);
            }
            if (varname != null && varname == word)
            {
                if (varname.Length == 1)
                {
                    varname = varname + "1";
                }
                else
                {
                    varname = varname[0] + "";
                }
            }

            if (type != null)
            {
                cleanType = FormatType(GetShortType(type));
            }

            StringBuilder sb = new StringBuilder();
            sb.Append("var ");
            if (varname != null)
            {
                sb.Append(varname);
                sb.Append(":");
            }
            if (cleanType != null)
            {
                sb.Append(cleanType);
            }
            else
            {
                sb.Append("$(EntryPoint)");
            }
            sb.Append(" = $(Boundary)");

            int indent = Sci.GetLineIndentation(lineNum);
            pos = Sci.PositionFromLine(lineNum) + indent / Sci.Indent;

            Sci.CurrentPos = pos;
            Sci.SetSel(pos, pos);
            InsertCode(pos, sb.ToString());

            if (type != null)
            {
                ClassModel inClassForImport = null;
                if (resolve.inClass != null)
                {
                    inClassForImport = resolve.inClass;
                }
                else if (resolve.relClass != null)
                {
                    inClassForImport = resolve.relClass;
                }
                else 
                {
                    inClassForImport = inClass;
                }
                List<string> l = new List<string>();
                l.Add(getQualifiedType(type, inClassForImport));
                pos += AddImportsByName(l, Sci.LineFromPosition(pos));
            }
        }
Exemple #19
0
        public static int GetBodyStart(int lineFrom, int lineTo, ScintillaNet.ScintillaControl Sci, int pos)
        {
            int posStart = Sci.PositionFromLine(lineFrom);
            int posEnd = Sci.LineEndPosition(lineTo);

            Sci.SetSel(posStart, posEnd);

            List<char> characterClass = new List<char>(new char[] { ' ', '\r', '\n', '\t' });
            string currentMethodBody = Sci.SelText;
            int nCount = 0;
            int funcBodyStart = pos;
            int extraLine = 0;
            if (pos == -1)
            {
                funcBodyStart = posStart + currentMethodBody.IndexOf('{');
                extraLine = 1;
            }
            while (funcBodyStart <= posEnd)
            {
                char c = (char)Sci.CharAt(++funcBodyStart);
                if (c == '}')
                {
                    int ln = Sci.LineFromPosition(funcBodyStart);
                    int indent = Sci.GetLineIndentation(ln);
                    if (lineFrom == lineTo || lineFrom == ln)
                    {
                        Sci.InsertText(funcBodyStart, Sci.NewLineMarker);
                        Sci.SetLineIndentation(ln + 1, indent);
                        ln++;
                    }
                    Sci.SetLineIndentation(ln, indent + Sci.Indent);
                    Sci.InsertText(funcBodyStart, Sci.NewLineMarker);
                    Sci.SetLineIndentation(ln + 1, indent);
                    Sci.SetLineIndentation(ln, indent + Sci.Indent);
                    funcBodyStart = Sci.LineEndPosition(ln);
                    break;
                }
                else if (!characterClass.Contains(c))
                {
                    break;
                }
                else if (Sci.EOLMode == 1 && c == '\r' && (++nCount) > extraLine)
                {
                    break;
                }
                else if (c == '\n' && (++nCount) > extraLine)
                {
                    if (Sci.EOLMode != 2)
                    {
                        funcBodyStart--;
                    }
                    break;
                }
            }
            return funcBodyStart;
        }
Exemple #20
0
        public override bool OnCompletionInsert(ScintillaNet.ScintillaControl sci, int position, string text, char trigger)
        {
            if (text == "Dictionary")
            {
                string insert = null;
                string line = sci.GetLine(sci.LineFromPosition(position));
                Match m = Regex.Match(line, @"\svar\s+(?<varname>.+)\s*:\s*Dictionary\.<(?<indextype>.+)(?=(>\s*=))");
                if (m.Success)
                {
                    insert = String.Format(".<{0}>", m.Groups["indextype"].Value);
                }
                else
                {
                    m = Regex.Match(line, @"\s*=\s*new");
                    if (m.Success)
                    {
                        ASResult result = ASComplete.GetExpressionType(sci, sci.PositionFromLine(sci.LineFromPosition(position)) + m.Index);
                        if (result != null && !result.IsNull() && result.Member != null && result.Member.Type != null)
                        {
                            m = Regex.Match(result.Member.Type, @"(?<=<).+(?=>)");
                            if (m.Success)
                            {
                                insert = String.Format(".<{0}>", m.Value);
                            }
                        }
                    }
                    if (insert == null)
                    {
                        if (trigger == '.' || trigger == '(') return true;
                        insert = ".<>";
                        sci.InsertText(position + text.Length, insert);
                        sci.CurrentPos = position + text.Length + 2;
                        sci.SetSel(sci.CurrentPos, sci.CurrentPos);
                        ASComplete.HandleAllClassesCompletion(sci, "", false, true);
                        return true;
                    }
                }
                if (insert == null) return false;
                if (trigger == '.')
                {
                    sci.InsertText(position + text.Length, insert.Substring(1));
                    sci.CurrentPos = position + text.Length;
                }
                else
                {
                    sci.InsertText(position + text.Length, insert);
                    sci.CurrentPos = position + text.Length + insert.Length;
                }
                sci.SetSel(sci.CurrentPos, sci.CurrentPos);
                return true;
            }

            return base.OnCompletionInsert(sci, position, text, trigger);
        }
Exemple #21
0
        private static void GenerateFunctionJob(GeneratorJobType job, ScintillaNet.ScintillaControl Sci, MemberModel member,
            bool detach, ClassModel inClass)
        {
            int position = 0;
            MemberModel latest = null;
            bool isOtherClass = false;

            Visibility funcVisi = job.Equals(GeneratorJobType.FunctionPublic) ? Visibility.Public : GetDefaultVisibility();
            int wordPos = Sci.WordEndPosition(Sci.CurrentPos, true);
            List<FunctionParameter> functionParameters = ParseFunctionParameters(Sci, wordPos);

            // evaluate, if the function should be generated in other class
            ASResult funcResult = ASComplete.GetExpressionType(Sci, Sci.WordEndPosition(Sci.CurrentPos, true));

            int contextOwnerPos = GetContextOwnerEndPos(Sci, Sci.WordStartPosition(Sci.CurrentPos, true));
            MemberModel isStatic = new MemberModel();
            if (contextOwnerPos != -1)
            {
                ASResult contextOwnerResult = ASComplete.GetExpressionType(Sci, contextOwnerPos);
                if (contextOwnerResult != null)
                {
                    if (contextOwnerResult.Member == null && contextOwnerResult.Type != null)
                    {
                        isStatic.Flags |= FlagType.Static;
                    }
                }
            }
            else if (member != null && (member.Flags & FlagType.Static) > 0)
            {
                isStatic.Flags |= FlagType.Static;
            }


            if (funcResult.RelClass != null && !funcResult.RelClass.IsVoid() && !funcResult.RelClass.Equals(inClass))
            {
                AddLookupPosition();
                lookupPosition = -1;

                DockContent dc = ASContext.MainForm.OpenEditableDocument(funcResult.RelClass.InFile.FileName, true);
                Sci = ASContext.CurSciControl;
                isOtherClass = true;

                FileModel fileModel = new FileModel();
                fileModel.Context = ASContext.Context;
                ASFileParser parser = new ASFileParser();
                parser.ParseSrc(fileModel, Sci.Text);

                foreach (ClassModel cm in fileModel.Classes)
                {
                    if (cm.QualifiedName.Equals(funcResult.RelClass.QualifiedName))
                    {
                        funcResult.RelClass = cm;
                        break;
                    }
                }
                inClass = funcResult.RelClass;

                ASContext.Context.UpdateContext(inClass.LineFrom);
            }

            string blockTmpl = null;
            if ((isStatic.Flags & FlagType.Static) > 0)
            {
                blockTmpl = TemplateUtils.GetBoundary("StaticMethods");
            }
            else if ((funcVisi & Visibility.Public) > 0)
            {
                blockTmpl = TemplateUtils.GetBoundary("PublicMethods");
            }
            else
            {
                blockTmpl = TemplateUtils.GetBoundary("PrivateMethods");
            }
            latest = TemplateUtils.GetTemplateBlockMember(Sci, blockTmpl);
            if (latest == null || (!isOtherClass && member == null))
            {
                latest = GetLatestMemberForFunction(inClass, funcVisi, isStatic);

                // if we generate function in current class..
                if (!isOtherClass)
                {
                    MethodsGenerationLocations location = ASContext.CommonSettings.MethodsGenerationLocations;
                    if (member == null)
                    {
                        detach = false;
                        lookupPosition = -1;
                        position = Sci.WordStartPosition(Sci.CurrentPos, true);
                        Sci.SetSel(position, Sci.WordEndPosition(position, true));
                    }
                    else if (latest != null && location == MethodsGenerationLocations.AfterSimilarAccessorMethod)
                    {
                        position = Sci.PositionFromLine(latest.LineTo + 1) - ((Sci.EOLMode == 0) ? 2 : 1);
                        Sci.SetSel(position, position);
                    }
                    else
                    {
                        position = Sci.PositionFromLine(member.LineTo + 1) - ((Sci.EOLMode == 0) ? 2 : 1);
                        Sci.SetSel(position, position);
                    }
                }
                else // if we generate function in another class..
                {
                    if (latest != null)
                    {
                        position = Sci.PositionFromLine(latest.LineTo + 1) - ((Sci.EOLMode == 0) ? 2 : 1);
                    }
                    else
                    {
                        position = GetBodyStart(inClass.LineFrom, inClass.LineTo, Sci);
                        detach = false;
                    }
                    Sci.SetSel(position, position);
                }
            }
            else
            {
                position = Sci.PositionFromLine(latest.LineTo + 1) - ((Sci.EOLMode == 0) ? 2 : 1);
                Sci.SetSel(position, position);
            }

            // add imports to function argument types
            if (functionParameters.Count > 0)
            {
                List<string> l = new List<string>();
                foreach (FunctionParameter fp in functionParameters)
                {
                    try
                    {
                        l.Add(fp.paramQualType);
                    }
                    catch (Exception) { }
                }
                int o = AddImportsByName(l, Sci.LineFromPosition(position));
                position += o;
                if (latest == null)
                    Sci.SetSel(position, Sci.WordEndPosition(position, true));
                else
                    Sci.SetSel(position, position);
            }
            
            List<MemberModel> parameters = new List<MemberModel>();
            for (int i = 0; i < functionParameters.Count; i++)
            {
                string name = functionParameters[i].paramName;
                string type = functionParameters[i].paramType;
                parameters.Add(new MemberModel(name, type, FlagType.ParameterVar, 0));
            }
            MemberModel newMember = NewMember(contextToken, isStatic, FlagType.Function, funcVisi);
            newMember.Parameters = parameters;
            GenerateFunction(newMember, position, detach, inClass);
        }
Exemple #22
0
        private static void GenerateProperty(GeneratorJobType job, MemberModel member, ClassModel inClass, ScintillaNet.ScintillaControl Sci)
        {
            MemberModel latest;
            string name = GetPropertyNameFor(member);
            PropertiesGenerationLocations location = ASContext.CommonSettings.PropertiesGenerationLocation;

            latest = TemplateUtils.GetTemplateBlockMember(Sci, TemplateUtils.GetBoundary("AccessorsMethods"));
            if (latest != null)
            {
                location = PropertiesGenerationLocations.AfterLastPropertyDeclaration;
            }
            else
            {
                if (location == PropertiesGenerationLocations.AfterLastPropertyDeclaration)
                {
                    latest = FindLatest(FlagType.Getter | FlagType.Setter, 0, inClass, false, false);
                }
                else latest = member;
            }
            if (latest == null) return;

            Sci.BeginUndoAction();
            try
            {
                if (isHaxe)
                {
                    if (name == null) name = member.Name;
                    string args = "(default, default)";
                    if (job == GeneratorJobType.GetterSetter) args = "(get, set)";
                    else if (job == GeneratorJobType.Getter) args = "(get, null)";
                    else if (job == GeneratorJobType.Setter) args = "(default, set)";
                    MakeHaxeProperty(Sci, member, args);
                }
                else
                {
                    if ((member.Access & Visibility.Public) > 0) // hide member
                    {
                        MakePrivate(Sci, member);
                    }
                    if (name == null) // rename var with starting underscore
                    {
                        name = member.Name;
                        string newName = GetNewPropertyNameFor(member);
                        if (RenameMember(Sci, member, newName)) member.Name = newName;
                    }
                }

                int atLine = latest.LineTo + 1;
                if (location == PropertiesGenerationLocations.BeforeVariableDeclaration)
                    atLine = latest.LineTo;
                int position = Sci.PositionFromLine(atLine) - ((Sci.EOLMode == 0) ? 2 : 1);

                if (job == GeneratorJobType.GetterSetter)
                {
                    Sci.SetSel(position, position);
                    GenerateGetterSetter(name, member, position);
                }
                else
                {
                    if (job != GeneratorJobType.Getter)
                    {
                        Sci.SetSel(position, position);
                        GenerateSetter(name, member, position);
                    }
                    if (job != GeneratorJobType.Setter)
                    {
                        Sci.SetSel(position, position);
                        GenerateGetter(name, member, position);
                    }
                }
            }
            finally
            {
                Sci.EndUndoAction();
            }
        }
Exemple #23
0
        public static void GenerateExtractMethod(ScintillaNet.ScintillaControl Sci, string NewName)
        {
            FileModel cFile;
            IASContext context = ASContext.Context;

            string selection = Sci.SelText;
            if (selection == null || selection.Length == 0)
            {
                return;
            }

            if (selection.TrimStart().Length == 0)
            {
                return;
            }

            Sci.SetSel(Sci.SelectionStart + selection.Length - selection.TrimStart().Length,
                Sci.SelectionEnd);
            Sci.CurrentPos = Sci.SelectionEnd;

            Int32 pos = Sci.CurrentPos;

            int lineStart = Sci.LineFromPosition(Sci.SelectionStart);
            int lineEnd = Sci.LineFromPosition(Sci.SelectionEnd);
            int firstLineIndent = Sci.GetLineIndentation(lineStart);
            int entryPointIndent = Sci.Indent;

            for (int i = lineStart; i <= lineEnd; i++)
            {
                int indent = Sci.GetLineIndentation(i);
                if (i > lineStart)
                {
                    Sci.SetLineIndentation(i, indent - firstLineIndent + entryPointIndent);
                }
            }

            string selText = Sci.SelText;
            string template = TemplateUtils.GetTemplate("CallFunction");
            template = TemplateUtils.ReplaceTemplateVariable(template, "Name", NewName);
            template = TemplateUtils.ReplaceTemplateVariable(template, "Arguments", "");

            ASGenerator.InsertCode(Sci.CurrentPos, template + ";");

            cFile = ASContext.Context.CurrentModel;
            ASFileParser parser = new ASFileParser();
            parser.ParseSrc(cFile, Sci.Text);

            bool isAs3 = cFile.Context.Settings.LanguageId == "AS3";

            FoundDeclaration found = GetDeclarationAtLine(Sci, lineStart);
            if (found == null || found.member == null)
            {
                return;
            }

            lookupPosition = Sci.CurrentPos;
            AddLookupPosition();

            MemberModel latest = TemplateUtils.GetTemplateBlockMember(Sci, TemplateUtils.GetBoundary("PrivateMethods"));

            if (latest == null)
                latest = GetLatestMemberForFunction(found.inClass, ASGenerator.GetDefaultVisibility(), found.member);

            if (latest == null)
                latest = found.member;

            int position = Sci.PositionFromLine(latest.LineTo + 1) - ((Sci.EOLMode == 0) ? 2 : 1);
            Sci.SetSel(position, position);

            FlagType flags = FlagType.Function;
            if ((found.member.Flags & FlagType.Static) > 0)
            {
                flags |= FlagType.Static;
            }

            MemberModel m = new MemberModel(NewName, context.Features.voidKey, flags, ASGenerator.GetDefaultVisibility());

            template = NewLine + TemplateUtils.GetTemplate("Function");
            template = TemplateUtils.ToDeclarationWithModifiersString(m, template);
            template = TemplateUtils.ReplaceTemplateVariable(template, "Body", selText);
            template = TemplateUtils.ReplaceTemplateVariable(template, "BlankLine", NewLine);
            InsertCode(position, template);
        }
Exemple #24
0
        private static void AssignStatementToVar(ClassModel inClass, ScintillaNet.ScintillaControl Sci, MemberModel member)
        {
            int lineNum = Sci.CurrentLine;
            string line = Sci.GetLine(lineNum);
            StatementReturnType returnType = GetStatementReturnType(Sci, inClass, line, Sci.PositionFromLine(lineNum));

            if (returnType == null) return;
            
            string type = null;
            string varname = null;
            ASResult resolve = returnType.resolve;
            string word = returnType.word;

            if (resolve != null && !resolve.IsNull())
            {
                if (resolve.Member != null && resolve.Member.Type != null)
                {
                    type = resolve.Member.Type;
                }
                else if (resolve.Type != null && resolve.Type.Name != null)
                {
                    type = resolve.Type.QualifiedName;
                }

                if (resolve.Member != null && resolve.Member.Name != null)
                {
                    varname = GuessVarName(resolve.Member.Name, type);
                }
            }

            if (!string.IsNullOrEmpty(word) && Char.IsDigit(word[0])) word = null;

            if (!string.IsNullOrEmpty(word) && (string.IsNullOrEmpty(type) || Regex.IsMatch(type, "(<[^]]+>)")))
                word = null;

            if (!string.IsNullOrEmpty(type) && type.Equals("void", StringComparison.OrdinalIgnoreCase))
                type = null;

            if (varname == null) varname = GuessVarName(word, type);

            if (varname != null && varname == word)
                varname = varname.Length == 1 ? varname + "1" : varname[0] + "";

            string cleanType = null;
            if (type != null) cleanType = FormatType(GetShortType(type));
            
            string template = TemplateUtils.GetTemplate("AssignVariable");
            template = TemplateUtils.ReplaceTemplateVariable(template, "Name", varname);
            template = TemplateUtils.ReplaceTemplateVariable(template, "Type", cleanType);

            int indent = Sci.GetLineIndentation(lineNum);
            int pos = Sci.PositionFromLine(lineNum) + indent / Sci.Indent;

            Sci.CurrentPos = pos;
            Sci.SetSel(pos, pos);
            InsertCode(pos, template);

            if (type != null)
            {
                ClassModel inClassForImport = null;
                if (resolve.InClass != null)
                {
                    inClassForImport = resolve.InClass;
                }
                else if (resolve.RelClass != null)
                {
                    inClassForImport = resolve.RelClass;
                }
                else 
                {
                    inClassForImport = inClass;
                }
                List<string> l = new List<string>();
                l.Add(getQualifiedType(type, inClassForImport));
                pos += AddImportsByName(l, Sci.LineFromPosition(pos));
            }
        }
Exemple #25
0
        public static bool MakePrivate(ScintillaNet.ScintillaControl Sci, MemberModel member)
        {
            ContextFeatures features = ASContext.Context.Features;
            string visibility = GetPrivateKeyword();
            if (features.publicKey == null || visibility == null) return false;
            Regex rePublic = new Regex(String.Format(@"\s*({0})\s+", features.publicKey));

            string line;
            Match m;
            int index, position;
            for (int i = member.LineFrom; i <= member.LineTo; i++)
            {
                line = Sci.GetLine(i);
                m = rePublic.Match(line);
                if (m.Success)
                {
                    index = Sci.MBSafeTextLength(line.Substring(0, m.Groups[1].Index));
                    position = Sci.PositionFromLine(i) + index;
                    Sci.SetSel(position, position + features.publicKey.Length);
                    Sci.ReplaceSel(visibility);
                    UpdateLookupPosition(position, features.publicKey.Length - visibility.Length);
                    return true;
                }
            }
            return false;
        }
Exemple #26
0
        private static void EventMetatag(ClassModel inClass, ScintillaNet.ScintillaControl Sci, MemberModel member)
        {
            ASResult resolve = ASComplete.GetExpressionType(Sci, Sci.WordEndPosition(Sci.CurrentPos, true));
            string line = Sci.GetLine(inClass.LineFrom);
            int position = Sci.PositionFromLine(inClass.LineFrom) + (line.Length - line.TrimStart().Length);

            string value = resolve.Member.Value;
            if (value != null)
            {
                if (value.StartsWith("\""))
                {
                    value = value.Trim(new char[] { '"' });
                }
                else if (value.StartsWith("'"))
                {
                    value = value.Trim(new char[] { '\'' });
                }
            }
            else value = resolve.Member.Type;

            if (value == "" || value == null)
                return;

            Regex re1 = new Regex("'(?:[^'\\\\]|(?:\\\\\\\\)|(?:\\\\\\\\)*\\\\.{1})*'");
            Regex re2 = new Regex("\"(?:[^\"\\\\]|(?:\\\\\\\\)|(?:\\\\\\\\)*\\\\.{1})*\"");
            Match m1 = re1.Match(value);
            Match m2 = re2.Match(value);

            if (m1.Success || m2.Success)
            {
                Match m = null;
                if (m1.Success && m2.Success) m = m1.Index > m2.Index ? m2 : m1;
                else if (m1.Success) m = m1;
                else m = m2;
                value = value.Substring(m.Index + 1, m.Length - 2);
            }

            string template = TemplateUtils.GetTemplate("EventMetatag");
            template = TemplateUtils.ReplaceTemplateVariable(template, "Name", value);
            template = TemplateUtils.ReplaceTemplateVariable(template, "Type", contextParam);
            template += "\n$(Boundary)";

            AddLookupPosition();

            Sci.CurrentPos = position;
            Sci.SetSel(position, position);
            InsertCode(position, template);
        }
Exemple #27
0
        static public void GenerateOverride(ScintillaNet.ScintillaControl Sci, ClassModel ofClass, MemberModel member, int position)
        {
            ContextFeatures features = ASContext.Context.Features;
            List<string> typesUsed = new List<string>();
            bool isProxy = (member.Namespace == "flash_proxy");
            if (isProxy) typesUsed.Add("flash.utils.flash_proxy");
            bool isAS2Event = ASContext.Context.Settings.LanguageId == "AS2" && member.Name.StartsWith("on");
            bool isObjectMethod = ofClass.QualifiedName == "Object";

            int line = Sci.LineFromPosition(position);
            string currentText = Sci.GetLine(line);
            int startPos = currentText.Length;
            GetStartPos(currentText, ref startPos, features.privateKey);
            GetStartPos(currentText, ref startPos, features.protectedKey);
            GetStartPos(currentText, ref startPos, features.internalKey);
            GetStartPos(currentText, ref startPos, features.publicKey);
            GetStartPos(currentText, ref startPos, features.staticKey);
            GetStartPos(currentText, ref startPos, features.overrideKey);
            startPos += Sci.PositionFromLine(line);

            FlagType flags = member.Flags;
            string acc = "";
            string decl = "";
            if (features.hasNamespaces && !string.IsNullOrEmpty(member.Namespace) && member.Namespace != "internal")
                acc = member.Namespace;
            else if ((member.Access & Visibility.Public) > 0) acc = features.publicKey;
            else if ((member.Access & Visibility.Internal) > 0) acc = features.internalKey;
            else if ((member.Access & Visibility.Protected) > 0) acc = features.protectedKey;
            else if ((member.Access & Visibility.Private) > 0 && features.methodModifierDefault != Visibility.Private) 
                acc = features.privateKey;

            bool isStatic = (flags & FlagType.Static) > 0;
            if (isStatic) acc = features.staticKey + " " + acc;

            if (!isAS2Event && !isObjectMethod)
                acc = features.overrideKey + " " + acc;

            acc = Regex.Replace(acc, "[ ]+", " ").Trim();

            if ((flags & (FlagType.Getter | FlagType.Setter)) > 0)
            {
                string type = member.Type;
                string name = member.Name;
                if (member.Parameters != null && member.Parameters.Count == 1)
                    type = member.Parameters[0].Type;
                type = FormatType(type);
                if (type == null && !features.hasInference) type = features.objectKey;

                bool genGetter = ofClass.Members.Search(name, FlagType.Getter, 0) != null;
                bool genSetter = ofClass.Members.Search(name, FlagType.Setter, 0) != null;

                if (isHaxe)
                {
                    // property is public but not the methods
                    acc = features.overrideKey;
                }

                if (genGetter)
                {
                    string tpl = TemplateUtils.GetTemplate("OverrideGetter", "Getter");
                    tpl = TemplateUtils.ReplaceTemplateVariable(tpl, "Modifiers", acc);
                    tpl = TemplateUtils.ReplaceTemplateVariable(tpl, "Name", name);
                    tpl = TemplateUtils.ReplaceTemplateVariable(tpl, "Type", type);
                    tpl = TemplateUtils.ReplaceTemplateVariable(tpl, "Member", "super." + name);
                    decl += tpl;
                }
                if (genSetter)
                {
                    string tpl = TemplateUtils.GetTemplate("OverrideSetter", "Setter");
                    tpl = TemplateUtils.ReplaceTemplateVariable(tpl, "Modifiers", acc);
                    tpl = TemplateUtils.ReplaceTemplateVariable(tpl, "Name", name);
                    tpl = TemplateUtils.ReplaceTemplateVariable(tpl, "Type", type);
                    tpl = TemplateUtils.ReplaceTemplateVariable(tpl, "Member", "super." + name);
                    tpl = TemplateUtils.ReplaceTemplateVariable(tpl, "Void", ASContext.Context.Features.voidKey ?? "void");
                    if (decl.Length > 0)
                    {
                        tpl = "\n\n" + tpl.Replace("$(EntryPoint)", "");
                    }
                    decl += tpl;
                }
                decl = TemplateUtils.ReplaceTemplateVariable(decl, "BlankLine", "");
            }
            else
            {
                string type = FormatType(member.Type);
                //if (type == null) type = features.objectKey;
                
                decl = acc + features.functionKey + " ";
                bool noRet = type == null || type.Equals("void", StringComparison.OrdinalIgnoreCase);
                type = (noRet && type != null) ? ASContext.Context.Features.voidKey : type;
                if (!noRet)
                {
                    string qType = getQualifiedType(type, ofClass);
                    typesUsed.Add(qType);
                    if (qType == type)
                    {
                        ClassModel rType = ASContext.Context.ResolveType(type, ofClass.InFile);
                        if (!rType.IsVoid()) type = rType.Name;
                    }
                }

                string action = (isProxy || isAS2Event) ? "" : GetSuperCall(member, typesUsed, ofClass);
                string template = TemplateUtils.GetTemplate("MethodOverride");
                
                // fix parameters if needed
                if (member.Parameters != null)
                    foreach (MemberModel para in member.Parameters)
                       if (para.Type == "any") para.Type = "*";

                template = TemplateUtils.ReplaceTemplateVariable(template, "Modifiers", acc);
                template = TemplateUtils.ReplaceTemplateVariable(template, "Name", member.Name);
                template = TemplateUtils.ReplaceTemplateVariable(template, "Arguments", TemplateUtils.ParametersString(member, true));
                template = TemplateUtils.ReplaceTemplateVariable(template, "Type", type);
                template = TemplateUtils.ReplaceTemplateVariable(template, "Method", action);
                decl = template;
            }

            Sci.BeginUndoAction();
            try
            {
                if (ASContext.Context.Settings.GenerateImports && typesUsed.Count > 0)
                {
                    int offset = AddImportsByName(typesUsed, line);
                    position += offset;
                    startPos += offset;
                }

                Sci.SetSel(startPos, position + member.Name.Length);
                InsertCode(startPos, decl);
            }
            finally { Sci.EndUndoAction(); }
        }
Exemple #28
0
        private static void ConvertToConst(ClassModel inClass, ScintillaNet.ScintillaControl Sci, MemberModel member, bool detach)
        {
            String suggestion = "NEW_CONST";
            String label = TextHelper.GetString("ASCompletion.Label.ConstName");
            String title = TextHelper.GetString("ASCompletion.Title.ConvertToConst");

            Hashtable info = new Hashtable();
            info["suggestion"] = suggestion;
            info["label"] = label;
            info["title"] = title;
            DataEvent de = new DataEvent(EventType.Command, "ProjectManager.LineEntryDialog", info);
            EventManager.DispatchEvent(null, de);
            if (!de.Handled)
                return;
            
            suggestion = (string)info["suggestion"];

            int position = Sci.CurrentPos;
            MemberModel latest = null;

            int wordPosEnd = Sci.WordEndPosition(position, true);
            int wordPosStart = Sci.WordStartPosition(position, true);
            char cr = (char)Sci.CharAt(wordPosEnd);
            if (cr == '.')
            {
                wordPosEnd = Sci.WordEndPosition(wordPosEnd + 1, true);
            }
            else
            {
                cr = (char)Sci.CharAt(wordPosStart - 1);
                if (cr == '.')
                {
                    wordPosStart = Sci.WordStartPosition(wordPosStart - 1, true);
                }
            }
            Sci.SetSel(wordPosStart, wordPosEnd);
            string word = Sci.SelText;
            Sci.ReplaceSel(suggestion);
            
            if (member == null)
            {
                detach = false;
                lookupPosition = -1;
                position = Sci.WordStartPosition(Sci.CurrentPos, true);
                Sci.SetSel(position, Sci.WordEndPosition(position, true));
            }
            else
            {
                latest = GetLatestMemberForVariable(GeneratorJobType.Constant, inClass, 
                    Visibility.Private, new MemberModel("", "", FlagType.Static, 0));
                if (latest != null)
                {
                    position = FindNewVarPosition(Sci, inClass, latest);
                }
                else
                {
                    position = GetBodyStart(inClass.LineFrom, inClass.LineTo, Sci);
                    detach = false;
                }
                if (position <= 0) return;
                Sci.SetSel(position, position);
            }

            MemberModel m = NewMember(suggestion, member, FlagType.Variable | FlagType.Constant | FlagType.Static);
            m.Type = ASContext.Context.Features.numberKey;
            m.Value = word;
            GenerateVariable(m, position, detach);
        }
Exemple #29
0
        private static void GenerateDefaultHandlerName(ScintillaNet.ScintillaControl Sci, int position, int targetPos, string eventName, bool closeBrace)
        {
            string target = null;
            int contextOwnerPos = GetContextOwnerEndPos(Sci, Sci.WordStartPosition(targetPos, true));
            if (contextOwnerPos != -1)
            {
                ASResult contextOwnerResult = ASComplete.GetExpressionType(Sci, contextOwnerPos);
                if (contextOwnerResult != null && !contextOwnerResult.IsNull()
                    && contextOwnerResult.Member != null)
                {
                    if (contextOwnerResult.Member.Name == "contentLoaderInfo" && Sci.CharAt(contextOwnerPos) == '.')
                    {
                        // we want to name the event from the loader var and not from the contentLoaderInfo parameter
                        contextOwnerPos = GetContextOwnerEndPos(Sci, Sci.WordStartPosition(contextOwnerPos - 1, true));
                        if (contextOwnerPos != -1)
                        {
                            contextOwnerResult = ASComplete.GetExpressionType(Sci, contextOwnerPos);
                            if (contextOwnerResult != null && !contextOwnerResult.IsNull()
                                && contextOwnerResult.Member != null)
                            {
                                target = contextOwnerResult.Member.Name;
                            }
                        }
                    }
                    else
                    {
                        target = contextOwnerResult.Member.Name;
                    }
                }
            }
            
            eventName = Camelize(eventName.Substring(eventName.LastIndexOf('.') + 1));
            if (target != null) target = target.TrimStart(new char[] { '_' });

            switch (ASContext.CommonSettings.HandlerNamingConvention)
            {
                case HandlerNamingConventions.handleTargetEventName:
                    if (target == null) contextToken = "handle" + Capitalize(eventName);
                    else contextToken = "handle" + Capitalize(target) + Capitalize(eventName);
                    break;
                case HandlerNamingConventions.onTargetEventName:
                    if (target == null) contextToken = "on" + Capitalize(eventName);
                    else contextToken = "on" + Capitalize(target) + Capitalize(eventName);
                    break;
                case HandlerNamingConventions.target_eventNameHandler:
                    if (target == null) contextToken = eventName + "Handler";
                    else contextToken = target + "_" + eventName + "Handler";
                    break;
                default: //HandlerNamingConventions.target_eventName
                    if (target == null) contextToken = eventName;
                    else contextToken = target + "_" + eventName;
                    break;
            }

            char c = (char)Sci.CharAt(position - 1);
            if (c == ',') InsertCode(position, "$(Boundary) " + contextToken + "$(Boundary)");
            else InsertCode(position, contextToken);

            position = Sci.WordEndPosition(position + 1, true);
            Sci.SetSel(position, position);
            c = (char)Sci.CharAt(position);
            if (c <= 32) if (closeBrace) Sci.ReplaceSel(");"); else Sci.ReplaceSel(";");

            Sci.SetSel(position, position);
        }
Exemple #30
0
        private static void ChangeDecl(ScintillaNet.ScintillaControl Sci, MemberModel memberModel, List<FunctionParameter> functionParameters)
        {
            bool paramsDiffer = false;
            if (memberModel.Parameters != null)
            {
                // check that parameters have one and the same type
                if (memberModel.Parameters.Count == functionParameters.Count)
                {
                    if (functionParameters.Count > 0)
                    {
                        List<MemberModel> parameters = memberModel.Parameters;
                        for (int i = 0; i < parameters.Count; i++)
                        {
                            MemberModel p = parameters[i];
                            if (p.Type != functionParameters[i].paramType)
                            {
                                paramsDiffer = true;
                                break;
                            }
                        }
                    }
                }
                else
                {
                    paramsDiffer = true;
                }
            }
            // check that parameters count differs
            else if (functionParameters.Count != 0)
            {
                paramsDiffer = true;
            }

            if (paramsDiffer)
            {
                int app = 0;
                List<MemberModel> newParameters = new List<MemberModel>();
                List<MemberModel> existingParameters = memberModel.Parameters;
                for (int i = 0; i < functionParameters.Count; i++)
                {
                    FunctionParameter p = functionParameters[i];
                    if (existingParameters != null
                        && existingParameters.Count > (i - app)
                        && existingParameters[i - app].Type == p.paramType)
                    {
                        newParameters.Add(existingParameters[i - app]);
                    }
                    else
                    {
                        if (existingParameters != null && existingParameters.Count < functionParameters.Count)
                        {
                            app++;
                        }
                        newParameters.Add(new MemberModel(p.paramName, p.paramType, FlagType.ParameterVar, 0));
                    }
                }
                memberModel.Parameters = newParameters;

                int posStart = Sci.PositionFromLine(memberModel.LineFrom);
                int posEnd = Sci.LineEndPosition(memberModel.LineTo);
                Sci.SetSel(posStart, posEnd);
                string selectedText = Sci.SelText;
                Regex rStart = new Regex(@"\s{1}" + memberModel.Name + @"\s*\(([^\)]*)\)(\s*:\s*([^({{|\n|\r|\s|;)]+))?");
                Match mStart = rStart.Match(selectedText);
                if (!mStart.Success)
                {
                    return;
                }

                int start = mStart.Index + posStart;
                int end = start + mStart.Length;

                Sci.SetSel(start, end);

                string decl = TemplateUtils.ToDeclarationString(memberModel, TemplateUtils.GetTemplate("MethodDeclaration"));
                InsertCode(Sci.CurrentPos, "$(Boundary) " + decl);

                // add imports to function argument types
                if (functionParameters.Count > 0)
                {
                    List<string> l = new List<string>();
                    foreach (FunctionParameter fp in functionParameters)
                    {
                        try
                        {
                            l.Add(fp.paramQualType);
                        }
                        catch (Exception)
                        {
                        }
                    }
                    start += AddImportsByName(l, Sci.LineFromPosition(end));
                }

                Sci.SetSel(start, start);
            }
        }