public async Task SendMessage(int id, string message, ParseMode mode = ParseMode.None, bool webPreview = true, int replyToMessageId = -1, object replyMarkup = null) { if (message.Length > 4096) { message = message.Substring(4090); } List<Param> param = new List<Param> { new Param("chat_id", id.ToString()), new Param("text", message), new Param("disable_web_page_preview", (!webPreview).ToString()), }; switch (mode) { case ParseMode.HTML: param.Add(new Param("parse_mode", "HTML")); break; case ParseMode.Markdown: param.Add(new Param("parse_mode", "Markdown")); break; } if (replyToMessageId != -1) { param.Add(new Param("reply_to_message_id", replyToMessageId.ToString())); } if (replyMarkup != null) { param.Add(new Param("reply_markup", JsonConvert.SerializeObject(replyMarkup))); } Message m = await MakeRequest<Message>("/sendMessage", Call.GET, param); }
public void SetMode(ParseMode mode) { Mode = mode; foreach (ConsoleCharacter consoleCharacter in _characterList) { consoleCharacter.SetMode(mode); } }
/// <summary> /// Returns parser instance for given parse mode. /// </summary> /// <param name="mode">Parse mode.</param> /// <returns>Parser instance.</returns> /// <exception cref="ArgumentOutOfRangeException"><paramref name="mode" /> is out of range.</exception> public static IParser GetParser(ParseMode mode) { switch (mode) { case ParseMode.Fast: return FastParser; case ParseMode.Classic: return ClassicParser; default: throw new ArgumentOutOfRangeException("mode"); } }
/// <summary> /// Returns parser instance for given parse mode. /// </summary> /// <param name="mode">Parse mode.</param> /// <returns>Parser instance.</returns> /// <exception cref="ArgumentOutOfRangeException"><paramref name="mode" /> is out of range.</exception> public static IParser GetParser(ParseMode mode) { // Check value if (!Enum.IsDefined(typeof(ParseMode), mode)) { throw new ArgumentOutOfRangeException("mode"); } switch (mode) { case ParseMode.Fast: return FastParser; default: return ClassicParser; } }
public Dictionary<string, string> Parse(ParseMode mode) { switch (mode) { case ParseMode.WhithoutArray: if (data.Count > 0) data.Clear(); string[] arr = cleaned.Split(','); foreach (string item in arr) { string[] tmp = item.Split(':'); data.Add(tmp[0].Trim().Replace("\"", ""), tmp[1].Replace("\"", "").Trim()); } break; case ParseMode.WithArray: if (data.Count > 0) data.Clear(); arr = cleaned.Split(','); for (int i = 0; i < arr.Length; i++) { string[] tmp = arr[i].Split(':'); data.Add(tmp[0].Trim(), tmp[1].Trim()); if (i == 0) break; } string upd = cleaned.Substring(cleaned.IndexOf("updates:")).Remove(0, 8).Trim(); upd = upd.Remove(upd.Length - 1, 1).Remove(0, 1); Regex oRegex = new Regex(@"(?<data>[\w*|\d+])"); MatchCollection oMatchCollection = oRegex.Matches(upd); List<string> list = new List<string>(); foreach (Match oMatch in oMatchCollection) { list.Add(oMatch.Groups["data"].Value); } break; default: break; } return data; }
public SinTD ParseIDL(string idlString, SinTD targetSinTD) { CurrentlyParsedSinTD = targetSinTD; lineNumberParsed = 0; currentlyParsing = ParseMode.NONE; wasParsingBeforeComment = ParseMode.NONE; string[] idlLines = idlString.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); foreach (string line in idlLines) { ++lineNumberParsed; parseLine(line.Trim()); } return CurrentlyParsedSinTD; }
public bool Parse(bool onlyHeader) { if (!File.Exists(FileName)) { Utils.Log(FileName + " doesn't exist. Can't parse data."); return false; } Map = new FOMap(); StreamReader r = File.OpenText(FileName); mode = ParseMode.Nothing; while (!r.EndOfStream && mode != ParseMode.Finished) { if (mode == ParseMode.Tiles && onlyHeader) break; if (mode == ParseMode.Objects) { parseObjects(r); break; } string line = r.ReadLine(); if (String.IsNullOrEmpty(line)) continue; if (updateModeLine(line)) continue; switch (mode) { case ParseMode.Header: parseHeaderLine(line); break; case ParseMode.Tiles: parseTileLine(line); break; default: break; } } r.Close(); _IsParsed = true; return true; }
/// <summary> /// Copies the current node to the supplied TextWriter at the TextWriter's current position. /// </summary> /// <remarks>Does not call <Mth>Flush</Mth> on the supplied <Typ>TextWriter</Typ>.</remarks> /// <exception cref="ArgumentNullException"><P>textWriter</P> is null.</exception> /// <exception cref="InvalidOperationException">The state of the reader is incorrect for this call.</exception> internal void CopyNode(TextWriter textWriter) { if (textWriter == null) throw new ArgumentNullException(); // if m_ParseWriter is null, something is wrong - e.g. the user called GetOuterXml() on this node already. if (m_ParseWriter == null) throw new InvalidOperationException(); // Copy the current contents of m_ParseWriter into textWriter. m_ParseWriter contains the current node's content // up to the point it has been read so far. m_ParseWriter.Flush(); m_ParseWriter.BaseStream.Position = 0; // We'll close the m_ParseWriter after this operation, so don't worry about the StreamReader // closing the underlying stream. using (StreamReader reader = new StreamReader(m_ParseWriter.BaseStream, m_ParseWriter.Encoding)) { int i = reader.Read(); while (i != -1) { textWriter.Write((char)(ushort)i); i = reader.Read(); } } // Set m_ParseWriter to null since ReadNextChar() should no longer write into it, but rather // create a new one. m_ParseWriter.Dispose(); m_ParseWriter = null; // if parse state is not None, the current node is partially parsed. // Set m_CopyNode to textWriter. This will cause further calls to Parse() to stream into m_CopyNode // instead of m_ParseWriter. if (m_ParseState != HtmlParseState.None) { m_CopyNode = textWriter; m_ParseMode = ParseMode.Skip; try { while (m_ParseState != HtmlParseState.None) { Parse(); } } catch (EndOfStreamException) { // do nothing } // now set m_CopyNode to null since we're done having Parse() copy into the textWriter. // Next call to Parse() will create a new m_ParseWriter. m_CopyNode = null; } }
private static async void MessageReceived(object sender, MessageEventArgs e) { string msg = ""; ParseMode parseMode = ParseMode.Html; var regId = new Regex(@"\d+$"); var regText = new Regex(@"^/[a-zA-Z]+"); string idStr = regId.Match(e.Message.Text).Value; int id = idStr == "" ? 0 : Convert.ToInt32(idStr); string text = regText.Match(e.Message.Text).Value; ikm = null; switch (text) { case "/hello": msg = "Hello world! I am great, yeah"; break; case "/categories": msg = "<b>Our categories:</b>\n"; var cats = await GetItems <IEnumerable <CatWithSubs> >("product/getAllCategories"); msg += "<pre>" + GetFormattedCategoryTree(cats) + "</pre>"; break; case "/products": msg = await GetListMessage <ProductInformation>("product", 1); break; case "/product": try { var prodInfo = await GetItem <ProductInformation>("product", id); var state = (prodInfo.State != ProductState.Normal ? $"<i>{prodInfo.State} product</i>\n" : ""); msg = $"{RatingStars(prodInfo.Rating)}\n" + $"<b>{prodInfo.Name}</b>\n" + $"{prodInfo.Description}\n" + state + $"๏.๏ {prodInfo.Watches}\n\n"; await SendImage(prodInfo.Preview.Id, e.Message.Chat); } catch (Exception exc) { msg = exc.Message; } break; case "/suppliers": msg = await GetListMessage <SupplierInformation>("supplier", 1); break; case "/supplier": try { var suppInfo = await GetItem <SupplierInformation>("supplier", id); msg = $"{RatingStars(suppInfo.Rating)}\n" + $"<b>{suppInfo.Name}</b>\n" + $"{suppInfo.Location.Address}\n" + $"๏.๏ {suppInfo.Watches}\n\n"; await SendImage(suppInfo.Preview.Id, e.Message.Chat); if (!(suppInfo.Location.Longtitude == 0 && suppInfo.Location.Latitude == 0)) { await botClient.SendVenueAsync( chatId : e.Message.Chat, latitude : suppInfo.Location.Latitude, longitude : suppInfo.Location.Longtitude, title : suppInfo.Name, address : suppInfo.Location.Address ); } } catch (Exception exc) { msg = exc.Message; } break; case "/articles": msg = await GetListMessage <ArticleInformation>("article", 1); break; case "/article": try { var artInfo = await GetItem <ArticleInformation>("article", id); msg = $"{RatingStars(artInfo.Rating)}\n" + $"<b>{artInfo.Name}</b>\n" + $"{artInfo.Description}\n" + $"๏.๏ {artInfo.Watches}\n\n"; } catch (Exception exc) { msg = exc.Message; } break; default: msg = "You wrote: " + e.Message.Text; break; } await botClient.SendTextMessageAsync( chatId : e.Message.Chat, text : msg, replyToMessageId : e.Message.MessageId, parseMode : parseMode, replyMarkup : ikm ); }
void ParseInto(string text, ref List <Node> nodes) { Filetype filetype = Filetype.XML; if (text.IndexOf("(dp0") == 0) { filetype = Filetype.Twine; } else if (text.IndexOf("[") == 0) { filetype = Filetype.JSON; } nodes.Clear(); switch (filetype) { case Filetype.JSON: var N = JSON.Parse(text); int c = 0; while (N[c] != null) { if (N[c]["title"] != null && N[c]["body"] != null) { nodes.Add(new Node(((string)N[c]["title"]).Trim(), ((string)(N[c]["body"])).Replace('\r', '\n'))); } c++; } break; case Filetype.XML: //var xmlParser = new XMLParser(text); //var xmlElement = xmlParser.Parse(); /* * XDocument xDoc = XDocument.Load("XMLFile1.xml"); * * var query = (from x in xDoc.Descendants("quiz").Elements("problem") * select new Question * { * question = x.Element("question").Value, * answerA = x.Element("answerA").Value, * answerB = x.Element("answerB").Value, * answerC = x.Element("answerC").Value, * answerD = x.Element("answerD").Value, * correct = x.Element("correct").Value * }).ToList(); */ break; case Filetype.Twine: string[] lines = text.Split('\n'); // get rid of tabs! for (int i = 0; i < lines.Length; i++) { lines[i] = Regex.Replace(lines[i], @"\t", ""); } ParseMode parseMode = ParseMode.None; string nodeTitle = ""; string nodeText = ""; foreach (string line in lines) { if (line.IndexOf("Tiddler") != -1) { parseMode = ParseMode.Text; } if (parseMode != ParseMode.None) { if (line[0] == 'V') { if (parseMode == ParseMode.Text) { nodeText = line.Substring(1, line.Length - 1); nodeText = nodeText.Replace("\\u000a", "\n"); nodeText = nodeText.Replace("\\u2013", "-"); parseMode = ParseMode.Title; } else if (parseMode == ParseMode.Title) { nodeTitle = line.Substring(1, line.Length - 1); } if (nodeTitle != "" && nodeText != "") { nodes.Add(new Node(nodeTitle, nodeText)); nodeText = ""; nodeTitle = ""; parseMode = ParseMode.Text; } } } } break; } }
/// <summary> /// Парсит тела конструкций, в том числе и новой функции. /// </summary> public static void Parse(TokenList tokens, out int counter, bool isRoot = false) { counter = 0; while (counter < tokens.Count) { BaseGenerator generator = CodeManager.GetGenerator(parseMode); TokenList nextTokens = tokens.GetRange(counter); Token currentToken = tokens[counter]; Token nextToken = tokens.Get(counter + 1); if (currentToken.TypeIs(TokenType.NextLine)) { lineIndex++; counter++; continue; } if (currentToken.TypeIs(TokenType.Id)) { // <variableName> = <expression>; if (nextToken.TypeIs(TokenType.AssignOperator)) { string variableName = currentToken.value; TokenList expression = nextTokens.GetRange(nextTokens.IndexOf("=") + 1, nextTokens.IndexOf(";")); generator.AddVariableAssignment(variableName, expression, isRoot); counter += nextTokens.IndexOf(";") + 1; } // <id>(<expression>); else if (nextToken.TypeIs(TokenType.BeginParenthesis)) { Token name = currentToken; TokenList attributes = GetExpressionInParenthesis(nextTokens, errors: false); if (attributes.Count == 0 && !nextTokens.Get(2).TypeIs(TokenType.EndParenthesis)) { throw new ParseException($"После '(' при вызове функции без параметров ожидалось ')', а не '{nextToken}'", lineIndex); } generator.AddFunctionCall(name, attributes); counter += nextTokens.IndexOf(";") + 1; } else { throw new ParseException($"После '{currentToken}' ожидалось '=' либо '(', а не '{nextToken}'", lineIndex); } } else if (currentToken.TypeIs(TokenType.Keyword)) { // функция <functionName>(<parameters>) { <functionBody> } if (currentToken.TypeIs(KeywordType.Function)) { NewFunction newFunction = CodeManager.NewFunction; string name = nextToken.value; TokenList parameters = GetExpressionInParenthesis(nextTokens, errors: false); TokenList body = GetBody(nextTokens, out counter, counter); if (!nextToken.TypeIs(TokenType.Id)) { throw new ParseException($"После ключевого слова 'функция' ожидалось название объявляемой функции, а не '{nextToken}'", lineIndex); } if (!nextTokens.Get(2).TypeIs(TokenType.BeginParenthesis)) { throw new ParseException($"После названия функции ожидалось '(', а не '{nextToken}'", lineIndex); } if (parameters.Count == 0 && !nextTokens.Get(3).TypeIs(TokenType.EndParenthesis)) { throw new ParseException($"После '(' при объявлении функции без параметров ожидалось ')', а не '{nextToken}'", lineIndex); } parameters.DeleteAll(","); newFunction.AddFunctionHeader(name, parameters); parseMode = ParseMode.FunctionCreation; Parse(body, out _); newFunction.Create(); parseMode = ParseMode.Default; } // если (<expresion>) { <body> } else if (currentToken.TypeIs(KeywordType.If)) { TokenList expression = GetExpressionInParenthesis(nextTokens); TokenList body = GetBody(nextTokens, out counter, counter); if (!nextToken.TypeIs(TokenType.BeginParenthesis)) { throw new ParseException($"После ')' ожидалось '{{', а не {nextToken}", lineIndex); } generator.AddIfConstruction(expression); Parse(body, out _); generator.AddConstructionEnd(); } // иначе { <body> } else if (currentToken.TypeIs(KeywordType.Else)) { TokenList body = GetBody(nextTokens, out counter, counter); generator.AddElseConstruction(); Parse(body, out _); generator.AddConstructionEnd(); } // делать { <body> } пока (<expression>) else if (currentToken.TypeIs(KeywordType.Do)) { TokenList body = GetBody(nextTokens, out counter, counter); generator.AddDoConstruction(); Parse(body, out _); generator.AddConstructionEnd(); nextTokens = tokens.GetRange(counter); currentToken = tokens[counter]; if (currentToken.TypeIs(KeywordType.While)) { TokenList expression = GetExpressionInParenthesis(nextTokens); if (expression.Count == 0) { throw new ParseException($"Конструкция 'пока' без выражения", lineIndex); } generator.AddEndingWhileConstruction(expression); counter += nextTokens.IndexOf(";") + 1; } else { throw new ParseException($"После окончания конструкции 'делать' ожидалось ключевое слово 'пока'", lineIndex); } } // пока (<expression>) { <body> } else if (currentToken.TypeIs(KeywordType.While)) { TokenList expression = GetExpressionInParenthesis(nextTokens); TokenList body = GetBody(nextTokens, out counter, counter); generator.AddWhileConstruction(expression); Parse(body, out _); generator.AddConstructionEnd(); } // пробовать { <tryBody> } отловить [(<errorValue>)] { <catchBody> } else if (currentToken.TypeIs(KeywordType.Try)) { TokenList tryBody = GetBody(nextTokens, out counter, counter); generator.AddTryConstruction(); Parse(tryBody, out _); generator.AddConstructionEnd(); nextTokens = tokens.GetRange(counter); currentToken = tokens[counter]; if (currentToken.TypeIs(KeywordType.Catch)) { TokenList expression = GetExpressionInParenthesis(nextTokens, errors: false); TokenList catchBody = GetBody(nextTokens, out counter, counter); if (expression.Count == 1 && expression[0].TypeIs(TokenType.Id)) { generator.AddCatchConstruction(expression[0]); } else { generator.AddCatchConstruction(); } Parse(catchBody, out _); generator.AddConstructionEnd(); } } // определить (<value>) { <body> } else if (currentToken.TypeIs(KeywordType.Switch)) { TokenList expression = GetExpressionInParenthesis(nextTokens); TokenList body = GetBody(nextTokens, out counter, counter); if (expression.Count == 1 && expression[0].TypeIs(TokenType.Id)) { generator.AddSwitchConstruction(expression[0]); ParseSwitch(body); generator.AddConstructionEnd(); } } // использовать ... else if (currentToken.TypeIs(KeywordType.Use)) { // ссылки "<path>" if (nextToken.TypeIs(KeywordType.Links) && nextTokens.Get(2).TypeIs(TokenType.String) && Path.GetExtension(nextTokens[2].value) == GlobalParams.linksExtention) { CodeManager.UpdateNamesMap(nextTokens[2].value); } // <id> else if (nextToken.TypeIs(TokenType.Id)) { Compilator.AddUsing(nextToken.ToString()); Compilator.AddClassRef(nextToken.ToString()); } counter += nextTokens.IndexOf(";") + 1; } // импорт ... else if (currentToken.TypeIs(KeywordType.Import)) { if (nextToken.TypeIs(TokenType.String)) { string path = nextToken.value; if (File.Exists(path)) { string extention = Path.GetExtension(path); if (extention == GlobalParams.codeExtention) { // ...... } else { Compilator.AddRef(path); } } } counter += nextTokens.IndexOf(";") + 1; } else { throw new ParseException($"На первой позиции не ожидалось ключевое слово {currentToken}", lineIndex); } } else { throw new ParseException($"Не удалось распознать слово '{currentToken}'", lineIndex); } } }
public async Task SendMessage(string username, string message, ParseMode mode = ParseMode.None, bool webPreview = true, int replyToMessageId = -1) { await SendMessage(ConvertFromUsernameToID(username), message, mode, webPreview, replyToMessageId); }
private static string ParseExpression(string code, string id, ParseMode mode, bool whenCondition, DekiScriptEnv env, DekiScriptRuntime runtime, Dictionary<string, string> channels, ref int i) { StringBuilder result = new StringBuilder(); int nesting = 0; for(; i < code.Length; ++i) { int start; switch(code[i]) { case '"': case '\'': // process strings start = i; ScanString(code, code[i], ref i); result.Append(code, start, i - start); --i; break; case '/': // check if / denotes the beginning of a comment, if so process it start = i; if(TryScanComment(code, ref i)) { // NOTE: remove comments in when-condition if(!whenCondition) { result.Append(code, start, i - start); result.Append("\n"); } --i; } else { result.Append(code[i]); } break; case '\\': // backslash (\) always appends the next character result.Append(code[i++]); if(i < code.Length) { result.Append(code[i]); } break; case '(': // increase nesting level result.Append(code[i]); ++nesting; break; case '{': // check if this is the beginning of a dekiscript block {{ }} if(((i + 1) < code.Length) && (code[i + 1] == '{')) { ++i; string value; start = i; if(TryParseDekiScriptExpression(code, env, runtime, ref i, out value)) { result.Append(value); } else { ++nesting; result.Append('{'); result.Append(code, start, i - start); --i; } } else { ++nesting; result.Append(code[i]); } break; case ')': case '}': // decrease nesting level and check if this is the end of the sougth expression result.Append(code[i]); --nesting; // NOTE: only exit if // 1) we don't have to read all of the code // 2) there are no open parentheses or cruly braces // 3) we don't on a complete statement or the current characteris a closing curly brace if((mode != ParseMode.ALL) && (nesting <= 0) && ((mode != ParseMode.STATEMENT) || (code[i] == '}'))) { // found the end of the expression ++i; return result.ToString(); } break; case ';': // check if the statement is the end of the sougth expression result.Append(code[i]); // NOTE: only exit if // 1) we don't have to read all of the code // 2) there are no open parentheses or cruly braces // 3) we stop on a complete statement if((nesting <= 0) && (mode == ParseMode.STATEMENT)) { // found the end of the expression ++i; return result.ToString(); } break; case '@': // channel name if(channels != null) { ++i; start = i; string channel; string name; if((i < code.Length) && ((code[i] == '"') || (code[i] == '\''))) { // process: @"channel_name" or @'channel_name' ScanString(code, code[i], ref i); channel = code.Substring(start, i - start); name = channel.Substring(1, channel.Length - 2).UnescapeString(); } else { // process: @channel_magic_id ScanId(code, ref i); name = code.Substring(start, i - start); if(!channels.TryGetValue(name, out channel)) { channel = env.GetMagicId(name).ToString(); } } start = i; ScanWhitespace(code, ref i); if((i < code.Length) && (code[i] == '(')) { // process: @channel ( ... ) string message = ParseExpression(code, id, ParseMode.EXPRESSION, false, env, runtime, channels, ref i); message = message.Substring(1, message.Length - 2).Trim(); if(message.Length == 0) { result.AppendFormat("Deki.publish({0})", channel); } else { result.AppendFormat("Deki.publish({0}, {1})", channel, message); } } else { // channel is used for reading; add it to the channel set to read on activation channels[name] = channel; // convert channel name and add whitespace result.AppendFormat("$channels[{0}]", name.QuoteString()); result.Append(code, start, i - start); } --i; } else { result.Append(code[i]); } break; case '#': // NOTE: don't process #id in the when-condition // element name if(!whenCondition && (channels != null)) { ++i; start = i; // process: #id ScanId(code, ref i); string name = code.Substring(start, i - start); result.Append("$(\"#" + name + "\")"); --i; } else { result.Append(code[i]); } break; default: // NOTE: don't process when() in the when-condition // check if this is the beginning of an identifier if(!whenCondition && IsAlpha(code[i])) { start = i; ScanId(code, ref i); int j = i; ScanWhitespace(code, ref j); // check if scanned identifier is the keyword 'when' if(((i - start) == WHEN.Length) && (string.Compare(code, start, WHEN, 0, WHEN.Length, StringComparison.Ordinal) == 0) && (j < code.Length) && (code[j] == '(')) { i = j; Dictionary<string, string> subChannels = new Dictionary<string, string>(); // parse the condition of the 'when()' statement string condition = ParseExpression(code, id, ParseMode.EXPRESSION, true, env, runtime, subChannels, ref i); // parse the body of the 'when()' expression string body = ParseExpression(code, id, ParseMode.STATEMENT, false, env, runtime, subChannels, ref i); BuildWhenStatement(condition.Trim(), id, body.Trim(), result, env, subChannels); } else { result.Append(code, start, i - start); } --i; } else { result.Append(code[i]); } break; } } return result.ToString(); }
static void RemoveCondition(string line, ParseMode parseMode) { ModifyCondition(line, parseMode, true); }
// Group: Parsing Functions // __________________________________________________________________________ /* Function: TryToSkipClassDeclarationLine * * If the iterator is on a class's declaration line, moves it past it and returns true. It does not handle the class body. * * Supported Modes: * * - <ParseMode.IterateOnly> * - <ParseMode.ParseClassPrototype> * - Everything else is treated as <ParseMode.IterateOnly>. */ protected bool TryToSkipClassDeclarationLine(ref TokenIterator iterator, ParseMode mode = ParseMode.IterateOnly) { TokenIterator lookahead = iterator; // Decorators if (TryToSkipDecorators(ref lookahead, mode)) { TryToSkipWhitespace(ref lookahead); } // Keyword if (lookahead.MatchesToken("class") == false) { ResetTokensBetween(iterator, lookahead, mode); return(false); } if (mode == ParseMode.ParseClassPrototype) { lookahead.ClassPrototypeParsingType = ClassPrototypeParsingType.Keyword; } lookahead.Next(); TryToSkipWhitespace(ref lookahead); // Name TokenIterator startOfIdentifier = lookahead; if (TryToSkipIdentifier(ref lookahead) == false) { ResetTokensBetween(iterator, lookahead, mode); return(false); } if (mode == ParseMode.ParseClassPrototype) { iterator.Tokenizer.SetClassPrototypeParsingTypeBetween(startOfIdentifier, lookahead, ClassPrototypeParsingType.Name); } TryToSkipWhitespace(ref lookahead); // Base classes if (lookahead.Character == '(') { if (mode == ParseMode.ParseClassPrototype) { lookahead.ClassPrototypeParsingType = ClassPrototypeParsingType.StartOfParents; } lookahead.Next(); TryToSkipWhitespace(ref lookahead); for (;;) { if (lookahead.Character == ')') { if (mode == ParseMode.ParseClassPrototype) { lookahead.ClassPrototypeParsingType = ClassPrototypeParsingType.EndOfParents; } break; } if (TryToSkipClassParent(ref lookahead, mode) == false) { ResetTokensBetween(iterator, lookahead, mode); return(false); } TryToSkipWhitespace(ref lookahead); if (lookahead.Character == ',') { if (mode == ParseMode.ParseClassPrototype) { lookahead.ClassPrototypeParsingType = ClassPrototypeParsingType.ParentSeparator; } lookahead.Next(); TryToSkipWhitespace(ref lookahead); } } } iterator = lookahead; return(true); }
// // Parses the string @input and returns a CSharpParser if succeeful. // // if @silent is set to true then no errors are // reported to the user. This is used to do various calls to the // parser and check if the expression is parsable. // // @partial_input: if @silent is true, then it returns whether the // parsed expression was partial, and more data is needed // static CSharpParser ParseString(ParseMode mode, string input, out bool partial_input) { partial_input = false; Reset(); queued_fields.Clear(); Stream s = new MemoryStream(Encoding.Default.GetBytes(input)); SeekableStreamReader seekable = new SeekableStreamReader(s, Encoding.Default); InputKind kind = ToplevelOrStatement(seekable); if (kind == InputKind.Error) { if (mode == ParseMode.ReportErrors) { ctx.Report.Error(-25, "Detection Parsing Error"); } partial_input = false; return(null); } if (kind == InputKind.EOF) { if (mode == ParseMode.ReportErrors) { Console.Error.WriteLine("Internal error: EOF condition should have been detected in a previous call with silent=true"); } partial_input = true; return(null); } seekable.Position = 0; CSharpParser parser = new CSharpParser(seekable, (CompilationUnit)Location.SourceFiles [0], ctx); if (kind == InputKind.StatementOrExpression) { parser.Lexer.putback_char = Tokenizer.EvalStatementParserCharacter; RootContext.StatementMode = true; } else { // // Do not activate EvalCompilationUnitParserCharacter until // I have figured out all the limitations to invoke methods // in the generated classes. See repl.txt // parser.Lexer.putback_char = Tokenizer.EvalUsingDeclarationsParserCharacter; //parser.Lexer.putback_char = Tokenizer.EvalCompilationUnitParserCharacter; RootContext.StatementMode = false; } if (mode == ParseMode.GetCompletions) { parser.Lexer.CompleteOnEOF = true; } ReportPrinter old_printer = null; if ((mode == ParseMode.Silent || mode == ParseMode.GetCompletions) && CSharpParser.yacc_verbose_flag == 0) { old_printer = ctx.Report.SetPrinter(new StreamReportPrinter(TextWriter.Null)); } try { parser.parse(); } finally { if (ctx.Report.Errors != 0) { if (mode != ParseMode.ReportErrors && parser.UnexpectedEOF) { partial_input = true; } parser.undo.ExecuteUndo(); parser = null; } if (old_printer != null) { ctx.Report.SetPrinter(old_printer); } } return(parser); }
public override PascalABCCompiler.SyntaxTree.syntax_tree_node BuildTree(string FileName, string Text, ParseMode ParseMode, List <string> DefinesList = null) { syntax_tree_node root = null; PreBuildTree(FileName); switch (ParseMode) { case ParseMode.Normal: root = BuildTreeInNormalMode(FileName, Text, DefinesList); break; case ParseMode.Expression: root = BuildTreeInExprMode(FileName, Text); break; case ParseMode.TypeAsExpression: root = BuildTreeInTypeExprMode(FileName, Text); break; case ParseMode.Special: root = BuildTreeInSpecialMode(FileName, Text); break; case ParseMode.ForFormatter: root = BuildTreeInFormatterMode(FileName, Text); break; case ParseMode.Statement: root = BuildTreeInStatementMode(FileName, Text); break; default: break; } if (root != null && root is compilation_unit) { (root as compilation_unit).file_name = FileName; (root as compilation_unit).compiler_directives = CompilerDirectives; if (root is unit_module) { if ((root as unit_module).unit_name.HeaderKeyword == UnitHeaderKeyword.Library) { (root as compilation_unit).compiler_directives.Add(new compiler_directive(new token_info("apptype"), new token_info("dll"))); } } } return(root); }
/// <summary> /// Load settings from the give INI file /// </summary> /// <param name="settingsfile">File to load</param> public static void LoadSettings(string settingsfile) { if (File.Exists(settingsfile)) { try { string serverAlias = ""; string[] Lines = File.ReadAllLines(settingsfile); ParseMode pMode = ParseMode.Default; foreach (string lineRAW in Lines) { string line = pMode == ParseMode.Main && lineRAW.ToLower().Trim().StartsWith("password") ? lineRAW.Trim() //Do not strip # in passwords : lineRAW.Split('#')[0].Trim(); if (line.Length > 0) { if (line[0] == '[' && line[line.Length - 1] == ']') { switch (line.Substring(1, line.Length - 2).ToLower()) { case "alerts": pMode = ParseMode.Alerts; break; case "antiafk": pMode = ParseMode.AntiAFK; break; case "autorelog": pMode = ParseMode.AutoRelog; break; case "chatlog": pMode = ParseMode.ChatLog; break; case "hangman": pMode = ParseMode.Hangman; break; case "main": pMode = ParseMode.Main; break; case "mcsettings": pMode = ParseMode.MCSettings; break; case "scriptscheduler": pMode = ParseMode.ScriptScheduler; break; case "remotecontrol": pMode = ParseMode.RemoteControl; break; case "proxy": pMode = ParseMode.Proxy; break; case "appvars": pMode = ParseMode.AppVars; break; case "autorespond": pMode = ParseMode.AutoRespond; break; case "chatformat": pMode = ParseMode.ChatFormat; break; default: pMode = ParseMode.Default; break; } } else { string argName = line.Split('=')[0]; if (line.Length > (argName.Length + 1)) { string argValue = line.Substring(argName.Length + 1); switch (pMode) { case ParseMode.Main: switch (argName.ToLower()) { case "login": Login = argValue; break; case "password": Password = argValue; break; case "serverip": if (!SetServerIP(argValue)) { serverAlias = argValue; } ; break; case "singlecommand": SingleCommand = argValue; break; case "language": Language = argValue; break; case "consoletitle": ConsoleTitle = argValue; break; case "timestamps": chatTimeStamps = str2bool(argValue); break; case "exitonfailure": interactiveMode = !str2bool(argValue); break; case "playerheadicon": playerHeadAsIcon = str2bool(argValue); break; case "chatbotlogfile": chatbotLogFile = argValue; break; case "mcversion": ServerVersion = argValue; break; case "splitmessagedelay": splitMessageDelay = TimeSpan.FromSeconds(str2int(argValue)); break; case "scriptcache": CacheScripts = str2bool(argValue); break; case "showsystemmessages": DisplaySystemMessages = str2bool(argValue); break; case "showxpbarmessages": DisplayXPBarMessages = str2bool(argValue); break; case "showchatlinks": DisplayChatLinks = str2bool(argValue); break; case "terrainandmovements": TerrainAndMovements = str2bool(argValue); break; case "privatemsgscmdname": PrivateMsgsCmdName = argValue.ToLower().Trim(); break; case "botmessagedelay": botMessageDelay = TimeSpan.FromSeconds(str2int(argValue)); break; case "debugmessages": DebugMessages = str2bool(argValue); break; case "botowners": Bots_Owners.Clear(); string[] names = argValue.ToLower().Split(','); if (!argValue.Contains(",") && argValue.ToLower().EndsWith(".txt") && File.Exists(argValue)) { names = File.ReadAllLines(argValue); } foreach (string name in names) { if (!String.IsNullOrWhiteSpace(name)) { Bots_Owners.Add(name.Trim()); } } break; case "internalcmdchar": switch (argValue.ToLower()) { case "none": internalCmdChar = ' '; break; case "slash": internalCmdChar = '/'; break; case "backslash": internalCmdChar = '\\'; break; } break; case "sessioncache": if (argValue == "none") { SessionCaching = CacheType.None; } else if (argValue == "memory") { SessionCaching = CacheType.Memory; } else if (argValue == "disk") { SessionCaching = CacheType.Disk; } break; case "accountlist": if (File.Exists(argValue)) { foreach (string account_line in File.ReadAllLines(argValue)) { //Each line contains account data: 'Alias,Login,Password' string[] account_data = account_line.Split('#')[0].Trim().Split(','); if (account_data.Length == 3) { Accounts[account_data[0].ToLower()] = new KeyValuePair <string, string>(account_data[1], account_data[2]); } } //Try user value against aliases after load Settings.SetAccount(Login); } break; case "serverlist": if (File.Exists(argValue)) { //Backup current server info string server_host_temp = ServerIP; ushort server_port_temp = ServerPort; foreach (string server_line in File.ReadAllLines(argValue)) { //Each line contains server data: 'Alias,Host:Port' string[] server_data = server_line.Split('#')[0].Trim().Split(','); server_data[0] = server_data[0].ToLower(); if (server_data.Length == 2 && server_data[0] != "localhost" && !server_data[0].Contains('.') && SetServerIP(server_data[1])) { Servers[server_data[0]] = new KeyValuePair <string, ushort>(ServerIP, ServerPort); } } //Restore current server info ServerIP = server_host_temp; ServerPort = server_port_temp; //Try server value against aliases after load SetServerIP(serverAlias); } break; case "brandinfo": switch (argValue.Trim().ToLower()) { case "mcc": BrandInfo = MCCBrandInfo; break; case "vanilla": BrandInfo = "vanilla"; break; default: BrandInfo = null; break; } break; case "resolvesrvrecords": if (argValue.Trim().ToLower() == "fast") { ResolveSrvRecords = true; ResolveSrvRecordsShortTimeout = true; } else { ResolveSrvRecords = str2bool(argValue); ResolveSrvRecordsShortTimeout = false; } break; } break; case ParseMode.Alerts: switch (argName.ToLower()) { case "enabled": Alerts_Enabled = str2bool(argValue); break; case "alertsfile": Alerts_MatchesFile = argValue; break; case "excludesfile": Alerts_ExcludesFile = argValue; break; case "beeponalert": Alerts_Beep_Enabled = str2bool(argValue); break; } break; case ParseMode.AntiAFK: switch (argName.ToLower()) { case "enabled": AntiAFK_Enabled = str2bool(argValue); break; case "delay": AntiAFK_Delay = str2int(argValue); break; case "command": AntiAFK_Command = argValue == "" ? "/ping" : argValue; break; } break; case ParseMode.AutoRelog: switch (argName.ToLower()) { case "enabled": AutoRelog_Enabled = str2bool(argValue); break; case "delay": AutoRelog_Delay = str2int(argValue); break; case "retries": AutoRelog_Retries = str2int(argValue); break; case "kickmessagesfile": AutoRelog_KickMessagesFile = argValue; break; } break; case ParseMode.ChatLog: switch (argName.ToLower()) { case "enabled": ChatLog_Enabled = str2bool(argValue); break; case "timestamps": ChatLog_DateTime = str2bool(argValue); break; case "filter": ChatLog_Filter = ChatBots.ChatLog.str2filter(argValue); break; case "logfile": ChatLog_File = argValue; break; } break; case ParseMode.Hangman: switch (argName.ToLower()) { case "enabled": Hangman_Enabled = str2bool(argValue); break; case "english": Hangman_English = str2bool(argValue); break; case "wordsfile": Hangman_FileWords_EN = argValue; break; case "fichiermots": Hangman_FileWords_FR = argValue; break; } break; case ParseMode.ScriptScheduler: switch (argName.ToLower()) { case "enabled": ScriptScheduler_Enabled = str2bool(argValue); break; case "tasksfile": ScriptScheduler_TasksFile = argValue; break; } break; case ParseMode.RemoteControl: switch (argName.ToLower()) { case "enabled": RemoteCtrl_Enabled = str2bool(argValue); break; case "autotpaccept": RemoteCtrl_AutoTpaccept = str2bool(argValue); break; case "tpaccepteveryone": RemoteCtrl_AutoTpaccept_Everyone = str2bool(argValue); break; } break; case ParseMode.ChatFormat: switch (argName.ToLower()) { case "builtins": ChatFormat_Builtins = str2bool(argValue); break; case "public": ChatFormat_Public = new Regex(argValue); break; case "private": ChatFormat_Private = new Regex(argValue); break; case "tprequest": ChatFormat_TeleportRequest = new Regex(argValue); break; } break; case ParseMode.Proxy: switch (argName.ToLower()) { case "enabled": ProxyEnabledLogin = ProxyEnabledIngame = str2bool(argValue); if (argValue.Trim().ToLower() == "login") { ProxyEnabledLogin = true; } break; case "type": argValue = argValue.ToLower(); if (argValue == "http") { proxyType = Proxy.ProxyHandler.Type.HTTP; } else if (argValue == "socks4") { proxyType = Proxy.ProxyHandler.Type.SOCKS4; } else if (argValue == "socks4a") { proxyType = Proxy.ProxyHandler.Type.SOCKS4a; } else if (argValue == "socks5") { proxyType = Proxy.ProxyHandler.Type.SOCKS5; } break; case "server": string[] host_splitted = argValue.Split(':'); if (host_splitted.Length == 1) { ProxyHost = host_splitted[0]; ProxyPort = 80; } else if (host_splitted.Length == 2) { ProxyHost = host_splitted[0]; ProxyPort = str2int(host_splitted[1]); } break; case "username": ProxyUsername = argValue; break; case "password": ProxyPassword = argValue; break; } break; case ParseMode.AppVars: SetVar(argName, argValue); break; case ParseMode.AutoRespond: switch (argName.ToLower()) { case "enabled": AutoRespond_Enabled = str2bool(argValue); break; case "matchesfile": AutoRespond_Matches = argValue; break; } break; case ParseMode.MCSettings: switch (argName.ToLower()) { case "enabled": MCSettings_Enabled = str2bool(argValue); break; case "locale": MCSettings_Locale = argValue; break; case "difficulty": switch (argValue.ToLower()) { case "peaceful": MCSettings_Difficulty = 0; break; case "easy": MCSettings_Difficulty = 1; break; case "normal": MCSettings_Difficulty = 2; break; case "difficult": MCSettings_Difficulty = 3; break; } break; case "renderdistance": MCSettings_RenderDistance = (byte)str2int(argValue); switch (argValue.ToLower()) { case "tiny": MCSettings_RenderDistance = 2; break; case "short": MCSettings_RenderDistance = 4; break; case "medium": MCSettings_RenderDistance = 8; break; case "far": MCSettings_RenderDistance = 16; break; } break; case "chatmode": switch (argValue.ToLower()) { case "enabled": MCSettings_ChatMode = 0; break; case "commands": MCSettings_ChatMode = 1; break; case "disabled": MCSettings_ChatMode = 2; break; } break; case "chatcolors": MCSettings_ChatColors = str2bool(argValue); break; case "skin_cape": MCSettings_Skin_Cape = str2bool(argValue); break; case "skin_jacket": MCSettings_Skin_Jacket = str2bool(argValue); break; case "skin_sleeve_left": MCSettings_Skin_Sleeve_Left = str2bool(argValue); break; case "skin_sleeve_right": MCSettings_Skin_Sleeve_Right = str2bool(argValue); break; case "skin_pants_left": MCSettings_Skin_Pants_Left = str2bool(argValue); break; case "skin_pants_right": MCSettings_Skin_Pants_Right = str2bool(argValue); break; case "skin_hat": MCSettings_Skin_Hat = str2bool(argValue); break; case "main_hand": switch (argValue.ToLower()) { case "left": MCSettings_MainHand = 0; break; case "right": MCSettings_MainHand = 1; break; } break; } break; } } } } } } catch (IOException) { } } }
public CFIInfo(byte[] data, ParseMode parseMode) { switch (parseMode) { case ParseMode.Every2Bytes: { var newData = new byte[data.Length / 2]; for (int i = 0; i < newData.Length; i++) { newData[i] = data[i * 2]; } data = newData; break; } case ParseMode.Every4Bytes: { var newData = new byte[data.Length / 4]; for (int i = 0; i < newData.Length; i++) { newData[i] = data[i * 4]; } data = newData; break; } } if (data[0x10] != 0x51 || data[0x11] != 0x52 || data[0x12] != 0x59) { throw new IOException("Can't enter CFI mode. Invalid flash memory? Broken cartridge? Is it inserted?"); } PrimaryAlgorithmCommandSet = (ushort)(data[0x13] + data[0x14] * 0x100); //var p = (ushort)(data[0x15] + data[0x16] * 0x100); AlternativeAlgorithmCommandSet = (ushort)(data[0x17] + data[0x18] * 0x100); //var a = (ushort)(data[0x19] + data[0x20] * 0x100); VccLogicSupplyMinimumProgramErase = (float)((data[0x1B] >> 4) + 0.1 * (data[0x1B] & 0x0F)); VccLogicSupplyMaximumProgramErase = (float)((data[0x1C] >> 4) + 0.1 * (data[0x1C] & 0x0F)); VppSupplyMinimumProgramErasevoltage = (float)((data[0x1D] >> 4) + 0.1 * (data[0x1D] & 0x0F)); VppSupplyMaximumProgramErasevoltage = (float)((data[0x1E] >> 4) + 0.1 * (data[0x1E] & 0x0F)); TypicalTimeoutPerSingleProgram = data[0x1F] == 0 ? 0 : (1U << data[0x1F]); TypicalTimeoutForMaximumSizeMultiByteProgram = data[0x20] == 0 ? 0 : (1U << data[0x20]); TypicalTimeoutPerIndividualBlockErase = data[0x21] == 0 ? 0 : (1U << data[0x21]); TypicalTimeoutForFullChipErase = data[0x22] == 0 ? 0 : (1U << data[0x22]); MaximumTimeoutPerSingleProgram = data[0x1F] == 0 ? 0 : ((1U << data[0x1F]) * (1U << data[0x23])); MaximumTimeoutForMaximumSizeMultiByteProgram = data[0x20] == 0 ? 0 : ((1U << data[0x20]) * (1U << data[0x24])); MaximumTimeoutPerIndividualBlockErase = data[0x21] == 0 ? 0 : ((1U << data[0x21]) * (1U << data[0x25])); MaximumTimeoutForFullChipErase = data[0x22] == 0 ? 0 : ((1U << data[0x22]) * (1U << data[0x26])); DeviceSize = 1U << data[0x27]; FlashDeviceInterfaceCodeDescription = (FlashDeviceInterface)(data[0x28] + data[0x29] * 0x100); MaximumNumberOfBytesInMultiProgram = (ushort)(1U << (data[0x2A] + data[0x2B] * 0x100)); var eraseBlockRegions = data[0x2C]; var regions = new List <EraseBlockRegionInfo>(); for (int i = 0; i < eraseBlockRegions; i++) { ushort numberOfBlocks = (ushort)(data[0x2D + i * 4] + data[0x2E + i * 4] * 0x100 + 1); uint sizeOfBlocks = (ushort)(data[0x2F + i * 4] + data[0x30 + i * 4] * 0x100); sizeOfBlocks = sizeOfBlocks == 0 ? 128 : (256 * sizeOfBlocks); regions.Add(new EraseBlockRegionInfo(numberOfBlocks, sizeOfBlocks)); } EraseBlockRegionsInfo = regions.AsReadOnly(); }
/// <summary> /// Responds to the Request with the given text message /// </summary> /// <param name="text">The text</param> /// <param name="parseMode">The parse mode</param> /// <param name="ct">Cancellation token</param> /// <returns></returns> public async Task RespondTextMessageAsync(string text, ParseMode parseMode = ParseMode.Default, CancellationToken cancellationToken = default(CancellationToken)) { await Bot.SendTextMessageAsync(Request.Message.Chat.Id, text, parseMode : parseMode, cancellationToken : cancellationToken); }
public async Task SendTextMessageAsync(UpdateMessage message, string text, ParseMode parseMode = ParseMode.Default) { await TelegramBot.SendTextMessageAsync(message.ChatId, text, parseMode); }
/// <summary> /// Parses until a new node is found. Skips over the remainder of the currently parsing node. /// </summary> /// <returns>true if a new node is found. false if end of stream is reached.</returns> internal bool GetNextNode() { try { // set Parse mode to Skip for the following calls to Parse, to parse over the // current node. m_ParseMode = ParseMode.Skip; while (m_ParseState != HtmlParseState.None) Parse(); // Now read the next node. Once Parse has parsed enough of the next node to // know what it is, it will set the m_NodeType, m_Name, etc. and return. // Set Parse mode to normal so the name of the node is stored in m_Name. m_ParseMode = ParseMode.Normal; Parse(); } catch (EndOfStreamException) { return false; } return true; }
public void SetMode(ParseMode mode) { _parseMode = mode; }
/// <summary> /// Sends a text message. /// </summary> /// <param name="chatId">Unique identifier for the message recipient.</param> /// <param name="text">Text of the message to be sent.</param> /// <param name="parseMode">Indicates the way that the Telegram should parse the sent message.</param> /// <param name="disableWebPagePreview">if set to <c>true</c> disables link previews for links in this message.</param> /// <param name="disableNotification">If set to <c>true</c> sends the message silently. iOS users will not receive a notification, Android users will receive a notification with no sound.</param> /// <param name="replyToMessageId">If the message is a reply, ID of the original message.</param> /// <param name="replyMarkup">Additional interface options. An <see cref="IReply" /> object for a custom reply keyboard, /// instructions to hide keyboard or to force a reply from the user.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of /// cancellation.</param> /// <returns> /// On success, returns the sent <see cref="Message" />. /// </returns> public Task <Message> SendMessageAsync(long chatId, [NotNull] string text, ParseMode parseMode = ParseMode.Normal, bool disableWebPagePreview = false, bool disableNotification = false, long replyToMessageId = 0, IReply replyMarkup = null, CancellationToken cancellationToken = default(CancellationToken)) { Contracts.EnsurePositiveNumber(chatId, nameof(chatId)); return(this.SendMessageAsync(chatId.ToString(), text, parseMode, disableWebPagePreview, disableNotification, replyToMessageId, replyMarkup, cancellationToken)); }
public syntax_tree_node BuildTree(string FileName, string Text, ParseMode parseMode) { if (this.parser == null) Reset(); GPB_PABCPreprocessor2 parser = new GPB_PABCPreprocessor2(this.grammar_stream, this.parser.LanguageGrammar, this.parser.prepr); parser.errors = Errors; parser.current_file_name = FileName; compilerDirectives = new List<compiler_directive>(); parser.CompilerDirectives = compilerDirectives; switch (parseMode) { case ParseMode.Expression: case ParseMode.Statement: return null; } syntax_tree_node cu = (syntax_tree_node)parser.Parse(Text); if (cu != null && cu is compilation_unit) { (cu as compilation_unit).file_name = FileName; (cu as compilation_unit).compiler_directives = compilerDirectives; } return cu; }
/// <summary>Sends a text message.</summary> /// <param name="chatId"> /// Unique identifier for the message recipient or username of the target channel (in the format /// @channelusername). /// </param> /// <param name="text">Text of the message to be sent.</param> /// <param name="parseMode"> /// Indicates the way that the Telegram should parse the sent message. /// </param> /// <param name="disableWebPagePreview"> /// if set to <c>true</c> disables link previews for links in this message. /// </param> /// <param name="disableNotification">If set to <c>true</c> sends the message silently. iOS users will not receive a notification, Android users will receive a notification with no sound.</param> /// <param name="replyToMessageId"> /// If the message is a reply, ID of the original message. /// </param> /// <param name="replyMarkup"> /// Additional interface options. An <see cref="IReply" /> object for a custom reply keyboard, /// instructions to hide keyboard or to force a reply from the user. /// </param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of /// cancellation. /// </param> /// <returns> /// On success, returns the sent <see cref="Message" />. /// </returns> public Task <Message> SendMessageAsync([NotNull] string chatId, [NotNull] string text, ParseMode parseMode = ParseMode.Normal, bool disableWebPagePreview = false, bool disableNotification = false, long replyToMessageId = 0, IReply replyMarkup = null, CancellationToken cancellationToken = default(CancellationToken)) { Contracts.EnsureNotNull(chatId, nameof(chatId)); Contracts.EnsureNotNull(text, nameof(text)); var parameters = new NameValueCollection { { "text", text } }; parameters.AddIf(disableWebPagePreview, "disable_web_page_preview", true); parameters.AddIf(parseMode != ParseMode.Normal, "parse_mode", ParseMode.Markdown.ToString()); return(this.CallTelegramMethodAsync <Message>(cancellationToken, "sendMessage", parameters, chatId, replyToMessageId, replyMarkup, disableNotification)); }
/// <summary> /// Sends a text message and requests to hide the current custom keyboard by default. Optionally if the /// message is a reply, ID of the original message will be sent. /// </summary> /// <param name="message">The original received message.</param> /// <param name="text">Text of the message to be sent.</param> /// <param name="parseMode">Indicates the way that the Telegram should parse the sent message.</param> /// <param name="disableWebPagePreview">if set to <c>true</c> disables link previews for links in this message.</param> /// <param name="disableNotification">If set to <c>true</c> sends the message silently. iOS users will not receive a notification, Android users will receive a notification with no sound.</param> /// <param name="replyMarkup">Additional interface options. An <see cref="IReply" /> object for a custom reply keyboard, /// instructions to hide keyboard or to force a reply from the user. Defaults to hide the current /// custom keyboard.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of /// cancellation.</param> /// <returns> /// On success, returns the sent <see cref="Message" />. /// </returns> public Task <Message> SendMessageAsync([NotNull] Message message, [NotNull] string text, ParseMode parseMode = ParseMode.Normal, bool disableWebPagePreview = false, bool disableNotification = false, IReply replyMarkup = null, CancellationToken cancellationToken = default(CancellationToken)) { Contracts.EnsureNotNull(message, nameof(message)); return(this.SendMessageAsync(message.Chat.Id.ToString(), text, parseMode, disableWebPagePreview, disableNotification, message.ReplyToMessage?.Id ?? 0, replyMarkup, cancellationToken)); }
/// <summary> /// Load settings from the give INI file /// </summary> /// <param name="settingsfile">File to load</param> public static void LoadSettings(string settingsfile) { if (File.Exists(settingsfile)) { try { string[] Lines = File.ReadAllLines(settingsfile); ParseMode pMode = ParseMode.Default; foreach (string lineRAW in Lines) { string line = lineRAW.Split('#')[0].Trim(); if (line.Length > 0) { if (line[0] == '[' && line[line.Length - 1] == ']') { switch (line.Substring(1, line.Length - 2).ToLower()) { case "alerts": pMode = ParseMode.Alerts; break; case "antiafk": pMode = ParseMode.AntiAFK; break; case "autorelog": pMode = ParseMode.AutoRelog; break; case "chatlog": pMode = ParseMode.ChatLog; break; case "hangman": pMode = ParseMode.Hangman; break; case "main": pMode = ParseMode.Main; break; case "scriptscheduler": pMode = ParseMode.ScriptScheduler; break; case "remotecontrol": pMode = ParseMode.RemoteControl; break; case "proxy": pMode = ParseMode.Proxy; break; case "appvars": pMode = ParseMode.AppVars; break; default: pMode = ParseMode.Default; break; } } else { string argName = line.Split('=')[0]; if (line.Length > (argName.Length + 1)) { string argValue = line.Substring(argName.Length + 1); switch (pMode) { case ParseMode.Main: switch (argName.ToLower()) { case "login": Login = argValue; break; case "password": Password = argValue; break; case "serverip": setServerIP(argValue); break; case "singlecommand": SingleCommand = argValue; break; case "language": Language = argValue; break; case "consoletitle": ConsoleTitle = argValue; break; case "timestamps": chatTimeStamps = str2bool(argValue); break; case "exitonfailure": exitOnFailure = str2bool(argValue); break; case "playerheadicon": playerHeadAsIcon = str2bool(argValue); break; case "chatbotlogfile": chatbotLogFile = argValue; break; case "mcversion": ServerVersion = argValue; break; case "botowners": Bots_Owners.Clear(); foreach (string name in argValue.ToLower().Replace(" ", "").Split(',')) { Bots_Owners.Add(name); } break; case "internalcmdchar": switch (argValue.ToLower()) { case "none": internalCmdChar = ' '; break; case "slash": internalCmdChar = '/'; break; case "backslash": internalCmdChar = '\\'; break; } break; case "accountlist": if (File.Exists(argValue)) { foreach (string account_line in File.ReadAllLines(argValue)) { //Each line contains account data: 'Alias,Login,Password' string[] account_data = account_line.Split('#')[0].Trim().Split(','); if (account_data.Length == 3) { Accounts[account_data[0].ToLower()] = new KeyValuePair <string, string>(account_data[1], account_data[2]); } } } break; case "serverlist": if (File.Exists(argValue)) { //Backup current server info string server_host_temp = ServerIP; short server_port_temp = ServerPort; foreach (string server_line in File.ReadAllLines(argValue)) { //Each line contains server data: 'Alias,Host:Port' string[] server_data = server_line.Split('#')[0].Trim().Split(','); server_data[0] = server_data[0].ToLower(); if (server_data.Length == 2 && server_data[0] != "localhost" && !server_data[0].Contains('.') && setServerIP(server_data[1])) { Servers[server_data[0]] = new KeyValuePair <string, short>(ServerIP, ServerPort); } } //Restore current server info ServerIP = server_host_temp; ServerPort = server_port_temp; } break; } break; case ParseMode.Alerts: switch (argName.ToLower()) { case "enabled": Alerts_Enabled = str2bool(argValue); break; case "alertsfile": Alerts_MatchesFile = argValue; break; case "excludesfile": Alerts_ExcludesFile = argValue; break; case "beeponalert": Alerts_Beep_Enabled = str2bool(argValue); break; } break; case ParseMode.AntiAFK: switch (argName.ToLower()) { case "enabled": AntiAFK_Enabled = str2bool(argValue); break; case "delay": AntiAFK_Delay = str2int(argValue); break; case "command": AntiAFK_Command = argValue == "" ? "/ping" : argValue; break; } break; case ParseMode.AutoRelog: switch (argName.ToLower()) { case "enabled": AutoRelog_Enabled = str2bool(argValue); break; case "delay": AutoRelog_Delay = str2int(argValue); break; case "retries": AutoRelog_Retries = str2int(argValue); break; case "kickmessagesfile": AutoRelog_KickMessagesFile = argValue; break; } break; case ParseMode.ChatLog: switch (argName.ToLower()) { case "enabled": ChatLog_Enabled = str2bool(argValue); break; case "timestamps": ChatLog_DateTime = str2bool(argValue); break; case "filter": ChatLog_Filter = ChatBots.ChatLog.str2filter(argValue); break; case "logfile": ChatLog_File = argValue; break; } break; case ParseMode.Hangman: switch (argName.ToLower()) { case "enabled": Hangman_Enabled = str2bool(argValue); break; case "english": Hangman_English = str2bool(argValue); break; case "wordsfile": Hangman_FileWords_EN = argValue; break; case "fichiermots": Hangman_FileWords_FR = argValue; break; } break; case ParseMode.ScriptScheduler: switch (argName.ToLower()) { case "enabled": ScriptScheduler_Enabled = str2bool(argValue); break; case "tasksfile": ScriptScheduler_TasksFile = argValue; break; } break; case ParseMode.RemoteControl: switch (argName.ToLower()) { case "enabled": RemoteCtrl_Enabled = str2bool(argValue); break; case "autotpaccept": RemoteCtrl_AutoTpaccept = str2bool(argValue); break; } break; case ParseMode.Proxy: switch (argName.ToLower()) { case "enabled": ProxyEnabled = str2bool(argValue); break; case "type": argValue = argValue.ToLower(); if (argValue == "http") { proxyType = Proxy.ProxyHandler.Type.HTTP; } else if (argValue == "socks4") { proxyType = Proxy.ProxyHandler.Type.SOCKS4; } else if (argValue == "socks4a") { proxyType = Proxy.ProxyHandler.Type.SOCKS4a; } else if (argValue == "socks5") { proxyType = Proxy.ProxyHandler.Type.SOCKS5; } break; case "server": string[] host_splitted = argValue.Split(':'); if (host_splitted.Length == 1) { ProxyHost = host_splitted[0]; ProxyPort = 80; } else if (host_splitted.Length == 2) { ProxyHost = host_splitted[0]; ProxyPort = str2int(host_splitted[1]); } break; case "username": ProxyUsername = argValue; break; case "password": ProxyPassword = argValue; break; } break; case ParseMode.AppVars: setVar(argName, argValue); break; } } } } } } catch (IOException) { } } }
public async Task SendTextMessageAsync(UpdateMessage message, MessageCode messageCode, ParseMode parseMode = ParseMode.Default) { await TelegramBot.SendTextMessageAsync( message.ChatId, _localizer.GetMessage(message.LanguageCode, messageCode), parseMode); }
// Common function to send a text message private async Task <Message> BotSendTextMessage(long chatId, string text, bool disableWebPagePreview = false, bool disableNotification = false, int replyToMessageId = 0, IReplyMarkup replyMarkup = null, ParseMode parseMode = ParseMode.Default, CancellationToken cancellationToken = default(CancellationToken)) { if (text.Trim() == "" || text == null) { return(null); // Nothing to say, nothing to do } if (text.Length > 4096) { text = text.Substring(0, 4090) + "..."; // There is a limit of 4096 characters for Telegram messages } Message m = new Message(); try { m = await Bot.SendTextMessageAsync(chatId, text, disableWebPagePreview, disableNotification, replyToMessageId, replyMarkup, parseMode, cancellationToken); Console.WriteLine("Sent text message <" + text + "> to ChatID " + chatId.ToString()); } catch (Exception e) { Console.WriteLine(string.Format("Failed send text message. {0} Exception caught.", e)); } return(m); }
/* Function: MarkAnnotationParameter * * Applies types to an annotation parameter, such as ""String"" in "@Copynight("String")" or "id = 12" in * "@RequestForEnhancement(id = 12, engineer = "String")". * * Supported Modes: * * - <ParseMode.ParsePrototype> * - The contents will be marked with parameter tokens. * - Everything else has no effect. */ protected void MarkAnnotationParameter(TokenIterator start, TokenIterator end, ParseMode mode = ParseMode.IterateOnly) { if (mode != ParseMode.ParsePrototype) { return; } start.NextPastWhitespace(end); end.PreviousPastWhitespace(PreviousPastWhitespaceMode.EndingBounds, start); if (start >= end) { return; } // Find and mark the equals sign, if there is one TokenIterator equals = start; while (equals < end) { if (equals.Character == '=') { equals.PrototypeParsingType = PrototypeParsingType.PropertyValueSeparator; break; } else if (TryToSkipComment(ref equals) || TryToSkipString(ref equals) || TryToSkipBlock(ref equals, true)) { } else { equals.Next(); } } // The equals sign will be at or past the end if it doesn't exist. if (equals >= end) { start.SetPrototypeParsingTypeBetween(end, PrototypeParsingType.PropertyValue); } else { TokenIterator iterator = equals; iterator.PreviousPastWhitespace(PreviousPastWhitespaceMode.EndingBounds, start); if (start < iterator) { start.SetPrototypeParsingTypeBetween(iterator, PrototypeParsingType.Name); } iterator = equals; iterator.Next(); iterator.NextPastWhitespace(end); if (iterator < end) { iterator.SetPrototypeParsingTypeBetween(end, PrototypeParsingType.PropertyValue); } } }
internal static void ReplyToCallback(CallbackQuery query, string text = null, bool edit = true, bool showAlert = false, InlineKeyboardMarkup replyMarkup = null, ParseMode parsemode = ParseMode.Default) { //first answer the callback Bot.Api.AnswerCallbackQueryAsync(query.Id, edit ? null : text, showAlert); //edit the original message if (edit) { Edit(query, text, replyMarkup, parsemode); } }
/** * Parses an Internationalized Resource Identifier (IRI) reference * under RFC3987. If the IRI is syntactically valid, splits * the _string into its components and returns an array containing * the indices into the components. * * @param s A _string. * @param parseMode Specifies whether certain characters are allowed * in the _string. * @return If the _string is a valid IRI reference, returns an array of 10 * integers. Each of the five pairs corresponds to the start * and end index of the IRI's scheme, authority, path, query, * or fragment component, respectively. If a component is absent, * both indices in that pair will be -1. If the _string is null * or is not a valid IRI, returns null. */ public static int[] splitIRI(string s, ParseMode parseMode) { if(s==null)return null; return splitIRI(s,0,s.Length,parseMode); }
internal static Task <Message> Edit(CallbackQuery query, string text, InlineKeyboardMarkup replyMarkup = null, ParseMode parsemode = ParseMode.Default) { return(Edit(query.Message.Chat.Id, query.Message.MessageId, text, replyMarkup, parsemode)); }
private void ParseAttributes() { // the node must be an element or Identifier for this to be a valid call if (m_NodeType != HtmlNodeType.Element && m_NodeType != HtmlNodeType.Identifier) return; // if parse state isn't None, the full node hasn't yet been parsed. if (m_ParseState != HtmlParseState.None) { // the call to Parse can throw if the end of stream is reached. // set m_ParseMode to ParseMode.Normal to capture attributes m_ParseMode = ParseMode.Normal; try { while (m_ParseState != HtmlParseState.None) { Parse(); } } catch (EndOfStreamException) { // do nothing } } }
internal static Task <Message> Edit(long id, int msgId, string text, InlineKeyboardMarkup replyMarkup = null, ParseMode parsemode = ParseMode.Default) { Bot.MessagesSent++; return(Bot.Api.EditMessageTextAsync(id, msgId, text, parsemode, replyMarkup: replyMarkup)); }
/// <summary> /// Returns the Html/Xml of the current Element up to its corresponding EndElement, unless the /// current Element is an empty element (e.g. ends with a /> and not just a >). If it is an /// empty element, returns only the current Element. /// </summary> /// <returns> /// Returns a <Typ>TextReader</Typ> that gives access to the HTML (or XML as the case may be) from /// the current node (which must be an Element node) to the corresponding EndElement /// node (or the end of the file if the EndElement doesn't exist.) /// </returns> /// <remarks> /// After calling this method, the state of the parser will be that the current note type is "none." /// </remarks> /// <exception cref="InvalidOperationException">If the node type isn't an Element node, /// or the node's name is blank.</exception> internal TextReader GetOuterHtml() { PlainTextString name = Name; // the current node type must be an Element node and have a name. if (m_NodeType != HtmlNodeType.Element || String.IsNullOrEmpty(name)) throw new InvalidOperationException(); // Move m_ParseWriter over to m_GetOuterHtmlWriter so everything gets copied into it, and it never // gets replaced (see ReadNextChar() - if m_GetOuterHtmlWriter is non-null, characters get // copied into it instead of m_ParseWriter.) m_GetOuterHtmlWriter = m_ParseWriter; m_ParseWriter = null; // Capture the rest of the current Element. Set m_ParseMode to Skip to avoid saving // attribute values. m_ParseMode = ParseMode.Skip; try { while (m_ParseState != HtmlParseState.None) Parse(); } catch (EndOfStreamException) { // do nothing } // If this isn't an empty element, find the corresponding EndElement if (!IsEmptyElement) { // keep a count of Element node names equivalent to the current node name, to // account for Elements of the same name that are inside the current Element, // in order to stop parsing at the corrent EndElement. int count = 1; // count the current Element while (count > 0 && GetNextNode()) { if (m_NodeType == HtmlNodeType.Element && 0 == String.Compare(Name, name, StringComparison.OrdinalIgnoreCase)) count++; else if (m_NodeType == HtmlNodeType.EndElement && 0 == String.Compare(Name, name, StringComparison.OrdinalIgnoreCase)) count--; } // If there is still a count, it means GetNextNode returned false, meaning end of stream. if (count == 0) { // make sure to finish parsing the current node try { while (m_ParseState != HtmlParseState.None) { Parse(); } } catch (EndOfStreamException) { // do nothing } } } // transfer the stream writer's stream into a text reader and return it. m_GetOuterHtmlWriter.Flush(); // the stream is a DetachableStream from the ReadNextChar() method DetachableStream detachableStream = (DetachableStream)m_GetOuterHtmlWriter.BaseStream; Stream stream = detachableStream.Stream; // the underlying stream // detach the stream from the m_GetOuterHtmlWriter detachableStream.Detach(); // position the underlying stream at position 0 and hand it off to the StreamReader stream.Position = 0; StreamReader reader = new StreamReader(stream, m_GetOuterHtmlWriter.Encoding); m_GetOuterHtmlWriter.Dispose(); m_GetOuterHtmlWriter = null; // set the current node type to "none" m_NodeType = HtmlNodeType.None; // return the reader return reader; }
internal static Task <Message> Send(string message, long id, bool clearKeyboard = false, InlineKeyboardMarkup customMenu = null, ParseMode parseMode = ParseMode.Html) { MessagesSent++; //message = message.Replace("`",@"\`"); if (clearKeyboard) { var menu = new ReplyKeyboardRemove() { RemoveKeyboard = true }; return(Api.SendTextMessageAsync(id, message, replyMarkup: menu, disableWebPagePreview: true, parseMode: parseMode)); } else if (customMenu != null) { return(Api.SendTextMessageAsync(id, message, replyMarkup: customMenu, disableWebPagePreview: true, parseMode: parseMode)); } else { return(Api.SendTextMessageAsync(id, message, disableWebPagePreview: true, parseMode: parseMode)); } }
public ConsoleLine(string text, ParseMode mode) { _characterList = new ConsoleCharacterList(); _characterList.AddRange(text.ToCharArray(), mode); Mode = mode; }
public syntax_tree_node BuildTree(string FileName, string Text, ParseMode ParseMode, List <string> DefinesList = null) { MatchCollection mc = Regex.Matches(Text, @"(([\f\t\v\x85\p{Z}])*///.*\r\n)*([\f\t\v\x85\p{Z}])*'''.*", RegexOptions.Compiled); syntax_tree_node cu = null; documentation_comment_list dcl = new documentation_comment_list(); if (mc.Count > 0) { int i = 0; int mci = 0, curmindex = mc[0].Index; int line_num = 1; int col = 1; documentation_comment_section dcs = null; int dcs_count = 0; int dcs_length = 0; while (true) { if (Text[i] == '\n') { line_num++; } if (dcs != null && dcs_count == dcs_length) { dcs.source_context = new SourceContext(dcs.source_context.begin_position.line_num, dcs.source_context.begin_position.column_num, line_num - 1, col); dcs = null; } if (Text[i] == '\n') { col = 0; } if (curmindex == i) { dcs = parse_section(mc[mci].Value); if (dcs.tags.Count > 0 || dcs.text != null) { dcs.source_context = new SourceContext(line_num, col, -1, -1); dcl.sections.Add(dcs); dcs_count = 0; dcs_length = mc[mci].Length; } mci++; if (mci < mc.Count) { curmindex = mc[mci].Index; } else { curmindex = -1; } } i++; col++; if (dcs != null) { dcs_count++; } if (i == Text.Length || (curmindex == -1 && dcs == null)) { break; } } } return(dcl); }
static void AddCondition(string line, ParseMode parseMode) { ModifyCondition(line, parseMode, false); }
public void PostToChannel(string message, ParseMode parseMode = ParseMode.Default) { PostToChannelAsync(message, parseMode).Wait(); }
static void ModifyCondition(string line, ParseMode parseMode, bool disableMode) { switch (parseMode) { case ParseMode.ACTION_START: ModifyList(line, ActionStart, disableMode); break; case ParseMode.ACTION_START_CONTAINS: ModifyList(line, ActionStart_contains, disableMode); break; case ParseMode.ACTION_FALSTART: ModifyList(line, ActionFalstart, disableMode); break; case ParseMode.ACTION_END: ModifyList(line, ActionEnd, disableMode); break; case ParseMode.ACTION_END_CONTAINS: ModifyList(line, ActionEnd_contains, disableMode); break; case ParseMode.ACTION_FALSEND: ModifyList(line, ActionFalsEnd, disableMode); break; case ParseMode.ACTION_FALSEND_LAST_EVENT: ModifyList(line, ActionFalsEndDueToLastAction, disableMode); break; default: break; } }
/// <summary> /// Edits text messages sent by the bot or via the bot (for inline bots). /// </summary> /// <param name="chatId"> /// Unique identifier for the target chat or username of the target channel (in the format /// @channelusername). /// </param> /// <param name="messageId">Unique identifier of the sent message.</param> /// <param name="text">New text of the message</param> /// <param name="parseMode"> /// A value from <see cref="ParseMode" /> enum indicates the way that the Telegram should parse the /// sent message. Send <see cref="ParseMode.Markdown" />, if you want Telegram apps to show bold, /// italic, fixed-width text or inline URLs in your bot's message. /// </param> /// <param name="disableWebPagePreview">Disables link previews for links in this message</param> /// <param name="replyMarkup"> /// An <see cref="InlineKeyboardMarkup" /> object for a custom reply keyboard. /// </param> /// <param name="cancellationToken"> /// A <see cref="T:System.Threading.CancellationToken" /> to observe while waiting for the task to /// complete. /// </param> /// <returns> /// A task that represents the asynchronous operation. The task results contains the edited /// <see cref="Message" /> on success. /// </returns> public Task<Message> EditMessageTextAsync([NotNull] string chatId, long messageId, [NotNull] string text, ParseMode parseMode = ParseMode.Normal, bool disableWebPagePreview = false, InlineKeyboardMarkup replyMarkup = null, CancellationToken cancellationToken = default(CancellationToken)) { Contracts.EnsureNotNull(chatId, nameof(chatId)); Contracts.EnsurePositiveNumber(messageId, nameof(messageId)); return this.EditMessageTextAsync(chatId, messageId, null, text, parseMode, disableWebPagePreview, replyMarkup, cancellationToken); }
public virtual PascalABCCompiler.SyntaxTree.syntax_tree_node BuildTree(string FileName, string Text, ParseMode ParseMode, List<string> DefinesList = null) { syntax_tree_node root = null; PreBuildTree(FileName); switch (ParseMode) { case ParseMode.Normal: root = BuildTreeInNormalMode(FileName, Text); break; case ParseMode.Expression: root = BuildTreeInExprMode(FileName, Text); break; case ParseMode.Special: root = BuildTreeInSpecialMode(FileName, Text); break; case ParseMode.ForFormatter: root = BuildTreeInFormatterMode(FileName, Text); break; case ParseMode.Statement: root = BuildTreeInStatementMode(FileName, Text); break; default: break; } if (root != null && root is compilation_unit) { (root as compilation_unit).file_name = FileName; (root as compilation_unit).compiler_directives = CompilerDirectives; if (root is unit_module) if ((root as unit_module).unit_name.HeaderKeyword == UnitHeaderKeyword.Library) (root as compilation_unit).compiler_directives.Add(new compiler_directive(new token_info("apptype"), new token_info("dll"))); } return root; }
private void PrologCode(TerminalSet _TS) { inQueryMode = false; try { SeeEndOfLine = false; GetSymbol(_TS.Union(LeftParen, Identifier, IntLiteral, RealLiteral, StringLiteral, Operator, Atom, Anonymous, CutSym, LSqBracket, LCuBracket, OpSym, BuiltinSym, ProgramSym, ReadingSym, PrologString, QMark), false, true); if (symbol.IsMemberOf(LeftParen, Identifier, IntLiteral, RealLiteral, StringLiteral, Operator, Atom, Anonymous, CutSym, LSqBracket, LCuBracket, OpSym, BuiltinSym, ProgramSym, ReadingSym, PrologString, QMark)) { GetSymbol(new TerminalSet(LeftParen, Identifier, IntLiteral, RealLiteral, StringLiteral, Operator, Atom, Anonymous, CutSym, LSqBracket, LCuBracket, OpSym, BuiltinSym, ProgramSym, ReadingSym, PrologString, QMark), false, true); if (symbol.Terminal == BuiltinSym) { symbol.SetProcessed(); parseMode = ParseMode.Builtin; Initialize(); Predefineds(_TS); } else if (symbol.Terminal == ProgramSym) { symbol.SetProcessed(); parseMode = ParseMode.Program; Initialize(); Program(_TS); } else if (symbol.Terminal == ReadingSym) { symbol.SetProcessed(); parseMode = ParseMode.Reading; ClauseSequence(_TS); } else { Globals.EraseVariables(); parseMode = ParseMode.Query; inQueryMode = true; GetSymbol(new TerminalSet(LeftParen, Identifier, IntLiteral, RealLiteral, StringLiteral, Operator, Atom, Anonymous, CutSym, LSqBracket, LCuBracket, OpSym, PrologString, QMark), false, true); if (symbol.IsMemberOf(LeftParen, Identifier, IntLiteral, RealLiteral, StringLiteral, Operator, Atom, Anonymous, CutSym, LSqBracket, LCuBracket, PrologString, QMark)) { terminalTable[DOT] = Dot; Set1000Operators(true); Query(new TerminalSet(Dot), out queryNode); } else { OperatorDefinition(new TerminalSet(Dot), true); queryNode = null; } GetSymbol(new TerminalSet(Dot), true, true); } } } finally { terminalTable[COMMA] = Operator; terminalTable[OP] = OpSym; terminalTable[DOT] = Dot; Terminate(); } }
private bool updateModeLine(string line) { if (line.Equals("[Header]")) { mode = ParseMode.Header; return true; } if (line.Equals("[Tiles]")) { mode = ParseMode.Tiles; return true; } if (line.Equals("[Objects]")) { mode = ParseMode.Objects; return true; } return false; }
public syntax_tree_node BuildTree(string FileName, string Text, ParseMode ParseMode, List<string> DefinesList = null) { MatchCollection mc = Regex.Matches(Text, @"(([\f\t\v\x85\p{Z}])*///.*\r\n)*([\f\t\v\x85\p{Z}])*'''.*", RegexOptions.Compiled); syntax_tree_node cu = null; documentation_comment_list dcl = new documentation_comment_list(); if (mc.Count > 0) { int i = 0; int mci = 0, curmindex = mc[0].Index; int line_num = 1; int col = 1; documentation_comment_section dcs=null; int dcs_count = 0; int dcs_length = 0; while (true) { if (Text[i] == '\n') { line_num++; } if (dcs!=null && dcs_count == dcs_length) { dcs.source_context = new SourceContext(dcs.source_context.begin_position.line_num, dcs.source_context.begin_position.column_num, line_num-1, col); dcs = null; } if (Text[i] == '\n') { col = 0; } if (curmindex == i) { dcs = parse_section(mc[mci].Value); if (dcs.tags.Count > 0 || dcs.text!=null) { dcs.source_context = new SourceContext(line_num, col, -1, -1); dcl.sections.Add(dcs); dcs_count = 0; dcs_length = mc[mci].Length; } mci++; if (mci < mc.Count) curmindex = mc[mci].Index; else curmindex = -1; } i++; col++; if (dcs != null) dcs_count++; if(i==Text.Length || (curmindex==-1 && dcs==null)) break; } } return dcl; }
public syntax_tree_node BuildTree(string FileName, string Text,string[] SearchPatchs, ParseMode ParseMode) { if (parser == null) Reset(); parser.errors = Errors; parser.current_file_name = FileName; switch (ParseMode) { case ParseMode.Expression: case ParseMode.Statement: return null; } syntax_tree_node cu = (syntax_tree_node)parser.Parse(Text); if (cu != null && cu is compilation_unit) (cu as compilation_unit).file_name = FileName; return cu; }
public syntax_tree_node BuildTree(string FileName, string Text, ParseMode ParseMode) { if (string.IsNullOrEmpty(Text)) return null; ICSharpCode.NRefactory.IParser parser = ICSharpCode.NRefactory.ParserFactory.CreateParser(ICSharpCode.NRefactory.SupportedLanguage.VBNet,new StringReader(Text)); syntax_tree_node cu = null; ASTConverter conv = new ASTConverter(); if (ParseMode == ParseMode.Expression) { ICSharpCode.NRefactory.Ast.Expression expr = parser.ParseExpression(); cu = conv.get_expression(expr); } else { parser.Parse(); cu = conv.get_syntax_tree(parser.CompilationUnit, FileName); } parser.Dispose(); return cu; }
public async void EditMessageTextAsync(ChatId chatId, int messageId, string text, ParseMode parseMode = ParseMode.Default, bool disableWebPagePreview = false, InlineKeyboardMarkup replyMarkup = null, CancellationToken cancellationToken = default) { try { //Markdown cant parse single _ symbol so we need change it to \\_ if (parseMode == ParseMode.Markdown || parseMode == ParseMode.MarkdownV2) { text = text.Replace("_", "\\_"); } await Bot.EditMessageTextAsync(chatId, messageId, text, parseMode, disableWebPagePreview, replyMarkup, cancellationToken); } catch (Exception ex) { if (ex is MessageIsNotModifiedException) { return; } Log.Error(ex, "EditMessageTextAsync error"); if (replyMarkup != null) { var data = JsonConvert.SerializeObject(replyMarkup); Log.Error(ex, $"EditMessageTextAsync error data: {data}"); } } }
/// <summary> /// Create a NetFieldParser, which will load all <see cref="NetFieldExportGroup"/> in the <see cref="AppDomain.CurrentDomain"/>. /// </summary> /// <param name="cache">Instance of NetGuidCache, used to resolve netguids to their string value.</param> /// <param name="mode"></param> /// <param name="assemblyNameFilter">Found assemblies should contain this string.</param> public NetFieldParser(NetGuidCache cache, ParseMode mode, string assemblyNameFilter = "ReplayReader") { GuidCache = cache; var types = AppDomain.CurrentDomain.GetAssemblies().Where(a => a.FullName.Contains(assemblyNameFilter) || a.FullName.Contains("Unreal.Core")).SelectMany(i => i.GetTypes()); var netFields = types.Where(c => c.GetCustomAttribute <NetFieldExportGroupAttribute>() != null); foreach (var type in netFields) { var attribute = type.GetCustomAttribute <NetFieldExportGroupAttribute>(); if (attribute.MinimalParseMode <= mode) { var info = new NetFieldGroupInfo { Type = type }; _netFieldGroups[attribute.Path] = info; AddNetFieldInfo(type, info); } } // Allows deserializing type arrays var netSubFields = types.Where(c => c.GetCustomAttribute <NetFieldExportSubGroupAttribute>() != null); foreach (var type in netSubFields) { var attribute = type.GetCustomAttribute <NetFieldExportSubGroupAttribute>(); if (attribute.MinimalParseMode <= mode) { var info = _netFieldGroups[attribute.Path]; AddNetFieldInfo(type, info); } } // ClassNetCaches var classNetCaches = types.Where(c => c.GetCustomAttribute <NetFieldExportClassNetCacheAttribute>() != null); foreach (var type in classNetCaches) { var attribute = type.GetCustomAttribute <NetFieldExportClassNetCacheAttribute>(); if (attribute.MinimalParseMode <= mode) { var info = new ClassNetCacheInfo(); AddClassNetInfo(type, info); _classNetCacheToNetFieldGroup[attribute.Path] = info; } } // PlayerControllers var controllers = types.Where(c => c.GetCustomAttribute <PlayerControllerAttribute>() != null); foreach (var type in controllers) { var attribute = type.GetCustomAttribute <PlayerControllerAttribute>(); PlayerControllerGroups.Add(attribute.Path); } //Type layout for dynamic arrays _primitiveTypeLayout.Add(typeof(bool), RepLayoutCmdType.PropertyBool); _primitiveTypeLayout.Add(typeof(byte), RepLayoutCmdType.PropertyByte); _primitiveTypeLayout.Add(typeof(ushort), RepLayoutCmdType.PropertyUInt16); _primitiveTypeLayout.Add(typeof(int), RepLayoutCmdType.PropertyInt); _primitiveTypeLayout.Add(typeof(uint), RepLayoutCmdType.PropertyUInt32); _primitiveTypeLayout.Add(typeof(ulong), RepLayoutCmdType.PropertyUInt64); _primitiveTypeLayout.Add(typeof(float), RepLayoutCmdType.PropertyFloat); _primitiveTypeLayout.Add(typeof(string), RepLayoutCmdType.PropertyString); // Allows deserializing type arrays var iPropertyTypes = types.Where(x => typeof(IProperty).IsAssignableFrom(x) && !x.IsInterface && !x.IsAbstract); foreach (var iPropertyType in iPropertyTypes) { _primitiveTypeLayout.Add(iPropertyType, RepLayoutCmdType.Property); } _primitiveTypeLayout.Add(typeof(object), RepLayoutCmdType.Ignore); }
private void ClauseNode(TerminalSet _TS) { Term head; TermNode body = null; ClauseNode c; if (parseMode != ParseMode.Reading) Globals.EraseVariables(); GetSymbol(new TerminalSet(LeftParen, Identifier, IntLiteral, RealLiteral, StringLiteral, Operator, Atom, Anonymous, CutSym, ImpliesSym, PromptSym, LSqBracket, LCuBracket, PrologString), false, true); if (symbol.IsMemberOf(LeftParen, Identifier, IntLiteral, RealLiteral, StringLiteral, Operator, Atom, Anonymous, CutSym, LSqBracket, LCuBracket, PrologString)) { PrologTerm(new TerminalSet(Dot, ImpliesSym, DCGArrowSym), out head); if (!head.IsGoal) PrologIO.Error("Illegal predicate head: {0}", head.ToString()); GetSymbol(new TerminalSet(Dot, ImpliesSym, DCGArrowSym), false, true); if (symbol.IsMemberOf(ImpliesSym, DCGArrowSym)) { GetSymbol(new TerminalSet(ImpliesSym, DCGArrowSym), false, true); if (symbol.Terminal == ImpliesSym) { symbol.SetProcessed(); Query(new TerminalSet(Dot), out body); } else { symbol.SetProcessed(); Term t; PrologTerm(new TerminalSet(Dot), out t); body = t.ToDCG(ref head); } } c = new ClauseNode(head, body); if (parseMode == ParseMode.Reading) readTerm = new Term(c).CleanUp(); else ps.AddClause(c); } else if (symbol.Terminal == PromptSym) { symbol.SetProcessed(); bool m = inQueryMode; bool o = is1000OperatorSetting; int k = terminalTable[DOT]; try { parseMode = ParseMode.Query; inQueryMode = true; terminalTable[DOT] = Dot; Set1000Operators(true); Query(new TerminalSet(Dot), out queryNode); PrologIO.Error("'?-' querymode in file not yet supported"); } finally { inQueryMode = m; terminalTable[DOT] = k; Set1000Operators(o); } } else { symbol.SetProcessed(); terminalTable.Add(Persistent, "Persistent", "persistent"); terminalTable.Add(Module, "Module", "module"); terminalTable.Add(UndefPredAction, "UndefPredAction", "undef_pred_action"); try { GetSymbol(new TerminalSet(LSqBracket, OpSym, EnsureLoaded, Discontiguous, AllDiscontiguous, Dynamic, Persistent, Module, UndefPredAction), false, true); if (symbol.Terminal == OpSym) { OperatorDefinition(new TerminalSet(Dot), true); } else if (symbol.Terminal == EnsureLoaded) { symbol.SetProcessed(); GetSymbol(new TerminalSet(LeftParen), true, true); GetSymbol(new TerminalSet(StringLiteral, Atom), false, true); if (symbol.Terminal == Atom) { symbol.SetProcessed(); } else { symbol.SetProcessed(); } string fileName = Utils.ExtendedFileName(symbol.ToString().ToLower(), ".pl"); if (Globals.ConsultedFiles[fileName] == null) { ps.Consult(fileName); Globals.ConsultedFiles[fileName] = true; } GetSymbol(new TerminalSet(RightParen), true, true); } else if (symbol.Terminal == Discontiguous) { symbol.SetProcessed(); Term t; PrologTerm(new TerminalSet(Dot), out t); ps.SetDiscontiguous(t); } else if (symbol.Terminal == AllDiscontiguous) { symbol.SetProcessed(); ps.SetDiscontiguous(true); } else if (symbol.Terminal == UndefPredAction) { symbol.SetProcessed(); Term t; PrologTerm(new TerminalSet(Dot), out t); ps.SetUndefPredAction(t, true); } else if (symbol.Terminal == Dynamic) { symbol.SetProcessed(); Term t; PrologTerm(new TerminalSet(Dot), out t); } else if (symbol.Terminal == Persistent) { PersistentDeclaration(new TerminalSet(Dot)); } else if (symbol.Terminal == Module) { symbol.SetProcessed(); GetSymbol(new TerminalSet(LeftParen), true, true); try { terminalTable[COMMA] = Comma; GetSymbol(new TerminalSet(StringLiteral, Atom), false, true); if (symbol.Terminal == Atom) { symbol.SetProcessed(); } else { symbol.SetProcessed(); } ps.SetModuleName(symbol.ToString()); GetSymbol(new TerminalSet(Comma), true, true); } finally { terminalTable[COMMA] = Operator; } Term t; PrologTerm(new TerminalSet(RightParen), out t); GetSymbol(new TerminalSet(RightParen), true, true); } else { symbol.SetProcessed(); int lines = 0; int files = 0; try { while (true) { GetSymbol(new TerminalSet(StringLiteral, Atom), false, true); if (symbol.Terminal == Atom) { symbol.SetProcessed(); } else { symbol.SetProcessed(); } string fileName = Utils.FileNameFromSymbol(symbol.ToString(), ".pl"); terminalTable[COMMA] = Operator; lines += ps.Consult(fileName); files++; terminalTable[COMMA] = Comma; GetSymbol(new TerminalSet(Comma, RSqBracket), false, true); if (symbol.Terminal == Comma) { symbol.SetProcessed(); } else break; } if (files > 1) PrologIO.Message("Grand total is {0} lines", lines); } finally { terminalTable[COMMA] = Operator; } GetSymbol(new TerminalSet(RSqBracket), true, true); } } finally { terminalTable.Remove("module"); terminalTable.Remove("persistent"); terminalTable.Remove("undef_pred_action"); } } GetSymbol(new TerminalSet(Dot), true, true); }
public TextResponse(string text, ParseMode parseMode = ParseMode.Markdown, int messageId = 0) { Text = text; ParseMode = parseMode; MessageId = messageId; }
public syntax_tree_node BuildTree(string FileName, string Text, string[] SearchPatchs, ParseMode ParseMode) { if (parser == null) Reset(); compilerDirectives = new System.Collections.Generic.List<compiler_directive>(); parser.CompilerDirectives = compilerDirectives; parser.errors = Errors; parser.current_file_name = FileName; parser.parsertools.LineCorrection = 0; syntax_tree_node cu = null; switch (ParseMode) { case ParseMode.Normal: cu = (syntax_tree_node)parser.Parse(Text); break; case ParseMode.Expression: case ParseMode.Statement: return null; } if (cu != null && cu is compilation_unit) { (cu as compilation_unit).file_name = FileName; (cu as compilation_unit).compiler_directives = parser.CompilerDirectives; } return cu; }
static IEnumerable <FunctionDecl> ParseInput(TextReader tr) { Dictionary <string, TypeReplacement> ThunkReturnTypes = new Dictionary <string, TypeReplacement>(); Dictionary <string, TypeReplacement> ThunkTypes = new Dictionary <string, TypeReplacement>(); ParseMode currentParseMode = ParseMode.FUNCTIONS; ParseMode oldParseMode = ParseMode.FUNCTIONS; List <FunctionDecl> functions = new List <FunctionDecl>(); int currentLineIndex = 1; for (string currentLine = tr.ReadLine(); currentLine != null; currentLine = tr.ReadLine(), currentLineIndex++) { try { if (currentLine.Length == 0) { continue; // Its an empty line, ignore } if (currentLine[0] == ';') { continue; // Its a comment } if (currentLine == "RETURNTYPES") { currentParseMode = ParseMode.RETURNTYPES; continue; } if (currentLine == "NORMALTYPES") { currentParseMode = ParseMode.NORMALTYPES; continue; } if (currentLine == "FUNCTIONS") { currentParseMode = ParseMode.FUNCTIONS; continue; } if (currentLine == "#endif") { currentParseMode = oldParseMode; continue; } if (currentLine.StartsWith("#if")) { oldParseMode = currentParseMode; currentParseMode = ParseMode.IFDEFING; } if (currentParseMode == ParseMode.IFDEFING) { continue; } switch (currentParseMode) { case ParseMode.NORMALTYPES: case ParseMode.RETURNTYPES: TypeReplacement t = new TypeReplacement(currentLine); if (currentParseMode == ParseMode.NORMALTYPES) { ThunkTypes.Add(t.ThunkTypeName, t); ThunkReturnTypes.Add(t.ThunkTypeName, t); } if (currentParseMode == ParseMode.RETURNTYPES) { ThunkReturnTypes[t.ThunkTypeName] = t; } break; case ParseMode.FUNCTIONS: functions.Add(new FunctionDecl(currentLine, ThunkReturnTypes, ThunkTypes)); break; } } catch (Exception e) { Console.Error.WriteLine("Error parsing line {0} : {1}", currentLineIndex, e.Message); } } return(functions.AsReadOnly()); }
// // Parses the string @input and returns a CSharpParser if succeeful. // // if @silent is set to true then no errors are // reported to the user. This is used to do various calls to the // parser and check if the expression is parsable. // // @partial_input: if @silent is true, then it returns whether the // parsed expression was partial, and more data is needed // static CSharpParser ParseString (ParseMode mode, string input, out bool partial_input) { partial_input = false; Reset (); queued_fields.Clear (); Tokenizer.LocatedToken.Initialize (); Stream s = new MemoryStream (Encoding.Default.GetBytes (input)); SeekableStreamReader seekable = new SeekableStreamReader (s, Encoding.Default); InputKind kind = ToplevelOrStatement (seekable); if (kind == InputKind.Error){ if (mode == ParseMode.ReportErrors) ctx.Report.Error (-25, "Detection Parsing Error"); partial_input = false; return null; } if (kind == InputKind.EOF){ if (mode == ParseMode.ReportErrors) Console.Error.WriteLine ("Internal error: EOF condition should have been detected in a previous call with silent=true"); partial_input = true; return null; } seekable.Position = 0; CSharpParser parser = new CSharpParser (seekable, (CompilationUnit) Location.SourceFiles [0], ctx); if (kind == InputKind.StatementOrExpression){ parser.Lexer.putback_char = Tokenizer.EvalStatementParserCharacter; RootContext.StatementMode = true; } else { // // Do not activate EvalCompilationUnitParserCharacter until // I have figured out all the limitations to invoke methods // in the generated classes. See repl.txt // parser.Lexer.putback_char = Tokenizer.EvalUsingDeclarationsParserCharacter; //parser.Lexer.putback_char = Tokenizer.EvalCompilationUnitParserCharacter; RootContext.StatementMode = false; } if (mode == ParseMode.GetCompletions) parser.Lexer.CompleteOnEOF = true; ReportPrinter old_printer = null; if ((mode == ParseMode.Silent || mode == ParseMode.GetCompletions) && CSharpParser.yacc_verbose_flag == 0) old_printer = SetPrinter (new StreamReportPrinter (TextWriter.Null)); try { parser.parse (); } finally { if (ctx.Report.Errors != 0){ if (mode != ParseMode.ReportErrors && parser.UnexpectedEOF) partial_input = true; parser.undo.ExecuteUndo (); parser = null; } if (old_printer != null) SetPrinter (old_printer); } return parser; }
// // Parses the string @input and returns a CSharpParser if succeeful. // // if @silent is set to true then no errors are // reported to the user. This is used to do various calls to the // parser and check if the expression is parsable. // // @partial_input: if @silent is true, then it returns whether the // parsed expression was partial, and more data is needed // CSharpParser ParseString(ParseMode mode, string input, out bool partial_input) { partial_input = false; Reset(); Tokenizer.LocatedToken.Initialize(); var enc = ctx.Settings.Encoding; var s = new MemoryStream(enc.GetBytes(input)); SeekableStreamReader seekable = new SeekableStreamReader(s, enc); InputKind kind = ToplevelOrStatement(seekable); if (kind == InputKind.Error) { if (mode == ParseMode.ReportErrors) { ctx.Report.Error(-25, "Detection Parsing Error"); } partial_input = false; return(null); } if (kind == InputKind.EOF) { if (mode == ParseMode.ReportErrors) { Console.Error.WriteLine("Internal error: EOF condition should have been detected in a previous call with silent=true"); } partial_input = true; return(null); } seekable.Position = 0; source_file.NamespaceContainer.DeclarationFound = false; CSharpParser parser = new CSharpParser(seekable, source_file); if (kind == InputKind.StatementOrExpression) { parser.Lexer.putback_char = Tokenizer.EvalStatementParserCharacter; ctx.Settings.StatementMode = true; } else { parser.Lexer.putback_char = Tokenizer.EvalCompilationUnitParserCharacter; ctx.Settings.StatementMode = false; } if (mode == ParseMode.GetCompletions) { parser.Lexer.CompleteOnEOF = true; } ReportPrinter old_printer = null; if ((mode == ParseMode.Silent || mode == ParseMode.GetCompletions) && CSharpParser.yacc_verbose_flag == 0) { old_printer = ctx.Report.SetPrinter(new StreamReportPrinter(TextWriter.Null)); } try { parser.parse(); } finally { if (ctx.Report.Errors != 0) { if (mode != ParseMode.ReportErrors && parser.UnexpectedEOF) { partial_input = true; } if (parser.undo != null) { parser.undo.ExecuteUndo(); } parser = null; } if (old_printer != null) { ctx.Report.SetPrinter(old_printer); } } return(parser); }
// // Parses the string @input and returns a CSharpParser if succeeful. // // if @silent is set to true then no errors are // reported to the user. This is used to do various calls to the // parser and check if the expression is parsable. // // @partial_input: if @silent is true, then it returns whether the // parsed expression was partial, and more data is needed // CSharpParser ParseString (ParseMode mode, string input, out bool partial_input) { partial_input = false; Reset (); var enc = ctx.Settings.Encoding; var s = new MemoryStream (enc.GetBytes (input)); SeekableStreamReader seekable = new SeekableStreamReader (s, enc); InputKind kind = ToplevelOrStatement (seekable); if (kind == InputKind.Error){ if (mode == ParseMode.ReportErrors) ctx.Report.Error (-25, "Detection Parsing Error"); partial_input = false; return null; } if (kind == InputKind.EOF){ if (mode == ParseMode.ReportErrors) Console.Error.WriteLine ("Internal error: EOF condition should have been detected in a previous call with silent=true"); partial_input = true; return null; } seekable.Position = 0; source_file.DeclarationFound = false; CSharpParser parser = new CSharpParser (seekable, source_file); if (kind == InputKind.StatementOrExpression){ parser.Lexer.putback_char = Tokenizer.EvalStatementParserCharacter; ctx.Settings.StatementMode = true; } else { parser.Lexer.putback_char = Tokenizer.EvalCompilationUnitParserCharacter; ctx.Settings.StatementMode = false; } if (mode == ParseMode.GetCompletions) parser.Lexer.CompleteOnEOF = true; ReportPrinter old_printer = null; if ((mode == ParseMode.Silent || mode == ParseMode.GetCompletions)) old_printer = ctx.Report.SetPrinter (new StreamReportPrinter (TextWriter.Null)); try { parser.parse (); } finally { if (ctx.Report.Errors != 0){ if (mode != ParseMode.ReportErrors && parser.UnexpectedEOF) partial_input = true; if (parser.undo != null) parser.undo.ExecuteUndo (); parser = null; } if (old_printer != null) ctx.Report.SetPrinter (old_printer); } return parser; }
/* Function: TryToSkipAnnotationParameters * * Tries to move the iterator past an annotation parameter section, such as "("String")" in "@Copynight("String")". * * Supported Modes: * * - <ParseMode.IterateOnly> * - <ParseMode.SyntaxHighlight> * - <ParseMode.ParsePrototype> * - The contents will be marked with parameter tokens. * - Everything else is treated as <ParseMode.IterateOnly>. */ protected bool TryToSkipAnnotationParameters(ref TokenIterator iterator, ParseMode mode = ParseMode.IterateOnly) { if (iterator.Character != '(') { return(false); } TokenIterator lookahead = iterator; if (!TryToSkipBlock(ref lookahead, false)) { return(false); } TokenIterator end = lookahead; if (mode == ParseMode.SyntaxHighlight) { iterator.SetSyntaxHighlightingTypeBetween(end, SyntaxHighlightingType.Metadata); } else if (mode == ParseMode.ParsePrototype) { TokenIterator openingParen = iterator; TokenIterator closingParen = lookahead; closingParen.Previous(); openingParen.PrototypeParsingType = PrototypeParsingType.StartOfParams; closingParen.PrototypeParsingType = PrototypeParsingType.EndOfParams; lookahead = openingParen; lookahead.Next(); TokenIterator startOfParam = lookahead; while (lookahead < closingParen) { if (lookahead.Character == ',') { MarkAnnotationParameter(startOfParam, lookahead, mode); lookahead.PrototypeParsingType = PrototypeParsingType.ParamSeparator; lookahead.Next(); startOfParam = lookahead; } else if (TryToSkipComment(ref lookahead) || TryToSkipString(ref lookahead) || TryToSkipBlock(ref lookahead, true)) { } else { lookahead.Next(); } } MarkAnnotationParameter(startOfParam, lookahead, mode); } iterator = end; return(true); }