diff --git a/AdditionalLanguages/SPython/SPythonLanguageInfo/SPythonIntellisenseSupport.cs b/AdditionalLanguages/SPython/SPythonLanguageInfo/SPythonIntellisenseSupport.cs new file mode 100644 index 000000000..4ff0408ab --- /dev/null +++ b/AdditionalLanguages/SPython/SPythonLanguageInfo/SPythonIntellisenseSupport.cs @@ -0,0 +1,1468 @@ +using PascalABCCompiler.Parsers; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Languages.SPython.Frontend.Data +{ + internal class SPythonIntellisenseSupport : BaseLanguageIntellisenseSupport + { + public override bool ApplySyntaxTreeConvertersForIntellisense => true; + + public override string BodyStartBracket => null; + + public override string BodyEndBracket => null; + + public override string ParameterDelimiter => ","; + + public override string DelimiterInIndexer => ","; + + public override string ResultVariableName => null; + + public override string ProcedureName => null; + + public override string FunctionName => "def"; + + public override string GenericTypesStartBracket => "["; + + public override string GenericTypesEndBracket => "]"; + + public override string ReturnTypeDelimiter => "->"; + + public override bool IncludeDotNetEntities => true; + + public override bool AddStandardUnitNamesToUserScope => false; + + public override bool AddStandardNetNamespacesToUserScope => true; + + public override bool UsesFunctionsOverlappingSourceContext => true; + + protected override string IntTypeName => "int"; + + private readonly Dictionary renamings = new Dictionary + { + ["biginteger"] = "bigint" + }; + + private readonly HashSet exclutions = new HashSet + { + // "__NewSetCreatorInternal" + }; + + public override void RenameOrExcludeSpecialNames(SymInfo[] symInfos) + { + for (var i = 0; i < symInfos.Length; i++) + { + if (symInfos[i] == null) + continue; + + if (renamings.TryGetValue(symInfos[i].name, out var newName)) + { + // копирование на всякий случай + symInfos[i] = new SymInfo(symInfos[i]); + symInfos[i].name = newName; + } + else if (exclutions.Contains(symInfos[i].name)) + { + symInfos[i] = new SymInfo(symInfos[i]); + symInfos[i].not_include = true; + } + } + } + + public override string GetUnitTemplate(string unitName) + { + return "#unit " + unitName + Environment.NewLine; + } + + public override string ConstructHeader(string meth, IProcScope scope, int tabCount) + { + throw new NotImplementedException(); + } + + public override string ConstructHeader(IProcRealizationScope scope, int tabCount) + { + throw new NotImplementedException(); + } + + public override string ConstructOverridedMethodHeader(IProcScope scope, out int off) + { + throw new NotImplementedException(); + } + + public override string FindExpression(int off, string Text, int line, int col, out KeywordKind keyw) + { + int i = off - 1; + int bound = 0; + bool punkt_sym = false; + keyw = KeywordKind.None; + System.Text.StringBuilder sb = new StringBuilder(); + Stack tokens = new Stack(); + Stack kav = new Stack(); + Stack ugl_skobki = new Stack(); + int num_in_ident = -1; + keyw = TestForKeyword(Text, i); + if (keyw == KeywordKind.Punkt) return ""; + while (i >= bound) + { + bool end = false; + char ch = Text[i]; + if (kav.Count == 0 && (char.IsLetterOrDigit(ch) || ch == '_' || ch == '&' || ch == '\'' || ch == '!')) + { + num_in_ident = i; + if (kav.Count == 0 && tokens.Count == 0) + { + int tmp = i; + if (ch == '\'') + { + i--; + if (kav.Count == 0) + kav.Push('\''); + while (i >= 0) + { + if (Text[i] != '\'') + i--; + else + { + if (i >= 1 && Text[i - 1] == '\'') + i -= 2; + else + break; + } + } + + if (i >= 0) + i--; + } + else + while (i >= 0 && (char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '&' || Text[i] == '!')) + { + i--; + } + while (i >= 0 && (Text[i] == ' ' || char.IsControl(Text[i]) || Text[i] == '}')) + { + if (Text[i] != '}') + i--; + else + { + while (i >= 0 && Text[i] != '{') //propusk kommentariev + i--; + if (i >= 0) + i--; + } + } + if (i >= 0 && (char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '&' || Text[i] == '!')) + { + bound = i + 1; + TestForKeyword(Text, i, ref bound, punkt_sym, out keyw); + for (int j = tmp; j > bound; j--) + { + sb.Insert(0, Text[j]); + } + if (sb.ToString().Trim() == "new") + return ""; + i = bound; + continue; + } + else if (i >= 0 && Text[i] == '\'') return ""; + i = tmp; + } + else + if (ch == '\'') + kav.Push('\''); + sb.Insert(0, ch);//.Append(Text[i]); + } + else if (ch == '.' || ch == '^' || ch == '&' || ch == '?' && IsPunctuation(Text, i + 1)) + { + if (ch == '.' && i >= 1 && Text[i - 1] == '.' && tokens.Count == 0) + end = true; + else if (ch == '?' && i + 1 < Text.Length && Text[i + 1] != '.') + end = true; + else + sb.Insert(0, ch); + if (ch != '.') + punkt_sym = true; + } + else if (ch == '}') + { + if (kav.Count == 0) + { + while (i >= 0 && Text[i] != '{') + { + if (Text[i] != '$')//skip {$ + sb.Insert(0, Text[i]); + i--; + } + if (i < 0) + { + break; + } + else if (Text[i] == '{') + { + sb.Insert(0, '{'); + } + } + else + sb.Insert(0, ch); + } + else if (ch == '{') + { + if (kav.Count == 0) + { + if (keyw == KeywordKind.None) + return sb.ToString(); + sb.Insert(0, ch); + break; + } + else sb.Insert(0, ch); + } + else + switch (ch) + { + case ')': + case ']': + if (kav.Count == 0) + { + string tmps = sb.ToString().Trim(' ', '\r', '\t', '\n'); + if (tmps.Length >= 1 && (char.IsLetter(tmps[0]) || tmps[0] == '_' || tmps[0] == '&' || tmps[0] == '?' || tmps[0] == '!') && tokens.Count == 0) + end = true; + else + tokens.Push(ch); + } + if (!end) + { + sb.Insert(0, ch); + punkt_sym = true; + } + break; + case '>': + if (tokens.Count == 0) + { + int j = i + 1; + + while (j < Text.Length && char.IsWhiteSpace(Text[j])) + j++; + + if (ugl_skobki.Count > 0 || i == off - 1 || j == off && off == Text.Length || j < Text.Length && Text[i - 1] != '-' && (Text[j] == '.' || Text[j] == '(')) + { + ugl_skobki.Push('>'); + sb.Insert(0, ch); + } + else if (i >= 1 && Text[i - 1] == '-') + { + if (!(kav.Count == 0 && tokens.Count == 0)) + sb.Insert(0, ch); + } + else + end = true; + } + else + sb.Insert(0, ch); + break; + case '<': + if (tokens.Count == 0) + { + if (ugl_skobki.Count > 0) + { + ugl_skobki.Pop(); + sb.Insert(0, ch); + } + else + end = true; + } + else + sb.Insert(0, ch); + break; + case '[': + case '(': + case '|': + if (ch == '|' && ((tokens.Count == 0) || (tokens.Peek() == ']') || (tokens.Peek() == ')') || (tokens.Peek() == ','))) + // Закрывающий | - после него (tokens.Pop()) - пусто или ] ) , + { + if (kav.Count == 0) + { + string tmps = sb.ToString().Trim(' ', '\r', '\t', '\n'); + if (tmps.Length >= 1 && (char.IsLetter(tmps[0]) || tmps[0] == '_' || tmps[0] == '&' || tmps[0] == '?' || tmps[0] == '!') && tokens.Count == 0) + end = true; + else + tokens.Push(ch); + } + if (!end) + { + sb.Insert(0, ch); + punkt_sym = true; + } + } + else + { + if (kav.Count == 0) // в т.ч. открывающий | + { + if (tokens.Count > 0) + { + tokens.Pop(); + punkt_sym = true; + sb.Insert(0, ch); + if (ch == '(') + { + int tmp = i--; + /*while (i >= 0 && (char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '&')) + { + i--; + }*/ + while (i >= 0 && (Text[i] == ' ' || char.IsControl(Text[i]) || Text[i] == '}')) + { + if (Text[i] != '}') + i--; + else + { + while (i >= 0 && Text[i] != '{') //propusk kommentariev + i--; + if (i >= 0) + i--; + } + } + if (i >= 0 && (char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '&' || Text[i] == '!' || Text[i] == '?' && IsPunctuation(Text, i + 1))) + { + bound = i + 1; + TestForKeyword(Text, i, ref bound, punkt_sym, out keyw); + if (keyw != KeywordKind.None && tokens.Count == 0) + { + end = true; + } + else bound = 0; + } + else if (i >= 0 && Text[i] == '\'') return ""; + i = tmp; + } + } + else + { + end = true; + if (ch == '[') + { + keyw = KeywordKind.SquareBracket; + } + } + + } + else sb.Insert(0, ch); punkt_sym = true; + } + break; + case '\'': + if (kav.Count == 0) kav.Push(ch); else kav.Pop(); + sb.Insert(0, ch); + punkt_sym = true; break; + default: + if (!(ch == ' ' || char.IsControl(ch))) + { + if (kav.Count == 0) + { + if (ch == ',' && ugl_skobki.Count > 0) + sb.Insert(0, ch); + else + if (tokens.Count == 0) + end = true; + else + sb.Insert(0, ch); + } + else + sb.Insert(0, ch); + } + else + { + if (Text[i] == '\n') + { + bool one_line_comment = false; + int comment_position = -1; + if (CheckForComment(Text, i - 1, out comment_position, out one_line_comment)) + { + if (!one_line_comment) + end = true; + else + { + sb.Insert(0, ch); + i = comment_position; + } + + } + else + sb.Insert(0, ch); + } + else + sb.Insert(0, ch); + } + punkt_sym = true; + break; + } + + if (end) + { + bool one_line_comment = false; + int comment_position = -1; + if (CheckForComment(Text, i, out comment_position, out one_line_comment)) + { + int new_line_ind = sb.ToString().IndexOf('\n'); + if (new_line_ind != -1) sb = sb.Remove(0, new_line_ind + 1); + else sb = sb.Remove(0, sb.Length); + } + break; + } + i--; + } + + //return RemovePossibleKeywords(sb); + if (sb.Length > 0 && sb[sb.Length - 1] == '?') + sb.Remove(sb.Length - 1, 1); + + return sb.ToString().Trim(); + } + + private bool CheckForComment(string Text, int off, out int comment_position, out bool one_line_comment) + { + int i = off; + one_line_comment = false; + comment_position = -1; + Stack kav = new Stack(); + bool is_comm = false; + while (i >= 0 && !is_comm && Text[i] != '\n' && Text[i] != '\r') + { + if (Text[i] == '\'' || Text[i] == '"') + { + if (kav.Count == 0) kav.Push('\''); + else kav.Pop(); + } + else if (Text[i] == '{') + { + if (kav.Count == 0) + { + comment_position = i; + while (i >= 0 && Text[i] != '\'' && Text[i] != '"') + i--; + if (i >= 1 && Text[i - 1] == '$') + return false; + is_comm = true; + return is_comm; + } + } + else if (Text[i] == '}') + { + return false; + } + else if (Text[i] == '#') + if (kav.Count == 0) + { + is_comm = true; + one_line_comment = true; + comment_position = i - 1; + } + + i--; + } + return is_comm; + } + + public override string FindExpressionForMethod(int off, string Text, int line, int col, char pressed_key, ref int num_param) + { + int i = off - 1; + string pattern = null; + int bound = 0; + System.Text.StringBuilder sb = new System.Text.StringBuilder(); + Stack tokens = new Stack(); + Stack kav = new Stack(); + Stack skobki = new Stack(); + Stack ugl_skobki = new Stack(); + bool comma_pressed = pressed_key == ','; + int num_in_ident = -1; + bool punkt_sym = false; + int next; + KeywordKind keyw = TestForKeyword(Text, i); + bool on_brace = false; + if (keyw == KeywordKind.Punkt) + return ""; + try + { + while (i >= bound) + { + bool end = false; + char ch = Text[i]; + if ((char.IsLetterOrDigit(ch) || ch == '_' || ch == '&' || ch == '!') && !isOperator(Text, i, out next)) + { + num_in_ident = i; + if (kav.Count == 0 && tokens.Count == 0) + { + int tmp = i; + while (i >= 0 && (char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '&' || Text[i] == '!') && !isOperator(Text, i, out next)) + { + i--; + } + while (i >= 0 && (Text[i] == ' ' || char.IsControl(Text[i]) || Text[i] == '}')) + { + if (Text[i] != '}') + i--; + else + { + while (i >= 0 && Text[i] != '{') //propusk kommentariev + i--; + if (i >= 0) + i--; + } + } + if (i >= 0 && (char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '&' || Text[i] == '!') && !isOperator(Text, i, out next)) + { + bound = i + 1; + TestForKeyword(Text, i, ref bound, punkt_sym, out keyw); + if (keyw == KeywordKind.New && comma_pressed) + bound = 0; + if (keyw == KeywordKind.Function || keyw == KeywordKind.Constructor || keyw == KeywordKind.Destructor) + return ""; + } + else if (i >= 0 && (Text[i] == '\'' || Text[i] == '"')) return ""; + i = tmp; + } + sb.Insert(0, ch);//.Append(Text[i]); + } + else if (ch == '.') sb.Insert(0, ch); + else if (ch == '}') + { + if (kav.Count == 0) + { + while (i >= 0 && Text[i] != '{') + { + sb.Insert(0, Text[i]); + i--; + } + if (i < 0) + { + break; + } + else if (Text[i] == '{') + { + sb.Insert(0, '{'); + } + } + else + sb.Insert(0, ch); + } + else if (ch == '{') + { + if (kav.Count == 0) + { + sb.Insert(0, ch); + break; + } + else sb.Insert(0, ch); + } + else + switch (ch) + { + case ')': + case ']': + case '>': + // Добавил это условие для питона EVA + if (pressed_key == '(' && ch == ')' && !sb.ToString().Contains(".") && tokens.Count == 0) + { + end = true; + break; + } + if (kav.Count == 0) + { + int j = i + 1; + + while (j < Text.Length && char.IsWhiteSpace(Text[j])) + j++; + if (ch != '>') + tokens.Push(ch); + if (ch == ')') + skobki.Push(ch); + if (tokens.Count > 0 || pressed_key == ',') + sb.Insert(0, ch); + else if (i == off - 1 || j == off && off == Text.Length || ugl_skobki.Count > 0 || j < Text.Length && Text[i - 1] != '-' && (Text[j] == '.' || Text[j] == '(')) + { + tokens.Push(ch); + ugl_skobki.Push(ch); + sb.Insert(0, ch); + } + else + end = true; + } + else + sb.Insert(0, ch); break; + case '[': + case '<': + case '(': + if (kav.Count == 0)//esli ne v kavychkah + { + if (ch == '(') + if (skobki.Count > 0) + skobki.Pop(); + else skobki.Push('('); + //esli byli zakryvaushie tokeny (polagaem, chto skobki korrektny, esli net, to parser v lubom sluchae ne proparsit + if (tokens.Count > 0) + { + if (ch != '<') + tokens.Pop(); + else if (ugl_skobki.Count > 0) + { + tokens.Pop(); + ugl_skobki.Pop(); + } + sb.Insert(0, ch);//dobavljaem k stroke + if (ch == '(') + { + int tmp = i--; + /*while (i >= 0 && (char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '&')) + { + i--; + }*/ + while (i >= 0 && (Text[i] == ' ' || char.IsControl(Text[i]) || Text[i] == '}')) + { + if (Text[i] != '}') + { + i--; + } + else + { + while (i >= 0 && Text[i] != '{') + { + //propusk kommentariev + i--; + } + if (i >= 0) + i--; + } + } + + if (i >= 0 && (char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '&' || Text[i] == '!')) + { + bound = i + 1; + TestForKeyword(Text, i, ref bound, punkt_sym, out keyw); + if (keyw == KeywordKind.New) + bound = 0; + else + if (keyw != KeywordKind.None && tokens.Count == 0) + end = true; + else + bound = 0; + } + else if (i >= 0 && (Text[i] == '\'' || Text[i] == '"')) return ""; + i = tmp; + } + } + else if (ch == '<' || ch == '>') + { + if (tokens.Count > 0 || pressed_key == ',') + sb.Insert(0, ch); + else + end = true; + } + else + if (!comma_pressed) //esli my ne v parametrah + end = true; //zakonchili, tak kak doshli do pervoj skobki + else + { + sb.Remove(0, sb.Length);//doshli do skobki, byla nazhata zapjataja, poetomu udaljaem vse parametry + if (ch == '(') + on_brace = true; + //on_skobka = true; + comma_pressed = false; + } + } + else sb.Insert(0, ch); + break; + case '\'': + case '"': + if (kav.Count == 0) + kav.Push(ch); + else + kav.Pop(); + sb.Insert(0, ch); + if (kav.Count == 0 && tokens.Count == 0) + end = true; + break; + default: + if (!(ch == ' ' || char.IsControl(ch))) + { + if (ch == '^') + sb.Insert(0, ch); + else + if (kav.Count == 0)//ne v kavychkah + { + if (tokens.Count == 0) + { + if (ch != ',' && !comma_pressed) + end = true;//esli ne na zapjatoj i ne v parametrah, to finish + else if (ch == ',' && !comma_pressed) + end = true; + else if (ch == ',' && (pressed_key == '(' || pressed_key == '[')) + end = true; + else + { + sb.Insert(0, ch);//prodolzhaem + if (isOperator(Text, i, out next)) + { + i = next; + continue; + } + } + + } + else + sb.Insert(0, ch);//esli est skobki, prodolzhaem + if (!end && ch == ',') + { + if (tokens.Count == 0) + num_param++;//esli na zapjatoj, uvelichivaem nomer parametra + } + } + else + sb.Insert(0, ch);//prodolzhaem + + } + else + if (Text[i] == '\n') + { + bool one_line_comment = false; + int comment_position = -1; + if (CheckForComment(Text, i - 1, out comment_position, out one_line_comment)) //proverjaem, net li kommenta ne predydushej stroke + { + if (!one_line_comment) + end = true; + else + { + sb.Insert(0, ch); + i = comment_position; + } + + } + else + sb.Insert(0, ch);//a inache vyrazhenie na neskolkih strokah + } + else + sb.Insert(0, ch); + break; + } + + if (end) + { + if (comma_pressed && !on_brace) + return ""; + bool one_line_comment = false; + int comment_position = -1; + if (CheckForComment(Text, i, out comment_position, out one_line_comment))//proverka na kommentarii + { + int new_line_ind = sb.ToString().IndexOf('\n'); + if (new_line_ind != -1) sb = sb.Remove(0, new_line_ind + 1); + else sb = sb.Remove(0, sb.Length); + } + break; + } + i--; + } + if (pressed_key == ',') + num_param++; + } + catch (Exception e) + { + + } + if (pressed_key == ',' && (!on_brace || skobki.Count == 0)) + return ""; + //return RemovePossibleKeywords(sb); + return sb.ToString().Trim(); + } + + private bool isOperator(string Text, int i, out int next) + { + next = i; + if (i >= 3) + { + string op = Text.Substring(i - 2, 3).ToLower().Trim(); + if (op == "and" || op == "div" || op == "mod" || op == "xor") + { + if (!char.IsLetterOrDigit(Text[i - 3]) && Text[i - 3] != '_' && Text[i - 3] != '&' && !(i + 1 < Text.Length && char.IsLetterOrDigit(Text[i + 1]))) + { + next = i - 3; + return true; + } + return false; + } + } + if (i >= 2) + { + string op = Text.Substring(i - 1, 2).ToLower().Trim(); + if (op == "or") + { + if (!char.IsLetterOrDigit(Text[i - 2]) && Text[i - 2] != '_' && Text[i - 2] != '&' && !(i + 1 < Text.Length && char.IsLetterOrDigit(Text[i + 1]))) + { + next = i - 2; + return true; + } + return false; + } + } + return false; + } + + public override string FindExpressionFromAnyPosition(int off, string Text, int line, int col, out KeywordKind keyw, out string expr_without_brackets) + { + int i = off - 1; + + // это например вызов метода без параметров + expr_without_brackets = null; + keyw = KeywordKind.None; + if (i < 0) + return ""; + bool is_char = false; + + // идем в обе стороны от off + System.Text.StringBuilder sb = new System.Text.StringBuilder(); + if (Text[i] != ' ' && (char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '&' || Text[i] == '?' && IsPunctuation(Text, i + 1) || Text[i] == '!')) + { + //sb.Remove(0,sb.Length); + while (i >= 0 && (char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '&' || Text[i] == '?' && IsPunctuation(Text, i + 1) || Text[i] == '!')) + { + //sb.Insert(0,Text[i]);//.Append(Text[i]); + i--; + } + is_char = true; + } + i = off; + if (i < Text.Length && Text[i] != ' ' && (char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '&' || Text[i] == '?' && IsPunctuation(Text, i + 1) || Text[i] == '!')) + { + while (i < Text.Length && (char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '!')) + { + //sb.Append(Text[i]);//.Append(Text[i]); + i++; + } + is_char = true; + } + if (is_char) + { + expr_without_brackets = FindExpression(i, Text, line, col, out keyw); + } + bool is_new = keyw == KeywordKind.New; + bool meth_call = false; + KeywordKind new_keyw = KeywordKind.None; + int j = i; + bool in_comment = false; + bool brackets = false; + while (j < Text.Length) + { + char c = Text[j]; + + if (c == '(' && !in_comment) + { + Stack sk_stack = new Stack(); + in_comment = false; + bool in_kav = false; + sk_stack.Push('('); + j++; + while (j < Text.Length) + { + c = Text[j]; + if (c == '(' && !in_kav) + sk_stack.Push('('); + else + if (c == ')' && !in_kav) + { + if (sk_stack.Count == 0) + { + break; + } + else + { + sk_stack.Pop(); + if (sk_stack.Count == 0) + { + i = j + 1; + meth_call = true; + break; + } + } + } + else if ((c == '\'' || c == '"') && !in_comment) + { + in_kav = !in_kav; + } + else if (c == '{' && !in_kav) + { + in_comment = true; + } + else if (c == '}' && !in_kav) + { + in_comment = false; + } + else if (c == '#' && !in_kav && !in_comment) + { + break; + } + j++; + } + break; + } + else if ((c == '<' || c == '&' && j < Text.Length - 1 && Text[j + 1] == '<') && !in_comment) + { + Stack sk_stack = new Stack(); + if (c == '&') + j++; + sk_stack.Push('<'); + j++; + bool generic = false; + while (j < Text.Length) + { + c = Text[j]; + if (c == '>') + { + sk_stack.Pop(); + if (sk_stack.Count == 0) + { + i = j + 1; + generic = true; + break; + } + } + else if (c == '<') + { + sk_stack.Push('<'); + + } + else if (!char.IsLetterOrDigit(c) && c != '?' && c != '&' && c != '.' && c != ' ' && c != '\t' && c != '\n' && c != ',' && c != '!') + { + break; + } + j++; + } + if (generic) + { + //break; + } + } + else if (c == '[' && !in_comment) + { + brackets = true; + break; + } + else if (c == '{') + { + in_comment = true; + } + else if (c == '}') + { + if (!in_comment) + break; + else + in_comment = false; + } + else if (c == ' ' || c == '\t' || c == '\n' || c == '\r') + { + + } + else + { + if (!in_comment) + break; + } + j++; + } + if (is_new && string.Compare(expr_without_brackets.Trim(' ', '\n', '\t', '\r'), "new", true) == 0 && !meth_call) + { + expr_without_brackets = null; + return null; + } + if (is_char) + { + string ss = FindExpression(i, Text, line, col, out new_keyw); + if (brackets && is_new) + { + int ind = ss.ToLower().IndexOf("new"); + if (ind != -1) + return ss.Substring(ind + 3); + } + if (is_new && ss != null && ss.IndexOf("new") == -1 && ss.IndexOf(":") != -1) + return expr_without_brackets + "(true?" + ss; + return ss; + } + return null; + } + + public override string GetDescription(IBaseScope scope) + { + switch (scope.Kind) + { + case ScopeKind.Type: return GetDescriptionForType(scope as ITypeScope); + case ScopeKind.CompiledType: return GetDescriptionForCompiledType(scope as ICompiledTypeScope); + case ScopeKind.Delegate: return GetDescriptionForDelegate(scope as IProcType); + case ScopeKind.TypeSynonim: return GetSynonimDescription(scope as ITypeSynonimScope); + case ScopeKind.Array: return GetDescriptionForArray(scope as IArrayScope); + case ScopeKind.Diapason: return GetDescriptionForDiapason(scope as IDiapasonScope); + case ScopeKind.File: return GetDescriptionForFile(scope as IFileScope); + case ScopeKind.Pointer: return GetDescriptionForPointer(scope as IPointerScope); + case ScopeKind.Enum: return GetDescriptionForEnum(scope as IEnumScope); + case ScopeKind.Set: return GetDescriptionForSet(scope as ISetScope); + case ScopeKind.ElementScope: return GetDescriptionForElementScope(scope as IElementScope); + case ScopeKind.CompiledField: return GetDescriptionForCompiledField(scope as ICompiledFieldScope); + case ScopeKind.CompiledProperty: return GetDescriptionForCompiledProperty(scope as ICompiledPropertyScope); + case ScopeKind.CompiledMethod: return GetDescriptionForCompiledMethod(scope as ICompiledMethodScope); + case ScopeKind.Namespace: return GetDescriptionForNamespace(scope as INamespaceScope); + case ScopeKind.Procedure: return GetDescriptionForProcedure(scope as IProcScope); + case ScopeKind.CompiledEvent: return GetDescriptionForCompiledEvent(scope as ICompiledEventScope); + case ScopeKind.CompiledConstructor: return GetDescriptionForCompiledConstructor(scope as ICompiledConstructorScope); + case ScopeKind.ShortString: return GetDescriptionForShortString(scope as IShortStringScope); + } + return ""; + } + + protected override string GetFullTypeName(Type ctn, bool no_alias = true) + { + TypeCode tc = Type.GetTypeCode(ctn); + if (ctn.FullName == null && !ctn.IsArray && !ctn.IsGenericTypeDefinition && ctn.IsGenericParameter) + return ctn.Name; + if (!ctn.IsEnum) + { + switch (tc) + { + case TypeCode.Int32: return "int"; + case TypeCode.Double: return "float"; + case TypeCode.Boolean: return "bool"; + case TypeCode.String: return "str"; + case TypeCode.Char: return "char"; + } + /*if (ctn.IsPointer) + if (ctn.FullName == "System.Void*") + return "pointer"; + else + return "^" + GetFullTypeName(ctn.GetElementType());*/ + } + else + return ctn.FullName; + if (!no_alias) + { + if (ctn.Name.Contains("Func`") || ctn.Name.Contains("Predicate`")) + return getLambdaRepresentation(ctn, true, new List()); + else if (ctn.Name.Contains("Action`")) + return getLambdaRepresentation(ctn, false, new List()); + else if (ctn.Name == "IEnumerable`1") + return "sequence of " + GetShortTypeName(ctn.GetGenericArguments()[0], false); + else if (ctn.Name.Contains("Tuple`")) + return get_tuple_string(ctn); + } + int gen_pos = ctn.Name.IndexOf("`"); + if (gen_pos != -1 || ctn.IsGenericType) + { + int len = ctn.GetGenericArguments().Length; + Type[] gen_ps = ctn.GetGenericArguments(); + System.Text.StringBuilder sb = new System.Text.StringBuilder(); + if (gen_pos != -1) + sb.Append(ctn.Namespace + "." + ctn.Name.Substring(0, gen_pos)); + else + sb.Append(ctn.Namespace + "." + ctn.Name); + sb.Append(GenericTypesStartBracket); + for (int i = 0; i < len; i++) + { + sb.Append(gen_ps[i].Name); + if (i < len - 1) + sb.Append(", "); + } + sb.Append(GenericTypesEndBracket); + return sb.ToString(); + } + if (ctn.IsArray) + { + var rank = ctn.GetArrayRank(); + var strrank = rank > 1 ? "[" + new string(',', rank - 1) + "]" : ""; + return $"array{strrank}" + " of " + GetFullTypeName(ctn.GetElementType()); + } + if (ctn == Type.GetType("System.Void*")) return "pointer"; + if (ctn.IsNested) + return ctn.Name; + return ctn.FullName; + } + + public override string GetKeyword(SymbolKind kind) + { + switch (kind) + { + case SymbolKind.Class: return "class"; + case SymbolKind.Enum: return "enum"; + case SymbolKind.Struct: return "record"; + case SymbolKind.Type: return "type"; + case SymbolKind.Interface: return "interface"; + case SymbolKind.Null: return "None"; + } + return ""; + } + + public override string GetShortTypeName(Type ctn, bool noalias = true) + { + TypeCode tc = Type.GetTypeCode(ctn); + if (ctn.FullName == null && !ctn.IsArray && !ctn.IsGenericTypeDefinition && ctn.IsGenericParameter) + return ctn.Name; + if (!ctn.IsEnum) + { + switch (tc) + { + case TypeCode.Int32: return "int"; + case TypeCode.Double: return "float"; + case TypeCode.Boolean: return "bool"; + case TypeCode.String: return "str"; + case TypeCode.Char: return "char"; + } + /*if (ctn.IsPointer) + if (ctn.FullName == "System.Void*") + return "pointer"; + else + return "^" + GetShortTypeName(ctn.GetElementType(), noalias);*/ + } + else return ctn.Name; + if (ctn.Name.Contains("`")) + { + if (!noalias) + { + if (ctn.Name.Contains("Func`") || ctn.Name.Contains("Predicate`")) + return getLambdaRepresentation(ctn, true, new List()); + else if (ctn.Name.Contains("Action`")) + return getLambdaRepresentation(ctn, false, new List()); + else if (ctn.Name == "IEnumerable`1") + return "sequence of " + GetShortTypeName(ctn.GetGenericArguments()[0], false); + else if (ctn.Name.Contains("Tuple`")) + return get_tuple_string(ctn); + } + int len = ctn.GetGenericArguments().Length; + System.Text.StringBuilder sb = new System.Text.StringBuilder(); + sb.Append(ctn.Name.Substring(0, ctn.Name.IndexOf('`'))); + sb.Append('['); + if (!noalias) + { + Type[] gen_ps = ctn.GetGenericArguments(); + for (int i = 0; i < len; i++) + { + sb.Append(gen_ps[i].Name); + if (i < len - 1) + sb.Append(", "); + } + } + sb.Append(']'); + return sb.ToString(); + } + if (ctn.IsArray) + { + var rank = ctn.GetArrayRank(); + var strrank = rank > 1 ? "[" + new string(',', rank - 1) + "]" : ""; + return $"array{strrank}" + " of " + GetShortTypeName(ctn.GetElementType()); + } + //if (ctn == Type.GetType("System.Void*")) return PascalABCCompiler.StringConstants.pointer_type_name; + return ctn.Name; + } + + public override string GetSimpleDescription(IBaseScope scope) + { + if (scope == null) + return ""; + switch (scope.Kind) + { + case ScopeKind.Delegate: + case ScopeKind.Array: + case ScopeKind.Diapason: + case ScopeKind.File: + case ScopeKind.Pointer: + case ScopeKind.Enum: + case ScopeKind.Set: + case ScopeKind.ShortString: + if (scope is ITypeScope && (scope as ITypeScope).Aliased) + return scope.Name; + break; + case ScopeKind.TypeSynonim: + case ScopeKind.Type: + if (scope.Name == "biginteger") + return "bigint"; + break; + } + switch (scope.Kind) + { + case ScopeKind.Type: return GetSimpleDescriptionForType(scope as ITypeScope); + case ScopeKind.CompiledType: return GetSimpleDescriptionForCompiledType(scope as ICompiledTypeScope); + case ScopeKind.Delegate: return GetDescriptionForDelegate(scope as IProcType); + case ScopeKind.TypeSynonim: return GetSimpleSynonimDescription(scope as ITypeSynonimScope); + case ScopeKind.Array: return GetDescriptionForArray(scope as IArrayScope); + case ScopeKind.Diapason: return GetDescriptionForDiapason(scope as IDiapasonScope); + case ScopeKind.File: return GetDescriptionForFile(scope as IFileScope); + case ScopeKind.Pointer: return GetDescriptionForPointer(scope as IPointerScope); + case ScopeKind.Enum: return GetDescriptionForEnum(scope as IEnumScope); + case ScopeKind.Set: return GetDescriptionForSet(scope as ISetScope); + case ScopeKind.ElementScope: return GetSimpleDescriptionForElementScope(scope as IElementScope); + case ScopeKind.CompiledField: return GetDescriptionForCompiledField(scope as ICompiledFieldScope); + case ScopeKind.CompiledProperty: return GetDescriptionForCompiledProperty(scope as ICompiledPropertyScope); + case ScopeKind.CompiledMethod: return GetDescriptionForCompiledMethod(scope as ICompiledMethodScope); + case ScopeKind.Namespace: return GetDescriptionForNamespace(scope as INamespaceScope); + case ScopeKind.Procedure: return GetSimpleDescriptionForProcedure(scope as IProcScope); + case ScopeKind.CompiledEvent: return GetDescriptionForCompiledEvent(scope as ICompiledEventScope); + case ScopeKind.CompiledConstructor: return GetDescriptionForCompiledConstructor(scope as ICompiledConstructorScope); + case ScopeKind.ShortString: return GetDescriptionForShortString(scope as IShortStringScope); + case ScopeKind.UnitInterface: return GetDescriptionForModule(scope as IInterfaceUnitScope); + //case ScopeKind.Procedure : return GetDescriptionForProcedure(scope as IProcScope); + } + return ""; + } + + private string GetDescriptionForModule(IInterfaceUnitScope scope) + { + var p = LanguageInformation.SpecialModulesAliases.FirstOrDefault(kv => kv.Value == scope.Name); + + if (!p.Equals(default(KeyValuePair))) + return "unit " + p.Key; + + return "unit " + scope.Name; + } + + private string GetDescriptionForFile(IFileScope scope) + { + StringBuilder sb = new StringBuilder(); + sb.Append("file"); + if (scope.ElementType != null) + { + string s = GetSimpleDescription(scope.ElementType); + if (s.Length > 0 && s[0] == '$') s = s.Substring(1, s.Length - 1); + sb.Append("[" + s + "]"); + } + return sb.ToString(); + } + + private string GetDescriptionForSet(ISetScope scope) + { + StringBuilder sb = new StringBuilder(); + + sb.Append("set["); + + if (scope.ElementType != null) + { + string s = GetSimpleDescription(scope.ElementType); + if (s.Length > 0 && s[0] == '$') s = s.Substring(1, s.Length - 1); + sb.Append(s); + } + + sb.Append("]"); + + return sb.ToString(); + } + + private string GetDescriptionForDiapason(IDiapasonScope scope) + { + return scope.Left.ToString() + ".." + scope.Right.ToString(); + } + + private string GetDescriptionForPointer(IPointerScope scope) + { + string s = ""; + if (scope.ElementType != null) + { + s = "^" + GetSimpleDescription(scope.ElementType); + } + else + s = "pointer"; + + return s; + } + + private string GetDescriptionForNamespace(INamespaceScope scope) + { + return "namespace " + scope.Name; + } + + private string GetSimpleSynonimDescription(ITypeSynonimScope scope) + { + return scope.Name; + } + + public override string GetStandardTypeByKeyword(KeywordKind keyw) + { + switch (keyw) + { + case KeywordKind.IntType: return "int"; + case KeywordKind.DoubleType: return "float"; + case KeywordKind.CharType: return "char"; + case KeywordKind.BoolType: return "bool"; + case KeywordKind.StringType: return "str"; + } + return null; + } + + public override string GetSynonimDescription(ITypeScope scope) + { + return "type " + scope.Name + GetGenericString(scope.TemplateArguments) + " = " + scope.Description; + } + + public override string GetSynonimDescription(ITypeSynonimScope scope) + { + if (scope.ActType is ICompiledTypeScope && !(scope.ActType as ICompiledTypeScope).Aliased) + return "type " + scope.Name + GetGenericString(scope.TemplateArguments) + " = " + GetSimpleDescriptionForCompiledType(scope.ActType as ICompiledTypeScope, true); + else + return "type " + scope.Name + GetGenericString(scope.TemplateArguments) + " = " + GetSimpleDescription(scope.ActType); + } + + public override string GetSynonimDescription(IProcScope scope) + { + return "type " + scope.Name + " = " + scope.Description; + } + + public override KeywordKind TestForKeyword(string Text, int i) + { + StringBuilder sb = new StringBuilder(); + int orig_i = i; + int j = i; + bool in_keyw = false; + while (j >= 0 && Text[j] != '\n') + j--; + Stack kav_stack = new Stack(); + j++; + bool in_format_str = false; + while (j <= i) + { + if (Text[j] == '\'' || Text[j] == '"') + { + if (kav_stack.Count == 0 && !in_keyw) + { + if (j == 0 || Text[j - 1] != '$') + kav_stack.Push('\''); + else + { + in_keyw = false; + in_format_str = true; + } + + } + else if (kav_stack.Count > 0) + kav_stack.Pop(); + } + else if (Text[j] == '{' && kav_stack.Count == 0 && !in_format_str) + in_keyw = true; + else + if (Text[j] == '}') + in_keyw = false; + j++; + } + j = i; + if ((kav_stack.Count != 0 || in_keyw) && !in_format_str) return PascalABCCompiler.Parsers.KeywordKind.Punkt; + if (j >= 0 && Text[j] == '.') return PascalABCCompiler.Parsers.KeywordKind.Punkt; + while (j >= 0) + { + //if (Text[j] == '{') return PascalABCCompiler.Parsers.KeywordKind.Punkt; + if (!in_keyw && (Text[j] == '\'' || Text[j] == '"' || Text[j] == '\n')) + break; + if (Text[j] == '}') + in_keyw = true; + else + if (Text[j] == '#' && !in_keyw) + return PascalABCCompiler.Parsers.KeywordKind.Punkt; + j--; + } + //if (j>= 0 && Text[j] == '\'') return CodeCompletion.KeywordKind.kw_punkt; + while (i >= 0 && (Text[i] == ' ' || char.IsControl(Text[i]))) i--; + if (i >= 0 && Text[i] == ':') return PascalABCCompiler.Parsers.KeywordKind.Colon; + + if (i >= 0 && Text[i] == ',') + { + + while (i >= 0 && Text[i] != '\n') + { + if (char.IsLetterOrDigit(Text[i])) + sb.Insert(0, Text[i]); + else + { + PascalABCCompiler.Parsers.KeywordKind keyw = GetKeywordKind(sb.ToString()); + if (keyw == PascalABCCompiler.Parsers.KeywordKind.Uses) + return PascalABCCompiler.Parsers.KeywordKind.Uses; + else if (keyw == PascalABCCompiler.Parsers.KeywordKind.Var) + return PascalABCCompiler.Parsers.KeywordKind.Var; + else sb.Remove(0, sb.Length); + } + i--; + } + } + else + while (i >= 0 && (char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '!')) + { + sb.Insert(0, Text[i]); + i--; + } + string s = sb.ToString().ToLower(); + + return GetKeywordKind(s); + } + + private string GetDescriptionForType(ITypeScope scope) + { + string template_str = GetTemplateString(scope); + switch (scope.ElemKind) + { + case SymbolKind.Class: + string mod = ""; + if (scope.IsStatic) + mod = "static "; + + if (scope.TopScope != null && scope.TopScope.Name != "" && !scope.TopScope.Name.Contains("$")) + return mod + "class " + scope.TopScope.Name + "." + scope.Name + template_str; + else return mod + "class " + scope.Name + template_str; + + case SymbolKind.Enum: + if (scope.TopScope != null && scope.TopScope.Name != "" && !scope.TopScope.Name.Contains("$")) + return "enum " + scope.TopScope.Name + "." + scope.Name; + else return "enum " + scope.Name; + } + + if (scope.TopScope != null) + return scope.TopScope.Name + "." + scope.Name; + else return scope.Name; + } + + private string GetDescriptionForCompiledType(ICompiledTypeScope scope) + { + string s = GetFullTypeName(scope.CompiledType); + ITypeScope[] instances = scope.GenericInstances; + if (instances.Length > 0) + { + System.Text.StringBuilder sb = new System.Text.StringBuilder(); + int ind = s.IndexOf(GenericTypesStartBracket); + if (ind != -1) sb.Append(s.Substring(0, ind)); + else + sb.Append(s); + sb.Append(GenericTypesStartBracket); + for (int i = 0; i < instances.Length; i++) + { + sb.Append(GetSimpleDescriptionWithoutNamespace(instances[i])); + //sb.Append(instances[i].Name); + if (i < instances.Length - 1) sb.Append(", "); + } + sb.Append(GenericTypesEndBracket); + s = sb.ToString(); + } + + switch (scope.ElemKind) + { + case SymbolKind.Class: + string mod = ""; + if (scope.IsStatic) + mod = "static "; + else + { + if (scope.IsAbstract) + mod = "abstract "; + if (scope.IsFinal) + mod += "sealed "; + } + return mod + "class " + s; + case SymbolKind.Interface: + return "interface " + s; + case SymbolKind.Enum: + return "enum " + s; + case SymbolKind.Delegate: + return "delegate " + s; + case SymbolKind.Struct: + return "record " + s; + case SymbolKind.Type: + return "type " + s; + } + return s; + } + } +} diff --git a/AdditionalLanguages/SPython/SPythonLanguageInfo/SPythonLanguage.cs b/AdditionalLanguages/SPython/SPythonLanguageInfo/SPythonLanguage.cs index 16c29412b..714179a02 100644 --- a/AdditionalLanguages/SPython/SPythonLanguageInfo/SPythonLanguage.cs +++ b/AdditionalLanguages/SPython/SPythonLanguageInfo/SPythonLanguage.cs @@ -11,6 +11,7 @@ namespace Languages.SPython public SPythonLanguage() : base( languageInformation: new Frontend.Data.SPythonLanguageInformation(), + languageIntellisenseSupport: new Frontend.Data.SPythonIntellisenseSupport(), parser: new SPythonParser.SPythonLanguageParser(), docParser: null, diff --git a/AdditionalLanguages/SPython/SPythonLanguageInfo/SPythonLanguageInformation.cs b/AdditionalLanguages/SPython/SPythonLanguageInfo/SPythonLanguageInformation.cs index 47a7ec982..b1682019b 100644 --- a/AdditionalLanguages/SPython/SPythonLanguageInfo/SPythonLanguageInformation.cs +++ b/AdditionalLanguages/SPython/SPythonLanguageInfo/SPythonLanguageInformation.cs @@ -1,83 +1,30 @@ -using PascalABCCompiler; -using PascalABCCompiler.Parsers; +using PascalABCCompiler.Parsers; using PascalABCCompiler.ParserTools.Directives; -using PascalABCCompiler.SyntaxTree; -using System; using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Text; namespace Languages.SPython.Frontend.Data { - internal class SPythonLanguageInformation : BaseLanguageInformation + internal class SPythonLanguageInformation : ILanguageInformation { - public override string Name => "SPython"; + public string Name => "SPython"; - public override string Version => "0.0.1"; + public string Version => "0.0.1"; - public override string Copyright => "Copyright © 2023-2026 by Vladislav Krylov, Egor Movchan"; + public string Copyright => "Copyright © 2023-2026 by Vladislav Krylov, Egor Movchan"; - public override string[] FilesExtensions => new string[] { ".pys" }; + public string[] FilesExtensions => new string[] { ".pys" }; - public override string[] SystemUnitNames => new string[] { "SPythonSystem", "SPythonHidden", "SPythonSystemPys" }; + public string[] SystemUnitNames => new string[] { "SPythonSystem", "SPythonHidden", "SPythonSystemPys" }; - public override bool SyntaxTreeIsConvertedAfterUsedModulesCompilation => true; + public bool SyntaxTreeIsConvertedAfterUsedModulesCompilation => true; - public override bool ApplySyntaxTreeConvertersForIntellisense => true; + public BaseKeywords KeywordsStorage { get; } = new SPythonParser.SPythonKeywords(); - public override BaseKeywords KeywordsStorage { get; } = new SPythonParser.SPythonKeywords(); + public Dictionary ValidDirectives { get; protected set; } - public override Dictionary ValidDirectives { get; protected set; } + public string CommentSymbol => "#"; - public override string CommentSymbol => "#"; - - public override string BodyStartBracket => null; - - public override string BodyEndBracket => null; - - public override string ParameterDelimiter => ","; - - public override string DelimiterInIndexer => ","; - - public override string ResultVariableName => null; - - public override string ProcedureName => null; - - public override string FunctionName => "def"; - - public override string GenericTypesStartBracket => "["; - - public override string GenericTypesEndBracket => "]"; - - public override string ReturnTypeDelimiter => "->"; - - public override bool CaseSensitive => true; - - public override bool IncludeDotNetEntities => true; - - public override bool AddStandardUnitNamesToUserScope => false; - - public override bool AddStandardNetNamespacesToUserScope => true; - - public override bool UsesFunctionsOverlappingSourceContext => true; - - protected override string IntTypeName => "int"; - - public override bool IsParams(string paramDescription) - { - return paramDescription.TrimStart().StartsWith("params"); - } - - private readonly Dictionary renamings = new Dictionary - { - ["biginteger"] = "bigint" - }; - - private readonly HashSet exclutions = new HashSet - { - // "__NewSetCreatorInternal" - }; + public bool CaseSensitive => true; private readonly Dictionary specialModulesAliases = new Dictionary { @@ -85,1473 +32,6 @@ namespace Languages.SPython.Frontend.Data { "random", "random1" }, }; - public override Dictionary SpecialModulesAliases => specialModulesAliases; - - public override void RenameOrExcludeSpecialNames(SymInfo[] symInfos) - { - for (var i = 0; i < symInfos.Length; i++) - { - if (symInfos[i] == null) - continue; - - if (renamings.TryGetValue(symInfos[i].name, out var newName)) - { - // копирование на всякий случай - symInfos[i] = new SymInfo(symInfos[i]); - symInfos[i].name = newName; - } - else if (exclutions.Contains(symInfos[i].name)) - { - symInfos[i] = new SymInfo(symInfos[i]); - symInfos[i].not_include = true; - } - } - } - - public override string GetUnitTemplate(string unitName) - { - return "#unit " + unitName + Environment.NewLine; - } - - public override string ConstructHeader(string meth, IProcScope scope, int tabCount) - { - throw new NotImplementedException(); - } - - public override string ConstructHeader(IProcRealizationScope scope, int tabCount) - { - throw new NotImplementedException(); - } - - public override string ConstructOverridedMethodHeader(IProcScope scope, out int off) - { - throw new NotImplementedException(); - } - - public override string FindExpression(int off, string Text, int line, int col, out KeywordKind keyw) - { - int i = off - 1; - int bound = 0; - bool punkt_sym = false; - keyw = KeywordKind.None; - System.Text.StringBuilder sb = new StringBuilder(); - Stack tokens = new Stack(); - Stack kav = new Stack(); - Stack ugl_skobki = new Stack(); - int num_in_ident = -1; - keyw = TestForKeyword(Text, i); - if (keyw == KeywordKind.Punkt) return ""; - while (i >= bound) - { - bool end = false; - char ch = Text[i]; - if (kav.Count == 0 && (char.IsLetterOrDigit(ch) || ch == '_' || ch == '&' || ch == '\'' || ch == '!')) - { - num_in_ident = i; - if (kav.Count == 0 && tokens.Count == 0) - { - int tmp = i; - if (ch == '\'') - { - i--; - if (kav.Count == 0) - kav.Push('\''); - while (i >= 0) - { - if (Text[i] != '\'') - i--; - else - { - if (i >= 1 && Text[i - 1] == '\'') - i -= 2; - else - break; - } - } - - if (i >= 0) - i--; - } - else - while (i >= 0 && (char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '&' || Text[i] == '!')) - { - i--; - } - while (i >= 0 && (Text[i] == ' ' || char.IsControl(Text[i]) || Text[i] == '}')) - { - if (Text[i] != '}') - i--; - else - { - while (i >= 0 && Text[i] != '{') //propusk kommentariev - i--; - if (i >= 0) - i--; - } - } - if (i >= 0 && (char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '&' || Text[i] == '!')) - { - bound = i + 1; - TestForKeyword(Text, i, ref bound, punkt_sym, out keyw); - for (int j = tmp; j > bound; j--) - { - sb.Insert(0, Text[j]); - } - if (sb.ToString().Trim() == "new") - return ""; - i = bound; - continue; - } - else if (i >= 0 && Text[i] == '\'') return ""; - i = tmp; - } - else - if (ch == '\'') - kav.Push('\''); - sb.Insert(0, ch);//.Append(Text[i]); - } - else if (ch == '.' || ch == '^' || ch == '&' || ch == '?' && IsPunctuation(Text, i + 1)) - { - if (ch == '.' && i >= 1 && Text[i - 1] == '.' && tokens.Count == 0) - end = true; - else if (ch == '?' && i + 1 < Text.Length && Text[i + 1] != '.') - end = true; - else - sb.Insert(0, ch); - if (ch != '.') - punkt_sym = true; - } - else if (ch == '}') - { - if (kav.Count == 0) - { - while (i >= 0 && Text[i] != '{') - { - if (Text[i] != '$')//skip {$ - sb.Insert(0, Text[i]); - i--; - } - if (i < 0) - { - break; - } - else if (Text[i] == '{') - { - sb.Insert(0, '{'); - } - } - else - sb.Insert(0, ch); - } - else if (ch == '{') - { - if (kav.Count == 0) - { - if (keyw == KeywordKind.None) - return sb.ToString(); - sb.Insert(0, ch); - break; - } - else sb.Insert(0, ch); - } - else - switch (ch) - { - case ')': - case ']': - if (kav.Count == 0) - { - string tmps = sb.ToString().Trim(' ', '\r', '\t', '\n'); - if (tmps.Length >= 1 && (char.IsLetter(tmps[0]) || tmps[0] == '_' || tmps[0] == '&' || tmps[0] == '?' || tmps[0] == '!') && tokens.Count == 0) - end = true; - else - tokens.Push(ch); - } - if (!end) - { - sb.Insert(0, ch); - punkt_sym = true; - } - break; - case '>': - if (tokens.Count == 0) - { - int j = i + 1; - - while (j < Text.Length && char.IsWhiteSpace(Text[j])) - j++; - - if (ugl_skobki.Count > 0 || i == off - 1 || j == off && off == Text.Length || j < Text.Length && Text[i - 1] != '-' && (Text[j] == '.' || Text[j] == '(')) - { - ugl_skobki.Push('>'); - sb.Insert(0, ch); - } - else if (i >= 1 && Text[i - 1] == '-') - { - if (!(kav.Count == 0 && tokens.Count == 0)) - sb.Insert(0, ch); - } - else - end = true; - } - else - sb.Insert(0, ch); - break; - case '<': - if (tokens.Count == 0) - { - if (ugl_skobki.Count > 0) - { - ugl_skobki.Pop(); - sb.Insert(0, ch); - } - else - end = true; - } - else - sb.Insert(0, ch); - break; - case '[': - case '(': - case '|': - if (ch == '|' && ((tokens.Count == 0) || (tokens.Peek() == ']') || (tokens.Peek() == ')') || (tokens.Peek() == ','))) - // Закрывающий | - после него (tokens.Pop()) - пусто или ] ) , - { - if (kav.Count == 0) - { - string tmps = sb.ToString().Trim(' ', '\r', '\t', '\n'); - if (tmps.Length >= 1 && (char.IsLetter(tmps[0]) || tmps[0] == '_' || tmps[0] == '&' || tmps[0] == '?' || tmps[0] == '!') && tokens.Count == 0) - end = true; - else - tokens.Push(ch); - } - if (!end) - { - sb.Insert(0, ch); - punkt_sym = true; - } - } - else - { - if (kav.Count == 0) // в т.ч. открывающий | - { - if (tokens.Count > 0) - { - tokens.Pop(); - punkt_sym = true; - sb.Insert(0, ch); - if (ch == '(') - { - int tmp = i--; - /*while (i >= 0 && (char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '&')) - { - i--; - }*/ - while (i >= 0 && (Text[i] == ' ' || char.IsControl(Text[i]) || Text[i] == '}')) - { - if (Text[i] != '}') - i--; - else - { - while (i >= 0 && Text[i] != '{') //propusk kommentariev - i--; - if (i >= 0) - i--; - } - } - if (i >= 0 && (char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '&' || Text[i] == '!' || Text[i] == '?' && IsPunctuation(Text, i + 1))) - { - bound = i + 1; - TestForKeyword(Text, i, ref bound, punkt_sym, out keyw); - if (keyw != KeywordKind.None && tokens.Count == 0) - { - end = true; - } - else bound = 0; - } - else if (i >= 0 && Text[i] == '\'') return ""; - i = tmp; - } - } - else - { - end = true; - if (ch == '[') - { - keyw = KeywordKind.SquareBracket; - } - } - - } - else sb.Insert(0, ch); punkt_sym = true; - } - break; - case '\'': - if (kav.Count == 0) kav.Push(ch); else kav.Pop(); - sb.Insert(0, ch); - punkt_sym = true; break; - default: - if (!(ch == ' ' || char.IsControl(ch))) - { - if (kav.Count == 0) - { - if (ch == ',' && ugl_skobki.Count > 0) - sb.Insert(0, ch); - else - if (tokens.Count == 0) - end = true; - else - sb.Insert(0, ch); - } - else - sb.Insert(0, ch); - } - else - { - if (Text[i] == '\n') - { - bool one_line_comment = false; - int comment_position = -1; - if (CheckForComment(Text, i - 1, out comment_position, out one_line_comment)) - { - if (!one_line_comment) - end = true; - else - { - sb.Insert(0, ch); - i = comment_position; - } - - } - else - sb.Insert(0, ch); - } - else - sb.Insert(0, ch); - } - punkt_sym = true; - break; - } - - if (end) - { - bool one_line_comment = false; - int comment_position = -1; - if (CheckForComment(Text, i, out comment_position, out one_line_comment)) - { - int new_line_ind = sb.ToString().IndexOf('\n'); - if (new_line_ind != -1) sb = sb.Remove(0, new_line_ind + 1); - else sb = sb.Remove(0, sb.Length); - } - break; - } - i--; - } - - //return RemovePossibleKeywords(sb); - if (sb.Length > 0 && sb[sb.Length - 1] == '?') - sb.Remove(sb.Length - 1, 1); - - return sb.ToString().Trim(); - } - - private bool CheckForComment(string Text, int off, out int comment_position, out bool one_line_comment) - { - int i = off; - one_line_comment = false; - comment_position = -1; - Stack kav = new Stack(); - bool is_comm = false; - while (i >= 0 && !is_comm && Text[i] != '\n' && Text[i] != '\r') - { - if (Text[i] == '\'' || Text[i] == '"') - { - if (kav.Count == 0) kav.Push('\''); - else kav.Pop(); - } - else if (Text[i] == '{') - { - if (kav.Count == 0) - { - comment_position = i; - while (i >= 0 && Text[i] != '\'' && Text[i] != '"') - i--; - if (i >= 1 && Text[i - 1] == '$') - return false; - is_comm = true; - return is_comm; - } - } - else if (Text[i] == '}') - { - return false; - } - else if (Text[i] == '#') - if (kav.Count == 0) - { - is_comm = true; - one_line_comment = true; - comment_position = i - 1; - } - - i--; - } - return is_comm; - } - - public override string FindExpressionForMethod(int off, string Text, int line, int col, char pressed_key, ref int num_param) - { - int i = off - 1; - string pattern = null; - int bound = 0; - System.Text.StringBuilder sb = new System.Text.StringBuilder(); - Stack tokens = new Stack(); - Stack kav = new Stack(); - Stack skobki = new Stack(); - Stack ugl_skobki = new Stack(); - bool comma_pressed = pressed_key == ','; - int num_in_ident = -1; - bool punkt_sym = false; - int next; - KeywordKind keyw = TestForKeyword(Text, i); - bool on_brace = false; - if (keyw == KeywordKind.Punkt) - return ""; - try - { - while (i >= bound) - { - bool end = false; - char ch = Text[i]; - if ((char.IsLetterOrDigit(ch) || ch == '_' || ch == '&' || ch == '!') && !isOperator(Text, i, out next)) - { - num_in_ident = i; - if (kav.Count == 0 && tokens.Count == 0) - { - int tmp = i; - while (i >= 0 && (char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '&' || Text[i] == '!') && !isOperator(Text, i, out next)) - { - i--; - } - while (i >= 0 && (Text[i] == ' ' || char.IsControl(Text[i]) || Text[i] == '}')) - { - if (Text[i] != '}') - i--; - else - { - while (i >= 0 && Text[i] != '{') //propusk kommentariev - i--; - if (i >= 0) - i--; - } - } - if (i >= 0 && (char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '&' || Text[i] == '!') && !isOperator(Text, i, out next)) - { - bound = i + 1; - TestForKeyword(Text, i, ref bound, punkt_sym, out keyw); - if (keyw == KeywordKind.New && comma_pressed) - bound = 0; - if (keyw == KeywordKind.Function || keyw == KeywordKind.Constructor || keyw == KeywordKind.Destructor) - return ""; - } - else if (i >= 0 && (Text[i] == '\'' || Text[i] == '"')) return ""; - i = tmp; - } - sb.Insert(0, ch);//.Append(Text[i]); - } - else if (ch == '.') sb.Insert(0, ch); - else if (ch == '}') - { - if (kav.Count == 0) - { - while (i >= 0 && Text[i] != '{') - { - sb.Insert(0, Text[i]); - i--; - } - if (i < 0) - { - break; - } - else if (Text[i] == '{') - { - sb.Insert(0, '{'); - } - } - else - sb.Insert(0, ch); - } - else if (ch == '{') - { - if (kav.Count == 0) - { - sb.Insert(0, ch); - break; - } - else sb.Insert(0, ch); - } - else - switch (ch) - { - case ')': - case ']': - case '>': - // Добавил это условие для питона EVA - if (pressed_key == '(' && ch == ')' && !sb.ToString().Contains(".") && tokens.Count == 0) - { - end = true; - break; - } - if (kav.Count == 0) - { - int j = i + 1; - - while (j < Text.Length && char.IsWhiteSpace(Text[j])) - j++; - if (ch != '>') - tokens.Push(ch); - if (ch == ')') - skobki.Push(ch); - if (tokens.Count > 0 || pressed_key == ',') - sb.Insert(0, ch); - else if (i == off - 1 || j == off && off == Text.Length || ugl_skobki.Count > 0 || j < Text.Length && Text[i - 1] != '-' && (Text[j] == '.' || Text[j] == '(')) - { - tokens.Push(ch); - ugl_skobki.Push(ch); - sb.Insert(0, ch); - } - else - end = true; - } - else - sb.Insert(0, ch); break; - case '[': - case '<': - case '(': - if (kav.Count == 0)//esli ne v kavychkah - { - if (ch == '(') - if (skobki.Count > 0) - skobki.Pop(); - else skobki.Push('('); - //esli byli zakryvaushie tokeny (polagaem, chto skobki korrektny, esli net, to parser v lubom sluchae ne proparsit - if (tokens.Count > 0) - { - if (ch != '<') - tokens.Pop(); - else if (ugl_skobki.Count > 0) - { - tokens.Pop(); - ugl_skobki.Pop(); - } - sb.Insert(0, ch);//dobavljaem k stroke - if (ch == '(') - { - int tmp = i--; - /*while (i >= 0 && (char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '&')) - { - i--; - }*/ - while (i >= 0 && (Text[i] == ' ' || char.IsControl(Text[i]) || Text[i] == '}')) - { - if (Text[i] != '}') - { - i--; - } - else - { - while (i >= 0 && Text[i] != '{') - { - //propusk kommentariev - i--; - } - if (i >= 0) - i--; - } - } - - if (i >= 0 && (char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '&' || Text[i] == '!')) - { - bound = i + 1; - TestForKeyword(Text, i, ref bound, punkt_sym, out keyw); - if (keyw == KeywordKind.New) - bound = 0; - else - if (keyw != KeywordKind.None && tokens.Count == 0) - end = true; - else - bound = 0; - } - else if (i >= 0 && (Text[i] == '\'' || Text[i] == '"')) return ""; - i = tmp; - } - } - else if (ch == '<' || ch == '>') - { - if (tokens.Count > 0 || pressed_key == ',') - sb.Insert(0, ch); - else - end = true; - } - else - if (!comma_pressed) //esli my ne v parametrah - end = true; //zakonchili, tak kak doshli do pervoj skobki - else - { - sb.Remove(0, sb.Length);//doshli do skobki, byla nazhata zapjataja, poetomu udaljaem vse parametry - if (ch == '(') - on_brace = true; - //on_skobka = true; - comma_pressed = false; - } - } - else sb.Insert(0, ch); - break; - case '\'': - case '"': - if (kav.Count == 0) - kav.Push(ch); - else - kav.Pop(); - sb.Insert(0, ch); - if (kav.Count == 0 && tokens.Count == 0) - end = true; - break; - default: - if (!(ch == ' ' || char.IsControl(ch))) - { - if (ch == '^') - sb.Insert(0, ch); - else - if (kav.Count == 0)//ne v kavychkah - { - if (tokens.Count == 0) - { - if (ch != ',' && !comma_pressed) - end = true;//esli ne na zapjatoj i ne v parametrah, to finish - else if (ch == ',' && !comma_pressed) - end = true; - else if (ch == ',' && (pressed_key == '(' || pressed_key == '[')) - end = true; - else - { - sb.Insert(0, ch);//prodolzhaem - if (isOperator(Text, i, out next)) - { - i = next; - continue; - } - } - - } - else - sb.Insert(0, ch);//esli est skobki, prodolzhaem - if (!end && ch == ',') - { - if (tokens.Count == 0) - num_param++;//esli na zapjatoj, uvelichivaem nomer parametra - } - } - else - sb.Insert(0, ch);//prodolzhaem - - } - else - if (Text[i] == '\n') - { - bool one_line_comment = false; - int comment_position = -1; - if (CheckForComment(Text, i - 1, out comment_position, out one_line_comment)) //proverjaem, net li kommenta ne predydushej stroke - { - if (!one_line_comment) - end = true; - else - { - sb.Insert(0, ch); - i = comment_position; - } - - } - else - sb.Insert(0, ch);//a inache vyrazhenie na neskolkih strokah - } - else - sb.Insert(0, ch); - break; - } - - if (end) - { - if (comma_pressed && !on_brace) - return ""; - bool one_line_comment = false; - int comment_position = -1; - if (CheckForComment(Text, i, out comment_position, out one_line_comment))//proverka na kommentarii - { - int new_line_ind = sb.ToString().IndexOf('\n'); - if (new_line_ind != -1) sb = sb.Remove(0, new_line_ind + 1); - else sb = sb.Remove(0, sb.Length); - } - break; - } - i--; - } - if (pressed_key == ',') - num_param++; - } - catch (Exception e) - { - - } - if (pressed_key == ',' && (!on_brace || skobki.Count == 0)) - return ""; - //return RemovePossibleKeywords(sb); - return sb.ToString().Trim(); - } - - private bool isOperator(string Text, int i, out int next) - { - next = i; - if (i >= 3) - { - string op = Text.Substring(i - 2, 3).ToLower().Trim(); - if (op == "and" || op == "div" || op == "mod" || op == "xor") - { - if (!char.IsLetterOrDigit(Text[i - 3]) && Text[i - 3] != '_' && Text[i - 3] != '&' && !(i + 1 < Text.Length && char.IsLetterOrDigit(Text[i + 1]))) - { - next = i - 3; - return true; - } - return false; - } - } - if (i >= 2) - { - string op = Text.Substring(i - 1, 2).ToLower().Trim(); - if (op == "or") - { - if (!char.IsLetterOrDigit(Text[i - 2]) && Text[i - 2] != '_' && Text[i - 2] != '&' && !(i + 1 < Text.Length && char.IsLetterOrDigit(Text[i + 1]))) - { - next = i - 2; - return true; - } - return false; - } - } - return false; - } - - public override string FindExpressionFromAnyPosition(int off, string Text, int line, int col, out KeywordKind keyw, out string expr_without_brackets) - { - int i = off - 1; - - // это например вызов метода без параметров - expr_without_brackets = null; - keyw = KeywordKind.None; - if (i < 0) - return ""; - bool is_char = false; - - // идем в обе стороны от off - System.Text.StringBuilder sb = new System.Text.StringBuilder(); - if (Text[i] != ' ' && (char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '&' || Text[i] == '?' && IsPunctuation(Text, i + 1) || Text[i] == '!')) - { - //sb.Remove(0,sb.Length); - while (i >= 0 && (char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '&' || Text[i] == '?' && IsPunctuation(Text, i + 1) || Text[i] == '!')) - { - //sb.Insert(0,Text[i]);//.Append(Text[i]); - i--; - } - is_char = true; - } - i = off; - if (i < Text.Length && Text[i] != ' ' && (char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '&' || Text[i] == '?' && IsPunctuation(Text, i + 1) || Text[i] == '!')) - { - while (i < Text.Length && (char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '!')) - { - //sb.Append(Text[i]);//.Append(Text[i]); - i++; - } - is_char = true; - } - if (is_char) - { - expr_without_brackets = FindExpression(i, Text, line, col, out keyw); - } - bool is_new = keyw == KeywordKind.New; - bool meth_call = false; - KeywordKind new_keyw = KeywordKind.None; - int j = i; - bool in_comment = false; - bool brackets = false; - while (j < Text.Length) - { - char c = Text[j]; - - if (c == '(' && !in_comment) - { - Stack sk_stack = new Stack(); - in_comment = false; - bool in_kav = false; - sk_stack.Push('('); - j++; - while (j < Text.Length) - { - c = Text[j]; - if (c == '(' && !in_kav) - sk_stack.Push('('); - else - if (c == ')' && !in_kav) - { - if (sk_stack.Count == 0) - { - break; - } - else - { - sk_stack.Pop(); - if (sk_stack.Count == 0) - { - i = j + 1; - meth_call = true; - break; - } - } - } - else if ((c == '\'' || c == '"') && !in_comment) - { - in_kav = !in_kav; - } - else if (c == '{' && !in_kav) - { - in_comment = true; - } - else if (c == '}' && !in_kav) - { - in_comment = false; - } - else if (c == '#' && !in_kav && !in_comment) - { - break; - } - j++; - } - break; - } - else if ((c == '<' || c == '&' && j < Text.Length - 1 && Text[j + 1] == '<') && !in_comment) - { - Stack sk_stack = new Stack(); - if (c == '&') - j++; - sk_stack.Push('<'); - j++; - bool generic = false; - while (j < Text.Length) - { - c = Text[j]; - if (c == '>') - { - sk_stack.Pop(); - if (sk_stack.Count == 0) - { - i = j + 1; - generic = true; - break; - } - } - else if (c == '<') - { - sk_stack.Push('<'); - - } - else if (!char.IsLetterOrDigit(c) && c != '?' && c != '&' && c != '.' && c != ' ' && c != '\t' && c != '\n' && c != ',' && c != '!') - { - break; - } - j++; - } - if (generic) - { - //break; - } - } - else if (c == '[' && !in_comment) - { - brackets = true; - break; - } - else if (c == '{') - { - in_comment = true; - } - else if (c == '}') - { - if (!in_comment) - break; - else - in_comment = false; - } - else if (c == ' ' || c == '\t' || c == '\n' || c == '\r') - { - - } - else - { - if (!in_comment) - break; - } - j++; - } - if (is_new && string.Compare(expr_without_brackets.Trim(' ', '\n', '\t', '\r'), "new", true) == 0 && !meth_call) - { - expr_without_brackets = null; - return null; - } - if (is_char) - { - string ss = FindExpression(i, Text, line, col, out new_keyw); - if (brackets && is_new) - { - int ind = ss.ToLower().IndexOf("new"); - if (ind != -1) - return ss.Substring(ind + 3); - } - if (is_new && ss != null && ss.IndexOf("new") == -1 && ss.IndexOf(":") != -1) - return expr_without_brackets + "(true?" + ss; - return ss; - } - return null; - } - - // TODO: Реализовать EVA - public override string GetArrayDescription(string elementType, int rank) - { - return ""; - } - - public override string GetClassKeyword(class_keyword keyw) - { - switch (keyw) - { - case class_keyword.Class: return "class"; - case class_keyword.TemplateClass: return "template class"; - } - return null; - } - - public override string GetDescription(IBaseScope scope) - { - switch (scope.Kind) - { - case ScopeKind.Type: return GetDescriptionForType(scope as ITypeScope); - case ScopeKind.CompiledType: return GetDescriptionForCompiledType(scope as ICompiledTypeScope); - case ScopeKind.Delegate: return GetDescriptionForDelegate(scope as IProcType); - case ScopeKind.TypeSynonim: return GetSynonimDescription(scope as ITypeSynonimScope); - case ScopeKind.Array: return GetDescriptionForArray(scope as IArrayScope); - case ScopeKind.Diapason: return GetDescriptionForDiapason(scope as IDiapasonScope); - case ScopeKind.File: return GetDescriptionForFile(scope as IFileScope); - case ScopeKind.Pointer: return GetDescriptionForPointer(scope as IPointerScope); - case ScopeKind.Enum: return GetDescriptionForEnum(scope as IEnumScope); - case ScopeKind.Set: return GetDescriptionForSet(scope as ISetScope); - case ScopeKind.ElementScope: return GetDescriptionForElementScope(scope as IElementScope); - case ScopeKind.CompiledField: return GetDescriptionForCompiledField(scope as ICompiledFieldScope); - case ScopeKind.CompiledProperty: return GetDescriptionForCompiledProperty(scope as ICompiledPropertyScope); - case ScopeKind.CompiledMethod: return GetDescriptionForCompiledMethod(scope as ICompiledMethodScope); - case ScopeKind.Namespace: return GetDescriptionForNamespace(scope as INamespaceScope); - case ScopeKind.Procedure: return GetDescriptionForProcedure(scope as IProcScope); - case ScopeKind.CompiledEvent: return GetDescriptionForCompiledEvent(scope as ICompiledEventScope); - case ScopeKind.CompiledConstructor: return GetDescriptionForCompiledConstructor(scope as ICompiledConstructorScope); - case ScopeKind.ShortString: return GetDescriptionForShortString(scope as IShortStringScope); - } - return ""; - } - - protected override string GetFullTypeName(Type ctn, bool no_alias = true) - { - TypeCode tc = Type.GetTypeCode(ctn); - if (ctn.FullName == null && !ctn.IsArray && !ctn.IsGenericTypeDefinition && ctn.IsGenericParameter) - return ctn.Name; - if (!ctn.IsEnum) - { - switch (tc) - { - case TypeCode.Int32: return "int"; - case TypeCode.Double: return "float"; - case TypeCode.Boolean: return "bool"; - case TypeCode.String: return "str"; - case TypeCode.Char: return "char"; - } - /*if (ctn.IsPointer) - if (ctn.FullName == "System.Void*") - return "pointer"; - else - return "^" + GetFullTypeName(ctn.GetElementType());*/ - } - else - return ctn.FullName; - if (!no_alias) - { - if (ctn.Name.Contains("Func`") || ctn.Name.Contains("Predicate`")) - return getLambdaRepresentation(ctn, true, new List()); - else if (ctn.Name.Contains("Action`")) - return getLambdaRepresentation(ctn, false, new List()); - else if (ctn.Name == "IEnumerable`1") - return "sequence of " + GetShortTypeName(ctn.GetGenericArguments()[0], false); - else if (ctn.Name.Contains("Tuple`")) - return get_tuple_string(ctn); - } - int gen_pos = ctn.Name.IndexOf("`"); - if (gen_pos != -1 || ctn.IsGenericType) - { - int len = ctn.GetGenericArguments().Length; - Type[] gen_ps = ctn.GetGenericArguments(); - System.Text.StringBuilder sb = new System.Text.StringBuilder(); - if (gen_pos != -1) - sb.Append(ctn.Namespace + "." + ctn.Name.Substring(0, gen_pos)); - else - sb.Append(ctn.Namespace + "." + ctn.Name); - sb.Append(GenericTypesStartBracket); - for (int i = 0; i < len; i++) - { - sb.Append(gen_ps[i].Name); - if (i < len - 1) - sb.Append(", "); - } - sb.Append(GenericTypesEndBracket); - return sb.ToString(); - } - if (ctn.IsArray) - { - var rank = ctn.GetArrayRank(); - var strrank = rank > 1 ? "[" + new string(',', rank - 1) + "]" : ""; - return $"array{strrank}" + " of " + GetFullTypeName(ctn.GetElementType()); - } - if (ctn == Type.GetType("System.Void*")) return "pointer"; - if (ctn.IsNested) - return ctn.Name; - return ctn.FullName; - } - - public override string GetKeyword(SymbolKind kind) - { - switch (kind) - { - case SymbolKind.Class: return "class"; - case SymbolKind.Enum: return "enum"; - case SymbolKind.Null: return "None"; - } - return ""; - } - - public override string GetShortName(ICompiledConstructorScope scope) - { - return "create"; - } - - public override string GetShortTypeName(Type ctn, bool noalias = true) - { - TypeCode tc = Type.GetTypeCode(ctn); - if (ctn.FullName == null && !ctn.IsArray && !ctn.IsGenericTypeDefinition && ctn.IsGenericParameter) - return ctn.Name; - if (!ctn.IsEnum) - { - switch (tc) - { - case TypeCode.Int32: return "int"; - case TypeCode.Double: return "float"; - case TypeCode.Boolean: return "bool"; - case TypeCode.String: return "str"; - case TypeCode.Char: return "char"; - } - /*if (ctn.IsPointer) - if (ctn.FullName == "System.Void*") - return "pointer"; - else - return "^" + GetShortTypeName(ctn.GetElementType(), noalias);*/ - } - else return ctn.Name; - if (ctn.Name.Contains("`")) - { - if (!noalias) - { - if (ctn.Name.Contains("Func`") || ctn.Name.Contains("Predicate`")) - return getLambdaRepresentation(ctn, true, new List()); - else if (ctn.Name.Contains("Action`")) - return getLambdaRepresentation(ctn, false, new List()); - else if (ctn.Name == "IEnumerable`1") - return "sequence of " + GetShortTypeName(ctn.GetGenericArguments()[0], false); - else if (ctn.Name.Contains("Tuple`")) - return get_tuple_string(ctn); - } - int len = ctn.GetGenericArguments().Length; - System.Text.StringBuilder sb = new System.Text.StringBuilder(); - sb.Append(ctn.Name.Substring(0, ctn.Name.IndexOf('`'))); - sb.Append('['); - if (!noalias) - { - Type[] gen_ps = ctn.GetGenericArguments(); - for (int i = 0; i < len; i++) - { - sb.Append(gen_ps[i].Name); - if (i < len - 1) - sb.Append(", "); - } - } - sb.Append(']'); - return sb.ToString(); - } - if (ctn.IsArray) - { - var rank = ctn.GetArrayRank(); - var strrank = rank > 1 ? "[" + new string(',', rank - 1) + "]" : ""; - return $"array{strrank}" + " of " + GetShortTypeName(ctn.GetElementType()); - } - //if (ctn == Type.GetType("System.Void*")) return PascalABCCompiler.StringConstants.pointer_type_name; - return ctn.Name; - } - - public override string GetSimpleDescription(IBaseScope scope) - { - if (scope == null) - return ""; - switch (scope.Kind) - { - case ScopeKind.Delegate: - case ScopeKind.Array: - case ScopeKind.Diapason: - case ScopeKind.File: - case ScopeKind.Pointer: - case ScopeKind.Enum: - case ScopeKind.Set: - case ScopeKind.ShortString: - if (scope is ITypeScope && (scope as ITypeScope).Aliased) - return scope.Name; - break; - case ScopeKind.TypeSynonim: - case ScopeKind.Type: - if (scope.Name == "biginteger") - return "bigint"; - break; - } - switch (scope.Kind) - { - case ScopeKind.Type: return GetSimpleDescriptionForType(scope as ITypeScope); - case ScopeKind.CompiledType: return GetSimpleDescriptionForCompiledType(scope as ICompiledTypeScope); - case ScopeKind.Delegate: return GetDescriptionForDelegate(scope as IProcType); - case ScopeKind.TypeSynonim: return GetSimpleSynonimDescription(scope as ITypeSynonimScope); - case ScopeKind.Array: return GetDescriptionForArray(scope as IArrayScope); - case ScopeKind.Diapason: return GetDescriptionForDiapason(scope as IDiapasonScope); - case ScopeKind.File: return GetDescriptionForFile(scope as IFileScope); - case ScopeKind.Pointer: return GetDescriptionForPointer(scope as IPointerScope); - case ScopeKind.Enum: return GetDescriptionForEnum(scope as IEnumScope); - case ScopeKind.Set: return GetDescriptionForSet(scope as ISetScope); - case ScopeKind.ElementScope: return GetSimpleDescriptionForElementScope(scope as IElementScope); - case ScopeKind.CompiledField: return GetDescriptionForCompiledField(scope as ICompiledFieldScope); - case ScopeKind.CompiledProperty: return GetDescriptionForCompiledProperty(scope as ICompiledPropertyScope); - case ScopeKind.CompiledMethod: return GetDescriptionForCompiledMethod(scope as ICompiledMethodScope); - case ScopeKind.Namespace: return GetDescriptionForNamespace(scope as INamespaceScope); - case ScopeKind.Procedure: return GetSimpleDescriptionForProcedure(scope as IProcScope); - case ScopeKind.CompiledEvent: return GetDescriptionForCompiledEvent(scope as ICompiledEventScope); - case ScopeKind.CompiledConstructor: return GetDescriptionForCompiledConstructor(scope as ICompiledConstructorScope); - case ScopeKind.ShortString: return GetDescriptionForShortString(scope as IShortStringScope); - case ScopeKind.UnitInterface: return GetDescriptionForModule(scope as IInterfaceUnitScope); - //case ScopeKind.Procedure : return GetDescriptionForProcedure(scope as IProcScope); - } - return ""; - } - - private string GetDescriptionForModule(IInterfaceUnitScope scope) - { - var p = specialModulesAliases.FirstOrDefault(kv => kv.Value == scope.Name); - - if (!p.Equals(default(KeyValuePair))) - return "unit " + p.Key; - - return "unit " + scope.Name; - } - - private string GetDescriptionForFile(IFileScope scope) - { - StringBuilder sb = new StringBuilder(); - sb.Append("file"); - if (scope.ElementType != null) - { - string s = GetSimpleDescription(scope.ElementType); - if (s.Length > 0 && s[0] == '$') s = s.Substring(1, s.Length - 1); - sb.Append("[" + s + "]"); - } - return sb.ToString(); - } - - private string GetDescriptionForSet(ISetScope scope) - { - StringBuilder sb = new StringBuilder(); - - sb.Append("set["); - - if (scope.ElementType != null) - { - string s = GetSimpleDescription(scope.ElementType); - if (s.Length > 0 && s[0] == '$') s = s.Substring(1, s.Length - 1); - sb.Append(s); - } - - sb.Append("]"); - - return sb.ToString(); - } - - private string GetDescriptionForDiapason(IDiapasonScope scope) - { - return scope.Left.ToString() + ".." + scope.Right.ToString(); - } - - private string GetDescriptionForPointer(IPointerScope scope) - { - string s = ""; - if (scope.ElementType != null) - { - s = "^" + GetSimpleDescription(scope.ElementType); - } - else - s = "pointer"; - - return s; - } - - private string GetDescriptionForNamespace(INamespaceScope scope) - { - return "namespace " + scope.Name; - } - - private string GetSimpleSynonimDescription(ITypeSynonimScope scope) - { - return scope.Name; - } - - public override string GetStandardTypeByKeyword(KeywordKind keyw) - { - switch (keyw) - { - case KeywordKind.IntType: return "int"; - case KeywordKind.DoubleType: return "float"; - case KeywordKind.CharType: return "char"; - case KeywordKind.BoolType: return "bool"; - case KeywordKind.StringType: return "str"; - } - return null; - } - - public override string GetStringForChar(char c) - { - return "'" + c.ToString() + "'"; - } - - public override string GetStringForSharpChar(int num) - { - return "#" + num.ToString(); - } - - public override string GetStringForString(string s) - { - return "'" + s + "'"; - } - - public override string GetSynonimDescription(ITypeScope scope) - { - return "type " + scope.Name + GetGenericString(scope.TemplateArguments) + " = " + scope.Description; - } - - public override string GetSynonimDescription(ITypeSynonimScope scope) - { - if (scope.ActType is ICompiledTypeScope && !(scope.ActType as ICompiledTypeScope).Aliased) - return "type " + scope.Name + GetGenericString(scope.TemplateArguments) + " = " + GetSimpleDescriptionForCompiledType(scope.ActType as ICompiledTypeScope, true); - else - return "type " + scope.Name + GetGenericString(scope.TemplateArguments) + " = " + GetSimpleDescription(scope.ActType); - } - - public override string GetSynonimDescription(IProcScope scope) - { - return "type " + scope.Name + " = " + scope.Description; - } - - public override bool IsDefinitionIdentifierAfterKeyword(KeywordKind keyw) - { - if (keyw == KeywordKind.Function || keyw == KeywordKind.Constructor || keyw == KeywordKind.Punkt) - return true; - return false; - } - - public override bool IsMethodCallParameterSeparator(char key) - { - return key == ','; - } - - public override bool IsTypeAfterKeyword(KeywordKind keyw) - { - if (keyw == KeywordKind.Colon) - return true; - return false; - } - - public override KeywordKind TestForKeyword(string Text, int i) - { - StringBuilder sb = new StringBuilder(); - int orig_i = i; - int j = i; - bool in_keyw = false; - while (j >= 0 && Text[j] != '\n') - j--; - Stack kav_stack = new Stack(); - j++; - bool in_format_str = false; - while (j <= i) - { - if (Text[j] == '\'' || Text[j] == '"') - { - if (kav_stack.Count == 0 && !in_keyw) - { - if (j == 0 || Text[j - 1] != '$') - kav_stack.Push('\''); - else - { - in_keyw = false; - in_format_str = true; - } - - } - else if (kav_stack.Count > 0) - kav_stack.Pop(); - } - else if (Text[j] == '{' && kav_stack.Count == 0 && !in_format_str) - in_keyw = true; - else - if (Text[j] == '}') - in_keyw = false; - j++; - } - j = i; - if ((kav_stack.Count != 0 || in_keyw) && !in_format_str) return PascalABCCompiler.Parsers.KeywordKind.Punkt; - if (j >= 0 && Text[j] == '.') return PascalABCCompiler.Parsers.KeywordKind.Punkt; - while (j >= 0) - { - //if (Text[j] == '{') return PascalABCCompiler.Parsers.KeywordKind.Punkt; - if (!in_keyw && (Text[j] == '\'' || Text[j] == '"' || Text[j] == '\n')) - break; - if (Text[j] == '}') - in_keyw = true; - else - if (Text[j] == '#' && !in_keyw) - return PascalABCCompiler.Parsers.KeywordKind.Punkt; - j--; - } - //if (j>= 0 && Text[j] == '\'') return CodeCompletion.KeywordKind.kw_punkt; - while (i >= 0 && (Text[i] == ' ' || char.IsControl(Text[i]))) i--; - if (i >= 0 && Text[i] == ':') return PascalABCCompiler.Parsers.KeywordKind.Colon; - - if (i >= 0 && Text[i] == ',') - { - - while (i >= 0 && Text[i] != '\n') - { - if (char.IsLetterOrDigit(Text[i])) - sb.Insert(0, Text[i]); - else - { - PascalABCCompiler.Parsers.KeywordKind keyw = GetKeywordKind(sb.ToString()); - if (keyw == PascalABCCompiler.Parsers.KeywordKind.Uses) - return PascalABCCompiler.Parsers.KeywordKind.Uses; - else if (keyw == PascalABCCompiler.Parsers.KeywordKind.Var) - return PascalABCCompiler.Parsers.KeywordKind.Var; - else sb.Remove(0, sb.Length); - } - i--; - } - } - else - while (i >= 0 && (char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '!')) - { - sb.Insert(0, Text[i]); - i--; - } - string s = sb.ToString().ToLower(); - - return GetKeywordKind(s); - } - - private string GetDescriptionForType(ITypeScope scope) - { - string template_str = GetTemplateString(scope); - switch (scope.ElemKind) - { - case SymbolKind.Class: - string mod = ""; - if (scope.IsStatic) - mod = "static "; - - if (scope.TopScope != null && scope.TopScope.Name != "" && !scope.TopScope.Name.Contains("$")) - return mod + "class " + scope.TopScope.Name + "." + scope.Name + template_str; - else return mod + "class " + scope.Name + template_str; - - case SymbolKind.Enum: - if (scope.TopScope != null && scope.TopScope.Name != "" && !scope.TopScope.Name.Contains("$")) - return "enum " + scope.TopScope.Name + "." + scope.Name; - else return "enum " + scope.Name; - } - - if (scope.TopScope != null) - return scope.TopScope.Name + "." + scope.Name; - else return scope.Name; - } - - private string GetDescriptionForCompiledType(ICompiledTypeScope scope) - { - string s = GetFullTypeName(scope.CompiledType); - ITypeScope[] instances = scope.GenericInstances; - if (instances.Length > 0) - { - System.Text.StringBuilder sb = new System.Text.StringBuilder(); - int ind = s.IndexOf(GenericTypesStartBracket); - if (ind != -1) sb.Append(s.Substring(0, ind)); - else - sb.Append(s); - sb.Append(GenericTypesStartBracket); - for (int i = 0; i < instances.Length; i++) - { - sb.Append(GetSimpleDescriptionWithoutNamespace(instances[i])); - //sb.Append(instances[i].Name); - if (i < instances.Length - 1) sb.Append(", "); - } - sb.Append(GenericTypesEndBracket); - s = sb.ToString(); - } - - switch (scope.ElemKind) - { - case SymbolKind.Class: - string mod = ""; - if (scope.IsStatic) - mod = "static "; - else - { - if (scope.IsAbstract) - mod = "abstract "; - if (scope.IsFinal) - mod += "sealed "; - } - return mod + "class " + s; - case SymbolKind.Interface: - return "interface " + s; - case SymbolKind.Enum: - return "enum " + s; - case SymbolKind.Delegate: - return "delegate " + s; - case SymbolKind.Struct: - return "record " + s; - case SymbolKind.Type: - return "type " + s; - } - return s; - } + public Dictionary SpecialModulesAliases => specialModulesAliases; } } diff --git a/AdditionalLanguages/SPython/SPythonParserKrylovMovchan/SPythonParser.cs b/AdditionalLanguages/SPython/SPythonParserKrylovMovchan/SPythonParser.cs index ea1d9dd1a..3224de150 100644 --- a/AdditionalLanguages/SPython/SPythonParserKrylovMovchan/SPythonParser.cs +++ b/AdditionalLanguages/SPython/SPythonParserKrylovMovchan/SPythonParser.cs @@ -14,32 +14,13 @@ namespace SPythonParser { public List SyntaxTreeConvertersForIntellisense { get; set; } - public override void Reset() - { - CompilerDirectives = new List(); - - Errors.Clear(); - } - - protected override void PreBuildTree(string FileName) - { - CompilerDirectives = new List(); - - } - protected override syntax_tree_node BuildTreeInNormalMode(string FileName, string Text, bool compilingNotMainProgram, List DefinesList = null) { - Errors.Clear(); - Warnings.Clear(); - syntax_tree_node root = Parse(Text, FileName, false, compilingNotMainProgram, DefinesList); if (Errors.Count > 0) return null; - if (root != null && root is compilation_unit) - (root as compilation_unit).file_name = FileName; - return root; } @@ -114,15 +95,11 @@ namespace SPythonParser protected override syntax_tree_node BuildTreeInSpecialMode(string FileName, string Text, bool compilingNotMainProgram) { - Errors.Clear(); - - return Parse(Text, FileName, compilingNotMainProgram); + return Parse(Text, FileName, compilingNotMainProgram: compilingNotMainProgram); } protected override syntax_tree_node BuildTreeInFormatterMode(string FileName, string Text) { - Errors.Clear(); - return Parse(Text, FileName, true); } diff --git a/CodeCompletion/CodeCompletion.cs b/CodeCompletion/CodeCompletion.cs index d6ecd504e..a9003ff8b 100644 --- a/CodeCompletion/CodeCompletion.cs +++ b/CodeCompletion/CodeCompletion.cs @@ -19,7 +19,6 @@ namespace CodeCompletion public Dictionary docs = new Dictionary(); // static bool parsers_loaded=false; - public IParser Parser; static CodeCompletionController() { @@ -48,6 +47,11 @@ namespace CodeCompletion // static string cur_ext = ".pas"; private static ILanguage currentLanguage; + /// + /// Запоминает язык текущего открытого файла. + /// Если язык файла не поддерживается в системе, то ошибка не выбрасывается, + /// текущему языку присваивается null. + /// public static void SetLanguage(string fileName) { currentLanguage = LanguageProvider.SelectLanguageByExtensionSafe(fileName); @@ -58,14 +62,21 @@ namespace CodeCompletion pabcNamespaces.Clear(); } - // нужно переделать на использование ILanguage EVA - public static IParser CurrentParser + public static ILanguage CurrentLanguage { get { - return currentLanguage?.Parser; + return currentLanguage; } } + + /// + /// Поддерживается ли Intellisense для текущего языка + /// + public static bool IntellisenseAvailable() + { + return CurrentLanguage != null && CurrentLanguage.LanguageIntellisenseSupport != null; + } public DomConverter Compile(string FileName, string Text) { @@ -75,11 +86,9 @@ namespace CodeCompletion ILanguage currentLanguage = LanguageProvider.SelectLanguageByExtension(FileName); - Parser = currentLanguage.Parser; - try { - cu = Parser.GetCompilationUnit(FileName, Text, ErrorsList, Warnings, ParseMode.Normal, false); + cu = currentLanguage.Parser.GetCompilationUnit(FileName, Text, ErrorsList, Warnings, ParseMode.Normal, false); ErrorsList.Clear(); @@ -117,7 +126,7 @@ namespace CodeCompletion string tmp = ParsersHelper.GetModifiedProgramm(Text); if (tmp != null) { - cu = Parser.GetCompilationUnit(FileName, Text, ErrorsList, Warnings, ParseMode.Special, false); + cu = currentLanguage.Parser.GetCompilationUnit(FileName, Text, ErrorsList, Warnings, ParseMode.Special, false); } ErrorsList.Clear(); @@ -179,11 +188,9 @@ namespace CodeCompletion if (currentLanguage == null) return dconv; - Parser = currentLanguage.Parser; - if (Text != null) { - cu = Parser.GetCompilationUnit(FileName, Text, ErrorsList, Warnings, ParseMode.Normal, true); + cu = currentLanguage.Parser.GetCompilationUnit(FileName, Text, ErrorsList, Warnings, ParseMode.Normal, true); } ErrorsList.Clear(); Warnings.Clear(); @@ -212,7 +219,7 @@ namespace CodeCompletion string tmp = ParsersHelper.GetModifiedProgramm(Text); if (tmp != null) { - cu = Parser.GetCompilationUnit(FileName, Text, ErrorsList, Warnings, ParseMode.Special, true); + cu = currentLanguage.Parser.GetCompilationUnit(FileName, Text, ErrorsList, Warnings, ParseMode.Special, true); } ErrorsList.Clear(); @@ -252,31 +259,31 @@ namespace CodeCompletion public PascalABCCompiler.Parsers.KeywordKind GetKeywordKind(string name) { - if (CodeCompletionController.CurrentParser != null) - return CodeCompletionController.CurrentParser.LanguageInformation.GetKeywordKind(name); + if (CodeCompletionController.IntellisenseAvailable()) + return CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.GetKeywordKind(name); return PascalABCCompiler.Parsers.KeywordKind.None; } public bool IsKeyword(string name) { - if (CodeCompletionController.CurrentParser != null) + if (CodeCompletionController.IntellisenseAvailable()) { - return CodeCompletionController.CurrentParser.LanguageInformation.IsKeyword(name); + return CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.IsKeyword(name); } return false; } public List GetKeywords() { - if (CodeCompletionController.CurrentParser != null) - return CodeCompletionController.CurrentParser.LanguageInformation.KeywordsStorage.KeywordsForIntellisenseList; + if (CodeCompletionController.IntellisenseAvailable()) + return CodeCompletionController.CurrentLanguage.LanguageInformation.KeywordsStorage.KeywordsForIntellisenseList; return new List(); } public List GetTypeKeywords() { - if (CodeCompletionController.CurrentParser != null) - return CodeCompletionController.CurrentParser.LanguageInformation.KeywordsStorage.TypeKeywords; + if (CodeCompletionController.IntellisenseAvailable()) + return CodeCompletionController.CurrentLanguage.LanguageInformation.KeywordsStorage.TypeKeywords; return new List(); } diff --git a/CodeCompletion/DomConverter.cs b/CodeCompletion/DomConverter.cs index 9c0ee31d6..905e36d8c 100644 --- a/CodeCompletion/DomConverter.cs +++ b/CodeCompletion/DomConverter.cs @@ -224,7 +224,7 @@ namespace CodeCompletion if (elem == null || !(elem is ProcScope)) { int pos = 0; - string full_name = CodeCompletionController.CurrentParser.LanguageInformation.ConstructOverridedMethodHeader(procs[i], out pos); + string full_name = CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.ConstructOverridedMethodHeader(procs[i], out pos); SymInfo si = new SymInfo(full_name.Substring(pos), procs[i].si.kind, full_name); si.acc_mod = procs[i].si.acc_mod; meths.Add(si); @@ -605,7 +605,7 @@ namespace CodeCompletion } } - string s = CodeCompletionController.CurrentParser.LanguageInformation.GetSimpleDescriptionWithoutNamespace((si as ElementScope).sc as PascalABCCompiler.Parsers.ITypeScope); + string s = CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.GetSimpleDescriptionWithoutNamespace((si as ElementScope).sc as PascalABCCompiler.Parsers.ITypeScope); if (s != out_si.name) out_si.addit_name = s; } @@ -765,7 +765,7 @@ namespace CodeCompletion pos.metadata_type = MetadataType.Class; if (!only_check) { - pos.metadata = CodeCompletionController.CurrentParser.LanguageInformation.GetCompiledTypeRepresentation(cs.CompiledType, cs.CompiledType, ref pos.line, ref pos.column); + pos.metadata = CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.GetCompiledTypeRepresentation(cs.CompiledType, cs.CompiledType, ref pos.line, ref pos.column); Type t = cs.CompiledType; int lines = 0; int ind = pos.metadata.IndexOf('\n'); @@ -787,7 +787,7 @@ namespace CodeCompletion pos.metadata_title = prepare_file_name(cfs.CompiledField.DeclaringType.Name); if (!only_check) { - pos.metadata = CodeCompletionController.CurrentParser.LanguageInformation.GetCompiledTypeRepresentation(cfs.CompiledField.DeclaringType, cfs.CompiledField, ref pos.line, ref pos.column); + pos.metadata = CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.GetCompiledTypeRepresentation(cfs.CompiledField.DeclaringType, cfs.CompiledField, ref pos.line, ref pos.column); Type t = cfs.CompiledField.DeclaringType; int lines = 0; int ind = pos.metadata.IndexOf('\n'); @@ -809,7 +809,7 @@ namespace CodeCompletion pos.metadata_type = MetadataType.Method; if (!only_check) { - pos.metadata = CodeCompletionController.CurrentParser.LanguageInformation.GetCompiledTypeRepresentation(cms.CompiledMethod.DeclaringType, cms.CompiledMethod, ref pos.line, ref pos.column); + pos.metadata = CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.GetCompiledTypeRepresentation(cms.CompiledMethod.DeclaringType, cms.CompiledMethod, ref pos.line, ref pos.column); Type t = cms.CompiledMethod.DeclaringType; int lines = 0; int ind = pos.metadata.IndexOf('\n'); @@ -829,7 +829,7 @@ namespace CodeCompletion pos.metadata_type = MetadataType.Property; if (!only_check) { - pos.metadata = CodeCompletionController.CurrentParser.LanguageInformation.GetCompiledTypeRepresentation((ss as CompiledPropertyScope).CompiledProperty.DeclaringType, (ss as CompiledPropertyScope).CompiledProperty, ref pos.line, ref pos.column); + pos.metadata = CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.GetCompiledTypeRepresentation((ss as CompiledPropertyScope).CompiledProperty.DeclaringType, (ss as CompiledPropertyScope).CompiledProperty, ref pos.line, ref pos.column); Type t = cps.CompiledProperty.DeclaringType; int lines = 0; int ind = pos.metadata.IndexOf('\n'); @@ -849,7 +849,7 @@ namespace CodeCompletion pos.metadata_type = MetadataType.Constructor; if (!only_check) { - pos.metadata = CodeCompletionController.CurrentParser.LanguageInformation.GetCompiledTypeRepresentation(ccs.CompiledConstructor.DeclaringType, ccs.CompiledConstructor, ref pos.line, ref pos.column); + pos.metadata = CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.GetCompiledTypeRepresentation(ccs.CompiledConstructor.DeclaringType, ccs.CompiledConstructor, ref pos.line, ref pos.column); Type t = ccs.CompiledConstructor.DeclaringType; int lines = 0; int ind = pos.metadata.IndexOf('\n'); @@ -869,7 +869,7 @@ namespace CodeCompletion pos.metadata_type = MetadataType.Event; if (!only_check) { - pos.metadata = CodeCompletionController.CurrentParser.LanguageInformation.GetCompiledTypeRepresentation(ces.CompiledEvent.DeclaringType, ces.CompiledEvent, ref pos.line, ref pos.column); + pos.metadata = CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.GetCompiledTypeRepresentation(ces.CompiledEvent.DeclaringType, ces.CompiledEvent, ref pos.line, ref pos.column); Type t = ces.CompiledEvent.DeclaringType; int lines = 0; int ind = pos.metadata.IndexOf('\n'); @@ -1113,7 +1113,7 @@ namespace CodeCompletion if (ps.is_constructor) si = new ElementScope(ps.declaringType); } - string[] description = CodeCompletionController.CurrentParser.LanguageInformation.GetIndexerString(si); + string[] description = CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.GetIndexerString(si); if (description != null) for (int i = 0; i < description.Length; i++) { diff --git a/CodeCompletion/DomSyntaxTreeVisitor.cs b/CodeCompletion/DomSyntaxTreeVisitor.cs index 25278e3e4..875a30040 100644 --- a/CodeCompletion/DomSyntaxTreeVisitor.cs +++ b/CodeCompletion/DomSyntaxTreeVisitor.cs @@ -308,7 +308,7 @@ namespace CodeCompletion var co = new CompilerOptions(); co.SavePCU = false; co.GenerateCode = false; - if (!currentUnitLanguage.ApplySyntaxTreeConvertersForIntellisense) + if (!currentUnitLanguage.LanguageIntellisenseSupport.ApplySyntaxTreeConvertersForIntellisense) co.UnitSyntaxTree = cu; co.SourceFileName = cu.source_context.FileName; co.ForIntellisense = true; @@ -474,9 +474,9 @@ namespace CodeCompletion else if (has_lambdas(_assign.from)) _assign.from.visit(this); else if (_assign.to is ident && cur_scope != null && cur_scope.Name.StartsWith("<>lambda") - && (_assign.to as ident).name.Equals(currentUnitLanguage.LanguageInformation.ResultVariableName, currentUnitLanguage.CaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase)) + && (_assign.to as ident).name.Equals(currentUnitLanguage.LanguageIntellisenseSupport.ResultVariableName, currentUnitLanguage.CaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase)) { - var sc = cur_scope.FindNameOnlyInThisType(currentUnitLanguage.LanguageInformation.ResultVariableName); + var sc = cur_scope.FindNameOnlyInThisType(currentUnitLanguage.LanguageIntellisenseSupport.ResultVariableName); if (sc is ElementScope) { ElementScope es = sc as ElementScope; @@ -935,7 +935,7 @@ namespace CodeCompletion { returned_scope = TypeTable.string_type;//entry_scope.FindName(StringConstants.string_type_name); //cnst_val.prim_val = "'"+_string_const.Value+"'"; - cnst_val.prim_val = this.converter.controller.Parser.LanguageInformation.GetStringForString(_string_const.Value); + cnst_val.prim_val = currentUnitLanguage.LanguageIntellisenseSupport.GetStringForString(_string_const.Value); } public override void visit(expression_list _expression_list) @@ -2094,7 +2094,7 @@ namespace CodeCompletion returned_scope = ps; - var resultName = currentUnitLanguage.LanguageInformation.ResultVariableName; + var resultName = currentUnitLanguage.LanguageIntellisenseSupport.ResultVariableName; if (resultName != null) { ps.AddName(resultName, new ElementScope(new SymInfo(resultName, SymbolKind.Variable, resultName), ps.return_type, ps)); @@ -2170,7 +2170,7 @@ namespace CodeCompletion if (bl.program_code.subnodes.Count == 1) { var ass = bl.program_code.subnodes[0] as assign; - if (ass != null && ass.to is ident && (ass.to as ident).name.Equals(currentUnitLanguage.LanguageInformation.ResultVariableName, currentUnitLanguage.CaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase)) + if (ass != null && ass.to is ident && (ass.to as ident).name.Equals(currentUnitLanguage.LanguageIntellisenseSupport.ResultVariableName, currentUnitLanguage.CaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase)) { if (!(ass.from is nil_const)) { @@ -2262,7 +2262,7 @@ namespace CodeCompletion if (_type_declaration.type_def is class_definition) { class_definition cl_def = _type_declaration.type_def as class_definition; - string key = this.converter.controller.Parser.LanguageInformation.GetClassKeyword(cl_def.keyword); + string key = currentUnitLanguage.LanguageIntellisenseSupport.GetClassKeyword(cl_def.keyword); if (cl_def.attribute == class_attribute.Auto) key = "auto " + key; else if ((cl_def.attribute & class_attribute.Abstract) == class_attribute.Abstract) @@ -2528,7 +2528,7 @@ namespace CodeCompletion var languageUsingStandardUnit = Languages.Facade.LanguageProvider.Instance.Languages.Find(lang => lang.SystemUnitNames.Contains(unitName)); // Пока что добавили возможость грубо отключить добавление NET пространств имен по умолчанию здесь (второе условие нужно, чтобы в стандартные модули языка они тоже не добавлялись) EVA - if (currentUnitLanguage.LanguageInformation.AddStandardNetNamespacesToUserScope && (languageUsingStandardUnit?.LanguageInformation.AddStandardNetNamespacesToUserScope ?? true)) + if (currentUnitLanguage.LanguageIntellisenseSupport.AddStandardNetNamespacesToUserScope && (languageUsingStandardUnit?.LanguageIntellisenseSupport.AddStandardNetNamespacesToUserScope ?? true)) namespaces.AddRange(PascalABCCompiler.NetHelper.NetHelper.GetNamespaces(_as)); InterfaceUnitScope unit_scope = null; @@ -2661,7 +2661,7 @@ namespace CodeCompletion { // добавление стандартных типов можно делать в отдельный фиктивный модуль, как в основном компиляторе // это позволит работать директиве DisableStandardUnits, а также не будет засорять сам стандартный модуль типами EVA - add_standart_types(entry_scope, language.LanguageInformation); + add_standart_types(entry_scope, language.LanguageIntellisenseSupport); if (language == Languages.Facade.LanguageProvider.Instance.MainLanguage) { @@ -2684,7 +2684,7 @@ namespace CodeCompletion } } - if (currentUnitLanguage.ApplySyntaxTreeConvertersForIntellisense) + if (currentUnitLanguage.LanguageIntellisenseSupport.ApplySyntaxTreeConvertersForIntellisense) { foreach (ISyntaxTreeConverter converter in currentUnitLanguage.SyntaxTreeConverters) { @@ -2729,7 +2729,8 @@ namespace CodeCompletion } } - if (currentUnitLanguage.ApplySyntaxTreeConvertersForIntellisense && currentUnitLanguage.LanguageInformation.SyntaxTreeIsConvertedAfterUsedModulesCompilation) + if (currentUnitLanguage.LanguageIntellisenseSupport.ApplySyntaxTreeConvertersForIntellisense + && currentUnitLanguage.LanguageInformation.SyntaxTreeIsConvertedAfterUsedModulesCompilation) { var namesFromUsedUnits = CollectNamesFromUsedUnits(cur_scope); @@ -2889,7 +2890,7 @@ namespace CodeCompletion //get_standart_types(dc.stv); // для SPython, например, не нужно подсказывать стандартные модули в программе, это условие для этого EVA - if (currentUnitLanguage.LanguageInformation.AddStandardUnitNamesToUserScope) + if (currentUnitLanguage.LanguageIntellisenseSupport.AddStandardUnitNamesToUserScope) { entry_scope.AddName(unitName, dc.visitor.entry_scope); } @@ -2907,7 +2908,7 @@ namespace CodeCompletion dc.visitor.entry_scope.InitAssemblies(); entry_scope.AddUsedUnit(dc.visitor.entry_scope); //get_standart_types(dc.stv); - if (currentUnitLanguage.LanguageInformation.AddStandardUnitNamesToUserScope) + if (currentUnitLanguage.LanguageIntellisenseSupport.AddStandardUnitNamesToUserScope) { entry_scope.AddName(unitName, dc.visitor.entry_scope); } @@ -3153,7 +3154,7 @@ namespace CodeCompletion currentUnitLanguage = Languages.Facade.LanguageProvider.Instance.SelectLanguageByName(_program_module.Language); // Пока что добавили возможость грубо отключить добавление NET пространств имен по умолчанию здесь EVA - if (currentUnitLanguage.LanguageInformation.AddStandardNetNamespacesToUserScope) + if (currentUnitLanguage.LanguageIntellisenseSupport.AddStandardNetNamespacesToUserScope) namespaces.AddRange(PascalABCCompiler.NetHelper.NetHelper.GetNamespaces(_as)); //List netScopes = new List(); @@ -3261,7 +3262,7 @@ namespace CodeCompletion } } - if (currentUnitLanguage.ApplySyntaxTreeConvertersForIntellisense) + if (currentUnitLanguage.LanguageIntellisenseSupport.ApplySyntaxTreeConvertersForIntellisense) { foreach (ISyntaxTreeConverter converter in currentUnitLanguage.SyntaxTreeConverters) { @@ -3310,7 +3311,8 @@ namespace CodeCompletion } } - if (currentUnitLanguage.ApplySyntaxTreeConvertersForIntellisense && currentUnitLanguage.LanguageInformation.SyntaxTreeIsConvertedAfterUsedModulesCompilation) + if (currentUnitLanguage.LanguageIntellisenseSupport.ApplySyntaxTreeConvertersForIntellisense + && currentUnitLanguage.LanguageInformation.SyntaxTreeIsConvertedAfterUsedModulesCompilation) { var namesFromUsedUnits = CollectNamesFromUsedUnits(cur_scope); @@ -3387,7 +3389,7 @@ namespace CodeCompletion } } - private void add_standart_types(SymScope cur_scope, ILanguageInformation languageInfo) + private void add_standart_types(SymScope cur_scope, ILanguageIntellisenseSupport languageIntellisenseSupport) { var standardTypesData = new List>() @@ -3415,7 +3417,7 @@ namespace CodeCompletion var keywordKind = data.Item1; var type = data.Item2; - var type_name = languageInfo.GetStandardTypeByKeyword(keywordKind); + var type_name = languageIntellisenseSupport.GetStandardTypeByKeyword(keywordKind); if (type_name != null) { @@ -4647,7 +4649,7 @@ namespace CodeCompletion { returned_scope = TypeTable.char_type;//entry_scope.FindName(StringConstants.char_type_name); if (in_kav) - cnst_val.prim_val = this.converter.controller.Parser.LanguageInformation.GetStringForChar(_char_const.cconst); + cnst_val.prim_val = currentUnitLanguage.LanguageIntellisenseSupport.GetStringForChar(_char_const.cconst); //cnst_val.prim_val = "'"+_char_const.cconst.ToString()+"'"; else cnst_val.prim_val = _char_const.cconst; } @@ -4660,7 +4662,7 @@ namespace CodeCompletion public override void visit(sharp_char_const _sharp_char_const) { returned_scope = TypeTable.char_type;//entry_scope.FindName(StringConstants.char_type_name); - cnst_val.prim_val = this.converter.controller.Parser.LanguageInformation.GetStringForSharpChar(_sharp_char_const.char_num); + cnst_val.prim_val = currentUnitLanguage.LanguageIntellisenseSupport.GetStringForSharpChar(_sharp_char_const.char_num); } private bool in_kav=true; @@ -5788,7 +5790,7 @@ namespace CodeCompletion TypeScope saved_return_type = ps.return_type; if (!disable_lambda_compilation) { - string resultName = currentUnitLanguage.LanguageInformation.ResultVariableName; + string resultName = currentUnitLanguage.LanguageIntellisenseSupport.ResultVariableName; if (awaitedProcType != null) { var invokeMeth = awaitedProcType.FindNameOnlyInType("Invoke") as ProcScope; diff --git a/CodeCompletion/SymTable.cs b/CodeCompletion/SymTable.cs index bd41af464..60c81f323 100644 --- a/CodeCompletion/SymTable.cs +++ b/CodeCompletion/SymTable.cs @@ -388,7 +388,7 @@ namespace CodeCompletion public List GetExtensionMethods(TypeScope ts, string name=null) { - StringComparison comparison = CodeCompletionController.CurrentParser.LanguageInformation.CaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase; + StringComparison comparison = CodeCompletionController.CurrentLanguage.CaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase; if (ts is TypeSynonim) return GetExtensionMethods((ts as TypeSynonim).actType, name); @@ -757,7 +757,7 @@ namespace CodeCompletion SymScope minScope = null; // задает нужна ли модификация алгоритма с обходом всех кандидатов EVA - bool findMinScope = CodeCompletionController.CurrentParser.LanguageInformation.UsesFunctionsOverlappingSourceContext; + bool findMinScope = CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.UsesFunctionsOverlappingSourceContext; SymScope foundScope = FindScopeByLocation(line, column, ref minScope, findMinScope); @@ -974,7 +974,7 @@ namespace CodeCompletion if (o is SymScope) ss = o as SymScope; else - if (!CodeCompletionController.CurrentParser.LanguageInformation.CaseSensitive) + if (!CodeCompletionController.CurrentLanguage.CaseSensitive) ss = (o as List)[0]; else { @@ -996,7 +996,7 @@ namespace CodeCompletion } if (ss == null) return null; TypeScope ts = ss as TypeScope; - if (CodeCompletionController.CurrentParser.LanguageInformation.CaseSensitive) + if (CodeCompletionController.CurrentLanguage.CaseSensitive) { string shortName = System.Text.RegularExpressions.Regex.Replace(name, @"`\d+$", ""); @@ -1021,10 +1021,10 @@ namespace CodeCompletion else if (members != null) foreach (SymScope ss in members) - if (string.Compare(ss.si.name, name, !CodeCompletionController.CurrentParser.LanguageInformation.CaseSensitive) == 0) + if (string.Compare(ss.si.name, name, !CodeCompletionController.CurrentLanguage.CaseSensitive) == 0) if (ss.loc != null && loc != null && check_for_def && cur_line != -1 && cur_col != -1) { - if (string.Compare(ss.loc.file_name, loc.file_name, !CodeCompletionController.CurrentParser.LanguageInformation.CaseSensitive) == 0 && this != ss) + if (string.Compare(ss.loc.file_name, loc.file_name, !CodeCompletionController.CurrentLanguage.CaseSensitive) == 0 && this != ss) { if (IsClassMember(ss) || IsAfterDefinition(ss.loc.begin_line_num, ss.loc.begin_column_num)) { @@ -1068,7 +1068,7 @@ namespace CodeCompletion } else if (members != null) foreach (SymScope ss in members) - if (string.Compare(ss.si.name, name, !CodeCompletionController.CurrentParser.LanguageInformation.CaseSensitive) == 0) + if (string.Compare(ss.si.name, name, !CodeCompletionController.CurrentLanguage.CaseSensitive) == 0) if (ss.loc != null && loc != null && check_for_def && cur_line != -1 && cur_col != -1) { if (string.Compare(ss.loc.file_name, loc.file_name, true) == 0 && this != ss && ss.topScope != this) @@ -1405,7 +1405,7 @@ namespace CodeCompletion public override string ToString() { - return CodeCompletionController.CurrentParser?.LanguageInformation.GetSimpleDescription(this); + return CodeCompletionController.CurrentLanguage?.LanguageIntellisenseSupport.GetSimpleDescription(this); } } @@ -1688,12 +1688,12 @@ namespace CodeCompletion public override void BuildDescription() { - si.description = CodeCompletionController.CurrentParser.LanguageInformation.GetDescription(this); + si.description = CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.GetDescription(this); } public void MakeDescription() { - si.description = CodeCompletionController.CurrentParser?.LanguageInformation.GetDescription(this); + si.description = CodeCompletionController.CurrentLanguage?.LanguageIntellisenseSupport.GetDescription(this); if (!string.IsNullOrEmpty(documentation)) si.description += Environment.NewLine + documentation; } @@ -1799,7 +1799,7 @@ namespace CodeCompletion public override string ToString() { - return CodeCompletionController.CurrentParser?.LanguageInformation.GetSimpleDescription(this); + return CodeCompletionController.CurrentLanguage?.LanguageIntellisenseSupport.GetSimpleDescription(this); } } @@ -2271,7 +2271,7 @@ namespace CodeCompletion public override string ToString() { - return CodeCompletionController.CurrentParser?.LanguageInformation.GetDescription(this); + return CodeCompletionController.CurrentLanguage?.LanguageIntellisenseSupport.GetDescription(this); } } @@ -2608,7 +2608,7 @@ namespace CodeCompletion { if (documentation != null && documentation.Length > 0 && documentation[0] == '-') return; this.si.description = this.ToString(); - this.si.addit_name = CodeCompletionController.CurrentParser?.LanguageInformation.GetShortName(this); + this.si.addit_name = CodeCompletionController.CurrentLanguage?.LanguageIntellisenseSupport.GetShortName(this); if (documentation != null) this.si.description += "\n" + this.documentation; } @@ -2616,7 +2616,7 @@ namespace CodeCompletion { if (documentation != null && documentation.Length > 0 && documentation[0] == '-') return; si.description = ToString(); - si.addit_name = CodeCompletionController.CurrentParser.LanguageInformation.GetShortName(this); + si.addit_name = CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.GetShortName(this); } public void AddTemplateParameter(string name) @@ -2841,8 +2841,8 @@ namespace CodeCompletion public override string ToString() { - simp_descr = CodeCompletionController.CurrentParser?.LanguageInformation.GetSimpleDescription(this); - return CodeCompletionController.CurrentParser?.LanguageInformation.GetDescription(this); + simp_descr = CodeCompletionController.CurrentLanguage?.LanguageIntellisenseSupport.GetSimpleDescription(this); + return CodeCompletionController.CurrentLanguage?.LanguageIntellisenseSupport.GetDescription(this); } } @@ -2934,7 +2934,7 @@ namespace CodeCompletion public override string ToString() { - return CodeCompletionController.CurrentParser.LanguageInformation.GetDescription(this); + return CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.GetDescription(this); } } @@ -3055,7 +3055,7 @@ namespace CodeCompletion public override string ToString() { - return CodeCompletionController.CurrentParser.LanguageInformation.GetDescription(this); + return CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.GetDescription(this); } } @@ -3213,7 +3213,7 @@ namespace CodeCompletion public override string ToString() { - return CodeCompletionController.CurrentParser.LanguageInformation.GetDescription(this); + return CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.GetDescription(this); } } @@ -3915,7 +3915,7 @@ namespace CodeCompletion public override string ToString() { - return CodeCompletionController.CurrentParser?.LanguageInformation.GetDescription(this); + return CodeCompletionController.CurrentLanguage?.LanguageIntellisenseSupport.GetDescription(this); } } @@ -4036,7 +4036,7 @@ namespace CodeCompletion public override string ToString() { //return left.ToString() + ".." + right.ToString(); - return CodeCompletionController.CurrentParser.LanguageInformation.GetDescription(this); + return CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.GetDescription(this); } } @@ -4236,7 +4236,7 @@ namespace CodeCompletion public override string ToString() { - return CodeCompletionController.CurrentParser.LanguageInformation.GetDescription(this); + return CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.GetDescription(this); } } @@ -4314,7 +4314,7 @@ namespace CodeCompletion this.topScope = topScope; if (baseScope == null) { - if (CodeCompletionController.CurrentParser.LanguageInformation.IncludeDotNetEntities) + if (CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.IncludeDotNetEntities) switch (kind) { case SymbolKind.Struct: this.baseScope = TypeTable.get_compiled_type(new SymInfo(typeof(ValueType).Name, SymbolKind.Struct, typeof(ValueType).FullName), typeof(ValueType)); break; @@ -4330,10 +4330,10 @@ namespace CodeCompletion si = new SymInfo("type", kind, "type"); switch (kind) { - case SymbolKind.Struct: si.description = CodeCompletionController.CurrentParser.LanguageInformation.GetKeyword(PascalABCCompiler.Parsers.SymbolKind.Struct); break; - case SymbolKind.Class: si.description = CodeCompletionController.CurrentParser.LanguageInformation.GetKeyword(PascalABCCompiler.Parsers.SymbolKind.Class); break; - case SymbolKind.Interface: si.description = CodeCompletionController.CurrentParser.LanguageInformation.GetKeyword(PascalABCCompiler.Parsers.SymbolKind.Interface); break; - case SymbolKind.Enum: si.description = CodeCompletionController.CurrentParser.LanguageInformation.GetKeyword(PascalABCCompiler.Parsers.SymbolKind.Enum); break; + case SymbolKind.Struct: si.description = CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.GetKeyword(PascalABCCompiler.Parsers.SymbolKind.Struct); break; + case SymbolKind.Class: si.description = CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.GetKeyword(PascalABCCompiler.Parsers.SymbolKind.Class); break; + case SymbolKind.Interface: si.description = CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.GetKeyword(PascalABCCompiler.Parsers.SymbolKind.Interface); break; + case SymbolKind.Enum: si.description = CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.GetKeyword(PascalABCCompiler.Parsers.SymbolKind.Enum); break; } } @@ -4928,17 +4928,17 @@ namespace CodeCompletion public override void BuildDescription() { - si.description = CodeCompletionController.CurrentParser.LanguageInformation.GetDescription(this); + si.description = CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.GetDescription(this); // Случай делегата if (aliased && this is ProcType) - si.description = CodeCompletionController.CurrentParser.LanguageInformation.GetSynonimDescription(this); + si.description = CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.GetSynonimDescription(this); } //opisanie, vysvechivaetsja v zheltkom okoshke public override string GetDescription() { - return CodeCompletionController.CurrentParser.LanguageInformation.GetDescription(this); + return CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.GetDescription(this); } //dubl????? @@ -5471,7 +5471,7 @@ namespace CodeCompletion public override void BuildDescription() { - si.description = CodeCompletionController.CurrentParser?.LanguageInformation.GetDescription(this); + si.description = CodeCompletionController.CurrentLanguage?.LanguageIntellisenseSupport.GetDescription(this); } private SymInfo convertToDefaultNETNames(Type t, SymInfo si) @@ -5772,7 +5772,7 @@ namespace CodeCompletion } if (si.name == null) AssemblyDocCache.AddDescribeToComplete(this.si, ctn); - this.si.name = CodeCompletionController.CurrentParser?.LanguageInformation.GetShortName(this); + this.si.name = CodeCompletionController.CurrentLanguage?.LanguageIntellisenseSupport.GetShortName(this); this.si.kind = get_kind(); this.si.description = GetDescription(); @@ -6131,7 +6131,7 @@ namespace CodeCompletion public override string GetFullName() { //return ctn.FullName; - return CodeCompletionController.CurrentParser.LanguageInformation.GetSimpleDescription(this); + return CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.GetSimpleDescription(this); } public override List GetOverridableMethods() @@ -6420,13 +6420,13 @@ namespace CodeCompletion public override string GetDescription() { - return CodeCompletionController.CurrentParser?.LanguageInformation.GetDescription(this); + return CodeCompletionController.CurrentLanguage?.LanguageIntellisenseSupport.GetDescription(this); } public override SymInfo[] GetNames(ExpressionVisitor ev, PascalABCCompiler.Parsers.KeywordKind keyword, bool called_in_base) { List syms = new List(); - if (!CodeCompletionController.CurrentParser.LanguageInformation.IncludeDotNetEntities) + if (!CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.IncludeDotNetEntities) return syms.ToArray(); MemberInfo[] mis = ctn.GetMembers(BindingFlags.Public | BindingFlags.NonPublic |/*BindingFlags.Instance|*/BindingFlags.Static | BindingFlags.FlattenHierarchy); List constrs = new List(); @@ -6552,7 +6552,7 @@ namespace CodeCompletion public SymInfo[] GetStaticNames() { List syms = new List(); - if (!CodeCompletionController.CurrentParser.LanguageInformation.IncludeDotNetEntities) + if (!CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.IncludeDotNetEntities) return syms.ToArray(); MemberInfo[] mis = ctn.GetMembers(BindingFlags.Public | BindingFlags.NonPublic |/*BindingFlags.Instance|*/BindingFlags.Static | BindingFlags.FlattenHierarchy); @@ -6637,7 +6637,7 @@ namespace CodeCompletion public override SymInfo[] GetNamesAsInObject(ExpressionVisitor ev) { List syms = new List(); - if (!CodeCompletionController.CurrentParser.LanguageInformation.IncludeDotNetEntities) + if (!CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.IncludeDotNetEntities) return syms.ToArray(); MemberInfo[] mis = ctn.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy); List members = new List(); @@ -6719,7 +6719,7 @@ namespace CodeCompletion public override SymInfo[] GetNamesAsInBaseClass(ExpressionVisitor ev, bool is_static) { List syms = new List(); - if (!CodeCompletionController.CurrentParser.LanguageInformation.IncludeDotNetEntities) + if (!CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.IncludeDotNetEntities) return syms.ToArray(); MemberInfo[] mis = ctn.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy); if (ctn.IsInterface) @@ -6841,7 +6841,7 @@ namespace CodeCompletion public override SymInfo[] GetNames() { List syms = new List(); - if (!CodeCompletionController.CurrentParser.LanguageInformation.IncludeDotNetEntities) + if (!CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.IncludeDotNetEntities) return syms.ToArray(); MemberInfo[] mis = ctn.GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy); if (ctn.IsInterface) @@ -6960,7 +6960,7 @@ namespace CodeCompletion public override SymInfo[] GetNamesAsInObject() { List syms = new List(); - if (!CodeCompletionController.CurrentParser.LanguageInformation.IncludeDotNetEntities) + if (!CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.IncludeDotNetEntities) return syms.ToArray(); MemberInfo[] mis = ctn.GetMembers(BindingFlags.Public | BindingFlags.Instance); foreach (MemberInfo mi in mis) @@ -7052,10 +7052,10 @@ namespace CodeCompletion public override List FindOverloadNames(string name) { - StringComparison comparison = CodeCompletionController.CurrentParser.LanguageInformation.CaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase; + StringComparison comparison = CodeCompletionController.CurrentLanguage.CaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase; List names = new List(); - List sil = PascalABCCompiler.NetHelper.NetHelper.FindNameIncludeProtected(ctn, name, CodeCompletionController.CurrentParser.LanguageInformation.CaseSensitive); + List sil = PascalABCCompiler.NetHelper.NetHelper.FindNameIncludeProtected(ctn, name, CodeCompletionController.CurrentLanguage.CaseSensitive); //IEnumerable ext_meths = PascalABCCompiler.NetHelper.NetHelper.GetExtensionMethods(ctn); List pascal_ext_meths = this.GetExtensionMethods(name, this); if (sil != null && sil.Count > 1 && sil.FirstOrDefault().sym_info.semantic_node_type == semantic_node_type.basic_property_node) @@ -7221,10 +7221,10 @@ namespace CodeCompletion public override SymScope FindName(string name) { - StringComparison comparison = CodeCompletionController.CurrentParser.LanguageInformation.CaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase; + StringComparison comparison = CodeCompletionController.CurrentLanguage.CaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase; - List sil = PascalABCCompiler.NetHelper.NetHelper.FindNameIncludeProtected(ctn, name, CodeCompletionController.CurrentParser.LanguageInformation.CaseSensitive); - if (!CodeCompletionController.CurrentParser.LanguageInformation.IncludeDotNetEntities) + List sil = PascalABCCompiler.NetHelper.NetHelper.FindNameIncludeProtected(ctn, name, CodeCompletionController.CurrentLanguage.CaseSensitive); + if (!CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.IncludeDotNetEntities) return null; if (sil == null) { @@ -7371,7 +7371,7 @@ namespace CodeCompletion public override string ToString() { - return CodeCompletionController.CurrentParser.LanguageInformation.GetFullTypeName(this); + return CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.GetFullTypeName(this); } } @@ -7511,7 +7511,7 @@ namespace CodeCompletion public override string ToString() { - return CodeCompletionController.CurrentParser.LanguageInformation.GetDescription(this); + return CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.GetDescription(this); } } @@ -7603,7 +7603,7 @@ namespace CodeCompletion public override string ToString() { //return "event "+ TypeUtility.GetShortTypeName(ei.DeclaringType) +"."+ ei.Name + ": "+sc.ToString(); - return CodeCompletionController.CurrentParser.LanguageInformation.GetDescription(this); + return CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.GetDescription(this); } } @@ -7705,7 +7705,7 @@ namespace CodeCompletion public override string ToString() { - return CodeCompletionController.CurrentParser.LanguageInformation.GetDescription(this); + return CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.GetDescription(this); } } @@ -7786,7 +7786,7 @@ namespace CodeCompletion } if (si.name == null) AssemblyDocCache.AddDescribeToComplete(this.si, mi); - this.si.name = CodeCompletionController.CurrentParser.LanguageInformation.GetShortName(this); + this.si.name = CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.GetShortName(this); this.si.description = this.ToString(); //this.si.describe += "\n"+AssemblyDocCache.GetDocumentation(mi.DeclaringType.Assembly,"M:"+mi.DeclaringType.FullName+"."+mi.Name+GetParamNames()); this.topScope = declaringType; @@ -7831,7 +7831,7 @@ namespace CodeCompletion this.is_global = is_global; if (si.name == null) AssemblyDocCache.AddDescribeToComplete(this.si, mi); - this.si.name = CodeCompletionController.CurrentParser.LanguageInformation.GetShortName(this); + this.si.name = CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.GetShortName(this); this.si.description = this.ToString(); //this.si.describe += "\n"+AssemblyDocCache.GetDocumentation(mi.DeclaringType.Assembly,"M:"+mi.DeclaringType.FullName+"."+mi.Name+GetParamNames()); this.topScope = declaringType; @@ -7997,7 +7997,7 @@ namespace CodeCompletion public override string ToString() { - return CodeCompletionController.CurrentParser.LanguageInformation.GetDescription(this); + return CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.GetDescription(this); } } @@ -8024,7 +8024,7 @@ namespace CodeCompletion foreach (ParameterInfo pi in mi.GetParameters()) parameters.Add(new CompiledParameterScope(new SymInfo(pi.Name, SymbolKind.Parameter, pi.Name), pi)); - this.si.name = CodeCompletionController.CurrentParser.LanguageInformation.GetShortName(this); + this.si.name = CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.GetShortName(this); this.si.description = this.ToString();//+"\n"+AssemblyDocCache.GetDocumentation(mi.DeclaringType.Assembly,"M:"+mi.DeclaringType.FullName+".#ctor"+GetParamNames()); this.topScope = declaringType; if (mi.IsPrivate) @@ -8113,7 +8113,7 @@ namespace CodeCompletion public override string ToString() { - return CodeCompletionController.CurrentParser.LanguageInformation.GetDescription(this); + return CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.GetDescription(this); } } diff --git a/CodeCompletion/Testing.cs b/CodeCompletion/Testing.cs index bb66d6426..18533f389 100644 --- a/CodeCompletion/Testing.cs +++ b/CodeCompletion/Testing.cs @@ -140,7 +140,7 @@ namespace CodeCompletion shouldPositions.Add(new Position(line + 1, col + 1, 0, 0, null)); string expr_without_brackets = null; PascalABCCompiler.Parsers.KeywordKind keyw = PascalABCCompiler.Parsers.KeywordKind.None; - string full_expr = CodeCompletion.CodeCompletionController.CurrentParser.LanguageInformation.FindExpressionFromAnyPosition(pos, content, line, col, out keyw, out expr_without_brackets); + string full_expr = CodeCompletion.CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.FindExpressionFromAnyPosition(pos, content, line, col, out keyw, out expr_without_brackets); List Errors = new List(); var errors = new List(); expression expr = parser.GetExpression("test" + System.IO.Path.GetExtension(FileName), full_expr, errors, new List()); @@ -160,7 +160,7 @@ namespace CodeCompletion shouldPositions.Add(new Position(line + 1, col, 0, 0, null)); string expr_without_brackets = null; PascalABCCompiler.Parsers.KeywordKind keyw = PascalABCCompiler.Parsers.KeywordKind.None; - string full_expr = CodeCompletion.CodeCompletionController.CurrentParser.LanguageInformation.FindExpressionFromAnyPosition(pos, content, line, col, out keyw, out expr_without_brackets); + string full_expr = CodeCompletion.CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.FindExpressionFromAnyPosition(pos, content, line, col, out keyw, out expr_without_brackets); List Errors = new List(); var errors = new List(); expression expr = parser.GetExpression("test" + System.IO.Path.GetExtension(FileName), full_expr, errors, new List()); @@ -239,7 +239,7 @@ namespace CodeCompletion { string expr_without_brackets = null; PascalABCCompiler.Parsers.KeywordKind keyw; - var expr = CodeCompletion.CodeCompletionController.CurrentParser.LanguageInformation.FindExpressionFromAnyPosition(pos, content, line, col, out keyw, out expr_without_brackets); + var expr = CodeCompletion.CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.FindExpressionFromAnyPosition(pos, content, line, col, out keyw, out expr_without_brackets); if (expr == null) expr = expr_without_brackets; var errors = new List(); @@ -253,7 +253,7 @@ namespace CodeCompletion { string expr_without_brackets = null; PascalABCCompiler.Parsers.KeywordKind keyw; - var expr = CodeCompletion.CodeCompletionController.CurrentParser.LanguageInformation.FindExpressionFromAnyPosition(pos, content, line, col, out keyw, out expr_without_brackets); + var expr = CodeCompletion.CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.FindExpressionFromAnyPosition(pos, content, line, col, out keyw, out expr_without_brackets); if (expr == null) expr = expr_without_brackets; var errors = new List(); @@ -270,7 +270,7 @@ namespace CodeCompletion { string expr_without_brackets = null; PascalABCCompiler.Parsers.KeywordKind keyw; - var expr = CodeCompletion.CodeCompletionController.CurrentParser.LanguageInformation.FindExpressionFromAnyPosition(pos, content, line, col, out keyw, out expr_without_brackets); + var expr = CodeCompletion.CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.FindExpressionFromAnyPosition(pos, content, line, col, out keyw, out expr_without_brackets); if (expr == null) expr = expr_without_brackets; var errors = new List(); @@ -345,266 +345,266 @@ namespace CodeCompletion int col=0; PascalABCCompiler.Parsers.KeywordKind keyw; //LanguageIntegration.LanguageIntegrator.ReloadAllParsers(); - IParser parser = LanguageProvider.Instance.MainLanguage.Parser; + var languageIntellisenseSupport = LanguageProvider.Instance.MainLanguage.LanguageIntellisenseSupport; string test_str = "System.Console"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off,test_str,line,col,out keyw); + s = languageIntellisenseSupport.FindExpression(off,test_str,line,col,out keyw); assert(s==test_str); test_str = "System(2+3,-Test34).Console"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off,test_str,line,col,out keyw); + s = languageIntellisenseSupport.FindExpression(off,test_str,line,col,out keyw); assert(s==test_str); test_str = "(a+b*c-e)"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off,test_str,line,col,out keyw); + s = languageIntellisenseSupport.FindExpression(off,test_str,line,col,out keyw); assert(s==test_str); test_str = "a[2,3+b[2-3*b(2*Test-&var,nil)]][56,89,(44)]"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off,test_str,line,col,out keyw); + s = languageIntellisenseSupport.FindExpression(off,test_str,line,col,out keyw); assert(s==test_str); test_str = "begin test"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off,test_str,line,col,out keyw); + s = languageIntellisenseSupport.FindExpression(off,test_str,line,col,out keyw); assert(s.Trim(' ','\n','\t')=="test"); test_str = "begin test[4]"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off,test_str,line,col,out keyw); + s = languageIntellisenseSupport.FindExpression(off,test_str,line,col,out keyw); assert(s.Trim(' ','\n','\t')=="test[4]"); test_str = "begin sin(2)"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off,test_str,line,col,out keyw); + s = languageIntellisenseSupport.FindExpression(off,test_str,line,col,out keyw); assert(s.Trim(' ','\n','\t')=="sin(2)"); test_str = "repeat test"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off,test_str,line,col,out keyw); + s = languageIntellisenseSupport.FindExpression(off,test_str,line,col,out keyw); assert(s.Trim(' ','\n','\t')=="test"); test_str = "while test"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off,test_str,line,col,out keyw); + s = languageIntellisenseSupport.FindExpression(off,test_str,line,col,out keyw); assert(s.Trim(' ','\n','\t')=="test"); test_str = "Test(new Text2, new Text3(2,3),inherited Create).a[new Text3]"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off,test_str,line,col,out keyw); + s = languageIntellisenseSupport.FindExpression(off,test_str,line,col,out keyw); assert(s==test_str); test_str = "Test[new Text2, new Text3(2,3),inherited Create].a[new Text3]"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off,test_str,line,col,out keyw); + s = languageIntellisenseSupport.FindExpression(off,test_str,line,col,out keyw); assert(s==test_str); test_str = "Str(a:2)"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off,test_str,line,col,out keyw); + s = languageIntellisenseSupport.FindExpression(off,test_str,line,col,out keyw); assert(s==test_str); test_str = "Str(a:2:5)"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off,test_str,line,col,out keyw); + s = languageIntellisenseSupport.FindExpression(off,test_str,line,col,out keyw); assert(s==test_str); test_str = "&Begin.&Var.&else.&for"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off,test_str,line,col,out keyw); + s = languageIntellisenseSupport.FindExpression(off,test_str,line,col,out keyw); assert(s==test_str); test_str = "a[s<5]"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off,test_str,line,col,out keyw); + s = languageIntellisenseSupport.FindExpression(off,test_str,line,col,out keyw); assert(s==test_str); test_str = "a[s>5]"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off,test_str,line,col,out keyw); + s = languageIntellisenseSupport.FindExpression(off,test_str,line,col,out keyw); assert(s==test_str); test_str = "a(s<5)"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off,test_str,line,col,out keyw); + s = languageIntellisenseSupport.FindExpression(off,test_str,line,col,out keyw); assert(s==test_str); test_str = "a(s>5)"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off,test_str,line,col,out keyw); + s = languageIntellisenseSupport.FindExpression(off,test_str,line,col,out keyw); assert(s==test_str); test_str = "ab{2 hsdjsdh 'ddd'}"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off,test_str,line,col,out keyw); + s = languageIntellisenseSupport.FindExpression(off,test_str,line,col,out keyw); assert(s==test_str); test_str = "TClass&.abc"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off,test_str,line,col,out keyw); + s = languageIntellisenseSupport.FindExpression(off,test_str,line,col,out keyw); assert(s==test_str); test_str = "TClass&"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off,test_str,line,col,out keyw); + s = languageIntellisenseSupport.FindExpression(off,test_str,line,col,out keyw); assert(s==test_str); test_str = "Test[new {dsdsdsd} Text2, new Text3{sdsd}(2,{''''''} 3),inherited {zez snj }Create]{...}.a{^^}[new Text3]"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off,test_str,line,col,out keyw); + s = languageIntellisenseSupport.FindExpression(off,test_str,line,col,out keyw); assert(s==test_str); test_str = "begin \n \t\t \n bb \t"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off,test_str,line,col,out keyw); + s = languageIntellisenseSupport.FindExpression(off,test_str,line,col,out keyw); assert(s.Trim('\n',' ','\t')=="bb"); test_str = "Test\n[new {dsdsdsd\n} Text2, new \t Text3(2,{''''''} 3),inherited {zez snj }Create]{...}.a{^^}[new Text3]"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off,test_str,line,col,out keyw); + s = languageIntellisenseSupport.FindExpression(off,test_str,line,col,out keyw); assert(s==test_str); test_str = "test//abcd\ntest.abcd"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off,test_str,line,col,out keyw); + s = languageIntellisenseSupport.FindExpression(off,test_str,line,col,out keyw); assert(s.Trim('\n',' ','\t')=="test.abcd"); test_str = "test(2,3) < ppp"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off,test_str,line,col,out keyw); + s = languageIntellisenseSupport.FindExpression(off,test_str,line,col,out keyw); assert(s.Trim('\n',' ','\t')=="ppp"); test_str = "test(2,3) + ppp"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off,test_str,line,col,out keyw); + s = languageIntellisenseSupport.FindExpression(off,test_str,line,col,out keyw); assert(s.Trim('\n',' ','\t')=="ppp"); test_str = "test(2,3) * ppp"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off,test_str,line,col,out keyw); + s = languageIntellisenseSupport.FindExpression(off,test_str,line,col,out keyw); assert(s.Trim('\n',' ','\t')=="ppp"); test_str = "test(2,3) div ppp"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off,test_str,line,col,out keyw); + s = languageIntellisenseSupport.FindExpression(off,test_str,line,col,out keyw); assert(s.Trim('\n',' ','\t')=="ppp"); test_str = "test(2,3) - ppp"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off,test_str,line,col,out keyw); + s = languageIntellisenseSupport.FindExpression(off,test_str,line,col,out keyw); assert(s.Trim('\n',' ','\t')=="ppp"); test_str = "test(2,3) shl ppp"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off,test_str,line,col,out keyw); + s = languageIntellisenseSupport.FindExpression(off,test_str,line,col,out keyw); assert(s.Trim('\n',' ','\t')=="ppp"); test_str = "(s as string)"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off,test_str,line,col,out keyw); + s = languageIntellisenseSupport.FindExpression(off,test_str,line,col,out keyw); assert(s==test_str); test_str = "begin (s as string)"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off,test_str,line,col,out keyw); + s = languageIntellisenseSupport.FindExpression(off,test_str,line,col,out keyw); assert(s.Trim('\n',' ','\t')=="(s as string)"); test_str = "test(2,3) shr ppp"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off,test_str,line,col,out keyw); + s = languageIntellisenseSupport.FindExpression(off,test_str,line,col,out keyw); assert(s.Trim('\n',' ','\t')=="ppp"); test_str = "test(2,3) > ppp"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off,test_str,line,col,out keyw); + s = languageIntellisenseSupport.FindExpression(off,test_str,line,col,out keyw); assert(s.Trim('\n',' ','\t')=="ppp"); test_str = "test(2,3) or ppp"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off,test_str,line,col,out keyw); + s = languageIntellisenseSupport.FindExpression(off,test_str,line,col,out keyw); assert(s.Trim('\n',' ','\t')=="ppp"); test_str = "test(2,3) and ppp"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off,test_str,line,col,out keyw); + s = languageIntellisenseSupport.FindExpression(off,test_str,line,col,out keyw); assert(s.Trim('\n',' ','\t')=="ppp"); test_str = "test(2,3) xor ppp"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off,test_str,line,col,out keyw); + s = languageIntellisenseSupport.FindExpression(off,test_str,line,col,out keyw); assert(s.Trim('\n',' ','\t')=="ppp"); test_str = "test(2,3) mod ppp"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off,test_str,line,col,out keyw); + s = languageIntellisenseSupport.FindExpression(off,test_str,line,col,out keyw); assert(s.Trim('\n',' ','\t')=="ppp"); test_str = "typeof(char)"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off,test_str,line,col,out keyw); + s = languageIntellisenseSupport.FindExpression(off,test_str,line,col,out keyw); assert(s.Trim('\n',' ','\t')==test_str); test_str = "sizeof(char)"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off,test_str,line,col,out keyw); + s = languageIntellisenseSupport.FindExpression(off,test_str,line,col,out keyw); assert(s.Trim('\n',' ','\t')==test_str); test_str = "()->(obj as string).Trim"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off, test_str, line, col, out keyw); + s = languageIntellisenseSupport.FindExpression(off, test_str, line, col, out keyw); assert(s.Trim('\n', ' ', '\t') == "(obj as string).Trim"); test_str = "Seq(0)\n.f1//комментарий\n.Print"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off, test_str, line, col, out keyw); + s = languageIntellisenseSupport.FindExpression(off, test_str, line, col, out keyw); assert(s.Trim('\n', ' ', '\t') == "Seq(0)\n.f1\n.Print"); test_str = "$'is {a}'"; off = test_str.Length-2; - s = parser.LanguageInformation.FindExpression(off, test_str, line, col, out keyw); + s = languageIntellisenseSupport.FindExpression(off, test_str, line, col, out keyw); assert(s.Trim('\n', ' ', '\t') == "a"); test_str = "seq1.Where(i ->(i = 1) or (i = 2)).JoinIntoString"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off, test_str, line, col, out keyw); + s = languageIntellisenseSupport.FindExpression(off, test_str, line, col, out keyw); assert(s.Trim('\n', ' ', '\t') == "seq1.Where(i ->(i = 1) or (i = 2)).JoinIntoString"); test_str = "$'{f1(s0)}'"; off = test_str.Length - 3; - s = parser.LanguageInformation.FindExpression(off, test_str, line, col, out keyw); + s = languageIntellisenseSupport.FindExpression(off, test_str, line, col, out keyw); assert(s.Trim('\n', ' ', '\t') == "s0"); test_str = "f1&\n.ToString"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off, test_str, line, col, out keyw); + s = languageIntellisenseSupport.FindExpression(off, test_str, line, col, out keyw); assert(s.Trim('\n', ' ', '\t') == test_str); test_str = "a[2:]"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off, test_str, line, col, out keyw); + s = languageIntellisenseSupport.FindExpression(off, test_str, line, col, out keyw); assert(s.Trim('\n', ' ', '\t') == test_str); test_str = "' '' '"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off, test_str, line, col, out keyw); + s = languageIntellisenseSupport.FindExpression(off, test_str, line, col, out keyw); assert(s.Trim('\n', ' ', '\t') == test_str); test_str = "' '' '' '"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off, test_str, line, col, out keyw); + s = languageIntellisenseSupport.FindExpression(off, test_str, line, col, out keyw); assert(s.Trim('\n', ' ', '\t') == test_str); test_str = "' ' '"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off, test_str, line, col, out keyw); + s = languageIntellisenseSupport.FindExpression(off, test_str, line, col, out keyw); assert(s.Trim('\n', ' ', '\t') == ""); test_str = "(2..4)"; off = test_str.Length; - s = parser.LanguageInformation.FindExpression(off, test_str, line, col, out keyw); + s = languageIntellisenseSupport.FindExpression(off, test_str, line, col, out keyw); assert(s.Trim('\n', ' ', '\t') == test_str); @@ -613,228 +613,228 @@ namespace CodeCompletion //testirovanie nazhatija skobki test_str = "writeln"; off = test_str.Length; - s = parser.LanguageInformation.FindExpressionForMethod(off,test_str,line,col,'(',ref num_param); + s = languageIntellisenseSupport.FindExpressionForMethod(off,test_str,line,col,'(',ref num_param); assert(s == test_str); assert(num_param==0); test_str = "Console.WriteLine"; off = test_str.Length; - s = parser.LanguageInformation.FindExpressionForMethod(off,test_str,line,col,'(',ref num_param); + s = languageIntellisenseSupport.FindExpressionForMethod(off,test_str,line,col,'(',ref num_param); assert(s == test_str); assert(num_param==0); test_str = "begin writeln"; off = test_str.Length; - s = parser.LanguageInformation.FindExpressionForMethod(off,test_str,line,col,'(',ref num_param); + s = languageIntellisenseSupport.FindExpressionForMethod(off,test_str,line,col,'(',ref num_param); assert(s.Trim('\n',' ','\t') == "writeln"); assert(num_param==0); test_str = "Console{dsdsdsd}.WriteLine{''''''sds}"; off = test_str.Length; - s = parser.LanguageInformation.FindExpressionForMethod(off,test_str,line,col,'(',ref num_param); + s = languageIntellisenseSupport.FindExpressionForMethod(off,test_str,line,col,'(',ref num_param); assert(s == test_str); assert(num_param==0); test_str = "test(2,3).mmm"; off = test_str.Length; - s = parser.LanguageInformation.FindExpressionForMethod(off,test_str,line,col,'(',ref num_param); + s = languageIntellisenseSupport.FindExpressionForMethod(off,test_str,line,col,'(',ref num_param); assert(s == test_str); assert(num_param==0); test_str = "test[2<3].a"; off = test_str.Length; - s = parser.LanguageInformation.FindExpressionForMethod(off,test_str,line,col,'(',ref num_param); + s = languageIntellisenseSupport.FindExpressionForMethod(off,test_str,line,col,'(',ref num_param); assert(s == test_str); assert(num_param==0); test_str = "test[2>3].a"; off = test_str.Length; - s = parser.LanguageInformation.FindExpressionForMethod(off,test_str,line,col,'(',ref num_param); + s = languageIntellisenseSupport.FindExpressionForMethod(off,test_str,line,col,'(',ref num_param); assert(s == test_str); assert(num_param==0); test_str = "test[2>3] .a"; off = test_str.Length; - s = parser.LanguageInformation.FindExpressionForMethod(off,test_str,line,col,'(',ref num_param); + s = languageIntellisenseSupport.FindExpressionForMethod(off,test_str,line,col,'(',ref num_param); assert(s == test_str); assert(num_param==0); test_str = "23 < test"; off = test_str.Length; - s = parser.LanguageInformation.FindExpressionForMethod(off,test_str,line,col,'(',ref num_param); + s = languageIntellisenseSupport.FindExpressionForMethod(off,test_str,line,col,'(',ref num_param); assert(s.Trim('\n',' ','\t') == "test"); assert(num_param==0); test_str = "23 > test"; off = test_str.Length; - s = parser.LanguageInformation.FindExpressionForMethod(off,test_str,line,col,'(',ref num_param); + s = languageIntellisenseSupport.FindExpressionForMethod(off,test_str,line,col,'(',ref num_param); assert(s.Trim('\n',' ','\t') == "test"); assert(num_param==0); test_str = "(a(i = 1) or (i = 2)).JoinIntoString"); test_str = "seq1.Where(i ->(i = '1') or (i = '2')).JoinIntoString"; off = test_str.Length; - s = parser.LanguageInformation.FindExpressionForMethod(off, test_str, line, col, '(', ref num_param); + s = languageIntellisenseSupport.FindExpressionForMethod(off, test_str, line, col, '(', ref num_param); assert(s.Trim('\n', ' ', '\t') == "seq1.Where(i ->(i = '1') or (i = '2')).JoinIntoString"); test_str = "f1&"; off = test_str.Length; - s = parser.LanguageInformation.FindExpressionForMethod(off, test_str, line, col, '(', ref num_param); + s = languageIntellisenseSupport.FindExpressionForMethod(off, test_str, line, col, '(', ref num_param); assert(s.Trim('\n', ' ', '\t') == "f1&"); test_str = "f1&"; off = test_str.Length; - s = parser.LanguageInformation.FindExpressionForMethod(off, test_str, line, col, '(', ref num_param); + s = languageIntellisenseSupport.FindExpressionForMethod(off, test_str, line, col, '(', ref num_param); assert(s.Trim('\n', ' ', '\t') == "f1&"); test_str = "&var.&uses.&procedure"; off = test_str.Length; - s = parser.LanguageInformation.FindExpressionForMethod(off,test_str,line,col,'(',ref num_param); + s = languageIntellisenseSupport.FindExpressionForMethod(off,test_str,line,col,'(',ref num_param); assert(s == test_str); test_str = "s.OrderBy"; off = test_str.Length; - s = parser.LanguageInformation.FindExpressionForMethod(off, test_str, line, col, '(', ref num_param); + s = languageIntellisenseSupport.FindExpressionForMethod(off, test_str, line, col, '(', ref num_param); assert(s == test_str); test_str = "f1&\n.ToString"; off = test_str.Length; - s = parser.LanguageInformation.FindExpressionForMethod(off, test_str, line, col, '(', ref num_param); + s = languageIntellisenseSupport.FindExpressionForMethod(off, test_str, line, col, '(', ref num_param); assert(s.Trim('\n', ' ', '\t') == "f1&\n.ToString"); test_str = "begin ''.PadLeft"; off = test_str.Length; - s = parser.LanguageInformation.FindExpressionForMethod(off, test_str, line, col, '(', ref num_param); + s = languageIntellisenseSupport.FindExpressionForMethod(off, test_str, line, col, '(', ref num_param); assert(s.Trim('\n', ' ', '\t') == "''.PadLeft"); test_str = "begin var s := ''.PadLeft"; off = test_str.Length; - s = parser.LanguageInformation.FindExpressionForMethod(off, test_str, line, col, '(', ref num_param); + s = languageIntellisenseSupport.FindExpressionForMethod(off, test_str, line, col, '(', ref num_param); assert(s.Trim('\n', ' ', '\t') == "''.PadLeft"); test_str = "begin \n var s := ''.PadLeft"; off = test_str.Length; - s = parser.LanguageInformation.FindExpressionForMethod(off, test_str, line, col, '(', ref num_param); + s = languageIntellisenseSupport.FindExpressionForMethod(off, test_str, line, col, '(', ref num_param); assert(s.Trim('\n', ' ', '\t') == "''.PadLeft"); test_str = "writeln(23);\n ''.PadLeft"; off = test_str.Length; - s = parser.LanguageInformation.FindExpressionForMethod(off, test_str, line, col, '(', ref num_param); + s = languageIntellisenseSupport.FindExpressionForMethod(off, test_str, line, col, '(', ref num_param); assert(s.Trim('\n', ' ', '\t') == "''.PadLeft"); test_str = "writeln(23);\n ''.PadLeft(2).ToString"; off = test_str.Length; - s = parser.LanguageInformation.FindExpressionForMethod(off, test_str, line, col, '(', ref num_param); + s = languageIntellisenseSupport.FindExpressionForMethod(off, test_str, line, col, '(', ref num_param); assert(s.Trim('\n', ' ', '\t') == "''.PadLeft(2).ToString"); @@ -843,129 +843,129 @@ namespace CodeCompletion test_str = ";test(3,aa.bb"; off = test_str.Length; num_param = 1; - s = parser.LanguageInformation.FindExpressionForMethod(off,test_str,line,col,',',ref num_param); + s = languageIntellisenseSupport.FindExpressionForMethod(off,test_str,line,col,',',ref num_param); assert(s == "test"); assert(num_param == 3); test_str = ";test(a[2,3,4],sin(2+3),aa.bb"; off = test_str.Length; num_param = 1; - s = parser.LanguageInformation.FindExpressionForMethod(off,test_str,line,col,',',ref num_param); + s = languageIntellisenseSupport.FindExpressionForMethod(off,test_str,line,col,',',ref num_param); assert(s == "test"); assert(num_param == 4); test_str = "Console.WriteLine(a[2,3,4]{ds},[1,2+3,5,'aa)'],sin(2+3,4+f(3)),aa.bb,(23)"; off = test_str.Length; num_param = 1; - s = parser.LanguageInformation.FindExpressionForMethod(off,test_str,line,col,',',ref num_param); + s = languageIntellisenseSupport.FindExpressionForMethod(off,test_str,line,col,',',ref num_param); assert(s == "Console.WriteLine"); assert(num_param == 6); test_str = "Console.WriteLine(new TClass(2,3"; off = test_str.Length; num_param = 1; - s = parser.LanguageInformation.FindExpressionForMethod(off,test_str,line,col,',',ref num_param); + s = languageIntellisenseSupport.FindExpressionForMethod(off,test_str,line,col,',',ref num_param); assert(s == "new TClass"); assert(num_param == 3); test_str = "Console.WriteLine(new{} TClass(2+f(2,[]),3"; off = test_str.Length; num_param = 1; - s = parser.LanguageInformation.FindExpressionForMethod(off,test_str,line,col,',',ref num_param); + s = languageIntellisenseSupport.FindExpressionForMethod(off,test_str,line,col,',',ref num_param); assert(s == "new{} TClass"); assert(num_param == 3); test_str = "begin \n\t sin("; off = test_str.Length; num_param = 1; - s = parser.LanguageInformation.FindExpressionForMethod(off,test_str,line,col,',',ref num_param); + s = languageIntellisenseSupport.FindExpressionForMethod(off,test_str,line,col,',',ref num_param); assert(s.Trim(' ','\n','\t') == "sin"); assert(num_param == 2); test_str = "sin(2)"; off = test_str.Length; num_param = 1; - s = parser.LanguageInformation.FindExpressionForMethod(off,test_str,line,col,',',ref num_param); + s = languageIntellisenseSupport.FindExpressionForMethod(off,test_str,line,col,',',ref num_param); assert(s.Trim(' ','\n','\t') == ""); test_str = "begin f(2)+sin(2,3,4)"; off = test_str.Length; num_param = 1; - s = parser.LanguageInformation.FindExpressionForMethod(off,test_str,line,col,',',ref num_param); + s = languageIntellisenseSupport.FindExpressionForMethod(off,test_str,line,col,',',ref num_param); assert(s.Trim(' ','\n','\t') == ""); test_str = ";\n [sin(f(3)),a[3]"; off = test_str.Length; num_param = 1; - s = parser.LanguageInformation.FindExpressionForMethod(off,test_str,line,col,',',ref num_param); + s = languageIntellisenseSupport.FindExpressionForMethod(off,test_str,line,col,',',ref num_param); assert(s.Trim(' ','\n','\t') == ""); test_str = ";\n (sin)"; off = test_str.Length; num_param = 1; - s = parser.LanguageInformation.FindExpressionForMethod(off,test_str,line,col,',',ref num_param); + s = languageIntellisenseSupport.FindExpressionForMethod(off,test_str,line,col,',',ref num_param); assert(s.Trim(' ','\n','\t') == ""); test_str = "max(2<3"; off = test_str.Length; num_param = 1; - s = parser.LanguageInformation.FindExpressionForMethod(off,test_str,line,col,',',ref num_param); + s = languageIntellisenseSupport.FindExpressionForMethod(off,test_str,line,col,',',ref num_param); assert(s.Trim(' ','\n','\t') == "max"); assert(num_param == 2); test_str = "max(2>3"; off = test_str.Length; num_param = 1; - s = parser.LanguageInformation.FindExpressionForMethod(off,test_str,line,col,',',ref num_param); + s = languageIntellisenseSupport.FindExpressionForMethod(off,test_str,line,col,',',ref num_param); assert(s.Trim(' ','\n','\t') == "max"); assert(num_param == 2); test_str = "max(Test&(2,3)"; off = test_str.Length; num_param = 1; - s = parser.LanguageInformation.FindExpressionForMethod(off,test_str,line,col,',',ref num_param); + s = languageIntellisenseSupport.FindExpressionForMethod(off,test_str,line,col,',',ref num_param); assert(s.Trim(' ','\n','\t') == "max"); assert(num_param == 2); test_str = "new TextABC(60,110,110,'Hello!',RGB(x"; off = test_str.Length; num_param = 1; - s = parser.LanguageInformation.FindExpressionForMethod(off,test_str,line,col,',',ref num_param); + s = languageIntellisenseSupport.FindExpressionForMethod(off,test_str,line,col,',',ref num_param); assert(s.Trim(' ','\n','\t') == "RGB"); assert(num_param == 2); test_str = "new TextABC(60,110,110,'Hello!',new RGB(x"; off = test_str.Length; num_param = 1; - s = parser.LanguageInformation.FindExpressionForMethod(off,test_str,line,col,',',ref num_param); + s = languageIntellisenseSupport.FindExpressionForMethod(off,test_str,line,col,',',ref num_param); assert(s.Trim(' ','\n','\t') == "new RGB"); assert(num_param == 2); test_str = "new TextABC(new RGB(x"; off = test_str.Length; num_param = 1; - s = parser.LanguageInformation.FindExpressionForMethod(off,test_str,line,col,',',ref num_param); + s = languageIntellisenseSupport.FindExpressionForMethod(off,test_str,line,col,',',ref num_param); assert(s.Trim(' ','\n','\t') == "new RGB"); assert(num_param == 2); test_str = "new TextABC(new RGB(x,(2)"; off = test_str.Length; num_param = 1; - s = parser.LanguageInformation.FindExpressionForMethod(off,test_str,line,col,',',ref num_param); + s = languageIntellisenseSupport.FindExpressionForMethod(off,test_str,line,col,',',ref num_param); assert(s.Trim(' ','\n','\t') == "new RGB"); assert(num_param == 3); test_str = "new TextABC(new RGB(x(2)"; off = test_str.Length; num_param = 1; - s = parser.LanguageInformation.FindExpressionForMethod(off,test_str,line,col,',',ref num_param); + s = languageIntellisenseSupport.FindExpressionForMethod(off,test_str,line,col,',',ref num_param); assert(s.Trim(' ','\n','\t') == "new RGB"); assert(num_param == 2); test_str = "Power(10 div 2"; off = test_str.Length; num_param = 1; - s = parser.LanguageInformation.FindExpressionForMethod(off, test_str, line, col, ',', ref num_param); + s = languageIntellisenseSupport.FindExpressionForMethod(off, test_str, line, col, ',', ref num_param); assert(s.Trim(' ', '\n', '\t') == "Power"); assert(num_param == 2); @@ -975,77 +975,77 @@ namespace CodeCompletion //mouse hover test_str = "sin(2)"; off = 1; - s = parser.LanguageInformation.FindExpressionFromAnyPosition(off,test_str,line,col,out keyw,out str); + s = languageIntellisenseSupport.FindExpressionFromAnyPosition(off,test_str,line,col,out keyw,out str); assert(s.Trim('\n',' ','\t')=="sin(2)"); test_str = "sin(2,3,4)"; off = 1; - s = parser.LanguageInformation.FindExpressionFromAnyPosition(off,test_str,line,col,out keyw,out str); + s = languageIntellisenseSupport.FindExpressionFromAnyPosition(off,test_str,line,col,out keyw,out str); assert(s.Trim('\n',' ','\t')=="sin(2,3,4)"); test_str = "sin {sdsd'} (2,3,4)"; off = 1; - s = parser.LanguageInformation.FindExpressionFromAnyPosition(off,test_str,line,col,out keyw,out str); + s = languageIntellisenseSupport.FindExpressionFromAnyPosition(off,test_str,line,col,out keyw,out str); assert(s.Trim('\n',' ','\t')==test_str); test_str = "sin (df,'3)+2','{')"; off = 1; - s = parser.LanguageInformation.FindExpressionFromAnyPosition(off,test_str,line,col,out keyw,out str); + s = languageIntellisenseSupport.FindExpressionFromAnyPosition(off,test_str,line,col,out keyw,out str); assert(s.Trim('\n',' ','\t')==test_str); test_str = "cos()"; off = 1; - s = parser.LanguageInformation.FindExpressionFromAnyPosition(off,test_str,line,col,out keyw,out str); + s = languageIntellisenseSupport.FindExpressionFromAnyPosition(off,test_str,line,col,out keyw,out str); assert(s.Trim('\n',' ','\t')==test_str); test_str = "cos{()}"; off = 1; - s = parser.LanguageInformation.FindExpressionFromAnyPosition(off,test_str,line,col,out keyw,out str); + s = languageIntellisenseSupport.FindExpressionFromAnyPosition(off,test_str,line,col,out keyw,out str); assert(s.Trim('\n',' ','\t')=="cos"); test_str = "cos//()"; off = 1; - s = parser.LanguageInformation.FindExpressionFromAnyPosition(off,test_str,line,col,out keyw,out str); + s = languageIntellisenseSupport.FindExpressionFromAnyPosition(off,test_str,line,col,out keyw,out str); assert(s.Trim('\n',' ','\t')=="cos"); test_str = "cos(//)"; off = 1; - s = parser.LanguageInformation.FindExpressionFromAnyPosition(off,test_str,line,col,out keyw,out str); + s = languageIntellisenseSupport.FindExpressionFromAnyPosition(off,test_str,line,col,out keyw,out str); assert(s.Trim('\n',' ','\t')=="cos"); test_str = "cos('//')"; off = 1; - s = parser.LanguageInformation.FindExpressionFromAnyPosition(off,test_str,line,col,out keyw,out str); + s = languageIntellisenseSupport.FindExpressionFromAnyPosition(off,test_str,line,col,out keyw,out str); assert(s.Trim('\n',' ','\t')==test_str); test_str = "cos({//})"; off = 1; - s = parser.LanguageInformation.FindExpressionFromAnyPosition(off,test_str,line,col,out keyw,out str); + s = languageIntellisenseSupport.FindExpressionFromAnyPosition(off,test_str,line,col,out keyw,out str); assert(s.Trim('\n',' ','\t')==test_str); test_str = "cos(Math.Cos(x)+1)"; off = 1; - s = parser.LanguageInformation.FindExpressionFromAnyPosition(off,test_str,line,col,out keyw,out str); + s = languageIntellisenseSupport.FindExpressionFromAnyPosition(off,test_str,line,col,out keyw,out str); assert(s.Trim('\n',' ','\t')==test_str); test_str = "new t1(2)"; off = 5; - s = parser.LanguageInformation.FindExpressionFromAnyPosition(off, test_str, line, col, out keyw, out str); + s = languageIntellisenseSupport.FindExpressionFromAnyPosition(off, test_str, line, col, out keyw, out str); assert(s.Trim('\n', ' ', '\t') == "new t1(2)"); test_str = "new t1>(2)"; off = 5; - s = parser.LanguageInformation.FindExpressionFromAnyPosition(off, test_str, line, col, out keyw, out str); + s = languageIntellisenseSupport.FindExpressionFromAnyPosition(off, test_str, line, col, out keyw, out str); assert(s.Trim('\n', ' ', '\t') == "new t1>(2)"); test_str = "t1&.x"; off = test_str.Length; - s = parser.LanguageInformation.FindExpressionFromAnyPosition(off, test_str, line, col, out keyw, out str); + s = languageIntellisenseSupport.FindExpressionFromAnyPosition(off, test_str, line, col, out keyw, out str); assert(s.Trim('\n', ' ', '\t') == "t1&.x"); test_str = "Arr(0).Select&"; off = 8; - s = parser.LanguageInformation.FindExpressionFromAnyPosition(off, test_str, line, col, out keyw, out str); + s = languageIntellisenseSupport.FindExpressionFromAnyPosition(off, test_str, line, col, out keyw, out str); assert(s.Trim('\n', ' ', '\t') == "Arr(0).Select&"); //---- @@ -1055,7 +1055,7 @@ namespace CodeCompletion StreamWriter sw = new StreamWriter("mscorlib.txt"); foreach (Type t in types) { - sw.WriteLine(parser.LanguageInformation.GetCompiledTypeRepresentation(t, t, ref i, ref j)); + sw.WriteLine(languageIntellisenseSupport.GetCompiledTypeRepresentation(t, t, ref i, ref j)); } sw.Close(); @@ -1063,7 +1063,7 @@ namespace CodeCompletion sw = new StreamWriter(typeof(System.Diagnostics.Process).Assembly.ManifestModule.ScopeName+".txt"); foreach (Type t in types) { - sw.WriteLine(parser.LanguageInformation.GetCompiledTypeRepresentation(t, t, ref i, ref j)); + sw.WriteLine(languageIntellisenseSupport.GetCompiledTypeRepresentation(t, t, ref i, ref j)); } sw.Close(); @@ -1072,7 +1072,7 @@ namespace CodeCompletion sw = new StreamWriter(typeof(System.Data.Constraint).Assembly.ManifestModule.ScopeName + ".txt"); foreach (Type t in types) { - sw.WriteLine(parser.LanguageInformation.GetCompiledTypeRepresentation(t, t, ref i, ref j)); + sw.WriteLine(languageIntellisenseSupport.GetCompiledTypeRepresentation(t, t, ref i, ref j)); } sw.Close(); @@ -1081,7 +1081,7 @@ namespace CodeCompletion sw = new StreamWriter(typeof(System.Xml.XmlDocument).Assembly.ManifestModule.ScopeName + ".txt"); foreach (Type t in types) { - sw.WriteLine(parser.LanguageInformation.GetCompiledTypeRepresentation(t, t, ref i, ref j)); + sw.WriteLine(languageIntellisenseSupport.GetCompiledTypeRepresentation(t, t, ref i, ref j)); } sw.Close(); } diff --git a/LanguageIntegrator/BaseLanguage.cs b/LanguageIntegrator/BaseLanguage.cs index af9d7ba99..8a5432ca3 100644 --- a/LanguageIntegrator/BaseLanguage.cs +++ b/LanguageIntegrator/BaseLanguage.cs @@ -2,9 +2,10 @@ // This code is distributed under the GNU LGPL (for details please see \doc\license.txt) using PascalABCCompiler.Parsers; -using System.Collections.Generic; using PascalABCCompiler.SyntaxTreeConverters; +using PascalABCCompiler.SystemLibrary; using PascalABCCompiler.TreeConverter; +using System.Collections.Generic; namespace Languages.Facade { @@ -13,14 +14,17 @@ namespace Languages.Facade /// public abstract class BaseLanguage : ILanguage { - /// - /// Все параметры должны быть не null (и не пустым массивом), кроме IDocParser в случае, если он не требуется + /// Все параметры должны быть не null (и не пустым массивом), + /// кроме IDocParser и ILanguageIntellisenseSupport в случае, если они не требуются /// - public BaseLanguage(ILanguageInformation languageInformation, + public BaseLanguage(ILanguageInformation languageInformation, ILanguageIntellisenseSupport languageIntellisenseSupport, IParser parser, IDocParser docParser, List syntaxTreeConverters) { this.LanguageInformation = languageInformation; + this.LanguageIntellisenseSupport = languageIntellisenseSupport; + if (this.LanguageIntellisenseSupport != null) + this.LanguageIntellisenseSupport.LanguageInformation = languageInformation; this.Parser = parser; this.Parser.LanguageInformation = languageInformation; this.DocParser = docParser; @@ -39,19 +43,37 @@ namespace Languages.Facade public string[] SystemUnitNames => LanguageInformation.SystemUnitNames; - public virtual ILanguageInformation LanguageInformation { get; } + public ILanguageInformation LanguageInformation { get; } - public virtual IParser Parser { get; protected set; } + public ILanguageIntellisenseSupport LanguageIntellisenseSupport { get; } - public virtual IDocParser DocParser { get; protected set; } + public IParser Parser { get; protected set; } - public virtual List SyntaxTreeConverters { get; protected set; } + public IDocParser DocParser { get; protected set; } - public bool ApplySyntaxTreeConvertersForIntellisense => LanguageInformation.ApplySyntaxTreeConvertersForIntellisense; + public List SyntaxTreeConverters { get; protected set; } - public virtual syntax_tree_visitor SyntaxTreeToSemanticTreeConverter { get; protected set; } + public syntax_tree_visitor SyntaxTreeToSemanticTreeConverter { get; protected set; } - public abstract void SetSemanticConstants(); + public virtual void SetSemanticConstants() + { + SemanticRulesConstants.ClassBaseType = SystemLibrary.object_type; + SemanticRulesConstants.StructBaseType = SystemLibrary.value_type; + SemanticRulesConstants.AddResultVariable = true; + SemanticRulesConstants.ZeroBasedStrings = true; + SemanticRulesConstants.FastStrings = false; + SemanticRulesConstants.InitStringAsEmptyString = true; + SemanticRulesConstants.UseDivisionAssignmentOperatorsForIntegerTypes = false; + SemanticRulesConstants.ManyVariablesOneInitializator = false; + SemanticRulesConstants.OrderIndependedMethodNames = true; + SemanticRulesConstants.OrderIndependedFunctionNames = false; + SemanticRulesConstants.OrderIndependedTypeNames = false; + SemanticRulesConstants.EnableExitProcedure = true; + SemanticRulesConstants.StrongPointersTypeCheckForDotNet = true; + SemanticRulesConstants.AllowChangeLoopVariable = false; + SemanticRulesConstants.AllowGlobalVisibilityForPABCDll = true; + SemanticRulesConstants.AllowMethodCallsWithoutParentheses = false; + } public abstract void SetSyntaxTreeToSemanticTreeConverter(); } diff --git a/LanguageIntegrator/ILanguage.cs b/LanguageIntegrator/ILanguage.cs index 9012ee723..d3263518d 100644 --- a/LanguageIntegrator/ILanguage.cs +++ b/LanguageIntegrator/ILanguage.cs @@ -30,6 +30,8 @@ namespace Languages.Facade ILanguageInformation LanguageInformation { get; } + ILanguageIntellisenseSupport LanguageIntellisenseSupport { get; } + /// /// Основной парсер языка /// @@ -45,11 +47,6 @@ namespace Languages.Facade /// List SyntaxTreeConverters { get; } - /// - /// Вызывать ли преобразователей синтаксического дерева в работе Intellisense - /// - bool ApplySyntaxTreeConvertersForIntellisense { get; } - /// /// Преобразователь из синтаксического дерева в семантическое /// diff --git a/ParserTools/ParserTools/BaseLanguageInformation.cs b/ParserTools/ParserTools/BaseLanguageIntellisenseSupport.cs similarity index 94% rename from ParserTools/ParserTools/BaseLanguageInformation.cs rename to ParserTools/ParserTools/BaseLanguageIntellisenseSupport.cs index b3d45ae89..3b017c7cf 100644 --- a/ParserTools/ParserTools/BaseLanguageInformation.cs +++ b/ParserTools/ParserTools/BaseLanguageIntellisenseSupport.cs @@ -1,4 +1,5 @@ -using PascalABCCompiler.ParserTools.Directives; +// Copyright (c) Ivan Bondarev, Stanislav Mikhalkovich (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) using PascalABCCompiler.SyntaxTree; using System; using System.Collections.Generic; @@ -8,25 +9,9 @@ using System.Text; namespace PascalABCCompiler.Parsers { - public abstract class BaseLanguageInformation : ILanguageInformation + public abstract class BaseLanguageIntellisenseSupport : ILanguageIntellisenseSupport { - public abstract string Name { get; } - - public abstract string Version { get; } - - public abstract string Copyright { get; } - - public abstract bool CaseSensitive { get; } - - public abstract string[] FilesExtensions { get; } - - public abstract string[] SystemUnitNames { get; } - - public abstract BaseKeywords KeywordsStorage { get; } - - public abstract Dictionary ValidDirectives { get; protected set; } - - public abstract string CommentSymbol { get; } + public ILanguageInformation LanguageInformation { get; set; } public abstract string BodyStartBracket { get; } @@ -46,8 +31,6 @@ namespace PascalABCCompiler.Parsers public abstract string ProcedureName { get; } public abstract string FunctionName { get; } - public abstract bool SyntaxTreeIsConvertedAfterUsedModulesCompilation { get; } - public abstract bool ApplySyntaxTreeConvertersForIntellisense { get; } public abstract bool IncludeDotNetEntities { get; } @@ -58,11 +41,12 @@ namespace PascalABCCompiler.Parsers public abstract bool UsesFunctionsOverlappingSourceContext { get; } - public virtual Dictionary SpecialModulesAliases => null; - protected abstract string IntTypeName { get; } - public abstract bool IsParams(string paramDescription); + public virtual bool IsParams(string paramDescription) + { + return paramDescription.TrimStart().StartsWith("params"); + } public virtual void RenameOrExcludeSpecialNames(SymInfo[] symInfos) { } @@ -141,9 +125,48 @@ namespace PascalABCCompiler.Parsers return null; } - public abstract string GetArrayDescription(string elementType, int rank); + public virtual string GetArrayDescription(string elementType, int rank) + { + if (rank == 1) + return "array of " + elementType; + else + { + StringBuilder sb = new StringBuilder(); + sb.Append('['); + for (int i = 0; i < rank - 1; i++) + sb.Append(DelimiterInIndexer); + sb.Append(']'); + return "array" + sb.ToString() + " of " + elementType; + } + } - public abstract string GetClassKeyword(class_keyword keyw); + public virtual string GetClassKeyword(class_keyword keyw) + { + switch (keyw) + { + case class_keyword.Class: return "class"; + case class_keyword.Interface: return "interface"; + case class_keyword.Record: return "record"; + case class_keyword.TemplateClass: return "template class"; + case class_keyword.TemplateRecord: return "template record"; + case class_keyword.TemplateInterface: return "template interface"; + } + return null; + } + + public virtual string GetKeyword(SymbolKind kind) + { + switch (kind) + { + case SymbolKind.Class: return "class"; + case SymbolKind.Enum: return "enum"; + case SymbolKind.Struct: return "record"; + case SymbolKind.Type: return "type"; + case SymbolKind.Interface: return "interface"; + case SymbolKind.Null: return "nil"; + } + return ""; + } public string GetCompiledTypeRepresentation(Type t, MemberInfo mi, ref int line, ref int col) { @@ -609,7 +632,7 @@ namespace PascalABCCompiler.Parsers public abstract string GetDescription(IBaseScope scope); - + // поменять на abstract EVA public virtual string GetDocumentTemplate(string lineText, string Text, int line, int col, int pos) { @@ -918,16 +941,19 @@ namespace PascalABCCompiler.Parsers return "string" + "[" + scope.Length + "]"; } - public abstract string GetKeyword(SymbolKind kind); - public KeywordKind GetKeywordKind(string name) { - if (KeywordsStorage.KeywordKinds.TryGetValue(name, out var kind)) + if (LanguageInformation.KeywordsStorage.KeywordKinds.TryGetValue(name, out var kind)) return kind; else return KeywordKind.None; } + public virtual string GetShortName(ICompiledConstructorScope scope) + { + return StringConstants.default_constructor_name; + } + public string GetShortName(ICompiledTypeScope scope) { return GetShortTypeName(scope.CompiledType); @@ -947,7 +973,6 @@ namespace PascalABCCompiler.Parsers return GetShortTypeName(scope.CompiledMethod); } - public abstract string GetShortName(ICompiledConstructorScope scope); public string GetShortName(IProcScope scope) { @@ -1433,9 +1458,9 @@ namespace PascalABCCompiler.Parsers return sc.Name + (((sc as ITypeScope).TemplateArguments != null && !sc.Name.EndsWith("<>") && sc.Name != "class") ? "<>" : "") + "."; } - if (sc is IInterfaceUnitScope && SpecialModulesAliases != null) + if (sc is IInterfaceUnitScope && LanguageInformation.SpecialModulesAliases != null) { - var p = SpecialModulesAliases.FirstOrDefault(kv => kv.Value == sc.Name); + var p = LanguageInformation.SpecialModulesAliases.FirstOrDefault(kv => kv.Value == sc.Name); if (!p.Equals(default(KeyValuePair))) return p.Key + "."; @@ -1454,9 +1479,9 @@ namespace PascalABCCompiler.Parsers return sc.Name + (((sc as ITypeScope).TemplateArguments != null && !sc.Name.EndsWith("<>")) ? "<>" : ""); } - if (sc is IInterfaceUnitScope && SpecialModulesAliases != null) + if (sc is IInterfaceUnitScope && LanguageInformation.SpecialModulesAliases != null) { - var p = SpecialModulesAliases.FirstOrDefault(kv => kv.Value == sc.Name); + var p = LanguageInformation.SpecialModulesAliases.FirstOrDefault(kv => kv.Value == sc.Name); if (!p.Equals(default(KeyValuePair))) return p.Key + "."; @@ -1579,11 +1604,20 @@ namespace PascalABCCompiler.Parsers public abstract string GetStandardTypeByKeyword(KeywordKind keyw); - public abstract string GetStringForChar(char c); + public virtual string GetStringForChar(char c) + { + return "'" + c.ToString() + "'"; + } - public abstract string GetStringForSharpChar(int num); + public virtual string GetStringForSharpChar(int num) + { + return "#" + num.ToString(); + } - public abstract string GetStringForString(string s); + public virtual string GetStringForString(string s) + { + return "'" + s + "'"; + } public abstract string GetSynonimDescription(ITypeScope scope); @@ -1633,14 +1667,23 @@ namespace PascalABCCompiler.Parsers return null; } - public abstract bool IsDefinitionIdentifierAfterKeyword(KeywordKind keyw); + public virtual bool IsDefinitionIdentifierAfterKeyword(KeywordKind keyw) + { + if (keyw == PascalABCCompiler.Parsers.KeywordKind.Function || keyw == PascalABCCompiler.Parsers.KeywordKind.Constructor || keyw == PascalABCCompiler.Parsers.KeywordKind.Destructor || keyw == PascalABCCompiler.Parsers.KeywordKind.Type || keyw == PascalABCCompiler.Parsers.KeywordKind.Var + || keyw == PascalABCCompiler.Parsers.KeywordKind.Unit || keyw == PascalABCCompiler.Parsers.KeywordKind.Const || keyw == PascalABCCompiler.Parsers.KeywordKind.Program || keyw == PascalABCCompiler.Parsers.KeywordKind.Punkt) + return true; + return false; + } public bool IsKeyword(string value) { - return KeywordsStorage.KeywordsForIntellisenseSet.Contains(value); + return LanguageInformation.KeywordsStorage.KeywordsForIntellisenseSet.Contains(value); } - public abstract bool IsMethodCallParameterSeparator(char key); + public virtual bool IsMethodCallParameterSeparator(char key) + { + return key == ','; + } public virtual bool IsNamespaceAfterKeyword(KeywordKind keyw) { @@ -1657,7 +1700,12 @@ namespace PascalABCCompiler.Parsers return key == '('; } - public abstract bool IsTypeAfterKeyword(KeywordKind keyw); + public virtual bool IsTypeAfterKeyword(KeywordKind keyw) + { + if (keyw == KeywordKind.Colon || keyw == KeywordKind.Of || keyw == KeywordKind.TypeDecl) + return true; + return false; + } // перенести реализацию сюда EVA public virtual string SkipNew(int off, string Text, ref KeywordKind keyw) @@ -1713,7 +1761,7 @@ namespace PascalABCCompiler.Parsers { keyword = KeywordKind.Raise; } - else if (KeywordsStorage.KeywordsTreatedAsFunctions.Contains(s)) + else if (LanguageInformation.KeywordsStorage.KeywordsTreatedAsFunctions.Contains(s)) { keyword = KeywordKind.None; } diff --git a/ParserTools/ParserTools/BaseParser.cs b/ParserTools/ParserTools/BaseParser.cs index 4ba75e2a6..dd0dab4e8 100644 --- a/ParserTools/ParserTools/BaseParser.cs +++ b/ParserTools/ParserTools/BaseParser.cs @@ -8,11 +8,11 @@ namespace PascalABCCompiler.Parsers { public abstract class BaseParser : IParser { - public List Errors { get; protected set; } = new List(); + protected List Errors = new List(); - public List Warnings { get; protected set; } = new List(); + protected List Warnings = new List(); - public List CompilerDirectives { get; protected set; } = new List(); + protected List CompilerDirectives = new List(); public ILanguageInformation LanguageInformation { get; set; } @@ -71,8 +71,11 @@ namespace PascalABCCompiler.Parsers private void InitializeBeforeParsing(List Errors, List Warnings) { + Errors.Clear(); + Warnings.Clear(); this.Errors = Errors; this.Warnings = Warnings; + this.CompilerDirectives = new List(); } protected virtual syntax_tree_node BuildTree(string FileName, string Text, List Errors, List Warnings, ParseMode ParseMode, bool compilingNotMainProgram, List DefinesList = null) @@ -134,10 +137,5 @@ namespace PascalABCCompiler.Parsers protected abstract syntax_tree_node BuildTreeInStatementMode(string FileName, string Text); - public virtual void Reset() - { - // если нужно - переопределяйте - } - } } diff --git a/ParserTools/ParserTools/DefaultLanguageInformation.cs b/ParserTools/ParserTools/DefaultLanguageInformation.cs new file mode 100644 index 000000000..2caabc798 --- /dev/null +++ b/ParserTools/ParserTools/DefaultLanguageInformation.cs @@ -0,0 +1,35 @@ +// Copyright (c) Ivan Bondarev, Stanislav Mikhalkovich (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + + +using PascalABCCompiler.ParserTools.Directives; +using System.Collections.Generic; + +namespace PascalABCCompiler.Parsers +{ + public abstract class DefaultLanguageInformation : ILanguageInformation + { + public abstract string Name { get; } + + public abstract string Version { get; } + + public abstract string Copyright { get; } + + public abstract bool CaseSensitive { get; } + + public abstract string[] FilesExtensions { get; } + + public abstract string[] SystemUnitNames { get; } + + public abstract BaseKeywords KeywordsStorage { get; } + + public virtual bool SyntaxTreeIsConvertedAfterUsedModulesCompilation => false; + + public virtual Dictionary ValidDirectives => null; + + // Важно переопределять для реализации тестов + public virtual string CommentSymbol => "//"; + + public virtual Dictionary SpecialModulesAliases => null; + } +} diff --git a/ParserTools/ParserTools/ILanguageInformation.cs b/ParserTools/ParserTools/ILanguageInformation.cs index 864b4a133..92d3717c7 100644 --- a/ParserTools/ParserTools/ILanguageInformation.cs +++ b/ParserTools/ParserTools/ILanguageInformation.cs @@ -6,10 +6,10 @@ using PascalABCCompiler.SyntaxTree; namespace PascalABCCompiler.Parsers { - /// - /// Интерфейс, предоставляющий информацию интеллисенсу - /// - public interface ILanguageInformation + /// + /// Информация о языке + /// + public interface ILanguageInformation { /// /// Название языка @@ -41,6 +41,43 @@ namespace PascalABCCompiler.Parsers /// string[] SystemUnitNames { get; } + /// + /// Нужно ли вызывать конверторы синтаксического дерева, срабатывающие после компиляции зависимостей + /// + bool SyntaxTreeIsConvertedAfterUsedModulesCompilation { get; } + + /// + /// Класс с информацией о ключевых словах языка + /// + BaseKeywords KeywordsStorage + { + get; + } + + /// + /// Данные о всех поддерживаемых директивах компилятора + /// + Dictionary ValidDirectives { get; } + + /// + /// Обозначение однострочного комментария (используется в TestRunner) + /// + string CommentSymbol { get; } + + /// + /// Имена стандартных модулей, которые не совпадают с именами их файлов. + /// Можно задавать null. + /// + Dictionary SpecialModulesAliases { get; } + } + + /// + /// Интерфейс, предоставляющий информацию интеллисенсу + /// + public interface ILanguageIntellisenseSupport + { + ILanguageInformation LanguageInformation { get; set; } + /// /// Получить полное описание элемента (в желтой подсказке) /// @@ -176,30 +213,11 @@ namespace PascalABCCompiler.Parsers int FindParamDelimForIndexer(string descriptionAfterOpeningParenthesis, int number); - /// - /// Нужно ли вызывать конверторы синтаксического дерева, срабатывающие после компиляции зависимостей - /// - bool SyntaxTreeIsConvertedAfterUsedModulesCompilation { get; } - /// /// Вызывать ли преобразователей синтаксического дерева в работе Intellisense /// bool ApplySyntaxTreeConvertersForIntellisense { get; } - Dictionary SpecialModulesAliases { get; } - - BaseKeywords KeywordsStorage - { - get; - } - - /// - /// Данные о всех поддерживаемых директивах компилятора - /// - Dictionary ValidDirectives { get; } - - string CommentSymbol { get; } - string BodyStartBracket { get; diff --git a/ParserTools/ParserTools/IParser.cs b/ParserTools/ParserTools/IParser.cs index 7b0dce7ed..90404a03e 100644 --- a/ParserTools/ParserTools/IParser.cs +++ b/ParserTools/ParserTools/IParser.cs @@ -3,22 +3,12 @@ using System.Collections.Generic; using PascalABCCompiler.SyntaxTree; using PascalABCCompiler.Errors; -using System; namespace PascalABCCompiler.Parsers { public enum ParseMode { Normal, Expression, Statement, Special, ForFormatter, TypeAsExpression }; public interface IParser { - List Errors { get; } - - List Warnings { get; } - - List CompilerDirectives - { - get; - } - ILanguageInformation LanguageInformation { get; set; } compilation_unit GetCompilationUnit(string FileName, string Text, List Errors, List Warnings, ParseMode parseMode, bool compilingNotMainProgram, List DefinesList = null); @@ -30,8 +20,6 @@ namespace PascalABCCompiler.Parsers statement GetStatement(string FileName, string Text, List Errors, List Warnings); expression GetTypeAsExpression(string FileName, string Text, List Errors, List Warnings); - - void Reset(); } diff --git a/ParserTools/ParserTools/SimpleParser.cs b/ParserTools/ParserTools/SimpleParser.cs new file mode 100644 index 000000000..e03f88704 --- /dev/null +++ b/ParserTools/ParserTools/SimpleParser.cs @@ -0,0 +1,38 @@ +// Copyright (c) Ivan Bondarev, Stanislav Mikhalkovich (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + +using PascalABCCompiler.SyntaxTree; + +namespace PascalABCCompiler.Parsers +{ + /// + /// Базовый класс для парсера без поддержки построения частей дерева и построения дерева с пропуском ошибок (Special mode) + /// + public abstract class SimpleParser : BaseParser + { + protected override syntax_tree_node BuildTreeInExprMode(string FileName, string Text) + { + throw new System.NotImplementedException(); + } + + protected override syntax_tree_node BuildTreeInFormatterMode(string FileName, string Text) + { + throw new System.NotImplementedException(); + } + + protected override syntax_tree_node BuildTreeInSpecialMode(string FileName, string Text, bool compilingNotMainProgram) + { + throw new System.NotImplementedException(); + } + + protected override syntax_tree_node BuildTreeInStatementMode(string FileName, string Text) + { + throw new System.NotImplementedException(); + } + + protected override syntax_tree_node BuildTreeInTypeExprMode(string FileName, string Text) + { + throw new System.NotImplementedException(); + } + } +} diff --git a/Parsers/PascalABCParserNewSaushkin/Parser.cs b/Parsers/PascalABCParserNewSaushkin/Parser.cs index 894156699..ee93095be 100644 --- a/Parsers/PascalABCParserNewSaushkin/Parser.cs +++ b/Parsers/PascalABCParserNewSaushkin/Parser.cs @@ -71,17 +71,6 @@ namespace Languages.Pascal.Frontend.Wrapping /// public class PascalABCNewLanguageParser : BaseParser { - - public override void Reset() - { - CompilerDirectives = new List(); - Errors.Clear(); - } - - protected override void PreBuildTree(string FileName) - { - CompilerDirectives = new List(); - } private syntax_tree_node Parse(string Text, string fileName, bool buildTreeForFormatter = false, List definesList = null) { @@ -115,8 +104,6 @@ namespace Languages.Pascal.Frontend.Wrapping protected override syntax_tree_node BuildTreeInNormalMode(string FileName, string Text, bool compilingNotMainProgram, List DefinesList = null) { - Errors.Clear(); - Warnings.Clear(); syntax_tree_node root = Parse(Text, FileName, false, DefinesList); if (Errors.Count > 0) @@ -163,14 +150,12 @@ namespace Languages.Pascal.Frontend.Wrapping protected override syntax_tree_node BuildTreeInSpecialMode(string FileName, string Text, bool compilingNotMainProgram) { - Errors.Clear(); syntax_tree_node root = Parse(Text, FileName); return root; } protected override syntax_tree_node BuildTreeInFormatterMode(string FileName, string Text) { - Errors.Clear(); syntax_tree_node root = Parse(Text, FileName, true); return root; } diff --git a/PascalABCLanguageInfo/PascalABCIntellisenseSupport.cs b/PascalABCLanguageInfo/PascalABCIntellisenseSupport.cs new file mode 100644 index 000000000..5c3949e77 --- /dev/null +++ b/PascalABCLanguageInfo/PascalABCIntellisenseSupport.cs @@ -0,0 +1,1799 @@ +using PascalABCCompiler; +using PascalABCCompiler.Parsers; +using PascalABCCompiler.SyntaxTree; +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Text; + +namespace Languages.Pascal.Frontend.Data +{ + internal class PascalABCIntellisenseSupport : BaseLanguageIntellisenseSupport + { + + protected IParser Parser + { + get + { + // Поле парсера желательно убрать отсюда EVA + return Facade.LanguageProvider.Instance.MainLanguage.Parser; + } + } + + public override string BodyStartBracket + { + get + { + return "begin"; + } + } + + public override string BodyEndBracket + { + get + { + return "end"; + } + } + + public override string ParameterDelimiter + { + get + { + return ";"; + } + } + + public override string DelimiterInIndexer => ","; + + public override string ResultVariableName => "Result"; + + public override string ProcedureName => "procedure"; + + public override string FunctionName => "function"; + + public override string GenericTypesStartBracket => "<"; + + public override string GenericTypesEndBracket => ">"; + + public override string ReturnTypeDelimiter => ":"; + + protected override string IntTypeName => "integer"; + + public override bool IncludeDotNetEntities + { + get + { + return true; + } + } + + public override bool ApplySyntaxTreeConvertersForIntellisense => false; + + public override bool AddStandardUnitNamesToUserScope => true; + + public override bool AddStandardNetNamespacesToUserScope => true; + + public override bool UsesFunctionsOverlappingSourceContext => false; + + public override bool IsParams(string paramDescription) + { + // три точки встречаются в описании некоторых стандартных функций в PABCSystem + return paramDescription.Contains("...") || paramDescription.TrimStart().StartsWith("params"); + } + + public override string GetDescription(IBaseScope scope) + { + switch (scope.Kind) + { + case ScopeKind.Type: return GetDescriptionForType(scope as ITypeScope); + case ScopeKind.CompiledType: return GetDescriptionForCompiledType(scope as ICompiledTypeScope); + case ScopeKind.Delegate: return GetDescriptionForDelegate(scope as IProcType); + case ScopeKind.TypeSynonim: return GetSynonimDescription(scope as ITypeSynonimScope); + case ScopeKind.Array: return GetDescriptionForArray(scope as IArrayScope); + case ScopeKind.Diapason: return GetDescriptionForDiapason(scope as IDiapasonScope); + case ScopeKind.File: return GetDescriptionForFile(scope as IFileScope); + case ScopeKind.Pointer: return GetDescriptionForPointer(scope as IPointerScope); + case ScopeKind.Enum: return GetDescriptionForEnum(scope as IEnumScope); + case ScopeKind.Set: return GetDescriptionForSet(scope as ISetScope); + case ScopeKind.ElementScope: return GetDescriptionForElementScope(scope as IElementScope); + case ScopeKind.CompiledField: return GetDescriptionForCompiledField(scope as ICompiledFieldScope); + case ScopeKind.CompiledProperty: return GetDescriptionForCompiledProperty(scope as ICompiledPropertyScope); + case ScopeKind.CompiledMethod: return GetDescriptionForCompiledMethod(scope as ICompiledMethodScope); + case ScopeKind.Namespace: return GetDescriptionForNamespace(scope as INamespaceScope); + case ScopeKind.Procedure: return GetDescriptionForProcedure(scope as IProcScope); + case ScopeKind.CompiledEvent: return GetDescriptionForCompiledEvent(scope as ICompiledEventScope); + case ScopeKind.CompiledConstructor: return GetDescriptionForCompiledConstructor(scope as ICompiledConstructorScope); + case ScopeKind.ShortString: return GetDescriptionForShortString(scope as IShortStringScope); + } + return ""; + } + + public override string GetSimpleDescription(IBaseScope scope) + { + if (scope == null) + return ""; + switch (scope.Kind) + { + case ScopeKind.Delegate: + case ScopeKind.Array: + case ScopeKind.Diapason: + case ScopeKind.File: + case ScopeKind.Pointer: + case ScopeKind.Enum: + case ScopeKind.Set: + case ScopeKind.ShortString: + if (scope is ITypeScope && (scope as ITypeScope).Aliased) + return scope.Name; + break; + } + switch (scope.Kind) + { + case ScopeKind.Type: return GetSimpleDescriptionForType(scope as ITypeScope); + case ScopeKind.CompiledType: return GetSimpleDescriptionForCompiledType(scope as ICompiledTypeScope); + case ScopeKind.Delegate: return GetDescriptionForDelegate(scope as IProcType); + case ScopeKind.TypeSynonim: return GetSimpleSynonimDescription(scope as ITypeSynonimScope); + case ScopeKind.Array: return GetDescriptionForArray(scope as IArrayScope); + case ScopeKind.Diapason: return GetDescriptionForDiapason(scope as IDiapasonScope); + case ScopeKind.File: return GetDescriptionForFile(scope as IFileScope); + case ScopeKind.Pointer: return GetDescriptionForPointer(scope as IPointerScope); + case ScopeKind.Enum: return GetDescriptionForEnum(scope as IEnumScope); + case ScopeKind.Set: return GetDescriptionForSet(scope as ISetScope); + case ScopeKind.ElementScope: return GetSimpleDescriptionForElementScope(scope as IElementScope); + case ScopeKind.CompiledField: return GetDescriptionForCompiledField(scope as ICompiledFieldScope); + case ScopeKind.CompiledProperty: return GetDescriptionForCompiledProperty(scope as ICompiledPropertyScope); + case ScopeKind.CompiledMethod: return GetDescriptionForCompiledMethod(scope as ICompiledMethodScope); + case ScopeKind.Namespace: return GetDescriptionForNamespace(scope as INamespaceScope); + case ScopeKind.Procedure: return GetSimpleDescriptionForProcedure(scope as IProcScope); + case ScopeKind.CompiledEvent: return GetDescriptionForCompiledEvent(scope as ICompiledEventScope); + case ScopeKind.CompiledConstructor: return GetDescriptionForCompiledConstructor(scope as ICompiledConstructorScope); + case ScopeKind.ShortString: return GetDescriptionForShortString(scope as IShortStringScope); + case ScopeKind.UnitInterface: return GetDescriptionForModule(scope as IInterfaceUnitScope); + //case ScopeKind.Procedure : return GetDescriptionForProcedure(scope as IProcScope); + } + return ""; + } + + protected override string GetSimpleDescriptionForType(ITypeScope scope) + { + // Замена на отображаемое имя для set (семантический Intellisense находит тип, которым set реализован) + if (scope.Name == StringConstants.pascalSetClassName && scope.TopScope.Name == StringConstants.pascalSystemUnitName) + return "set of " + GetTemplateStringWithoutBrackets(scope); + + return base.GetSimpleDescriptionForType(scope); + } + + private string GetDescriptionForModule(IInterfaceUnitScope scope) + { + return (scope.IsNamespaceUnit ? "namespace " : "unit ") + scope.Name; + } + + public override string GetStandardTypeByKeyword(KeywordKind keyw) + { + switch (keyw) + { + case KeywordKind.ObjectType: return "object"; + case KeywordKind.StringType: return "string"; + case KeywordKind.ByteType: return "byte"; + case KeywordKind.SByteType: return "shortint"; + case KeywordKind.ShortType: return "smallint"; + case KeywordKind.UShortType: return "word"; + case KeywordKind.IntType: return "integer"; + case KeywordKind.UIntType: return "longword"; + case KeywordKind.Int64Type: return "int64"; + case KeywordKind.UInt64Type: return "uint64"; + case KeywordKind.DoubleType: return "real"; + case KeywordKind.FloatType: return "single"; + case KeywordKind.CharType: return "char"; + case KeywordKind.BoolType: return "boolean"; + case KeywordKind.PointerType: return "pointer"; + } + return null; + } + + protected override string GetFullTypeName(Type ctn, bool no_alias = true) + { + TypeCode tc = Type.GetTypeCode(ctn); + if (ctn.FullName == null && !ctn.IsArray && !ctn.IsGenericTypeDefinition && ctn.IsGenericParameter) + return ctn.Name; + if (!ctn.IsEnum) + { + switch (tc) + { + case TypeCode.Int32: return "integer"; + case TypeCode.Double: return "real"; + case TypeCode.Boolean: return "boolean"; + case TypeCode.String: return "string"; + case TypeCode.Char: return "char"; + case TypeCode.Byte: return "byte"; + case TypeCode.SByte: return "shortint"; + case TypeCode.Int16: return "smallint"; + case TypeCode.Int64: return "int64"; + case TypeCode.UInt16: return "word"; + case TypeCode.UInt32: return "longword"; + case TypeCode.UInt64: return "uint64"; + case TypeCode.Single: return "single"; + } + if (ctn.IsPointer) + if (ctn.FullName == "System.Void*") + return "pointer"; + else + return "^" + GetFullTypeName(ctn.GetElementType()); + } + else + return ctn.FullName; + if (!no_alias) + { + if (ctn.Name.Contains("Func`") || ctn.Name.Contains("Predicate`")) + return getLambdaRepresentation(ctn, true, new List()); + else if (ctn.Name.Contains("Action`")) + return getLambdaRepresentation(ctn, false, new List()); + else if (ctn.Name == "IEnumerable`1") + return "sequence of " + GetShortTypeName(ctn.GetGenericArguments()[0], false); + else if (ctn.Name.Contains("Tuple`")) + return get_tuple_string(ctn); + } + int gen_pos = ctn.Name.IndexOf("`"); + if (gen_pos != -1 || ctn.IsGenericType) + { + int len = ctn.GetGenericArguments().Length; + Type[] gen_ps = ctn.GetGenericArguments(); + System.Text.StringBuilder sb = new System.Text.StringBuilder(); + if (gen_pos != -1) + sb.Append(ctn.Namespace + "." + ctn.Name.Substring(0, gen_pos)); + else + sb.Append(ctn.Namespace + "." + ctn.Name); + sb.Append(GenericTypesStartBracket); + for (int i = 0; i < len; i++) + { + sb.Append(gen_ps[i].Name); + if (i < len - 1) + sb.Append(", "); + } + sb.Append(GenericTypesEndBracket); + return sb.ToString(); + } + if (ctn.IsArray) + { + var rank = ctn.GetArrayRank(); + var strrank = rank > 1 ? "[" + new string(',', rank - 1) + "]" : ""; + return $"array{strrank}" + " of " + GetFullTypeName(ctn.GetElementType()); + } + if (ctn == Type.GetType("System.Void*")) return "pointer"; + if (ctn.IsNested) + return ctn.Name; + return ctn.FullName; + } + + public override string GetShortTypeName(Type ctn, bool noalias = true) + { + TypeCode tc = Type.GetTypeCode(ctn); + if (ctn.FullName == null && !ctn.IsArray && !ctn.IsGenericTypeDefinition && ctn.IsGenericParameter) + return ctn.Name; + if (!ctn.IsEnum) + { + switch (tc) + { + case TypeCode.Int32: return "integer"; + case TypeCode.Double: return "real"; + case TypeCode.Boolean: return "boolean"; + case TypeCode.String: return "string"; + case TypeCode.Char: return "char"; + case TypeCode.Byte: return "byte"; + case TypeCode.SByte: return "shortint"; + case TypeCode.Int16: return "smallint"; + case TypeCode.Int64: return "int64"; + case TypeCode.UInt16: return "word"; + case TypeCode.UInt32: return "longword"; + case TypeCode.UInt64: return "uint64"; + case TypeCode.Single: return "single"; + } + if (ctn.IsPointer) + if (ctn.FullName == "System.Void*") + return "pointer"; + else + return "^" + GetShortTypeName(ctn.GetElementType(), noalias); + } + else return ctn.Name; + if (ctn.Name.Contains("`")) + { + if (!noalias) + { + if (ctn.Name.Contains("Func`") || ctn.Name.Contains("Predicate`")) + return getLambdaRepresentation(ctn, true, new List()); + else if (ctn.Name.Contains("Action`")) + return getLambdaRepresentation(ctn, false, new List()); + else if (ctn.Name == "IEnumerable`1") + return "sequence of " + GetShortTypeName(ctn.GetGenericArguments()[0], false); + else if (ctn.Name.Contains("Tuple`")) + return get_tuple_string(ctn); + } + int len = ctn.GetGenericArguments().Length; + System.Text.StringBuilder sb = new System.Text.StringBuilder(); + sb.Append(ctn.Name.Substring(0, ctn.Name.IndexOf('`'))); + sb.Append(GenericTypesStartBracket); + if (!noalias) + { + Type[] gen_ps = ctn.GetGenericArguments(); + for (int i = 0; i < len; i++) + { + sb.Append(gen_ps[i].Name); + if (i < len - 1) + sb.Append(", "); + } + } + sb.Append(GenericTypesEndBracket); + /*sb.Append('<'); + for (int i=0; i');*/ + return sb.ToString(); + } + if (ctn.IsArray) + { + var rank = ctn.GetArrayRank(); + var strrank = rank > 1 ? "[" + new string(',', rank - 1) + "]" : ""; + return $"array{strrank}" + " of " + GetShortTypeName(ctn.GetElementType()); + } + //if (ctn == Type.GetType("System.Void*")) return PascalABCCompiler.StringConstants.pointer_type_name; + return ctn.Name; + } + + protected string GetDescriptionForType(ITypeScope scope) + { + string template_str = GetTemplateString(scope); + switch (scope.ElemKind) + { + case SymbolKind.Class: + string mod = ""; + if (scope.IsStatic) + mod = "static "; + else + { + if (scope.IsAbstract) + mod = "abstract "; + if (scope.IsFinal) + mod += "sealed "; + } + if (scope.TopScope != null && scope.TopScope.Name != "" && !scope.TopScope.Name.Contains("$")) + return mod + "class " + scope.TopScope.Name + "." + scope.Name + template_str; + else return mod + "class " + scope.Name + template_str; + case SymbolKind.Interface: + if (scope.TopScope != null && scope.TopScope.Name != "" && !scope.TopScope.Name.Contains("$")) + return "interface " + scope.TopScope.Name + "." + scope.Name + template_str; + else return "interface " + scope.Name + template_str; + case SymbolKind.Enum: + if (scope.TopScope != null && scope.TopScope.Name != "" && !scope.TopScope.Name.Contains("$")) + return "enum " + scope.TopScope.Name + "." + scope.Name; + else return "enum " + scope.Name; + case SymbolKind.Delegate: + if (scope.TopScope != null && scope.TopScope.Name != "" && !scope.TopScope.Name.Contains("$")) + return "delegate " + scope.TopScope.Name + "." + scope.Name + template_str; + else return "delegate " + scope.Name + template_str; + case SymbolKind.Struct: + if (scope.TopScope != null && scope.TopScope.Name != "" && !scope.TopScope.Name.Contains("$")) + return "record " + scope.TopScope.Name + "." + scope.Name + template_str; + else return "record " + scope.Name + template_str; + } + + if (scope.TopScope != null) + return scope.TopScope.Name + "." + scope.Name; + else return scope.Name; + } + + protected string GetDescriptionForCompiledType(ICompiledTypeScope scope) + { + string s = GetFullTypeName(scope.CompiledType); + ITypeScope[] instances = scope.GenericInstances; + if (instances.Length > 0) + { + System.Text.StringBuilder sb = new System.Text.StringBuilder(); + int ind = s.IndexOf(GenericTypesStartBracket); + if (ind != -1) sb.Append(s.Substring(0, ind)); + else + sb.Append(s); + sb.Append(GenericTypesStartBracket); + for (int i = 0; i < instances.Length; i++) + { + sb.Append(GetSimpleDescriptionWithoutNamespace(instances[i])); + //sb.Append(instances[i].Name); + if (i < instances.Length - 1) sb.Append(", "); + } + sb.Append(GenericTypesEndBracket); + s = sb.ToString(); + } + + switch (scope.ElemKind) + { + case SymbolKind.Class: + string mod = ""; + if (scope.IsStatic) + mod = "static "; + else + { + if (scope.IsAbstract) + mod = "abstract "; + if (scope.IsFinal) + mod += "sealed "; + } + return mod + "class " + s; + case SymbolKind.Interface: + return "interface " + s; + case SymbolKind.Enum: + return "enum " + s; + case SymbolKind.Delegate: + return "delegate " + s; + case SymbolKind.Struct: + return "record " + s; + case SymbolKind.Type: + return "type " + s; + } + return s; + } + + private string GetDescriptionForDiapason(IDiapasonScope scope) + { + return scope.Left.ToString() + ".." + scope.Right.ToString(); + } + + private string GetDescriptionForFile(IFileScope scope) + { + System.Text.StringBuilder sb = new System.Text.StringBuilder(); + sb.Append("file"); + if (scope.ElementType != null) + { + string s = GetSimpleDescription(scope.ElementType); + if (s.Length > 0 && s[0] == '$') s = s.Substring(1, s.Length - 1); + sb.Append(" of " + s); + } + return sb.ToString(); + } + + private string GetDescriptionForPointer(IPointerScope scope) + { + string s = ""; + if (scope.ElementType != null) + { + s = "^" + GetSimpleDescription(scope.ElementType); + } + else + s = "pointer"; + + return s; + } + + private string GetDescriptionForSet(ISetScope scope) + { + System.Text.StringBuilder sb = new System.Text.StringBuilder(); + sb.Append("set of "); + if (scope.ElementType != null) + { + string s = GetSimpleDescription(scope.ElementType); + if (s.Length > 0 && s[0] == '$') s = s.Substring(1, s.Length - 1); + sb.Append(s); + } + return sb.ToString(); + } + + private string GetDescriptionForNamespace(INamespaceScope scope) + { + return "namespace " + scope.Name; + } + + public override string GetSynonimDescription(ITypeScope scope) + { + return "type " + scope.Name + GetGenericString(scope.TemplateArguments) + " = " + scope.Description; + } + + public override string GetSynonimDescription(ITypeSynonimScope scope) + { + if (scope.ActType is ICompiledTypeScope && !(scope.ActType as ICompiledTypeScope).Aliased) + return "type " + scope.Name + GetGenericString(scope.TemplateArguments) + " = " + GetSimpleDescriptionForCompiledType(scope.ActType as ICompiledTypeScope, true); + else + return "type " + scope.Name + GetGenericString(scope.TemplateArguments) + " = " + GetSimpleDescription(scope.ActType); + } + + public override string GetSynonimDescription(IProcScope scope) + { + return "type " + scope.Name + " = " + scope.Description; + } + + private string GetSimpleSynonimDescription(ITypeSynonimScope scope) + { + return scope.Name; + } + + + protected string GetAccessModifier(access_modifer mod) + { + switch (mod) + { + case access_modifer.private_modifer: return "private"; + case access_modifer.protected_modifer: return "protected"; + case access_modifer.public_modifer: return "public"; + case access_modifer.published_modifer: return "published"; + case access_modifer.internal_modifer: return "internal"; + } + return ""; + } + + public override string ConstructOverridedMethodHeader(IProcScope scope, out int off) + { + System.Text.StringBuilder sb = new System.Text.StringBuilder(); + if (scope.AccessModifier != access_modifer.internal_modifer) + sb.Append(GetAccessModifier(scope.AccessModifier) + " "); + if (scope.ReturnType == null) + sb.Append("procedure "); + else + sb.Append("function "); + off = sb.Length; + sb.Append(scope.Name); + sb.Append(GetGenericString(scope.TemplateParameters)); + if (!(scope is ICompiledMethodScope)) + { + IElementScope[] parameters = scope.Parameters; + if (parameters != null && parameters.Length > 0) + { + sb.Append('('); + for (int i = 0; i < scope.Parameters.Length; i++) + { + sb.Append(GetSimpleDescription(parameters[i])); + if (i < parameters.Length - 1) + { + sb.Append(ParameterDelimiter + " "); + } + } + sb.Append(')'); + } + } + else + { + ParameterInfo[] pis = (scope as ICompiledMethodScope).CompiledMethod.GetParameters(); + if (pis.Length > 0) + { + sb.Append('('); + for (int i = 0; i < pis.Length; i++) + { + if (pis[i].ParameterType.IsByRef) + sb.Append("var "); + else if (IsParams(pis[i])) + sb.Append("params "); + sb.Append(pis[i].Name); + sb.Append(": "); + if (!pis[i].ParameterType.IsByRef) + sb.Append(GetFullTypeName(pis[i].ParameterType)); + else sb.Append(GetFullTypeName(pis[i].ParameterType.GetElementType())); + if (i < pis.Length - 1) + sb.Append(ParameterDelimiter + " "); + } + sb.Append(')'); + } + } + if (scope.ReturnType != null) + sb.Append(ReturnTypeDelimiter + " " + GetSimpleDescription(scope.ReturnType)); + sb.Append("; override;"); + return sb.ToString(); + } + + public override string ConstructHeader(IProcRealizationScope scope, int tabCount) + { + System.Text.StringBuilder sb = new System.Text.StringBuilder(); + sb.Append('\t'); + if (!scope.DefProc.IsAbstract) + sb.Append(GetAccessModifier(access_modifer.public_modifer) + " "); + else + if (scope.DefProc.AccessModifier != access_modifer.none && scope.DefProc.AccessModifier != access_modifer.internal_modifer) + sb.Append(GetAccessModifier(scope.DefProc.AccessModifier) + " "); + if (scope.DefProc.ReturnType == null) + sb.Append("procedure "); + else + sb.Append("function "); + sb.Append(scope.Name); + sb.Append(GetGenericString(scope.TemplateParameters)); + + if (!(scope.DefProc is ICompiledMethodScope)) + { + IElementScope[] parameters = scope.DefProc.Parameters; + if (parameters != null && parameters.Length > 0) + { + sb.Append('('); + for (int i = 0; i < scope.DefProc.Parameters.Length; i++) + { + sb.Append(GetSimpleDescription(parameters[i])); + if (i < parameters.Length - 1) + { + sb.Append(ParameterDelimiter + " "); + } + } + sb.Append(')'); + } + } + else + { + ParameterInfo[] pis = (scope.DefProc as ICompiledMethodScope).CompiledMethod.GetParameters(); + if (pis.Length > 0) + { + sb.Append('('); + for (int i = 0; i < pis.Length; i++) + { + if (pis[i].ParameterType.IsByRef) + sb.Append("var "); + else if (IsParams(pis[i])) + sb.Append("params "); + sb.Append(pis[i].Name); + sb.Append(": "); + if (!pis[i].ParameterType.IsByRef) + sb.Append(GetFullTypeName(pis[i].ParameterType)); + else sb.Append(GetFullTypeName(pis[i].ParameterType.GetElementType())); + if (i < pis.Length - 1) + sb.Append(ParameterDelimiter + " "); + } + sb.Append(')'); + } + } + + if (scope.DefProc.ReturnType != null) + sb.Append(ReturnTypeDelimiter + " " + GetSimpleDescription(scope.DefProc.ReturnType)); + sb.Append(';'); + if (scope.DefProc.IsAbstract) + sb.Append("override;"); + return sb.ToString(); + } + + private void get_procedure_template(procedure_header header, StringBuilder res, int col) + { + if (header.parameters != null) + for (int i = 0; i < header.parameters.params_list.Count; i++) + for (int j = 0; j < header.parameters.params_list[i].idents.idents.Count; j++) + { + res.AppendLine(); + for (int k = 0; k < col - 3; k++) + res.Append(' '); + res.Append("/// "); + } + if (header is function_header) + { + res.AppendLine(); + for (int k = 0; k < col - 3; k++) + res.Append(' '); + res.Append("/// "); + } + } + + public override string GetDocumentTemplate(string lineText, string Text, int line, int col, int pos) + { + try + { + if (lineText == null) return ""; + StringBuilder res = new StringBuilder(); + if (lineText.StartsWith("procedure") || lineText.StartsWith("function") || lineText.StartsWith("constructor") || lineText.StartsWith("destructor")) + { + StringBuilder sb = new StringBuilder(); + sb.AppendLine(lineText); + sb.AppendLine("begin end;"); + sb.AppendLine("begin end."); + program_module node = this.Parser.GetCompilationUnit("test.pas", sb.ToString(), null, null, ParseMode.Special, false) as program_module; + procedure_header header = (node.program_block.defs.defs[0] as procedure_definition).proc_header; + get_procedure_template(header, res, col); + return res.ToString(); + } + else if (lineText.StartsWith("class") || lineText.StartsWith("public") || lineText.StartsWith("private") || lineText.StartsWith("protected") || lineText.StartsWith("internal")) + { + StringBuilder sb = new StringBuilder(); + sb.AppendLine(lineText); + sb.AppendLine("begin end;"); + sb.AppendLine("begin end."); + program_module node = this.Parser.GetCompilationUnit("test.pas", sb.ToString(), null, null, ParseMode.Special, false) as program_module; + if (node.program_block.defs != null && node.program_block.defs.defs.Count > 0 && node.program_block.defs.defs[0] is procedure_definition) + { + procedure_header header = (node.program_block.defs.defs[0] as procedure_definition).proc_header; + get_procedure_template(header, res, col); + return res.ToString(); + } + return ""; + } + else return ""; + } + catch + { + + } + return ""; + } + + public override string GetUnitTemplate(string unitName) + { + var sb = new StringBuilder(); + + sb.AppendLine("unit " + unitName + ";"); + sb.AppendLine(); + sb.AppendLine("interface"); + sb.AppendLine(); + sb.AppendLine("implementation"); + sb.AppendLine(); + sb.Append("end."); + + return sb.ToString(); + } + + public override string ConstructHeader(string meth, IProcScope scope, int tabCount) + { + int i = 0; + bool is_cnstr = false; + StringBuilder sb = new StringBuilder(); + if (meth.StartsWith("static ")) + meth = meth.Remove(0, "static ".Length); + else if (meth.StartsWith("class ")) + meth = meth.Remove(0, "class ".Length); + if (scope.IsStatic) + sb.Append("static "); + while (i < meth.Length && char.IsLetterOrDigit(meth[i])) + { + sb.Append(meth[i++]); + } + if (sb.ToString().ToLower() == "constructor") is_cnstr = true; + sb.Append(' '); + while (i < meth.Length && !(char.IsLetterOrDigit(meth[i]) || meth[i] == '_' || meth[i] == '(' || meth[i] == ';')) + if (meth[i] == '{') + while (i < meth.Length && meth[i] != '}') i++; + else + i++; + if (i < meth.Length) + { + if (scope.TopScope is ITypeScope && ((scope.TopScope as ITypeScope).ElemKind == SymbolKind.Class || (scope.TopScope as ITypeScope).ElemKind == SymbolKind.Struct)) + sb.Append(GetSimpleDescriptionForType(scope.TopScope as ITypeScope) + "."); + //if (meth[i] == '(' || meth[i] == ';') + sb.Append(scope.Name); + sb.Append(GetGenericString(scope.TemplateParameters)); + + while (i < meth.Length && (char.IsLetterOrDigit(meth[i]) || meth[i] == '_')) i++; + while (i < meth.Length && meth[i] != ';' && meth[i] != '(' && meth[i] != ':') + if (meth[i] == '{') while (i < meth.Length && meth[i] != '}') i++; + else i++; + if (meth[i] == '(') + { + sb.Append('('); + bool in_kav = false; + Stack sk_stack = new Stack(); + sk_stack.Push('('); i++; + bool default_value = false; + while (i < meth.Length && sk_stack.Count > 0) + { + if (meth[i] == '\'') in_kav = !in_kav; + else if (meth[i] == '(') { if (!in_kav) sk_stack.Push('('); } + else if (meth[i] == ')') { if (!in_kav) sk_stack.Pop(); } + if (meth[i] == ':' && meth[i + 1] == '=' && !in_kav) + default_value = true; + else if (meth[i] == ';' && !in_kav) + default_value = false; + if (!default_value || meth[i] == ')' && sk_stack.Count == 0) + { + if (meth[i] == ')' && sk_stack.Count == 0 && default_value) + sb = new StringBuilder(sb.ToString().TrimEnd()); + sb.Append(meth[i]); + } + i++; + } + while (i < meth.Length && meth[i] != ':' && meth[i] != ';') + if (meth[i] == '{') while (i < meth.Length && meth[i] != '}') i++; + else sb.Append(meth[i++]); + + //sb.Append(')'); + } + if (meth[i] == ':') + { + bool in_kav = false; + while (i < meth.Length && !(meth[i] == ';' && !in_kav)) + { + if (meth[i] == '{' && !in_kav) while (i < meth.Length && meth[i] != '}') i++; + else if (meth[i] == '\'') in_kav = !in_kav; + sb.Append(meth[i]); + i++; + } + } + sb.Append(';'); + } + sb.AppendLine(); + sb.AppendLine("begin"); + for (int j = 0; j < tabCount; j++) + sb.Append(' '); + sb.AppendLine(); + sb.AppendLine("end;"); + return sb.ToString(); + } + + private bool isOperator(string Text, int i, out int next) + { + next = i; + if (i >= 3) + { + string op = Text.Substring(i - 2, 3).ToLower().Trim(); + if (op == "and" || op == "div" || op == "mod" || op == "xor") + { + if (!char.IsLetterOrDigit(Text[i - 3]) && Text[i - 3] != '_' && Text[i - 3] != '&' && !(i + 1 < Text.Length && char.IsLetterOrDigit(Text[i + 1]))) + { + next = i - 3; + return true; + } + return false; + } + } + if (i >= 2) + { + string op = Text.Substring(i - 1, 2).ToLower().Trim(); + if (op == "or") + { + if (!char.IsLetterOrDigit(Text[i - 2]) && Text[i - 2] != '_' && Text[i - 2] != '&' && !(i + 1 < Text.Length && char.IsLetterOrDigit(Text[i + 1]))) + { + next = i - 2; + return true; + } + return false; + } + } + return false; + } + + private bool CheckForComment(string Text, int off, out int comment_position, out bool one_line_comment) + { + int i = off; + one_line_comment = false; + comment_position = -1; + Stack kav = new Stack(); + bool is_comm = false; + while (i >= 0 && !is_comm && Text[i] != '\n' && Text[i] != '\r') + { + if (Text[i] == '\'') + { + if (kav.Count == 0) kav.Push('\''); + else kav.Pop(); + } + else if (Text[i] == '{') + { + if (kav.Count == 0) + { + comment_position = i; + while (i >= 0 && Text[i] != '\'') + i--; + if (i >= 1 && Text[i - 1] == '$') + return false; + is_comm = true; + return is_comm; + } + } + else if (Text[i] == '}') + { + return false; + } + else if (Text[i] == '/') + if (i > 0 && Text[i - 1] == '/' && kav.Count == 0) + { + is_comm = true; + one_line_comment = true; + comment_position = i - 1; + } + + i--; + } + return is_comm; + } + + public override string FindExpression(int off, string Text, int line, int col, out KeywordKind keyw) + { + int i = off - 1; + int bound = 0; + bool punkt_sym = false; + keyw = KeywordKind.None; + System.Text.StringBuilder sb = new StringBuilder(); + Stack tokens = new Stack(); + Stack kav = new Stack(); + Stack ugl_skobki = new Stack(); + int num_in_ident = -1; + keyw = TestForKeyword(Text, i); + if (keyw == KeywordKind.Punkt) return ""; + while (i >= bound) + { + bool end = false; + char ch = Text[i]; + if (kav.Count == 0 && (char.IsLetterOrDigit(ch) || ch == '_' || ch == '&' || ch == '\'' || ch == '!')) + { + num_in_ident = i; + if (kav.Count == 0 && tokens.Count == 0) + { + int tmp = i; + if (ch == '\'') + { + i--; + if (kav.Count == 0) + kav.Push('\''); + while (i >= 0) + { + if (Text[i] != '\'') + i--; + else + { + if (i >= 1 && Text[i - 1] == '\'') + i -= 2; + else + break; + } + } + + if (i >= 0) + i--; + } + else + while (i >= 0 && (char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '&' || Text[i] == '!')) + { + i--; + } + while (i >= 0 && (Text[i] == ' ' || char.IsControl(Text[i]) || Text[i] == '}')) + { + if (Text[i] != '}') + i--; + else + { + while (i >= 0 && Text[i] != '{') //propusk kommentariev + i--; + if (i >= 0) + i--; + } + } + if (i >= 0 && (char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '&' || Text[i] == '!')) + { + bound = i + 1; + TestForKeyword(Text, i, ref bound, punkt_sym, out keyw); + for (int j = tmp; j > bound; j--) + { + sb.Insert(0, Text[j]); + } + if (sb.ToString().Trim() == "new") + return ""; + i = bound; + continue; + } + else if (i >= 0 && Text[i] == '\'') return ""; + i = tmp; + } + else + if (ch == '\'') + kav.Push('\''); + sb.Insert(0, ch);//.Append(Text[i]); + } + else if (ch == '.' || ch == '^' || ch == '&' || ch == '?' && IsPunctuation(Text, i + 1)) + { + if (ch == '.' && i >= 1 && Text[i - 1] == '.' && tokens.Count == 0) + end = true; + else if (ch == '?' && i + 1 < Text.Length && Text[i + 1] != '.') + end = true; + else + sb.Insert(0, ch); + if (ch != '.') + punkt_sym = true; + } + else if (ch == '}') + { + if (kav.Count == 0) + { + while (i >= 0 && Text[i] != '{') + { + if (Text[i] != '$')//skip {$ + sb.Insert(0, Text[i]); + i--; + } + if (i < 0) + { + break; + } + else if (Text[i] == '{') + { + sb.Insert(0, '{'); + } + } + else + sb.Insert(0, ch); + } + else if (ch == '{') + { + if (kav.Count == 0) + { + if (keyw == KeywordKind.None) + return sb.ToString(); + sb.Insert(0, ch); + break; + } + else sb.Insert(0, ch); + } + else + switch (ch) + { + case ')': + case ']': + if (kav.Count == 0) + { + string tmps = sb.ToString().Trim(' ', '\r', '\t', '\n'); + if (tmps.Length >= 1 && (char.IsLetter(tmps[0]) || tmps[0] == '_' || tmps[0] == '&' || tmps[0] == '?' || tmps[0] == '!') && tokens.Count == 0) + end = true; + else + tokens.Push(ch); + } + if (!end) + { + sb.Insert(0, ch); + punkt_sym = true; + } + break; + case '>': + if (tokens.Count == 0) + { + int j = i + 1; + + while (j < Text.Length && char.IsWhiteSpace(Text[j])) + j++; + + if (ugl_skobki.Count > 0 || i == off - 1 || j == off && off == Text.Length || j < Text.Length && Text[i - 1] != '-' && (Text[j] == '.' || Text[j] == '(')) + { + ugl_skobki.Push('>'); + sb.Insert(0, ch); + } + else if (i >= 1 && Text[i - 1] == '-') + { + if (!(kav.Count == 0 && tokens.Count == 0)) + sb.Insert(0, ch); + } + else + end = true; + } + else + sb.Insert(0, ch); + break; + case '<': + if (tokens.Count == 0) + { + if (ugl_skobki.Count > 0) + { + ugl_skobki.Pop(); + sb.Insert(0, ch); + } + else + end = true; + } + else + sb.Insert(0, ch); + break; + case '[': + case '(': + case '|': + if (ch == '|' && ((tokens.Count == 0) || (tokens.Peek() == ']') || (tokens.Peek() == ')') || (tokens.Peek() == ','))) + // Закрывающий | - после него (tokens.Pop()) - пусто или ] ) , + { + if (kav.Count == 0) + { + string tmps = sb.ToString().Trim(' ', '\r', '\t', '\n'); + if (tmps.Length >= 1 && (char.IsLetter(tmps[0]) || tmps[0] == '_' || tmps[0] == '&' || tmps[0] == '?' || tmps[0] == '!') && tokens.Count == 0) + end = true; + else + tokens.Push(ch); + } + if (!end) + { + sb.Insert(0, ch); + punkt_sym = true; + } + } + else + { + if (kav.Count == 0) // в т.ч. открывающий | + { + if (tokens.Count > 0) + { + tokens.Pop(); + punkt_sym = true; + sb.Insert(0, ch); + if (ch == '(') + { + int tmp = i--; + /*while (i >= 0 && (char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '&')) + { + i--; + }*/ + while (i >= 0 && (Text[i] == ' ' || char.IsControl(Text[i]) || Text[i] == '}')) + { + if (Text[i] != '}') + i--; + else + { + while (i >= 0 && Text[i] != '{') //propusk kommentariev + i--; + if (i >= 0) + i--; + } + } + if (i >= 0 && (char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '&' || Text[i] == '!' || Text[i] == '?' && IsPunctuation(Text, i + 1))) + { + bound = i + 1; + TestForKeyword(Text, i, ref bound, punkt_sym, out keyw); + if (keyw != KeywordKind.None && tokens.Count == 0) + { + end = true; + } + else bound = 0; + } + else if (i >= 0 && Text[i] == '\'') return ""; + i = tmp; + } + } + else + { + end = true; + if (ch == '[') + { + keyw = KeywordKind.SquareBracket; + } + } + + } + else sb.Insert(0, ch); punkt_sym = true; + } + break; + case '\'': + if (kav.Count == 0) kav.Push(ch); else kav.Pop(); + sb.Insert(0, ch); + punkt_sym = true; break; + default: + if (!(ch == ' ' || char.IsControl(ch))) + { + if (kav.Count == 0) + { + if (ch == ',' && ugl_skobki.Count > 0) + sb.Insert(0, ch); + else + if (tokens.Count == 0) + end = true; + else + sb.Insert(0, ch); + } + else + sb.Insert(0, ch); + } + else + { + if (Text[i] == '\n') + { + bool one_line_comment = false; + int comment_position = -1; + if (CheckForComment(Text, i - 1, out comment_position, out one_line_comment)) + { + if (!one_line_comment) + end = true; + else + { + sb.Insert(0, ch); + i = comment_position; + } + + } + else + sb.Insert(0, ch); + } + else + sb.Insert(0, ch); + } + punkt_sym = true; + break; + } + + if (end) + { + bool one_line_comment = false; + int comment_position = -1; + if (CheckForComment(Text, i, out comment_position, out one_line_comment)) + { + int new_line_ind = sb.ToString().IndexOf('\n'); + if (new_line_ind != -1) sb = sb.Remove(0, new_line_ind + 1); + else sb = sb.Remove(0, sb.Length); + } + break; + } + i--; + } + + //return RemovePossibleKeywords(sb); + if (sb.Length > 0 && sb[sb.Length - 1] == '?') + sb.Remove(sb.Length - 1, 1); + return sb.ToString(); + + } + + public override string FindExpressionFromAnyPosition(int off, string Text, int line, int col, out KeywordKind keyw, out string expr_without_brackets) + { + int i = off - 1; + + // это например вызов метода без параметров + expr_without_brackets = null; + keyw = KeywordKind.None; + if (i < 0) + return ""; + bool is_char = false; + + // идем в обе стороны от off + System.Text.StringBuilder sb = new System.Text.StringBuilder(); + if (Text[i] != ' ' && (Char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '&' || Text[i] == '?' && IsPunctuation(Text, i + 1) || Text[i] == '!')) + { + //sb.Remove(0,sb.Length); + while (i >= 0 && (Char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '&' || Text[i] == '?' && IsPunctuation(Text, i + 1) || Text[i] == '!')) + { + //sb.Insert(0,Text[i]);//.Append(Text[i]); + i--; + } + is_char = true; + } + i = off; + if (i < Text.Length && Text[i] != ' ' && (Char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '&' || Text[i] == '?' && IsPunctuation(Text, i + 1) || Text[i] == '!')) + { + while (i < Text.Length && (Char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '!')) + { + //sb.Append(Text[i]);//.Append(Text[i]); + i++; + } + is_char = true; + } + if (is_char) + { + expr_without_brackets = FindExpression(i, Text, line, col, out keyw); + } + bool is_new = keyw == KeywordKind.New; + bool meth_call = false; + KeywordKind new_keyw = KeywordKind.None; + int j = i; + bool in_comment = false; + bool brackets = false; + while (j < Text.Length) + { + char c = Text[j]; + + if (c == '(' && !in_comment) + { + Stack sk_stack = new Stack(); + in_comment = false; + bool in_kav = false; + sk_stack.Push('('); + j++; + while (j < Text.Length) + { + c = Text[j]; + if (c == '(' && !in_kav) + sk_stack.Push('('); + else + if (c == ')' && !in_kav) + { + if (sk_stack.Count == 0) + { + break; + } + else + { + sk_stack.Pop(); + if (sk_stack.Count == 0) + { + i = j + 1; + meth_call = true; + break; + } + } + } + else if (c == '\'' && !in_comment) + { + in_kav = !in_kav; + } + else if (c == '{' && !in_kav) + { + in_comment = true; + } + else if (c == '}' && !in_kav) + { + in_comment = false; + } + else if (c == '/' && !in_kav && !in_comment) + { + if (j + 1 < Text.Length && Text[j + 1] == '/') + break; + } + j++; + } + break; + } + else if ((c == '<' || c == '&' && j < Text.Length - 1 && Text[j + 1] == '<') && !in_comment) + { + Stack sk_stack = new Stack(); + if (c == '&') + j++; + sk_stack.Push('<'); + j++; + bool generic = false; + while (j < Text.Length) + { + c = Text[j]; + if (c == '>') + { + sk_stack.Pop(); + if (sk_stack.Count == 0) + { + i = j + 1; + generic = true; + break; + } + } + else if (c == '<') + { + sk_stack.Push('<'); + + } + else if (!char.IsLetterOrDigit(c) && c != '?' && c != '&' && c != '.' && c != ' ' && c != '\t' && c != '\n' && c != ',' && c != '!') + { + break; + } + j++; + } + if (generic) + { + //break; + } + } + else if (c == '[' && !in_comment) + { + brackets = true; + break; + } + else if (c == '{') + { + in_comment = true; + } + else if (c == '}') + { + if (!in_comment) + break; + else + in_comment = false; + } + else if (c == ' ' || c == '\t' || c == '\n' || c == '\r') + { + + } + else + { + if (!in_comment) + break; + } + j++; + } + if (is_new && string.Compare(expr_without_brackets.Trim(' ', '\n', '\t', '\r'), "new", true) == 0 && !meth_call) + { + expr_without_brackets = null; + return null; + } + if (is_char) + { + string ss = FindExpression(i, Text, line, col, out new_keyw); + if (brackets && is_new) + { + int ind = ss.ToLower().IndexOf("new"); + if (ind != -1) + return ss.Substring(ind + 3); + } + if (is_new && ss != null && ss.IndexOf("new") == -1 && ss.IndexOf(":") != -1) + return expr_without_brackets + "(true?" + ss; + return ss; + } + return null; + } + + public override KeywordKind TestForKeyword(string Text, int i) + { + StringBuilder sb = new StringBuilder(); + int orig_i = i; + int j = i; + bool in_keyw = false; + while (j >= 0 && Text[j] != '\n') + j--; + Stack kav_stack = new Stack(); + j++; + bool in_format_str = false; + while (j <= i) + { + if (Text[j] == '\'') + { + if (kav_stack.Count == 0 && !in_keyw) + { + if (j == 0 || Text[j - 1] != '$') + kav_stack.Push('\''); + else + { + in_keyw = false; + in_format_str = true; + } + + } + else if (kav_stack.Count > 0) + kav_stack.Pop(); + } + else if (Text[j] == '{' && kav_stack.Count == 0 && !in_format_str) + in_keyw = true; + else + if (Text[j] == '}') + in_keyw = false; + j++; + } + j = i; + if ((kav_stack.Count != 0 || in_keyw) && !in_format_str) return PascalABCCompiler.Parsers.KeywordKind.Punkt; + if (j >= 0 && Text[j] == '.') return PascalABCCompiler.Parsers.KeywordKind.Punkt; + while (j >= 0) + { + //if (Text[j] == '{') return PascalABCCompiler.Parsers.KeywordKind.Punkt; + if (!in_keyw && (Text[j] == '\'' || Text[j] == '\n')) + break; + if (Text[j] == '}') + in_keyw = true; + else + if (Text[j] == '/' && !in_keyw) + if (j > 0 && Text[j - 1] == '/') return PascalABCCompiler.Parsers.KeywordKind.Punkt; + j--; + } + //if (j>= 0 && Text[j] == '\'') return CodeCompletion.KeywordKind.kw_punkt; + while (i >= 0 && (Text[i] == ' ' || char.IsControl(Text[i]))) i--; + if (i >= 0 && Text[i] == ':') return PascalABCCompiler.Parsers.KeywordKind.Colon; + + if (i >= 0 && Text[i] == ',') + { + + while (i >= 0 && Text[i] != '\n') + { + if (char.IsLetterOrDigit(Text[i])) + sb.Insert(0, Text[i]); + else + { + PascalABCCompiler.Parsers.KeywordKind keyw = GetKeywordKind(sb.ToString()); + if (keyw == PascalABCCompiler.Parsers.KeywordKind.Uses) + return PascalABCCompiler.Parsers.KeywordKind.Uses; + else if (keyw == PascalABCCompiler.Parsers.KeywordKind.Var) + return PascalABCCompiler.Parsers.KeywordKind.Var; + else sb.Remove(0, sb.Length); + } + i--; + } + } + else + while (i >= 0 && (char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '!')) + { + sb.Insert(0, Text[i]); + i--; + } + string s = sb.ToString().ToLower(); + + return GetKeywordKind(s); + } + + public override string SkipNew(int off, string Text, ref KeywordKind keyw) + { + int tmp = off; + string expr = null; + while (off >= 0 && char.IsLetterOrDigit(Text[off])) off--; + while (off >= 0 && (Text[off] == ' ' || char.IsControl(Text[off]))) off--; + if (off >= 1 && Text[off] == '=' && Text[off - 1] == ':') + { + off -= 2; + while (off >= 0 && (Text[off] == ' ' || char.IsControl(Text[off]))) off--; + if (off >= 0 && (Text[off] == '_' || char.IsLetterOrDigit(Text[off]) || Text[off] == '!' || Text[off] == ']' || Text[off] == '>')) + expr = FindExpression(off + 1, Text, 0, 0, out keyw); + } + return expr; + } + + public override string FindExpressionForMethod(int off, string Text, int line, int col, char pressed_key, ref int num_param) + { + int i = off - 1; + string pattern = null; + int bound = 0; + System.Text.StringBuilder sb = new System.Text.StringBuilder(); + Stack tokens = new Stack(); + Stack kav = new Stack(); + Stack skobki = new Stack(); + Stack ugl_skobki = new Stack(); + bool comma_pressed = pressed_key == ','; + int num_in_ident = -1; + bool punkt_sym = false; + int next; + KeywordKind keyw = TestForKeyword(Text, i); + bool on_brace = false; + if (keyw == KeywordKind.Punkt) + return ""; + try + { + while (i >= bound) + { + bool end = false; + char ch = Text[i]; + if ((char.IsLetterOrDigit(ch) || ch == '_' || ch == '&' || ch == '!') && !isOperator(Text, i, out next)) + { + num_in_ident = i; + if (kav.Count == 0 && tokens.Count == 0) + { + int tmp = i; + while (i >= 0 && (char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '&' || Text[i] == '!') && !isOperator(Text, i, out next)) + { + i--; + } + while (i >= 0 && (Text[i] == ' ' || char.IsControl(Text[i]) || Text[i] == '}')) + { + if (Text[i] != '}') + i--; + else + { + while (i >= 0 && Text[i] != '{') //propusk kommentariev + i--; + if (i >= 0) + i--; + } + } + if (i >= 0 && (char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '&' || Text[i] == '!') && !isOperator(Text, i, out next)) + { + bound = i + 1; + TestForKeyword(Text, i, ref bound, punkt_sym, out keyw); + if (keyw == KeywordKind.New && comma_pressed) + bound = 0; + if (keyw == KeywordKind.Function || keyw == KeywordKind.Constructor || keyw == KeywordKind.Destructor) + return ""; + } + else if (i >= 0 && Text[i] == '\'') return ""; + i = tmp; + } + sb.Insert(0, ch);//.Append(Text[i]); + } + else if (ch == '.') sb.Insert(0, ch); + else if (ch == '}') + { + if (kav.Count == 0) + { + while (i >= 0 && Text[i] != '{') + { + sb.Insert(0, Text[i]); + i--; + } + if (i < 0) + { + break; + } + else if (Text[i] == '{') + { + sb.Insert(0, '{'); + } + } + else + sb.Insert(0, ch); + } + else if (ch == '{') + { + if (kav.Count == 0) + { + sb.Insert(0, ch); + break; + } + else sb.Insert(0, ch); + } + else + switch (ch) + { + case ')': + case ']': + case '>': + if (kav.Count == 0) + { + int j = i + 1; + + while (j < Text.Length && char.IsWhiteSpace(Text[j])) + j++; + if (ch != '>') + tokens.Push(ch); + if (ch == ')') + skobki.Push(ch); + if (tokens.Count > 0 || pressed_key == ',') + sb.Insert(0, ch); + else if (i == off - 1 || j == off && off == Text.Length || ugl_skobki.Count > 0 || j < Text.Length && Text[i - 1] != '-' && (Text[j] == '.' || Text[j] == '(')) + { + tokens.Push(ch); + ugl_skobki.Push(ch); + sb.Insert(0, ch); + } + else + end = true; + } + else + sb.Insert(0, ch); break; + case '[': + case '<': + case '(': + if (kav.Count == 0)//esli ne v kavychkah + { + if (ch == '(') + if (skobki.Count > 0) + skobki.Pop(); + else skobki.Push('('); + //esli byli zakryvaushie tokeny (polagaem, chto skobki korrektny, esli net, to parser v lubom sluchae ne proparsit + if (tokens.Count > 0) + { + if (ch != '<') + tokens.Pop(); + else if (ugl_skobki.Count > 0) + { + tokens.Pop(); + ugl_skobki.Pop(); + } + sb.Insert(0, ch);//dobavljaem k stroke + if (ch == '(') + { + int tmp = i--; + /*while (i >= 0 && (char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '&')) + { + i--; + }*/ + while (i >= 0 && (Text[i] == ' ' || char.IsControl(Text[i]) || Text[i] == '}')) + { + if (Text[i] != '}') + { + i--; + } + else + { + while (i >= 0 && Text[i] != '{') + { + //propusk kommentariev + i--; + } + if (i >= 0) + i--; + } + } + + if (i >= 0 && (char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '&' || Text[i] == '!')) + { + bound = i + 1; + TestForKeyword(Text, i, ref bound, punkt_sym, out keyw); + if (keyw == KeywordKind.New) + bound = 0; + else + if (keyw != KeywordKind.None && tokens.Count == 0) + end = true; + else + bound = 0; + } + else if (i >= 0 && Text[i] == '\'') return ""; + i = tmp; + } + } + else if (ch == '<' || ch == '>') + { + if (tokens.Count > 0 || pressed_key == ',') + sb.Insert(0, ch); + else + end = true; + } + else + if (!comma_pressed) //esli my ne v parametrah + end = true; //zakonchili, tak kak doshli do pervoj skobki + else + { + sb.Remove(0, sb.Length);//doshli do skobki, byla nazhata zapjataja, poetomu udaljaem vse parametry + if (ch == '(') + on_brace = true; + //on_skobka = true; + comma_pressed = false; + } + } + else sb.Insert(0, ch); + break; + case '\'': + if (kav.Count == 0) + kav.Push(ch); + else + kav.Pop(); + sb.Insert(0, ch); + if (kav.Count == 0 && tokens.Count == 0) + end = true; + break; + default: + if (!(ch == ' ' || char.IsControl(ch))) + { + if (ch == '^') + sb.Insert(0, ch); + else + if (kav.Count == 0)//ne v kavychkah + { + if (tokens.Count == 0) + { + if (ch != ',' && !comma_pressed) + end = true;//esli ne na zapjatoj i ne v parametrah, to finish + else if (ch == ',' && !comma_pressed) + end = true; + else if (ch == ',' && (pressed_key == '(' || pressed_key == '[')) + end = true; + else + { + sb.Insert(0, ch);//prodolzhaem + if (isOperator(Text, i, out next)) + { + i = next; + continue; + } + } + + } + else + sb.Insert(0, ch);//esli est skobki, prodolzhaem + if (!end && ch == ',') + { + if (tokens.Count == 0) + num_param++;//esli na zapjatoj, uvelichivaem nomer parametra + } + } + else + sb.Insert(0, ch);//prodolzhaem + + } + else + if (Text[i] == '\n') + { + bool one_line_comment = false; + int comment_position = -1; + if (CheckForComment(Text, i - 1, out comment_position, out one_line_comment)) //proverjaem, net li kommenta ne predydushej stroke + { + if (!one_line_comment) + end = true; + else + { + sb.Insert(0, ch); + i = comment_position; + } + + } + else + sb.Insert(0, ch);//a inache vyrazhenie na neskolkih strokah + } + else + sb.Insert(0, ch); + break; + } + + if (end) + { + if (comma_pressed && !on_brace) + return ""; + bool one_line_comment = false; + int comment_position = -1; + if (CheckForComment(Text, i, out comment_position, out one_line_comment))//proverka na kommentarii + { + int new_line_ind = sb.ToString().IndexOf('\n'); + if (new_line_ind != -1) sb = sb.Remove(0, new_line_ind + 1); + else sb = sb.Remove(0, sb.Length); + } + break; + } + i--; + } + if (pressed_key == ',') + num_param++; + } + catch (Exception e) + { + + } + if (pressed_key == ',' && (!on_brace || skobki.Count == 0)) + return ""; + //return RemovePossibleKeywords(sb); + return sb.ToString(); + } + } +} diff --git a/PascalABCLanguageInfo/PascalABCLanguage.cs b/PascalABCLanguageInfo/PascalABCLanguage.cs index ed66ce0bb..985ed6bd7 100644 --- a/PascalABCLanguageInfo/PascalABCLanguage.cs +++ b/PascalABCLanguageInfo/PascalABCLanguage.cs @@ -15,6 +15,7 @@ namespace Languages.Pascal public PascalABCLanguage() : base( languageInformation: new Frontend.Data.PascalABCLanguageInformation(), + languageIntellisenseSupport: new Frontend.Data.PascalABCIntellisenseSupport(), parser: new Frontend.Wrapping.PascalABCNewLanguageParser(), docParser: new Frontend.Documentation.PascalDocTagsLanguageParser(), diff --git a/PascalABCLanguageInfo/PascalABCLanguageInformation.cs b/PascalABCLanguageInfo/PascalABCLanguageInformation.cs index 63f9d1a64..d10fbfd46 100644 --- a/PascalABCLanguageInfo/PascalABCLanguageInformation.cs +++ b/PascalABCLanguageInfo/PascalABCLanguageInformation.cs @@ -1,11 +1,7 @@ // Copyright (c) Ivan Bondarev, Stanislav Mikhalkovich (for details please see \doc\copyright.txt) // This code is distributed under the GNU LGPL (for details please see \doc\license.txt) using System; -using System.Text; -using System.Linq; using System.Collections.Generic; -using PascalABCCompiler.SyntaxTree; -using System.Reflection; using PascalABCCompiler.Parsers; using PascalABCCompiler; @@ -14,34 +10,29 @@ using static PascalABCCompiler.ParserTools.Directives.DirectiveHelper; namespace Languages.Pascal.Frontend.Data { - public class PascalABCLanguageInformation : BaseLanguageInformation + public class PascalABCLanguageInformation : ILanguageInformation { - public override string Name => StringConstants.pascalLanguageName; + public string Name => StringConstants.pascalLanguageName; - public override string Version => "1.2"; + public string Version => "1.2"; - public override string Copyright => "Copyright © 2005-2026 by Ivan Bondarev, Stanislav Mikhalkovich"; + public string Copyright => "Copyright © 2005-2026 by Ivan Bondarev, Stanislav Mikhalkovich"; - public override string[] FilesExtensions => new string[] { StringConstants.pascalSourceFileExtension }; + public bool CaseSensitive => false; - public override string[] SystemUnitNames => StringConstants.pascalDefaultStandardModules; + public string[] FilesExtensions => new string[] { StringConstants.pascalSourceFileExtension }; - public override bool SyntaxTreeIsConvertedAfterUsedModulesCompilation => false; + public string[] SystemUnitNames => StringConstants.pascalDefaultStandardModules; - public override bool ApplySyntaxTreeConvertersForIntellisense => false; + public bool SyntaxTreeIsConvertedAfterUsedModulesCompilation => false; - protected IParser Parser - { - get - { - // Поле парсера желательно убрать отсюда EVA - return Facade.LanguageProvider.Instance.SelectLanguageByName(StringConstants.pascalLanguageName).Parser; - } - } + public string CommentSymbol => "//"; - public override BaseKeywords KeywordsStorage { get; } = new Core.PascalABCKeywords(); + public Dictionary SpecialModulesAliases => null; - public override Dictionary ValidDirectives { get; protected set; } + public BaseKeywords KeywordsStorage { get; } = new Core.PascalABCKeywords(); + + public Dictionary ValidDirectives { get; protected set; } public PascalABCLanguageInformation() { @@ -95,1891 +86,6 @@ namespace Languages.Pascal.Frontend.Data }; #endregion } - - public override string CommentSymbol => "//"; - - public override string BodyStartBracket - { - get - { - return "begin"; - } - } - - public override string BodyEndBracket - { - get - { - return "end"; - } - } - - public List Keywords - { - get - { - return KeywordsStorage.KeywordsForIntellisenseList; - } - } - - public List TypeKeywords - { - get - { - return KeywordsStorage.TypeKeywords; - } - } - - public override string ParameterDelimiter - { - get - { - return ";"; - } - } - - public override string DelimiterInIndexer => ","; - - public override string ResultVariableName => "Result"; - - public override string ProcedureName => "procedure"; - - public override string FunctionName => "function"; - - public override string GenericTypesStartBracket => "<"; - - public override string GenericTypesEndBracket => ">"; - - public override string ReturnTypeDelimiter => ":"; - - protected override string IntTypeName => "integer"; - - public override bool CaseSensitive - { - get - { - return false; - } - } - - public override bool IncludeDotNetEntities - { - get - { - return true; - } - } - - public override bool AddStandardUnitNamesToUserScope => true; - - public override bool AddStandardNetNamespacesToUserScope => true; - - public override bool UsesFunctionsOverlappingSourceContext => false; - - public override bool IsParams(string paramDescription) - { - return paramDescription.Contains("...") || paramDescription.TrimStart().StartsWith("params"); - } - - public override string GetDescription(IBaseScope scope) - { - switch (scope.Kind) - { - case ScopeKind.Type: return GetDescriptionForType(scope as ITypeScope); - case ScopeKind.CompiledType: return GetDescriptionForCompiledType(scope as ICompiledTypeScope); - case ScopeKind.Delegate: return GetDescriptionForDelegate(scope as IProcType); - case ScopeKind.TypeSynonim: return GetSynonimDescription(scope as ITypeSynonimScope); - case ScopeKind.Array: return GetDescriptionForArray(scope as IArrayScope); - case ScopeKind.Diapason: return GetDescriptionForDiapason(scope as IDiapasonScope); - case ScopeKind.File: return GetDescriptionForFile(scope as IFileScope); - case ScopeKind.Pointer: return GetDescriptionForPointer(scope as IPointerScope); - case ScopeKind.Enum: return GetDescriptionForEnum(scope as IEnumScope); - case ScopeKind.Set: return GetDescriptionForSet(scope as ISetScope); - case ScopeKind.ElementScope: return GetDescriptionForElementScope(scope as IElementScope); - case ScopeKind.CompiledField: return GetDescriptionForCompiledField(scope as ICompiledFieldScope); - case ScopeKind.CompiledProperty: return GetDescriptionForCompiledProperty(scope as ICompiledPropertyScope); - case ScopeKind.CompiledMethod: return GetDescriptionForCompiledMethod(scope as ICompiledMethodScope); - case ScopeKind.Namespace: return GetDescriptionForNamespace(scope as INamespaceScope); - case ScopeKind.Procedure: return GetDescriptionForProcedure(scope as IProcScope); - case ScopeKind.CompiledEvent: return GetDescriptionForCompiledEvent(scope as ICompiledEventScope); - case ScopeKind.CompiledConstructor: return GetDescriptionForCompiledConstructor(scope as ICompiledConstructorScope); - case ScopeKind.ShortString: return GetDescriptionForShortString(scope as IShortStringScope); - } - return ""; - } - - public override string GetSimpleDescription(IBaseScope scope) - { - if (scope == null) - return ""; - switch (scope.Kind) - { - case ScopeKind.Delegate: - case ScopeKind.Array: - case ScopeKind.Diapason: - case ScopeKind.File: - case ScopeKind.Pointer: - case ScopeKind.Enum: - case ScopeKind.Set: - case ScopeKind.ShortString: - if (scope is ITypeScope && (scope as ITypeScope).Aliased) - return scope.Name; - break; - } - switch (scope.Kind) - { - case ScopeKind.Type: return GetSimpleDescriptionForType(scope as ITypeScope); - case ScopeKind.CompiledType: return GetSimpleDescriptionForCompiledType(scope as ICompiledTypeScope); - case ScopeKind.Delegate: return GetDescriptionForDelegate(scope as IProcType); - case ScopeKind.TypeSynonim: return GetSimpleSynonimDescription(scope as ITypeSynonimScope); - case ScopeKind.Array: return GetDescriptionForArray(scope as IArrayScope); - case ScopeKind.Diapason: return GetDescriptionForDiapason(scope as IDiapasonScope); - case ScopeKind.File: return GetDescriptionForFile(scope as IFileScope); - case ScopeKind.Pointer: return GetDescriptionForPointer(scope as IPointerScope); - case ScopeKind.Enum: return GetDescriptionForEnum(scope as IEnumScope); - case ScopeKind.Set: return GetDescriptionForSet(scope as ISetScope); - case ScopeKind.ElementScope: return GetSimpleDescriptionForElementScope(scope as IElementScope); - case ScopeKind.CompiledField: return GetDescriptionForCompiledField(scope as ICompiledFieldScope); - case ScopeKind.CompiledProperty: return GetDescriptionForCompiledProperty(scope as ICompiledPropertyScope); - case ScopeKind.CompiledMethod: return GetDescriptionForCompiledMethod(scope as ICompiledMethodScope); - case ScopeKind.Namespace: return GetDescriptionForNamespace(scope as INamespaceScope); - case ScopeKind.Procedure: return GetSimpleDescriptionForProcedure(scope as IProcScope); - case ScopeKind.CompiledEvent: return GetDescriptionForCompiledEvent(scope as ICompiledEventScope); - case ScopeKind.CompiledConstructor: return GetDescriptionForCompiledConstructor(scope as ICompiledConstructorScope); - case ScopeKind.ShortString: return GetDescriptionForShortString(scope as IShortStringScope); - case ScopeKind.UnitInterface: return GetDescriptionForModule(scope as IInterfaceUnitScope); - //case ScopeKind.Procedure : return GetDescriptionForProcedure(scope as IProcScope); - } - return ""; - } - - protected override string GetSimpleDescriptionForType(ITypeScope scope) - { - // Замена на отображаемое имя для set (семантический Intellisense находит тип, которым set реализован) - if (scope.Name == StringConstants.pascalSetClassName && scope.TopScope.Name == StringConstants.pascalSystemUnitName) - return "set of " + GetTemplateStringWithoutBrackets(scope); - - return base.GetSimpleDescriptionForType(scope); - } - - private string GetDescriptionForModule(IInterfaceUnitScope scope) - { - return (scope.IsNamespaceUnit ? "namespace " : "unit ") + scope.Name; - } - - - public override string GetShortName(ICompiledConstructorScope scope) - { - return StringConstants.default_constructor_name; - } - - public override string GetKeyword(SymbolKind kind) - { - switch (kind) - { - case SymbolKind.Class: return "class"; - case SymbolKind.Enum: return "enum"; - case SymbolKind.Struct: return "record"; - case SymbolKind.Type: return "type"; - case SymbolKind.Interface: return "interface"; - case SymbolKind.Null: return "nil"; - } - return ""; - } - - public override string GetArrayDescription(string elementType, int rank) - { - if (rank == 1) - return "array of " + elementType; - else - { - StringBuilder sb = new StringBuilder(); - sb.Append('['); - sb.Append(',', rank - 1); - sb.Append(']'); - return "array" + sb.ToString() + " of " + elementType; - } - } - - public override string GetStandardTypeByKeyword(KeywordKind keyw) - { - switch (keyw) - { - case KeywordKind.ObjectType: return "object"; - case KeywordKind.StringType: return "string"; - case KeywordKind.ByteType: return "byte"; - case KeywordKind.SByteType: return "shortint"; - case KeywordKind.ShortType: return "smallint"; - case KeywordKind.UShortType: return "word"; - case KeywordKind.IntType: return "integer"; - case KeywordKind.UIntType: return "longword"; - case KeywordKind.Int64Type: return "int64"; - case KeywordKind.UInt64Type: return "uint64"; - case KeywordKind.DoubleType: return "real"; - case KeywordKind.FloatType: return "single"; - case KeywordKind.CharType: return "char"; - case KeywordKind.BoolType: return "boolean"; - case KeywordKind.PointerType: return "pointer"; - } - return null; - } - - protected override string GetFullTypeName(Type ctn, bool no_alias = true) - { - TypeCode tc = Type.GetTypeCode(ctn); - if (ctn.FullName == null && !ctn.IsArray && !ctn.IsGenericTypeDefinition && ctn.IsGenericParameter) - return ctn.Name; - if (!ctn.IsEnum) - { - switch (tc) - { - case TypeCode.Int32: return "integer"; - case TypeCode.Double: return "real"; - case TypeCode.Boolean: return "boolean"; - case TypeCode.String: return "string"; - case TypeCode.Char: return "char"; - case TypeCode.Byte: return "byte"; - case TypeCode.SByte: return "shortint"; - case TypeCode.Int16: return "smallint"; - case TypeCode.Int64: return "int64"; - case TypeCode.UInt16: return "word"; - case TypeCode.UInt32: return "longword"; - case TypeCode.UInt64: return "uint64"; - case TypeCode.Single: return "single"; - } - if (ctn.IsPointer) - if (ctn.FullName == "System.Void*") - return "pointer"; - else - return "^" + GetFullTypeName(ctn.GetElementType()); - } - else - return ctn.FullName; - if (!no_alias) - { - if (ctn.Name.Contains("Func`") || ctn.Name.Contains("Predicate`")) - return getLambdaRepresentation(ctn, true, new List()); - else if (ctn.Name.Contains("Action`")) - return getLambdaRepresentation(ctn, false, new List()); - else if (ctn.Name == "IEnumerable`1") - return "sequence of " + GetShortTypeName(ctn.GetGenericArguments()[0], false); - else if (ctn.Name.Contains("Tuple`")) - return get_tuple_string(ctn); - } - int gen_pos = ctn.Name.IndexOf("`"); - if (gen_pos != -1 || ctn.IsGenericType) - { - int len = ctn.GetGenericArguments().Length; - Type[] gen_ps = ctn.GetGenericArguments(); - System.Text.StringBuilder sb = new System.Text.StringBuilder(); - if (gen_pos != -1) - sb.Append(ctn.Namespace + "." + ctn.Name.Substring(0, gen_pos)); - else - sb.Append(ctn.Namespace + "." + ctn.Name); - sb.Append(GenericTypesStartBracket); - for (int i = 0; i < len; i++) - { - sb.Append(gen_ps[i].Name); - if (i < len - 1) - sb.Append(", "); - } - sb.Append(GenericTypesEndBracket); - return sb.ToString(); - } - if (ctn.IsArray) - { - var rank = ctn.GetArrayRank(); - var strrank = rank > 1 ? "[" + new string(',', rank - 1) + "]" : ""; - return $"array{strrank}" + " of " + GetFullTypeName(ctn.GetElementType()); - } - if (ctn == Type.GetType("System.Void*")) return "pointer"; - if (ctn.IsNested) - return ctn.Name; - return ctn.FullName; - } - - public override string GetClassKeyword(PascalABCCompiler.SyntaxTree.class_keyword keyw) - { - switch (keyw) - { - case PascalABCCompiler.SyntaxTree.class_keyword.Class: return "class"; - case PascalABCCompiler.SyntaxTree.class_keyword.Interface: return "interface"; - case PascalABCCompiler.SyntaxTree.class_keyword.Record: return "record"; - case PascalABCCompiler.SyntaxTree.class_keyword.TemplateClass: return "template class"; - case PascalABCCompiler.SyntaxTree.class_keyword.TemplateRecord: return "template record"; - case PascalABCCompiler.SyntaxTree.class_keyword.TemplateInterface: return "template interface"; - } - return null; - } - - public override string GetShortTypeName(Type ctn, bool noalias = true) - { - TypeCode tc = Type.GetTypeCode(ctn); - if (ctn.FullName == null && !ctn.IsArray && !ctn.IsGenericTypeDefinition && ctn.IsGenericParameter) - return ctn.Name; - if (!ctn.IsEnum) - { - switch (tc) - { - case TypeCode.Int32: return "integer"; - case TypeCode.Double: return "real"; - case TypeCode.Boolean: return "boolean"; - case TypeCode.String: return "string"; - case TypeCode.Char: return "char"; - case TypeCode.Byte: return "byte"; - case TypeCode.SByte: return "shortint"; - case TypeCode.Int16: return "smallint"; - case TypeCode.Int64: return "int64"; - case TypeCode.UInt16: return "word"; - case TypeCode.UInt32: return "longword"; - case TypeCode.UInt64: return "uint64"; - case TypeCode.Single: return "single"; - } - if (ctn.IsPointer) - if (ctn.FullName == "System.Void*") - return "pointer"; - else - return "^" + GetShortTypeName(ctn.GetElementType(), noalias); - } - else return ctn.Name; - if (ctn.Name.Contains("`")) - { - if (!noalias) - { - if (ctn.Name.Contains("Func`") || ctn.Name.Contains("Predicate`")) - return getLambdaRepresentation(ctn, true, new List()); - else if (ctn.Name.Contains("Action`")) - return getLambdaRepresentation(ctn, false, new List()); - else if (ctn.Name == "IEnumerable`1") - return "sequence of " + GetShortTypeName(ctn.GetGenericArguments()[0], false); - else if (ctn.Name.Contains("Tuple`")) - return get_tuple_string(ctn); - } - int len = ctn.GetGenericArguments().Length; - System.Text.StringBuilder sb = new System.Text.StringBuilder(); - sb.Append(ctn.Name.Substring(0, ctn.Name.IndexOf('`'))); - sb.Append(GenericTypesStartBracket); - if (!noalias) - { - Type[] gen_ps = ctn.GetGenericArguments(); - for (int i = 0; i < len; i++) - { - sb.Append(gen_ps[i].Name); - if (i < len - 1) - sb.Append(", "); - } - } - sb.Append(GenericTypesEndBracket); - /*sb.Append('<'); - for (int i=0; i');*/ - return sb.ToString(); - } - if (ctn.IsArray) - { - var rank = ctn.GetArrayRank(); - var strrank = rank > 1 ? "[" + new string(',', rank - 1) + "]" : ""; - return $"array{strrank}" + " of " + GetShortTypeName(ctn.GetElementType()); - } - //if (ctn == Type.GetType("System.Void*")) return PascalABCCompiler.StringConstants.pointer_type_name; - return ctn.Name; - } - - protected string GetDescriptionForType(ITypeScope scope) - { - string template_str = GetTemplateString(scope); - switch (scope.ElemKind) - { - case SymbolKind.Class: - string mod = ""; - if (scope.IsStatic) - mod = "static "; - else - { - if (scope.IsAbstract) - mod = "abstract "; - if (scope.IsFinal) - mod += "sealed "; - } - if (scope.TopScope != null && scope.TopScope.Name != "" && !scope.TopScope.Name.Contains("$")) - return mod + "class " + scope.TopScope.Name + "." + scope.Name + template_str; - else return mod + "class " + scope.Name + template_str; - case SymbolKind.Interface: - if (scope.TopScope != null && scope.TopScope.Name != "" && !scope.TopScope.Name.Contains("$")) - return "interface " + scope.TopScope.Name + "." + scope.Name + template_str; - else return "interface " + scope.Name + template_str; - case SymbolKind.Enum: - if (scope.TopScope != null && scope.TopScope.Name != "" && !scope.TopScope.Name.Contains("$")) - return "enum " + scope.TopScope.Name + "." + scope.Name; - else return "enum " + scope.Name; - case SymbolKind.Delegate: - if (scope.TopScope != null && scope.TopScope.Name != "" && !scope.TopScope.Name.Contains("$")) - return "delegate " + scope.TopScope.Name + "." + scope.Name + template_str; - else return "delegate " + scope.Name + template_str; - case SymbolKind.Struct: - if (scope.TopScope != null && scope.TopScope.Name != "" && !scope.TopScope.Name.Contains("$")) - return "record " + scope.TopScope.Name + "." + scope.Name + template_str; - else return "record " + scope.Name + template_str; - } - - if (scope.TopScope != null) - return scope.TopScope.Name + "." + scope.Name; - else return scope.Name; - } - - protected string GetDescriptionForCompiledType(ICompiledTypeScope scope) - { - string s = GetFullTypeName(scope.CompiledType); - ITypeScope[] instances = scope.GenericInstances; - if (instances.Length > 0) - { - System.Text.StringBuilder sb = new System.Text.StringBuilder(); - int ind = s.IndexOf(GenericTypesStartBracket); - if (ind != -1) sb.Append(s.Substring(0, ind)); - else - sb.Append(s); - sb.Append(GenericTypesStartBracket); - for (int i = 0; i < instances.Length; i++) - { - sb.Append(GetSimpleDescriptionWithoutNamespace(instances[i])); - //sb.Append(instances[i].Name); - if (i < instances.Length - 1) sb.Append(", "); - } - sb.Append(GenericTypesEndBracket); - s = sb.ToString(); - } - - switch (scope.ElemKind) - { - case SymbolKind.Class: - string mod = ""; - if (scope.IsStatic) - mod = "static "; - else - { - if (scope.IsAbstract) - mod = "abstract "; - if (scope.IsFinal) - mod += "sealed "; - } - return mod + "class " + s; - case SymbolKind.Interface: - return "interface " + s; - case SymbolKind.Enum: - return "enum " + s; - case SymbolKind.Delegate: - return "delegate " + s; - case SymbolKind.Struct: - return "record " + s; - case SymbolKind.Type: - return "type " + s; - } - return s; - } - - private string GetDescriptionForDiapason(IDiapasonScope scope) - { - return scope.Left.ToString() + ".." + scope.Right.ToString(); - } - - private string GetDescriptionForFile(IFileScope scope) - { - System.Text.StringBuilder sb = new System.Text.StringBuilder(); - sb.Append("file"); - if (scope.ElementType != null) - { - string s = GetSimpleDescription(scope.ElementType); - if (s.Length > 0 && s[0] == '$') s = s.Substring(1, s.Length - 1); - sb.Append(" of " + s); - } - return sb.ToString(); - } - - private string GetDescriptionForPointer(IPointerScope scope) - { - string s = ""; - if (scope.ElementType != null) - { - s = "^" + GetSimpleDescription(scope.ElementType); - } - else - s = "pointer"; - - return s; - } - - private string GetDescriptionForSet(ISetScope scope) - { - System.Text.StringBuilder sb = new System.Text.StringBuilder(); - sb.Append("set of "); - if (scope.ElementType != null) - { - string s = GetSimpleDescription(scope.ElementType); - if (s.Length > 0 && s[0] == '$') s = s.Substring(1, s.Length - 1); - sb.Append(s); - } - return sb.ToString(); - } - - private string GetDescriptionForNamespace(INamespaceScope scope) - { - return "namespace " + scope.Name; - } - - public override string GetSynonimDescription(ITypeScope scope) - { - return "type " + scope.Name + GetGenericString(scope.TemplateArguments) + " = " + scope.Description; - } - - public override string GetSynonimDescription(ITypeSynonimScope scope) - { - if (scope.ActType is ICompiledTypeScope && !(scope.ActType as ICompiledTypeScope).Aliased) - return "type " + scope.Name + GetGenericString(scope.TemplateArguments) + " = " + GetSimpleDescriptionForCompiledType(scope.ActType as ICompiledTypeScope, true); - else - return "type " + scope.Name + GetGenericString(scope.TemplateArguments) + " = " + GetSimpleDescription(scope.ActType); - } - - public override string GetSynonimDescription(IProcScope scope) - { - return "type " + scope.Name + " = " + scope.Description; - } - - private string GetSimpleSynonimDescription(ITypeSynonimScope scope) - { - return scope.Name; - } - - public override string GetStringForChar(char c) - { - return "'" + c.ToString() + "'"; - } - - public override string GetStringForSharpChar(int num) - { - return "#" + num.ToString(); - } - - public override string GetStringForString(string s) - { - return "'" + s + "'"; - } - - - protected string GetAccessModifier(access_modifer mod) - { - switch (mod) - { - case access_modifer.private_modifer: return "private"; - case access_modifer.protected_modifer: return "protected"; - case access_modifer.public_modifer: return "public"; - case access_modifer.published_modifer: return "published"; - case access_modifer.internal_modifer: return "internal"; - } - return ""; - } - - public override string ConstructOverridedMethodHeader(IProcScope scope, out int off) - { - System.Text.StringBuilder sb = new System.Text.StringBuilder(); - if (scope.AccessModifier != access_modifer.internal_modifer) - sb.Append(GetAccessModifier(scope.AccessModifier) + " "); - if (scope.ReturnType == null) - sb.Append("procedure "); - else - sb.Append("function "); - off = sb.Length; - sb.Append(scope.Name); - sb.Append(GetGenericString(scope.TemplateParameters)); - if (!(scope is ICompiledMethodScope)) - { - IElementScope[] parameters = scope.Parameters; - if (parameters != null && parameters.Length > 0) - { - sb.Append('('); - for (int i = 0; i < scope.Parameters.Length; i++) - { - sb.Append(GetSimpleDescription(parameters[i])); - if (i < parameters.Length - 1) - { - sb.Append(ParameterDelimiter + " "); - } - } - sb.Append(')'); - } - } - else - { - ParameterInfo[] pis = (scope as ICompiledMethodScope).CompiledMethod.GetParameters(); - if (pis.Length > 0) - { - sb.Append('('); - for (int i = 0; i < pis.Length; i++) - { - if (pis[i].ParameterType.IsByRef) - sb.Append("var "); - else if (IsParams(pis[i])) - sb.Append("params "); - sb.Append(pis[i].Name); - sb.Append(": "); - if (!pis[i].ParameterType.IsByRef) - sb.Append(GetFullTypeName(pis[i].ParameterType)); - else sb.Append(GetFullTypeName(pis[i].ParameterType.GetElementType())); - if (i < pis.Length - 1) - sb.Append(ParameterDelimiter + " "); - } - sb.Append(')'); - } - } - if (scope.ReturnType != null) - sb.Append(ReturnTypeDelimiter + " " + GetSimpleDescription(scope.ReturnType)); - sb.Append("; override;"); - return sb.ToString(); - } - - public override string ConstructHeader(IProcRealizationScope scope, int tabCount) - { - System.Text.StringBuilder sb = new System.Text.StringBuilder(); - sb.Append('\t'); - if (!scope.DefProc.IsAbstract) - sb.Append(GetAccessModifier(access_modifer.public_modifer) + " "); - else - if (scope.DefProc.AccessModifier != access_modifer.none && scope.DefProc.AccessModifier != access_modifer.internal_modifer) - sb.Append(GetAccessModifier(scope.DefProc.AccessModifier) + " "); - if (scope.DefProc.ReturnType == null) - sb.Append("procedure "); - else - sb.Append("function "); - sb.Append(scope.Name); - sb.Append(GetGenericString(scope.TemplateParameters)); - - if (!(scope.DefProc is ICompiledMethodScope)) - { - IElementScope[] parameters = scope.DefProc.Parameters; - if (parameters != null && parameters.Length > 0) - { - sb.Append('('); - for (int i = 0; i < scope.DefProc.Parameters.Length; i++) - { - sb.Append(GetSimpleDescription(parameters[i])); - if (i < parameters.Length - 1) - { - sb.Append(ParameterDelimiter + " "); - } - } - sb.Append(')'); - } - } - else - { - ParameterInfo[] pis = (scope.DefProc as ICompiledMethodScope).CompiledMethod.GetParameters(); - if (pis.Length > 0) - { - sb.Append('('); - for (int i = 0; i < pis.Length; i++) - { - if (pis[i].ParameterType.IsByRef) - sb.Append("var "); - else if (IsParams(pis[i])) - sb.Append("params "); - sb.Append(pis[i].Name); - sb.Append(": "); - if (!pis[i].ParameterType.IsByRef) - sb.Append(GetFullTypeName(pis[i].ParameterType)); - else sb.Append(GetFullTypeName(pis[i].ParameterType.GetElementType())); - if (i < pis.Length - 1) - sb.Append(ParameterDelimiter + " "); - } - sb.Append(')'); - } - } - - if (scope.DefProc.ReturnType != null) - sb.Append(ReturnTypeDelimiter + " " + GetSimpleDescription(scope.DefProc.ReturnType)); - sb.Append(';'); - if (scope.DefProc.IsAbstract) - sb.Append("override;"); - return sb.ToString(); - } - - private void get_procedure_template(procedure_header header, StringBuilder res, int col) - { - if (header.parameters != null) - for (int i = 0; i < header.parameters.params_list.Count; i++) - for (int j = 0; j < header.parameters.params_list[i].idents.idents.Count; j++) - { - res.AppendLine(); - for (int k = 0; k < col - 3; k++) - res.Append(' '); - res.Append("/// "); - } - if (header is function_header) - { - res.AppendLine(); - for (int k = 0; k < col - 3; k++) - res.Append(' '); - res.Append("/// "); - } - } - - public override string GetDocumentTemplate(string lineText, string Text, int line, int col, int pos) - { - try - { - if (lineText == null) return ""; - StringBuilder res = new StringBuilder(); - if (lineText.StartsWith("procedure") || lineText.StartsWith("function") || lineText.StartsWith("constructor") || lineText.StartsWith("destructor")) - { - StringBuilder sb = new StringBuilder(); - sb.AppendLine(lineText); - sb.AppendLine("begin end;"); - sb.AppendLine("begin end."); - program_module node = this.Parser.GetCompilationUnit("test.pas", sb.ToString(), null, null, ParseMode.Special, false) as program_module; - procedure_header header = (node.program_block.defs.defs[0] as procedure_definition).proc_header; - get_procedure_template(header, res, col); - return res.ToString(); - } - else if (lineText.StartsWith("class") || lineText.StartsWith("public") || lineText.StartsWith("private") || lineText.StartsWith("protected") || lineText.StartsWith("internal")) - { - StringBuilder sb = new StringBuilder(); - sb.AppendLine(lineText); - sb.AppendLine("begin end;"); - sb.AppendLine("begin end."); - program_module node = this.Parser.GetCompilationUnit("test.pas", sb.ToString(), null, null, ParseMode.Special, false) as program_module; - if (node.program_block.defs != null && node.program_block.defs.defs.Count > 0 && node.program_block.defs.defs[0] is procedure_definition) - { - procedure_header header = (node.program_block.defs.defs[0] as procedure_definition).proc_header; - get_procedure_template(header, res, col); - return res.ToString(); - } - return ""; - } - else return ""; - } - catch - { - - } - return ""; - } - - public override string GetUnitTemplate(string unitName) - { - var sb = new StringBuilder(); - - sb.AppendLine("unit " + unitName + ";"); - sb.AppendLine(); - sb.AppendLine("interface"); - sb.AppendLine(); - sb.AppendLine("implementation"); - sb.AppendLine(); - sb.Append("end."); - - return sb.ToString(); - } - - public override string ConstructHeader(string meth, IProcScope scope, int tabCount) - { - int i = 0; - bool is_cnstr = false; - StringBuilder sb = new StringBuilder(); - if (meth.StartsWith("static ")) - meth = meth.Remove(0, "static ".Length); - else if (meth.StartsWith("class ")) - meth = meth.Remove(0, "class ".Length); - if (scope.IsStatic) - sb.Append("static "); - while (i < meth.Length && char.IsLetterOrDigit(meth[i])) - { - sb.Append(meth[i++]); - } - if (sb.ToString().ToLower() == "constructor") is_cnstr = true; - sb.Append(' '); - while (i < meth.Length && !(char.IsLetterOrDigit(meth[i]) || meth[i] == '_' || meth[i] == '(' || meth[i] == ';')) - if (meth[i] == '{') - while (i < meth.Length && meth[i] != '}') i++; - else - i++; - if (i < meth.Length) - { - if (scope.TopScope is ITypeScope && ((scope.TopScope as ITypeScope).ElemKind == SymbolKind.Class || (scope.TopScope as ITypeScope).ElemKind == SymbolKind.Struct)) - sb.Append(GetSimpleDescriptionForType(scope.TopScope as ITypeScope) + "."); - //if (meth[i] == '(' || meth[i] == ';') - sb.Append(scope.Name); - sb.Append(GetGenericString(scope.TemplateParameters)); - - while (i < meth.Length && (char.IsLetterOrDigit(meth[i]) || meth[i] == '_')) i++; - while (i < meth.Length && meth[i] != ';' && meth[i] != '(' && meth[i] != ':') - if (meth[i] == '{') while (i < meth.Length && meth[i] != '}') i++; - else i++; - if (meth[i] == '(') - { - sb.Append('('); - bool in_kav = false; - Stack sk_stack = new Stack(); - sk_stack.Push('('); i++; - bool default_value = false; - while (i < meth.Length && sk_stack.Count > 0) - { - if (meth[i] == '\'') in_kav = !in_kav; - else if (meth[i] == '(') { if (!in_kav) sk_stack.Push('('); } - else if (meth[i] == ')') { if (!in_kav) sk_stack.Pop(); } - if (meth[i] == ':' && meth[i + 1] == '=' && !in_kav) - default_value = true; - else if (meth[i] == ';' && !in_kav) - default_value = false; - if (!default_value || meth[i] == ')' && sk_stack.Count == 0) - { - if (meth[i] == ')' && sk_stack.Count == 0 && default_value) - sb = new StringBuilder(sb.ToString().TrimEnd()); - sb.Append(meth[i]); - } - i++; - } - while (i < meth.Length && meth[i] != ':' && meth[i] != ';') - if (meth[i] == '{') while (i < meth.Length && meth[i] != '}') i++; - else sb.Append(meth[i++]); - - //sb.Append(')'); - } - if (meth[i] == ':') - { - bool in_kav = false; - while (i < meth.Length && !(meth[i] == ';' && !in_kav)) - { - if (meth[i] == '{' && !in_kav) while (i < meth.Length && meth[i] != '}') i++; - else if (meth[i] == '\'') in_kav = !in_kav; - sb.Append(meth[i]); - i++; - } - } - sb.Append(';'); - } - sb.AppendLine(); - sb.AppendLine("begin"); - for (int j = 0; j < tabCount; j++) - sb.Append(' '); - sb.AppendLine(); - sb.AppendLine("end;"); - return sb.ToString(); - } - - private bool isOperator(string Text, int i, out int next) - { - next = i; - if (i >= 3) - { - string op = Text.Substring(i - 2, 3).ToLower().Trim(); - if (op == "and" || op == "div" || op == "mod" || op == "xor") - { - if (!char.IsLetterOrDigit(Text[i - 3]) && Text[i - 3] != '_' && Text[i - 3] != '&' && !(i + 1 < Text.Length && char.IsLetterOrDigit(Text[i + 1]))) - { - next = i - 3; - return true; - } - return false; - } - } - if (i >= 2) - { - string op = Text.Substring(i - 1, 2).ToLower().Trim(); - if (op == "or") - { - if (!char.IsLetterOrDigit(Text[i - 2]) && Text[i - 2] != '_' && Text[i - 2] != '&' && !(i + 1 < Text.Length && char.IsLetterOrDigit(Text[i + 1]))) - { - next = i - 2; - return true; - } - return false; - } - } - return false; - } - - private bool CheckForComment(string Text, int off, out int comment_position, out bool one_line_comment) - { - int i = off; - one_line_comment = false; - comment_position = -1; - Stack kav = new Stack(); - bool is_comm = false; - while (i >= 0 && !is_comm && Text[i] != '\n' && Text[i] != '\r') - { - if (Text[i] == '\'') - { - if (kav.Count == 0) kav.Push('\''); - else kav.Pop(); - } - else if (Text[i] == '{') - { - if (kav.Count == 0) - { - comment_position = i; - while (i >= 0 && Text[i] != '\'') - i--; - if (i >= 1 && Text[i - 1] == '$') - return false; - is_comm = true; - return is_comm; - } - } - else if (Text[i] == '}') - { - return false; - } - else if (Text[i] == '/') - if (i > 0 && Text[i - 1] == '/' && kav.Count == 0) - { - is_comm = true; - one_line_comment = true; - comment_position = i - 1; - } - - i--; - } - return is_comm; - } - - public override string FindExpression(int off, string Text, int line, int col, out KeywordKind keyw) - { - int i = off - 1; - int bound = 0; - bool punkt_sym = false; - keyw = KeywordKind.None; - System.Text.StringBuilder sb = new StringBuilder(); - Stack tokens = new Stack(); - Stack kav = new Stack(); - Stack ugl_skobki = new Stack(); - int num_in_ident = -1; - keyw = TestForKeyword(Text, i); - if (keyw == KeywordKind.Punkt) return ""; - while (i >= bound) - { - bool end = false; - char ch = Text[i]; - if (kav.Count == 0 && (char.IsLetterOrDigit(ch) || ch == '_' || ch == '&' || ch == '\'' || ch == '!')) - { - num_in_ident = i; - if (kav.Count == 0 && tokens.Count == 0) - { - int tmp = i; - if (ch == '\'') - { - i--; - if (kav.Count == 0) - kav.Push('\''); - while (i >= 0) - { - if (Text[i] != '\'') - i--; - else - { - if (i >= 1 && Text[i - 1] == '\'') - i -= 2; - else - break; - } - } - - if (i >= 0) - i--; - } - else - while (i >= 0 && (char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '&' || Text[i] == '!')) - { - i--; - } - while (i >= 0 && (Text[i] == ' ' || char.IsControl(Text[i]) || Text[i] == '}')) - { - if (Text[i] != '}') - i--; - else - { - while (i >= 0 && Text[i] != '{') //propusk kommentariev - i--; - if (i >= 0) - i--; - } - } - if (i >= 0 && (char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '&' || Text[i] == '!')) - { - bound = i + 1; - TestForKeyword(Text, i, ref bound, punkt_sym, out keyw); - for (int j = tmp; j > bound; j--) - { - sb.Insert(0, Text[j]); - } - if (sb.ToString().Trim() == "new") - return ""; - i = bound; - continue; - } - else if (i >= 0 && Text[i] == '\'') return ""; - i = tmp; - } - else - if (ch == '\'') - kav.Push('\''); - sb.Insert(0, ch);//.Append(Text[i]); - } - else if (ch == '.' || ch == '^' || ch == '&' || ch == '?' && IsPunctuation(Text, i + 1)) - { - if (ch == '.' && i >= 1 && Text[i - 1] == '.' && tokens.Count == 0) - end = true; - else if (ch == '?' && i + 1 < Text.Length && Text[i + 1] != '.') - end = true; - else - sb.Insert(0, ch); - if (ch != '.') - punkt_sym = true; - } - else if (ch == '}') - { - if (kav.Count == 0) - { - while (i >= 0 && Text[i] != '{') - { - if (Text[i] != '$')//skip {$ - sb.Insert(0, Text[i]); - i--; - } - if (i < 0) - { - break; - } - else if (Text[i] == '{') - { - sb.Insert(0, '{'); - } - } - else - sb.Insert(0, ch); - } - else if (ch == '{') - { - if (kav.Count == 0) - { - if (keyw == KeywordKind.None) - return sb.ToString(); - sb.Insert(0, ch); - break; - } - else sb.Insert(0, ch); - } - else - switch (ch) - { - case ')': - case ']': - if (kav.Count == 0) - { - string tmps = sb.ToString().Trim(' ', '\r', '\t', '\n'); - if (tmps.Length >= 1 && (char.IsLetter(tmps[0]) || tmps[0] == '_' || tmps[0] == '&' || tmps[0] == '?' || tmps[0] == '!') && tokens.Count == 0) - end = true; - else - tokens.Push(ch); - } - if (!end) - { - sb.Insert(0, ch); - punkt_sym = true; - } - break; - case '>': - if (tokens.Count == 0) - { - int j = i + 1; - - while (j < Text.Length && char.IsWhiteSpace(Text[j])) - j++; - - if (ugl_skobki.Count > 0 || i == off - 1 || j == off && off == Text.Length || j < Text.Length && Text[i - 1] != '-' && (Text[j] == '.' || Text[j] == '(')) - { - ugl_skobki.Push('>'); - sb.Insert(0, ch); - } - else if (i >= 1 && Text[i - 1] == '-') - { - if (!(kav.Count == 0 && tokens.Count == 0)) - sb.Insert(0, ch); - } - else - end = true; - } - else - sb.Insert(0, ch); - break; - case '<': - if (tokens.Count == 0) - { - if (ugl_skobki.Count > 0) - { - ugl_skobki.Pop(); - sb.Insert(0, ch); - } - else - end = true; - } - else - sb.Insert(0, ch); - break; - case '[': - case '(': - case '|': - if (ch == '|' && ((tokens.Count == 0) || (tokens.Peek() == ']') || (tokens.Peek() == ')') || (tokens.Peek() == ','))) - // Закрывающий | - после него (tokens.Pop()) - пусто или ] ) , - { - if (kav.Count == 0) - { - string tmps = sb.ToString().Trim(' ', '\r', '\t', '\n'); - if (tmps.Length >= 1 && (char.IsLetter(tmps[0]) || tmps[0] == '_' || tmps[0] == '&' || tmps[0] == '?' || tmps[0] == '!') && tokens.Count == 0) - end = true; - else - tokens.Push(ch); - } - if (!end) - { - sb.Insert(0, ch); - punkt_sym = true; - } - } - else - { - if (kav.Count == 0) // в т.ч. открывающий | - { - if (tokens.Count > 0) - { - tokens.Pop(); - punkt_sym = true; - sb.Insert(0, ch); - if (ch == '(') - { - int tmp = i--; - /*while (i >= 0 && (char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '&')) - { - i--; - }*/ - while (i >= 0 && (Text[i] == ' ' || char.IsControl(Text[i]) || Text[i] == '}')) - { - if (Text[i] != '}') - i--; - else - { - while (i >= 0 && Text[i] != '{') //propusk kommentariev - i--; - if (i >= 0) - i--; - } - } - if (i >= 0 && (char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '&' || Text[i] == '!' || Text[i] == '?' && IsPunctuation(Text, i + 1))) - { - bound = i + 1; - TestForKeyword(Text, i, ref bound, punkt_sym, out keyw); - if (keyw != KeywordKind.None && tokens.Count == 0) - { - end = true; - } - else bound = 0; - } - else if (i >= 0 && Text[i] == '\'') return ""; - i = tmp; - } - } - else - { - end = true; - if (ch == '[') - { - keyw = KeywordKind.SquareBracket; - } - } - - } - else sb.Insert(0, ch); punkt_sym = true; - } - break; - case '\'': - if (kav.Count == 0) kav.Push(ch); else kav.Pop(); - sb.Insert(0, ch); - punkt_sym = true; break; - default: - if (!(ch == ' ' || char.IsControl(ch))) - { - if (kav.Count == 0) - { - if (ch == ',' && ugl_skobki.Count > 0) - sb.Insert(0, ch); - else - if (tokens.Count == 0) - end = true; - else - sb.Insert(0, ch); - } - else - sb.Insert(0, ch); - } - else - { - if (Text[i] == '\n') - { - bool one_line_comment = false; - int comment_position = -1; - if (CheckForComment(Text, i - 1, out comment_position, out one_line_comment)) - { - if (!one_line_comment) - end = true; - else - { - sb.Insert(0, ch); - i = comment_position; - } - - } - else - sb.Insert(0, ch); - } - else - sb.Insert(0, ch); - } - punkt_sym = true; - break; - } - - if (end) - { - bool one_line_comment = false; - int comment_position = -1; - if (CheckForComment(Text, i, out comment_position, out one_line_comment)) - { - int new_line_ind = sb.ToString().IndexOf('\n'); - if (new_line_ind != -1) sb = sb.Remove(0, new_line_ind + 1); - else sb = sb.Remove(0, sb.Length); - } - break; - } - i--; - } - - //return RemovePossibleKeywords(sb); - if (sb.Length > 0 && sb[sb.Length - 1] == '?') - sb.Remove(sb.Length - 1, 1); - return sb.ToString(); - - } - - public override string FindExpressionFromAnyPosition(int off, string Text, int line, int col, out KeywordKind keyw, out string expr_without_brackets) - { - int i = off - 1; - - // это например вызов метода без параметров - expr_without_brackets = null; - keyw = KeywordKind.None; - if (i < 0) - return ""; - bool is_char = false; - - // идем в обе стороны от off - System.Text.StringBuilder sb = new System.Text.StringBuilder(); - if (Text[i] != ' ' && (Char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '&' || Text[i] == '?' && IsPunctuation(Text, i + 1) || Text[i] == '!')) - { - //sb.Remove(0,sb.Length); - while (i >= 0 && (Char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '&' || Text[i] == '?' && IsPunctuation(Text, i + 1) || Text[i] == '!')) - { - //sb.Insert(0,Text[i]);//.Append(Text[i]); - i--; - } - is_char = true; - } - i = off; - if (i < Text.Length && Text[i] != ' ' && (Char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '&' || Text[i] == '?' && IsPunctuation(Text, i + 1) || Text[i] == '!')) - { - while (i < Text.Length && (Char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '!')) - { - //sb.Append(Text[i]);//.Append(Text[i]); - i++; - } - is_char = true; - } - if (is_char) - { - expr_without_brackets = FindExpression(i, Text, line, col, out keyw); - } - bool is_new = keyw == KeywordKind.New; - bool meth_call = false; - KeywordKind new_keyw = KeywordKind.None; - int j = i; - bool in_comment = false; - bool brackets = false; - while (j < Text.Length) - { - char c = Text[j]; - - if (c == '(' && !in_comment) - { - Stack sk_stack = new Stack(); - in_comment = false; - bool in_kav = false; - sk_stack.Push('('); - j++; - while (j < Text.Length) - { - c = Text[j]; - if (c == '(' && !in_kav) - sk_stack.Push('('); - else - if (c == ')' && !in_kav) - { - if (sk_stack.Count == 0) - { - break; - } - else - { - sk_stack.Pop(); - if (sk_stack.Count == 0) - { - i = j + 1; - meth_call = true; - break; - } - } - } - else if (c == '\'' && !in_comment) - { - in_kav = !in_kav; - } - else if (c == '{' && !in_kav) - { - in_comment = true; - } - else if (c == '}' && !in_kav) - { - in_comment = false; - } - else if (c == '/' && !in_kav && !in_comment) - { - if (j + 1 < Text.Length && Text[j + 1] == '/') - break; - } - j++; - } - break; - } - else if ((c == '<' || c == '&' && j < Text.Length - 1 && Text[j + 1] == '<') && !in_comment) - { - Stack sk_stack = new Stack(); - if (c == '&') - j++; - sk_stack.Push('<'); - j++; - bool generic = false; - while (j < Text.Length) - { - c = Text[j]; - if (c == '>') - { - sk_stack.Pop(); - if (sk_stack.Count == 0) - { - i = j + 1; - generic = true; - break; - } - } - else if (c == '<') - { - sk_stack.Push('<'); - - } - else if (!char.IsLetterOrDigit(c) && c != '?' && c != '&' && c != '.' && c != ' ' && c != '\t' && c != '\n' && c != ',' && c != '!') - { - break; - } - j++; - } - if (generic) - { - //break; - } - } - else if (c == '[' && !in_comment) - { - brackets = true; - break; - } - else if (c == '{') - { - in_comment = true; - } - else if (c == '}') - { - if (!in_comment) - break; - else - in_comment = false; - } - else if (c == ' ' || c == '\t' || c == '\n' || c == '\r') - { - - } - else - { - if (!in_comment) - break; - } - j++; - } - if (is_new && string.Compare(expr_without_brackets.Trim(' ', '\n', '\t', '\r'), "new", true) == 0 && !meth_call) - { - expr_without_brackets = null; - return null; - } - if (is_char) - { - string ss = FindExpression(i, Text, line, col, out new_keyw); - if (brackets && is_new) - { - int ind = ss.ToLower().IndexOf("new"); - if (ind != -1) - return ss.Substring(ind + 3); - } - if (is_new && ss != null && ss.IndexOf("new") == -1 && ss.IndexOf(":") != -1) - return expr_without_brackets + "(true?" + ss; - return ss; - } - return null; - } - - public override KeywordKind TestForKeyword(string Text, int i) - { - StringBuilder sb = new StringBuilder(); - int orig_i = i; - int j = i; - bool in_keyw = false; - while (j >= 0 && Text[j] != '\n') - j--; - Stack kav_stack = new Stack(); - j++; - bool in_format_str = false; - while (j <= i) - { - if (Text[j] == '\'') - { - if (kav_stack.Count == 0 && !in_keyw) - { - if (j == 0 || Text[j - 1] != '$') - kav_stack.Push('\''); - else - { - in_keyw = false; - in_format_str = true; - } - - } - else if (kav_stack.Count > 0) - kav_stack.Pop(); - } - else if (Text[j] == '{' && kav_stack.Count == 0 && !in_format_str) - in_keyw = true; - else - if (Text[j] == '}') - in_keyw = false; - j++; - } - j = i; - if ((kav_stack.Count != 0 || in_keyw) && !in_format_str) return PascalABCCompiler.Parsers.KeywordKind.Punkt; - if (j >= 0 && Text[j] == '.') return PascalABCCompiler.Parsers.KeywordKind.Punkt; - while (j >= 0) - { - //if (Text[j] == '{') return PascalABCCompiler.Parsers.KeywordKind.Punkt; - if (!in_keyw && (Text[j] == '\'' || Text[j] == '\n')) - break; - if (Text[j] == '}') - in_keyw = true; - else - if (Text[j] == '/' && !in_keyw) - if (j > 0 && Text[j - 1] == '/') return PascalABCCompiler.Parsers.KeywordKind.Punkt; - j--; - } - //if (j>= 0 && Text[j] == '\'') return CodeCompletion.KeywordKind.kw_punkt; - while (i >= 0 && (Text[i] == ' ' || char.IsControl(Text[i]))) i--; - if (i >= 0 && Text[i] == ':') return PascalABCCompiler.Parsers.KeywordKind.Colon; - - if (i >= 0 && Text[i] == ',') - { - - while (i >= 0 && Text[i] != '\n') - { - if (char.IsLetterOrDigit(Text[i])) - sb.Insert(0, Text[i]); - else - { - PascalABCCompiler.Parsers.KeywordKind keyw = GetKeywordKind(sb.ToString()); - if (keyw == PascalABCCompiler.Parsers.KeywordKind.Uses) - return PascalABCCompiler.Parsers.KeywordKind.Uses; - else if (keyw == PascalABCCompiler.Parsers.KeywordKind.Var) - return PascalABCCompiler.Parsers.KeywordKind.Var; - else sb.Remove(0, sb.Length); - } - i--; - } - } - else - while (i >= 0 && (char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '!')) - { - sb.Insert(0, Text[i]); - i--; - } - string s = sb.ToString().ToLower(); - - return GetKeywordKind(s); - } - - public override string SkipNew(int off, string Text, ref KeywordKind keyw) - { - int tmp = off; - string expr = null; - while (off >= 0 && char.IsLetterOrDigit(Text[off])) off--; - while (off >= 0 && (Text[off] == ' ' || char.IsControl(Text[off]))) off--; - if (off >= 1 && Text[off] == '=' && Text[off - 1] == ':') - { - off -= 2; - while (off >= 0 && (Text[off] == ' ' || char.IsControl(Text[off]))) off--; - if (off >= 0 && (Text[off] == '_' || char.IsLetterOrDigit(Text[off]) || Text[off] == '!' || Text[off] == ']' || Text[off] == '>')) - expr = FindExpression(off + 1, Text, 0, 0, out keyw); - } - return expr; - } - - public override string FindExpressionForMethod(int off, string Text, int line, int col, char pressed_key, ref int num_param) - { - int i = off - 1; - string pattern = null; - int bound = 0; - System.Text.StringBuilder sb = new System.Text.StringBuilder(); - Stack tokens = new Stack(); - Stack kav = new Stack(); - Stack skobki = new Stack(); - Stack ugl_skobki = new Stack(); - bool comma_pressed = pressed_key == ','; - int num_in_ident = -1; - bool punkt_sym = false; - int next; - KeywordKind keyw = TestForKeyword(Text, i); - bool on_brace = false; - if (keyw == KeywordKind.Punkt) - return ""; - try - { - while (i >= bound) - { - bool end = false; - char ch = Text[i]; - if ((char.IsLetterOrDigit(ch) || ch == '_' || ch == '&' || ch == '!') && !isOperator(Text, i, out next)) - { - num_in_ident = i; - if (kav.Count == 0 && tokens.Count == 0) - { - int tmp = i; - while (i >= 0 && (char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '&' || Text[i] == '!') && !isOperator(Text, i, out next)) - { - i--; - } - while (i >= 0 && (Text[i] == ' ' || char.IsControl(Text[i]) || Text[i] == '}')) - { - if (Text[i] != '}') - i--; - else - { - while (i >= 0 && Text[i] != '{') //propusk kommentariev - i--; - if (i >= 0) - i--; - } - } - if (i >= 0 && (char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '&' || Text[i] == '!') && !isOperator(Text, i, out next)) - { - bound = i + 1; - TestForKeyword(Text, i, ref bound, punkt_sym, out keyw); - if (keyw == KeywordKind.New && comma_pressed) - bound = 0; - if (keyw == KeywordKind.Function || keyw == KeywordKind.Constructor || keyw == KeywordKind.Destructor) - return ""; - } - else if (i >= 0 && Text[i] == '\'') return ""; - i = tmp; - } - sb.Insert(0, ch);//.Append(Text[i]); - } - else if (ch == '.') sb.Insert(0, ch); - else if (ch == '}') - { - if (kav.Count == 0) - { - while (i >= 0 && Text[i] != '{') - { - sb.Insert(0, Text[i]); - i--; - } - if (i < 0) - { - break; - } - else if (Text[i] == '{') - { - sb.Insert(0, '{'); - } - } - else - sb.Insert(0, ch); - } - else if (ch == '{') - { - if (kav.Count == 0) - { - sb.Insert(0, ch); - break; - } - else sb.Insert(0, ch); - } - else - switch (ch) - { - case ')': - case ']': - case '>': - if (kav.Count == 0) - { - int j = i + 1; - - while (j < Text.Length && char.IsWhiteSpace(Text[j])) - j++; - if (ch != '>') - tokens.Push(ch); - if (ch == ')') - skobki.Push(ch); - if (tokens.Count > 0 || pressed_key == ',') - sb.Insert(0, ch); - else if (i == off - 1 || j == off && off == Text.Length || ugl_skobki.Count > 0 || j < Text.Length && Text[i - 1] != '-' && (Text[j] == '.' || Text[j] == '(')) - { - tokens.Push(ch); - ugl_skobki.Push(ch); - sb.Insert(0, ch); - } - else - end = true; - } - else - sb.Insert(0, ch); break; - case '[': - case '<': - case '(': - if (kav.Count == 0)//esli ne v kavychkah - { - if (ch == '(') - if (skobki.Count > 0) - skobki.Pop(); - else skobki.Push('('); - //esli byli zakryvaushie tokeny (polagaem, chto skobki korrektny, esli net, to parser v lubom sluchae ne proparsit - if (tokens.Count > 0) - { - if (ch != '<') - tokens.Pop(); - else if (ugl_skobki.Count > 0) - { - tokens.Pop(); - ugl_skobki.Pop(); - } - sb.Insert(0, ch);//dobavljaem k stroke - if (ch == '(') - { - int tmp = i--; - /*while (i >= 0 && (char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '&')) - { - i--; - }*/ - while (i >= 0 && (Text[i] == ' ' || char.IsControl(Text[i]) || Text[i] == '}')) - { - if (Text[i] != '}') - { - i--; - } - else - { - while (i >= 0 && Text[i] != '{') - { - //propusk kommentariev - i--; - } - if (i >= 0) - i--; - } - } - - if (i >= 0 && (char.IsLetterOrDigit(Text[i]) || Text[i] == '_' || Text[i] == '&' || Text[i] == '!')) - { - bound = i + 1; - TestForKeyword(Text, i, ref bound, punkt_sym, out keyw); - if (keyw == KeywordKind.New) - bound = 0; - else - if (keyw != KeywordKind.None && tokens.Count == 0) - end = true; - else - bound = 0; - } - else if (i >= 0 && Text[i] == '\'') return ""; - i = tmp; - } - } - else if (ch == '<' || ch == '>') - { - if (tokens.Count > 0 || pressed_key == ',') - sb.Insert(0, ch); - else - end = true; - } - else - if (!comma_pressed) //esli my ne v parametrah - end = true; //zakonchili, tak kak doshli do pervoj skobki - else - { - sb.Remove(0, sb.Length);//doshli do skobki, byla nazhata zapjataja, poetomu udaljaem vse parametry - if (ch == '(') - on_brace = true; - //on_skobka = true; - comma_pressed = false; - } - } - else sb.Insert(0, ch); - break; - case '\'': - if (kav.Count == 0) - kav.Push(ch); - else - kav.Pop(); - sb.Insert(0, ch); - if (kav.Count == 0 && tokens.Count == 0) - end = true; - break; - default: - if (!(ch == ' ' || char.IsControl(ch))) - { - if (ch == '^') - sb.Insert(0, ch); - else - if (kav.Count == 0)//ne v kavychkah - { - if (tokens.Count == 0) - { - if (ch != ',' && !comma_pressed) - end = true;//esli ne na zapjatoj i ne v parametrah, to finish - else if (ch == ',' && !comma_pressed) - end = true; - else if (ch == ',' && (pressed_key == '(' || pressed_key == '[')) - end = true; - else - { - sb.Insert(0, ch);//prodolzhaem - if (isOperator(Text, i, out next)) - { - i = next; - continue; - } - } - - } - else - sb.Insert(0, ch);//esli est skobki, prodolzhaem - if (!end && ch == ',') - { - if (tokens.Count == 0) - num_param++;//esli na zapjatoj, uvelichivaem nomer parametra - } - } - else - sb.Insert(0, ch);//prodolzhaem - - } - else - if (Text[i] == '\n') - { - bool one_line_comment = false; - int comment_position = -1; - if (CheckForComment(Text, i - 1, out comment_position, out one_line_comment)) //proverjaem, net li kommenta ne predydushej stroke - { - if (!one_line_comment) - end = true; - else - { - sb.Insert(0, ch); - i = comment_position; - } - - } - else - sb.Insert(0, ch);//a inache vyrazhenie na neskolkih strokah - } - else - sb.Insert(0, ch); - break; - } - - if (end) - { - if (comma_pressed && !on_brace) - return ""; - bool one_line_comment = false; - int comment_position = -1; - if (CheckForComment(Text, i, out comment_position, out one_line_comment))//proverka na kommentarii - { - int new_line_ind = sb.ToString().IndexOf('\n'); - if (new_line_ind != -1) sb = sb.Remove(0, new_line_ind + 1); - else sb = sb.Remove(0, sb.Length); - } - break; - } - i--; - } - if (pressed_key == ',') - num_param++; - } - catch (Exception e) - { - - } - if (pressed_key == ',' && (!on_brace || skobki.Count == 0)) - return ""; - //return RemovePossibleKeywords(sb); - return sb.ToString(); - } - - - public override bool IsMethodCallParameterSeparator(char key) - { - return key == ','; - } - - - public override bool IsDefinitionIdentifierAfterKeyword(KeywordKind keyw) - { - if (keyw == PascalABCCompiler.Parsers.KeywordKind.Function || keyw == PascalABCCompiler.Parsers.KeywordKind.Constructor || keyw == PascalABCCompiler.Parsers.KeywordKind.Destructor || keyw == PascalABCCompiler.Parsers.KeywordKind.Type || keyw == PascalABCCompiler.Parsers.KeywordKind.Var - || keyw == PascalABCCompiler.Parsers.KeywordKind.Unit || keyw == PascalABCCompiler.Parsers.KeywordKind.Const || keyw == PascalABCCompiler.Parsers.KeywordKind.Program || keyw == PascalABCCompiler.Parsers.KeywordKind.Punkt) - return true; - return false; - } - - public override bool IsTypeAfterKeyword(KeywordKind keyw) - { - if (keyw == KeywordKind.Colon || keyw == KeywordKind.Of || keyw == KeywordKind.TypeDecl) - return true; - return false; - } - } #region LEGACY - C language /*public class CLanguageInformation : DefaultLanguageInformation diff --git a/PluginsSupport/Interfaces.cs b/PluginsSupport/Interfaces.cs index 5bc38400b..345b6a2a0 100644 --- a/PluginsSupport/Interfaces.cs +++ b/PluginsSupport/Interfaces.cs @@ -362,8 +362,8 @@ namespace VisualPascalABCPlugins public interface IWidgetStatusContoller { - void SetStartDebugEnabled(); - void SetStartDebugDisabled(); + void SetStartDebugAndRunEnabled(); + void SetStartDebugAndRunDisabled(); void SetDebugStopDisabled(); void SetDebugStopEnabled(); void SetAddExprMenuVisible(bool val); @@ -372,10 +372,10 @@ namespace VisualPascalABCPlugins void SetDebugPausedDisabled(); void SetPlayButtonsVisible(bool val); void SetStopEnabled(bool enabled); - void SetCompilingButtonsEnabled(bool Enabled); + void SetCompilingAndRunButtonsEnabled(bool Enabled); void SetDebugButtonsEnabled(bool val); void SetOptionsEnabled(bool val); - bool CompilingButtonsEnabled { get; set; } + bool CompilingAndRunButtonsEnabled { get; set; } void EnableCodeCompletionToolTips(bool val); void ChangeContinueDebugNameOnStart(); void ChangeStartDebugNameOnContinue(); diff --git a/PluginsSupportLinux/Interfaces.cs b/PluginsSupportLinux/Interfaces.cs index 1484dba8e..78b1eb106 100644 --- a/PluginsSupportLinux/Interfaces.cs +++ b/PluginsSupportLinux/Interfaces.cs @@ -348,8 +348,8 @@ namespace VisualPascalABCPlugins public interface IWidgetStatusContoller { - void SetStartDebugEnabled(); - void SetStartDebugDisabled(); + void SetStartDebugAndRunEnabled(); + void SetStartDebugAndRunDisabled(); void SetDebugStopDisabled(); void SetDebugStopEnabled(); void SetAddExprMenuVisible(bool val); @@ -358,10 +358,10 @@ namespace VisualPascalABCPlugins void SetDebugPausedDisabled(); void SetPlayButtonsVisible(bool val); void SetStopEnabled(bool enabled); - void SetCompilingButtonsEnabled(bool Enabled); + void SetCompilingAndRunButtonsEnabled(bool Enabled); void SetDebugButtonsEnabled(bool val); void SetOptionsEnabled(bool val); - bool CompilingButtonsEnabled { get; set; } + bool CompilingAndRunButtonsEnabled { get; set; } void EnableCodeCompletionToolTips(bool val); void ChangeContinueDebugNameOnStart(); void ChangeStartDebugNameOnContinue(); diff --git a/VisualPascalABCNET/DS/CodeCompletionVisual/TipPainterTools.cs b/VisualPascalABCNET/DS/CodeCompletionVisual/TipPainterTools.cs index faddc1a84..3115a640e 100644 --- a/VisualPascalABCNET/DS/CodeCompletionVisual/TipPainterTools.cs +++ b/VisualPascalABCNET/DS/CodeCompletionVisual/TipPainterTools.cs @@ -67,11 +67,11 @@ namespace ICSharpCode.TextEditor.Util if (param_num == -1) return; - var languageInfo = CodeCompletion.CodeCompletionController.CurrentParser.LanguageInformation; + var languageIntellisenseSupport = CodeCompletion.CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport; int startIndex = basicDescription.IndexOf("(", basicDescription.IndexOf("(" + PascalABCCompiler.StringResources.Get("CODE_COMPLETION_EXTENSION")) + 1) + 1; - int paranthesisIndex = languageInfo.FindClosingParenthesis(basicDescription.Substring(startIndex), ')'); + int paranthesisIndex = languageIntellisenseSupport.FindClosingParenthesis(basicDescription.Substring(startIndex), ')'); if (paranthesisIndex == -1) return; @@ -84,7 +84,7 @@ namespace ICSharpCode.TextEditor.Util if (bold_beg != 0) { - int paramDelimIndex = languageInfo.FindParamDelim(basicDescription.Substring(bold_beg), 1); + int paramDelimIndex = languageIntellisenseSupport.FindParamDelim(basicDescription.Substring(bold_beg), 1); if (paramDelimIndex == -1) { @@ -105,7 +105,7 @@ namespace ICSharpCode.TextEditor.Util { string paramDescription = basicDescription.Substring(startIndex, paranthesisIndex); - if (languageInfo.IsParams(paramDescription)) + if (languageIntellisenseSupport.IsParams(paramDescription)) { bold_beg = startIndex; bold_len = paranthesisIndex; @@ -115,15 +115,15 @@ namespace ICSharpCode.TextEditor.Util { string descriptionAfterBracket = basicDescription.Substring(startIndex); - int paramDelimIndex = languageInfo.FindParamDelim(descriptionAfterBracket, paramsCount - 1); + int paramDelimIndex = languageIntellisenseSupport.FindParamDelim(descriptionAfterBracket, paramsCount - 1); if (paramDelimIndex != -1) { - int paramDelimLength = languageInfo.ParameterDelimiter.Length; + int paramDelimLength = languageIntellisenseSupport.ParameterDelimiter.Length; string paramDescription = descriptionAfterBracket.Substring(paramDelimIndex + paramDelimLength, paranthesisIndex - paramDelimIndex - paramDelimLength); - if (languageInfo.IsParams(paramDescription)) + if (languageIntellisenseSupport.IsParams(paramDescription)) { bold_beg = paramDelimIndex + startIndex + paramDelimLength; bold_len = end_sk - bold_beg; @@ -133,12 +133,12 @@ namespace ICSharpCode.TextEditor.Util } else { - int paramDelimIndex = languageInfo.FindParamDelim(basicDescription.Substring(startIndex), param_num - 1); + int paramDelimIndex = languageIntellisenseSupport.FindParamDelim(basicDescription.Substring(startIndex), param_num - 1); if (paramDelimIndex != -1) { - bold_beg = paramDelimIndex + startIndex + languageInfo.ParameterDelimiter.Length; - int secondParamDelimIndex = languageInfo.FindParamDelim(basicDescription.Substring(startIndex), param_num); + bold_beg = paramDelimIndex + startIndex + languageIntellisenseSupport.ParameterDelimiter.Length; + int secondParamDelimIndex = languageIntellisenseSupport.FindParamDelim(basicDescription.Substring(startIndex), param_num); if (secondParamDelimIndex == -1) { diff --git a/VisualPascalABCNET/DS/VisualEnvironmentCompiler.cs b/VisualPascalABCNET/DS/VisualEnvironmentCompiler.cs index 93613662a..825b23112 100644 --- a/VisualPascalABCNET/DS/VisualEnvironmentCompiler.cs +++ b/VisualPascalABCNET/DS/VisualEnvironmentCompiler.cs @@ -33,7 +33,7 @@ namespace VisualPascalABC private System.Threading.Thread MainProgramThread = System.Threading.Thread.CurrentThread; private System.Threading.Thread StartingThread; public delegate void SetFlagDelegate(bool flag); - private SetFlagDelegate SetCompilingButtonsEnabled; + private SetFlagDelegate SetCompilingAndRunButtonsEnabled; private SetFlagDelegate SetDebugButtonsEnabled; public ConvertTextDelegate ConvertUnitTextProperty { get; set; } @@ -67,7 +67,7 @@ namespace VisualPascalABC Dictionary OpenDocuments; public VisualEnvironmentCompiler(InvokeDegegate beginInvoke, - SetFlagDelegate setCompilingButtonsEnabled, SetFlagDelegate setCompilingDebugEnabled, SetTextDelegate setStateText, + SetFlagDelegate setCompilingAndRunButtonsEnabled, SetFlagDelegate setCompilingDebugEnabled, SetTextDelegate setStateText, SetTextDelegate addTextToCompilerMessages, ToolStripMenuItem pluginsMenuItem, ToolStrip pluginsToolStrip, ExecuteSourceLocationActionDelegate ExecuteSLAction, ExecuteVisualEnvironmentCompilerActionDelegate ExecuteVECAction, @@ -77,7 +77,7 @@ namespace VisualPascalABC this.StandartDirectories = StandartDirectories; this.ErrorsManager = ErrorsManager; this.ChangeVisualEnvironmentState += onChangeVisualEnvironmentState; - SetCompilingButtonsEnabled = setCompilingButtonsEnabled; + SetCompilingAndRunButtonsEnabled = setCompilingAndRunButtonsEnabled; SetDebugButtonsEnabled = setCompilingDebugEnabled; SetStateText = setStateText; AddTextToCompilerMessages = addTextToCompilerMessages; @@ -362,7 +362,7 @@ namespace VisualPascalABC { case PascalABCCompiler.CompilerState.CompilationStarting: RusName = VECStringResources.Get("STATE_START_COMPILING_ASSEMBLY{0}"); - SetCompilingButtonsEnabled(false); + SetCompilingAndRunButtonsEnabled(false); ParsedFiles.Clear(); break; case PascalABCCompiler.CompilerState.BeginCompileFile: RusName = VECStringResources.Get("STATE_BEGINCOMPILEFILE{0}"); break; @@ -407,21 +407,22 @@ namespace VisualPascalABC if (!ThreadPool.QueueUserWorkItem(new WaitCallback(LoadPlugins))) LoadPlugins(null); - SetCompilingButtonsEnabled(true); - SetDebugButtonsEnabled(true); + SetCompilingAndRunButtonsEnabled(true); + if (CodeCompletion.CodeCompletionController.IntellisenseAvailable()) + SetDebugButtonsEnabled(true); } } else { if (Compiler == sender) { - SetCompilingButtonsEnabled(true); + SetCompilingAndRunButtonsEnabled(true); } } break; case PascalABCCompiler.CompilerState.Reloading: if (Compiler == sender) - SetCompilingButtonsEnabled(false); + SetCompilingAndRunButtonsEnabled(false); RusName = VECStringResources.Get("STATE_RELOADING"); break; case PascalABCCompiler.CompilerState.CompilationFinished: diff --git a/VisualPascalABCNET/Form1.cs b/VisualPascalABCNET/Form1.cs index c60b539a2..4f87d6083 100644 --- a/VisualPascalABCNET/Form1.cs +++ b/VisualPascalABCNET/Form1.cs @@ -261,6 +261,7 @@ namespace VisualPascalABC this.StepOutButton.Visible = false; PlayPauseButtonsVisibleInPanel = PlayPauseButtonsVisibleInPanel; SetDebugButtonsEnabled(false); + SetRunButtonsEnabled(false); } AddOwnedForm(CompilerForm1 = new CompilerForm()); @@ -335,7 +336,7 @@ namespace VisualPascalABC RunManager RunnerManager = (WorkbenchServiceFactory.RunService as WorkbenchRunService).RunnerManager; VisualEnvironmentCompiler = new VisualEnvironmentCompiler( - this.BeginInvoke, SetCompilingButtonsEnabled, SetDedugButtonsEnabled, SetStateText, + this.BeginInvoke, SetCompilingAndRunButtonsEnabled, SetDebugButtonsEnabled, SetStateText, AddTextToCompilerMessagesSync, miPlugins, toolStrip1, ExecuteSourceLocationAction, ExecuteVisualEnvironmentCompilerAction, ErrorsManager, RunnerManager, WorkbenchServiceFactory.DebuggerManager, UserOptions, WorkbenchStorage.StandartDirectories, OpenDocuments, this); @@ -403,9 +404,9 @@ namespace VisualPascalABC WorkbenchServiceFactory.FileService.OpenFile(FileNameToWait, null); } SetStopEnabled(false); - CompilingButtonsEnabled = CloseButtonsEnabled = SaveAllButtonsEnabled = SaveButtonsEnabled = false; - SetDedugButtonsEnabled(false); - SetCompilingButtonsEnabled(false); + CompilingAndRunButtonsEnabled = CloseButtonsEnabled = SaveAllButtonsEnabled = SaveButtonsEnabled = false; + SetDebugButtonsEnabled(false); + SetCompilingAndRunButtonsEnabled(false); HelpFileName = PascalABCCompiler.Tools.ReplaceAllKeys(Constants.HelpFileName, WorkbenchStorage.StandartDirectories); DotNetHelpFileName = PascalABCCompiler.Tools.ReplaceAllKeys(Constants.DotNetHelpFileName, WorkbenchStorage.StandartDirectories); diff --git a/VisualPascalABCNET/IB/CodeCompletion/CodeCompletionActions.cs b/VisualPascalABCNET/IB/CodeCompletion/CodeCompletionActions.cs index af1f30472..669eac58d 100644 --- a/VisualPascalABCNET/IB/CodeCompletion/CodeCompletionActions.cs +++ b/VisualPascalABCNET/IB/CodeCompletion/CodeCompletionActions.cs @@ -20,7 +20,7 @@ namespace VisualPascalABC public static void Rename(TextArea textArea) { - if (CodeCompletion.CodeCompletionController.CurrentParser == null) return; + if (!CodeCompletion.CodeCompletionController.IntellisenseAvailable()) return; IDocument doc = textArea.Document; string textContent = doc.TextContent; ccp = new CodeCompletionProvider(); @@ -60,7 +60,7 @@ namespace VisualPascalABC public static void RenameUnit(string FileName, string new_val) { - if (CodeCompletion.CodeCompletionController.CurrentParser == null) return; + if (!CodeCompletion.CodeCompletionController.IntellisenseAvailable()) return; ccp = new CodeCompletionProvider(); IDocument doc = null; CodeCompletion.CodeCompletionController controller = new CodeCompletion.CodeCompletionController(); @@ -121,11 +121,8 @@ namespace VisualPascalABC public static List GetDefinitionPosition(TextArea textArea, bool only_check) { - IParser parser = CodeCompletion.CodeCompletionController.CurrentParser; + if (!CodeCompletion.CodeCompletionController.IntellisenseAvailable()) return new List(); - if (parser == null) - return new List(); - IDocument doc = textArea.Document; string textContent = doc.TextContent; ccp = new CodeCompletionProvider(); @@ -137,7 +134,7 @@ namespace VisualPascalABC // Проверка, что компилируем Паскаль временно EVA 10.11.2024 - if (parser == Languages.Facade.LanguageProvider.Instance.SelectLanguageByName(StringConstants.pascalLanguageName).Parser) + if (CodeCompletion.CodeCompletionController.CurrentLanguage == Languages.Facade.LanguageProvider.Instance.MainLanguage) { if (expressionResult != full_expr && full_expr.StartsWith("(")) return new List(); @@ -158,7 +155,7 @@ namespace VisualPascalABC public static List GetRealizationPosition(TextArea textArea) { - if (CodeCompletion.CodeCompletionController.CurrentParser == null) return new List(); + if (!CodeCompletion.CodeCompletionController.IntellisenseAvailable()) return new List(); IDocument doc = textArea.Document; string textContent = doc.TextContent; ccp = new CodeCompletionProvider(); @@ -172,7 +169,7 @@ namespace VisualPascalABC public static List FindReferences(TextArea textArea) { - if (CodeCompletion.CodeCompletionController.CurrentParser == null) return new List(); + if (!CodeCompletion.CodeCompletionController.IntellisenseAvailable()) return new List(); ccp = new CodeCompletionProvider(); string full_expr; string expressionResult = FindFullExpression(textArea.Document.TextContent, textArea, out ccp.keyword, out full_expr); @@ -181,7 +178,7 @@ namespace VisualPascalABC public static void GotoRealization(TextArea textArea) { - if (CodeCompletion.CodeCompletionController.CurrentParser == null) return; + if (!CodeCompletion.CodeCompletionController.IntellisenseAvailable()) return; position = GetRealizationPosition(textArea); if (position == null || position.Count == 0) return; if (position.Count == 1) @@ -210,7 +207,7 @@ namespace VisualPascalABC public static bool CanGoTo(TextArea textArea) { - if (CodeCompletion.CodeCompletionController.CurrentParser == null) return false; + if (!CodeCompletion.CodeCompletionController.IntellisenseAvailable()) return false; List poses = GetDefinitionPosition(textArea, true); if (poses == null || poses.Count == 0) return false; foreach (Position pos in poses) @@ -223,7 +220,7 @@ namespace VisualPascalABC public static bool CanGoToRealization(TextArea textArea) { - if (CodeCompletion.CodeCompletionController.CurrentParser == null) return false; + if (!CodeCompletion.CodeCompletionController.IntellisenseAvailable()) return false; List poses = GetRealizationPosition(textArea); if (poses == null || poses.Count == 0) return false; foreach (Position pos in poses) @@ -238,7 +235,7 @@ namespace VisualPascalABC { try { - if (CodeCompletion.CodeCompletionController.CurrentParser == null) return false; + if (!CodeCompletion.CodeCompletionController.IntellisenseAvailable()) return false; ccp = new CodeCompletionProvider(); string full_expr; string expressionResult = FindFullExpression(textArea.Document.TextContent, textArea, out ccp.keyword, out full_expr); @@ -259,7 +256,7 @@ namespace VisualPascalABC { try { - if (CodeCompletion.CodeCompletionController.CurrentParser == null) return false; + if (!CodeCompletion.CodeCompletionController.IntellisenseAvailable()) return false; ccp = new CodeCompletionProvider(); Position pos = new Position(); //string text = "procedure Test(a : integer);\n begin \n x := 1; \n end;";//ccp.GetRealizationTextToAdd(out pos); @@ -276,7 +273,7 @@ namespace VisualPascalABC { try { - if (CodeCompletion.CodeCompletionController.CurrentParser == null) return; + if (!CodeCompletion.CodeCompletionController.IntellisenseAvailable()) return; ccp = new CodeCompletionProvider(); Position pos = new Position(); //string text = "procedure Test(a : integer);\n begin \n x := 1; \n end;";//ccp.GetRealizationTextToAdd(out pos); @@ -299,7 +296,7 @@ namespace VisualPascalABC private static TextArea _textArea; public static void GenerateOverridableMethods(TextArea textArea) { - if (CodeCompletion.CodeCompletionController.CurrentParser == null) return; + if (!CodeCompletion.CodeCompletionController.IntellisenseAvailable()) return; ccp = new CodeCompletionProvider(); _textArea = textArea; int off = textArea.Caret.Offset; @@ -329,7 +326,7 @@ namespace VisualPascalABC public static void GenerateClassOrMethodRealization(TextArea textArea) { - if (CodeCompletion.CodeCompletionController.CurrentParser == null) return; + if (!CodeCompletion.CodeCompletionController.IntellisenseAvailable()) return; ccp = new CodeCompletionProvider(); Position pos = new Position(); //string text = "procedure Test(a : integer);\n begin \n x := 1; \n end;";//ccp.GetRealizationTextToAdd(out pos); @@ -459,12 +456,12 @@ namespace VisualPascalABC public static bool GenerateCommentTemplate(TextArea textArea) { - if (CodeCompletion.CodeCompletionController.CurrentParser == null) return false; + if (!CodeCompletion.CodeCompletionController.IntellisenseAvailable()) return false; ccp = new CodeCompletionProvider(); //if (!should_insert_comment(textArea)) // return false; string lineText = get_next_line(textArea); - string addit = CodeCompletion.CodeCompletionController.CurrentParser.LanguageInformation.GetDocumentTemplate( + string addit = CodeCompletion.CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.GetDocumentTemplate( lineText, textArea.Document.TextContent, textArea.Caret.Line, textArea.Caret.Column, textArea.Caret.Offset); if (addit == null) return false; @@ -506,7 +503,7 @@ namespace VisualPascalABC public static void GotoDefinition(TextArea _textArea) { - if (CodeCompletion.CodeCompletionController.CurrentParser == null) return; + if (!CodeCompletion.CodeCompletionController.IntellisenseAvailable()) return; position = GetDefinitionPosition(_textArea, false); if (position == null) return; if (position.Count == 1) @@ -544,9 +541,9 @@ namespace VisualPascalABC keyw = PascalABCCompiler.Parsers.KeywordKind.None; string expr_without_brackets = null; full_expr = null; - if (CodeCompletion.CodeCompletionController.CurrentParser != null) + if (CodeCompletion.CodeCompletionController.IntellisenseAvailable()) { - full_expr = CodeCompletion.CodeCompletionController.CurrentParser.LanguageInformation.FindExpressionFromAnyPosition(_textArea.Caret.Offset, Text, _textArea.Caret.Line, _textArea.Caret.Column, out keyw, out expr_without_brackets); + full_expr = CodeCompletion.CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.FindExpressionFromAnyPosition(_textArea.Caret.Offset, Text, _textArea.Caret.Line, _textArea.Caret.Column, out keyw, out expr_without_brackets); return expr_without_brackets; } return null; @@ -554,7 +551,7 @@ namespace VisualPascalABC private static string FindOnlyIdent(string Text, TextArea _textArea, ref string name) { - return CodeCompletion.CodeCompletionController.CurrentParser.LanguageInformation.FindOnlyIdentifier(_textArea.Caret.Offset, Text, _textArea.Caret.Line, _textArea.Caret.Column, ref name); + return CodeCompletion.CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.FindOnlyIdentifier(_textArea.Caret.Offset, Text, _textArea.Caret.Line, _textArea.Caret.Column, ref name); } @@ -642,7 +639,7 @@ namespace VisualPascalABC if (!WorkbenchServiceFactory.Workbench.UserOptions.CodeCompletionDot) return; - if (CodeCompletion.CodeCompletionController.CurrentParser == null) + if (!CodeCompletion.CodeCompletionController.IntellisenseAvailable()) return; is_begin = true; @@ -687,7 +684,7 @@ namespace VisualPascalABC { public override void Execute(TextArea textArea) { - if (WorkbenchServiceFactory.DebuggerManager.IsRunning) + if (WorkbenchServiceFactory.DebuggerManager.IsRunning || !CodeCompletion.CodeCompletionController.IntellisenseAvailable()) return; WorkbenchServiceFactory.Workbench.ErrorsListWindow.ClearErrorList(); VisualPABCSingleton.MainForm.CurrentCodeFileDocument.DeselectAll(); @@ -697,12 +694,14 @@ namespace VisualPascalABC // MainForm.VisualEnvironmentCompiler.Compiler.ParsersController.Compile( // file_name, TextEditor.Text, null, Errors, PascalABCCompiler.Parsers.ParseMode.Normal); string text = WorkbenchServiceFactory.Workbench.VisualEnvironmentCompiler.SourceFilesProvider(VisualPABCSingleton.MainForm.CurrentCodeFileDocument.FileName, PascalABCCompiler.SourceFileOperation.GetText) as string; + PascalABCCompiler.SyntaxTree.compilation_unit cu = - Languages.Facade.LanguageProvider.Instance.SelectLanguageByExtensionSafe(VisualPABCSingleton.MainForm.CurrentCodeFileDocument.FileName)?.Parser.GetCompilationUnitForFormatter( + CodeCompletion.CodeCompletionController.CurrentLanguage.Parser.GetCompilationUnitForFormatter( VisualPABCSingleton.MainForm.CurrentCodeFileDocument.FileName, text, //VisualPascalABC.Form1.Form1_object._currentCodeFileDocument.TextEditor.Text, Errors, new List()); + if (Errors.Count == 0) { string formattedText = cf.FormatTree(text, cu, textArea.Caret.Line + 1, textArea.Caret.Column + 1); @@ -732,17 +731,18 @@ namespace VisualPascalABC { //try { + if (!WorkbenchServiceFactory.Workbench.UserOptions.CodeCompletionDot) + return; + + if (!CodeCompletion.CodeCompletionController.IntellisenseAvailable()) return; + textArea = _textArea; int off = textArea.Caret.Offset; string text = textArea.Document.TextContent.Substring(0, textArea.Caret.Offset); - if (!WorkbenchServiceFactory.Workbench.UserOptions.CodeCompletionDot) - return; - - if (CodeCompletion.CodeCompletionController.CurrentParser == null) return; CodeCompletionProvider completionDataProvider = new CodeCompletionProvider(); - completionDataProvider.preSelection = CodeCompletion.CodeCompletionController.CurrentParser.LanguageInformation.FindPattern(off, text, out var is_pattern); + completionDataProvider.preSelection = CodeCompletion.CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.FindPattern(off, text, out var is_pattern); codeCompletionWindow = PABCNETCodeCompletionWindow.ShowCompletionWindow( VisualPABCSingleton.MainForm, // The parent window for the completion window diff --git a/VisualPascalABCNET/IB/CodeCompletion/CodeCompletionHelpers.cs b/VisualPascalABCNET/IB/CodeCompletion/CodeCompletionHelpers.cs index 41c692b96..46de49bc4 100644 --- a/VisualPascalABCNET/IB/CodeCompletion/CodeCompletionHelpers.cs +++ b/VisualPascalABCNET/IB/CodeCompletion/CodeCompletionHelpers.cs @@ -54,8 +54,8 @@ namespace VisualPascalABC { public static PascalABCCompiler.Parsers.KeywordKind TestForKeyword(string Text, int i) { - if (CodeCompletion.CodeCompletionController.CurrentParser != null && CodeCompletion.CodeCompletionController.CurrentParser.LanguageInformation !=null) - return CodeCompletion.CodeCompletionController.CurrentParser.LanguageInformation.TestForKeyword(Text, i); + if (CodeCompletion.CodeCompletionController.IntellisenseAvailable()) + return CodeCompletion.CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.TestForKeyword(Text, i); return PascalABCCompiler.Parsers.KeywordKind.None; } diff --git a/VisualPascalABCNET/IB/CodeCompletion/CodeCompletionKeyHandler.cs b/VisualPascalABCNET/IB/CodeCompletion/CodeCompletionKeyHandler.cs index 3c860c58e..5194a086c 100644 --- a/VisualPascalABCNET/IB/CodeCompletion/CodeCompletionKeyHandler.cs +++ b/VisualPascalABCNET/IB/CodeCompletion/CodeCompletionKeyHandler.cs @@ -64,7 +64,7 @@ namespace VisualPascalABC { if (!WorkbenchServiceFactory.Workbench.UserOptions.AllowCodeCompletion || !VisualPABCSingleton.MainForm.VisualEnvironmentCompiler.compilerLoaded) return false; - if (CodeCompletion.CodeCompletionController.CurrentParser == null) return false; + if (!CodeCompletion.CodeCompletionController.IntellisenseAvailable()) return false; if (codeCompletionWindow != null) { // If completion window is open and wants to handle the key, don't let the text area @@ -93,8 +93,6 @@ namespace VisualPascalABC } if (key == '.') { - if (CodeCompletion.CodeCompletionController.CurrentParser == null) - return false; if (!string.IsNullOrEmpty(WorkbenchServiceFactory.DocumentService.CurrentCodeFileDocument.TextEditor.ActiveTextAreaControl.SelectionManager.SelectedText)) { WorkbenchServiceFactory.DocumentService.CurrentCodeFileDocument.TextEditor.ActiveTextAreaControl.Caret.Position = WorkbenchServiceFactory.DocumentService.CurrentCodeFileDocument.TextEditor.ActiveTextAreaControl.SelectionManager.SelectionCollection[0].StartPosition; @@ -123,7 +121,6 @@ namespace VisualPascalABC } else if (key == '(' || key == '[' || key == ',') { - if (CodeCompletion.CodeCompletionController.CurrentParser == null) return false; if (VisualPABCSingleton.MainForm.UserOptions.CodeCompletionParams) { ICSharpCode.TextEditor.Gui.InsightWindow.IInsightDataProvider idp = new DefaultInsightDataProvider(-1, false, key); @@ -145,7 +142,6 @@ namespace VisualPascalABC } else if (key == ' ') { - if (CodeCompletion.CodeCompletionController.CurrentParser == null) return false; if (VisualPABCSingleton.MainForm.UserOptions.CodeCompletionDot) { PascalABCCompiler.Parsers.KeywordKind keyw = KeywordChecker.TestForKeyword(editor.Document.TextContent, editor.ActiveTextAreaControl.TextArea.Caret.Offset - 1); @@ -171,7 +167,7 @@ namespace VisualPascalABC } else if (key == '\n') { - if (VisualPABCSingleton.MainForm.UserOptions.AllowCodeCompletion && CodeCompletion.CodeCompletionController.CurrentParser != null) + if (VisualPABCSingleton.MainForm.UserOptions.AllowCodeCompletion) { try { @@ -193,9 +189,8 @@ namespace VisualPascalABC { if (VisualPABCSingleton.MainForm.UserOptions.CodeCompletionDot) { - if (CodeCompletion.CodeCompletionController.CurrentParser == null) return false; PascalABCCompiler.Parsers.KeywordKind keyw = KeywordChecker.TestForKeyword(editor.Document.TextContent, editor.ActiveTextAreaControl.TextArea.Caret.Offset - 1); - if (CodeCompletion.CodeCompletionController.CurrentParser.LanguageInformation.IsDefinitionIdentifierAfterKeyword(keyw)) + if (CodeCompletion.CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.IsDefinitionIdentifierAfterKeyword(keyw)) return false; // если не первый символ выражения (предыдущий тоже буква или "_"), то не открываем новое окно @@ -221,7 +216,6 @@ namespace VisualPascalABC { if (mainForm.UserOptions.AllowCodeFormatting) { - if (CodeCompletion.CodeCompletionController.currentParser == null) return false; string bracket = CodeCompletion.CodeCompletionController.currentParser.LanguageInformation.GetBodyStartBracket(); string end_bracket = CodeCompletion.CodeCompletionController.currentParser.LanguageInformation.GetBodyEndBracket(); if (bracket != null) diff --git a/VisualPascalABCNET/IB/CodeCompletion/CodeCompletionParserController.cs b/VisualPascalABCNET/IB/CodeCompletion/CodeCompletionParserController.cs index 0f9170d72..50983776b 100644 --- a/VisualPascalABCNET/IB/CodeCompletion/CodeCompletionParserController.cs +++ b/VisualPascalABCNET/IB/CodeCompletion/CodeCompletionParserController.cs @@ -75,11 +75,7 @@ namespace VisualPascalABC public void RegisterFileForParsing(string FileName) { - if (Languages.Facade.LanguageProvider.Instance.HasLanguageForExtension(FileName)) - { - filesToParse[FileName] = true; - CodeCompletion.CodeCompletionController.SetLanguage(FileName); - } + filesToParse[FileName] = true; } public void CloseFile(string FileName) diff --git a/VisualPascalABCNET/IB/CodeCompletion/CodeCompletionProvider.cs b/VisualPascalABCNET/IB/CodeCompletion/CodeCompletionProvider.cs index 721afb957..2e480b86a 100644 --- a/VisualPascalABCNET/IB/CodeCompletion/CodeCompletionProvider.cs +++ b/VisualPascalABCNET/IB/CodeCompletion/CodeCompletionProvider.cs @@ -125,12 +125,12 @@ namespace VisualPascalABC private string construct_header(string meth, CodeCompletion.ProcScope ps, int tabCount) { //if (CodeCompletion.CodeCompletionController.currentParser != null) - return CodeCompletion.CodeCompletionController.CurrentParser.LanguageInformation.ConstructHeader(meth, ps, tabCount); + return CodeCompletion.CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.ConstructHeader(meth, ps, tabCount); } private string construct_header(CodeCompletion.ProcRealization ps, int tabCount) { - return CodeCompletion.CodeCompletionController.CurrentParser.LanguageInformation.ConstructHeader(ps, tabCount); + return CodeCompletion.CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.ConstructHeader(ps, tabCount); } public CodeCompletion.SymScope FindScopeByLocation(string fileName, int line, int col) @@ -294,8 +294,8 @@ namespace VisualPascalABC public string FindExpression(int off, string Text, int line, int col) { - if (CodeCompletion.CodeCompletionController.CurrentParser != null) - return CodeCompletion.CodeCompletionController.CurrentParser.LanguageInformation.FindExpression(off, Text, line, col, out keyword); + if (CodeCompletion.CodeCompletionController.IntellisenseAvailable()) + return CodeCompletion.CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.FindExpression(off, Text, line, col, out keyword); return null; } @@ -324,14 +324,14 @@ namespace VisualPascalABC try { - ILanguageInformation languageInformation = CodeCompletion.CodeCompletionController.CurrentParser.LanguageInformation; + ILanguage currentLanguage = CodeCompletion.CodeCompletionController.CurrentLanguage; List keywords; bool isTypeAfterKeyword = false; // если по смыслу должен вводиться тип данных - if (languageInformation.IsTypeAfterKeyword(keyw)) + if (currentLanguage.LanguageIntellisenseSupport.IsTypeAfterKeyword(keyw)) { keywords = CodeCompletion.CodeCompletionNameHelper.Helper.GetTypeKeywords(); isTypeAfterKeyword = true; @@ -344,7 +344,7 @@ namespace VisualPascalABC bool isNamespaceAfterKeyword = false; // конструкция типа "uses" - if (languageInformation.IsNamespaceAfterKeyword(keyw)) + if (currentLanguage.LanguageIntellisenseSupport.IsNamespaceAfterKeyword(keyw)) { isNamespaceAfterKeyword = true; } @@ -358,11 +358,9 @@ namespace VisualPascalABC if (symInfos != null) { - bool languageCaseSensitive = LanguageProvider.Instance.SelectLanguageByExtension(FileName).CaseSensitive; + currentLanguage.LanguageIntellisenseSupport.RenameOrExcludeSpecialNames(symInfos); - languageInformation.RenameOrExcludeSpecialNames(symInfos); - - AddCompletionDatasByFirstForSymInfos(resultList, charTyped, symInfos, languageCaseSensitive); + AddCompletionDatasByFirstForSymInfos(resultList, charTyped, symInfos, currentLanguage.CaseSensitive); //resultList.Sort(); //defaultCompletionElement = resultList[0] as DefaultCompletionData; @@ -506,7 +504,7 @@ namespace VisualPascalABC }; string expressionText = GetExpressionTextForCompletionData(off, text, line, col, - currentLanguage.LanguageInformation, in context, out var insidePatternWithDots, out var ctrlOrShiftSpaceAfterDot, out var pattern); + currentLanguage.LanguageIntellisenseSupport, in context, out var insidePatternWithDots, out var ctrlOrShiftSpaceAfterDot, out var pattern); // добавляем ключевые слова в случае "ctrl + space", нажатых в "пустом" месте if (!ctrlOrShiftSpaceAfterDot && context.ctrlSpace && string.IsNullOrEmpty(pattern)) @@ -537,7 +535,7 @@ namespace VisualPascalABC if (symInfos != null) { - currentLanguage.LanguageInformation.RenameOrExcludeSpecialNames(symInfos); + currentLanguage.LanguageIntellisenseSupport.RenameOrExcludeSpecialNames(symInfos); AddCompletionDatasForSymInfos(resultList, currentLanguage.CaseSensitive, symInfos, selectedSymInfo, lastUsedMember); } @@ -689,7 +687,7 @@ namespace VisualPascalABC /// /// Получение текста выражения, введенного пользователем перед нажатием "триггерной" клавиши /// - private string GetExpressionTextForCompletionData(int off, string text, int line, int col, ILanguageInformation languageInformation, in ActionContext context, out bool insidePatternWithDots, out bool ctrlOrShiftSpaceAfterDot, out string pattern) + private string GetExpressionTextForCompletionData(int off, string text, int line, int col, ILanguageIntellisenseSupport languageIntellisenseSupport, in ActionContext context, out bool insidePatternWithDots, out bool ctrlOrShiftSpaceAfterDot, out string pattern) { string expressionText = null; @@ -700,7 +698,7 @@ namespace VisualPascalABC if (context.ctrlSpace || context.shiftSpace) { - pattern = languageInformation.FindPattern(off, text, out var isPattern); + pattern = languageIntellisenseSupport.FindPattern(off, text, out var isPattern); // в конце выражения точка if (!isPattern && text[off - 1] == '.') @@ -718,7 +716,7 @@ namespace VisualPascalABC } else if (context.spaceAfterNew) { - expressionText = languageInformation.SkipNew(off - 1, text, ref keyword); + expressionText = languageIntellisenseSupport.SkipNew(off - 1, text, ref keyword); } else if (context.dotPressed) // keywordKind != KeywordKind.Uses { diff --git a/VisualPascalABCNET/IB/CodeCompletion/DefinitionByMouseClickManager.cs b/VisualPascalABCNET/IB/CodeCompletion/DefinitionByMouseClickManager.cs index 284a907e1..903067e75 100644 --- a/VisualPascalABCNET/IB/CodeCompletion/DefinitionByMouseClickManager.cs +++ b/VisualPascalABCNET/IB/CodeCompletion/DefinitionByMouseClickManager.cs @@ -3,13 +3,9 @@ using System; using System.Collections.Generic; using System.Drawing; -using System.IO; -using System.Linq; -using System.Text; using System.Windows.Forms; using ICSharpCode.TextEditor; using ICSharpCode.TextEditor.Document; -using ICSharpCode.TextEditor.Gui.CompletionWindow; namespace VisualPascalABC { @@ -19,11 +15,17 @@ namespace VisualPascalABC public static void DefinitionByMouseClickManager_TextAreaMouseMove(object sender, MouseEventArgs e) { + if (!CodeCompletion.CodeCompletionController.IntellisenseAvailable()) + return; + makeWordUnderline(sender, e); } public static void DefinitionByMouseClickManager_TextAreaMouseDown(object sender, EventArgs e) { + if (!CodeCompletion.CodeCompletionController.IntellisenseAvailable()) + return; + TextArea textArea = (TextArea)sender; if (Control.ModifierKeys == Keys.Control && textArea.SelectionManager.SelectionCollection.Count == 0) { diff --git a/VisualPascalABCNET/IB/CodeCompletion/InsightProvider.cs b/VisualPascalABCNET/IB/CodeCompletion/InsightProvider.cs index fbcd8fa67..ce5f3c601 100644 --- a/VisualPascalABCNET/IB/CodeCompletion/InsightProvider.cs +++ b/VisualPascalABCNET/IB/CodeCompletion/InsightProvider.cs @@ -31,8 +31,8 @@ namespace VisualPascalABC private string FindExpression(int off, string Text, int line, int col) { - if (CodeCompletion.CodeCompletionController.CurrentParser != null) - return CodeCompletion.CodeCompletionController.CurrentParser.LanguageInformation.FindExpressionForMethod(off, Text, line, col, pressed_key, ref num_param); + if (CodeCompletion.CodeCompletionController.IntellisenseAvailable()) + return CodeCompletion.CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.FindExpressionForMethod(off, Text, line, col, pressed_key, ref num_param); return null; } @@ -42,7 +42,7 @@ namespace VisualPascalABC { if (setupOnlyOnce && this.textArea != null) { - if (CodeCompletion.CodeCompletionController.CurrentParser.LanguageInformation.IsMethodCallParameterSeparator(pressed_key)) + if (CodeCompletion.CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.IsMethodCallParameterSeparator(pressed_key)) { FindExpression(textArea.Caret.Offset, textArea.Document.TextContent.Substring(0, textArea.Caret.Offset), textArea.Caret.Line, textArea.Caret.Column); @@ -71,9 +71,9 @@ namespace VisualPascalABC if (dconv != null) { //if (pressed_key == '(' || pressed_key == ',') - if (CodeCompletion.CodeCompletionController.CurrentParser.LanguageInformation.IsOpenBracketForMethodCall(pressed_key) || CodeCompletion.CodeCompletionController.CurrentParser.LanguageInformation.IsMethodCallParameterSeparator(pressed_key)) + if (CodeCompletion.CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.IsOpenBracketForMethodCall(pressed_key) || CodeCompletion.CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.IsMethodCallParameterSeparator(pressed_key)) methods = dconv.GetNameOfMethod(e, expr, line, col, num_param, ref defaultIndex, cur_param_num, out param_count); - else if (CodeCompletion.CodeCompletionController.CurrentParser.LanguageInformation.IsOpenBracketForIndex(pressed_key)) + else if (CodeCompletion.CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.IsOpenBracketForIndex(pressed_key)) methods = dconv.GetIndex(e, line, col); } } diff --git a/VisualPascalABCNET/IB/CodeCompletion/TooltipServiceManager.cs b/VisualPascalABCNET/IB/CodeCompletion/TooltipServiceManager.cs index 12b8801cb..585d567cd 100644 --- a/VisualPascalABCNET/IB/CodeCompletion/TooltipServiceManager.cs +++ b/VisualPascalABCNET/IB/CodeCompletion/TooltipServiceManager.cs @@ -8,7 +8,6 @@ using System.Windows.Forms; using ICSharpCode.TextEditor; using ICSharpCode.TextEditor.Document; using ICSharpCode.TextEditor.Gui.CompletionWindow; -using PascalABCCompiler.Parsers; namespace VisualPascalABC { @@ -29,9 +28,9 @@ namespace VisualPascalABC //string expr = FindFullExpression(doc.TextContent, seg.Offset + logicPos.X,e.LogicalPosition.Line,e.LogicalPosition.Column); - IParser parser = CodeCompletion.CodeCompletionController.CurrentParser; + var currentLanguage = CodeCompletion.CodeCompletionController.CurrentLanguage; - string expr = parser.LanguageInformation.FindExpressionFromAnyPosition( + string expr = currentLanguage.LanguageIntellisenseSupport.FindExpressionFromAnyPosition( lineSegment.Offset + logicPos.X, doc.TextContent, e.LogicalPosition.Line, e.LogicalPosition.Column, out var keyw, out var exprWithoutBrackets); // пока непонятно, когда такое может быть EVA @@ -44,25 +43,25 @@ namespace VisualPascalABC List Errors = new List(); List Warnings = new List(); - PascalABCCompiler.SyntaxTree.expression expressionTree = parser.GetExpression("test" + Path.GetExtension(fileName), + PascalABCCompiler.SyntaxTree.expression expressionTree = currentLanguage.Parser.GetExpression("test" + Path.GetExtension(fileName), expr, Errors, Warnings); // Пока добавили проверку, что анализируем Паскаль EVA - if (Errors.Count > 0 && parser == Languages.Facade.LanguageProvider.Instance.MainLanguage.Parser) + if (Errors.Count > 0 && currentLanguage == Languages.Facade.LanguageProvider.Instance.MainLanguage) { string s = expr.TrimStart(); if (s.Length > 0 && s[0] == '^') { Errors.Clear(); exprWithoutBrackets = exprWithoutBrackets.TrimStart().Substring(1); - expressionTree = parser.GetExpression("test" + Path.GetExtension(fileName), s.Substring(1), Errors, Warnings); + expressionTree = currentLanguage.Parser.GetExpression("test" + Path.GetExtension(fileName), s.Substring(1), Errors, Warnings); } } List Errors2 = new List(); // проверка для выражения без скобок - PascalABCCompiler.SyntaxTree.expression expressionTree2 = parser.GetExpression("test" + Path.GetExtension(fileName), exprWithoutBrackets, Errors2, Warnings); + PascalABCCompiler.SyntaxTree.expression expressionTree2 = currentLanguage.Parser.GetExpression("test" + Path.GetExtension(fileName), exprWithoutBrackets, Errors2, Warnings); // если не получается, то сразу возврат if (expressionTree2 == null || Errors2.Count > 0) @@ -118,7 +117,7 @@ namespace VisualPascalABC { if (!VisualPABCSingleton.MainForm.UserOptions.CodeCompletionHint) return; - if (CodeCompletion.CodeCompletionController.CurrentParser == null) + if (!CodeCompletion.CodeCompletionController.IntellisenseAvailable()) return; try { diff --git a/VisualPascalABCNET/IB/Debugger/Debugger.cs b/VisualPascalABCNET/IB/Debugger/Debugger.cs index f69424e82..57effe020 100644 --- a/VisualPascalABCNET/IB/Debugger/Debugger.cs +++ b/VisualPascalABCNET/IB/Debugger/Debugger.cs @@ -304,7 +304,7 @@ namespace VisualPascalABC public bool IsRunning = false; public string ExeFileName; public bool ShowDebugTabs=true; - public PascalABCCompiler.Parsers.IParser parser = null; + public Languages.Facade.ILanguage language = null; EventHandler debuggerStateEvent; public DebugHelper() @@ -465,7 +465,7 @@ namespace VisualPascalABC this.FullFileName = Path.Combine(Path.GetDirectoryName(fileName), this.FileName); this.ExeFileName = fileName; CurrentLine = 0; - this.parser = Languages.Facade.LanguageProvider.Instance.SelectLanguageByExtensionSafe(FullFileName)?.Parser; + this.language = Languages.Facade.LanguageProvider.Instance.SelectLanguageByExtension(FullFileName); this.PrevFullFileName = FullFileName; AssemblyHelper.LoadAssembly(fileName); dbg.ProcessStarted += debugProcessStarted; @@ -534,7 +534,7 @@ namespace VisualPascalABC //ChangeLocalVars(e.Process); //if (e.Process.IsPaused) WorkbenchServiceFactory.DebuggerOperationsService.RefreshPad(new FunctionItem(e.Process.SelectedFunction).SubItems); - workbench.WidgetController.SetStartDebugEnabled(); + workbench.WidgetController.SetStartDebugAndRunEnabled(); if (currentFunction != e.Process.SelectedFunction) { if (WorkbenchServiceFactory.Workbench.DisassemblyWindow.IsVisible) @@ -601,7 +601,7 @@ namespace VisualPascalABC private void debuggedProcess_Expired(object sender, EventArgs e) { - workbench.WidgetController.SetStartDebugEnabled(); + workbench.WidgetController.SetStartDebugAndRunEnabled(); } private void debuggedProcess_ExceptionThrown(object sender, ExceptionEventArgs e) @@ -666,7 +666,7 @@ namespace VisualPascalABC workbench.ServiceContainer.EditorService.SetEditorDisabled(false); //RemoveMarker(frm.CurrentCodeFileDocument.TextEditor.ActiveTextAreaControl.Document); evaluator = null; - parser= null; + language= null; FileName = null; handle = 0; ExeFileName = null; @@ -694,7 +694,7 @@ namespace VisualPascalABC workbench.WidgetController.SetDebugTabsVisible(true); workbench.WidgetController.SetPlayButtonsVisible(true); workbench.WidgetController.SetDebugStopEnabled();//e.Process.LogMessage += messageEventProc; - workbench.WidgetController.SetStartDebugDisabled(); + workbench.WidgetController.SetStartDebugAndRunDisabled(); workbench.WidgetController.ChangeStartDebugNameOnContinue(); workbench.WidgetController.EnableCodeCompletionToolTips(false); workbench.WidgetController.SetAddExprMenuVisible(true); @@ -1239,7 +1239,7 @@ namespace VisualPascalABC { sb.Insert(0, '.'); PascalABCCompiler.Parsers.KeywordKind keyw = PascalABCCompiler.Parsers.KeywordKind.None; - string s = CodeCompletion.CodeCompletionController.CurrentParser.LanguageInformation. + string s = CodeCompletion.CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport. FindExpression(i, text, 0, 0, out keyw); if (s != null) { @@ -1598,7 +1598,7 @@ namespace VisualPascalABC { try { - workbench.WidgetController.SetStartDebugEnabled(); + workbench.WidgetController.SetStartDebugAndRunEnabled(); dbg.Processes[0].Terminate(); } catch (System.Exception e) @@ -1614,7 +1614,7 @@ namespace VisualPascalABC { try { - workbench.WidgetController.SetStartDebugEnabled(); + workbench.WidgetController.SetStartDebugAndRunEnabled(); dbg.Processes[0].Break(); } catch (System.Exception e) @@ -1680,7 +1680,7 @@ namespace VisualPascalABC { try { - workbench.WidgetController.SetStartDebugDisabled(); + workbench.WidgetController.SetStartDebugAndRunDisabled(); if (debuggedProcess.SelectedFunction.Name == ".cctor") { var sequencePoints = debuggedProcess.SelectedFunction.symMethod.SequencePoints; @@ -1708,7 +1708,7 @@ namespace VisualPascalABC { try { - workbench.WidgetController.SetStartDebugDisabled(); + workbench.WidgetController.SetStartDebugAndRunDisabled(); dbg.Processes[0].Continue(); CurrentLineBookmark.Remove(); } @@ -1725,7 +1725,7 @@ namespace VisualPascalABC { try { - workbench.WidgetController.SetStartDebugDisabled(); + workbench.WidgetController.SetStartDebugAndRunDisabled(); stepin_stmt = dbg.Processes[0].NextStatement; dbg.Processes[0].StepInto(); CurrentLineBookmark.Remove(); @@ -1745,7 +1745,7 @@ namespace VisualPascalABC { if (IsRunning) { - workbench.WidgetController.SetStartDebugDisabled(); + workbench.WidgetController.SetStartDebugAndRunDisabled(); dbg.Processes[0].StepOut(); CurrentLineBookmark.Remove(); } @@ -1765,7 +1765,7 @@ namespace VisualPascalABC { //cur_brpt = dbg.AddBreakpoint(new SourcecodeSegment((frm.CurrentTabPage.ag as CodeFileDocumentControl).file_name,(frm.CurrentTabPage.ag as CodeFileDocumentControl).TextEditor.ActiveTextAreaControl.Caret.Line + 1,(frm.CurrentTabPage.Tag as CodeFileDocumentControl).TextEditor.ActiveTextAreaControl.Caret.Column + 1, // (frm.CurrentTabPage.ag as CodeFileDocumentControl).TextEditor.ActiveTextAreaControl.Caret.Column+100), true); - workbench.WidgetController.SetStartDebugDisabled(); + workbench.WidgetController.SetStartDebugAndRunDisabled(); currentBreakpoint = dbg.AddBreakpoint(WorkbenchServiceFactory.DocumentService.CurrentCodeFileDocument.FileName, WorkbenchServiceFactory.DocumentService.CurrentCodeFileDocument.TextEditor.ActiveTextAreaControl.Caret.Line + 1); AddGoToBreakPoint(currentBreakpoint); Status = DebugStatus.None; diff --git a/VisualPascalABCNET/IB/Debugger/LocalVars.cs b/VisualPascalABCNET/IB/Debugger/LocalVars.cs index aa1dd0465..7342dd5f9 100644 --- a/VisualPascalABCNET/IB/Debugger/LocalVars.cs +++ b/VisualPascalABCNET/IB/Debugger/LocalVars.cs @@ -717,8 +717,8 @@ namespace VisualPascalABC } else if (val.IsNull) - if (WorkbenchServiceFactory.DebuggerManager.parser != null) - return WorkbenchServiceFactory.DebuggerManager.parser.LanguageInformation.GetKeyword(PascalABCCompiler.Parsers.SymbolKind.Null); + if (WorkbenchServiceFactory.DebuggerManager.language != null) + return WorkbenchServiceFactory.DebuggerManager.language.LanguageIntellisenseSupport.GetKeyword(PascalABCCompiler.Parsers.SymbolKind.Null); else return "nil"; else diff --git a/VisualPascalABCNET/IB/Debugger/Utility.cs b/VisualPascalABCNET/IB/Debugger/Utility.cs index c7b2682bc..c6a354383 100644 --- a/VisualPascalABCNET/IB/Debugger/Utility.cs +++ b/VisualPascalABCNET/IB/Debugger/Utility.cs @@ -122,8 +122,8 @@ namespace VisualPascalABC public static string WrapTypeName(DebugType type) { if (type.IsArray) - if (WorkbenchServiceFactory.DebuggerManager.parser != null) - return WorkbenchServiceFactory.DebuggerManager.parser.LanguageInformation.GetArrayDescription(WrapTypeName(type.GetElementType()), type.GetArrayRank()); + if (WorkbenchServiceFactory.DebuggerManager.language != null) + return WorkbenchServiceFactory.DebuggerManager.language.LanguageIntellisenseSupport.GetArrayDescription(WrapTypeName(type.GetElementType()), type.GetArrayRank()); else return "array of " + WrapTypeName(type.GetElementType()); return internalWrapTypeName(type.FullName); @@ -182,23 +182,23 @@ namespace VisualPascalABC private static string internalWrapTypeName(string name) { - if (WorkbenchServiceFactory.DebuggerManager.parser != null) + if (WorkbenchServiceFactory.DebuggerManager.language != null) switch (name) { - case "System.Boolean": return WorkbenchServiceFactory.DebuggerManager.parser.LanguageInformation.GetShortTypeName(typeof(bool)); - case "System.Int32": return WorkbenchServiceFactory.DebuggerManager.parser.LanguageInformation.GetShortTypeName(typeof(int)); - case "System.Byte": return WorkbenchServiceFactory.DebuggerManager.parser.LanguageInformation.GetShortTypeName(typeof(byte)); - case "System.Double": return WorkbenchServiceFactory.DebuggerManager.parser.LanguageInformation.GetShortTypeName(typeof(double)); - case "System.String": return WorkbenchServiceFactory.DebuggerManager.parser.LanguageInformation.GetShortTypeName(typeof(string)); - case "System.Char": return WorkbenchServiceFactory.DebuggerManager.parser.LanguageInformation.GetShortTypeName(typeof(char)); - case "System.SByte": return WorkbenchServiceFactory.DebuggerManager.parser.LanguageInformation.GetShortTypeName(typeof(sbyte)); - case "System.Int16": return WorkbenchServiceFactory.DebuggerManager.parser.LanguageInformation.GetShortTypeName(typeof(short)); - case "System.UInt16": return WorkbenchServiceFactory.DebuggerManager.parser.LanguageInformation.GetShortTypeName(typeof(ushort)); - case "System.UInt32": return WorkbenchServiceFactory.DebuggerManager.parser.LanguageInformation.GetShortTypeName(typeof(uint)); - case "System.Int64": return WorkbenchServiceFactory.DebuggerManager.parser.LanguageInformation.GetShortTypeName(typeof(long)); - case "System.UInt64": return WorkbenchServiceFactory.DebuggerManager.parser.LanguageInformation.GetShortTypeName(typeof(ulong)); - case "System.Float32": return WorkbenchServiceFactory.DebuggerManager.parser.LanguageInformation.GetShortTypeName(typeof(float)); - case "System.IntPtr": return WorkbenchServiceFactory.DebuggerManager.parser.LanguageInformation.GetShortTypeName(Type.GetType("System.Void*")); + case "System.Boolean": return WorkbenchServiceFactory.DebuggerManager.language.LanguageIntellisenseSupport.GetShortTypeName(typeof(bool)); + case "System.Int32": return WorkbenchServiceFactory.DebuggerManager.language.LanguageIntellisenseSupport.GetShortTypeName(typeof(int)); + case "System.Byte": return WorkbenchServiceFactory.DebuggerManager.language.LanguageIntellisenseSupport.GetShortTypeName(typeof(byte)); + case "System.Double": return WorkbenchServiceFactory.DebuggerManager.language.LanguageIntellisenseSupport.GetShortTypeName(typeof(double)); + case "System.String": return WorkbenchServiceFactory.DebuggerManager.language.LanguageIntellisenseSupport.GetShortTypeName(typeof(string)); + case "System.Char": return WorkbenchServiceFactory.DebuggerManager.language.LanguageIntellisenseSupport.GetShortTypeName(typeof(char)); + case "System.SByte": return WorkbenchServiceFactory.DebuggerManager.language.LanguageIntellisenseSupport.GetShortTypeName(typeof(sbyte)); + case "System.Int16": return WorkbenchServiceFactory.DebuggerManager.language.LanguageIntellisenseSupport.GetShortTypeName(typeof(short)); + case "System.UInt16": return WorkbenchServiceFactory.DebuggerManager.language.LanguageIntellisenseSupport.GetShortTypeName(typeof(ushort)); + case "System.UInt32": return WorkbenchServiceFactory.DebuggerManager.language.LanguageIntellisenseSupport.GetShortTypeName(typeof(uint)); + case "System.Int64": return WorkbenchServiceFactory.DebuggerManager.language.LanguageIntellisenseSupport.GetShortTypeName(typeof(long)); + case "System.UInt64": return WorkbenchServiceFactory.DebuggerManager.language.LanguageIntellisenseSupport.GetShortTypeName(typeof(ulong)); + case "System.Float32": return WorkbenchServiceFactory.DebuggerManager.language.LanguageIntellisenseSupport.GetShortTypeName(typeof(float)); + case "System.IntPtr": return WorkbenchServiceFactory.DebuggerManager.language.LanguageIntellisenseSupport.GetShortTypeName(Type.GetType("System.Void*")); default: return name; } else diff --git a/VisualPascalABCNET/IB/FormExtensions.cs b/VisualPascalABCNET/IB/FormExtensions.cs index 57274c80d..bee392a3a 100644 --- a/VisualPascalABCNET/IB/FormExtensions.cs +++ b/VisualPascalABCNET/IB/FormExtensions.cs @@ -464,7 +464,7 @@ namespace VisualPascalABC void tsIntellisense_DropDownOpened(object sender, EventArgs e) { - if (UserOptions.AllowCodeCompletion) + if (UserOptions.AllowCodeCompletion && CodeCompletion.CodeCompletionController.IntellisenseAvailable()) { //GotoAction ga = new GotoAction(); TextArea ta = CurrentCodeFileDocument.TextEditor.ActiveTextAreaControl.TextArea; @@ -474,18 +474,47 @@ namespace VisualPascalABC //this.cmFindAllReferences.Enabled = ga.CanFindReferences(ta); this.miGenerateRealization.Enabled = CodeCompletionActionsManager.CanGenerateRealization(ta); } + else + { + DisableIntellisenseDropDownOptions(); + } } private void OpeningContextMenu(object sender, CancelEventArgs args) { - GotoAction ga = new GotoAction(); - TextArea ta = CurrentCodeFileDocument.TextEditor.ActiveTextAreaControl.TextArea; - this.cmGotoDefinition.Enabled = CodeCompletionActionsManager.CanGoTo(ta); - this.cmGotoRealization.Enabled = CodeCompletionActionsManager.CanGoToRealization(ta); - this.cmFindAllReferences.Enabled = CodeCompletionActionsManager.CanFindReferences(ta); - this.cmGenerateRealization.Enabled = CodeCompletionActionsManager.CanGenerateRealization(ta); - this.cmRename.Enabled = CodeCompletionActionsManager.CanGoTo(ta); - } + if (CodeCompletion.CodeCompletionController.IntellisenseAvailable()) + { + // GotoAction ga = new GotoAction(); + TextArea ta = CurrentCodeFileDocument.TextEditor.ActiveTextAreaControl.TextArea; + + this.cmGotoDefinition.Enabled = CodeCompletionActionsManager.CanGoTo(ta); + this.cmGotoRealization.Enabled = CodeCompletionActionsManager.CanGoToRealization(ta); + this.cmFindAllReferences.Enabled = CodeCompletionActionsManager.CanFindReferences(ta); + this.cmGenerateRealization.Enabled = CodeCompletionActionsManager.CanGenerateRealization(ta); + this.cmRename.Enabled = CodeCompletionActionsManager.CanGoTo(ta); + } + else + { + DisableIntellisenseContextMenuOptions(); + } + } + + private void DisableIntellisenseContextMenuOptions() + { + this.cmGotoDefinition.Enabled = false; + this.cmGotoRealization.Enabled = false; + this.cmFindAllReferences.Enabled = false; + this.cmGenerateRealization.Enabled = false; + this.cmRename.Enabled = false; + } + + private void DisableIntellisenseDropDownOptions() + { + this.tsGotoDefinition.Enabled = false; + this.tsGotoRealization.Enabled = false; + this.tsFindAllReferences.Enabled = false; + this.miGenerateRealization.Enabled = false; + } private void ClosingContextMenu(object sender, CancelEventArgs args) { diff --git a/VisualPascalABCNET/Projects/ProjectTasks.cs b/VisualPascalABCNET/Projects/ProjectTasks.cs index bca01b223..02093dac4 100644 --- a/VisualPascalABCNET/Projects/ProjectTasks.cs +++ b/VisualPascalABCNET/Projects/ProjectTasks.cs @@ -114,11 +114,11 @@ namespace VisualPascalABC string full_file_name = Path.Combine(Path.GetDirectoryName(ProjectFactory.Instance.CurrentProject.Path),frm.FileName); StreamWriter sw = File.CreateText(full_file_name); - ILanguageInformation languageInfo = Languages.Facade.LanguageProvider.Instance.SelectLanguageByExtension(frm.FileName).LanguageInformation; + var languageIntellisenseSupport = Languages.Facade.LanguageProvider.Instance.SelectLanguageByExtension(frm.FileName).LanguageIntellisenseSupport; if (frm.GetFileFilter() == FileType.Unit) { - sw.Write(languageInfo.GetUnitTemplate(Path.GetFileNameWithoutExtension(frm.FileName))); + sw.Write(languageIntellisenseSupport.GetUnitTemplate(Path.GetFileNameWithoutExtension(frm.FileName))); } else { diff --git a/VisualPascalABCNET/Workbench/BuildService.cs b/VisualPascalABCNET/Workbench/BuildService.cs index 0328ae04a..ee82bbd48 100644 --- a/VisualPascalABCNET/Workbench/BuildService.cs +++ b/VisualPascalABCNET/Workbench/BuildService.cs @@ -55,7 +55,7 @@ namespace VisualPascalABC public string Compile(PascalABCCompiler.IProjectInfo project, bool rebuild, string RuntimeServicesModule, bool ForRun, bool RunWithEnvironment) { ProjectService.SaveProject(); - Workbench.WidgetController.CompilingButtonsEnabled = false; + Workbench.WidgetController.CompilingAndRunButtonsEnabled = false; Workbench.CompilerConsoleWindow.ClearConsole(); CompilerOptions1.SourceFileName = project.Path; CompilerOptions1.OutputDirectory = project.OutputDirectory; @@ -98,7 +98,7 @@ namespace VisualPascalABC public string Compile(string FileName, bool rebuild, string RuntimeServicesModule, bool ForRun, bool RunWithEnvironment) { - Workbench.WidgetController.CompilingButtonsEnabled = false; + Workbench.WidgetController.CompilingAndRunButtonsEnabled = false; var UserOptions = Workbench.UserOptions; diff --git a/VisualPascalABCNET/Workbench/FileOperations.cs b/VisualPascalABCNET/Workbench/FileOperations.cs index c4e708de4..535e6158b 100644 --- a/VisualPascalABCNET/Workbench/FileOperations.cs +++ b/VisualPascalABCNET/Workbench/FileOperations.cs @@ -87,7 +87,8 @@ namespace VisualPascalABC } //CloseButtonsEnabled = OpenDocuments.Count > 1; ChangedSelectedTab(); - if (FileName != null) // SS 09.08.08 + if (FileName != null // SS 09.08.08 + && CodeCompletion.CodeCompletionController.IntellisenseAvailable()) WorkbenchServiceFactory.CodeCompletionParserController.RegisterFileForParsing(FileName); } diff --git a/VisualPascalABCNET/Workbench/HelpService.cs b/VisualPascalABCNET/Workbench/HelpService.cs index e76920a82..de2877f2c 100644 --- a/VisualPascalABCNET/Workbench/HelpService.cs +++ b/VisualPascalABCNET/Workbench/HelpService.cs @@ -95,7 +95,7 @@ namespace VisualPascalABC case "string": return false; } - if (CodeCompletion.CodeCompletionController.CurrentParser == null) return false; + if (!CodeCompletion.CodeCompletionController.IntellisenseAvailable()) return false; List poses = CodeCompletionActionsManager.GetDefinitionPosition(CurrentSyntaxEditor.TextEditor.ActiveTextAreaControl.TextArea, true); if (poses == null || poses.Count == 0) return false; foreach (Position pos in poses) diff --git a/VisualPascalABCNET/Workbench/RunService.cs b/VisualPascalABCNET/Workbench/RunService.cs index 55d590589..58a35ca67 100644 --- a/VisualPascalABCNET/Workbench/RunService.cs +++ b/VisualPascalABCNET/Workbench/RunService.cs @@ -119,7 +119,7 @@ namespace VisualPascalABC if (ProjectFactory.Instance.ProjectLoaded) tabPage = DocumentService.GetTabPageForMainFile(); if (attachdbg && !Workbench.UserOptions.AlwaysAttachDebuggerAtStart) - fictive_attach = !startWithGoto && !needFirstBreakpoint && !DebuggerManager.HasBreakpoints(); + fictive_attach = !startWithGoto && !needFirstBreakpoint && !DebuggerManager.HasBreakpoints() || !CodeCompletion.CodeCompletionController.IntellisenseAvailable(); WorkbenchServiceFactory.OperationsService.ClearOutputTextBoxForTabPage(tabPage); Workbench.ErrorsListWindow.ClearErrorList(); DesignerService.GenerateAllDesignersCode(); diff --git a/VisualPascalABCNET/Workbench/RunnerManagerHandlers.cs b/VisualPascalABCNET/Workbench/RunnerManagerHandlers.cs index f647c4cb6..72b160c38 100644 --- a/VisualPascalABCNET/Workbench/RunnerManagerHandlers.cs +++ b/VisualPascalABCNET/Workbench/RunnerManagerHandlers.cs @@ -27,7 +27,7 @@ namespace VisualPascalABC void ButtonsEnableDisable_RunStart() { Workbench.WidgetController.SetStopEnabled(true); - Workbench.WidgetController.SetCompilingButtonsEnabled(false); + Workbench.WidgetController.SetCompilingAndRunButtonsEnabled(false); Workbench.WidgetController.SetDebugButtonsEnabled(false); Workbench.WidgetController.SetOptionsEnabled(false); } @@ -35,8 +35,9 @@ namespace VisualPascalABC void ButtonsEnableDisable_RunStop() { Workbench.WidgetController.SetStopEnabled(false); - Workbench.WidgetController.SetCompilingButtonsEnabled(true); - Workbench.WidgetController.SetDebugButtonsEnabled(true); + Workbench.WidgetController.SetCompilingAndRunButtonsEnabled(true); + if (CodeCompletion.CodeCompletionController.IntellisenseAvailable()) + Workbench.WidgetController.SetDebugButtonsEnabled(true); Workbench.WidgetController.SetOptionsEnabled(true); } diff --git a/VisualPascalABCNET/Workbench/VisibilityService.cs b/VisualPascalABCNET/Workbench/VisibilityService.cs index 48b4c094d..57067c814 100644 --- a/VisualPascalABCNET/Workbench/VisibilityService.cs +++ b/VisualPascalABCNET/Workbench/VisibilityService.cs @@ -22,10 +22,10 @@ namespace VisualPascalABC internal List BottomDockContent = new List(); List VisibleBottomContent = new List(); - public bool CompilingButtonsEnabled + public bool CompilingAndRunButtonsEnabled { get { return miRun.Enabled; } - set { SetCompilingButtonsEnabled(value); } + set { SetCompilingAndRunButtonsEnabled(value); } } bool SaveButtonsEnabled @@ -100,16 +100,17 @@ namespace VisualPascalABC set { miNavigForw.Enabled = tsNavigForw.Enabled = value; } } - public void SetDedugButtonsEnabled(bool Enabled) + /// + /// Активировать/Деактивировать все кнопки, относящиеся к дебагу. + /// + public void SetDebugButtonsEnabled(bool Enabled) { StepIntoButton.Enabled = StepOverButton.Enabled = StartDebugButton.Enabled = - mDEBUGSTARTToolStripMenuItem.Enabled = mSTEPOVERToolStripMenuItem.Enabled = mSTEPINToolStripMenuItem.Enabled = mRUNTOCURToolStripMenuItem.Enabled = Enabled; - + mDEBUGSTARTToolStripMenuItem.Enabled = mSTEPOVERToolStripMenuItem.Enabled = + mSTEPINToolStripMenuItem.Enabled = mRUNTOCURToolStripMenuItem.Enabled = Enabled; //toolStrip1.Refresh(); } - - bool BottomDockContentVisible { get @@ -317,7 +318,7 @@ namespace VisualPascalABC } } - public void SetCompilingButtonsEnabled(bool Enabled) + public void SetCompilingAndRunButtonsEnabled(bool Enabled) { if (Enabled) { @@ -388,7 +389,7 @@ namespace VisualPascalABC public void SetDebugStopEnabled() { - SetCompilingButtonsEnabled(false); + SetCompilingAndRunButtonsEnabled(false); this.mDEBUGSTOPToolStripMenuItem.Enabled = true; this.mDEBUGENDToolStripMenuItem.Enabled = true; this.mSTEPToolStripMenuItem.Enabled = true; @@ -412,7 +413,7 @@ namespace VisualPascalABC this.mDEBUGSTARTToolStripMenuItem.Text = Form1StringResources.Get("M_DEBUGSTART"); } - public void SetStartDebugDisabled() + public void SetStartDebugAndRunDisabled() { this.mDEBUGSTARTToolStripMenuItem.Enabled = false; this.StartDebugButton.Enabled = false; @@ -429,7 +430,10 @@ namespace VisualPascalABC SaveDebugContext(); } - public void SetStartDebugEnabled() + /// + /// Активирует кнопки для Debug и запуска программы + /// + public void SetStartDebugAndRunEnabled() { this.mDEBUGSTARTToolStripMenuItem.Enabled = true; this.StartDebugButton.Enabled = true; @@ -439,6 +443,7 @@ namespace VisualPascalABC this.StepOverButton.Enabled = true; this.mRUNTOCURToolStripMenuItem.Enabled = true; this.mSTEPToolStripMenuItem.Enabled = true; + this.miRun.Enabled = true; this.StartButton.Enabled = true; ChangeDebugButtons(false); @@ -453,7 +458,7 @@ namespace VisualPascalABC this.StepOutButton.Enabled = false; if (!(clicked_stop_debug_in_menu && WorkbenchServiceFactory.RunService.IsRun() && debuggedPage != ActiveCodeFileDocument)) { - SetCompilingButtonsEnabled(true); + SetCompilingAndRunButtonsEnabled(true); this.stopButton.Enabled = false; this.miStop.Enabled = false; } @@ -510,42 +515,17 @@ namespace VisualPascalABC } } - public void SetDebugButtonsEnabled(bool val) + /// + /// Активировать/Деактивировать все кнопки, относящиеся к форматированию кода + /// + private void SetFormatButtonsEnabled(bool enabled) { - if (val) - { - this.mDEBUGSTOPToolStripMenuItem.Enabled = false; - this.mDEBUGSTARTToolStripMenuItem.Enabled = false; - this.StartDebugButton.Enabled = true; - this.StopDebugButton.Enabled = true; - this.StepOutButton.Enabled = false; - this.StepOverButton.Enabled = true; - this.StepIntoButton.Enabled = true; - this.mDEBUGSTARTToolStripMenuItem.Enabled = true; - this.mSTEPINToolStripMenuItem.Enabled = true; - this.mSTEPOVERToolStripMenuItem.Enabled = true; - this.mSTEPToolStripMenuItem.Enabled = false; - this.mRUNTOCURToolStripMenuItem.Enabled = true; - this.miRun.Enabled = true; - this.StartButton.Enabled = true; - } - else - { - this.mDEBUGSTOPToolStripMenuItem.Enabled = false; - this.mSTEPToolStripMenuItem.Enabled = false; - this.StartDebugButton.Enabled = false; - this.StopDebugButton.Enabled = false; - this.StepOutButton.Enabled = false; - this.StepOverButton.Enabled = false; - this.StepIntoButton.Enabled = false; - this.mDEBUGSTARTToolStripMenuItem.Enabled = false; - this.mSTEPINToolStripMenuItem.Enabled = false; - this.mSTEPOVERToolStripMenuItem.Enabled = false; - this.mRUNTOCURToolStripMenuItem.Enabled = false; - this.mSTEPToolStripMenuItem.Enabled = false; - this.miRun.Enabled = false; - this.StartButton.Enabled = false; - } + tsFormat.Enabled = mFORMATToolStripMenuItem.Enabled = cmFormat.Enabled = enabled; + } + + private void SetRunButtonsEnabled(bool enabled) + { + miRun.Enabled = StartButton.Enabled = enabled; } bool mDEBUGSTOPToolStripMenuItem_Enabled; diff --git a/VisualPascalABCNET/Workbench/WindowOperations.cs b/VisualPascalABCNET/Workbench/WindowOperations.cs index 9bf4433de..f2bc6d1bc 100644 --- a/VisualPascalABCNET/Workbench/WindowOperations.cs +++ b/VisualPascalABCNET/Workbench/WindowOperations.cs @@ -398,8 +398,19 @@ namespace VisualPascalABC CurrentWebBrowserControl = null; SetFocusToEditor(); } + + CodeCompletion.CodeCompletionController.SetLanguage(CurrentCodeFileDocument.FileName); + + bool intellisenseAvailable = CodeCompletion.CodeCompletionController.IntellisenseAvailable(); + + SetFormatButtonsEnabled(intellisenseAvailable); + + if (!intellisenseAvailable) + SetDebugButtonsEnabled(false); // активация кнопок произойдет ниже, если возможно + if (BakSelectedTab == CurrentCodeFileDocument) return; + LastSelectedTab = BakSelectedTab; BakSelectedTab = CurrentCodeFileDocument; @@ -420,8 +431,6 @@ namespace VisualPascalABC OutputWindow.outputTextBox = OutputTextBoxs[CurrentCodeFileDocument]; } - CodeCompletion.CodeCompletionController.SetLanguage(CurrentCodeFileDocument.FileName); - SetFocusToEditor(); bool run = WorkbenchServiceFactory.RunService.IsRun(CurrentEXEFileName); WorkbenchServiceFactory.DebuggerManager.SetAsPossibleDebugPage(CurrentCodeFileDocument); @@ -435,16 +444,16 @@ namespace VisualPascalABC if (VisualEnvironmentCompiler != null) if (!debug) { - SetCompilingButtonsEnabled(!run && VisualEnvironmentCompiler.compilerLoaded); - SetDebugButtonsEnabled(!run && VisualEnvironmentCompiler.compilerLoaded); + SetCompilingAndRunButtonsEnabled(!run && VisualEnvironmentCompiler.compilerLoaded); + SetDebugButtonsEnabled(intellisenseAvailable && !run && VisualEnvironmentCompiler.compilerLoaded); } else { - SetCompilingButtonsEnabled(!debug); + SetCompilingAndRunButtonsEnabled(!debug); SetDebugButtonsAsByDebug(); } else - SetCompilingButtonsEnabled(false); + SetCompilingAndRunButtonsEnabled(false); SaveButtonsEnabled = CurrentCodeFileDocument.DocumentChanged; UpdateUndoRedoEnabled(); UpdateCutCopyButtonsEnabled(); diff --git a/VisualPascalABCNETLinux/DS/CodeCompletionVisual/TipPainterTools.cs b/VisualPascalABCNETLinux/DS/CodeCompletionVisual/TipPainterTools.cs index c181efcc2..bbf7e3794 100644 --- a/VisualPascalABCNETLinux/DS/CodeCompletionVisual/TipPainterTools.cs +++ b/VisualPascalABCNETLinux/DS/CodeCompletionVisual/TipPainterTools.cs @@ -66,11 +66,11 @@ namespace ICSharpCode.TextEditor.Util if (param_num == -1) return; - var languageInfo = CodeCompletion.CodeCompletionController.CurrentParser.LanguageInformation; + var languageIntellisenseSupport = CodeCompletion.CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport; int startIndex = basicDescription.IndexOf("(", basicDescription.IndexOf("(" + PascalABCCompiler.StringResources.Get("CODE_COMPLETION_EXTENSION")) + 1) + 1; - int paranthesisIndex = languageInfo.FindClosingParenthesis(basicDescription.Substring(startIndex), ')'); + int paranthesisIndex = languageIntellisenseSupport.FindClosingParenthesis(basicDescription.Substring(startIndex), ')'); if (paranthesisIndex == -1) return; @@ -83,7 +83,7 @@ namespace ICSharpCode.TextEditor.Util if (bold_beg != 0) { - int paramDelimIndex = languageInfo.FindParamDelim(basicDescription.Substring(bold_beg), 1); + int paramDelimIndex = languageIntellisenseSupport.FindParamDelim(basicDescription.Substring(bold_beg), 1); if (paramDelimIndex == -1) { @@ -104,7 +104,7 @@ namespace ICSharpCode.TextEditor.Util { string paramDescription = basicDescription.Substring(startIndex, paranthesisIndex); - if (languageInfo.IsParams(paramDescription)) + if (languageIntellisenseSupport.IsParams(paramDescription)) { bold_beg = startIndex; bold_len = paranthesisIndex; @@ -114,15 +114,15 @@ namespace ICSharpCode.TextEditor.Util { string descriptionAfterBracket = basicDescription.Substring(startIndex); - int paramDelimIndex = languageInfo.FindParamDelim(descriptionAfterBracket, paramsCount - 1); + int paramDelimIndex = languageIntellisenseSupport.FindParamDelim(descriptionAfterBracket, paramsCount - 1); if (paramDelimIndex != -1) { - int paramDelimLength = languageInfo.ParameterDelimiter.Length; + int paramDelimLength = languageIntellisenseSupport.ParameterDelimiter.Length; string paramDescription = descriptionAfterBracket.Substring(paramDelimIndex + paramDelimLength, paranthesisIndex - paramDelimIndex - paramDelimLength); - if (languageInfo.IsParams(paramDescription)) + if (languageIntellisenseSupport.IsParams(paramDescription)) { bold_beg = paramDelimIndex + startIndex + paramDelimLength; bold_len = end_sk - bold_beg; @@ -132,12 +132,12 @@ namespace ICSharpCode.TextEditor.Util } else { - int paramDelimIndex = languageInfo.FindParamDelim(basicDescription.Substring(startIndex), param_num - 1); + int paramDelimIndex = languageIntellisenseSupport.FindParamDelim(basicDescription.Substring(startIndex), param_num - 1); if (paramDelimIndex != -1) { - bold_beg = paramDelimIndex + startIndex + languageInfo.ParameterDelimiter.Length; - int secondParamDelimIndex = languageInfo.FindParamDelim(basicDescription.Substring(startIndex), param_num); + bold_beg = paramDelimIndex + startIndex + languageIntellisenseSupport.ParameterDelimiter.Length; + int secondParamDelimIndex = languageIntellisenseSupport.FindParamDelim(basicDescription.Substring(startIndex), param_num); if (secondParamDelimIndex == -1) { diff --git a/VisualPascalABCNETLinux/DS/VisualEnvironmentCompiler.cs b/VisualPascalABCNETLinux/DS/VisualEnvironmentCompiler.cs index 954f97906..ee2921ab3 100644 --- a/VisualPascalABCNETLinux/DS/VisualEnvironmentCompiler.cs +++ b/VisualPascalABCNETLinux/DS/VisualEnvironmentCompiler.cs @@ -34,7 +34,7 @@ namespace VisualPascalABC private System.Threading.Thread MainProgramThread = System.Threading.Thread.CurrentThread; private System.Threading.Thread StartingThread; public delegate void SetFlagDelegate(bool flag); - private SetFlagDelegate SetCompilingButtonsEnabled; + private SetFlagDelegate SetCompilingAndRunButtonsEnabled; private SetFlagDelegate SetDebugButtonsEnabled; public delegate void SetTextDelegate(string text); public delegate string ConvertUnitText(string FileName, string text); // Это пока только для шифрованного Tasks. В остальных случаях он нулевой @@ -67,7 +67,7 @@ namespace VisualPascalABC Dictionary OpenDocuments; public VisualEnvironmentCompiler(InvokeDegegate beginInvoke, - SetFlagDelegate setCompilingButtonsEnabled, SetFlagDelegate setCompilingDebugEnabled, SetTextDelegate setStateText, + SetFlagDelegate setCompilingAndRunButtonsEnabled, SetFlagDelegate setCompilingDebugEnabled, SetTextDelegate setStateText, SetTextDelegate addTextToCompilerMessages, ToolStripMenuItem pluginsMenuItem, ToolStrip pluginsToolStrip, ExecuteSourceLocationActionDelegate ExecuteSLAction, ExecuteVisualEnvironmentCompilerActionDelegate ExecuteVECAction, @@ -77,7 +77,7 @@ namespace VisualPascalABC this.StandartDirectories = StandartDirectories; this.ErrorsManager = ErrorsManager; this.ChangeVisualEnvironmentState += onChangeVisualEnvironmentState; - SetCompilingButtonsEnabled = setCompilingButtonsEnabled; + SetCompilingAndRunButtonsEnabled = setCompilingAndRunButtonsEnabled; SetDebugButtonsEnabled = setCompilingDebugEnabled; SetStateText = setStateText; AddTextToCompilerMessages = addTextToCompilerMessages; @@ -351,7 +351,7 @@ namespace VisualPascalABC { case PascalABCCompiler.CompilerState.CompilationStarting: RusName = VECStringResources.Get("STATE_START_COMPILING_ASSEMBLY{0}"); - SetCompilingButtonsEnabled(false); + SetCompilingAndRunButtonsEnabled(false); ParsedFiles.Clear(); break; case PascalABCCompiler.CompilerState.BeginCompileFile: RusName = VECStringResources.Get("STATE_BEGINCOMPILEFILE{0}"); break; @@ -397,21 +397,22 @@ namespace VisualPascalABC //if (!ThreadPool.QueueUserWorkItem(new WaitCallback(LoadPlugins))) // LoadPlugins(null); - SetCompilingButtonsEnabled(true); - SetDebugButtonsEnabled(true); + SetCompilingAndRunButtonsEnabled(true); + if (CodeCompletion.CodeCompletionController.IntellisenseAvailable()) + SetDebugButtonsEnabled(true); } } else { if (Compiler == sender) { - SetCompilingButtonsEnabled(true); + SetCompilingAndRunButtonsEnabled(true); } } break; case PascalABCCompiler.CompilerState.Reloading: if (Compiler == sender) - SetCompilingButtonsEnabled(false); + SetCompilingAndRunButtonsEnabled(false); RusName = VECStringResources.Get("STATE_RELOADING"); break; case PascalABCCompiler.CompilerState.CompilationFinished: diff --git a/VisualPascalABCNETLinux/Form1.cs b/VisualPascalABCNETLinux/Form1.cs index 45e86f844..79924b8ee 100644 --- a/VisualPascalABCNETLinux/Form1.cs +++ b/VisualPascalABCNETLinux/Form1.cs @@ -318,6 +318,7 @@ namespace VisualPascalABC this.StepOutButton.Visible = false; PlayPauseButtonsVisibleInPanel = PlayPauseButtonsVisibleInPanel; SetDebugButtonsEnabled(false); + SetRunButtonsEnabled(false); } // Для Linux сделать все Debug-кнопки неактивными @@ -408,7 +409,7 @@ namespace VisualPascalABC RunManager RunnerManager = (WorkbenchServiceFactory.RunService as WorkbenchRunService).RunnerManager; VisualEnvironmentCompiler = new VisualEnvironmentCompiler( - this.BeginInvoke, SetCompilingButtonsEnabled, SetDedugButtonsEnabled, SetStateText, + this.BeginInvoke, SetCompilingAndRunButtonsEnabled, SetDebugButtonsEnabled, SetStateText, AddTextToCompilerMessagesSync, miPlugins, toolStrip1, ExecuteSourceLocationAction, ExecuteVisualEnvironmentCompilerAction, ErrorsManager, RunnerManager, WorkbenchServiceFactory.DebuggerManager, UserOptions, WorkbenchStorage.StandartDirectories, OpenDocuments, this); @@ -493,10 +494,10 @@ namespace VisualPascalABC WorkbenchServiceFactory.FileService.OpenFile(FileNameToWait, null); } SetStopEnabled(false); - CompilingButtonsEnabled = CloseButtonsEnabled = SaveAllButtonsEnabled = SaveButtonsEnabled = false; + CompilingAndRunButtonsEnabled = CloseButtonsEnabled = SaveAllButtonsEnabled = SaveButtonsEnabled = false; if (DebuggerVisible) - SetDedugButtonsEnabled(false); - SetCompilingButtonsEnabled(false); + SetDebugButtonsEnabled(false); + SetCompilingAndRunButtonsEnabled(false); HelpFileName = PascalABCCompiler.Tools.ReplaceAllKeys(Constants.HelpFileName, WorkbenchStorage.StandartDirectories); DotNetHelpFileName = PascalABCCompiler.Tools.ReplaceAllKeys(Constants.DotNetHelpFileName, WorkbenchStorage.StandartDirectories); diff --git a/VisualPascalABCNETLinux/IB/CodeCompletion/CodeCompletionActions.cs b/VisualPascalABCNETLinux/IB/CodeCompletion/CodeCompletionActions.cs index 18828d15c..31e501e3e 100644 --- a/VisualPascalABCNETLinux/IB/CodeCompletion/CodeCompletionActions.cs +++ b/VisualPascalABCNETLinux/IB/CodeCompletion/CodeCompletionActions.cs @@ -20,7 +20,7 @@ namespace VisualPascalABC public static void Rename(TextArea textArea) { - if (CodeCompletion.CodeCompletionController.CurrentParser == null) return; + if (!CodeCompletion.CodeCompletionController.IntellisenseAvailable()) return; IDocument doc = textArea.Document; string textContent = doc.TextContent; ccp = new CodeCompletionProvider(); @@ -60,7 +60,7 @@ namespace VisualPascalABC public static void RenameUnit(string FileName, string new_val) { - if (CodeCompletion.CodeCompletionController.CurrentParser == null) return; + if (!CodeCompletion.CodeCompletionController.IntellisenseAvailable()) return; ccp = new CodeCompletionProvider(); IDocument doc = null; CodeCompletion.CodeCompletionController controller = new CodeCompletion.CodeCompletionController(); @@ -120,10 +120,7 @@ namespace VisualPascalABC public static List GetDefinitionPosition(TextArea textArea, bool only_check) { - IParser parser = CodeCompletion.CodeCompletionController.CurrentParser; - - if (parser == null) - return new List(); + if (!CodeCompletion.CodeCompletionController.IntellisenseAvailable()) return new List(); IDocument doc = textArea.Document; string textContent = doc.TextContent; @@ -136,7 +133,7 @@ namespace VisualPascalABC // Проверка, что компилируем Паскаль временно EVA 10.11.2024 - if (parser == Languages.Facade.LanguageProvider.Instance.SelectLanguageByName(StringConstants.pascalLanguageName).Parser) + if (CodeCompletion.CodeCompletionController.CurrentLanguage == Languages.Facade.LanguageProvider.Instance.MainLanguage) { if (expressionResult != full_expr && full_expr.StartsWith("(")) return new List(); @@ -157,7 +154,7 @@ namespace VisualPascalABC public static List GetRealizationPosition(TextArea textArea) { - if (CodeCompletion.CodeCompletionController.CurrentParser == null) return new List(); + if (!CodeCompletion.CodeCompletionController.IntellisenseAvailable()) return new List(); IDocument doc = textArea.Document; string textContent = doc.TextContent; ccp = new CodeCompletionProvider(); @@ -171,7 +168,7 @@ namespace VisualPascalABC public static List FindReferences(TextArea textArea) { - if (CodeCompletion.CodeCompletionController.CurrentParser == null) return new List(); + if (!CodeCompletion.CodeCompletionController.IntellisenseAvailable()) return new List(); ccp = new CodeCompletionProvider(); string full_expr; string expressionResult = FindFullExpression(textArea.Document.TextContent, textArea, out ccp.keyword, out full_expr); @@ -180,7 +177,7 @@ namespace VisualPascalABC public static void GotoRealization(TextArea textArea) { - if (CodeCompletion.CodeCompletionController.CurrentParser == null) return; + if (!CodeCompletion.CodeCompletionController.IntellisenseAvailable()) return; position = GetRealizationPosition(textArea); if (position == null || position.Count == 0) return; if (position.Count == 1) @@ -209,7 +206,7 @@ namespace VisualPascalABC public static bool CanGoTo(TextArea textArea) { - if (CodeCompletion.CodeCompletionController.CurrentParser == null) return false; + if (!CodeCompletion.CodeCompletionController.IntellisenseAvailable()) return false; List poses = GetDefinitionPosition(textArea, true); if (poses == null || poses.Count == 0) return false; foreach (Position pos in poses) @@ -222,7 +219,7 @@ namespace VisualPascalABC public static bool CanGoToRealization(TextArea textArea) { - if (CodeCompletion.CodeCompletionController.CurrentParser == null) return false; + if (!CodeCompletion.CodeCompletionController.IntellisenseAvailable()) return false; List poses = GetRealizationPosition(textArea); if (poses == null || poses.Count == 0) return false; foreach (Position pos in poses) @@ -237,7 +234,7 @@ namespace VisualPascalABC { try { - if (CodeCompletion.CodeCompletionController.CurrentParser == null) return false; + if (!CodeCompletion.CodeCompletionController.IntellisenseAvailable()) return false; ccp = new CodeCompletionProvider(); string full_expr; string expressionResult = FindFullExpression(textArea.Document.TextContent, textArea, out ccp.keyword, out full_expr); @@ -258,7 +255,7 @@ namespace VisualPascalABC { try { - if (CodeCompletion.CodeCompletionController.CurrentParser == null) return false; + if (!CodeCompletion.CodeCompletionController.IntellisenseAvailable()) return false; ccp = new CodeCompletionProvider(); Position pos = new Position(); //string text = "procedure Test(a : integer);\n begin \n x := 1; \n end;";//ccp.GetRealizationTextToAdd(out pos); @@ -275,7 +272,7 @@ namespace VisualPascalABC { try { - if (CodeCompletion.CodeCompletionController.CurrentParser == null) return; + if (!CodeCompletion.CodeCompletionController.IntellisenseAvailable()) return; ccp = new CodeCompletionProvider(); Position pos = new Position(); //string text = "procedure Test(a : integer);\n begin \n x := 1; \n end;";//ccp.GetRealizationTextToAdd(out pos); @@ -298,7 +295,7 @@ namespace VisualPascalABC private static TextArea _textArea; public static void GenerateOverridableMethods(TextArea textArea) { - if (CodeCompletion.CodeCompletionController.CurrentParser == null) return; + if (!CodeCompletion.CodeCompletionController.IntellisenseAvailable()) return; ccp = new CodeCompletionProvider(); _textArea = textArea; int off = textArea.Caret.Offset; @@ -328,7 +325,7 @@ namespace VisualPascalABC public static void GenerateClassOrMethodRealization(TextArea textArea) { - if (CodeCompletion.CodeCompletionController.CurrentParser == null) return; + if (!CodeCompletion.CodeCompletionController.IntellisenseAvailable()) return; ccp = new CodeCompletionProvider(); Position pos = new Position(); //string text = "procedure Test(a : integer);\n begin \n x := 1; \n end;";//ccp.GetRealizationTextToAdd(out pos); @@ -458,12 +455,12 @@ namespace VisualPascalABC public static bool GenerateCommentTemplate(TextArea textArea) { - if (CodeCompletion.CodeCompletionController.CurrentParser == null) return false; + if (!CodeCompletion.CodeCompletionController.IntellisenseAvailable()) return false; ccp = new CodeCompletionProvider(); //if (!should_insert_comment(textArea)) // return false; string lineText = get_next_line(textArea); - string addit = CodeCompletion.CodeCompletionController.CurrentParser.LanguageInformation.GetDocumentTemplate( + string addit = CodeCompletion.CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.GetDocumentTemplate( lineText, textArea.Document.TextContent, textArea.Caret.Line, textArea.Caret.Column, textArea.Caret.Offset); if (addit == null) return false; @@ -505,7 +502,7 @@ namespace VisualPascalABC public static void GotoDefinition(TextArea _textArea) { - if (CodeCompletion.CodeCompletionController.CurrentParser == null) return; + if (!CodeCompletion.CodeCompletionController.IntellisenseAvailable()) return; position = GetDefinitionPosition(_textArea, false); if (position == null) return; if (position.Count == 1) @@ -543,9 +540,9 @@ namespace VisualPascalABC keyw = PascalABCCompiler.Parsers.KeywordKind.None; string expr_without_brackets = null; full_expr = null; - if (CodeCompletion.CodeCompletionController.CurrentParser != null) + if (CodeCompletion.CodeCompletionController.IntellisenseAvailable()) { - full_expr = CodeCompletion.CodeCompletionController.CurrentParser.LanguageInformation.FindExpressionFromAnyPosition(_textArea.Caret.Offset, Text, _textArea.Caret.Line, _textArea.Caret.Column, out keyw, out expr_without_brackets); + full_expr = CodeCompletion.CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.FindExpressionFromAnyPosition(_textArea.Caret.Offset, Text, _textArea.Caret.Line, _textArea.Caret.Column, out keyw, out expr_without_brackets); return expr_without_brackets; } return null; @@ -553,7 +550,7 @@ namespace VisualPascalABC private static string FindOnlyIdent(string Text, TextArea _textArea, ref string name) { - return CodeCompletion.CodeCompletionController.CurrentParser.LanguageInformation.FindOnlyIdentifier(_textArea.Caret.Offset, Text, _textArea.Caret.Line, _textArea.Caret.Column, ref name); + return CodeCompletion.CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.FindOnlyIdentifier(_textArea.Caret.Offset, Text, _textArea.Caret.Line, _textArea.Caret.Column, ref name); } @@ -605,7 +602,7 @@ namespace VisualPascalABC { public override void Execute(TextArea textArea) { - if (WorkbenchServiceFactory.DebuggerManager.IsRunning) + if (WorkbenchServiceFactory.DebuggerManager.IsRunning || !CodeCompletion.CodeCompletionController.IntellisenseAvailable()) return; WorkbenchServiceFactory.Workbench.ErrorsListWindow.ClearErrorList(); VisualPABCSingleton.MainForm.CurrentCodeFileDocument.DeselectAll(); @@ -615,12 +612,14 @@ namespace VisualPascalABC // MainForm.VisualEnvironmentCompiler.Compiler.ParsersController.Compile( // file_name, TextEditor.Text, null, Errors, PascalABCCompiler.Parsers.ParseMode.Normal); string text = WorkbenchServiceFactory.Workbench.VisualEnvironmentCompiler.SourceFilesProvider(VisualPABCSingleton.MainForm.CurrentCodeFileDocument.FileName, PascalABCCompiler.SourceFileOperation.GetText) as string; + PascalABCCompiler.SyntaxTree.compilation_unit cu = - Languages.Facade.LanguageProvider.Instance.SelectLanguageByExtensionSafe(VisualPABCSingleton.MainForm.CurrentCodeFileDocument.FileName)?.Parser.GetCompilationUnitForFormatter( + CodeCompletion.CodeCompletionController.CurrentLanguage.Parser.GetCompilationUnitForFormatter( VisualPABCSingleton.MainForm.CurrentCodeFileDocument.FileName, text, //VisualPascalABC.Form1.Form1_object._currentCodeFileDocument.TextEditor.Text, Errors, new List()); + if (Errors.Count == 0) { string formattedText = cf.FormatTree(text, cu, textArea.Caret.Line + 1, textArea.Caret.Column + 1); @@ -682,7 +681,7 @@ namespace VisualPascalABC } if (!WorkbenchServiceFactory.Workbench.UserOptions.CodeCompletionDot) return; - if (CodeCompletion.CodeCompletionController.CurrentParser == null) return; + if (CodeCompletion.CodeCompletionController.CurrentLanguage == null) return; CodeCompletionProvider completionDataProvider = new CodeCompletionProvider(); bool is_pattern = false; @@ -690,7 +689,7 @@ namespace VisualPascalABC is_begin = true; - completionDataProvider.preSelection = CodeCompletion.CodeCompletionController.CurrentParser.LanguageInformation.FindPattern(off, text, out is_pattern); + completionDataProvider.preSelection = CodeCompletion.CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.FindPattern(off, text, out is_pattern); if (!is_pattern && off > 0 && text[off - 1] == '.') key = '_';//was '$' diff --git a/VisualPascalABCNETLinux/IB/CodeCompletion/CodeCompletionHelpers.cs b/VisualPascalABCNETLinux/IB/CodeCompletion/CodeCompletionHelpers.cs index 41c692b96..46de49bc4 100644 --- a/VisualPascalABCNETLinux/IB/CodeCompletion/CodeCompletionHelpers.cs +++ b/VisualPascalABCNETLinux/IB/CodeCompletion/CodeCompletionHelpers.cs @@ -54,8 +54,8 @@ namespace VisualPascalABC { public static PascalABCCompiler.Parsers.KeywordKind TestForKeyword(string Text, int i) { - if (CodeCompletion.CodeCompletionController.CurrentParser != null && CodeCompletion.CodeCompletionController.CurrentParser.LanguageInformation !=null) - return CodeCompletion.CodeCompletionController.CurrentParser.LanguageInformation.TestForKeyword(Text, i); + if (CodeCompletion.CodeCompletionController.IntellisenseAvailable()) + return CodeCompletion.CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.TestForKeyword(Text, i); return PascalABCCompiler.Parsers.KeywordKind.None; } diff --git a/VisualPascalABCNETLinux/IB/CodeCompletion/CodeCompletionKeyHandler.cs b/VisualPascalABCNETLinux/IB/CodeCompletion/CodeCompletionKeyHandler.cs index f4f761ca3..d24c2f388 100644 --- a/VisualPascalABCNETLinux/IB/CodeCompletion/CodeCompletionKeyHandler.cs +++ b/VisualPascalABCNETLinux/IB/CodeCompletion/CodeCompletionKeyHandler.cs @@ -64,7 +64,7 @@ namespace VisualPascalABC { if (!WorkbenchServiceFactory.Workbench.UserOptions.AllowCodeCompletion || !VisualPABCSingleton.MainForm.VisualEnvironmentCompiler.compilerLoaded) return false; - if (CodeCompletion.CodeCompletionController.CurrentParser == null) return false; + if (!CodeCompletion.CodeCompletionController.IntellisenseAvailable()) return false; if (codeCompletionWindow != null) { // If completion window is open and wants to handle the key, don't let the text area @@ -93,8 +93,6 @@ namespace VisualPascalABC } if (key == '.') { - if (CodeCompletion.CodeCompletionController.CurrentParser == null) - return false; if (!string.IsNullOrEmpty(WorkbenchServiceFactory.DocumentService.CurrentCodeFileDocument.TextEditor.ActiveTextAreaControl.SelectionManager.SelectedText)) { WorkbenchServiceFactory.DocumentService.CurrentCodeFileDocument.TextEditor.ActiveTextAreaControl.Caret.Position = WorkbenchServiceFactory.DocumentService.CurrentCodeFileDocument.TextEditor.ActiveTextAreaControl.SelectionManager.SelectionCollection[0].StartPosition; @@ -124,7 +122,6 @@ namespace VisualPascalABC } else if (key == '(' || key == '[' || key == ',') { - if (CodeCompletion.CodeCompletionController.CurrentParser == null) return false; if (VisualPABCSingleton.MainForm.UserOptions.CodeCompletionParams) { ICSharpCode.TextEditor.Gui.InsightWindow.IInsightDataProvider idp = new DefaultInsightDataProvider(-1, false, key); @@ -147,7 +144,6 @@ namespace VisualPascalABC } else if (key == ' ') { - if (CodeCompletion.CodeCompletionController.CurrentParser == null) return false; if (VisualPABCSingleton.MainForm.UserOptions.CodeCompletionDot) { PascalABCCompiler.Parsers.KeywordKind keyw = KeywordChecker.TestForKeyword(editor.Document.TextContent, editor.ActiveTextAreaControl.TextArea.Caret.Offset - 1); @@ -173,7 +169,7 @@ namespace VisualPascalABC } else if (key == '\n') { - if (VisualPABCSingleton.MainForm.UserOptions.AllowCodeCompletion && CodeCompletion.CodeCompletionController.CurrentParser != null) + if (VisualPABCSingleton.MainForm.UserOptions.AllowCodeCompletion) { try { @@ -194,9 +190,8 @@ namespace VisualPascalABC { if (VisualPABCSingleton.MainForm.UserOptions.CodeCompletionDot) { - if (CodeCompletion.CodeCompletionController.CurrentParser == null) return false; PascalABCCompiler.Parsers.KeywordKind keyw = KeywordChecker.TestForKeyword(editor.Document.TextContent, editor.ActiveTextAreaControl.TextArea.Caret.Offset - 1); - if (CodeCompletion.CodeCompletionController.CurrentParser.LanguageInformation.IsDefinitionIdentifierAfterKeyword(keyw)) + if (CodeCompletion.CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.IsDefinitionIdentifierAfterKeyword(keyw)) return false; // если не первый символ выражения (предыдущий тоже буква или "_"), то не открываем новое окно diff --git a/VisualPascalABCNETLinux/IB/CodeCompletion/CodeCompletionParserController.cs b/VisualPascalABCNETLinux/IB/CodeCompletion/CodeCompletionParserController.cs index adf43c72f..70e5db106 100644 --- a/VisualPascalABCNETLinux/IB/CodeCompletion/CodeCompletionParserController.cs +++ b/VisualPascalABCNETLinux/IB/CodeCompletion/CodeCompletionParserController.cs @@ -76,11 +76,7 @@ namespace VisualPascalABC public void RegisterFileForParsing(string FileName) { - if (Languages.Facade.LanguageProvider.Instance.HasLanguageForExtension(FileName)) - { - filesToParse[FileName] = true; - CodeCompletion.CodeCompletionController.SetLanguage(FileName); - } + filesToParse[FileName] = true; } public void CloseFile(string FileName) diff --git a/VisualPascalABCNETLinux/IB/CodeCompletion/CodeCompletionProvider.cs b/VisualPascalABCNETLinux/IB/CodeCompletion/CodeCompletionProvider.cs index cfd57fee1..fa06c7722 100644 --- a/VisualPascalABCNETLinux/IB/CodeCompletion/CodeCompletionProvider.cs +++ b/VisualPascalABCNETLinux/IB/CodeCompletion/CodeCompletionProvider.cs @@ -126,12 +126,12 @@ namespace VisualPascalABC private string construct_header(string meth, CodeCompletion.ProcScope ps, int tabCount) { //if (CodeCompletion.CodeCompletionController.currentParser != null) - return CodeCompletion.CodeCompletionController.CurrentParser.LanguageInformation.ConstructHeader(meth, ps, tabCount); + return CodeCompletion.CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.ConstructHeader(meth, ps, tabCount); } private string construct_header(CodeCompletion.ProcRealization ps, int tabCount) { - return CodeCompletion.CodeCompletionController.CurrentParser.LanguageInformation.ConstructHeader(ps, tabCount); + return CodeCompletion.CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.ConstructHeader(ps, tabCount); } public CodeCompletion.SymScope FindScopeByLocation(string fileName, int line, int col) @@ -295,8 +295,8 @@ namespace VisualPascalABC public string FindExpression(int off, string Text, int line, int col) { - if (CodeCompletion.CodeCompletionController.CurrentParser != null) - return CodeCompletion.CodeCompletionController.CurrentParser.LanguageInformation.FindExpression(off, Text, line, col, out keyword); + if (CodeCompletion.CodeCompletionController.IntellisenseAvailable()) + return CodeCompletion.CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.FindExpression(off, Text, line, col, out keyword); return null; } @@ -325,14 +325,14 @@ namespace VisualPascalABC try { - ILanguageInformation languageInformation = CodeCompletion.CodeCompletionController.CurrentParser.LanguageInformation; + ILanguage currentLanguage = CodeCompletion.CodeCompletionController.CurrentLanguage; List keywords; bool isTypeAfterKeyword = false; // если по смыслу должен вводиться тип данных - if (languageInformation.IsTypeAfterKeyword(keyw)) + if (currentLanguage.LanguageIntellisenseSupport.IsTypeAfterKeyword(keyw)) { keywords = CodeCompletion.CodeCompletionNameHelper.Helper.GetTypeKeywords(); isTypeAfterKeyword = true; @@ -345,7 +345,7 @@ namespace VisualPascalABC bool isNamespaceAfterKeyword = false; // конструкция типа "uses" - if (languageInformation.IsNamespaceAfterKeyword(keyw)) + if (currentLanguage.LanguageIntellisenseSupport.IsNamespaceAfterKeyword(keyw)) { isNamespaceAfterKeyword = true; } @@ -359,11 +359,9 @@ namespace VisualPascalABC if (symInfos != null) { - bool languageCaseSensitive = LanguageProvider.Instance.SelectLanguageByExtension(FileName).CaseSensitive; + currentLanguage.LanguageIntellisenseSupport.RenameOrExcludeSpecialNames(symInfos); - languageInformation.RenameOrExcludeSpecialNames(symInfos); - - AddCompletionDatasByFirstForSymInfos(resultList, charTyped, symInfos, languageCaseSensitive); + AddCompletionDatasByFirstForSymInfos(resultList, charTyped, symInfos, currentLanguage.CaseSensitive); //resultList.Sort(); //defaultCompletionElement = resultList[0] as DefaultCompletionData; @@ -507,7 +505,7 @@ namespace VisualPascalABC }; string expressionText = GetExpressionTextForCompletionData(off, text, line, col, - currentLanguage.LanguageInformation, in context, out var insidePatternWithDots, out var ctrlOrShiftSpaceAfterDot, out var pattern); + currentLanguage.LanguageIntellisenseSupport, in context, out var insidePatternWithDots, out var ctrlOrShiftSpaceAfterDot, out var pattern); // добавляем ключевые слова в случае "ctrl + space", нажатых в "пустом" месте if (!ctrlOrShiftSpaceAfterDot && context.ctrlSpace && string.IsNullOrEmpty(pattern)) @@ -538,7 +536,7 @@ namespace VisualPascalABC if (symInfos != null) { - currentLanguage.LanguageInformation.RenameOrExcludeSpecialNames(symInfos); + currentLanguage.LanguageIntellisenseSupport.RenameOrExcludeSpecialNames(symInfos); AddCompletionDatasForSymInfos(resultList, currentLanguage.CaseSensitive, symInfos, selectedSymInfo, lastUsedMember); } @@ -690,7 +688,7 @@ namespace VisualPascalABC /// /// Получение текста выражения, введенного пользователем перед нажатием "триггерной" клавиши /// - private string GetExpressionTextForCompletionData(int off, string text, int line, int col, ILanguageInformation languageInformation, in ActionContext context, out bool insidePatternWithDots, out bool ctrlOrShiftSpaceAfterDot, out string pattern) + private string GetExpressionTextForCompletionData(int off, string text, int line, int col, ILanguageIntellisenseSupport languageInformation, in ActionContext context, out bool insidePatternWithDots, out bool ctrlOrShiftSpaceAfterDot, out string pattern) { string expressionText = null; diff --git a/VisualPascalABCNETLinux/IB/CodeCompletion/DefinitionByMouseClickManager.cs b/VisualPascalABCNETLinux/IB/CodeCompletion/DefinitionByMouseClickManager.cs index 284a907e1..db7cc036b 100644 --- a/VisualPascalABCNETLinux/IB/CodeCompletion/DefinitionByMouseClickManager.cs +++ b/VisualPascalABCNETLinux/IB/CodeCompletion/DefinitionByMouseClickManager.cs @@ -19,11 +19,17 @@ namespace VisualPascalABC public static void DefinitionByMouseClickManager_TextAreaMouseMove(object sender, MouseEventArgs e) { + if (!CodeCompletion.CodeCompletionController.IntellisenseAvailable()) + return; + makeWordUnderline(sender, e); } public static void DefinitionByMouseClickManager_TextAreaMouseDown(object sender, EventArgs e) { + if (!CodeCompletion.CodeCompletionController.IntellisenseAvailable()) + return; + TextArea textArea = (TextArea)sender; if (Control.ModifierKeys == Keys.Control && textArea.SelectionManager.SelectionCollection.Count == 0) { diff --git a/VisualPascalABCNETLinux/IB/CodeCompletion/InsightProvider.cs b/VisualPascalABCNETLinux/IB/CodeCompletion/InsightProvider.cs index fbcd8fa67..ce5f3c601 100644 --- a/VisualPascalABCNETLinux/IB/CodeCompletion/InsightProvider.cs +++ b/VisualPascalABCNETLinux/IB/CodeCompletion/InsightProvider.cs @@ -31,8 +31,8 @@ namespace VisualPascalABC private string FindExpression(int off, string Text, int line, int col) { - if (CodeCompletion.CodeCompletionController.CurrentParser != null) - return CodeCompletion.CodeCompletionController.CurrentParser.LanguageInformation.FindExpressionForMethod(off, Text, line, col, pressed_key, ref num_param); + if (CodeCompletion.CodeCompletionController.IntellisenseAvailable()) + return CodeCompletion.CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.FindExpressionForMethod(off, Text, line, col, pressed_key, ref num_param); return null; } @@ -42,7 +42,7 @@ namespace VisualPascalABC { if (setupOnlyOnce && this.textArea != null) { - if (CodeCompletion.CodeCompletionController.CurrentParser.LanguageInformation.IsMethodCallParameterSeparator(pressed_key)) + if (CodeCompletion.CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.IsMethodCallParameterSeparator(pressed_key)) { FindExpression(textArea.Caret.Offset, textArea.Document.TextContent.Substring(0, textArea.Caret.Offset), textArea.Caret.Line, textArea.Caret.Column); @@ -71,9 +71,9 @@ namespace VisualPascalABC if (dconv != null) { //if (pressed_key == '(' || pressed_key == ',') - if (CodeCompletion.CodeCompletionController.CurrentParser.LanguageInformation.IsOpenBracketForMethodCall(pressed_key) || CodeCompletion.CodeCompletionController.CurrentParser.LanguageInformation.IsMethodCallParameterSeparator(pressed_key)) + if (CodeCompletion.CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.IsOpenBracketForMethodCall(pressed_key) || CodeCompletion.CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.IsMethodCallParameterSeparator(pressed_key)) methods = dconv.GetNameOfMethod(e, expr, line, col, num_param, ref defaultIndex, cur_param_num, out param_count); - else if (CodeCompletion.CodeCompletionController.CurrentParser.LanguageInformation.IsOpenBracketForIndex(pressed_key)) + else if (CodeCompletion.CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport.IsOpenBracketForIndex(pressed_key)) methods = dconv.GetIndex(e, line, col); } } diff --git a/VisualPascalABCNETLinux/IB/CodeCompletion/TooltipServiceManager.cs b/VisualPascalABCNETLinux/IB/CodeCompletion/TooltipServiceManager.cs index c34b39199..d855c5de2 100644 --- a/VisualPascalABCNETLinux/IB/CodeCompletion/TooltipServiceManager.cs +++ b/VisualPascalABCNETLinux/IB/CodeCompletion/TooltipServiceManager.cs @@ -8,7 +8,6 @@ using System.Windows.Forms; using ICSharpCode.TextEditor; using ICSharpCode.TextEditor.Document; using ICSharpCode.TextEditor.Gui.CompletionWindow; -using PascalABCCompiler.Parsers; namespace VisualPascalABC { @@ -29,9 +28,9 @@ namespace VisualPascalABC //string expr = FindFullExpression(doc.TextContent, seg.Offset + logicPos.X,e.LogicalPosition.Line,e.LogicalPosition.Column); - IParser parser = CodeCompletion.CodeCompletionController.CurrentParser; + var currentLanguage = CodeCompletion.CodeCompletionController.CurrentLanguage; - string expr = parser.LanguageInformation.FindExpressionFromAnyPosition( + string expr = currentLanguage.LanguageIntellisenseSupport.FindExpressionFromAnyPosition( lineSegment.Offset + logicPos.X, doc.TextContent, e.LogicalPosition.Line, e.LogicalPosition.Column, out var keyw, out var exprWithoutBrackets); // пока непонятно, когда такое может быть EVA @@ -44,25 +43,25 @@ namespace VisualPascalABC List Errors = new List(); List Warnings = new List(); - PascalABCCompiler.SyntaxTree.expression expressionTree = parser.GetExpression("test" + Path.GetExtension(fileName), + PascalABCCompiler.SyntaxTree.expression expressionTree = currentLanguage.Parser.GetExpression("test" + Path.GetExtension(fileName), expr, Errors, Warnings); // Пока добавили проверку, что анализируем Паскаль EVA - if (Errors.Count > 0 && parser == Languages.Facade.LanguageProvider.Instance.MainLanguage.Parser) + if (Errors.Count > 0 && currentLanguage == Languages.Facade.LanguageProvider.Instance.MainLanguage) { string s = expr.TrimStart(); if (s.Length > 0 && s[0] == '^') { Errors.Clear(); exprWithoutBrackets = exprWithoutBrackets.TrimStart().Substring(1); - expressionTree = parser.GetExpression("test" + Path.GetExtension(fileName), s.Substring(1), Errors, Warnings); + expressionTree = currentLanguage.Parser.GetExpression("test" + Path.GetExtension(fileName), s.Substring(1), Errors, Warnings); } } List Errors2 = new List(); // проверка для выражения без скобок - PascalABCCompiler.SyntaxTree.expression expressionTree2 = parser.GetExpression("test" + Path.GetExtension(fileName), exprWithoutBrackets, Errors2, Warnings); + PascalABCCompiler.SyntaxTree.expression expressionTree2 = currentLanguage.Parser.GetExpression("test" + Path.GetExtension(fileName), exprWithoutBrackets, Errors2, Warnings); // если не получается, то сразу возврат if (expressionTree2 == null || Errors2.Count > 0) @@ -123,7 +122,7 @@ namespace VisualPascalABC { if (!VisualPABCSingleton.MainForm.UserOptions.CodeCompletionHint) return; - if (CodeCompletion.CodeCompletionController.CurrentParser == null) + if (!CodeCompletion.CodeCompletionController.IntellisenseAvailable()) return; try { diff --git a/VisualPascalABCNETLinux/IB/Debugger/Debugger.cs b/VisualPascalABCNETLinux/IB/Debugger/Debugger.cs index 5d43d2416..b0cc40b6d 100644 --- a/VisualPascalABCNETLinux/IB/Debugger/Debugger.cs +++ b/VisualPascalABCNETLinux/IB/Debugger/Debugger.cs @@ -315,7 +315,7 @@ namespace VisualPascalABC public bool IsRunning = false; public string ExeFileName; public bool ShowDebugTabs=true; - public PascalABCCompiler.Parsers.IParser parser = null; + public Languages.Facade.ILanguage language = null; EventHandler debuggerStateEvent; private Mono.Debugging.Soft.SoftDebuggerSession monoDebuggerSession; private Mono.Debugging.Client.StackFrame stackFrame; @@ -485,7 +485,7 @@ namespace VisualPascalABC this.FullFileName = Path.Combine(Path.GetDirectoryName(fileName), this.FileName); this.ExeFileName = fileName; CurrentLine = 0; - this.parser = Languages.Facade.LanguageProvider.Instance.SelectLanguageByExtensionSafe(FullFileName)?.Parser; + this.language = Languages.Facade.LanguageProvider.Instance.SelectLanguageByExtension(FullFileName); this.PrevFullFileName = FullFileName; AssemblyHelper.LoadAssembly(fileName); //dbg.ProcessStarted += debugProcessStarted; @@ -509,7 +509,7 @@ namespace VisualPascalABC this.FullFileName = Path.Combine(Path.GetDirectoryName(fileName), this.FileName); this.ExeFileName = fileName; CurrentLine = 0; - this.parser = Languages.Facade.LanguageProvider.Instance.SelectLanguageByExtensionSafe(FullFileName)?.Parser; + this.language = Languages.Facade.LanguageProvider.Instance.SelectLanguageByExtension(FullFileName); this.PrevFullFileName = FullFileName; AssemblyHelper.LoadAssembly(fileName); @@ -541,7 +541,7 @@ namespace VisualPascalABC workbench.WidgetController.SetDebugTabsVisible(true); workbench.WidgetController.SetPlayButtonsVisible(true); workbench.WidgetController.SetDebugStopEnabled();//e.Process.LogMessage += messageEventProc; - workbench.WidgetController.SetStartDebugDisabled(); + workbench.WidgetController.SetStartDebugAndRunDisabled(); workbench.WidgetController.ChangeStartDebugNameOnContinue(); workbench.WidgetController.EnableCodeCompletionToolTips(false); workbench.WidgetController.SetAddExprMenuVisible(true); @@ -597,7 +597,7 @@ namespace VisualPascalABC workbench.ServiceContainer.EditorService.SetEditorDisabled(false); //RemoveMarker(frm.CurrentCodeFileDocument.TextEditor.ActiveTextAreaControl.Document); evaluator = null; - parser = null; + language = null; FileName = null; handle = 0; ExeFileName = null; @@ -642,7 +642,7 @@ namespace VisualPascalABC if (evaluator != null) evaluator.SetCurrentMonoFrame(monoDebuggerSession, stackFrame); JumpToCurrentLine(); - workbench.WidgetController.SetStartDebugEnabled(); + workbench.WidgetController.SetStartDebugAndRunEnabled(); WorkbenchServiceFactory.DebuggerOperationsService.RefreshPad(new FunctionItem(stackFrame).SubItems); } @@ -662,7 +662,7 @@ namespace VisualPascalABC if (evaluator != null) evaluator.SetCurrentMonoFrame(monoDebuggerSession, stackFrame); JumpToCurrentLine(); - workbench.WidgetController.SetStartDebugEnabled(); + workbench.WidgetController.SetStartDebugAndRunEnabled(); } Function currentFunction; @@ -785,7 +785,7 @@ namespace VisualPascalABC private void debuggedProcess_Expired(object sender, EventArgs e) { - workbench.WidgetController.SetStartDebugEnabled(); + workbench.WidgetController.SetStartDebugAndRunEnabled(); } private void debuggedProcess_ExceptionThrown(object sender, ExceptionEventArgs e) @@ -850,7 +850,7 @@ namespace VisualPascalABC workbench.ServiceContainer.EditorService.SetEditorDisabled(false); //RemoveMarker(frm.CurrentCodeFileDocument.TextEditor.ActiveTextAreaControl.Document); evaluator = null; - parser= null; + language= null; FileName = null; handle = 0; ExeFileName = null; @@ -894,7 +894,7 @@ namespace VisualPascalABC workbench.WidgetController.SetDebugTabsVisible(true); workbench.WidgetController.SetPlayButtonsVisible(true); workbench.WidgetController.SetDebugStopEnabled();//e.Process.LogMessage += messageEventProc; - workbench.WidgetController.SetStartDebugDisabled(); + workbench.WidgetController.SetStartDebugAndRunDisabled(); workbench.WidgetController.ChangeStartDebugNameOnContinue(); workbench.WidgetController.EnableCodeCompletionToolTips(false); workbench.WidgetController.SetAddExprMenuVisible(true); @@ -1466,7 +1466,7 @@ namespace VisualPascalABC { sb.Insert(0, '.'); PascalABCCompiler.Parsers.KeywordKind keyw = PascalABCCompiler.Parsers.KeywordKind.None; - string s = CodeCompletion.CodeCompletionController.CurrentParser.LanguageInformation. + string s = CodeCompletion.CodeCompletionController.CurrentLanguage.LanguageIntellisenseSupport. FindExpression(i, text, 0, 0, out keyw); if (s != null) { @@ -2011,7 +2011,7 @@ namespace VisualPascalABC { try { - workbench.WidgetController.SetStartDebugEnabled(); + workbench.WidgetController.SetStartDebugAndRunEnabled(); dbg.Processes[0].Terminate(); } catch (System.Exception e) @@ -2027,7 +2027,7 @@ namespace VisualPascalABC { try { - workbench.WidgetController.SetStartDebugEnabled(); + workbench.WidgetController.SetStartDebugAndRunEnabled(); dbg.Processes[0].Break(); } catch (System.Exception e) @@ -2093,7 +2093,7 @@ namespace VisualPascalABC { try { - workbench.WidgetController.SetStartDebugDisabled(); + workbench.WidgetController.SetStartDebugAndRunDisabled(); CurrentLineBookmark.Remove(); monoDebuggerSession.NextLine(); @@ -2114,7 +2114,7 @@ namespace VisualPascalABC { try { - workbench.WidgetController.SetStartDebugDisabled(); + workbench.WidgetController.SetStartDebugAndRunDisabled(); monoDebuggerSession.Continue(); CurrentLineBookmark.Remove(); } @@ -2134,7 +2134,7 @@ namespace VisualPascalABC { try { - workbench.WidgetController.SetStartDebugDisabled(); + workbench.WidgetController.SetStartDebugAndRunDisabled(); stepin_stmt = monoDebuggerSession.ActiveThread.Backtrace.GetFrame(0).SourceLocation; monoDebuggerSession.StepLine(); CurrentLineBookmark.Remove(); @@ -2157,7 +2157,7 @@ namespace VisualPascalABC { if (IsRunning) { - workbench.WidgetController.SetStartDebugDisabled(); + workbench.WidgetController.SetStartDebugAndRunDisabled(); monoDebuggerSession.StepOut(); CurrentLineBookmark.Remove(); } @@ -2177,7 +2177,7 @@ namespace VisualPascalABC { //cur_brpt = dbg.AddBreakpoint(new SourcecodeSegment((frm.CurrentTabPage.ag as CodeFileDocumentControl).file_name,(frm.CurrentTabPage.ag as CodeFileDocumentControl).TextEditor.ActiveTextAreaControl.Caret.Line + 1,(frm.CurrentTabPage.Tag as CodeFileDocumentControl).TextEditor.ActiveTextAreaControl.Caret.Column + 1, // (frm.CurrentTabPage.ag as CodeFileDocumentControl).TextEditor.ActiveTextAreaControl.Caret.Column+100), true); - workbench.WidgetController.SetStartDebugDisabled(); + workbench.WidgetController.SetStartDebugAndRunDisabled(); currentBreakpoint = monoDebuggerSession.Breakpoints.Add(WorkbenchServiceFactory.DocumentService.CurrentCodeFileDocument.FileName, WorkbenchServiceFactory.DocumentService.CurrentCodeFileDocument.TextEditor.ActiveTextAreaControl.Caret.Line + 1); AddGoToBreakPoint(currentBreakpoint); Status = DebugStatus.None; diff --git a/VisualPascalABCNETLinux/IB/Debugger/Utility.cs b/VisualPascalABCNETLinux/IB/Debugger/Utility.cs index 025c63c33..4435847b8 100644 --- a/VisualPascalABCNETLinux/IB/Debugger/Utility.cs +++ b/VisualPascalABCNETLinux/IB/Debugger/Utility.cs @@ -132,8 +132,8 @@ namespace VisualPascalABC public static string WrapTypeName(DebugType type) { if (type.IsArray) - if (WorkbenchServiceFactory.DebuggerManager.parser != null) - return WorkbenchServiceFactory.DebuggerManager.parser.LanguageInformation.GetArrayDescription(WrapTypeName(type.GetElementType()), type.GetArrayRank()); + if (WorkbenchServiceFactory.DebuggerManager.language != null) + return WorkbenchServiceFactory.DebuggerManager.language.LanguageIntellisenseSupport.GetArrayDescription(WrapTypeName(type.GetElementType()), type.GetArrayRank()); else return "array of " + WrapTypeName(type.GetElementType()); return internalWrapTypeName(type.FullName); @@ -192,23 +192,23 @@ namespace VisualPascalABC private static string internalWrapTypeName(string name) { - if (WorkbenchServiceFactory.DebuggerManager.parser != null) + if (WorkbenchServiceFactory.DebuggerManager.language != null) switch (name) { - case "System.Boolean": return WorkbenchServiceFactory.DebuggerManager.parser.LanguageInformation.GetShortTypeName(typeof(bool)); - case "System.Int32": return WorkbenchServiceFactory.DebuggerManager.parser.LanguageInformation.GetShortTypeName(typeof(int)); - case "System.Byte": return WorkbenchServiceFactory.DebuggerManager.parser.LanguageInformation.GetShortTypeName(typeof(byte)); - case "System.Double": return WorkbenchServiceFactory.DebuggerManager.parser.LanguageInformation.GetShortTypeName(typeof(double)); - case "System.String": return WorkbenchServiceFactory.DebuggerManager.parser.LanguageInformation.GetShortTypeName(typeof(string)); - case "System.Char": return WorkbenchServiceFactory.DebuggerManager.parser.LanguageInformation.GetShortTypeName(typeof(char)); - case "System.SByte": return WorkbenchServiceFactory.DebuggerManager.parser.LanguageInformation.GetShortTypeName(typeof(sbyte)); - case "System.Int16": return WorkbenchServiceFactory.DebuggerManager.parser.LanguageInformation.GetShortTypeName(typeof(short)); - case "System.UInt16": return WorkbenchServiceFactory.DebuggerManager.parser.LanguageInformation.GetShortTypeName(typeof(ushort)); - case "System.UInt32": return WorkbenchServiceFactory.DebuggerManager.parser.LanguageInformation.GetShortTypeName(typeof(uint)); - case "System.Int64": return WorkbenchServiceFactory.DebuggerManager.parser.LanguageInformation.GetShortTypeName(typeof(long)); - case "System.UInt64": return WorkbenchServiceFactory.DebuggerManager.parser.LanguageInformation.GetShortTypeName(typeof(ulong)); - case "System.Float32": return WorkbenchServiceFactory.DebuggerManager.parser.LanguageInformation.GetShortTypeName(typeof(float)); - case "System.IntPtr": return WorkbenchServiceFactory.DebuggerManager.parser.LanguageInformation.GetShortTypeName(Type.GetType("System.Void*")); + case "System.Boolean": return WorkbenchServiceFactory.DebuggerManager.language.LanguageIntellisenseSupport.GetShortTypeName(typeof(bool)); + case "System.Int32": return WorkbenchServiceFactory.DebuggerManager.language.LanguageIntellisenseSupport.GetShortTypeName(typeof(int)); + case "System.Byte": return WorkbenchServiceFactory.DebuggerManager.language.LanguageIntellisenseSupport.GetShortTypeName(typeof(byte)); + case "System.Double": return WorkbenchServiceFactory.DebuggerManager.language.LanguageIntellisenseSupport.GetShortTypeName(typeof(double)); + case "System.String": return WorkbenchServiceFactory.DebuggerManager.language.LanguageIntellisenseSupport.GetShortTypeName(typeof(string)); + case "System.Char": return WorkbenchServiceFactory.DebuggerManager.language.LanguageIntellisenseSupport.GetShortTypeName(typeof(char)); + case "System.SByte": return WorkbenchServiceFactory.DebuggerManager.language.LanguageIntellisenseSupport.GetShortTypeName(typeof(sbyte)); + case "System.Int16": return WorkbenchServiceFactory.DebuggerManager.language.LanguageIntellisenseSupport.GetShortTypeName(typeof(short)); + case "System.UInt16": return WorkbenchServiceFactory.DebuggerManager.language.LanguageIntellisenseSupport.GetShortTypeName(typeof(ushort)); + case "System.UInt32": return WorkbenchServiceFactory.DebuggerManager.language.LanguageIntellisenseSupport.GetShortTypeName(typeof(uint)); + case "System.Int64": return WorkbenchServiceFactory.DebuggerManager.language.LanguageIntellisenseSupport.GetShortTypeName(typeof(long)); + case "System.UInt64": return WorkbenchServiceFactory.DebuggerManager.language.LanguageIntellisenseSupport.GetShortTypeName(typeof(ulong)); + case "System.Float32": return WorkbenchServiceFactory.DebuggerManager.language.LanguageIntellisenseSupport.GetShortTypeName(typeof(float)); + case "System.IntPtr": return WorkbenchServiceFactory.DebuggerManager.language.LanguageIntellisenseSupport.GetShortTypeName(Type.GetType("System.Void*")); default: return name; } else diff --git a/VisualPascalABCNETLinux/IB/FormExtensions.cs b/VisualPascalABCNETLinux/IB/FormExtensions.cs index a309413dd..70c59a447 100644 --- a/VisualPascalABCNETLinux/IB/FormExtensions.cs +++ b/VisualPascalABCNETLinux/IB/FormExtensions.cs @@ -462,7 +462,7 @@ namespace VisualPascalABC void tsIntellisense_DropDownOpened(object sender, EventArgs e) { - if (UserOptions.AllowCodeCompletion) + if (UserOptions.AllowCodeCompletion && CodeCompletion.CodeCompletionController.IntellisenseAvailable()) { //GotoAction ga = new GotoAction(); TextArea ta = CurrentCodeFileDocument.TextEditor.ActiveTextAreaControl.TextArea; @@ -470,21 +470,50 @@ namespace VisualPascalABC this.tsGotoRealization.Enabled = CodeCompletionActionsManager.CanGoToRealization(ta); this.tsFindAllReferences.Enabled = CodeCompletionActionsManager.CanFindReferences(ta); //this.cmFindAllReferences.Enabled = ga.CanFindReferences(ta); - this.miGenerateRealization.Enabled = CodeCompletionActionsManager.CanGenerateRealization(ta); + this.miGenerateRealization.Enabled = CodeCompletionActionsManager.CanGenerateRealization(ta); + } + else + { + DisableIntellisenseDropDownOptions(); } } private void OpeningContextMenu(object sender, CancelEventArgs args) { - GotoAction ga = new GotoAction(); - TextArea ta = CurrentCodeFileDocument.TextEditor.ActiveTextAreaControl.TextArea; - this.cmGotoDefinition.Enabled = CodeCompletionActionsManager.CanGoTo(ta); - this.cmGotoRealization.Enabled = CodeCompletionActionsManager.CanGoToRealization(ta); - this.cmFindAllReferences.Enabled = CodeCompletionActionsManager.CanFindReferences(ta); - this.cmGenerateRealization.Enabled = CodeCompletionActionsManager.CanGenerateRealization(ta); - this.cmRename.Enabled = CodeCompletionActionsManager.CanGoTo(ta); - } - + if (CodeCompletion.CodeCompletionController.IntellisenseAvailable()) + { + // GotoAction ga = new GotoAction(); + TextArea ta = CurrentCodeFileDocument.TextEditor.ActiveTextAreaControl.TextArea; + + this.cmGotoDefinition.Enabled = CodeCompletionActionsManager.CanGoTo(ta); + this.cmGotoRealization.Enabled = CodeCompletionActionsManager.CanGoToRealization(ta); + this.cmFindAllReferences.Enabled = CodeCompletionActionsManager.CanFindReferences(ta); + this.cmGenerateRealization.Enabled = CodeCompletionActionsManager.CanGenerateRealization(ta); + this.cmRename.Enabled = CodeCompletionActionsManager.CanGoTo(ta); + } + else + { + DisableIntellisenseContextMenuOptions(); + } + } + + private void DisableIntellisenseContextMenuOptions() + { + this.cmGotoDefinition.Enabled = false; + this.cmGotoRealization.Enabled = false; + this.cmFindAllReferences.Enabled = false; + this.cmGenerateRealization.Enabled = false; + this.cmRename.Enabled = false; + } + + private void DisableIntellisenseDropDownOptions() + { + this.tsGotoDefinition.Enabled = false; + this.tsGotoRealization.Enabled = false; + this.tsFindAllReferences.Enabled = false; + this.miGenerateRealization.Enabled = false; + } + private void ClosingContextMenu(object sender, CancelEventArgs args) { this.cmRename.Enabled = true; diff --git a/VisualPascalABCNETLinux/Projects/ProjectTasks.cs b/VisualPascalABCNETLinux/Projects/ProjectTasks.cs index 21769657b..1e322bacf 100644 --- a/VisualPascalABCNETLinux/Projects/ProjectTasks.cs +++ b/VisualPascalABCNETLinux/Projects/ProjectTasks.cs @@ -99,11 +99,11 @@ namespace VisualPascalABC string full_file_name = Path.Combine(Path.GetDirectoryName(ProjectFactory.Instance.CurrentProject.Path),frm.FileName); StreamWriter sw = File.CreateText(full_file_name); - ILanguageInformation languageInfo = Languages.Facade.LanguageProvider.Instance.SelectLanguageByExtension(frm.FileName).LanguageInformation; + var languageIntellisenseSupport = Languages.Facade.LanguageProvider.Instance.SelectLanguageByExtension(frm.FileName).LanguageIntellisenseSupport; if (frm.GetFileFilter() == FileType.Unit) { - sw.Write(languageInfo.GetUnitTemplate(Path.GetFileNameWithoutExtension(frm.FileName))); + sw.Write(languageIntellisenseSupport.GetUnitTemplate(Path.GetFileNameWithoutExtension(frm.FileName))); } else { diff --git a/VisualPascalABCNETLinux/Workbench/BuildService.cs b/VisualPascalABCNETLinux/Workbench/BuildService.cs index 3bb72c13d..df44451df 100644 --- a/VisualPascalABCNETLinux/Workbench/BuildService.cs +++ b/VisualPascalABCNETLinux/Workbench/BuildService.cs @@ -53,7 +53,7 @@ namespace VisualPascalABC public string Compile(PascalABCCompiler.IProjectInfo project, bool rebuild, string RuntimeServicesModule, bool ForRun, bool RunWithEnvironment) { ProjectService.SaveProject(); - Workbench.WidgetController.CompilingButtonsEnabled = false; + Workbench.WidgetController.CompilingAndRunButtonsEnabled = false; Workbench.CompilerConsoleWindow.ClearConsole(); CompilerOptions1.SourceFileName = project.Path; CompilerOptions1.OutputDirectory = project.OutputDirectory; @@ -98,7 +98,7 @@ namespace VisualPascalABC public string Compile(string FileName, bool rebuild, string RuntimeServicesModule, bool ForRun, bool RunWithEnvironment) { - Workbench.WidgetController.CompilingButtonsEnabled = false; + Workbench.WidgetController.CompilingAndRunButtonsEnabled = false; var UserOptions = Workbench.UserOptions; diff --git a/VisualPascalABCNETLinux/Workbench/FileOperations.cs b/VisualPascalABCNETLinux/Workbench/FileOperations.cs index 2d606b7da..40534883a 100644 --- a/VisualPascalABCNETLinux/Workbench/FileOperations.cs +++ b/VisualPascalABCNETLinux/Workbench/FileOperations.cs @@ -94,7 +94,8 @@ namespace VisualPascalABC } //CloseButtonsEnabled = OpenDocuments.Count > 1; ChangedSelectedTab(); - if (FileName != null) // SS 09.08.08 + if (FileName != null // SS 09.08.08 + && CodeCompletion.CodeCompletionController.IntellisenseAvailable()) WorkbenchServiceFactory.CodeCompletionParserController.RegisterFileForParsing(FileName); } diff --git a/VisualPascalABCNETLinux/Workbench/HelpService.cs b/VisualPascalABCNETLinux/Workbench/HelpService.cs index 0ff404c19..80d396f85 100644 --- a/VisualPascalABCNETLinux/Workbench/HelpService.cs +++ b/VisualPascalABCNETLinux/Workbench/HelpService.cs @@ -95,7 +95,7 @@ namespace VisualPascalABC case "string": return false; } - if (CodeCompletion.CodeCompletionController.CurrentParser == null) return false; + if (!CodeCompletion.CodeCompletionController.IntellisenseAvailable()) return false; List poses = CodeCompletionActionsManager.GetDefinitionPosition(CurrentSyntaxEditor.TextEditor.ActiveTextAreaControl.TextArea, true); if (poses == null || poses.Count == 0) return false; foreach (Position pos in poses) diff --git a/VisualPascalABCNETLinux/Workbench/RunService.cs b/VisualPascalABCNETLinux/Workbench/RunService.cs index f76d4414d..b78f3e45f 100644 --- a/VisualPascalABCNETLinux/Workbench/RunService.cs +++ b/VisualPascalABCNETLinux/Workbench/RunService.cs @@ -108,7 +108,7 @@ namespace VisualPascalABC if (ProjectFactory.Instance.ProjectLoaded) tabPage = DocumentService.GetTabPageForMainFile(); if (attachdbg && !Workbench.UserOptions.AlwaysAttachDebuggerAtStart) - fictive_attach = !startWithGoto && !needFirstBreakpoint && !DebuggerManager.HasBreakpoints(); + fictive_attach = !startWithGoto && !needFirstBreakpoint && !DebuggerManager.HasBreakpoints() || !CodeCompletion.CodeCompletionController.IntellisenseAvailable(); WorkbenchServiceFactory.OperationsService.ClearOutputTextBoxForTabPage(tabPage); Workbench.ErrorsListWindow.ClearErrorList(); //DesignerService.GenerateAllDesignersCode(); diff --git a/VisualPascalABCNETLinux/Workbench/RunnerManagerHandlers.cs b/VisualPascalABCNETLinux/Workbench/RunnerManagerHandlers.cs index f647c4cb6..72b160c38 100644 --- a/VisualPascalABCNETLinux/Workbench/RunnerManagerHandlers.cs +++ b/VisualPascalABCNETLinux/Workbench/RunnerManagerHandlers.cs @@ -27,7 +27,7 @@ namespace VisualPascalABC void ButtonsEnableDisable_RunStart() { Workbench.WidgetController.SetStopEnabled(true); - Workbench.WidgetController.SetCompilingButtonsEnabled(false); + Workbench.WidgetController.SetCompilingAndRunButtonsEnabled(false); Workbench.WidgetController.SetDebugButtonsEnabled(false); Workbench.WidgetController.SetOptionsEnabled(false); } @@ -35,8 +35,9 @@ namespace VisualPascalABC void ButtonsEnableDisable_RunStop() { Workbench.WidgetController.SetStopEnabled(false); - Workbench.WidgetController.SetCompilingButtonsEnabled(true); - Workbench.WidgetController.SetDebugButtonsEnabled(true); + Workbench.WidgetController.SetCompilingAndRunButtonsEnabled(true); + if (CodeCompletion.CodeCompletionController.IntellisenseAvailable()) + Workbench.WidgetController.SetDebugButtonsEnabled(true); Workbench.WidgetController.SetOptionsEnabled(true); } diff --git a/VisualPascalABCNETLinux/Workbench/VisibilityService.cs b/VisualPascalABCNETLinux/Workbench/VisibilityService.cs index 5a716d6be..ba83a1af9 100644 --- a/VisualPascalABCNETLinux/Workbench/VisibilityService.cs +++ b/VisualPascalABCNETLinux/Workbench/VisibilityService.cs @@ -22,10 +22,10 @@ namespace VisualPascalABC internal List BottomDockContent = new List(); List VisibleBottomContent = new List(); - public bool CompilingButtonsEnabled + public bool CompilingAndRunButtonsEnabled { get { return miRun.Enabled; } - set { SetCompilingButtonsEnabled(value); } + set { SetCompilingAndRunButtonsEnabled(value); } } bool SaveButtonsEnabled @@ -100,18 +100,18 @@ namespace VisualPascalABC set { miNavigForw.Enabled = tsNavigForw.Enabled = value; } } - public void SetDedugButtonsEnabled(bool Enabled) + /// + /// Активировать/Деактивировать все кнопки, относящиеся к дебагу. + /// + public void SetDebugButtonsEnabled(bool Enabled) { - if (!DebuggerVisible) - return; - StepIntoButton.Enabled = StepOverButton.Enabled = StartDebugButton.Enabled = - mDEBUGSTARTToolStripMenuItem.Enabled = mSTEPOVERToolStripMenuItem.Enabled = mSTEPINToolStripMenuItem.Enabled = mRUNTOCURToolStripMenuItem.Enabled = Enabled; - + mDEBUGSTARTToolStripMenuItem.Enabled = mSTEPOVERToolStripMenuItem.Enabled = + mSTEPINToolStripMenuItem.Enabled = mRUNTOCURToolStripMenuItem.Enabled = Enabled; //toolStrip1.Refresh(); } - + bool BottomDockContentVisible { @@ -322,7 +322,7 @@ namespace VisualPascalABC } } - public void SetCompilingButtonsEnabled(bool Enabled) + public void SetCompilingAndRunButtonsEnabled(bool Enabled) { if (Enabled) { @@ -393,7 +393,7 @@ namespace VisualPascalABC public void SetDebugStopEnabled() { - SetCompilingButtonsEnabled(false); + SetCompilingAndRunButtonsEnabled(false); this.mDEBUGSTOPToolStripMenuItem.Enabled = true; this.mDEBUGENDToolStripMenuItem.Enabled = true; this.mSTEPToolStripMenuItem.Enabled = true; @@ -417,7 +417,7 @@ namespace VisualPascalABC this.mDEBUGSTARTToolStripMenuItem.Text = Form1StringResources.Get("M_DEBUGSTART"); } - public void SetStartDebugDisabled() + public void SetStartDebugAndRunDisabled() { this.mDEBUGSTARTToolStripMenuItem.Enabled = false; this.StartDebugButton.Enabled = false; @@ -434,7 +434,10 @@ namespace VisualPascalABC SaveDebugContext(); } - public void SetStartDebugEnabled() + /// + /// Активирует кнопки для Debug и запуска программы + /// + public void SetStartDebugAndRunEnabled() { this.mDEBUGSTARTToolStripMenuItem.Enabled = true; this.StartDebugButton.Enabled = true; @@ -444,6 +447,7 @@ namespace VisualPascalABC this.StepOverButton.Enabled = true; this.mRUNTOCURToolStripMenuItem.Enabled = true; this.mSTEPToolStripMenuItem.Enabled = true; + this.miRun.Enabled = true; this.StartButton.Enabled = true; ChangeDebugButtons(false); @@ -458,7 +462,7 @@ namespace VisualPascalABC this.StepOutButton.Enabled = false; if (!(clicked_stop_debug_in_menu && WorkbenchServiceFactory.RunService.IsRun() && debuggedPage != ActiveCodeFileDocument)) { - SetCompilingButtonsEnabled(true); + SetCompilingAndRunButtonsEnabled(true); this.stopButton.Enabled = false; this.miStop.Enabled = false; } @@ -518,44 +522,17 @@ namespace VisualPascalABC } } - public void SetDebugButtonsEnabled(bool val) + /// + /// Активировать/Деактивировать все кнопки, относящиеся к форматированию кода + /// + private void SetFormatButtonsEnabled(bool enabled) { - if (!DebuggerVisible) - return; - if (val) - { - this.mDEBUGSTOPToolStripMenuItem.Enabled = false; - this.mDEBUGSTARTToolStripMenuItem.Enabled = false; - this.StartDebugButton.Enabled = true; - this.StopDebugButton.Enabled = true; - this.StepOutButton.Enabled = false; - this.StepOverButton.Enabled = true; - this.StepIntoButton.Enabled = true; - this.mDEBUGSTARTToolStripMenuItem.Enabled = true; - this.mSTEPINToolStripMenuItem.Enabled = true; - this.mSTEPOVERToolStripMenuItem.Enabled = true; - this.mSTEPToolStripMenuItem.Enabled = false; - this.mRUNTOCURToolStripMenuItem.Enabled = true; - this.miRun.Enabled = true; - this.StartButton.Enabled = true; - } - else - { - this.mDEBUGSTOPToolStripMenuItem.Enabled = false; - this.mSTEPToolStripMenuItem.Enabled = false; - this.StartDebugButton.Enabled = false; - this.StopDebugButton.Enabled = false; - this.StepOutButton.Enabled = false; - this.StepOverButton.Enabled = false; - this.StepIntoButton.Enabled = false; - this.mDEBUGSTARTToolStripMenuItem.Enabled = false; - this.mSTEPINToolStripMenuItem.Enabled = false; - this.mSTEPOVERToolStripMenuItem.Enabled = false; - this.mRUNTOCURToolStripMenuItem.Enabled = false; - this.mSTEPToolStripMenuItem.Enabled = false; - this.miRun.Enabled = false; - this.StartButton.Enabled = false; - } + tsFormat.Enabled = mFORMATToolStripMenuItem.Enabled = cmFormat.Enabled = enabled; + } + + private void SetRunButtonsEnabled(bool enabled) + { + miRun.Enabled = StartButton.Enabled = enabled; } bool mDEBUGSTOPToolStripMenuItem_Enabled; diff --git a/VisualPascalABCNETLinux/Workbench/WindowOperations.cs b/VisualPascalABCNETLinux/Workbench/WindowOperations.cs index f9d249d75..af0a89738 100644 --- a/VisualPascalABCNETLinux/Workbench/WindowOperations.cs +++ b/VisualPascalABCNETLinux/Workbench/WindowOperations.cs @@ -410,8 +410,19 @@ namespace VisualPascalABC CurrentWebBrowserControl = null; SetFocusToEditor(); } + + CodeCompletion.CodeCompletionController.SetLanguage(CurrentCodeFileDocument.FileName); + + bool intellisenseAvailable = CodeCompletion.CodeCompletionController.IntellisenseAvailable(); + + SetFormatButtonsEnabled(intellisenseAvailable); + + if (!intellisenseAvailable) + SetDebugButtonsEnabled(false); // активация кнопок произойдет ниже, если возможно + if (BakSelectedTab == CurrentCodeFileDocument) return; + LastSelectedTab = BakSelectedTab; BakSelectedTab = CurrentCodeFileDocument; @@ -432,8 +443,6 @@ namespace VisualPascalABC OutputWindow.outputTextBox = OutputTextBoxs[CurrentCodeFileDocument]; } - CodeCompletion.CodeCompletionController.SetLanguage(CurrentCodeFileDocument.FileName); - SetFocusToEditor(); bool run = WorkbenchServiceFactory.RunService.IsRun(CurrentEXEFileName); WorkbenchServiceFactory.DebuggerManager.SetAsPossibleDebugPage(CurrentCodeFileDocument); @@ -447,16 +456,16 @@ namespace VisualPascalABC if (VisualEnvironmentCompiler != null) if (!debug) { - SetCompilingButtonsEnabled(!run && VisualEnvironmentCompiler.compilerLoaded); - SetDebugButtonsEnabled(!run && VisualEnvironmentCompiler.compilerLoaded); + SetCompilingAndRunButtonsEnabled(!run && VisualEnvironmentCompiler.compilerLoaded); + SetDebugButtonsEnabled(intellisenseAvailable && !run && VisualEnvironmentCompiler.compilerLoaded); } else { - SetCompilingButtonsEnabled(!debug); + SetCompilingAndRunButtonsEnabled(!debug); SetDebugButtonsAsByDebug(); } else - SetCompilingButtonsEnabled(false); + SetCompilingAndRunButtonsEnabled(false); SaveButtonsEnabled = CurrentCodeFileDocument.DocumentChanged; UpdateUndoRedoEnabled(); UpdateCutCopyButtonsEnabled(); diff --git a/documentation/DeveloperGuides/Integrating new language.md b/documentation/DeveloperGuides/Integrating new language.md index 5f23669fb..c2eeb29d5 100644 --- a/documentation/DeveloperGuides/Integrating new language.md +++ b/documentation/DeveloperGuides/Integrating new language.md @@ -1,5 +1,5 @@ ### Шаг 1 -Необходимо создать папку, называющуюся так же, как Ваш язык в папке *AdditionalLanguages*, расположенной в корне репозитория. Далее создать в ней два обязательных проекта. Это проект парсера Вашего языка, а также проект, содержащий класс Вашего языка (унаследованный от класса `BaseLanguage`, находящегося в стандартном проекте `LanguageIntegrator`) и класс "базы данных" языка (унаследованный от класса `BaseLanguageInformation` из проекта `ParserTools`). +Необходимо создать папку, называющуюся так же, как Ваш язык в папке *AdditionalLanguages*, расположенной в корне репозитория. Далее создать в ней два обязательных проекта. Это проект парсера Вашего языка, а также проект, содержащий класс Вашего языка (унаследованный от класса `BaseLanguage`, находящегося в стандартном проекте `LanguageIntegrator`) и класс "базы данных" языка (унаследованный от класса `DefaultLanguageInformation` или напрямую от интерфейса `ILanguageInformation` из проекта `ParserTools`). Для совместимости целевой платформой Ваших проектов должна быть *.NET Framework 4.0*. В свойствах проекта и для Release, и для Debug версии должен быть выбран выходной путь `..\..\..\bin\`. @@ -9,30 +9,32 @@ ### Шаг 2 В проекты Вы добавляете все необходимые для работы ссылки. Вам точно понадобятся ссылки на проекты `ParserTools`, `Errors`, `SyntaxTree` в проекте Вашего парсера и на проекты `LanguageIntegrator`, `ParserTools`, `SyntaxTree` в проекте с наследником `BaseLanguage`. ### Шаг 3 -Вам нужно унаследовать Ваш парсер (который является оберткой над GPPG парсером) от класса `BaseParser`, либо напрямую реализовать интерфейс `IParser`, если Вы не хотите пользоваться функциональностью из `BaseParser`. +Вам нужно унаследовать Ваш парсер (который является оберткой над GPPG парсером) от класса `BaseParser`, либо от класса `SimpleParser`, если Вы не хотите на начальном этапе реализовывать методы парсера для поддержки Intellisense. -Класс `BaseParser` содержит абстрактные методы, обязательные к реализации, самый главный из которых называется `BuildTreeInNormalMode`. Он отвечает за построение синтаксического дерева программы при обычном процессе компиляции. Остальные методы относятся к *Intellisense* и их реализация может быть пустой на первое время. +Класс `BaseParser` содержит абстрактные методы, обязательные к реализации, самый главный из которых называется `BuildTreeInNormalMode`. Он отвечает за построение синтаксического дерева программы при обычном процессе компиляции. Остальные методы в основном относятся к *Intellisense*. Для реализации `BuildTreeInNormalMode` Вам потребуется вызвать в этом методе сгенерированный GPPG парсер Вашего языка. Возвращаемое значение должно быть корнем полученного в результате парсинга синтаксического дерева. Для реализации парсера Вы можете также использовать такие базовые абстрактные классы как `BaseKeywords` и `BaseParserTools`. ### Шаг 4 -Для реализации методов в наследнике `BaseLanguageInformation` на первое время можно взять методы из `PascalABCLanguageInformation`, они используются в системе *Intellisense*. Но Вам также нужно задать следующие параметры языка: +Для реализации свойств в наследнике `DefaultLanguageInformation` Вам нужно задать следующие параметры языка: 1) имя языка, версия языка, строка с указанием авторских прав 2) расширения файлов Вашего языка 3) имена стандартных модулей языка 4) чувствительность к регистру и т. д. +Обращайте внимание на документирующие комментарии к свойствам. ### Шаг 5 В сделанном Вами наследнике `BaseLanguage` Вы пишете конструктор, который передает в `base()` следующие параметры: -1) класс "базы данных" языка, хранящий информацию в основном необходимую для Intellisense (наследник `BaseLanguageInformation`). -2) парсер Вашего языка (наследник `BaseParser`) -3) парсер XML-комментариев (если его нет, то можно передавать `null`) -4) список преобразователей синтаксического дерева с одним обязательным элементом (для него можно взять стандартную базовую версию под названием `DefaultSyntaxTreeConverter`) +1) класс "базы данных" языка, хранящий информацию в основном необходимую для Intellisense (наследник `DefaultLanguageInformation`). +2) класс с методами для поддержки Intellisense (если его нет, можно передавать `null`) +3) парсер Вашего языка (наследник `BaseParser`) +4) парсер XML-комментариев (если его нет, то можно передавать `null`) +5) список преобразователей синтаксического дерева с одним обязательным элементом (для него можно взять стандартную базовую версию под названием `DefaultSyntaxTreeConverter`) -Также Вы реализуете метод `SetSemanticConstants`, в котором задаете необходимые параметры (значения переменных) из файла *SemanticRulesConstants.cs* (проект TreeConverter). +При необходимости Вы можете переопределить метод `SetSemanticConstants`, в котором нужно задавать необходимые параметры (значения переменных) из файла *SemanticRulesConstants.cs* (проект TreeConverter). Для простого языка этого может не потребоваться. И наконец, реализуете метод `SetSyntaxTreeToSemanticTreeConverter`, в котором создаете новый экземпляр преобразователя синтаксического дерева в семантическое (присваиваете его свойству `SyntaxTreeToSemanticTreeConverter`). Для простых языков в качестве преобразователя можно присваивать экземпляр класса `syntax_tree_visitor`, получив его следующим образом: `LanguageProvider.Instance.MainLanguage.SyntaxTreeToSemanticTreeConverter`.